diff --git a/.config/APIConsistency-Profiles-20250318.xlsx b/.config/APIConsistency-Profiles-20250318.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..f2c09e7f05737c99bb83059fe551ab85ff2f5f6e Binary files /dev/null and b/.config/APIConsistency-Profiles-20250318.xlsx differ diff --git a/.config/APIConsistency-Whitelist-20250318.xlsx b/.config/APIConsistency-Whitelist-20250318.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..5a33a207badfed2b86c85cc1fb605a16eeae122a Binary files /dev/null and b/.config/APIConsistency-Whitelist-20250318.xlsx differ diff --git a/.config/Profiles.json b/.config/Profiles.json new file mode 100644 index 0000000000000000000000000000000000000000..efe95bc7084a477008231ee8a012c19eaa97e9f7 --- /dev/null +++ b/.config/Profiles.json @@ -0,0 +1,38 @@ +{ + "sampleCodeAccuracy": { + "AC": [ + { + "branch": "OpenHarmony-5.1.0-Release", + "sdkVersion": "18" + } + ], + "CI": [ + { + "branch": "master", + "sdkVersion": "20" + }, + { + "branch": "OpenHarmony-5.1.0-Release", + "sdkVersion": "18" + } + ] + }, + "deprecatedInterface": { + "AC": [ + { + "branch": "master", + "sdkVersion": "20" + } + ], + "CI": [ + { + "branch": "master", + "sdkVersion": "20" + }, + { + "branch": "OpenHarmony-5.1.0-Release", + "sdkVersion": "18" + } + ] + } +} \ No newline at end of file diff --git a/.config/SampleCodeAccuracy-Profiles-20250318.xlsx b/.config/SampleCodeAccuracy-Profiles-20250318.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..a03001197e0f0fb4fcaf9ebec4f1ee4cd2ca0077 Binary files /dev/null and b/.config/SampleCodeAccuracy-Profiles-20250318.xlsx differ diff --git a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md index 053cf579b44d8c050f16a314cbfaafcbdd43aea8..2d2b75ee8832b7cb3c9ecb3cba9bde045c3d7471 100644 --- a/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md +++ b/.gitee/PULL_REQUEST_TEMPLATE.zh-CN.md @@ -3,10 +3,11 @@ > **注意:** > 请务必按如下模板反馈PR所携带的修改信息。 > 请分析是否需要同步合入活跃的发布分支。当前活跃的发布分支除master外还包括: -> OpenHarmony-5.0.0-Release (API Level 12) -> OpenHarmony-5.0.1-Release (API Level 13) +> OpenHarmony-feature-20240401 (API Level 17) +> OpenHarmony-5.0.3-Release (API Level 15、API Level 16) > OpenHarmony-5.0.2-Release (API Level 14) -> OpenHarmony-5.0.3-Release (API Level 15) +> OpenHarmony-5.0.1-Release (API Level 13) +> OpenHarmony-5.0.0-Release (API Level 12) ## 文档变更类型 diff --git a/CODEOWNERS b/CODEOWNERS index a1c0914b1684a1ff45ab78499d473a602614b5f8..e74f2238913ba65c4c2213acbcfe222f5cef9a75 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -19,24 +19,31 @@ zh-cn/release-notes/changelogs/ @ang-huawei zh-cn/release-notes/changelogs/**/changelogs-ability.md @ang-huawei @huipeizi [设备开发] -zh-cn/device-dev/ @li-yan339 @zengyawen +zh-cn/device-dev/ @li-yan339 @zengyawen @fang-jinxu [入门-快速入门] zh-cn/application-dev/quick-start/start-overview.md @ge-yafang zh-cn/application-dev/quick-start/start-with-ets-stage.md @ge-yafang [入门-开发基础知识-应用程序包基础知识与应用配置文件] -zh-cn/application-dev/quick-start/app*.md @Brilliantry_Rui @changzheng6 @hou-xiangyu1029 @kongjing2 @small_bricklayer -zh-cn/application-dev/quick-start/module*.md @Brilliantry_Rui @changzheng6 @hou-xiangyu1029 @kongjing2 @small_bricklayer -zh-cn/application-dev/quick-start/multi-hap*.md @Brilliantry_Rui @changzheng6 @hou-xiangyu1029 @kongjing2 @small_bricklayer -zh-cn/application-dev/quick-start/deviceconfig-structure.md @Brilliantry_Rui @changzheng6 @hou-xiangyu1029 @kongjing2 @small_bricklayer -zh-cn/application-dev/quick-start/shared-guide.md @Brilliantry_Rui @changzheng6 @hou-xiangyu1029 @kongjing2 @small_bricklayer -zh-cn/application-dev/quick-start/har-package.md @Brilliantry_Rui @changzheng6 @hou-xiangyu1029 @kongjing2 @small_bricklayer -zh-cn/application-dev/quick-start/in-app-hsp.md @Brilliantry_Rui @changzheng6 @hou-xiangyu1029 @kongjing2 @small_bricklayer -zh-cn/application-dev/quick-start/quickfix*.md @Brilliantry_Rui @changzheng6 @hou-xiangyu1029 @kongjing2 @small_bricklayer +zh-cn/application-dev/quick-start/app*.md @Brilliantry_Rui @changzheng6 @kongjing2 @small_bricklayer +zh-cn/application-dev/quick-start/module*.md @Brilliantry_Rui @changzheng6 @kongjing2 @small_bricklayer +zh-cn/application-dev/quick-start/multi-hap*.md @Brilliantry_Rui @changzheng6 @kongjing2 @small_bricklayer +zh-cn/application-dev/quick-start/deviceconfig-structure.md @Brilliantry_Rui @changzheng6 @kongjing2 @small_bricklayer +zh-cn/application-dev/quick-start/shared-guide.md @Brilliantry_Rui @changzheng6 @kongjing2 @small_bricklayer +zh-cn/application-dev/quick-start/har-package.md @Brilliantry_Rui @changzheng6 @kongjing2 @small_bricklayer +zh-cn/application-dev/quick-start/in-app-hsp.md @Brilliantry_Rui @changzheng6 @kongjing2 @small_bricklayer +zh-cn/application-dev/quick-start/quickfix*.md @Brilliantry_Rui @changzheng6 @kongjing2 @small_bricklayer +zh-cn/application-dev/quick-start/integrated-hsp.md @Brilliantry_Rui @changzheng6 @kongjing2 @small_bricklayer +zh-cn/application-dev/quick-start/har-to-hsp.md @Brilliantry_Rui @changzheng6 @kongjing2 @small_bricklayer +zh-cn/application-dev/quick-start/hsp-to-har.md @Brilliantry_Rui @changzheng6 @kongjing2 @small_bricklayer +zh-cn/application-dev/quick-start/typical-scenario-configuration.md @Brilliantry_Rui @changzheng6 @kongjing2 @small_bricklayer +zh-cn/application-dev/quick-start/app-clone.md @Brilliantry_Rui @changzheng6 @kongjing2 @small_bricklayer +zh-cn/application-dev/quick-start/multiInstance.md @Brilliantry_Rui @changzheng6 @kongjing2 @small_bricklayer +zh-cn/application-dev/quick-start/layered-image.md @Brilliantry_Rui @changzheng6 @kongjing2 @small_bricklayer [入门-资源分类与访问] -zh-cn/application-dev/quick-start/resource-categories-and-access.md @Buda-Liu @Brilliantry_Rui @budda-wang @yangqing3 +zh-cn/application-dev/quick-start/resource-categories-and-access.md @Brilliantry_Rui @lliule21 @lpw_work @budda-wang [入门-学习Arkts语言] zh-cn/application-dev/quick-start/arkts-get-started.md @zhang_yixin13 @qyhuo32 @@ -46,75 +53,13 @@ zh-cn/application-dev/quick-start/typescript-to-arkts-migration-guide.md @zhang_ zh-cn/application-dev/quick-start/arkts-more-cases.md @zhang_yixin13 @qyhuo32 zh-cn/application-dev/quick-start/arkts-high-performance-programming.md @zhang_yixin13 @qyhuo32 -zh-cn/application-dev/quick-start/arkts-basic-syntax-overview.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-declarative-ui-description.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-create-custom-components.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-page-custom-components-lifecycle.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-custom-components-freeze.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-custom-components-access-restrictions.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-builder.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-builderparam.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-wrapBuilder.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-style.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-extend.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-statestyles.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-state-management-overview.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-animatable-extend.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-require.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-reusable.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu - -zh-cn/application-dev/quick-start/arkts-state-management-overview.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-state.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-prop.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-link.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-provide-and-consume.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-observed-and-objectlink.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-application-state-management-overview.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-localstorage.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-appstorage.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-persiststorage.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-environment.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-other-state-mgmt-functions-overview.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-watch.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-two-way-sync.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-track.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-mvvm.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-state-management-best-practices.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/properly-use-state-management-to-develope.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu - -zh-cn/application-dev/quick-start/arkts-new-observedV2-and-trace.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-new-componentV2.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-new-local.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-new-param.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-new-once.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-new-event.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-new-monitor.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-new-Provider-and-Consumer.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-new-Computed.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-new-binding.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-new-type.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-new-appstoragev2.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-new-persistencev2.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-custom-components-freezeV2.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-new-rendering-control-repeat.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-new-getTarget.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-new-makeObserved.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-mvvm-V2.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-custom-component-mixed-scenarios.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-v1-v2-migration.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-rendering-control-contentslot.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu - -zh-cn/application-dev/quick-start/arkts-rendering-control-overview.md @zhang_yixin13 @TerryTsao @lixingchi1 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-rendering-control-ifelse.md @zhang_yixin13 @TerryTsao @lixingchi1 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-rendering-control-foreach.md @zhang_yixin13 @TerryTsao @lixingchi1 @jiyujia926 @seaside_wu -zh-cn/application-dev/quick-start/arkts-rendering-control-lazyforeach.md @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu - [开发-Ability Kit-元能力] zh-cn/application-dev/kit-readme/Readme-Ability-Kit.md @huipeizi @ccllee @lxfycode @lixueqing513 zh-cn/application-dev/application-models/ @huipeizi @ccllee @lxfycode @lixueqing513 zh-cn/application-dev/application-models/uiability*.md @huipeizi @li-weifeng2 @lxfycode @lixueqing513 zh-cn/application-dev/application-models/thread*.md @huipeizi @li-weifeng2 @lxfycode @lixueqing513 zh-cn/application-dev/application-models/itc*.md @huipeizi @li-weifeng2 @lxfycode @lixueqing513 +zh-cn/application-dev/application-models/canopenlink.md @Brilliantry_Rui @changzheng6 @kongjing2 @small_bricklayer [开发-Accessibility Kit] @@ -232,6 +177,7 @@ zh-cn/application-dev/arkts-utils/xml-conversion.md @ge-yafang @gongjunsong @bla [开发-ArkUI-UI开发] +zh-cn/application-dev/ui/state-management/ @zhang_yixin13 @TerryTsao @s10021109 @jiyujia926 @seaside_wu zh-cn/application-dev/ui/arkui-overview.md @fredyuan0912 @HelloCrease zh-cn/application-dev/ui/arkts-ui-development-overview.md @fredyuan0912 @HelloCrease zh-cn/application-dev/ui/arkts-layout-development-overview.md @fredyuan0912 @HelloCrease @@ -244,48 +190,52 @@ zh-cn/application-dev/ui/arkts-layout-development-media-query.md @laigerendaqiu zh-cn/application-dev/ui/arkts-layout-development-create-list.md @yeyinglong_admin @cc520bf @fredyuan0912 @HelloCrease zh-cn/application-dev/ui/arkts-layout-development-create-grid.md @zcdqs @cc520bf @fredyuan0912 @HelloCrease zh-cn/application-dev/ui/arkts-layout-development-create-looping.md @yan-shuifeng @cc520bf @fredyuan0912 @HelloCrease -zh-cn/application-dev/ui/arkts-common-components-button.md @luyuxuan1 @HelloCrease @youzhi92 -zh-cn/application-dev/ui/arkts-common-components-radio-button.md @youzhi92 @luyuxuan1 @HelloCrease -zh-cn/application-dev/ui/arkts-common-components-switch.md @luyuxuan1 @HelloCrease @youzhi92 +zh-cn/application-dev/ui/arkts-common-components-button.md @li-xinlei007 @HelloCrease @firminly +zh-cn/application-dev/ui/arkts-common-components-radio-button.md @houguobiao @li-xinlei007 @HelloCrease +zh-cn/application-dev/ui/arkts-common-components-switch.md @li-xinlei007 @HelloCrease @houguobiao zh-cn/application-dev/ui/arkts-common-components-progress-indicator.md @yeyinglong_admin @cc520bf @fredyuan0912 @HelloCrease zh-cn/application-dev/ui/arkts-common-components-text-display.md @crazyracing0726 @fredyuan0912 @HelloCrease zh-cn/application-dev/ui/arkts-common-components-text-input.md @crazyracing0726 @fredyuan0912 @HelloCrease -zh-cn/application-dev/ui/arkts-common-components-custom-dialog.md @luyuxuan1 @HelloCrease @zhanghaibo0 +zh-cn/application-dev/ui/arkts-common-components-custom-dialog.md @li-xinlei007 @HelloCrease @houguobiao zh-cn/application-dev/ui/arkts-common-components-video-player.md @keerecles @ZhangYu-Home @fredyuan0912 @HelloCrease -zh-cn/application-dev/ui/arkts-common-components-xcomponent.md @keerecles @ZhangYu-Home @luyuxuan1 @HelloCrease -zh-cn/application-dev/ui/arkts-popup-and-menu-components-popup.md @luyuxuan1 @HelloCrease @zhanghaibo0 -zh-cn/application-dev/ui/arkts-popup-and-menu-components-menu.md @luyuxuan1 @HelloCrease @zhanghaibo0 -zh-cn/application-dev/ui/arkts-routing.md @raulnaruto_admin @luyuxuan1 @HelloCrease +zh-cn/application-dev/ui/arkts-common-components-xcomponent.md @keerecles @ZhangYu-Home @HelloCrease +zh-cn/application-dev/ui/arkts-popup-and-menu-components-popup.md @li-xinlei007 @HelloCrease @firminly +zh-cn/application-dev/ui/arkts-popup-and-menu-components-uicontext-popup.md @li-xinlei007 @HelloCrease @firminly +zh-cn/application-dev/ui/arkts-popup-and-menu-components-menu.md @li-xinlei007 @HelloCrease @zhanghaibo0 +zh-cn/application-dev/ui/arkts-popup-and-menu-components-uicontext-menu.md @li-xinlei007 @HelloCrease @zhanghaibo0 +zh-cn/application-dev/ui/arkts-popup-overview.md @li-xinlei007 @HelloCrease @zhanghaibo0 +zh-cn/application-dev/ui/arkts-dialog-overview.md @li-xinlei007 @HelloCrease @zhanghaibo0 +zh-cn/application-dev/ui/arkts-routing.md @raulnaruto_admin @HelloCrease zh-cn/application-dev/ui/arkts-navigation-navigation.md @jiangdayuan @raulnaruto_admin @fredyuan0912 @HelloCrease zh-cn/application-dev/ui/arkts-navigation-tabs.md @yan-shuifeng @cc520bf @fredyuan0912 @HelloCrease zh-cn/application-dev/ui/arkts-graphics-display.md @lexiaoyao2 @fredyuan0912 @HelloCrease -zh-cn/application-dev/ui/arkts-geometric-shape-drawing.md @keerecles @seaside_wu @luyuxuan1 @HelloCrease -zh-cn/application-dev/ui/arkts-drawing-customization-on-canvas.md @keerecles @ZhangYu-Home @luyuxuan1 @HelloCrease -zh-cn/application-dev/ui/arkts-animation.md @lightningHo @huaweimaxuchu @luyuxuan1 @HelloCrease -zh-cn/application-dev/ui/arkts-attribute-animation-overview.md @lightningHo @huaweimaxuchu @luyuxuan1 @HelloCrease -zh-cn/application-dev/ui/arkts-attribute-animation-apis.md @lightningHo @huaweimaxuchu @luyuxuan1 @HelloCrease -zh-cn/application-dev/ui/arkts-custom-attribute-animation.md @lightningHo @huaweimaxuchu @luyuxuan1 @HelloCrease -zh-cn/application-dev/ui/arkts-transition-overview.md @lightningHo @huaweimaxuchu @luyuxuan1 @HelloCrease -zh-cn/application-dev/ui/arkts-enter-exit-transition.md @lightningHo @huaweimaxuchu @luyuxuan1 @HelloCrease -zh-cn/application-dev/ui/arkts-navigation-transition.md @lightningHo @huaweimaxuchu @luyuxuan1 @HelloCrease -zh-cn/application-dev/ui/arkts-modal-transition.md @lightningHo @huaweimaxuchu @luyuxuan1 @HelloCrease -zh-cn/application-dev/ui/arkts-shared-element-transition.md @lightningHo @huaweimaxuchu @luyuxuan1 @HelloCrease -zh-cn/application-dev/ui/arkts-page-transition-animation.md @lightningHo @huaweimaxuchu @luyuxuan1 @HelloCrease -zh-cn/application-dev/ui/arkts-component-animation.md @lightningHo @huaweimaxuchu @luyuxuan1 @HelloCrease -zh-cn/application-dev/ui/arkts-curve-overview.md @lightningHo @huaweimaxuchu @luyuxuan1 @HelloCrease -zh-cn/application-dev/ui/arkts-traditional-curve.md @lightningHo @huaweimaxuchu @luyuxuan1 @HelloCrease -zh-cn/application-dev/ui/arkts-spring-curve.md @lightningHo @huaweimaxuchu @luyuxuan1 @HelloCrease -zh-cn/application-dev/ui/arkts-animation-smoothing.md @lightningHo @huaweimaxuchu @luyuxuan1 @HelloCrease -zh-cn/application-dev/ui/arkts-blur-effect.md @lightningHo @huaweimaxuchu @luyuxuan1 @HelloCrease -zh-cn/application-dev/ui/arkts-shadow-effect.md @lightningHo @huaweimaxuchu @luyuxuan1 @HelloCrease -zh-cn/application-dev/ui/arkts-color-effect.md @lightningHo @luyuxuan1 @HelloCrease -zh-cn/application-dev/ui/arkts-event-overview.md @zhaojian2021 @jiangtao92 @luyuxuan1 @HelloCrease -zh-cn/application-dev/ui/arkts-common-events-touch-screen-event.md @zhaojian2021 @jiangtao92 @luyuxuan1 @HelloCrease -zh-cn/application-dev/ui/arkts-common-events-device-input-event.md @zhaojian2021 @jiangtao92 @luyuxuan1 @HelloCrease -zh-cn/application-dev/ui/arkts-common-events-focus-event.md @piggyguy @jiangtao92 @luyuxuan1 @HelloCrease -zh-cn/application-dev/ui/arkts-gesture-events-binding.md @zhaojian2021 @jiangtao92 @luyuxuan1 @HelloCrease -zh-cn/application-dev/ui/arkts-gesture-events-single-gesture.md @zhaojian2021 @jiangtao92 @luyuxuan1 @HelloCrease -zh-cn/application-dev/ui/arkts-gesture-events-combined-gestures.md @zhaojian2021 @jiangtao92 @luyuxuan1 @HelloCrease +zh-cn/application-dev/ui/arkts-geometric-shape-drawing.md @keerecles @seaside_wu @HelloCrease +zh-cn/application-dev/ui/arkts-drawing-customization-on-canvas.md @keerecles @ZhangYu-Home @HelloCrease +zh-cn/application-dev/ui/arkts-animation.md @hehongyang9 @lightningHo @huaweimaxuchu @HelloCrease +zh-cn/application-dev/ui/arkts-attribute-animation-overview.md @hehongyang9 @lightningHo @huaweimaxuchu @HelloCrease +zh-cn/application-dev/ui/arkts-attribute-animation-apis.md @hehongyang9 @lightningHo @huaweimaxuchu @HelloCrease +zh-cn/application-dev/ui/arkts-custom-attribute-animation.md @hehongyang9 @lightningHo @huaweimaxuchu @HelloCrease +zh-cn/application-dev/ui/arkts-transition-overview.md @hehongyang9 @lightningHo @huaweimaxuchu @HelloCrease +zh-cn/application-dev/ui/arkts-enter-exit-transition.md @hehongyang9 @lightningHo @huaweimaxuchu @HelloCrease +zh-cn/application-dev/ui/arkts-navigation-transition.md @lightningHo @huaweimaxuchu @HelloCrease +zh-cn/application-dev/ui/arkts-modal-transition.md @lightningHo @huaweimaxuchu @HelloCrease +zh-cn/application-dev/ui/arkts-shared-element-transition.md @hehongyang9 @lightningHo @huaweimaxuchu @HelloCrease +zh-cn/application-dev/ui/arkts-page-transition-animation.md @hehongyang9 @lightningHo @huaweimaxuchu @HelloCrease +zh-cn/application-dev/ui/arkts-component-animation.md @hehongyang9 @lightningHo @huaweimaxuchu @HelloCrease +zh-cn/application-dev/ui/arkts-curve-overview.md @hehongyang9 @lightningHo @huaweimaxuchu @HelloCrease +zh-cn/application-dev/ui/arkts-traditional-curve.md @hehongyang9 @lightningHo @huaweimaxuchu @HelloCrease +zh-cn/application-dev/ui/arkts-spring-curve.md @hehongyang9 @lightningHo @huaweimaxuchu @HelloCrease +zh-cn/application-dev/ui/arkts-animation-smoothing.md @hehongyang9 @lightningHo @huaweimaxuchu @HelloCrease +zh-cn/application-dev/ui/arkts-blur-effect.md @hehongyang9 @lightningHo @huaweimaxuchu @HelloCrease +zh-cn/application-dev/ui/arkts-shadow-effect.md @hehongyang9 @lightningHo @huaweimaxuchu @HelloCrease +zh-cn/application-dev/ui/arkts-color-effect.md @hehongyang9 @lightningHo @HelloCrease +zh-cn/application-dev/ui/arkts-event-overview.md @piggyguy @jiangtao92 @HelloCrease +zh-cn/application-dev/ui/arkts-common-events-touch-screen-event.md @piggyguy @jiangtao92 @HelloCrease +zh-cn/application-dev/ui/arkts-common-events-device-input-event.md @piggyguy @jiangtao92 @HelloCrease +zh-cn/application-dev/ui/arkts-common-events-focus-event.md @piggyguy @jiangtao92 @HelloCrease +zh-cn/application-dev/ui/arkts-gesture-events-binding.md @piggyguy @jiangtao92 @HelloCrease +zh-cn/application-dev/ui/arkts-gesture-events-single-gesture.md @piggyguy @jiangtao92 @HelloCrease +zh-cn/application-dev/ui/arkts-gesture-events-combined-gestures.md @piggyguy @jiangtao92 @HelloCrease zh-cn/application-dev/ui/arkts-user-defined.md @sunfei2021 @fredyuan0912 @HelloCrease zh-cn/application-dev/ui/arkts-user-defined-node.md @sunfei2021 @fredyuan0912 @HelloCrease zh-cn/application-dev/ui/arkts-user-defined-place-hoder.md @sunfei2021 @fredyuan0912 @HelloCrease @@ -296,21 +246,21 @@ zh-cn/application-dev/ui/ndk-build-ui-overview.md @yan-shuifeng @fredyuan0912 @H zh-cn/application-dev/ui/ndk-access-the-arkts-page.md @yan-shuifeng @fredyuan0912 @HelloCrease zh-cn/application-dev/ui/ndk-listen-to-component-events.md @yan-shuifeng @fredyuan0912 @HelloCrease zh-cn/application-dev/ui/ndk-bind-gesture-events.md @yan-shuifeng @fredyuan0912 @HelloCrease -zh-cn/application-dev/ui/ndk-use-animation.md @yan-shuifeng @fredyuan0912 @HelloCrease +zh-cn/application-dev/ui/ndk-use-animation.md @hehongyang9 @yan-shuifeng @fredyuan0912 @HelloCrease zh-cn/application-dev/ui/ndk-loading-long-list.md @yan-shuifeng @fredyuan0912 @HelloCrease zh-cn/application-dev/ui/ndk-build-pop-up-window.md @yan-shuifeng @fredyuan0912 @HelloCrease zh-cn/application-dev/ui/ndk-build-custom-components.md @yan-shuifeng @fredyuan0912 @HelloCrease zh-cn/application-dev/ui/ndk-embed-arkts-components.md @yan-shuifeng @fredyuan0912 @HelloCrease -zh-cn/application-dev/ui/arkts-dialog-overview.md @luyuxuan1 @HelloCrease @zhanghaibo0 -zh-cn/application-dev/ui/arkts-base-dialog-overview.md @luyuxuan1 @HelloCrease @zhanghaibo0 -zh-cn/application-dev/ui/arkts-uicontext-custom-dialog.md @luyuxuan1 @HelloCrease @zhanghaibo0 -zh-cn/application-dev/ui/arkts-fixes-style-dialog.md @luyuxuan1 @HelloCrease @zhanghaibo0 -zh-cn/application-dev/ui/arkts-modal-overview.md @luyuxuan1 @HelloCrease @cheng-feiwang -zh-cn/application-dev/ui/arkts-sheet-page.md @luyuxuan1 @HelloCrease @cheng-feiwang -zh-cn/application-dev/ui/arkts-contentcover-page.md @luyuxuan1 @HelloCrease @cheng-feiwang -zh-cn/application-dev/ui/arkts-create-toast.md @luyuxuan1 @HelloCrease @zhanghaibo0 -zh-cn/application-dev/ui/arkts-create-overlaymanager.md @luyuxuan1 @HelloCrease @zhanghaibo0 -zh-cn/application-dev/ui/arkts-advanced-components-arcbutton.md @luyuxuan1 @HelloCrease +zh-cn/application-dev/ui/arkts-dialog-overview.md @li-xinlei007 @HelloCrease @zhanghaibo0 +zh-cn/application-dev/ui/arkts-base-dialog-overview.md @li-xinlei007 @HelloCrease @zhanghaibo0 +zh-cn/application-dev/ui/arkts-uicontext-custom-dialog.md @li-xinlei007 @HelloCrease @zhanghaibo0 +zh-cn/application-dev/ui/arkts-fixes-style-dialog.md @li-xinlei007 @HelloCrease @zhanghaibo0 +zh-cn/application-dev/ui/arkts-modal-overview.md @li-xinlei007 @HelloCrease @cheng-feiwang +zh-cn/application-dev/ui/arkts-sheet-page.md @HelloCrease @cheng-feiwang +zh-cn/application-dev/ui/arkts-contentcover-page.md @HelloCrease @cheng-feiwang +zh-cn/application-dev/ui/arkts-create-toast.md @li-xinlei007 @HelloCrease @zhanghaibo0 +zh-cn/application-dev/ui/arkts-create-overlaymanager.md @li-xinlei007 @HelloCrease @zhanghaibo0 +zh-cn/application-dev/ui/arkts-advanced-components-arcbutton.md @li-xinlei007 @HelloCrease [开发-ArkUI-窗口管理] zh-cn/application-dev/windowmanager/ @ge-yafang @zhangqiang183 @zhouyaoying @zxg-gitee @nobuggers @qinliwen @@ -318,25 +268,26 @@ zh-cn/application-dev/application-models/windowextensionability.md @zhangqiang18 [开发-Arkweb] -zh-cn/application-dev/web/ @bigpumpkin @HelloCrease @litao33 @zhang-xinyue15 - +zh-cn/application-dev/web/ @bigpumpkin @HelloCrease @litao33 @GHiker [开发-Background Tasks Kit] -zh-cn/application-dev/task-management/background-task-overview.md @Brilliantry_Rui -zh-cn/application-dev/task-management/transient-task.md @Brilliantry_Rui -zh-cn/application-dev/task-management/continuous-task.md @Brilliantry_Rui -zh-cn/application-dev/task-management/work-scheduler.md @Brilliantry_Rui -zh-cn/application-dev/task-management/agent-powered-reminder.md @Brilliantry_Rui -zh-cn/application-dev/task-management/efficiency-resource-request.md @Brilliantry_Rui -h-cn/application-dev/task-management/native-transient-task.md @Brilliantry_Rui @Brilliantry_Rui -zh-cn/application-dev/device-usage-statistics/device-usage-statistics-overview.md @Brilliantry_Rui -zh-cn/application-dev/device-usage-statistics/device-usage-statistics-use-guide.md @Brilliantry_Rui +zh-cn/application-dev/task-management/ @Brilliantry_Rui @zhouben25 @cooffee10 @cheng-shichang +zh-cn/application-dev/task-management/background-task-overview.md @Brilliantry_Rui @zhouben25 @cooffee10 @cheng-shichang +zh-cn/application-dev/task-management/transient-task.md @Brilliantry_Rui @zhouben25 @cooffee10 @cheng-shichang +zh-cn/application-dev/task-management/continuous-task.md @Brilliantry_Rui @zhouben25 @cooffee10 @cheng-shichang +zh-cn/application-dev/task-management/work-scheduler.md @Brilliantry_Rui @zhouben25 @cooffee10 @cheng-shichang +zh-cn/application-dev/task-management/agent-powered-reminder.md @Brilliantry_Rui @zhouben25 @cooffee10 @cheng-shichang +zh-cn/application-dev/task-management/efficiency-resource-request.md @Brilliantry_Rui @zhouben25 @cooffee10 @cheng-shichang +zh-cn/application-dev/task-management/native-transient-task.md @Brilliantry_Rui @zhouben25 @cooffee10 @cheng-shichang +zh-cn/application-dev/device-usage-statistics/ @Brilliantry_Rui @zhouben25 @cooffee10 @cheng-shichang +zh-cn/application-dev/device-usage-statistics/device-usage-statistics-overview.md @Brilliantry_Rui @zhouben25 @cooffee10 @cheng-shichang +zh-cn/application-dev/device-usage-statistics/device-usage-statistics-use-guide.md @Brilliantry_Rui @zhouben25 @cooffee10 @cheng-shichang [开发-Basic Services Kit-帐号] zh-cn/application-dev/account/ @zengyawen [开发-Basic Services Kit-公共事件] -zh-cn/application-dev/basic-services/common-event/ @huipeizi @idanny @shine_hk +zh-cn/application-dev/basic-services/common-event/ @huipeizi @dong-qingran @shine_hk [开发-Basic Services Kit-设备管理] zh-cn/application-dev/device/usb-overview.md @li-yan339 @Kevin-Lau @liuhonggang123 @@ -374,7 +325,7 @@ zh-cn/application-dev/device/externaldevice-guidelines.md @li-yan339 [开发-Form Kit] -zh-cn/application-dev/form/ @Eiln @cmz001 @Brilliantry_Rui @yuanzhishuai @ylsnow +zh-cn/application-dev/form/ @ylsnow @cmz001 @Brilliantry_Rui @Eiln [开发-DFX] @@ -394,51 +345,52 @@ zh-cn/application-dev/inputmethod/inputmethod_application_guide.md @illybyy @mur zh-cn/application-dev/inputmethod/switch_inputmehod_guide.md @illybyy @murphy1984 @feng-aiwen @zhang_yixin13 @SuperShrimp [开发-Input kit] -zh-cn/application-dev/device/inputdevice-guidelines.md @Brilliantry_Rui @mayunteng -zh-cn/application-dev/device/pointerstyle-guidelines.md @Brilliantry_Rui @mayunteng -zh-cn/application-dev/device/inputmonitor-guidelines.md @Brilliantry_Rui @mayunteng -zh-cn/application-dev/device/inputeventclient-guidelines.md @Brilliantry_Rui @mayunteng -zh-cn/application-dev/device/inputconsumer-guidelines.md @Brilliantry_Rui @mayunteng -zh-cn/application-dev/device/shortkey-guidelines.md @Brilliantry_Rui @mayunteng -zh-cn/application-dev/device/input-overview.md @Brilliantry_Rui @mayunteng -zh-cn/application-dev/device/monitor-guidelines.md @Brilliantry_Rui @mayunteng -zh-cn/application-dev/device/interceptor-guidelines.md @Brilliantry_Rui @mayunteng +zh-cn/application-dev/device/input @Brilliantry_Rui @mayunteng @ustblx @hanruofei +zh-cn/application-dev/device/inputdevice-guidelines.md @Brilliantry_Rui @mayunteng @ustblx @hanruofei +zh-cn/application-dev/device/pointerstyle-guidelines.md @Brilliantry_Rui @mayunteng @ustblx @hanruofei +zh-cn/application-dev/device/inputmonitor-guidelines.md @Brilliantry_Rui @mayunteng @ustblx @hanruofei +zh-cn/application-dev/device/inputeventclient-guidelines.md @Brilliantry_Rui @mayunteng @ustblx @hanruofei +zh-cn/application-dev/device/inputconsumer-guidelines.md @Brilliantry_Rui @mayunteng @ustblx @hanruofei +zh-cn/application-dev/device/shortkey-guidelines.md @Brilliantry_Rui @mayunteng @ustblx @hanruofei +zh-cn/application-dev/device/input-overview.md @Brilliantry_Rui @mayunteng @ustblx @hanruofei +zh-cn/application-dev/device/monitor-guidelines.md @Brilliantry_Rui @mayunteng @ustblx @hanruofei +zh-cn/application-dev/device/interceptor-guidelines.md @Brilliantry_Rui @mayunteng @ustblx @hanruofei [开发-IPC Kit] -zh-cn/application-dev/connectivity/ipc-rpc-overview.md @zhang_yixin13 @luodh0157 @zhaopeng_gitee @zhang-yang123321 -zh-cn/application-dev/connectivity/ipc-rpc-development-guideline.md @zhang_yixin13 @luodh0157 @zhaopeng_gitee @zhang-yang123321 -zh-cn/application-dev/connectivity/subscribe-remote-state.md @zhang_yixin13 @luodh0157 @zhaopeng_gitee @zhang-yang123321 +zh-cn/application-dev/connectivity/ipc-rpc-overview.md @zhang_yixin13 @xdx1921 @zhaopeng_gitee @zhang-yang123321 +zh-cn/application-dev/connectivity/ipc-rpc-development-guideline.md @zhang_yixin13 @xdx1921 @zhaopeng_gitee @zhang-yang123321 +zh-cn/application-dev/connectivity/subscribe-remote-state.md @zhang_yixin13 @xdx1921 @zhaopeng_gitee @zhang-yang123321 [开发-Localization Kit] -zh-cn/application-dev/internationalization/ @Brilliantry_Rui @yliupy @yangqing3 @sunyaozu -zh-cn/application-dev/internationalization/i18n-l10n.md @Brilliantry_Rui @yliupy @yangqing3 @sunyaozu -zh-cn/application-dev/internationalization/i18n-ui-design.md @Brilliantry_Rui @yliupy @yangqing3 @sunyaozu -zh-cn/application-dev/internationalization/i18n-locale-culture.md @Brilliantry_Rui @yliupy @yangqing3 @sunyaozu -zh-cn/application-dev/internationalization/i18n-system-language-region.md @Brilliantry_Rui @yliupy @yangqing3 @sunyaozu -zh-cn/application-dev/internationalization/i18n-preferred-language.md @Brilliantry_Rui @yliupy @yangqing3 @sunyaozu -zh-cn/application-dev/internationalization/i18n-user-preferences.md @Brilliantry_Rui @yliupy @yangqing3 @sunyaozu -zh-cn/application-dev/internationalization/i18n-time-date.md @Brilliantry_Rui @yliupy @yangqing3 @sunyaozu -zh-cn/application-dev/internationalization/i18n-numbers-weights-measures.md @Brilliantry_Rui @yliupy @yangqing3 @sunyaozu -zh-cn/application-dev/internationalization/i18n-phone-numbers.md @Brilliantry_Rui @yliupy @yangqing3 @sunyaozu -zh-cn/application-dev/internationalization/i18n-calendar.md @Brilliantry_Rui @yliupy @yangqing3 @sunyaozu -zh-cn/application-dev/internationalization/i18n-time-zone.md @Brilliantry_Rui @yliupy @yangqing3 @sunyaozu -zh-cn/application-dev/internationalization/i18n-dst-transition.md @Brilliantry_Rui @yliupy @yangqing3 @sunyaozu -zh-cn/application-dev/internationalization/i18n-sorting-overview.md @Brilliantry_Rui @yliupy @yangqing3 @sunyaozu -zh-cn/application-dev/internationalization/i18n-sorting-local.md @Brilliantry_Rui @yliupy @yangqing3 @sunyaozu -zh-cn/application-dev/internationalization/i18n-sorting-index.md @Brilliantry_Rui @yliupy @yangqing3 @sunyaozu -zh-cn/application-dev/internationalization/i18n-character-processing.md @Brilliantry_Rui @yliupy @yangqing3 @sunyaozu -zh-cn/application-dev/internationalization/i18n-language-region-display.md @Brilliantry_Rui @yliupy @yangqing3 @sunyaozu -zh-cn/application-dev/internationalization/i18n-time-zone-display.md @Brilliantry_Rui @yliupy @yangqing3 @sunyaozu -zh-cn/application-dev/internationalization/l10n-multilingual-resources.md @Brilliantry_Rui @yliupy @yangqing3 @sunyaozu -zh-cn/application-dev/internationalization/l10n-hard-coding-concatenate.md @Brilliantry_Rui @yliupy @yangqing3 @sunyaozu -zh-cn/application-dev/internationalization/l10n-translation-scene.md @Brilliantry_Rui @yliupy @yangqing3 @sunyaozu -zh-cn/application-dev/internationalization/l10n-singular-plural.md @Brilliantry_Rui @yliupy @yangqing3 @sunyaozu -zh-cn/application-dev/internationalization/pseudo-i18n-testing-overview.md @Brilliantry_Rui @yliupy @yangqing3 @sunyaozu -zh-cn/application-dev/internationalization/pseudo-i18n-testing-translation.md @Brilliantry_Rui @yliupy @yangqing3 @sunyaozu -zh-cn/application-dev/internationalization/pseudo-i18n-testing-mirror.md @Brilliantry_Rui @yliupy @yangqing3 @sunyaozu -zh-cn/application-dev/internationalization/linguistic-testing.md @Brilliantry_Rui @yliupy @yangqing3 @sunyaozu +zh-cn/application-dev/internationalization/ @Brilliantry_Rui @yliupy @sunyaozu @lpw_work +zh-cn/application-dev/internationalization/i18n-l10n.md @Brilliantry_Rui @yliupy @sunyaozu @lpw_work +zh-cn/application-dev/internationalization/i18n-ui-design.md @Brilliantry_Rui @yliupy @sunyaozu @lpw_work +zh-cn/application-dev/internationalization/i18n-locale-culture.md @Brilliantry_Rui @yliupy @sunyaozu @lpw_work +zh-cn/application-dev/internationalization/i18n-system-language-region.md @Brilliantry_Rui @yliupy @sunyaozu @lpw_work +zh-cn/application-dev/internationalization/i18n-preferred-language.md @Brilliantry_Rui @yliupy @sunyaozu @lpw_work +zh-cn/application-dev/internationalization/i18n-user-preferences.md @Brilliantry_Rui @yliupy @sunyaozu @lpw_work +zh-cn/application-dev/internationalization/i18n-time-date.md @Brilliantry_Rui @yliupy @sunyaozu @lpw_work +zh-cn/application-dev/internationalization/i18n-numbers-weights-measures.md @Brilliantry_Rui @yliupy @sunyaozu @lpw_work +zh-cn/application-dev/internationalization/i18n-phone-numbers.md @Brilliantry_Rui @yliupy @sunyaozu @lpw_work +zh-cn/application-dev/internationalization/i18n-calendar.md @Brilliantry_Rui @yliupy @sunyaozu @lpw_work +zh-cn/application-dev/internationalization/i18n-time-zone.md @Brilliantry_Rui @yliupy @sunyaozu @lpw_work +zh-cn/application-dev/internationalization/i18n-dst-transition.md @Brilliantry_Rui @yliupy @sunyaozu @lpw_work +zh-cn/application-dev/internationalization/i18n-sorting-overview.md @Brilliantry_Rui @yliupy @sunyaozu @lpw_work +zh-cn/application-dev/internationalization/i18n-sorting-local.md @Brilliantry_Rui @yliupy @sunyaozu @lpw_work +zh-cn/application-dev/internationalization/i18n-sorting-index.md @Brilliantry_Rui @yliupy @sunyaozu @lpw_work +zh-cn/application-dev/internationalization/i18n-character-processing.md @Brilliantry_Rui @yliupy @sunyaozu @lpw_work +zh-cn/application-dev/internationalization/i18n-language-region-display.md @Brilliantry_Rui @yliupy @sunyaozu @lpw_work +zh-cn/application-dev/internationalization/i18n-time-zone-display.md @Brilliantry_Rui @yliupy @sunyaozu @lpw_work +zh-cn/application-dev/internationalization/l10n-multilingual-resources.md @Brilliantry_Rui @yliupy @sunyaozu @lpw_work +zh-cn/application-dev/internationalization/l10n-hard-coding-concatenate.md @Brilliantry_Rui @yliupy @sunyaozu @lpw_work +zh-cn/application-dev/internationalization/l10n-translation-scene.md @Brilliantry_Rui @yliupy @sunyaozu @lpw_work +zh-cn/application-dev/internationalization/l10n-singular-plural.md @Brilliantry_Rui @yliupy @sunyaozu @lpw_work +zh-cn/application-dev/internationalization/pseudo-i18n-testing-overview.md @Brilliantry_Rui @yliupy @sunyaozu @lpw_work +zh-cn/application-dev/internationalization/pseudo-i18n-testing-translation.md @Brilliantry_Rui @yliupy @sunyaozu @lpw_work +zh-cn/application-dev/internationalization/pseudo-i18n-testing-mirror.md @Brilliantry_Rui @yliupy @sunyaozu @lpw_work +zh-cn/application-dev/internationalization/linguistic-testing.md @Brilliantry_Rui @yliupy @sunyaozu @lpw_work [开发-Location Kit] zh-cn/application-dev/device/device-location-overview.md @RayShih @@ -450,9 +402,9 @@ zh-cn/application-dev/device/device-location-geocoding.md @RayShih zh-cn/application-dev/media/ @zengyawen [开发-MDM Kit] -zh-cn/application-dev/mdm/mdm-kit-intro.md @Brilliantry_Rui -zh-cn/application-dev/mdm/mdm-kit-guide.md @Brilliantry_Rui -zh-cn/application-dev/mdm/mdm-kit-admin.md @Brilliantry_Rui +zh-cn/application-dev/mdm/mdm-kit-intro.md @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han +zh-cn/application-dev/mdm/mdm-kit-guide.md @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han +zh-cn/application-dev/mdm/mdm-kit-admin.md @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han [开发-MindSpore Lite Kit] zh-cn/application-dev/ai/MindSpore-Lite-Kit-Introduction.md @ge-yafang @principal87 @limingjiang @@ -471,7 +423,7 @@ zh-cn/application-dev/device/stationary-guidelines.md @mayunteng_1 @hu-zhiqiong [开发-Network Kit] -zh-cn/application-dev/network/ @zhang_yixin13 @jiayanhong-hw @w30013702 @rain_myf +zh-cn/application-dev/network/ @zhang_yixin13 @lbch_hw [开发-Neural NetWork Runtime Kit] @@ -486,7 +438,7 @@ zh-cn/application-dev/napi/rawfile-guidelines.md @Brilliantry_Rui @budda-wang @y [开发-Notification Kit] -zh-cn/application-dev/notification/ @huipeizi @idanny @shine_hk +zh-cn/application-dev/notification/ @huipeizi @dong-qingran @shine_hk @@ -514,15 +466,15 @@ zh-cn/application-dev/device/sensor/sensor-guidelines-as.md @hu-zhiqiong @lixian [开发-Telephony Kit] -zh-cn/application-dev/telephony/telephony-overview.md @zhang_yixin13 @jiayanhong-hw @w30013702 @dingxiaochen -zh-cn/application-dev/telephony/telephony-call.md @zhang_yixin13 @jiayanhong-hw @w30013702 @dingxiaochen -zh-cn/application-dev/telephony/telephony-sms.md @zhang_yixin13 @jiayanhong-hw @w30013702 @dingxiaochen +zh-cn/application-dev/telephony/telephony-overview.md @zhang_yixin13 +zh-cn/application-dev/telephony/telephony-call.md @zhang_yixin13 +zh-cn/application-dev/telephony/telephony-sms.md @zhang_yixin13 [开发-Test Kit] -zh-cn/application-dev/application-test/arkxtest-guidelines.md @Brilliantry_Rui @inter515 -zh-cn/application-dev/application-test/smartperf-guidelines.md @Brilliantry_Rui @niuguoliang @xielinnan -zh-cn/application-dev/application-test/wukong-guidelines.md @Brilliantry_Rui +zh-cn/application-dev/application-test/arkxtest-guidelines.md @Brilliantry_Rui @inter515 @laonie666 @lv_yu_peng +zh-cn/application-dev/application-test/smartperf-guidelines.md @Brilliantry_Rui @inter515 @niuguoliang @laonie666 @lv_yu_peng +zh-cn/application-dev/application-test/wukong-guidelines.md @Brilliantry_Rui @qkfg @caixincen [开发-Webgl] zh-cn/application-dev/webgl/ @ge-yafang @zhangqiang183 @wind_zj @zxg-gitee @@ -556,20 +508,21 @@ zh-cn/application-dev/reference/apis-ability-kit/errorcode-DistributedSchedule.m [API参考-Ability Kit-包管理] -zh-cn/application-dev/reference/apis-ability-kit/js-apis-bundle*.md @Brilliantry_Rui @changzheng6 @hou-xiangyu1029 @kongjing2 @small_bricklayer -zh-cn/application-dev/reference/apis-ability-kit/js-apis-appControl.md @Brilliantry_Rui @changzheng6 @hou-xiangyu1029 @kongjing2 @small_bricklayer -zh-cn/application-dev/reference/apis-ability-kit/js-apis-defaultAppManager.md @Brilliantry_Rui @changzheng6 @hou-xiangyu1029 @kongjing2 @small_bricklayer -zh-cn/application-dev/reference/apis-ability-kit/js-apis-distributedBundleManager.md @Brilliantry_Rui @changzheng6 @hou-xiangyu1029 @kongjing2 @small_bricklayer -zh-cn/application-dev/reference/apis-ability-kit/js-apis-freeInstall.md @Brilliantry_Rui @changzheng6 @hou-xiangyu1029 @kongjing2 @small_bricklayer -zh-cn/application-dev/reference/apis-ability-kit/js-apis-installer.md @Brilliantry_Rui @changzheng6 @hou-xiangyu1029 @kongjing2 @small_bricklayer -zh-cn/application-dev/reference/apis-ability-kit/js-apis-launcherBundleManager.md @Brilliantry_Rui @changzheng6 @hou-xiangyu1029 @kongjing2 @small_bricklayer -zh-cn/application-dev/reference/apis-ability-kit/js-apis-overlay.md @Brilliantry_Rui @changzheng6 @hou-xiangyu1029 @kongjing2 @small_bricklayer -zh-cn/application-dev/reference/apis-ability-kit/js-apis-zlib.md @Brilliantry_Rui @changzheng6 @hou-xiangyu1029 @kongjing2 @small_bricklayer -zh-cn/application-dev/reference/apis-ability-kit/errorcode-bundle.md @Brilliantry_Rui @changzheng6 @hou-xiangyu1029 @kongjing2 @small_bricklayer -zh-cn/application-dev/reference/apis-ability-kit/errorcode-zlib.md @Brilliantry_Rui @changzheng6 @hou-xiangyu1029 @kongjing2 @small_bricklayer +zh-cn/application-dev/reference/apis-ability-kit/js-apis-bundle*.md @Brilliantry_Rui @changzheng6 @kongjing2 @small_bricklayer +zh-cn/application-dev/reference/apis-ability-kit/js-apis-installer-sys.md @Brilliantry_Rui @changzheng6 @kongjing2 @small_bricklayer +zh-cn/application-dev/reference/apis-ability-kit/js-apis-appControl.md @Brilliantry_Rui @changzheng6 @kongjing2 @small_bricklayer +zh-cn/application-dev/reference/apis-ability-kit/js-apis-defaultAppManager.md @Brilliantry_Rui @changzheng6 @kongjing2 @small_bricklayer +zh-cn/application-dev/reference/apis-ability-kit/js-apis-distributedBundleManager.md @Brilliantry_Rui @changzheng6 @kongjing2 @small_bricklayer +zh-cn/application-dev/reference/apis-ability-kit/js-apis-freeInstall.md @Brilliantry_Rui @changzheng6 @kongjing2 @small_bricklayer +zh-cn/application-dev/reference/apis-ability-kit/js-apis-installer.md @Brilliantry_Rui @changzheng6 @kongjing2 @small_bricklayer +zh-cn/application-dev/reference/apis-ability-kit/js-apis-launcherBundleManager.md @Brilliantry_Rui @changzheng6 @kongjing2 @small_bricklayer +zh-cn/application-dev/reference/apis-ability-kit/js-apis-overlay.md @Brilliantry_Rui @changzheng6 @kongjing2 @small_bricklayer +zh-cn/application-dev/reference/apis-ability-kit/js-apis-zlib.md @Brilliantry_Rui @changzheng6 @kongjing2 @small_bricklayer +zh-cn/application-dev/reference/apis-ability-kit/errorcode-bundle.md @Brilliantry_Rui @changzheng6 @kongjing2 @small_bricklayer +zh-cn/application-dev/reference/apis-ability-kit/errorcode-zlib.md @Brilliantry_Rui @changzheng6 @kongjing2 @small_bricklayer [API参考-Ability Kit-分布式] -zh-cn/application-dev/reference/apis-ability-kit/js-apis-distributedMissionManager.md @chenmingJay @Brilliantry_Rui @nan-xiansen @iceice1001 +zh-cn/application-dev/reference/apis-ability-kit/js-apis-distributedMissionManager.md @chenmingJay @nan-xiansen @iceice1001 [API参考-Accessibility kit] @@ -638,13 +591,13 @@ zh-cn/application-dev/reference/apis-arkts/js-apis-taskpool.md @gongjunsong @ge- zh-cn/application-dev/reference/apis-arkui/js-service-widget-ui/ @HelloCrease [API参考-ArkUI-TS组件] -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-events-click.md @jiangtao92 @zhaojian2021 @fredyuan0912 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-events-touch.md @jiangtao92 @zhaojian2021 @fredyuan0912 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-events-click.md @jiangtao92 @piggyguy @fredyuan0912 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-events-touch.md @jiangtao92 @piggyguy @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-events-show-hide.md @jiangtao92 @sunfei2021 @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-events-drag-drop.md @jiangtao92 @piggyguy @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-events-key.md @jiangtao92 @benb365 @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-focus-event.md @jiangtao92 @benb365 @fredyuan0912 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-mouse-key.md @jiangtao92 @zhaojian2021 @fredyuan0912 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-mouse-key.md @jiangtao92 @piggyguy @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-component-area-change-event.md @jiangtao92 @sunfei2021 @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-component-visible-area-change-event.md @jiangtao92 @sunfei2021 @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-events-keyboardshortcut.md @jiangtao92 @benb365 @fredyuan0912 @HelloCrease @@ -653,66 +606,66 @@ zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-size zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-location.md @laigerendaqiu @crazyracing0726 @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-layout-constraints.md @laigerendaqiu @crazyracing0726 @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-flex-layout.md @laigerendaqiu @crazyracing0726 @fredyuan0912 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-border.md @laigerendaqiu @crazyracing0726 @luyuxuan1 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-border-image.md @crazyracing0726 @luyuxuan1 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-background.md @jiangtao92 @sunfei2021 @luyuxuan1 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-opacity.md @lightningHo @luyuxuan1 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-border.md @laigerendaqiu @crazyracing0726 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-border-image.md @crazyracing0726 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-background.md @jiangtao92 @sunfei2021 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-opacity.md @hehongyang9 @lightningHo @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-visibility.md @jiangtao92 @sunfei2021 @fredyuan0912 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-enable.md @jiangtao92 @zhaojian2021 @fredyuan0912 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-enable.md @jiangtao92 @piggyguy @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-overlay.md @jiangtao92 @benb365 @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-z-order.md @jiangtao92 @sunfei2021 @fredyuan0912 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-transformation.md @lightningHo @luyuxuan1 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-image-effect.md @lightningHo @luyuxuan1 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-sharp-clipping.md @lightningHo @luyuxuan1 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-transformation.md @hehongyang9 @lightningHo @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-image-effect.md @hehongyang9 @lightningHo @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-sharp-clipping.md @hehongyang9 @lightningHo @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-grid.md @laigerendaqiu @fredyuan0912 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-gradient-color.md @lightningHo @luyuxuan1 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-popup.md @zhanghaibo0 @luyuxuan1 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-menu.md @luyuxuan1 @HelloCrease @zhanghaibo0 +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-gradient-color.md @hehongyang9 @lightningHo @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-popup.md @zhanghaibo0 @li-xinlei007 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-menu.md @li-xinlei007 @HelloCrease @zhanghaibo0 zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-focus.md @benb365 @fredyuan0912 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-hover-effect.md @jiangtao92 @zhaojian2021 @fredyuan0912 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-hover-effect.md @jiangtao92 @piggyguy @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-component-id.md @jiangtao92 @sunfei2021 @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-polymorphic-style.md @jiangtao92 @piggyguy @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-restoreId.md @jiangtao92 @sunfei2021 @fredyuan0912 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-foreground-color.md @lightningHo @luyuxuan1 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-foreground-blur-style.md @lightningHo @luyuxuan1 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-click-effect.md @lightningHo @luyuxuan1 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-foreground-color.md @hehongyang9 @lightningHo @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-foreground-blur-style.md @hehongyang9 @lightningHo @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-click-effect.md @lightningHo @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-accessibility.md @lmleon @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-attribute-modifier.md @harmony_zhangjian @sunfei2021 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-outline.md @luyuxuan1 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-touch-target.md @jiangtao92 @zhaojian2021 @fredyuan0912 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-hit-test-behavior.md @jiangtao92 @zhaojian2021 @fredyuan0912 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-modal-transition.md @raulnaruto_admin @cheng-feiwang @luyuxuan1 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-sheet-transition.md @raulnaruto_admin @cheng-feiwang @luyuxuan1 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-outline.md @hehongyang9 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-touch-target.md @jiangtao92 @piggyguy @fredyuan0912 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-hit-test-behavior.md @jiangtao92 @piggyguy @fredyuan0912 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-modal-transition.md @raulnaruto_admin @cheng-feiwang @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-sheet-transition.md @raulnaruto_admin @cheng-feiwang @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-obscured.md @jiangtao92 @sunfei2021 @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-text-style.md @jyj-0306 @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-drag-drop.md @jiangtao92 @piggyguy @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-expand-safe-area.md @laigerendaqiu @fredyuan0912 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-renderfit.md @lightningHo @luyuxuan1 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-monopolize-events.md @zhaojian2021 @fredyuan0912 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-cursor.md @zhaojian2021 @fredyuan0912 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-use-effect-sys.md @lightningHo @luyuxuan1 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-image-effect-sys.md @lightningHo @luyuxuan1 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-background-sys.md @lightningHo @luyuxuan1 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-foreground-blur-style-sys.md @lightningHo @luyuxuan1 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-gesture-settings.md @jiangtao92 @zhaojian2021 @fredyuan0912 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-gestures-tapgesture.md @jiangtao92 @zhaojian2021 @fredyuan0912 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-gestures-longpressgesture.md @jiangtao92 @zhaojian2021 @fredyuan0912 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-gestures-pangesture.md @jiangtao92 @zhaojian2021 @fredyuan0912 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-gestures-pinchgesture.md @jiangtao92 @zhaojian2021 @fredyuan0912 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-gestures-rotationgesture.md @jiangtao92 @zhaojian2021 @fredyuan0912 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-gestures-swipegesture.md @jiangtao92 @zhaojian2021 @fredyuan0912 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-combined-gestures.md @jiangtao92 @zhaojian2021 @fredyuan0912 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-gesture-customize-judge.md @jiangtao92 @zhaojian2021 @fredyuan0912 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-renderfit.md @hehongyang9 @lightningHo @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-monopolize-events.md @piggyguy @fredyuan0912 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-cursor.md @piggyguy @fredyuan0912 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-use-effect-sys.md @hehongyang9 @lightningHo @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-image-effect-sys.md @lightningHo @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-background-sys.md @lightningHo @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-foreground-blur-style-sys.md @lightningHo @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-gesture-settings.md @jiangtao92 @piggyguy @fredyuan0912 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-gestures-tapgesture.md @jiangtao92 @piggyguy @fredyuan0912 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-gestures-longpressgesture.md @jiangtao92 @piggyguy @fredyuan0912 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-gestures-pangesture.md @jiangtao92 @piggyguy @fredyuan0912 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-gestures-pinchgesture.md @jiangtao92 @piggyguy @fredyuan0912 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-gestures-rotationgesture.md @jiangtao92 @piggyguy @fredyuan0912 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-gestures-swipegesture.md @jiangtao92 @piggyguy @fredyuan0912 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-combined-gestures.md @jiangtao92 @piggyguy @fredyuan0912 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-gesture-customize-judge.md @jiangtao92 @piggyguy @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-container-alphabet-indexer.md @cc520bf @yeyinglong_admin @lihaoyn @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-blank.md @laigerendaqiu @fredyuan0912 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-button.md @youzhi92 @luyuxuan1 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-calendarpicker.md @jinweiliu @lexiaoyao2 @luyuxuan1 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-checkbox.md @youzhi92 @luyuxuan1 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-checkboxgroup.md @youzhi92 @luyuxuan1 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-button.md @firminly @li-xinlei007 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-calendarpicker.md @jinweiliu @lexiaoyao2 @li-xinlei007 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-checkbox.md @houguobiao @li-xinlei007 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-checkboxgroup.md @houguobiao @li-xinlei007 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-containerspan.md @jyj-0306 @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-datapanel.md @lihaoyn @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-datepicker.md @jinweiliu @lexiaoyao2 @luyuxuan1 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-datepicker.md @jinweiliu @lexiaoyao2 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-divider.md @laigerendaqiu @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-gauge.md @ileft201 @lihaoyn @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-image.md @lexiaoyao2 @fredyuan0912 @HelloCrease @@ -720,9 +673,9 @@ zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-imageani zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-imagespan.md @lexiaoyao2 @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-loadingprogress.md @ileft201 @lihaoyn @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-marquee.md @jyj-0306 @fredyuan0912 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-menu.md @luyuxuan1 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-menuitem.md @luyuxuan1 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-menuitemgroup.md @luyuxuan1 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-menu.md @li-xinlei007 @HelloCrease @zhanghaibo0 +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-menuitem.md @li-xinlei007 @HelloCrease @zhanghaibo0 +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-menuitemgroup.md @li-xinlei007 @HelloCrease @zhanghaibo0 zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-navigation.md @raulnaruto_admin @jiangdayuan @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-navrouter.md @raulnaruto_admin @jiangdayuan @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-navdestination.md @raulnaruto_admin @jiangdayuan @fredyuan0912 @HelloCrease @@ -730,14 +683,14 @@ zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-nodecont zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-patternlock.md @ileft201 @lihaoyn @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-progress.md @ileft201 @lihaoyn @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-qrcode.md @ileft201 @lihaoyn @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-radio.md @youzhi92 @fredyuan0912 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-rating.md @youzhi92 @fredyuan0912 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-radio.md @houguobiao @li-xinlei007 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-rating.md @firminly @li-xinlei007 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-richeditor.md @vviinnoo24 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-richtext.md @bigpumpkin @HelloCrease @litao33 @zhang-xinyue15 +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-richtext.md @bigpumpkin @HelloCrease @litao33 @GHiker zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-scrollbar.md @cc520bf @yeyinglong_admin @lihaoyn @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-search.md @jyj-0306 @fredyuan0912 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-select.md @youzhi92 @luyuxuan1 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-slider.md @youzhi92 @luyuxuan1 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-select.md @zhanghaibo0 @li-xinlei007 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-slider.md @firminly @li-xinlei007 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-span.md @jyj-0306 @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-stepper.md @raulnaruto_admin @jiangdayuan @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-stepperitem.md @raulnaruto_admin @jiangdayuan @fredyuan0912 @HelloCrease @@ -747,10 +700,10 @@ zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-text.md zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-textarea.md @jyj-0306 @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-textclock.md @ileft201 @lihaoyn @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-textinput.md @jyj-0306 @fredyuan0912 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-textpicker.md @jinweiliu @lexiaoyao2 @luyuxuan1 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-textpicker.md @jinweiliu @lexiaoyao2 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-texttimer.md @ileft201 @lihaoyn @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-timepicker.md @jinweiliu @lexiaoyao2 @luyuxuan1 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-toggle.md @youzhi92 @luyuxuan1 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-timepicker.md @jinweiliu @lexiaoyao2 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-toggle.md @houguobiao @li-xinlei007 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-xcomponent.md @ZhangYu-Home @keerecles @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-component3d-sys.md @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-image-sys.md @crazyracing0726 @fredyuan0912 @HelloCrease @@ -765,9 +718,9 @@ zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-container-counter.md @ile zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-container-flex.md @laigerendaqiu @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-container-flowitem.md @cc520bf @zcdqs @lihaoyn @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-container-folderstack.md @laigerendaqiu @fredyuan0912 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-formcomponent-sys.md @arondave @hehe9876 @Brilliantry_Rui @ylsnow -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-container-formlink.md @arondave @hehe9876 @Brilliantry_Rui @ylsnow -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-formmenu.md @Brilliantry_Rui @ylsnow +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-formcomponent-sys.md @Brilliantry_Rui @ylsnow @cmz001 @Eiln +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-container-formlink.md @Brilliantry_Rui @ylsnow @cmz001 @Eiln +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-formmenu.md @Brilliantry_Rui @ylsnow @cmz001 @Eiln zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-container-gridcol.md @laigerendaqiu @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-container-gridrow.md @laigerendaqiu @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-container-grid.md @cc520bf @zcdqs @lihaoyn @HelloCrease @@ -777,7 +730,7 @@ zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-container-list.md @cc520b zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-container-listitem.md @cc520bf @yeyinglong_admin @lihaoyn @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-container-listitemgroup.md @cc520bf @yeyinglong_admin @lihaoyn @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-container-navigator.md @raulnaruto_admin @jiangdayuan @fredyuan0912 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-container-panel.md @raulnaruto_admin @luyuxuan1 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-container-panel.md @raulnaruto_admin @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-container-refresh.md @cc520bf @yeyinglong_admin @lihaoyn @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-container-relativecontainer.md @laigerendaqiu @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-container-row.md @laigerendaqiu @fredyuan0912 @HelloCrease @@ -823,7 +776,7 @@ zh-cn/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-Exceptio zh-cn/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-Filter.md @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-GridObjectSortComponent.md @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ProgressButton.md @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-Popup.md @youzhi92 @luyuxuan1 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-Popup.md @firminly @li-xinlei007 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-SegmentButton.md @youzhi92 @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-SelectionMenu.md @jyj-0306 @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-SelectTitleBar.md @HelloCrease @@ -835,38 +788,49 @@ zh-cn/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ToolBar. zh-cn/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-TreeView.md @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-FullScreenLaunchComponent.md @dutie123 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-animatorproperty.md @lightningHo @luyuxuan1 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-explicit-animation.md @lightningHo @luyuxuan1 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-keyframeAnimateTo.md @lightningHo @luyuxuan1 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-page-transition-animation.md @lightningHo @luyuxuan1 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-transition-animation-component.md @lightningHo @luyuxuan1 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-transition-animation-shared-elements.md @lightningHo @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-transition-animation-geometrytransition.md @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-motion-path-animation.md @lightningHo @luyuxuan1 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-particle-animation.md @lightningHo @luyuxuan1 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-explicit-animatetoimmediately-sys.md @lightningHo @luyuxuan1 @HelloCrease - -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-methods-alert-dialog-box.md @luyuxuan1 @HelloCrease @zhanghaibo0 -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-methods-action-sheet.md @luyuxuan1 @HelloCrease @zhanghaibo0 -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-methods-custom-dialog-box.md @luyuxuan1 @HelloCrease @zhanghaibo0 -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-methods-calendarpicker-dialog.md @jinweiliu @lexiaoyao2 @luyuxuan1 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-methods-datepicker-dialog.md @jinweiliu @lexiaoyao2 @luyuxuan1 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-methods-timepicker-dialog.md @jinweiliu @lexiaoyao2 @luyuxuan1 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-methods-textpicker-dialog.md @jinweiliu @lexiaoyao2 @luyuxuan1 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-methods-menu.md @youzhi92 @luyuxuan1 @HelloCrease - -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-custom-component-lifecycle.md @seaside_wu @s10021109 @fredyuan0912 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-animatorproperty.md @hehongyang9 @lightningHo @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-explicit-animation.md @hehongyang9 @lightningHo @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-keyframeAnimateTo.md @hehongyang9 @lightningHo @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-page-transition-animation.md @lightningHo @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-transition-animation-component.md @hehongyang9 @lightningHo @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-transition-animation-shared-elements.md @hehongyang9 @lightningHo @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-transition-animation-geometrytransition.md @hehongyang9 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-motion-path-animation.md @hehongyang9 @lightningHo @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-particle-animation.md @hehongyang9 @lightningHo @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-explicit-animatetoimmediately-sys.md @hehongyang9 @lightningHo @HelloCrease + +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-methods-alert-dialog-box.md @li-xinlei007 @HelloCrease @houguobiao +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-methods-action-sheet.md @li-xinlei007 @HelloCrease @houguobiao +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-methods-custom-dialog-box.md @li-xinlei007 @HelloCrease @houguobiao +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-methods-calendarpicker-dialog.md @jinweiliu @lexiaoyao2 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-methods-datepicker-dialog.md @jinweiliu @lexiaoyao2 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-methods-timepicker-dialog.md @jinweiliu @lexiaoyao2 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-methods-textpicker-dialog.md @jinweiliu @lexiaoyao2 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-methods-menu.md @zhanghaibo0 @li-xinlei007 @HelloCrease + +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-custom-component-lifecycle.md @jiyujia926 @seaside_wu @s10021109 @zhang_yixin13 zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-custom-component-api.md @s10021109 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-state-management.md @jiyujia926 @s10021109 @fredyuan0912 @zhang_yixin13 +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-state-management.md @jiyujia926 @s10021109 @zhang_yixin13 zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-pixel-units.md @jiangtao92 @sunfei2021 @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-appendix-enums.md @jiangtao92 @sunfei2021 @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-types.md @jiangtao92 @sunfei2021 @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-container-ability-component-sys.md @seaside_wu @keerecles @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-container-gridcontainer.md @crazyracing0726 @fredyuan0912 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-click.md @jiangtao92 @zhaojian2021 @fredyuan0912 @HelloCrease - +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-universal-attributes-click.md @jiangtao92 @piggyguy @fredyuan0912 @HelloCrease + + +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-rendering-control-foreach.md @jiyujia926 @seaside_wu @s10021109 @zhang_yixin13 +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-rendering-control-lazyforeach.md @jiyujia926 @seaside_wu @s10021109 @zhang_yixin13 +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-rendering-control-repeat.md @jiyujia926 @seaside_wu @s10021109 @zhang_yixin13 +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ts-state-management-sys.md @jiyujia926 @seaside_wu @s10021109 @zhang_yixin13 +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-SegmentButtonV2.md @jiyujia926 @seaside_wu @s10021109 +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ProgressButtonV2.md @jiyujia926 @seaside_wu @s10021109 +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ToolBarV2.md @jiyujia926 @seaside_wu @s10021109 +zh-cn/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-SubHeaderV2.md @jiyujia926 @seaside_wu @s10021109 +zh-cn/application-dev/reference/apis-arkui/js-apis-StateManagement.md @jiyujia926 @seaside_wu @s10021109 @zhang_yixin13 + [API参考-ArkUI-ArkTS] -zh-cn/application-dev/reference/apis-arkui/js-apis-animator.md @lightningHo @luyuxuan1 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/js-apis-animator.md @hehongyang9 @lightningHo @HelloCrease zh-cn/application-dev/reference/apis-arkui/js-apis-arkui-componentSnapshot.md @piggyguy @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/js-apis-arkui-componentUtils.md @piggyguy @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/js-apis-arkui-dragController.md @piggyguy @fredyuan0912 @HelloCrease @@ -874,22 +838,22 @@ zh-cn/application-dev/reference/apis-arkui/js-apis-arkui-drawableDescriptor.md zh-cn/application-dev/reference/apis-arkui/js-apis-arkui-inspector.md @HelloCrease zh-cn/application-dev/reference/apis-arkui/js-apis-arkui-node.md @lightningHo @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/js-apis-arkui-observer.md @fredyuan0912 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/js-apis-arkui-UIContext.md @sunfei2021 @luyuxuan1 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/js-apis-curve.md @lightningHo @luyuxuan1 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/js-apis-arkui-UIContext.md @sunfei2021 @fredyuan0912 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/js-apis-curve.md @hehongyang9 @lightningHo @HelloCrease zh-cn/application-dev/reference/apis-arkui/js-apis-font.md @HelloCrease -zh-cn/application-dev/reference/apis-arkui/js-apis-matrix4.md @lightningHo @luyuxuan1 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/js-apis-matrix4.md @hehongyang9 @lightningHo @HelloCrease zh-cn/application-dev/reference/apis-arkui/js-apis-measure.md @jyj-0306 @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/js-apis-mediaquery.md @laigerendaqiu @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/js-apis-plugincomponent.md @fredyuan0912 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/js-apis-promptAction.md @luyuxuan1 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/js-apis-promptAction.md @li-xinlei007 @HelloCrease zh-cn/application-dev/reference/apis-arkui/js-apis-router.md @raulnaruto_admin @fredyuan0912 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/js-apis-getContext.md @luyuxuan1 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/js-apis-getContext.md @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/js-apis-postCardAction.md @arondave @hehe9876 @HelloCrease zh-cn/application-dev/reference/apis-arkui/js-apis-arkui-drawableDescriptor-sys.md @crazyracing0726 @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/js-apis-arkui-performancemonitor-sys.md @lushi1202 @HelloCrease zh-cn/application-dev/reference/apis-arkui/js-apis-devicestatus-draginteraction-sys.md @piggyguy @fredyuan0912 @HelloCrease zh-cn/application-dev/reference/apis-arkui/js-apis-plugincomponent-sys.md @keerecles @fredyuan0912 @HelloCrease -zh-cn/application-dev/reference/apis-arkui/js-apis-uiappearance-sys.md @lushi1202 @luyuxuan1 @HelloCrease +zh-cn/application-dev/reference/apis-arkui/js-apis-uiappearance-sys.md @lushi1202 @HelloCrease zh-cn/application-dev/reference/apis-arkui/js-apis-uiExtensionHost-sys.md @ge-yafang @zhouyaoying @nobuggers zh-cn/application-dev/reference/apis-arkui/js-apis-arkui-uiExtension.md @ge-yafang @zhouyaoying @nobuggers zh-cn/application-dev/reference/apis-arkui/js-apis-arkui-uiExtension-sys.md @ge-yafang @zhouyaoying @nobuggers @@ -919,26 +883,27 @@ zh-cn/application-dev/reference/apis-arkui/errorcode-display.md @ge-yafang @acha [API参考-ArkWeb] -zh-cn/application-dev/reference/apis-arkweb/js-apis-webview.md @bigpumpkin @HelloCrease @litao33 @zhang-xinyue15 -zh-cn/application-dev/reference/apis-arkweb/ts-basic-components-web.md @bigpumpkin @HelloCrease @litao33 @zhang-xinyue15 -zh-cn/application-dev/reference/apis-arkweb/native_interface_arkweb.md @bigpumpkin @HelloCrease @litao33 @zhang-xinyue15 -zh-cn/application-dev/reference/apis-arkweb/errorcode-webview.md @bigpumpkin @HelloCrease @litao33 @zhang-xinyue15 +zh-cn/application-dev/reference/apis-arkweb/js-apis-webview.md @bigpumpkin @HelloCrease @litao33 @GHiker +zh-cn/application-dev/reference/apis-arkweb/ts-basic-components-web.md @bigpumpkin @HelloCrease @litao33 @GHiker +zh-cn/application-dev/reference/apis-arkweb/native_interface_arkweb.md @bigpumpkin @HelloCrease @litao33 @GHiker +zh-cn/application-dev/reference/apis-arkweb/errorcode-webview.md @bigpumpkin @HelloCrease @litao33 @GHiker [API参考-Background Tasks Kit] -zh-cn/application-dev/reference/apis-backgroundtasks-kit/js-apis-reminderAgentManager.md @Brilliantry_Rui -zh-cn/application-dev/reference/apis-backgroundtasks-kit/js-apis-reminderAgentManager-sys.md @Brilliantry_Rui -zh-cn/application-dev/reference/apis-backgroundtasks-kit/js-apis-resourceschedule-backgroundTaskManager.md @Brilliantry_Rui -zh-cn/application-dev/reference/apis-backgroundtasks-kit/js-apis-resourceschedule-backgroundTaskManager-sys.md @Brilliantry_Rui -zh-cn/application-dev/reference/apis-backgroundtasks-kit/js-apis-resourceschedule-workScheduler.md @Brilliantry_Rui -zh-cn/application-dev/reference/apis-backgroundtasks-kit/js-apis-WorkSchedulerExtensionAbility.md @Brilliantry_Rui -zh-cn/application-dev/reference/apis-backgroundtasks-kit/js-apis-inner-application-WorkSchedulerExtensionContext.md @Brilliantry_Rui -zh-cn/application-dev/reference/apis-backgroundtasks-kit/js-apis-resourceschedule-deviceStandby-sys.md @Brilliantry_Rui -zh-cn/application-dev/reference/apis-backgroundtasks-kit/js-apis-resourceschedule-deviceUsageStatistics-sys.md @Brilliantry_Rui -zh-cn/application-dev/reference/apis-backgroundtasks-kit/errorcode-backgroundTaskMgr.md @Brilliantry_Rui -zh-cn/application-dev/reference/apis-backgroundtasks-kit/errorcode-reminderAgentManager.md @Brilliantry_Rui -zh-cn/application-dev/reference/apis-backgroundtasks-kit/errorcode-workScheduler.md @Brilliantry_Rui -zh-cn/application-dev/reference/apis-backgroundtasks-kit/errorcode-DeviceUsageStatistics.md @Brilliantry_Rui +zh-cn/application-dev/reference/apis-backgroundtasks-kit @Brilliantry_Rui @zhouben25 @cooffee10 @cheng-shichang +zh-cn/application-dev/reference/apis-backgroundtasks-kit/js-apis-reminderAgentManager.md @Brilliantry_Rui @zhouben25 @cooffee10 @cheng-shichang +zh-cn/application-dev/reference/apis-backgroundtasks-kit/js-apis-reminderAgentManager-sys.md @Brilliantry_Rui @zhouben25 @cooffee10 @cheng-shichang +zh-cn/application-dev/reference/apis-backgroundtasks-kit/js-apis-resourceschedule-backgroundTaskManager.md @Brilliantry_Rui @zhouben25 @cooffee10 @cheng-shichang +zh-cn/application-dev/reference/apis-backgroundtasks-kit/js-apis-resourceschedule-backgroundTaskManager-sys.md @Brilliantry_Rui @zhouben25 @cooffee10 @cheng-shichang +zh-cn/application-dev/reference/apis-backgroundtasks-kit/js-apis-resourceschedule-workScheduler.md @Brilliantry_Rui @zhouben25 @cooffee10 @cheng-shichang +zh-cn/application-dev/reference/apis-backgroundtasks-kit/js-apis-WorkSchedulerExtensionAbility.md @Brilliantry_Rui @zhouben25 @cooffee10 @cheng-shichang +zh-cn/application-dev/reference/apis-backgroundtasks-kit/js-apis-inner-application-WorkSchedulerExtensionContext.md @Brilliantry_Rui @zhouben25 @cooffee10 @cheng-shichang +zh-cn/application-dev/reference/apis-backgroundtasks-kit/js-apis-resourceschedule-deviceStandby-sys.md @Brilliantry_Rui @zhouben25 @cooffee10 @cheng-shichang +zh-cn/application-dev/reference/apis-backgroundtasks-kit/js-apis-resourceschedule-deviceUsageStatistics-sys.md @Brilliantry_Rui @zhouben25 @cooffee10 @cheng-shichang +zh-cn/application-dev/reference/apis-backgroundtasks-kit/errorcode-backgroundTaskMgr.md @Brilliantry_Rui @zhouben25 @cooffee10 @cheng-shichang +zh-cn/application-dev/reference/apis-backgroundtasks-kit/errorcode-reminderAgentManager.md @Brilliantry_Rui @zhouben25 @cooffee10 @cheng-shichang +zh-cn/application-dev/reference/apis-backgroundtasks-kit/errorcode-workScheduler.md @Brilliantry_Rui @zhouben25 @cooffee10 @cheng-shichang +zh-cn/application-dev/reference/apis-backgroundtasks-kit/errorcode-DeviceUsageStatistics.md @Brilliantry_Rui @zhouben25 @cooffee10 @cheng-shichang [API参考-Basic Services Kit-配置策略] zh-cn/application-dev/reference/apis-basic-services-kit/js-apis-configPolicy-sys.md @Brilliantry_Rui @yangqing3 @liubingbing @@ -952,13 +917,13 @@ zh-cn/application-dev/reference/apis-basic-services-kit/js-apis-osAccount-sys.md zh-cn/application-dev/reference/apis-basic-services-kit/errorcode-account.md @zengyawen [API参考-Basic Services Kit-公共事件] -zh-cn/application-dev/reference/apis-basic-sevices-kit/js-apis-commonEvent*.md @huipeizi @idanny @shine_hk -zh-cn/application-dev/reference/apis-basic-sevices-kit/js-apis-inner-commonEvent*.md @huipeizi @idanny @shine_hk -zh-cn/application-dev/reference/apis-basic-sevices-kit/js-apis-emitter.md @huipeizi @idanny @shine_hk -zh-cn/application-dev/reference/apis-basic-sevices-kit/capi-common-event.md @huipeizi @idanny @shine_hk -zh-cn/application-dev/reference/apis-basic-sevices-kit/oh_commonevent*.md @huipeizi @idanny @shine_hk -zh-cn/application-dev/reference/apis-basic-sevices-kit/common_event/ @huipeizi @idanny @shine_hk -zh-cn/application-dev/reference/apis-basic-sevices-kit/errorcode-CommonEventService.md @huipeizi @idanny @shine_hk +zh-cn/application-dev/reference/apis-basic-sevices-kit/js-apis-commonEvent*.md @huipeizi @dong-qingran @shine_hk +zh-cn/application-dev/reference/apis-basic-sevices-kit/js-apis-inner-commonEvent*.md @huipeizi @dong-qingran @shine_hk +zh-cn/application-dev/reference/apis-basic-sevices-kit/js-apis-emitter.md @huipeizi @dong-qingran @shine_hk +zh-cn/application-dev/reference/apis-basic-sevices-kit/capi-common-event.md @huipeizi @dong-qingran @shine_hk +zh-cn/application-dev/reference/apis-basic-sevices-kit/oh_commonevent*.md @huipeizi @dong-qingran @shine_hk +zh-cn/application-dev/reference/apis-basic-sevices-kit/common_event/ @huipeizi @dong-qingran @shine_hk +zh-cn/application-dev/reference/apis-basic-sevices-kit/errorcode-CommonEventService.md @huipeizi @dong-qingran @shine_hk [API参考-Basic Services Kit-设备管理] @@ -1087,7 +1052,7 @@ zh-cn/application-dev/reference/apis-driverdevelopment-kit/ @li-yan339 [API参考-Form Kit] -zh-cn/application-dev/reference/apis-form-kit/ @Eiln @cmz001 @Brilliantry_Rui @yuanzhishuai @ylsnow +zh-cn/application-dev/reference/apis-form-kit/ @ylsnow @cmz001 @Brilliantry_Rui @Eiln @@ -1096,29 +1061,31 @@ zh-cn/application-dev/reference/apis-ime-kit/ @illybyy @murphy1984 @feng-aiwen [API参考-Input Kit] -zh-cn/application-dev/reference/apis-input-kit/ @hhh2 @Brilliantry_Rui @mayunteng @star-wind-snow-and-rain +zh-cn/application-dev/reference/apis-input-kit/ @Brilliantry_Rui @mayunteng @ustblx @hanruofei [API参考-IPC Kit] -zh-cn/application-dev/reference/apis-ipc-kit/js-apis-rpc.md @luodh0157 @zhang_yixin13 @zhaopeng_gitee @zhang-yang123321 +zh-cn/application-dev/reference/apis-ipc-kit/js-apis-rpc.md @xdx1921 @zhang_yixin13 @zhaopeng_gitee @zhang-yang123321 [API参考-Localization Kit] -zh-cn/application-dev/reference/apis-Localization-kit/js-apis-i18n.md @Brilliantry_Rui @yliupy @yangqing3 @sunyaozu -zh-cn/application-dev/reference/apis-Localization-kit/js-apis-intl.md @Brilliantry_Rui @yliupy @yangqing3 @sunyaozu -zh-cn/application-dev/reference/apis-Localization-kit/js-apis-i18n-sys.md @Brilliantry_Rui @yliupy @yangqing3 @sunyaozu -zh-cn/application-dev/reference/apis-Localization-kit/errorcode-i18n.md @Brilliantry_Rui @yliupy @yangqing3 @sunyaozu -zh-cn/application-dev/reference/apis-Localization-kit/js-apis-resource-manager.md @Brilliantry_Rui @budda-wang @yangqing3 -zh-cn/application-dev/reference/apis-Localization-kit/js-apis-sendable-resource-manager.md @Brilliantry_Rui @budda-wang @yangqing3 -zh-cn/application-dev/reference/apis-Localization-kit/rawfile.md @Brilliantry_Rui @budda-wang @yangqing3 -zh-cn/application-dev/reference/apis-Localization-kit/resourcemanager.md @Brilliantry_Rui @budda-wang @yangqing3 -zh-cn/application-dev/reference/apis-Localization-kit/raw__dir_8h.md @Brilliantry_Rui @budda-wang @yangqing3 -zh-cn/application-dev/reference/apis-Localization-kit/raw__file__manager_8h.md @Brilliantry_Rui @budda-wang @yangqing3 -zh-cn/application-dev/reference/apis-Localization-kit/raw__file_8h.md @Brilliantry_Rui @budda-wang @yangqing3 -zh-cn/application-dev/reference/apis-Localization-kit/ohresmgr_8h.md @Brilliantry_Rui @budda-wang @yangqing3 -zh-cn/application-dev/reference/apis-Localization-kit/resmgr__common_8h.md @Brilliantry_Rui @budda-wang @yangqing3 -zh-cn/application-dev/reference/apis-Localization-kit/_raw_file_descriptor.md @Brilliantry_Rui @budda-wang @yangqing3 -zh-cn/application-dev/reference/apis-Localization-kit/_raw_file_descriptor64.md @Brilliantry_Rui @budda-wang @yangqing3 -zh-cn/application-dev/reference/apis-Localization-kit/errorcode-resource-manager.md @Brilliantry_Rui @budda-wang @yangqing3 +zh-cn/application-dev/reference/apis-Localization-kit @Brilliantry_Rui @lpw_work +zh-cn/application-dev/reference/apis-Localization-kit/js-apis-i18n.md @Brilliantry_Rui @yliupy @sunyaozu @lpw_work @lpw_work +zh-cn/application-dev/reference/apis-Localization-kit/js-apis-intl.md @Brilliantry_Rui @yliupy @sunyaozu @lpw_work +zh-cn/application-dev/reference/apis-Localization-kit/js-apis-i18n-sys.md @Brilliantry_Rui @yliupy @sunyaozu @lpw_work +zh-cn/application-dev/reference/apis-Localization-kit/errorcode-i18n.md @Brilliantry_Rui @yliupy @sunyaozu @lpw_work + +zh-cn/application-dev/reference/apis-Localization-kit/js-apis-resource-manager.md @Brilliantry_Rui @budda-wang @lpw_work +zh-cn/application-dev/reference/apis-Localization-kit/js-apis-sendable-resource-manager.md @Brilliantry_Rui @budda-wang @lpw_work +zh-cn/application-dev/reference/apis-Localization-kit/rawfile.md @Brilliantry_Rui @budda-wang @lpw_work +zh-cn/application-dev/reference/apis-Localization-kit/resourcemanager.md @Brilliantry_Rui @budda-wang @lpw_work +zh-cn/application-dev/reference/apis-Localization-kit/raw__dir_8h.md @Brilliantry_Rui @budda-wang @lpw_work +zh-cn/application-dev/reference/apis-Localization-kit/raw__file__manager_8h.md @Brilliantry_Rui @budda-wang @lpw_work +zh-cn/application-dev/reference/apis-Localization-kit/raw__file_8h.md @Brilliantry_Rui @budda-wang @lpw_work +zh-cn/application-dev/reference/apis-Localization-kit/ohresmgr_8h.md @Brilliantry_Rui @budda-wang @lpw_work +zh-cn/application-dev/reference/apis-Localization-kit/resmgr__common_8h.md @Brilliantry_Rui @budda-wang @lpw_work +zh-cn/application-dev/reference/apis-Localization-kit/_raw_file_descriptor.md @Brilliantry_Rui @budda-wang @lpw_work +zh-cn/application-dev/reference/apis-Localization-kit/_raw_file_descriptor64.md @Brilliantry_Rui @budda-wang @lpw_work +zh-cn/application-dev/reference/apis-Localization-kit/errorcode-resource-manager.md @Brilliantry_Rui @budda-wang @lpw_work [API参考-Location Kit] zh-cn/application-dev/reference/apis-location-kit/ @cheng_guohong @RayShih @cheng_guohong @xiangkejin123 @@ -1137,40 +1104,40 @@ zh-cn/application-dev/reference/apis-media-library-kit/ @zengyawen [API参考-MDM Kit] -zh-cn/application-dev/reference/apis-mdm-kit/ @liuzuming @Brilliantry_Rui @yangqing3 -zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-accountManager.md @liuzuming @Brilliantry_Rui @yangqing3 -zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-adminManager.md @liuzuming @Brilliantry_Rui @yangqing3 -zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-applicationManager.md @liuzuming @Brilliantry_Rui @yangqing3 -zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-bluetoothManager.md @liuzuming @Brilliantry_Rui @yangqing3 -zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-browser.md @liuzuming @Brilliantry_Rui @yangqing3 -zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-bundleManager.md @liuzuming @Brilliantry_Rui @yangqing3 -zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-deviceControl.md @liuzuming @Brilliantry_Rui @yangqing3 -zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-deviceInfo.md @liuzuming @Brilliantry_Rui @yangqing3 -zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-deviceSettings.md @liuzuming @Brilliantry_Rui @yangqing3 -zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-locationManager.md @liuzuming @Brilliantry_Rui @yangqing3 -zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-networkManager.md @liuzuming @Brilliantry_Rui @yangqing3 -zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-restrictions.md @liuzuming @Brilliantry_Rui @yangqing3 -zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-securityManager.md @liuzuming @Brilliantry_Rui @yangqing3 -zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-systemManager.md @liuzuming @Brilliantry_Rui @yangqing3 -zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-usbManager.md @liuzuming @Brilliantry_Rui @yangqing3 -zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-wifiManager.md @liuzuming @Brilliantry_Rui @yangqing3 -zh-cn/application-dev/reference/apis-mdm-kit/js-apis-EnterpriseAdminExtensionAbility.md @liuzuming @Brilliantry_Rui @yangqing3 -zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-accountManager-sys.md @liuzuming @Brilliantry_Rui @yangqing3 -zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-adminManager-sys.md @liuzuming @Brilliantry_Rui @yangqing3 -zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-applicationManager-sys.md @liuzuming @Brilliantry_Rui @yangqing3 -zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-bluetoothManager-sys.md @liuzuming @Brilliantry_Rui @yangqing3 -zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-browser-sys.md @liuzuming @Brilliantry_Rui @yangqing3 -zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-bundleManager-sys.md @liuzuming @Brilliantry_Rui @yangqing3 -zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-dateTimeManager-sys.md @liuzuming @Brilliantry_Rui @yangqing3 -zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-deviceControl-sys.md @liuzuming @Brilliantry_Rui @yangqing3 -zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-deviceInfo-sys.md @liuzuming @Brilliantry_Rui @yangqing3 -zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-deviceSettings-sys.md @liuzuming @Brilliantry_Rui @yangqing3 -zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-networkManager-sys.md @liuzuming @Brilliantry_Rui @yangqing3 -zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-restrictions-sys.md @liuzuming @Brilliantry_Rui @yangqing3 -zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-securityManager-sys.md @liuzuming @Brilliantry_Rui @yangqing3 -zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-usbManager-sys.md @liuzuming @Brilliantry_Rui @yangqing3 -zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-wifiManager-sys.md @liuzuming @Brilliantry_Rui @yangqing3 -zh-cn/application-dev/reference/apis-mdm-kit/errorcode-enterpriseDeviceManager.md @liuzuming @Brilliantry_Rui @yangqing3 +zh-cn/application-dev/reference/apis-mdm-kit/ @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han +zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-accountManager.md @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han +zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-adminManager.md @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han +zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-applicationManager.md @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han +zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-bluetoothManager.md @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han +zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-browser.md @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han +zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-bundleManager.md @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han +zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-deviceControl.md @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han +zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-deviceInfo.md @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han +zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-deviceSettings.md @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han +zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-locationManager.md @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han +zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-networkManager.md @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han +zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-restrictions.md @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han +zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-securityManager.md @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han +zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-systemManager.md @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han +zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-usbManager.md @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han +zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-wifiManager.md @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han +zh-cn/application-dev/reference/apis-mdm-kit/js-apis-EnterpriseAdminExtensionAbility.md @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han +zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-accountManager-sys.md @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han +zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-adminManager-sys.md @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han +zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-applicationManager-sys.md @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han +zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-bluetoothManager-sys.md @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han +zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-browser-sys.md @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han +zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-bundleManager-sys.md @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han +zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-dateTimeManager-sys.md @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han +zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-deviceControl-sys.md @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han +zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-deviceInfo-sys.md @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han +zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-deviceSettings-sys.md @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han +zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-networkManager-sys.md @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han +zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-restrictions-sys.md @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han +zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-securityManager-sys.md @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han +zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-usbManager-sys.md @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han +zh-cn/application-dev/reference/apis-mdm-kit/js-apis-enterprise-wifiManager-sys.md @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han +zh-cn/application-dev/reference/apis-mdm-kit/errorcode-enterpriseDeviceManager.md @liuzuming @Brilliantry_Rui @lpw_work @lucifinil_han [API参考-MindSpore Lite Kit] @@ -1186,7 +1153,7 @@ zh-cn/application-dev/reference/apis-multimodalawareness-kit/js-apis-stationary. [API参考-Network Kit] -zh-cn/application-dev/reference/apis-network-kit/ @jiayanhong-hw @zhang_yixin13 @w30013702 @rain_myf +zh-cn/application-dev/reference/apis-network-kit/ @lbch_hw @zhang_yixin13 [API参考-Neural NetWork Runtime Kit] @@ -1194,7 +1161,7 @@ zh-cn/application-dev/reference/apis-neural-network-runtime-kit/_neural_network_ [API参考-Notification Kit] -zh-cn/application-dev/reference/apis-notification-kit/ @huipeizi @idanny @shine_hk +zh-cn/application-dev/reference/apis-notification-kit/ @huipeizi @dong-qingran @shine_hk @@ -1231,28 +1198,30 @@ zh-cn/application-dev/reference/apis-sensor-service-kit/errorcode-vibrator.md @h [API参考-Telephony Kit] -zh-cn/application-dev/reference/apis-telephony-kit/ @jiayanhong-hw @zhang_yixin13 @w30013702 @dingxiaochen +zh-cn/application-dev/reference/apis-telephony-kit/ @zhang_yixin13 [API参考-Test Kit] -zh-cn/application-dev/reference/apis-tesk-kit/js-apis-testRunner.md -zh-cn/application-dev/reference/apis-tesk-kit/js-apis-app-ability-abilityDelegatorRegistry.md -zh-cn/application-dev/reference/apis-tesk-kit/js-apis-uitest.md @inter515 @Brilliantry_Rui @inter515 -zh-cn/application-dev/reference/apis-tesk-kit/errorcode-uitest.md @Brilliantry_Rui @inter515 -zh-cn/application-dev/reference/apis-basic-services-kit/js-apis-deviceAttest-sys.md @Brilliantry_Rui @jiyong +zh-cn/application-dev/reference/apis-tesk-kit/ @Brilliantry_Rui @inter515 @laonie666 @lv_yu_peng @yangyuyan-yyy +zh-cn/application-dev/reference/apis-tesk-kit/js-apis-testRunner.md @Brilliantry_Rui @inter515 @laonie666 @lv_yu_peng @yangyuyan-yyy +zh-cn/application-dev/reference/apis-tesk-kit/js-apis-app-ability-abilityDelegatorRegistry.md @Brilliantry_Rui @inter515 @laonie666 @lv_yu_peng @yangyuyan-yyy +zh-cn/application-dev/reference/apis-tesk-kit/js-apis-uitest.md @Brilliantry_Rui @inter515 @laonie666 @lv_yu_peng @yangyuyan-yyy +zh-cn/application-dev/reference/apis-tesk-kit/errorcode-uitest.md @Brilliantry_Rui @inter515 @laonie666 @lv_yu_peng @yangyuyan-yyy +zh-cn/application-dev/reference/apis-basic-services-kit/js-apis-deviceAttest-sys.md @Brilliantry_Rui @jiyong [工具-元能力、包管理、通知等] zh-cn/application-dev/tools/aa-tool.md @huipeizi @ccllee @lxfycode @lixueqing513 -zh-cn/application-dev/tools/bm-tool.md @Brilliantry_Rui @changzheng6 @hou-xiangyu1029 @kongjing2 @small_bricklayer -zh-cn/application-dev/tools/packing-tool.md @jsjzju @huipeizi @lixueqing513 -zh-cn/application-dev/tools/unpacking-tool.md @jsjzju @huipeizi @lixueqing513 -zh-cn/application-dev/tools/app-check-tool.md @jsjzju @huipeizi @lixueqing513 -zh-cn/application-dev/tools/cem-tool.md @huipeizi @idanny @shine_hk -zh-cn/application-dev/tools/anm-tool.md @huipeizi @idanny @shine_hk +zh-cn/application-dev/tools/bm-tool.md @Brilliantry_Rui @changzheng6 @kongjing2 @small_bricklayer +zh-cn/application-dev/tools/packing-tool.md @Brilliantry_Rui @changzheng6 @kongjing2 @small_bricklayer +zh-cn/application-dev/tools/unpacking-tool.md @Brilliantry_Rui @changzheng6 @kongjing2 @small_bricklayer +zh-cn/application-dev/tools/app-check-tool.md @Brilliantry_Rui @changzheng6 @kongjing2 @small_bricklayer +zh-cn/application-dev/tools/cem-tool.md @huipeizi @dong-qingran @shine_hk +zh-cn/application-dev/tools/anm-tool.md @huipeizi @dong-qingran @shine_hk +zh-cn/application-dev/tools/restool.md @Brilliantry_Rui @lliule21 @lpw_work @budda-wang [FAQ] zh-cn/application-dev/faqs/ @zengyawen zh-cn/application-dev/faqs/faqs-ability.md @huipeizi @ccllee @lxfycode @lixueqing513 -zh-cn/application-dev/faqs/faqs-bundle-management.md @huipeizi @changzheng6 @hou-xiangyu1029 @kongjing2 -zh-cn/application-dev/faqs/faqs-event-notification.md @huipeizi @idanny @shine_hk +zh-cn/application-dev/faqs/faqs-bundle-management.md @Brilliantry_Rui @changzheng6 @kongjing2 @small_bricklayer +zh-cn/application-dev/faqs/faqs-event-notification.md @huipeizi @dong-qingran @shine_hk diff --git a/README_zh.md b/README_zh.md index f665ee65345cf05b811b4e62cc075cae285729e8..c3d7fbcb884c958589bedf68c41207ca48e0961d 100644 --- a/README_zh.md +++ b/README_zh.md @@ -18,6 +18,8 @@ - master:最新开发版本。 + - OpenHarmony 5.0.3 Release版本(API Level 15):点击[此处](zh-cn/release-notes/OpenHarmony-v5.0.3-release.md)了解版本详情。 + - OpenHarmony 5.0.2 Release版本(API Level 14):点击[此处](zh-cn/release-notes/OpenHarmony-v5.0.2-release.md)了解版本详情。 - OpenHarmony 5.0.1 Release版本(API Level 13):点击[此处](zh-cn/release-notes/OpenHarmony-v5.0.1-release.md)了解版本详情。 diff --git a/en/application-dev/ads-service/oaid-service-sys.md b/en/application-dev/ads-service/oaid-service-sys.md new file mode 100644 index 0000000000000000000000000000000000000000..9edd6cd418f17756010c772c5fb135b9f3c1d4c6 --- /dev/null +++ b/en/application-dev/ads-service/oaid-service-sys.md @@ -0,0 +1,78 @@ +# Resetting OAID Information (for System Applications Only) + +## When to Use + +The OAID changes in the following scenarios: +- A user restores the factory settings of the device. +- A system application configures its bundle name in the **etc/advertising/oaid/oaid_service_config.json** file in the device's system directory and calls the **resetOAID()** API to reset the OAID. Note that the bundle name should be appended to the array in the file and separated with others by commas (,). +The following describes how to configure a system application to reset the OAID. + +## Available APIs + +| API| Description| +| -------- | -------- | +| [resetOAID()](../../reference/apis-ads-kit/js-apis-oaid-sys.md#identifierresetoaid): void | Resets an OAID. This is a system API.| + + +## How to Develop + +1. In the **module.json5** file of the module, configure the [ohos.permission.APP_TRACKING_CONSENT](../../security/AccessToken/permissions-for-all-user.md#ohospermissionapp_tracking_consent) permission. The sample code is as follows: + ```ts + { + "module": { + "requestPermissions": [ + { + "name": "ohos.permission.APP_TRACKING_CONSENT", + "reason": "$string:reason", + "usedScene": { + "abilities": [ + "EntryFormAbility" + ], + "when": "inuse" + } + } + ] + } + } + ``` + + Request authorization from the user in a dialog box when the application is started. For details about how to obtain the context, see [Context](../../application-models/application-context-stage.md). The sample code is as follows: + ```ts + import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; + import { BusinessError } from '@ohos.base'; + import hilog from '@ohos.hilog'; + import common from '@ohos.app.ability.common'; + + function requestOAIDTrackingConsentPermissions(context: common.Context): void { + // Display a dialog box when the page is displayed to request the user to grant the ad tracking permission. + const atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); + try { + atManager.requestPermissionsFromUser(context, ["ohos.permission.APP_TRACKING_CONSENT"]).then((data) => { + if (data.authResults[0] == 0) { + hilog.info(0x0000, 'testTag', '%{public}s', 'request permission success'); + } else { + hilog.error(0x0000, 'testTag', '%{public}s', 'user rejected'); + } + }).catch((err: BusinessError) => { + hilog.error(0x0000, 'testTag', '%{public}s', `request permission failed, error: ${err.code} ${err.message}`); + }) + } catch (err) { + hilog.error(0x0000, 'testTag', '%{public}s', `catch err->${err.code}, ${err.message}`); + } + } + ``` + +2. Call **resetOAID()** (a system API) to reset the OAID. The sample code is as follows: + ```ts + import identifier from '@ohos.identifier.oaid'; + import hilog from '@ohos.hilog'; + + // Reset the OAID. + try { + identifier.resetOAID(); + } catch (err) { + hilog.error(0x0000, 'testTag', '%{public}s', `reset oaid catch error: ${err.code} ${err.message}`); + } + ``` + + \ No newline at end of file diff --git a/en/application-dev/ai/mindspore/MindSpore-Lite-Kit-Introduction.md b/en/application-dev/ai/mindspore/MindSpore-Lite-Kit-Introduction.md index 7eeb9e99e01342c6e633c71f0d5b8efa194a0115..45619cbec184f2290f9de71fce306478c248ad12 100644 --- a/en/application-dev/ai/mindspore/MindSpore-Lite-Kit-Introduction.md +++ b/en/application-dev/ai/mindspore/MindSpore-Lite-Kit-Introduction.md @@ -10,6 +10,10 @@ So far, MindSpore Lite has been widely used in applications such as image classi - Target recognition: uses the preset object detection model to identify objects in the input frames of a camera, add labels to the objects, and mark them with bounding boxes. - Image segmentation: detects the positions of objects in a graph or the object of a specific pixel in the graph. +## Constraints + +- This kit can run and be debugged on real devices, but not on emulators. + ## Advantages MindSpore Lite provides AI model inference capabilities for hardware devices and end-to-end solutions for developers to empower intelligent applications in all scenarios. Its advantages include: @@ -48,6 +52,6 @@ MindSpore Lite is built in the OpenHarmony standard system as a system component ## Relationship with Other Kits -Neural Network Runtime (NNRt) functions as a bridge to connect the upper-layer AI inference framework and underlying acceleration chips, implementing cross-chip inference computing of AI models. +Neural Network Runtime (NNRt) functions as a bridge to connect the upper-layer AI inference framework and underlying acceleration chips, implementing cross-chip inference computing for AI models. -MindSpore Lite natively allows you to configure NNRt for AI-dedicated chips (such as NPUs) to accelerate inference. Therefore, you can configure MindSpore Lite to use the NNRt hardware. The focus of this topic is about how to develop AI applications using MindSpore Lite. For details about how to use NNRt, see [Connecting the Neural Network Runtime to an AI Inference Framework](../nnrt/neural-network-runtime-guidelines.md). +MindSpore Lite allows you to configure NNRt for AI-dedicated chips (such as NPUs) to accelerate inference. Therefore, you can configure MindSpore Lite to use the NNRt hardware. The focus of this topic is about how to develop AI applications using MindSpore Lite. For details about how to use NNRt, see [Connecting the Neural Network Runtime to an AI Inference Framework](../nnrt/neural-network-runtime-guidelines.md). diff --git a/en/application-dev/ai/mindspore/mindspore-guidelines-based-js.md b/en/application-dev/ai/mindspore/mindspore-guidelines-based-js.md index 1e845decb5adee8f45fccf576c153e7d188ea793..cf411b3176024c32c554306e2b6adce5fddb5ac5 100644 --- a/en/application-dev/ai/mindspore/mindspore-guidelines-based-js.md +++ b/en/application-dev/ai/mindspore/mindspore-guidelines-based-js.md @@ -221,8 +221,8 @@ let maxIndexArray: Array = []; // The buffer data of the input image is stored in float32View after preprocessing. For details, see Image Input and Preprocessing. let inputs: ArrayBuffer[] = [float32View.buffer]; -let resMgr: resourceManager.ResourceManager = getContext().getApplicationContext().resourceManager; -resMgr.getRawFileContent(modelName).then(modelBuffer => { +let resMgr = this.getUIContext()?.getHostContext()?.getApplicationContext().resourceManager; +resMgr?.getRawFileContent(modelName).then(modelBuffer => { // predict modelPredict(modelBuffer.buffer.slice(0), inputs).then(outputs => { console.info('=========MS_LITE_LOG: MS_LITE predict success====='); @@ -299,3 +299,4 @@ Touch the **photo** button on the device screen, select an image, and touch **OK + diff --git a/en/application-dev/ai/mindspore/mindspore-guidelines-based-native.md b/en/application-dev/ai/mindspore/mindspore-guidelines-based-native.md index c80f28ad4f87a7357c4d9e9746cfed340b5bc317..568f5bcff2b5078cbdf14257ff9b69f141d5f36c 100644 --- a/en/application-dev/ai/mindspore/mindspore-guidelines-based-native.md +++ b/en/application-dev/ai/mindspore/mindspore-guidelines-based-native.md @@ -413,7 +413,7 @@ In **entry/src/main/ets/pages/Index.ets**, call the encapsulated ArkTS module to import msliteNapi from 'libentry.so' import { resourceManager } from '@kit.LocalizationKit'; -let resMgr: resourceManager.ResourceManager = getContext().getApplicationContext().resourceManager; +let resMgr = this.getUIContext()?.getHostContext()?.getApplicationContext().resourceManager; let max: number = 0; let maxIndex: number = 0; let maxArray: Array = []; @@ -489,3 +489,4 @@ console.info('MS_LITE_LOG: *** Finished MSLite Demo ***'); Touch the **photo** button on the device screen, select an image, and touch **OK**. The top 4 categories of the image are displayed below the image. + diff --git a/en/application-dev/ai/mindspore/mindspore-lite-converter-guidelines.md b/en/application-dev/ai/mindspore/mindspore-lite-converter-guidelines.md index 48a4ba2634c72bb877fb84a801bc30a17c6f2191..932a2ad8044deab5b7a18dc264f6eaf2b987dbf6 100644 --- a/en/application-dev/ai/mindspore/mindspore-lite-converter-guidelines.md +++ b/en/application-dev/ai/mindspore/mindspore-lite-converter-guidelines.md @@ -42,13 +42,8 @@ You can obtain the MindSpore Lite model conversion tool in either of the followi - CMake >= 3.18.3 - Git >= 2.28.0 -2. Obtain the [MindSpore Lite source code](https://gitee.com/openharmony/third_party_mindspore). The source code is managed in "compressed package + patch" mode. Run the following commands to decompress the source code package and install the patch: - - ```bash - python3 build_helper.py --in_zip_path=./mindspore-v2.3.0.zip --patch_dir=./patches/ --out_src_path=./mindspore-src - ``` - - If the command execution is successful, the complete MindSpore Lite source code is generated in `mindspore-src/source/`. +2. Obtain the [MindSpore Lite source code](https://gitee.com/openharmony/third_party_mindspore). + The complete source code of MindSpore Lite is available at `mindspore-src/source/`. 3. Start building. diff --git a/en/application-dev/ai/mindspore/mindspore-lite-guidelines.md b/en/application-dev/ai/mindspore/mindspore-lite-guidelines.md index 90f7fca4f982a2850d1eace6f12408c68234cb1a..5dceba6d7ce1447eceaaa322144faad6c9f91d51 100644 --- a/en/application-dev/ai/mindspore/mindspore-lite-guidelines.md +++ b/en/application-dev/ai/mindspore/mindspore-lite-guidelines.md @@ -26,7 +26,7 @@ APIs involved in MindSpore Lite model inference are categorized into context API | ------------------ | ----------------- | |OH_AI_ContextHandle OH_AI_ContextCreate()|Creates a context object. This API must be used together with **OH_AI_ContextDestroy**.| |void OH_AI_ContextSetThreadNum(OH_AI_ContextHandle context, int32_t thread_num)|Sets the number of runtime threads.| -| void OH_AI_ContextSetThreadAffinityMode(OH_AI_ContextHandle context, int mode)|Sets the affinity mode for binding runtime threads to CPU cores, which are classified into large, medium, and small cores based on the CPU frequency. You only need to bind the large or medium cores, but not small cores. +|void OH_AI_ContextSetThreadAffinityMode(OH_AI_ContextHandle context, int mode)|Sets the affinity mode for binding runtime threads to CPU cores, which are classified into large, medium, and small cores based on the CPU frequency. You only need to bind the large or medium cores, but not small cores.| |OH_AI_DeviceInfoHandle OH_AI_DeviceInfoCreate(OH_AI_DeviceType device_type)|Creates a runtime device information object.| |void OH_AI_ContextDestroy(OH_AI_ContextHandle *context)|Destroys a context object.| |void OH_AI_DeviceInfoSetEnableFP16(OH_AI_DeviceInfoHandle device_info, bool is_fp16)|Sets whether to enable float16 inference. This function is available only for CPU and GPU devices.| @@ -90,7 +90,7 @@ The development process consists of the following main steps: The required model can be downloaded directly or obtained using the model conversion tool. - If the downloaded model is in the `.ms` format, you can use it directly for inference. The following uses the **mobilenetv2.ms** model as an example. - - If the downloaded model uses a third-party framework, such as TensorFlow, TensorFlow Lite, Caffe, or ONNX, you can use the [model conversion tool](https://www.mindspore.cn/lite/docs/en/master/use/downloads.html#1-8-1) to convert it to the `.ms` format. + - If the downloaded model uses a third-party framework, such as TensorFlow, TensorFlow Lite, Caffe, or ONNX, you can use the [model conversion tool](https://www.mindspore.cn/lite/docs/en/master/use/downloads.html#2-3-0) to convert it to the `.ms` format. 2. Create a context, and set parameters such as the number of runtime threads and device type. @@ -269,8 +269,10 @@ The development process consists of the following main steps: dl ) ``` - - To use ohos-sdk for cross compilation, you need to set the native toolchain path for the CMake tool as follows: `-DCMAKE_TOOLCHAIN_FILE="/xxx/native/build/cmake/ohos.toolchain.cmake"`. - + - To use ohos-sdk for cross compilation, you need to set the toolchain path for the CMake tool as follows: `-DCMAKE_TOOLCHAIN_FILE="/{sdkPath}/native/build/cmake/ohos.toolchain.cmake"`. + + Where, **sdkPath** indicates the SDK path in the DevEco Studio installation directory. To obtain the SDK path, go to the project page on DevEco Studio, choose **File** > **Settings...** > **OpenHarmony SDK**, and view the information in **Location**. + - The toolchain builds a 64-bit application by default. To build a 32-bit application, add the following configuration: `-DOHOS_ARCH="armeabi-v7a"`. 2. Run the CMake tool. @@ -290,4 +292,3 @@ The development process consists of the following main steps: output data is: 0.000018 0.000012 0.000026 0.000194 0.000156 0.001501 0.000240 0.000825 0.000016 0.000006 0.000007 0.000004 0.000004 0.000004 0.000015 0.000099 0.000011 0.000013 0.000005 0.000023 0.000004 0.000008 0.000003 0.000003 0.000008 0.000014 0.000012 0.000006 0.000019 0.000006 0.000018 0.000024 0.000010 0.000002 0.000028 0.000372 0.000010 0.000017 0.000008 0.000004 0.000007 0.000010 0.000007 0.000012 0.000005 0.000015 0.000007 0.000040 0.000004 0.000085 0.000023 ``` - diff --git a/en/application-dev/application-models/Readme-EN.md b/en/application-dev/application-models/Readme-EN.md index 343ff872866a680e2342612104396d11fe338c57..dd31d63f79366a98a0e9af9ae451c92b1b65a67a 100644 --- a/en/application-dev/application-models/Readme-EN.md +++ b/en/application-dev/application-models/Readme-EN.md @@ -1,12 +1,12 @@ -# Ability Kit +# Ability Kit - [Introduction to Ability Kit](abilitykit-overview.md) - [Application Models](application-models.md) -- Stage Model Development +- Stage Model Development - [Stage Model Development Overview](stage-model-development-overview.md) - - Stage Model Application Components + - Stage Model Application Components - [Application- or Component-Level Configuration](application-component-configuration-stage.md) - - UIAbility Component + - UIAbility Component - [UIAbility Overview](uiability-overview.md) - [UIAbility Lifecycle](uiability-lifecycle.md) - [UIAbility Launch Type](uiability-launch-type.md) @@ -25,21 +25,22 @@ - [EmbeddedUIExtensionAbility](embeddeduiextensionability.md) - [AbilityStage Component Container](abilitystage.md) - [Context](application-context-stage.md) - - Want + - Want - [Want Overview](want-overview.md) - [Matching Rules of Explicit Want and Implicit Want](explicit-implicit-want-mappings.md) - [Using Explicit Want to Start an Application Component](ability-startup-with-explicit-want.md) - [Common action and entities Values (Not Recommended)](actions-entities.md) - [Component Startup Rules (Stage Model)](component-startup-rules.md) - [AppStartup](app-startup.md) + - [Obtaining Reasons for Abnormal Application Exits](ability-exit-info-record.md) - - Inter-Device Application Component Interaction (Hopping) + - Inter-Device Application Component Interaction (Hopping) - [Hopping Overview](inter-device-interaction-hop-overview.md) - [Cross-Device Migration](hop-cross-device-migration.md) - [Multi-device Collaboration](hop-multi-device-collaboration.md) - [Subscribing to System Environment Variable Changes](subscribe-system-environment-variable-changes.md) - - Inter-Application Redirection + - Inter-Application Redirection - [Overview of Application Redirection](link-between-apps-overview.md) - Starting a Specified Application - [Overview of Starting a Specified Application](app-startup-overview.md) @@ -64,18 +65,18 @@ - [Process Model (Stage Model)](process-model-stage.md) - [Thread Model (Stage Model)](thread-model-stage.md) - - Mission Management (for System Applications Only) + - Mission Management (for System Applications Only) - [Mission Management Scenarios](mission-management-overview.md) - [Mission Management and Launch Type](mission-management-launch-type.md) - [Page Stack and Mission List](page-mission-stack.md) - [Setting the Icon and Name of a Mission Snapshot](mission-set-icon-name-for-task-snapshot.md) - [Application Configuration File](config-file-stage.md) -- FA Model Development +- FA Model Development - [FA Model Development Overview](fa-model-development-overview.md) - - FA Model Application Components + - FA Model Application Components - [Application- or Component-Level Configuration](application-component-configuration-fa.md) - - PageAbility Component Development + - PageAbility Component Development - [PageAbility Overview](pageability-overview.md) - [PageAbility Configuration](pageability-configuration.md) - [PageAbility Lifecycle](pageability-lifecycle.md) @@ -83,19 +84,21 @@ - [Creating a PageAbility](create-pageability.md) - [Starting a Local PageAbility](start-local-pageability.md) - [Stopping a PageAbility](stop-pageability.md) + - [Starting a Remote PageAbility (for System Applications Only)](start-remote-pageability.md) + - [Starting a Specified Page](start-page.md) - [Window Properties](window-properties.md) - [Requesting Permissions](request-permissions.md) - [Redirection Rules](redirection-rules.md) - - ServiceAbility Component Development + - ServiceAbility Component Development - [ServiceAbility Overview](serviceability-overview.md) - [ServiceAbility Configuration](serviceability-configuration.md) - [ServiceAbility Lifecycle](serviceability-lifecycle.md) - [Creating a ServiceAbility](create-serviceability.md) - [Starting a ServiceAbility](start-serviceability.md) - [Connecting to a ServiceAbility](connect-serviceability.md) - - DataAbility Component Development + - DataAbility Component Development - [DataAbility Overview](dataability-overview.md) - [DataAbility Configuration](dataability-configuration.md) - [DataAbility Lifecycle](dataability-lifecycle.md) @@ -113,25 +116,25 @@ - [Application Configuration File](config-file-fa.md) -- Development of Component Interaction Between the FA Model and Stage Model +- Development of Component Interaction Between the FA Model and Stage Model - [Component Interaction Between the FA Model and Stage Model](fa-stage-interaction-overview.md) - [Starting a UIAbility from the FA Model](start-uiability-from-fa.md) - [Connecting to a ServiceExtensionAbility from the FA Model](bind-serviceextensionability-from-fa.md) - [Accessing a DataShareExtensionAbility from the FA Model](access-datashareextensionability-from-fa.md) - [Starting a PageAbility from the Stage Model](start-pageability-from-stage.md) - [Connecting to a ServiceAbility from the Stage Model](bind-serviceability-from-stage.md) -- Switching from the FA Model to the Stage Model +- Switching from the FA Model to the Stage Model - [Model Switching Overview](model-switch-overview.md) - - Configuration File Switching + - Configuration File Switching - [Differences in Configuration Files](configuration-file-diff.md) - [Switching of app and deviceConfig](app-deviceconfig-switch.md) - [Switching of module](module-switch.md) - - Component Switching + - Component Switching - [PageAbility Switching](pageability-switch.md) - [ServiceAbility Switching](serviceability-switch.md) - [DataAbility Switching](dataability-switch.md) - [Widget Switching](widget-switch.md) - - API Switching + - API Switching - [API Switching Overview](api-switch-overview.md) - [Context Switching](context-switch.md) - [featureAbility Switching](featureability-switch.md) diff --git a/en/application-dev/application-models/ability-exit-info-record.md b/en/application-dev/application-models/ability-exit-info-record.md new file mode 100644 index 0000000000000000000000000000000000000000..5de391f65940ab4178dc2fe2c1da7dcb758e859c --- /dev/null +++ b/en/application-dev/application-models/ability-exit-info-record.md @@ -0,0 +1,93 @@ +# Obtaining Reasons for Abnormal Application Exits + +If an application crashes and then restarts, you often need to know why it crashed and what the state was, such as the RSS and PSS values of the application memory and the time of the last exit. You can obtain the information from the **launchParam** parameter in the **OnCreate** lifecycle function of the UIAbility and UIExtensionAbility. You can use the information to analyze and improve the application experience, adjust service logic, and boost the application stability. + +## Constraints + +Only the [UIAbility](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md) and [UIExtensionAbility](../reference/apis-ability-kit/js-apis-app-ability-uiExtensionAbility.md) support the obtaining of the last exit reason. + +## Available APIs + +Read [API](../reference/apis-ability-kit/js-apis-app-ability-abilityConstant.md#launchparam) for the API reference. + +| **API** | **Description**| +| -------- | -------- | +| [LaunchParam](../reference/apis-ability-kit/js-apis-app-ability-abilityConstant.md#launchparam) | Parameters for starting an ability. The **lastExitReason**, **lastExitMessage**, and **lastExitDetailInfo** fields record the information about the last abnormal exit of the ability. | +| [LastExitDetailInfo](../reference/apis-ability-kit/js-apis-app-ability-abilityConstant.md#lastexitdetailinfo18) | Detailed information about the last exit.| + +## How to Develop + +1. Obtain the reason for the last exit. + + Read the last exit information of the ability from **launchParam** of the **OnCreate** lifecycle function of the UIAbility class. + + ```ts + import { UIAbility, Want, AbilityConstant } from '@kit.AbilityKit'; + + const MAX_RSS_THRESHOLD: number = 100000; + const MAX_PSS_THRESHOLD: number = 100000; + + function doSomething() { + console.log('do Something'); + } + + function doAnotherThing() { + console.log('do Another Thing'); + } + + class MyAbility extends UIAbility { + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { + // Obtain the exit reason. + let reason: number = launchParam.lastExitReason; + let subReason: number = -1; + if (launchParam.lastExitDetailInfo) { + subReason = launchParam.lastExitDetailInfo.exitSubReason; + } + let exitMsg: string = launchParam.lastExitMessage; + + if (launchParam.lastExitDetailInfo) { + // Obtain the information about the process where the ability was running before it exited. + let pid = launchParam.lastExitDetailInfo.pid; + let processName: string = launchParam.lastExitDetailInfo.processName; + let rss: number = launchParam.lastExitDetailInfo.rss; + let pss: number = launchParam.lastExitDetailInfo.pss; + // Obtain other information. + let uid: number = launchParam.lastExitDetailInfo.uid; + let timestamp: number = launchParam.lastExitDetailInfo.timestamp; + } + } + } + ``` + +2. Perform service processing based on the last exit information. + + - You can add different processing logic for different exit reasons. The following provides an example. + + ```ts + if (reason === AbilityConstant.LastExitReason.APP_FREEZE) { + // The ability exited last time due to no response. Add processing logic here. + doSomething(); + } else if (reason === AbilityConstant.LastExitReason.SIGNAL && subReason === 9) { + // The ability exited last time because the process is terminated by the kill -9 signal. Add processing logic here. + doAnotherThing(); + } else if (reason === AbilityConstant.LastExitReason.RESOURCE_CONTROL) { + // The ability exited last time due to RSS control last time. Implement the processing logic here. The simplest approach is to print the information. + console.log('The ability has exit last because the rss control, the lastExitReason is '+ reason + + ', subReason is ' + subReason + ', lastExitMessage is ' + exitMsg); + } + ``` + + - Detect abnormal application memory usage based on process information. The following provides an example. + + ```ts + if (rss > MAX_RSS_THRESHOLD || pss > MAX_PSS_THRESHOLD) { + // If the RSS or PSS value is too high, the memory usage is close to or has reached the upper limit. Print a warning or add processing logic. + console.warn('Process ' + processName + '(' + pid + ') memory usage approaches or reaches the upper limit.'); + } + ``` + + - Use the timestamp of the abnormal exit to pinpoint when the issue occurred, facilitating problem locating. + + ```ts + console.log('App ' + uid + ' terminated at ' + timestamp); + ``` diff --git a/en/application-dev/application-models/abilitykit-overview.md b/en/application-dev/application-models/abilitykit-overview.md index 8120ea09b753b78cc4e45e8f46fbb79468dd3114..83e914995ae66ce8687d4bc6e41f348c7cd4d8ad 100644 --- a/en/application-dev/application-models/abilitykit-overview.md +++ b/en/application-dev/application-models/abilitykit-overview.md @@ -27,7 +27,7 @@ Ability Kit provides an application model for application development and runnin - The object-oriented development mode makes the code of complex applications easy to read, maintain, and scale. - Modular development is supported. -2. **Native support for cross-device migration and multi-device collaboration at the application component level** +2. **Support for cross-device migration and multi-device collaboration at the application component level** The stage model decouples application components from User Interfaces (UIs). - The declarative feature of ArkUI allows the UI to be restored based on the data or status saved in application components, which facilitates cross-device migration. diff --git a/en/application-dev/application-models/abilitystage.md b/en/application-dev/application-models/abilitystage.md index bef10b4cfe7fdc769ad94e70dae50550cfceddae..8339d1a9ae24a66e5247b32cb4d64eff344feea5 100644 --- a/en/application-dev/application-models/abilitystage.md +++ b/en/application-dev/application-models/abilitystage.md @@ -1,7 +1,7 @@ # AbilityStage Component Container -[AbilityStage](../reference/apis-ability-kit/js-apis-app-ability-abilityStage.md) is a component container at the [module](../quick-start/application-package-structure-stage.md) level. When the [HAP](../quick-start/hap-package.md) of an application is loaded for the first time, an AbilityStage instance is created. You can perform operations such as initialization on the instance. +[AbilityStage](../reference/apis-ability-kit/js-apis-app-ability-abilityStage.md) is a component container at the [module](../quick-start/application-package-overview.md#multi-module design mechanism) level. When the [HAP](../quick-start/hap-package.md) of an application is loaded for the first time, an AbilityStage instance is created. You can perform operations such as initialization on the instance. An AbilityStage instance corresponds to a module. diff --git a/en/application-dev/application-models/access-datashareextensionability-from-fa.md b/en/application-dev/application-models/access-datashareextensionability-from-fa.md index 1c968aed1561bcf4bf9f746ce73f5b342a7e4326..47e5b62209a6c2ec8bd8cabe2326b51b89c00c25 100644 --- a/en/application-dev/application-models/access-datashareextensionability-from-fa.md +++ b/en/application-dev/application-models/access-datashareextensionability-from-fa.md @@ -5,9 +5,9 @@ Regardless of the FA model or stage model, the data read/write function consists of the client and server. -- In the FA model, the client uses the **DataAbilityHelper** class to provide external APIs, and the server uses the **DataAbility** class to provide database read and write services. +- In the FA model, the client uses [DataAbilityHelper](../reference/apis-ability-kit/js-apis-inner-ability-dataAbilityHelper.md) to provide external APIs, and the server uses [DataAbility](dataability-overview.md) to provide database read and write services. -- In the stage model, the client uses the **DataShareHelper** class to provide external APIs, and the server uses the **DataShareExtensionAbility** class to provide database read and write services. +- In the stage model, the client uses [DataShareHelper](../reference/apis-arkdata/js-apis-data-dataShare-sys.md#datasharehelper) to provide external APIs, and the server uses [DataShareExtensionAbility](../reference/apis-arkdata/js-apis-application-dataShareExtensionAbility-sys.md) to provide database read and write services If the client uses the FA model whereas the server is upgraded to the stage model, the client cannot access the server. @@ -31,7 +31,7 @@ Instead of manual modification, the system adopts the following processing: ![FAvsStage-uri](figures/FAvsStage-uri.png) -3. The **DataShareHelper** class implements only certain APIs of **DataAbilityHelper**. For details about the APIs, see the table below. +2. The **DataShareHelper** class implements only certain APIs of **DataAbilityHelper**. For details about the APIs, see the table below. **Table 1** API compatibility when the FA model accesses a DataShareExtensionAbility of the stage model diff --git a/en/application-dev/application-models/actions-entities.md b/en/application-dev/application-models/actions-entities.md index a17749fbc3d9ae43572daa8b7d672e77f20d5536..dbfb2ab7f889cf8bd4fc3e5c232f70a21726fb42 100644 --- a/en/application-dev/application-models/actions-entities.md +++ b/en/application-dev/application-models/actions-entities.md @@ -4,9 +4,9 @@ > > Due to the generalized use of the fields **action** and **entities**, the system lacks control over the behavior of applications declaring **action** and **entities**. This loophole allows malicious applications to make false declarations, hijacking traffic and rendering post-redirection features inoperative. As such, the system intends to deprecate unnecessary **action** and **entities**. You are advised to [start an application of the specified type](./start-intent-panel.md). -The **action** field specifies the common operation (such as viewing, sharing, and application details) to be performed by the caller. In implicit [Want](../reference/apis-ability-kit/js-apis-app-ability-want.md), you can define this field and use it together with **uri** or **parameters** to specify the operation to be performed on the data, for example, viewing URI data. For example, if the URI is a website and the action is **ACTION_VIEW_DATA**, the application component that supports access to the website is matched. Declaring the **action** field in Want indicates that the invoked application should support the declared operation. The **actions** field under **skills** in the configuration file indicates the operations supported by the application. +The **action** field specifies the common operation (such as viewing, sharing, and application details) to be performed by the caller. In implicit [Want](../reference/apis-ability-kit/js-apis-app-ability-want.md), you can define this field and use it together with **uri** or **parameters** to specify the operation to be performed on the data, for example, viewing URI data. For example, if the URI is a website and the action is **ACTION_VIEW_DATA**, the application component that supports access to the website is matched. Declaring the **action** field in Want indicates that the invoked application should support the declared operation. The **actions** field under [skills](../quick-start/module-configuration-file.md#skills) in the configuration file indicates the operations supported by the application. Common **actions** values are as follows. For details, see [action](../reference/apis-ability-kit/js-apis-ability-wantConstant.md#action). -The following **action** values are available: +**Common action values** - **ACTION_HOME**: action of starting the application entry component. It must be used together with **ENTITY_HOME**. The application icon on the home screen is an explicit entry component. Users can touch the icon to start the entry component. Multiple entry components can be configured for an application. @@ -17,9 +17,9 @@ The following **action** values are available: - **ACTION_VIEW_MULTIPLE_DATA**: action of launching the UI for sending multiple data records. -The **entities** field specifies the additional category information (such as browser and video player) of the target component. It is a supplement to action in implicit [Want](../reference/apis-ability-kit/js-apis-app-ability-want.md). You can define this field to filter application categories, for example, browser. Declaring the **entities** field in Want indicates that the invoked application should belong to the declared category. The **entities** field under **skills** in the configuration file indicates the categories supported by the application. +The **entities** field specifies the additional category information (such as browser and video player) of the target component. It is a supplement to action in implicit [Want](../reference/apis-ability-kit/js-apis-app-ability-want.md). You can define this field to filter application categories, for example, browser. Declaring the **entities** field in Want indicates that the invoked application should belong to the declared category. The **entities** field under [skills](../quick-start/module-configuration-file.md#skills) in the configuration file indicates the categories supported by the application. Common **entities** values are as follows. For details, see [entity](../reference/apis-ability-kit/js-apis-ability-wantConstant.md#entity). -The following **entities** values are available: +**Common entities values** - **ENTITY_DEFAULT**: default category, which is meaningless. diff --git a/en/application-dev/application-models/app-linking-startup.md b/en/application-dev/application-models/app-linking-startup.md index 1717e2391f709bd3c946ec0727e7faf8ac505383..1e3b4d83667dabec99f184dbc97038d12ac5808a 100644 --- a/en/application-dev/application-models/app-linking-startup.md +++ b/en/application-dev/application-models/app-linking-startup.md @@ -36,6 +36,11 @@ Configure the [module.json5 file](../quick-start/module-configuration-file.md) o * The **uris** field must contain an element whose **scheme** is **https** and **host** is a domain name address. * **domainVerify** must be set to **true**. +> **NOTE** +> +> By default, the **skills** field contains a **skill** object, which is used to identify the application entry. Application redirection links should not be configured in this object. Instead, separate **skill** objects should be used. If there are multiple redirection scenarios, create different **skill** objects under **skills**. Otherwise, the configuration does not take effect. + + For example, the configuration below declares that the application is associated with the domain name www.example.com. ```json @@ -46,6 +51,14 @@ For example, the configuration below declares that the application is associated { // ... "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + }, { "entities": [ // entities must contain "entity.system.browsable". @@ -67,7 +80,7 @@ For example, the configuration below declares that the application is associated ], // domainVerify must be set to true. "domainVerify": true - } + } // Add a skill object for redirection. If there are multiple redirection scenarios, create multiple skill objects. ] } ] diff --git a/en/application-dev/application-models/app-startup.md b/en/application-dev/application-models/app-startup.md index ac5de1341af1e25a15016f935ed4db70c272cff5..398314434aa388fe10f2acf54d062169eca2330d 100644 --- a/en/application-dev/application-models/app-startup.md +++ b/en/application-dev/application-models/app-startup.md @@ -3,25 +3,38 @@ ## Overview -During application initialization, a series of startup tasks are triggered. If these tasks are concentratedly placed within the [onCreate](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityoncreate) lifecycle of the [UIAbility](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md) of the application's main module ([module](../quick-start/application-package-overview.md#module-types) of the entry type), they must be executed sequentially on the main thread, which significantly affects the application launch speed. In addition, when there are too many tasks, complex dependencies between them make the code difficult to maintain. +During application launch, a series of startup tasks are often required. If all these tasks are placed within the [onCreate](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityoncreate) lifecycle of the [UIAbility](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md) in the application's main module ([module](../quick-start/application-package-overview.md#module-types) of the entry type), they can only be executed sequentially on the main thread, which significantly affects the application launch speed. In addition, when there are too many tasks, complex dependencies between them make the code difficult to maintain. -AppStartup offers an efficient approach to application initialization. By enabling the asynchronous initiation of startup tasks, it ensures a smoother startup process. The centralized configuration of task execution order and interdependencies in a single file simplifies and clarifies the startup codebase, enhancing maintainability. +AppStartup offers an efficient approach to application launch. By supporting asynchronous initiation of startup tasks, it ensures a smoother startup process. The centralized configuration of execution order and dependencies of multiple startup tasks in a single file simplifies and clarifies the startup codebase, enhancing maintainability. -AppStartup supports startup tasks in automatic or manual mode. By default, the automatic mode is used. During the creation of an [AbilityStage](../reference/apis-ability-kit/js-apis-app-ability-abilityStage.md), the configured startup tasks are loaded and executed in automatic mode. You can also call [startupManager.run](../reference/apis-ability-kit/js-apis-app-appstartup-startupManager.md#startupmanagerrun) to execute the startup tasks in manual mode after a UIAbility is created. +## Working Mechanism + +AppStartup supports startup tasks in automatic or manual mode. By default, automatic mode is used. During the creation of an [AbilityStage](../reference/apis-ability-kit/js-apis-app-ability-abilityStage.md), the configured startup tasks are loaded and executed in automatic mode. You can also call [startupManager.run](../reference/apis-ability-kit/js-apis-app-appstartup-startupManager.md#startupmanagerrun) to execute the startup tasks in manual mode after an AbilityStage is created. **Figure 1** Startup procedure ![app-startup-procedure](figures/app-startup-procedure.png) + +## Supported Scope + +- AppStartup is only triggered when the entry UIAbility is launched. It is not triggered when ExtensionAbility or non-entry UIAbility are launched. + +- Starting from API version 18, AppStartup supports configuring startup tasks in [HSP](../quick-start/har-package.md) and [HAR](../quick-start/in-app-hsp.md) modules. However, startup tasks and .so file preloading tasks in the HSP and HAR modules cannot be explicitly set to automatic mode. They can be initiated by startup tasks and .so file preloading tasks of the entry module that are in automatic mode. + +- Starting from API version 18, AppStartup supports the configuration of .so file preloading tasks. For details about how to develop .so files, refer to [Node-API](../napi/use-napi-process.md) to create a native C++ project. + + ## Constraints -- AppStartup can be used only in the UIAbility of an entry [module](../quick-start/application-package-overview.md#module-types). +- AppStartup must be enabled in the [module.json5 file](../quick-start/module-configuration-file.md) of the entry-type [module](../quick-start/application-package-overview.md#module-types) before being used. + +- Circular dependencies between startup tasks or .so file preloading tasks are not allowed. -- Circular dependencies are not allowed between startup tasks. ## Development Process -1. [Defining an AppStartup Configuration File](#defining-an-appstartup-configuration-file): Create an AppStartup configuration file in the resource file directory, add the configuration about startup tasks, and reference the configuration file in [module.json5](../quick-start/module-configuration-file.md). +1. [Defining an AppStartup Configuration File](#defining-an-appstartup-configuration-file): Create an AppStartup configuration file in the resource file directory, add the configuration about startup tasks, and reference this configuration file in [module.json5](../quick-start/module-configuration-file.md). 2. [Setting Startup Parameters](#setting-startup-parameters): In the startup parameter file, set parameters such as the timeout interval and startup task listener. 3. [Adding a Startup Task for Each Component to Be Initialized](#adding-a-startup-task-for-each-component-to-be-initialized): Implement the [StartupTask](../reference/apis-ability-kit/js-apis-app-appstartup-startupTask.md) interface. @@ -29,24 +42,25 @@ AppStartup supports startup tasks in automatic or manual mode. By default, the a ### Defining an AppStartup Configuration File -1. Create a AppStartup configuration file in the **resources/base/profile** directory of the application's main module ([module](../quick-start/application-package-overview.md#module-types) of the entry type). The file name can be customized. The following uses **startup_config.json** as an example. +1. Create an AppStartup configuration file in the **resources/base/profile** directory of the application's main module ([module](../quick-start/application-package-overview.md#module-types) of the entry type). The file name can be customized. The following uses **startup_config.json** as an example. -2. In the **startup_config.json** file, add the configuration for each startup task in sequence. +2. In the **startup_config.json** file, add the configuration for each startup task and .so file preloading task in sequence. - It is assumed that the application has six startup tasks. The dependencies between the tasks are shown in the figure below. To facilitate concurrent execution of startup tasks, a startup task file should contain only one startup task. In this example, each startup task corresponds to a startup task file. + It is assumed that the application has six startup tasks and six .so file preloading tasks. The dependencies between the tasks are shown in the figure below. To facilitate concurrent execution of startup tasks, a startup task file should contain only one startup task. In this example, each startup task corresponds to a startup task file. You are not advised to run code logic in the loading callback of .so files, as prolonged .so file loading can adversely affect the main thread's operation. - **Figure 2** Dependencies between startup tasks + **Figure 2** Dependencies between the startup tasks and .so file preloading tasks ![app-startup](figures/app-startup.png) 1. In the **ets/startup** directory, create six startup task files and a common startup parameter file. The file names must be unique. 1. Create six startup task files. In this example, the six files are named from **StartupTask_001.ets** to **StartupTask_006.ets**. - 2. Create a startup parameter file. In this example, the file name is **StartupConfig.ets**. + 2. Create.so files by referring to [Node-API](../napi/use-napi-process.md). In this example, the six files are named from **libentry_001.so** to **libentry_006.so**. + 3. Create a startup parameter file. In this example, the file name is **StartupConfig.ets**. 2. Add the information about the startup task files and startup parameter file to the **startup_config.json** file. - The following is an example of the **startup_config.json** file: + The following is an example of the **startup_config.json** file of the application's main module: ```json { @@ -65,6 +79,7 @@ AppStartup supports startup tasks in automatic or manual mode. By default, the a "name": "StartupTask_002", "srcEntry": "./ets/startup/StartupTask_002.ets", "dependencies": [ + "StartupTask_003", "StartupTask_004" ], "runOnThread": "taskPool", @@ -103,28 +118,88 @@ AppStartup supports startup tasks in automatic or manual mode. By default, the a "excludeFromAutoStart": true } ], + "appPreloadHintStartupTasks": [ + { + "name": "libentry_001", + "srcEntry": "libentry_001.so", + "dependencies": [ + "libentry_002", + "libentry_003" + ], + "runOnThread": "taskPool" + }, + { + "name": "libentry_002", + "srcEntry": "libentry_002.so", + "dependencies": [ + "libentry_003", + "libentry_004" + ], + "runOnThread": "taskPool" + }, + { + "name": "libentry_003", + "srcEntry": "libentry_003.so", + "dependencies": [ + "libentry_004" + ], + "runOnThread": "taskPool" + }, + { + "name": "libentry_004", + "srcEntry": "libentry_004.so", + "runOnThread": "taskPool" + }, + { + "name": "libentry_005", + "srcEntry": "libentry_005.so", + "dependencies": [ + "libentry_006" + ], + "runOnThread": "taskPool", + "excludeFromAutoStart": true + }, + { + "name": "libentry_006", + "srcEntry": "libentry_006.so", + "runOnThread": "taskPool", + "excludeFromAutoStart": true + } + ], "configEntry": "./ets/startup/StartupConfig.ets" } ``` + **Table 1** Fields in the startup_config.json file - | Field| Description| Data Type| Default Value Allowed| + | Field| Description| Data Type| Optional| | -------- | -------- | -------- | -------- | - | startupTasks | Configuration about the startup tasks. For details, see the following table.| Object array| No| - | configEntry | Path of the startup parameter file.| String| No| + | startupTasks | Configuration about the startup tasks. For details, see the following table.| Object array| Optional, defaults to an empty array| + | appPreloadHintStartupTasks | Configuration about the .so file preloading tasks. For details, see the following table.| Object array| Optional, defaults to an empty array| + | configEntry | Path of the startup parameter file.
**NOTE**
Do not configure this field for the HSP and HAR.| String| Mandatory| **Table 2** Description of startupTasks - | Field| Description| Data Type| Default Value Allowed| + | Field| Description| Data Type| Optional| + | -------- | -------- | -------- | -------- | + | name | Name of the startup task, which can be customized. It is recommended that the name be the same as the class name.| String| Mandatory| + | srcEntry | Path of the file corresponding to the startup task.| String| Mandatory| + | dependencies | Array holding the class names of other startup tasks on which this task depends.| Object array| Optional, defaults to an empty array| + | excludeFromAutoStart | Whether to exclude automatic mode. For details, see [Changing the Startup Mode](#optional-changing-the-startup-mode).
- **true**: manual mode.
- **false**: automatic mode.
**NOTE**
This field must be set to **true** for the HSP and HAR.| Boolean| Optional, defaults to **false**| + | runOnThread | Thread where the startup task is executed.
- **mainThread**: executed in the main thread.
- **taskPool**: executed in an asynchronous thread.| String| Optional, defaults to **mainThread**| + | waitOnMainThread | Whether the main thread needs to wait until the startup task finishes execution. This parameter is valid only when **runOnThread** is set to **taskPool**.
- **true**: The main thread loads the application home page only the startup task finishes execution.
- **false**: The main thread does not wait for the startup task to finish execution.| Boolean| Optional, defaults to **true**| + + **Table 3** appPreloadHintStartupTasks + + | Field| Description| Data Type| Optional| | -------- | -------- | -------- | -------- | - | name | Class name of the startup task.| String| No| - | srcEntry | Path of the file corresponding to the startup task.| String| No| - | dependencies | Array holding the class names of other startup tasks on which the startup task depends.| Object array| Yes (initial value: left empty)| - | excludeFromAutoStart | Whether to exclude the automatic mode. For details, see [Changing the Startup Mode](#optional-changing-the-startup-mode).
- **true**: manual mode.
- **false**: automatic mode.| Boolean| Yes (initial value: **false**)| - | runOnThread | Thread where the startup task is executed.
- **mainThread**: executed in the main thread.
- **taskPool**: executed in an asynchronous thread.| String| Yes (initial value: **mainThread**)| - | waitOnMainThread | Whether the main thread needs to wait until the startup task finishes execution. This parameter is valid only when **runOnThread** is set to **taskPool**.
- **true**: The main thread loads the application home page only the startup task finishes execution.
- **false**: The main thread does not wait for the startup task to finish execution.| Boolean| Yes (initial value: **true**)| + | name | Name of the .so file to preload.| String| Mandatory| + | srcEntry | File name of the .so file, including the extension.| String| Mandatory| + | dependencies | Array holding the .so file names of other preloading tasks on which this task depends.| Object array| Optional, defaults to an empty array| + | excludeFromAutoStart | Whether to exclude automatic mode. For details, see [Changing the Startup Mode](#optional-changing-the-startup-mode).
- **true**: manual mode.
- **false**: automatic mode.
**NOTE**
This field must be set to **true** for the HSP and HAR.| Boolean| Optional, defaults to **false**| + | runOnThread | Thread where preloading is performed.
- **taskPool**: executed in an asynchronous thread.
**NOTE**
Preloading of .so files can be executed only in TaskPool threads.| String| Mandatory| 3. Add the index of the AppStartup configuration file to the **appStartup** tag in the [module.json5 file](../quick-start/module-configuration-file.md). @@ -214,12 +289,109 @@ export default class StartupTask_001 extends StartupTask { } ``` + ### (Optional) Using AppStartup in the HSP and HAR + + Large applications often consist of multiple [HSP](../quick-start/har-package.md) and [HAR](../quick-start/in-app-hsp.md) modules. This section provides an example to demonstrate how to use AppStartup in HSP and HAR packages. This example application includes two HSP packages (hsp1, hsp2) and one HAR package (har1), with startup tasks and .so file preloading tasks. + + Perform the following steps: + + 1. Create an AppStartup configuration file under the **resources/base/profile** directory for each HSP and HAR, in addition to the main module. Different modules can use the same file name. The following uses **startup_config.json** as an example. + + 2. Configure the **startup_config.json** file for each module. + + The table below lists the startup tasks and .so file preloading tasks available for the application. + + **Table 4** Startup tasks and .so file preloading tasks + | Module| Startup Task| Preloading Task| + | ------- | -------------------------------- | -------------------------------- | + | entry | HAP_Task_01 | libentry_01 | + | hsp1 | HSP1_Task_01
HSP1_Task_02 | libhsp1_01
libhsp1_02 | + | hsp2 | HSP2_Task_01 | libhsp2_01 | + | har | HAR1_Task_01 | libhar1_01 | + + **Figure 3** Dependencies between the startup tasks and .so file preloading tasks + + ![app-startup](figures/hsp-har-startup.png) + + For details about the **startup_config.json** file of the entry module, see [Defining an AppStartup Configuration File](#defining-an-appstartup-configuration-file). For the HSP and HAR, do not configure the **configEntry** field in the **startup_config.json** file. The following uses the configuration file of **hsp1** as an example: + + ```json + { + "startupTasks": [ + { + "name": "HSP1_Task_01", + "srcEntry": "./ets/startup/HSP1_Task_01.ets", + "dependencies": [ + "HSP1_Task_02", + "HAR1_Task_01" + ], + "runOnThread": "taskPool", + "waitOnMainThread": false, + "excludeFromAutoStart": true + } + ], + "appPreloadHintStartupTasks": [ + { + "name": "libhsp1_01", + "srcEntry": "libhsp1_01.so", + "dependencies": [ + "libhsp1_02", + "libhar1_01" + ], + "runOnThread": "taskPool", + "excludeFromAutoStart": true + } + ] + } + ``` + + 3. Add the index of the AppStartup configuration file to the **appStartup** tag in the [module.json5 file](../quick-start/module-configuration-file.md) of each module. + + The following are examples of **module.json5** for **hsp1**, **hsp2**, and **har1**: + + ```json + { + "module": { + "name": "hsp1", + "type": "shared", + // ... + "appStartup": "$profile:startup_config," // AppStartup configuration file + // ... + } + } + ``` + ```json + { + "module": { + "name": "hsp2", + "type": "shared", + // ... + "appStartup": "$profile:startup_config," // AppStartup configuration file + // ... + } + } + ``` + ```json + { + "module": { + "name": "har1", + "type": "har", + // ... + "appStartup": "$profile:startup_config," // AppStartup configuration file + // ... + } + } + ``` + + For details about other steps, see [Setting Startup Parameters](#setting-startup-parameters) and [Adding a Startup Task for Each Component to Be Initialized](#adding-a-startup-task-for-each-component-to-be-initialized). + + ### (Optional) Changing the Startup Mode -AppStartup provides automatic and manual mode. By default, the automatic mode is used. However, you can change the mode to manual as required. +AppStartup provides two modes for executing startup tasks: automatic and manual. The entry module defaults to automatic mode, but you can change it to manual mode if needed. The HSP and HAR support the configuration of manual mode only. -- Automatic mode: After an AbilityStage is created, the startup task is automatically executed. -- Manual mode: After a UIAbility is created, you need to manually call the API to execute the startup task. Modules that are infrequently used do not need to be initialized when the application is started. You can change the startup mode of these modules to manual. After the application is started, you can call [startupManager.run](../reference/apis-ability-kit/js-apis-app-appstartup-startupManager.md#startupmanagerrun) to execute the startup task. +- Automatic mode: After an AbilityStage is created, startup tasks are automatically executed. +- Manual mode: After a UIAbility is created, you need to manually call the API to execute the startup tasks and .so file preloading tasks. Modules that are infrequently used do not need to be initialized when the application is launched. You can change the startup mode of these modules to manual. After the application finishes launching, you can call [startupManager.run](../reference/apis-ability-kit/js-apis-app-appstartup-startupManager.md#startupmanagerrun) to execute the startup tasks and .so file preloading tasks. The following uses the **onCreate** lifecycle of the UIAbility as an example to describe how to manually trigger a startup task. The sample code is as follows: @@ -231,13 +403,13 @@ import { BusinessError } from '@kit.BasicServicesKit'; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); - let startParams = ['StartupTask_005', 'StartupTask_006']; + let startParams = ["StartupTask_005", "StartupTask_006"]; try { startupManager.run(startParams).then(() => { console.log('StartupTest startupManager run then, startParams = '); }).catch((error: BusinessError) => { - console.info("StartupTest promise catch error, error = " + JSON.stringify(error)); - console.info("StartupTest promise catch error, startParams = " + console.info('StartupTest promise catch error, error = ' + JSON.stringify(error)); + console.info('StartupTest promise catch error, startParams = ' + JSON.stringify(startParams)); }) } catch (error) { @@ -260,8 +432,9 @@ import { startupManager } from '@kit.AbilityKit'; @Entry @Component struct Index { - @State message: string = 'Manual Mode' - @State startParams: Array = ['StartupTask_006']; + @State message: string = "Manual Mode"; + @State startParams1: Array = ["StartupTask_006"]; + @State startParams2: Array = ["libentry_006"]; build() { RelativeContainer() { @@ -270,8 +443,11 @@ struct Index { .fontSize(20) .fontWeight(FontWeight.Bold) .onClick(() => { - if (!startupManager.isStartupTaskInitialized("StartupTask_006")) { // Check whether the startup task finishes execution. - startupManager.run(this.startParams) + if (!startupManager.isStartupTaskInitialized("StartupTask_006") ) { // Check whether the startup task finishes execution. + startupManager.run(this.startParams1) + } + if (!startupManager.isStartupTaskInitialized("libentry_006") ) { + startupManager.run(this.startParams2) } }) .alignRules({ @@ -284,4 +460,3 @@ struct Index { } } ``` - diff --git a/en/application-dev/application-models/app-uri-config.md b/en/application-dev/application-models/app-uri-config.md index e4bd922dd5055f52d90062e0a8bf275ec6cf7f75..30c457954bcb2412ca3a95f17865dd0c0118831e 100644 --- a/en/application-dev/application-models/app-uri-config.md +++ b/en/application-dev/application-models/app-uri-config.md @@ -1,7 +1,7 @@ # Application Link Description ## Description of uris -**uris** declared in **skills** of the **module.json5** file contains the following fields. +**uris** declared in [skills](../quick-start/module-configuration-file.md#skills) of the [module.json5 file](../quick-start/module-configuration-file.md) contains the following fields. > **NOTE** > @@ -36,6 +36,11 @@ URIs can be expressed in different formats based on the available fields. Among ### Description of linkFeature +> **NOTE** +> +> The number of **linkFeature** declared in a bundle cannot exceed 150. + + The use of the **linkFeature** field enables an application to deliver a more user-friendly redirection experience. (The declaration of the **linkFeature** field must be reviewed by the application market before being released.) The use scenarios are as follows: 1. Identification of applications of the same type: When the caller starts a vertical application (for example, navigation applications), the system identifies the matched applications based on the **linkFeature** field and displays the applications on the vertical domain panel. diff --git a/en/application-dev/application-models/application-component-configuration-stage.md b/en/application-dev/application-models/application-component-configuration-stage.md index 6cfe3b1cb00044fb98134fa69761113fe61b0e3d..a6b9f9be1b5e843d871930d5fe62e5999de8eb08 100644 --- a/en/application-dev/application-models/application-component-configuration-stage.md +++ b/en/application-dev/application-models/application-component-configuration-stage.md @@ -7,7 +7,7 @@ During application development, you must configure tags to identify an applicati The bundle name is specified by the **bundleName** field in the [app.json5 file](../quick-start/app-configuration-file.md) in the **AppScope** directory of the project. This field identifies an application and must be globally unique. You are advised to use the reverse domain name notation, for example, *com.example.demo*, where the first part is the domain suffix **com**, the second part is the vendor/individual name, and the third part is the application name, which can be of multiple levels. ## Configuring Icons and Labels -Icons and labels are usually configured together. They correspond to the **icon** and **label** fields in the [app.json5 file](../quick-start/app-configuration-file.md) and [module.json5 file](../quick-start/module-configuration-file.md). Since 5.0.3.800, DevEco Studio does not forcibly verify the **icons** and **labels** in the **module.json5** file. Therefore, you can configure them in either **module.json5** or **app.json5**. +Icons and labels are usually configured together. They correspond to the **icon** and **label** fields in the [app.json5 file](../quick-start/app-configuration-file.md) and [module.json5 file](../quick-start/module-configuration-file.md). In DevEco Studio 5.0.3.800 and later versions, the **icon** and **label** fields are optional in the **module.json5** file, but mandatory in the **app.json5** file. This means that you can skip **icons** and **labels** in the **module.json5** file. ### Generation Mechanism * If the HAP file contains UIAbility configuration, the following scenarios are possible: diff --git a/en/application-dev/application-models/application-context-stage.md b/en/application-dev/application-models/application-context-stage.md index 51cfcd95c32c239a33b68e1af710ee2d8137b52d..89a1cdd926805b35d5049e2234a3df0a777efa53 100644 --- a/en/application-dev/application-models/application-context-stage.md +++ b/en/application-dev/application-models/application-context-stage.md @@ -26,7 +26,7 @@ } } ``` - + > **NOTE** > > For details about how to obtain the context of a **UIAbility** instance on the page, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). @@ -81,135 +81,88 @@ This topic describes how to use the context in the following scenarios: ### Obtaining Application File Paths -The [base class Context](../reference/apis-ability-kit/js-apis-inner-application-context.md) provides the capability of obtaining application file paths. [ApplicationContext](../reference/apis-ability-kit/js-apis-inner-application-applicationContext.md), [AbilityStageContext](../reference/apis-ability-kit/js-apis-inner-application-abilityStageContext.md), [UIAbilityContext](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md), and [ExtensionContext](../reference/apis-ability-kit/js-apis-inner-application-extensionContext.md) inherit this capability. The application file paths are a type of application sandbox paths. For details, see [Application Sandbox Directory](../file-management/app-sandbox-directory.md). - -The application file paths obtained by the preceding contexts are different. - -- The application file path obtained through [ApplicationContext](../reference/apis-ability-kit/js-apis-inner-application-applicationContext.md) is at the application level. This path is recommended for storing global application information, and the files in the path will be deleted when the application is uninstalled. - - | Name| Path| - | -------- | -------- | - | bundleCodeDir | \/el1/bundle| - | cacheDir | \/\/base/cache| - | filesDir | \/\/base/files| - | preferencesDir | \/\/base/preferences| - | tempDir | \/\/base/temp| - | databaseDir | \/\/database| - | distributedFilesDir | \/el2/distributedFiles| - | cloudFileDir12+ | \/el2/cloud| - - The sample code is as follows: - - ```ts - import { common } from '@kit.AbilityKit'; - import { hilog } from '@kit.PerformanceAnalysisKit'; - import { promptAction } from '@kit.ArkUI'; +The [base class Context](../reference/apis-ability-kit/js-apis-inner-application-context.md) provides the capability of obtaining application file paths. [ApplicationContext](../reference/apis-ability-kit/js-apis-inner-application-applicationContext.md), [AbilityStageContext](../reference/apis-ability-kit/js-apis-inner-application-abilityStageContext.md), [UIAbilityContext](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md), and [ExtensionContext](../reference/apis-ability-kit/js-apis-inner-application-extensionContext.md) inherit this capability. However, the specific paths retrieved can differ based on the type of the context used. - const TAG: string = '[Page_Context]'; - const DOMAIN_NUMBER: number = 0xFF00; +- [ApplicationContext](../reference/apis-ability-kit/js-apis-inner-application-applicationContext.md): This context provides access to the application-level file path, which is used to store global application information. Files in this path are removed when the application is uninstalled. +- [AbilityStageContext](../reference/apis-ability-kit/js-apis-inner-application-abilityStageContext.md), [UIAbilityContext](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md), and [ExtensionContext](../reference/apis-ability-kit/js-apis-inner-application-extensionContext.md): These contexts provide access to [module-level](../quick-start/application-package-overview.md) file paths. Files in these paths are removed when the corresponding [HAP](../quick-start/hap-package.md) or [HSP](../quick-start/in-app-hsp.md) module is uninstalled. Uninstalling an HAP or HSP module does not affect files under the application-level path unless all HAP and HSP modules of the application are uninstalled. - @Entry - @Component - struct Page_Context { - private context = getContext(this) as common.UIAbilityContext; - - build() { - Column() { - //... - List({ initialIndex: 0 }) { - ListItem() { - Row() { - //... - } - .onClick(() => { - let applicationContext = this.context.getApplicationContext(); - let cacheDir = applicationContext.cacheDir; - let tempDir = applicationContext.tempDir; - let filesDir = applicationContext.filesDir; - let databaseDir = applicationContext.databaseDir; - let bundleCodeDir = applicationContext.bundleCodeDir; - let distributedFilesDir = applicationContext.distributedFilesDir; - let preferencesDir = applicationContext.preferencesDir; - let cloudFileDir = applicationContext.cloudFileDir; - // Obtain the application file path. - let filePath = tempDir + 'test.txt'; - hilog.info(DOMAIN_NUMBER, TAG, `filePath: ${filePath}`); - if (filePath !== null) { - promptAction.showToast({ - message: filePath - }); - } - }) - } - //... - } - //... - } - //... - } - } - ``` + - UIAbilityContext: This context can be used to obtain the file paths of the module containing the UIAbility. + - ExtensionContext: This context can be used to obtain the file paths of the module containing the ExtensionAbility. + - AbilityStageContext: Given that AbilityStageContext is initialized earlier than UIAbilityContext and ExtensionContext, it is typically used to obtain file paths within the AbilityStage. -- The application file path obtained through [AbilityStageContext](../reference/apis-ability-kit/js-apis-inner-application-abilityStageContext.md), [UIAbilityContext](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md), and [ExtensionContext](../reference/apis-ability-kit/js-apis-inner-application-extensionContext.md) is at the [HAP](../quick-start/hap-package.md) level. This path is recommended for storing HAP-related information, and the files in this path are deleted when the HAP is uninstalled. However, the deletion does not affect the files in the application-level path unless all HAPs of the application are uninstalled. +>**NOTE** +> +> The application file paths are a type of application sandbox paths. For details, see [Application Sandbox Directory](../file-management/app-sandbox-directory.md). - | Name| Path| - | -------- | -------- | - | bundleCodeDir | \/el1/bundle| - | cacheDir | \/\/base/**haps/\**/cache| - | filesDir | \/\/base/**haps/\**/files| - | preferencesDir | \/\/base/**haps/\**/preferences| - | tempDir | \/\/base/**haps/\**/temp| - | databaseDir | \/\/database/**\**| - | distributedFilesDir | \/el2/distributedFiles/**\**| - | cloudFileDir12+ | \/el2/cloud/**\**| +**Table 1** Description of application file paths obtained by different types of contexts +| Name| Description| Path Obtained by ApplicationContext| Path Obtained by AbilityStageContext, UIAbilityContext, and ExtensionContext| +| -------- | -------- | -------- | -------- | +| bundleCodeDir | Bundle code directory.| \/el1/bundle| \/el1/bundle| +| cacheDir | Cache directory.| \/\/base/cache| \/\/base/**haps/\**/cache| +| filesDir | File directory.| \/\/base/files| \/\/base/**haps/\**/files| +| preferencesDir | Preferences directory.| \/\/base/preferences| \/\/base/**haps/\**/preferences| +| tempDir | Temporary directory.| \/\/base/temp| \/\/base/**haps/\**/temp| +| databaseDir | Database directory.| \/\/database| \/\/database/**\**| +| distributedFilesDir | Distributed file directory.| \/el2/distributedFiles| \/el2/distributedFiles/| +| resourceDir11+ | Resource directory.
**NOTE**
You are required to manually create the **resfile** directory in **\\resource**.| N/A| \/el1/bundle/**\**/resources/resfile| +| cloudFileDir12+ | Cloud file directory.| \/el2/cloud| \/el2/cloud/| - The sample code is as follows: +This section uses ApplicationContext as an example to describe how to obtain the application file path, create a file in the path, and read and write the file. The sample code is as follows: ```ts import { common } from '@kit.AbilityKit'; + import { buffer } from '@kit.ArkTS'; + import { fileIo, ReadOptions } from '@kit.CoreFileKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; - import { promptAction } from '@kit.ArkUI'; const TAG: string = '[Page_Context]'; const DOMAIN_NUMBER: number = 0xFF00; @Entry @Component - struct Page_Context { + struct Index { + @State message: string = 'Hello World'; private context = getContext(this) as common.UIAbilityContext; build() { - Column() { - //... - List({ initialIndex: 0 }) { - ListItem() { - Row() { - //... - } - .onClick(() => { - let cacheDir = this.context.cacheDir; - let tempDir = this.context.tempDir; - let filesDir = this.context.filesDir; - let databaseDir = this.context.databaseDir; - let bundleCodeDir = this.context.bundleCodeDir; - let distributedFilesDir = this.context.distributedFilesDir; - let preferencesDir = this.context.preferencesDir; - let cloudFileDir = applicationContext.cloudFileDir; - // Obtain the application file path. - let filePath = tempDir + 'test.txt'; - hilog.info(DOMAIN_NUMBER, TAG, `filePath: ${filePath}`); - if (filePath !== null) { - promptAction.showToast({ - message: filePath - }); - } - }) + Row() { + Column() { + Text(this.message) + // ... + Button() { + Text('create file') + // ... + .onClick(() => { + let applicationContext = this.context.getApplicationContext(); + // Obtain the application file path. + let filesDir = applicationContext.filesDir; + hilog.info(DOMAIN_NUMBER, TAG, `filePath: ${filesDir}`); + // Create and open the file if it does not exist. Open the file if it already exists. + let file = fileIo.openSync(filesDir + '/test.txt', fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE); + // Write data to the file. + let writeLen = fileIo.writeSync(file.fd, "Try to write str."); + hilog.info(DOMAIN_NUMBER, TAG, `The length of str is: ${writeLen}`); + // Create an ArrayBuffer object with a size of 1024 bytes to store the data read from the file. + let arrayBuffer = new ArrayBuffer(1024); + // Set the offset and length to read. + let readOptions: ReadOptions = { + offset: 0, + length: arrayBuffer.byteLength + }; + // Read the file content to the ArrayBuffer object and return the number of bytes that are actually read. + let readLen = fileIo.readSync(file.fd, arrayBuffer, readOptions); + // Convert the ArrayBuffer object into a Buffer object and output it as a string. + let buf = buffer.from(arrayBuffer, 0, readLen); + hilog.info(DOMAIN_NUMBER, TAG, `the content of file: ${buf.toString()}`); + // Close the file. + fileIo.closeSync(file); + }) } - //... + // ... } - //... + // ... } - //... + // ... } } ``` @@ -316,7 +269,7 @@ struct Page_Context { ### Obtaining the Context of Other Modules in the Current Application Call [createModuleContext(context: Context, moduleName: string)](../reference/apis-ability-kit/js-apis-app-ability-application.md#applicationcreatemodulecontext12) to obtain the context of another module in the current application. After obtaining the context, you can obtain the resource information of that module. - + ```ts import { common, application } from '@kit.AbilityKit'; import { promptAction } from '@kit.ArkUI'; @@ -344,12 +297,12 @@ Call [createModuleContext(context: Context, moduleName: string)](../reference/ap console.info(`CreateModuleContext success, data: ${JSON.stringify(data)}`); if (data !== null) { promptAction.showToast({ - message: ('Context obtained.') + message: ('Context obtained') }); } }) .catch((err: BusinessError) => { - console.error(`CeateMudleContext failed, err code:${err.code}, err msg: ${err.message}`); + console.error(`CreateModuleContext failed, err code:${err.code}, err msg: ${err.message}`); }); }) } diff --git a/en/application-dev/application-models/application-models.md b/en/application-dev/application-models/application-models.md index 821a37de6140fdb3b4a69393602081bc142d3b4b..0289e6bc7617ae6b76d7eb10791a70f126828e55 100644 --- a/en/application-dev/application-models/application-models.md +++ b/en/application-dev/application-models/application-models.md @@ -50,6 +50,6 @@ The table below describes their differences in detail. | -------- | -------- | -------- | | **Application component**| 1. Component classification
![fa-model-component](figures/fa-model-component.png)
- PageAbility: supports user interaction via the UI. For details, see [PageAbility Component Overview](pageability-overview.md).
- ServiceAbility: provides background services without the UI. For details, see [ServiceAbility Component Overview](serviceability-overview.md).
- DataAbility: provides the data sharing capability without the UI. For details, see [DataAbility Component Overview](dataability-overview.md).
2. Development mode
Application components are specified by exporting anonymous objects and fixed entry files. You cannot perform derivation. It is inconvenient for capability expansion.| 1. Component classification
![stage-model-component](figures/stage-model-component.png)
- UIAbility: supports user interaction with the UI. For details, see [UIAbility Component Overview](uiability-overview.md).
- ExtensionAbility: provides scenario-specific extension capabilities (such as widget and input methods). For details, see [ExtensionAbility Component Overview](extensionability-overview.md).
2. Development mode
The object-oriented mode is used to provide open application components as classes. You can derive application components for capability expansion.| | **Process model**| There are two types of processes:
1. Main process
2. Render process
For details, see [Process Model](process-model-fa.md).| There are three types of processes:
1. Main process
2. ExtensionAbility process
3. Render process
For details, see [Process Model](process-model-stage.md).| -| **Thread model**| 1. ArkTS engine instance creation
A process can run multiple application component instances, and each application component instance runs in an independent ArkTS engine instance.
2. Thread model
Each ArkTS engine instance is created on an independent thread (non-main thread). The main thread does not have an ArkTS engine instance.
3. Intra-process object sharing: not supported.
For details, see [Thread Model](thread-model-fa.md).| 1. ArkTS engine instance creation
A process can run multiple application component instances, and all application component instances share one ArkTS engine instance.
2. Thread model
The ArkTS engine instance is created on the main thread.
3. Intra-process object sharing: supported.
For details, see [Thread Model](thread-model-stage.md).| +| **Thread model**| 1. ArkTS engine instance creation
A process can run multiple instances of application components, and each instance runs in an independent ArkTS engine instance.
2. Thread model
Each ArkTS engine instance is created on an independent thread (non-main thread). The main thread does not have an ArkTS engine instance.
3. Intra-process object sharing: not supported.
For details, see [Thread Model](thread-model-fa.md).| 1. ArkTS engine instance creation
A process can run multiple application component instances, and all application component instances share one ArkTS engine instance.
2. Thread model
The ArkTS engine instance is created on the main thread.
3. Intra-process object sharing: supported.
For details, see [Thread Model](thread-model-stage.md).| |**Mission management model**| - A mission is created for each PageAbility component instance.
- Missions are stored persistently until they are deleted by users or the number of missions exceeds the maximum (customized based on the product configuration).
- PageAbility components do not form a stack structure.| - A mission is created for each UIAbility component instance.
- Missions are stored persistently until they are deleted by users or the number of missions exceeds the maximum (customized based on the product configuration).
- UIAbility components do not form a stack structure.| | **Configuration file**| The **config.json** file contains the application, HAP, and application component information.
For details, see [Application Configuration File Overview (FA Model)](../quick-start/application-configuration-file-overview-fa.md).| The **app.json5** file contains the application information, and the **module.json5** file contains the HAP and application component information.
For details, see [Application Configuration File Overview (Stage Model)](../quick-start/application-configuration-file-overview-stage.md).| diff --git a/en/application-dev/application-models/canopenlink.md b/en/application-dev/application-models/canopenlink.md index 0685288b83b2b4ff4b8cb966a97a1279820eb858..06dd28dd4b81df8c16aeb5874d610d02169489c4 100644 --- a/en/application-dev/application-models/canopenlink.md +++ b/en/application-dev/application-models/canopenlink.md @@ -13,7 +13,6 @@ For details about the matching rules, see [Matching Rules of Explicit Want and I 1. Configure the [querySchemes](../quick-start/module-configuration-file.md) field in the **module.json5** file of the entry module to declare the URL schemes. - A configuration example is as follows: ```json { "module": { @@ -28,7 +27,6 @@ For details about the matching rules, see [Matching Rules of Explicit Want and I 2. Import the **ohos.bundle.bundleManager** module. 3. Call **canOpenLink**. - The sample code is as follows: ```ts import { bundleManager } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; @@ -46,7 +44,6 @@ For details about the matching rules, see [Matching Rules of Explicit Want and I ### Procedure for the Target Application Configure the [uris](../quick-start/module-configuration-file.md#skills) field in the **module.json5** file. -A configuration example is as follows: ```json { "module": { diff --git a/en/application-dev/application-models/capi_nativechildprocess_development_guideline.md b/en/application-dev/application-models/capi_nativechildprocess_development_guideline.md index 24ec03fd5bc4b6032e4d63e104aaee223a768356..2ca29eb3a39c6b19bfed51de74991d29ecfb3b58 100644 --- a/en/application-dev/application-models/capi_nativechildprocess_development_guideline.md +++ b/en/application-dev/application-models/capi_nativechildprocess_development_guideline.md @@ -19,7 +19,9 @@ This topic describes how to create a native child process in the main process an > **NOTE** > -> Currently, only 2-in-1 devices are supported, and only one native child process can be started for a process. +> This function is valid only for 2-in-1 devices. +> +> Since API version 15, a single process supports a maximum of 50 native child processes. In API version 14 and earlier versions, a single process supports only one native child process. ### How to Develop @@ -282,3 +284,75 @@ libchild_process.so # ... ) ``` + +## Child Threads Obtaining Startup Parameters + +### When to Use + +Since API version 16, child processes can obtain startup parameters. + +### Available APIs + +| Name | Description | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | +| [NativeChildProcess_Args](../reference/apis-ability-kit/c-apis-ability-childprocess.md#nativechildprocess_args)* [OH_Ability_GetCurrentChildProcessArgs](../reference/apis-ability-kit/c-apis-ability-childprocess.md#oh_ability_startnativechildprocess)() | Returns the startup parameters of the child process.| + +### How to Develop + + +**Linking Dynamic Libraries** + +```txt +libchild_process.so +``` + +**Including Header Files** + +```c++ +#include +``` + +**Obtaining Startup Parameters** + +After a child process is created through [OH_Ability_StartNativeChildProcess](../reference/apis-ability-kit/c-apis-ability-childprocess.md#oh_ability_startnativechildprocess), it can call [OH_Ability_GetCurrentChildProcessArgs()](../reference/apis-ability-kit/c-apis-ability-childprocess.md#oh_ability_startnativechildprocess) to obtain the startup parameters [NativeChildProcess_Args](../reference/apis-ability-kit/c-apis-ability-childprocess.md#nativechildprocess_args) from any .so file or child thread, facilitating operations on related file descriptors. + +```c++ +#include +#include + +extern "C" { + +void ThreadFunc() +{ + // Obtain the startup parameters of the child process. + NativeChildProcess_Args *args = OH_Ability_GetCurrentChildProcessArgs(); + // If the startup parameters fail to be obtained, a null pointer is returned. + if (args == nullptr) { + return; + } + // Obtain the value of entryPrams in the startup parameters. + char *entryParams = args.entryParams; + // Obtain the FD list. + NativeChildProcess_Fd *current = args.fdList.head; + while (current != nullptr) { + char *fdName = current->fdName; + int32_t fd = current->fd; + current = current->next; + // Service logic + } +} + +/** + * Entry function of a child process, which implements the service logic of the child process. + * args is the startup parameters of the child process. + */ +void Main(NativeChildProcess_Args args) +{ + // Service logic + + // Create a thread. + std::thread tObj(ThreadFunc); +} + +} // extern "C" +``` diff --git a/en/application-dev/application-models/component-startup-rules.md b/en/application-dev/application-models/component-startup-rules.md index 027c7e85640b1b1b72916150a5d367e5260b921e..346bc4c7b82a011dbda2fdd44e5d4dffb9091568 100644 --- a/en/application-dev/application-models/component-startup-rules.md +++ b/en/application-dev/application-models/component-startup-rules.md @@ -26,7 +26,7 @@ In view of this, the system formulates a set of component startup rules, as foll If the **exported** field of the component is set to **true**, the component can be called by other applications. If the field is set to **false**, the component cannot be called by other applications. If this is the case, you must also verify the permission **ohos.permission.START_INVISIBLE_ABILITY**, which is available only for system applications. For details about the **exported** fields, see [abilities](../quick-start/module-configuration-file.md#abilities). -- Before starting a UIAbility component of a background application, verify the permission **ohos.permission.START_ABILITIES_FROM_BACKGROUND**, which is available only for system applications. +- Before starting a UIAbility component of a background application, the caller must verify the permission ohos.permission.START_ABILITIES_FROM_BACKGROUND, which is available only for system applications. For 2-in-1 devices, if an application has created a floating window in the foreground, it can start other UIAbility components without verifying this permission after it transitions to the background. > **NOTE** > diff --git a/en/application-dev/application-models/deep-linking-startup.md b/en/application-dev/application-models/deep-linking-startup.md index 5cd1a67268f64ea8932a469492682b432562a1b9..5a9be6ed35085e3da0f0f8ad024671a451f38a14 100644 --- a/en/application-dev/application-models/deep-linking-startup.md +++ b/en/application-dev/application-models/deep-linking-startup.md @@ -11,11 +11,13 @@ Deep Linking searches for an application based on the URI matching rules in impl ### Configuring the module.json5 File -To be accessed by other applications, an application must configure the [skills](../quick-start/module-configuration-file.md#skills) field of the [module.json5 file](../quick-start/module-configuration-file.md). The value of **scheme** under **uri** can be customized. It can be any string that does not contain special characters or start with **ohos**. +To be accessed by other applications, an application must configure the [skills](../quick-start/module-configuration-file.md#skills) field of the [module.json5 file](../quick-start/module-configuration-file.md). > **NOTE** > -> The value of **scheme** in Deep Linking cannot be **https**, **http**, or **file**. Otherwise, the default system browser is started. +> By default, the **skills** field contains a **skill** object, which is used to identify the application entry. Application redirection links should not be configured in this object. Instead, separate **skill** objects should be used. If there are multiple redirection scenarios, create different **skill** objects under **skills**. Otherwise, the configuration does not take effect. +> +> In Deep Linking, the **scheme** value can be customized to any string that does not contain special characters and does not start with **ohos**. It is generally recommended to avoid using **https**, **http**, or **file** to prevent the default system browser from being launched. A configuration example is as follows: @@ -28,6 +30,14 @@ A configuration example is as follows: { // ... "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + }, { "actions": [ // actions cannot be empty. Otherwise, matching the target application fails. @@ -41,7 +51,7 @@ A configuration example is as follows: "host": "www.example.com" } ] - } + } // Add a skill object for redirection. If there are multiple redirection scenarios, create multiple skill objects. ] } ] diff --git a/en/application-dev/application-models/extensionability-overview.md b/en/application-dev/application-models/extensionability-overview.md index ca26bb071cfe3490a614a4c2d63f2cae50159a98..f10a33a6a2896aff93c840a5b2aa7f0f656b46db 100644 --- a/en/application-dev/application-models/extensionability-overview.md +++ b/en/application-dev/application-models/extensionability-overview.md @@ -10,23 +10,24 @@ The table below lists the ExtensionAbility types defined in the system. > **NOTE** > -> - The column **Allow Third-Party Apps to Implement** specifies whether third-party applications can inherit the **ExtensionAbility** parent class and implement their own service logic for a type of ExtensionAbility. The value **Y** means that third-party applications can implement their own service logic for a type of ExtensionAbility, **N** means the opposite. -> - The column **Allow Third-Party Apps to Access** specifies whether third-party applications can access external services provided by a type of ExtensionAbility. The value **Y** means that third-party applications can access external services provided by a certain type of ExtensionAbility, **N** means that they cannot access external services, and **NA** means that no external services are provided. -> - The column **Allow Independent ExtensionAbility Sandbox** specifies whether an independent sandbox is provided for an ExtensionAbility. In versions earlier than API version 12, an application and its ExtensionAbilities use the same sandbox. Since API version 12, a new ExtensionAbility uses an independent sandbox. Currently, the InputMethodExtensionAbility runs in an independent sandbox for security purposes. The value **Y** means that an independent sandbox is provided for an ExtensionAbility, and **N** means that no independent sandbox is provided for an ExtensionAbility. -> - The column **Allow ExtensionAbilities to Access Sendable Data in Strict Mode** specifies whether an ExtensionAbility can access sendable data in strict mode. Sendable data is implemented by configuring [data-group-ids](../security/app-provision-structure.md#bundle-info) and [dataGroupIds](../quick-start/module-configuration-file.md#extensionabilities) of the application. Strict access indicates that the sendable data is read-only, and non-strict access indicates that the data can be read and written. The value **Y** means that an ExtensionAbility uses strict mode to access sendable data, that is, it can read sendable data. The value **N** means that an ExtensionAbility uses non-strict mode to access sendable data, that is, it can read and write sendable data. +> - The column **Allow Third-Party Apps to Implement** specifies whether third-party applications can inherit the **ExtensionAbility** parent class and implement their own service logic for a type of ExtensionAbility. +> - The column **Allow Third-Party Apps to Access** specifies whether third-party applications can access external services provided by a type of ExtensionAbility. +> - The column **Allow Independent ExtensionAbility Sandbox** specifies whether an independent sandbox is provided for an ExtensionAbility. In versions earlier than API version 12, an application and its ExtensionAbilities use the same sandbox. Since API version 12, a new ExtensionAbility uses an independent sandbox. Currently, the InputMethodExtensionAbility runs in an independent sandbox for security purposes. +> - The column **Allow ExtensionAbilities to Access Sendable Data in Strict Mode** specifies whether an ExtensionAbility can access sendable data in strict mode. Sendable data is implemented by configuring [data-group-ids](../security/app-provision-structure.md#bundle-info) and [dataGroupIds](../quick-start/module-configuration-file.md#extensionabilities) of the application. Strict access indicates that the sendable data is read-only, and non-strict access indicates that the data can be read and written. System applications are not restricted. They can implement all the ExtensionAbility types defined in the system and access external services provided by all the ExtensionAbility types. | ExtensionAbility Type | Description| Allow Third-Party Apps to Implement | Allow Third-Party Apps to Access | Allow Independent ExtensionAbility Sandbox | Allow ExtensionAbilities to Access Sendable Data in Strict Mode | -| ------------------------ | -------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | -| [FormExtensionAbility](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md) | ExtensionAbility component of the FORM type, which provides APIs related to [widgets](../form/formkit-overview.md). | Y | N | N | N | -| [WorkSchedulerExtensionAbility](../reference/apis-backgroundtasks-kit/js-apis-WorkSchedulerExtensionAbility.md) | ExtensionAbility component of the WORK_SCHEDULER type, which provides callbacks for [deferred tasks](../task-management/work-scheduler.md). | Y | NA | N | N | -| [InputMethodExtensionAbility](../reference/apis-ime-kit/js-apis-inputmethod-extension-ability.md) | ExtensionAbility component of the INPUT_METHOD type, which is used to develop [input method applications](../inputmethod/ime-kit-intro.md). | Y | Y | Y | N if you have enabled the full mode in input method management
Y if you have not enabled the full mode in input method management| -| [BackupExtensionAbility](../reference/apis-core-file-kit/js-apis-application-backupExtensionAbility.md) | ExtensionAbility component of the BACKUP type, which provides APIs for [backing up and restoring application data](../file-management/app-file-backup-overview.md). | Y | NA | N | N | -| [DriverExtensionAbility](../reference/apis-driverdevelopment-kit/js-apis-app-ability-driverExtensionAbility.md) | ExtensionAbility component of the DRIVER type, which provides the [driver-related extension framework](../device/driver/driverextensionability.md). | Y | Y | N | N | -| [EmbeddedUIExtensionAbility](../reference/apis-ability-kit/js-apis-app-ability-embeddedUIExtensionAbility.md) | ExtensionAbility component of the EMBEDDED_UI type, which provides the [embedded UI across processes](embeddeduiextensionability.md).| Y | Y | N | N | -| [ShareExtensionAbility](../reference/apis-ability-kit/js-apis-app-ability-shareExtensionAbility.md) | ExtensionAbility component of the SHARE type, which is used to extend the sharing template service.| Y | Y | N | N | +| ------------------------ | -------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | + | [FormExtensionAbility](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md) | ExtensionAbility component of the FORM type, which provides APIs related to [widgets](../form/formkit-overview.md). | Yes| No| No| In non-strict mode, sendable data can be read and written.| +| [WorkSchedulerExtensionAbility](../reference/apis-backgroundtasks-kit/js-apis-WorkSchedulerExtensionAbility.md) | ExtensionAbility component of the WORK_SCHEDULER type, which provides callbacks for [deferred tasks](../task-management/work-scheduler.md). | Yes| N/A| No| In non-strict mode, sendable data can be read and written.| +| [InputMethodExtensionAbility](../reference/apis-ime-kit/js-apis-inputmethod-extension-ability.md) | ExtensionAbility component of the INPUT_METHOD type, which is used to develop [input method applications](../inputmethod/ime-kit-intro.md). | Yes| Yes| Yes| If full mode is enabled in input method management (in non-strict mode), sendable data can be read and written. If full mode is not enabled (in strict mode), sendable data can be read only.| +| [BackupExtensionAbility](../reference/apis-core-file-kit/js-apis-application-backupExtensionAbility.md) | ExtensionAbility component of the BACKUP type, which provides APIs for [backing up and restoring application data](../file-management/app-file-backup-overview.md). | Yes| N/A| No| In non-strict mode, sendable data can be read and written.| +| [DriverExtensionAbility](../reference/apis-driverdevelopment-kit/js-apis-app-ability-driverExtensionAbility.md) | ExtensionAbility component of the DRIVER type, which provides the [driver-related extension framework](../device/driver/driverextensionability.md). | Yes| Yes| No| In non-strict mode, sendable data can be read and written.| +| [EmbeddedUIExtensionAbility](../reference/apis-ability-kit/js-apis-app-ability-embeddedUIExtensionAbility.md) | ExtensionAbility component of the EMBEDDED_UI type, which provides the [embedded UI across processes](embeddeduiextensionability.md).| Yes| Yes| No| In non-strict mode, sendable data can be read and written.| +| [ShareExtensionAbility](../reference/apis-ability-kit/js-apis-app-ability-shareExtensionAbility.md) | ExtensionAbility component of the SHARE type, which is used to extend the sharing template service.| Yes| Yes| No| In non-strict mode, sendable data can be read and written.| +| [FenceExtension](../reference/apis-location-kit/js-apis-app-ability-FenceExtensionAbility.md) | ExtensionAbility component of the FENCE type, which provides the [geofence](../device/location/fenceExtensionAbility.md) capability.| Yes| No| No| In non-strict mode, sendable data can be read and written.| diff --git a/en/application-dev/application-models/figures/UIAbility-Life-Cycle-WindowStage.png b/en/application-dev/application-models/figures/UIAbility-Life-Cycle-WindowStage.png new file mode 100644 index 0000000000000000000000000000000000000000..f39c3d37cb5a7a43d58309d8e151fee57112c533 Binary files /dev/null and b/en/application-dev/application-models/figures/UIAbility-Life-Cycle-WindowStage.png differ diff --git a/en/application-dev/application-models/figures/app-startup-procedure.png b/en/application-dev/application-models/figures/app-startup-procedure.png index d78d1d382595f1d8f8fd67235754c0c9670cc4ef..eb14c958c7f887ad6d33622c925eab1ae46a7983 100644 Binary files a/en/application-dev/application-models/figures/app-startup-procedure.png and b/en/application-dev/application-models/figures/app-startup-procedure.png differ diff --git a/en/application-dev/application-models/figures/app-startup.png b/en/application-dev/application-models/figures/app-startup.png index 14bfbef88f8ae0b40f57adbce02182d571aa182b..9827d50812a29f2d9321072db6f56c5b53c2900f 100644 Binary files a/en/application-dev/application-models/figures/app-startup.png and b/en/application-dev/application-models/figures/app-startup.png differ diff --git a/en/application-dev/application-models/figures/application-component-configuration-stage-app-module-1.png b/en/application-dev/application-models/figures/application-component-configuration-stage-app-module-1.png new file mode 100644 index 0000000000000000000000000000000000000000..5db852e92eb2f4bd782df5c370d3028c7cc65cb1 Binary files /dev/null and b/en/application-dev/application-models/figures/application-component-configuration-stage-app-module-1.png differ diff --git a/en/application-dev/application-models/figures/hsp-har-startup.png b/en/application-dev/application-models/figures/hsp-har-startup.png new file mode 100644 index 0000000000000000000000000000000000000000..54e1574787e04760a6bce8aabd8c0dddfdef226a Binary files /dev/null and b/en/application-dev/application-models/figures/hsp-har-startup.png differ diff --git a/en/application-dev/application-models/figures/start-express-panel.png b/en/application-dev/application-models/figures/start-express-panel.png index e3929ce1ca10336ccd5d08d5f03105c7571ccc95..82f320c76925a8eb5a3fce09ba1c413b958fa3d6 100644 Binary files a/en/application-dev/application-models/figures/start-express-panel.png and b/en/application-dev/application-models/figures/start-express-panel.png differ diff --git a/en/application-dev/application-models/figures/start-finance-panel.png b/en/application-dev/application-models/figures/start-finance-panel.png index 1ead6627e73bfd6ddef90d742fb0f80a0923d8d8..027623fc9f08ebaeaa273e37526ab5e38472ea08 100644 Binary files a/en/application-dev/application-models/figures/start-finance-panel.png and b/en/application-dev/application-models/figures/start-finance-panel.png differ diff --git a/en/application-dev/application-models/figures/start-flight-panel.png b/en/application-dev/application-models/figures/start-flight-panel.png index e3929ce1ca10336ccd5d08d5f03105c7571ccc95..82f320c76925a8eb5a3fce09ba1c413b958fa3d6 100644 Binary files a/en/application-dev/application-models/figures/start-flight-panel.png and b/en/application-dev/application-models/figures/start-flight-panel.png differ diff --git a/en/application-dev/application-models/figures/start-mail-panel.png b/en/application-dev/application-models/figures/start-mail-panel.png index 205ac73d4121ae7dd75b58bcd23508ef32786d9d..5f7cbec5c5d6c9855cfa2c87239dceb801993911 100644 Binary files a/en/application-dev/application-models/figures/start-mail-panel.png and b/en/application-dev/application-models/figures/start-mail-panel.png differ diff --git a/en/application-dev/application-models/figures/start-navigation-panel.png b/en/application-dev/application-models/figures/start-navigation-panel.png index 1050cbc2a421b6ae4db98f842091624b764979d6..9d6f54d27fdb2a95507cbcb0fcb00d13dfdc8575 100644 Binary files a/en/application-dev/application-models/figures/start-navigation-panel.png and b/en/application-dev/application-models/figures/start-navigation-panel.png differ diff --git a/en/application-dev/application-models/hop-cross-device-migration.md b/en/application-dev/application-models/hop-cross-device-migration.md index 47130403cb80ecc2eee98fac180e520193cd025e..8f0b2a26ad405346ceca9d83ff9f9c62d6b48cdf 100644 --- a/en/application-dev/application-models/hop-cross-device-migration.md +++ b/en/application-dev/application-models/hop-cross-device-migration.md @@ -290,6 +290,7 @@ To implement special scenarios, for example, where migration is required only fo > **NOTE** > > Currently, only the page stack implemented based on the router module can be automatically restored. The page stack implemented using the **Navigation** component cannot be automatically restored. +> > If an application uses the **Navigation** component for routing, you can disable default page stack migration by setting [SUPPORT_CONTINUE_PAGE_STACK_KEY](../reference/apis-ability-kit/js-apis-app-ability-wantConstant.md#params) to **false**. In addition, save the page (or page stack) to be migrated in **want**, and manually load the specified page on the target device. By default, the page stack is restored during the migration of a [UIAbility](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md). Before [onCreate()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityoncreate) or [onNewWant()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityonnewwant) finishes the execution, call [restoreWindowStage()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#restore) to pass in the current window context, which will be used for page stack loading and restoration. The **restoreWindowStage()** API must be executed in a synchronous API. If it is executed during an asynchronous callback, there is a possibility that the page fails to be loaded during application startup. @@ -366,13 +367,14 @@ export default class MigrationAbility extends UIAbility { } ``` -### Supporting Cross-Device Migration Between Different Abilities in the Same Application +### Migrating Between Abilities in the Same Application Across Devices Generally, the same ability is involved during a cross-device migration. However, different ability names may be configured for the same service on different device types, resulting in different abilities. To support migration in this scenario, you can configure the **continueType** flag under **abilities** in the [module.json5](../quick-start/module-configuration-file.md) file for association. The values of the **continueType** tag of the two abilities must be the same. The following is an example: > **NOTE** > > The value of **continueType** must be unique in an application. The value is a string of a maximum of 127 bytes consisting of letters, digits, and underscores (_). + > > The **continueType** tag is a string array. If multiple fields are configured, only the first field takes effect. ```json @@ -405,6 +407,62 @@ The values of the **continueType** tag of the two abilities must be the same. Th } ``` +### Migrating Abilities with Different Bundle Names in the Same Application Across Devices +An application may use different bundle names on different devices. To support migration in this scenario, configure **abilities** in the **module.json5** file of the application as follows: + +- **continueBundleName**: bundle name of the application on the peer device. +- **continueType**: The same value must be used. + + > **NOTE** + > + > The value of **continueType** must be unique in an application. The value is a string of a maximum of 127 bytes consisting of letters, digits, and underscores (_). + > + > The **continueType** tag is a string array. If multiple fields are configured, only the first field takes effect. + + +An example is as follows: + +An application with different bundle names is migrated between device A and device B. The bundle name of the application on device A is com.demo.example1, and that on device B is com.demo.example2. + +```JSON +// In the configuration file for device A, set continueBundleName to the bundle name of the application on device B. +{ + "module": { + // ··· + "abilities": [ + { + "name": "EntryAbility", + // ··· + "continueType": ["continueType"], + "continueBundleName": ["com.demo.example2"], // continueBundleName is set to com.demo.example2, which is the bundle name of the application on device B. + + } + ] + + } +} +``` + +```JSON +// In the configuration file for device B, set continueBundleName to the bundle name of the application on device A. +{ + "module": { + // ··· + "abilities": [ + { + "name": "EntryAbility", + // ··· + "continueType": ["continueType"], + "continueBundleName": ["com.demo.example1"], // continueBundleName is set to com.demo.example1, which is the bundle name of the application on device A. + + } + ] + + } +} + +``` + ### Quickly Starting a Target Application By default, the target application on the peer device is not started immediately when the migration is initiated. It waits until the data to migrate is synchronized from the source device to the peer device. To start the target application immediately upon the initiation of a migration, you can add the **_ContinueQuickStart** suffix to the value of **continueType**. In this way, only the migrated data is restored after the data synchronization, delivering an even better migration experience. @@ -422,7 +480,11 @@ By default, the target application on the peer device is not started immediately } } ``` -With quick start, the target application starts while waiting for the data to migration, minimizing the duration that users wait for the migration to complete. Note that, for the first migration with quick start enabled, the [onCreate()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityoncreate) or [onNewWant()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityonnewwant) callback is triggered, in which **launchReason** is **PREPARE_CONTINUATION**. The introduce of the **launchReason** parameter solves problems related to redirection and timing. It also provides a loading screen during quick startup, delivering a better experience. The following figure shows the quick start process. +With quick start, the target application starts while waiting for the data to migration, minimizing the duration that users wait for the migration to complete. Note that, for the first migration with quick start enabled, the [onCreate()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityoncreate) or [onNewWant()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityonnewwant) callback is triggered, in which **launchReason** is **PREPARE_CONTINUATION**. The introduction of the **launchReason** parameter solves problems related to redirection and timing. It also provides a loading screen during quick startup. + +Since API version 18, an application that displays a loading page during quick launch can [obtain the quick startup result during cross-device migration](../reference/apis-ability-kit/js-apis-app-ability-continueManager.md#continuemanageron). Depending on this result, the application can take appropriate actions. For example, if the quick startup is successful, the application can dismiss the loading page and proceed to the continuation page. + +The following figure shows the quick start process. ![hop-cross-device-migration](figures/continue_quick_start.png) @@ -487,7 +549,7 @@ export default class MigrationAbility extends UIAbility { } ``` -When the target application is quickly started, the [onWindowStageCreate()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate) and [onWindowStageRestore()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagerestore) callbacks are triggered in sequence. Generally, in **onWindowStageCreate()**, you call [loadContent()](../reference/apis-arkui/js-apis-window.md#loadcontent9) to load the page. This API throws an asynchronous task to load the home page. This asynchronous task is not synchronous with **onWindowStageRestore()**. If UI-related APIs (such as route APIs) are used in **onWindowStageRestore()**, the invoking time may be earlier than the home page loading time. To ensure the normal loading sequence, you can use [setTimeout()](../reference/common/js-apis-timer.md#settimeout) to throw an asynchronous task for related operations. For details, see the sample code. +When the target application is quickly started, the [onWindowStageCreate()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate) and [onWindowStageRestore()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagerestore) callbacks are triggered in sequence. Generally, in **onWindowStageCreate()**, you call [loadContent()](../reference/apis-arkui/js-apis-window.md#loadcontent9) to load the page. This API throws an asynchronous task to load the home page. This asynchronous task is not synchronous with **onWindowStageRestore()**. If UI-related APIs (such as route APIs) are used in **onWindowStageRestore()**, the invoking time may be earlier than the home page loading time. To ensure the normal loading sequence, you can use [setTimeout()](../reference/common/js-apis-timer.md#settimeout) to throw an asynchronous task for related operations. The sample code is as follows: @@ -611,8 +673,10 @@ On the source device, save the data to migrate to a distributed [data object](.. > **NOTE** > -> Distributed data objects must be activated before being made persistent. Therefore, the **save()** API must be called after setSessionId(). +> Distributed data objects must be activated before being made persistent. Therefore, the **save()** API must be called after **setSessionId()**. +> > For applications that need to exit from the source device after migration, use **await** to wait until the **save()** API finishes execution. This prevents the application from exiting before data is saved. Since API version 12, an asynchronous **onContinue()** API is provided for this scenario. +> > Currently, the **sessionId** field in **wantParams** is occupied by the system in the migration process. You are advised to define another key in **wantParams** to store the ID to avoid data exceptions. The sample code is as follows: @@ -695,9 +759,11 @@ In [onCreate()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#u > **NOTE** > -> 1. The distributed data object of the peer device to be added to the network cannot be a temporary variable. This is because the callback of the **on()** API may be executed after **onCreate()** or **onNewWant()** finishes execution. If the temporary variable is released, a null pointer exception may occur. You can use a class member variable to avoid this problem. -> 2. The attributes of the object used to create the distributed data object on the peer device must be undefined before the distributed data object is activated. Otherwise, the source data will be overwritten after new data is added to the network, and data restoration will fail. -> 3. Before activating the distributed data object, call **on()** to listen for the restore event. This helps prevent data restoration failure caused by event missing. +> The distributed data object of the peer device to be added to the network cannot be a temporary variable. This is because the callback of the **on()** API may be executed after **onCreate()** or **onNewWant()** finishes execution. If the temporary variable is released, a null pointer exception may occur. You can use a class member variable to avoid this problem. +> +> The attributes of the object used to create the distributed data object on the peer device must be undefined before the distributed data object is activated. Otherwise, the source data will be overwritten after new data is added to the network, and data restoration will fail. +> +> Before activating the distributed data object, call **on()** to listen for the restore event. This helps prevent data restoration failure caused by event missing. The sample code is as follows: diff --git a/en/application-dev/application-models/inter-device-interaction-hop-overview.md b/en/application-dev/application-models/inter-device-interaction-hop-overview.md index 33f3bb437b3018f0c6be19c96704027ff726c9e1..3b48dd46ccfb8b095b22941cc3fec4d652ea5ba4 100644 --- a/en/application-dev/application-models/inter-device-interaction-hop-overview.md +++ b/en/application-dev/application-models/inter-device-interaction-hop-overview.md @@ -23,7 +23,7 @@ Distributed operations across devices are called hopping, which is further class Multi-device collaboration provides users with more efficient and immersive experience than with a single device. Multi-device collaboration is used in the following typical scenarios: - Scenario 1: You open the same note on devices A and B. On device A, you select images from the local Gallery, insert them to the note, and edit them. On device B, you edit the text. - - Scenario 2: : You are chatting with a customer on device A, and the customer asks for a file, which is stored on device B. You can use the chat software to open the file application on device B, select the required file, and send it back to device A. Then, you use the chat software to send it to the customer. From the perspective of application development, multi-device collaboration enables different UIAbility or ServiceExtensionAbility components to run simultaneously or alternately on multiple devices to provide a complete service, or enables the same UIAbility and ServiceExtensionAbility component to run simultaneously on multiple devices to provide a complete service. + - Scenario 2: : You are chatting with a customer on device A, and the customer asks for a file, which is stored on device B. You can use the chat software to open the file application on device B, select the required file, and send it back to device A. Then, you use the chat software to send it to the customer. From the perspective of application development, multi-device collaboration enables different [UIAbility](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md) or [ServiceExtensionAbility](../reference/apis-ability-kit/js-apis-app-ability-serviceExtensionAbility-sys.md) components to run simultaneously or alternately on multiple devices to provide a complete service, or enables the same UIAbility and ServiceExtensionAbility component to run simultaneously on multiple devices to provide a complete service. ## Hopping Architecture diff --git a/en/application-dev/application-models/mission-set-icon-name-for-task-snapshot.md b/en/application-dev/application-models/mission-set-icon-name-for-task-snapshot.md index 2a0f47113a8b1ee3244aa2f1ea52e4a1bf12ddc5..056ccc169d62f1d83f98efaaf0e8f2ce57e20d96 100644 --- a/en/application-dev/application-models/mission-set-icon-name-for-task-snapshot.md +++ b/en/application-dev/application-models/mission-set-icon-name-for-task-snapshot.md @@ -66,7 +66,7 @@ const DOMAIN_NUMBER: number = 0xFF00; let context: common.UIAbilityContext = this.context; // UIAbilityContext // Set a name for the mission snapshot. context.setMissionLabel('test').then(() => { - hilog.info(DOMAIN_NUMBER, TAG, 'Succeeded in seting mission label.'); + hilog.info(DOMAIN_NUMBER, TAG, 'Succeeded in setting mission label.'); }).catch((err: BusinessError) => { hilog.error(DOMAIN_NUMBER, TAG, `Failed to set mission label. Code is ${err.code}, message is ${err.message}`); }); diff --git a/en/application-dev/application-models/process-model-stage.md b/en/application-dev/application-models/process-model-stage.md index f4f9401e6d30913cc28074d01880eb9b1e3a8e98..ebfebd122fffcb6644f8cdab222aa1a9332bc74a 100644 --- a/en/application-dev/application-models/process-model-stage.md +++ b/en/application-dev/application-models/process-model-stage.md @@ -1,11 +1,11 @@ # Process Model (Stage Model) +A process is the basic unit for a system to allocate resources, and is the basis of an operating system structure. The process model is shown below. - -- Generally, all UIAbility, ServiceExtensionAbility, and DataShareExtensionAbility components of an application (with the same bundle name) run in an independent process, which is **Main process** in green in the figure. -- All ExtensionAbility components of the same type (except ServiceExtensionAbility and DataShareExtensionAbility) of an application (with the same bundle name) run in an independent process, such as **FormExtensionAbility process**, **InputMethodExtensionAbility process**, and other **ExtensionAbility process** in blue in the figure. +- Generally, all UIAbility, ServiceExtensionAbility, and DataShareExtensionAbility components of an application (with the same bundle name) run in an independent process, which is **Main process** in green in the figure. +- All ExtensionAbility components of the same type (except ServiceExtensionAbility and DataShareExtensionAbility) of an application (with the same bundle name) run in an independent process, such as **FormExtensionAbility process**, **InputMethodExtensionAbility process**, and other **ExtensionAbility process** in blue in the figure. - WebView has an independent render process, which is **Render process** in yellow in the figure. > **NOTE** @@ -23,7 +23,7 @@ The process model is shown below. > - You can create ServiceExtensionAbility and DataShareExtensionAbility only for system applications. > - To view information about all running processes, run the **hdc shell** command to enter the shell CLI of the device, and run the **ps -ef** command. -A system application can apply for multi-process permissions (as shown in the following figure) and configure a custom process for an HAP. UIAbility, DataShareExtensionAbility, and ServiceExtensionAbility in the HAP run in the custom process. Different HAPs run in different processes by configuring different process names. +A system application can apply for multi-process permissions (as shown in the following figure) and configure a custom process for an HAP. In this way, the UIAbilities, DataShareExtensionAbilities, and ServiceExtensionAbilities in the HAP run in the custom process. For details about how to request the permissions, see [Application Privilege Configuration](../../device-dev/subsystems/subsys-app-privilege-config-guide.md). To configure a custom process for an HAP, use **process** in [module.json5](../quick-start/module-configuration-file.md#tags-in-the-configuration-file). **Figure 2** Multi-process @@ -34,4 +34,3 @@ The system provides the following inter-process communication (IPC) mechanism: [Common Events](../basic-services/common-event/common-event-overview.md): This mechanism is used in one-to-many communication scenarios. Multiple subscribers may receive events at the same time. - diff --git a/en/application-dev/application-models/serviceextensionability.md b/en/application-dev/application-models/serviceextensionability.md index 9f63bbe670be5b1173aabbf27d41a17dcb7a5afd..3fd179811a1bc815c24d00fce74c1648574d1a25 100644 --- a/en/application-dev/application-models/serviceextensionability.md +++ b/en/application-dev/application-models/serviceextensionability.md @@ -203,7 +203,7 @@ To manually create a ServiceExtensionAbility in the DevEco Studio project, perfo ## Starting a Background Service (for System Applications Only) -A system application uses the [startServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext-sys.md#uiabilitycontextstartserviceextensionability) method to start a background service. The [onRequest()](../reference/apis-ability-kit/js-apis-app-ability-serviceExtensionAbility-sys.md#serviceextensionabilityonrequest) callback is invoked, through which the background service receives the **Want** object passed by the caller. After the background service is started, its lifecycle is independent of the client. In other words, even if the client is destroyed, the background service remains alive. Therefore, the background service must be stopped by calling [terminateSelf()](../reference/apis-ability-kit/js-apis-inner-application-serviceExtensionContext-sys.md#serviceextensioncontextterminateself) when its work is complete. Alternatively, another component can call [stopServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext-sys.md#abilitycontextstopserviceextensionability) to stop the background service. +A system application uses the [startServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext-sys.md#uiabilitycontextstartserviceextensionability) method to start a background service. The [onRequest()](../reference/apis-ability-kit/js-apis-app-ability-serviceExtensionAbility-sys.md#serviceextensionabilityonrequest) callback is invoked, through which the background service receives the [Want](../reference/apis-ability-kit/js-apis-app-ability-want.md) object passed by the caller. After the background service is started, its lifecycle is independent of the client. In other words, even if the client is destroyed, the background service remains alive. Therefore, the background service must be stopped by calling [terminateSelf()](../reference/apis-ability-kit/js-apis-inner-application-serviceExtensionContext-sys.md#serviceextensioncontextterminateself) when its work is complete. Alternatively, another component can call [stopServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext-sys.md#abilitycontextstopserviceextensionability) to stop the background service. > **NOTE** > **startServiceExtensionAbility()**, **stopServiceExtensionAbility()**, and **terminateSelf()** provided by the **ServiceExtensionContext** class are system APIs and cannot be called by third-party applications. diff --git a/en/application-dev/application-models/start-email-apps-by-mailto.md b/en/application-dev/application-models/start-email-apps-by-mailto.md index e1ec72d84d7e614dad556f2e1f6bbbf512a83011..83f5b4688358566c90d4fc114e33f899a8f7c5df 100644 --- a/en/application-dev/application-models/start-email-apps-by-mailto.md +++ b/en/application-dev/application-models/start-email-apps-by-mailto.md @@ -12,6 +12,9 @@ Typical development scenarios are as follows: - Within applications: - In a mobile application, touching a **Feedback** button may cause the application to activate the system's default email client, with the feedback email address and issue details preset. - In a mobile application, when users touch a **Share via email** button, the application can use the mailto protocol to initiate the email client, pre-populating the subject and body of the email. +> **NOTE** +> - To start an email application through mailto, the initiating application must first format the string according to the mailto protocol and then use this method to launch the email application. The email application parses the mailto string to populate fields like the sender, recipient, and email body. +> - If the initiating application already has details such as the sender, recipient, and email body, you are advised to [use startAbilityByType to start an email application](start-email-apps.md). ## Format of mailto diff --git a/en/application-dev/application-models/start-email-apps.md b/en/application-dev/application-models/start-email-apps.md index 252aeabc97cb6e1da148dd2e6c3330a622d04998..80f444392529497aece9f49c868be54325a1f449 100644 --- a/en/application-dev/application-models/start-email-apps.md +++ b/en/application-dev/application-models/start-email-apps.md @@ -1,6 +1,9 @@ # Using startAbilityByType to Start an Email Application This topic describes how to open the vertical domain panel of email applications. +> **NOTE** +> +> If the parameter from the initiating application is a mailto string, you are advised to [use mailto to start an email application](start-email-apps-by-mailto.md). Upon receiving the mailto string, the email application parses the string to fill in details like the sender, recipient, and email body. ## Parameters on the Email Application Panel @@ -15,7 +18,7 @@ If the **type** field in **startAbilityByType** is set to **mail**, **wantParam* | body | string | No | Email body. | | ability.params.stream | string[ ] | No | Email attachments (URI list of the attachments). | | ability.want.params.uriPermissionFlag | [wantConstant.Flags](../reference/apis-ability-kit/js-apis-app-ability-wantConstant.md#flags) | No | At least the read permission must be granted on the email attachments. This parameter is mandatory when **ability.params.stream** is specified.| -| sceneType | number | No | 1: Send an email. The default value is **1**. | +| sceneType | number | No | Intent scene, which indicates the purpose of the current request. 1: Send an email. The default value is **1**. | > **NOTE** > @@ -24,7 +27,7 @@ If the **type** field in **startAbilityByType** is set to **mail**, **wantParam* > * For parameters of the string[] type displayed in the vertical domain panel of email applications, all elements in the array must be encoded using **encodeURI**. ## Developing a Caller Application -1. Import the **ohos.app.ability.common** module. +1. Import the module. ```ts import { common, wantConstant } from '@kit.AbilityKit'; ``` @@ -96,7 +99,7 @@ If the **type** field in **startAbilityByType** is set to **mail**, **wantParam* 2. Parse and process the parameters transferred from the panel. ```ts - UIAbility::onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void + UIAbility.onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void ``` The **want.parameters** parameter contains the following parameters, which may be slightly different from the ones passed in by the caller. diff --git a/en/application-dev/application-models/start-express-apps.md b/en/application-dev/application-models/start-express-apps.md index b8232b27c9505442499198978b9cb012b13aa8cf..3a8a261df465449a0594ce40cc35328ba92ad38e 100644 --- a/en/application-dev/application-models/start-express-apps.md +++ b/en/application-dev/application-models/start-express-apps.md @@ -6,22 +6,21 @@ For example, in a messaging application, when a user receives a delivery trackin ## Parameters on the Express Delivery Application Panel -If the **type** field in **startAbilityByType** is set to **express**, the intent scenario of express delivery query is supported. The corresponding **wantParam** parameter contains the following properties. +If the **type** field in **startAbilityByType** is set to **express**, the intent scenario of express delivery query is supported. The corresponding **wantParam** parameter contains the following properties. | Name | Type | Mandatory| Description | | --------- | ------ | ---- | -------------------------------------- | -| sceneType | number | No | Intent. The default value is **1**. In express delivery query scenarios, set it to **1** or leave it empty.| +| sceneType | number | No | Intent scene, which indicates the purpose of the current request. The default value is **1**. In express delivery query scenarios, set it to **1** or leave it empty.| | expressNo | string | Yes | Express delivery tracking number. | ## Developing a Caller Application -1. Import the **ohos.app.ability.common** module. +1. Import the module. ```ts import { common } from '@kit.AbilityKit'; ``` - 2. Construct parameters and call the **startAbilityByType** API. ```ts @@ -86,7 +85,7 @@ If the **type** field in **startAbilityByType** is set to **express**, the inten 2. Parse parameters and perform corresponding processing. ```ts - UIAbility::onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void + UIAbility.onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void ``` The **want.uri** parameter carries the URI corresponding to **linkFeature** configured by the target application. diff --git a/en/application-dev/application-models/start-finance-apps.md b/en/application-dev/application-models/start-finance-apps.md index 91ce78c056de907eb60d160b3678bda52f117c54..bc5e9137736fe5adfb25d8268de77c7739b90bec 100644 --- a/en/application-dev/application-models/start-finance-apps.md +++ b/en/application-dev/application-models/start-finance-apps.md @@ -8,11 +8,11 @@ If the **type** field in **startAbilityByType** is set to **finance**, **wantPar | Name | Type | Mandatory| Description| | -------------------- | ------------------------------------------------------------ | -------- | -------- | -| sceneType | number | No| The options are as follows: 1: transfer; 2: credit card repayment. The default value is **1**.| +| sceneType | number | No| Intent scene, which indicates the purpose of the current request. The options are as follows: 1: transfer; 2: credit card repayment. The default value is **1**.| | bankCardNo | string | No | Bank card number.| ## Developing a Caller Application -1. Import the **ohos.app.ability.common** module. +1. Import the module. ```ts import { common } from '@kit.AbilityKit'; ``` @@ -87,7 +87,7 @@ If the **type** field in **startAbilityByType** is set to **finance**, **wantPar 2. Parse and process the parameters transferred from the panel. ```ts - UIAbility::onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void + UIAbility.onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void ``` The **want.uri** parameter carries the URI corresponding to **linkFeature** configured by the target application. diff --git a/en/application-dev/application-models/start-flight-apps.md b/en/application-dev/application-models/start-flight-apps.md index 71d86d4ed27899668a8c12e5e1d92fd4bc235d1f..af2107cf64e355f6280d83dfc5ec0ea164ce2f3c 100644 --- a/en/application-dev/application-models/start-flight-apps.md +++ b/en/application-dev/application-models/start-flight-apps.md @@ -12,7 +12,7 @@ If the **type** field in **startAbilityByType** is set to **flight**, two intent | Name | Type | Mandatory| Description | | ------------- | ------ | ---- | ------------------------------------------------------------ | - | sceneType | number | No | Intent. The default value is **1**. In scenarios of flight query by flight number, set it to **1** or leave it empty. | + | sceneType | number | No | Intent scene, which indicates the purpose of the current request. The default value is **1**. In scenarios of flight query by flight number, set it to **1** or leave it empty. | | flightNo | string | Yes | Flight number, which is a two-digit code of the airline company plus a dight.| | departureDate | string | No | Flight departure date, in the format of YYYY-MM-DD. | @@ -20,7 +20,7 @@ If the **type** field in **startAbilityByType** is set to **flight**, two intent | Name | Type | Mandatory| Description | | -------------------- | ---------------------- | ---- | -------------------------------------------------------- | - | sceneType | number | Yes | Intent. In scenarios of flight query by origin and destination, set it to **2**. | + | sceneType | number | Yes | Intent scene, which indicates the purpose of the current request. In scenarios of flight query by origin and destination, set it to **2**. | | originLocation | string | Yes | Departure place. | | destinationLocation | string | Yes | Destination. | | departureDate | string | No | Flight departure date, in the format of YYYY-MM-DD. | @@ -28,7 +28,7 @@ If the **type** field in **startAbilityByType** is set to **flight**, two intent ## Developing a Caller Application -1. Import the **ohos.app.ability.common** module. +1. Import the module. ```ts import { common } from '@kit.AbilityKit'; ``` @@ -103,7 +103,7 @@ If the **type** field in **startAbilityByType** is set to **flight**, two intent 2. Parse parameters and perform corresponding processing. ```ts - UIAbility::onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void + UIAbility.onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void ``` The **want.uri** parameter carries the URI corresponding to **linkFeature** configured by the target application. diff --git a/en/application-dev/application-models/start-navigation-apps.md b/en/application-dev/application-models/start-navigation-apps.md index 92c52004b84f86ee6a13b4e753f6e3a905970ac3..de6ef28da69ff35d382d57146324a79878807323 100644 --- a/en/application-dev/application-models/start-navigation-apps.md +++ b/en/application-dev/application-models/start-navigation-apps.md @@ -15,7 +15,7 @@ If the **type** field in **startAbilityByType** is set to **navigation**, three | Name | Type | Mandatory| Description | | -------------------- | ---------------------- | ---- | ---------------------------------------------------- | - | sceneType | number | No | Intent. The default value is **1**. In route planning scenarios, set it to **1** or leave it empty. | + | sceneType | number | No | Intent scene, which indicates the purpose of the current request. The default value is **1**. In route planning scenarios, set it to **1** or leave it empty. | | originName | string | No | Name of the source. | | originLatitude | number | No | Latitude of the source. | | originLongitude | number | No | Longitude of the source. | @@ -30,7 +30,7 @@ If the **type** field in **startAbilityByType** is set to **navigation**, three | Name | Type | Mandatory| Description | | -------------------- | ---------------------- | ---- | ----------------- | - | sceneType | number | Yes | Intent. Set it to **2** for navigation scenarios.| + | sceneType | number | Yes | Intent scene, which indicates the purpose of the current request. Set it to **2** for navigation scenarios.| | destinationName | string | No | Name of the destination. | | destinationLatitude | number | Yes | Latitude of the destination. | | destinationLongitude | number | Yes | Longitude of the destination. | @@ -40,21 +40,21 @@ If the **type** field in **startAbilityByType** is set to **navigation**, three | Name | Type | Mandatory| Description | | --------------- | ------ | ---- | --------------------- | - | sceneType | number | Yes | Intent. Set it to **3** for place search scenarios.| + | sceneType | number | Yes | Intent scene, which indicates the purpose of the current request. Set it to **3** for place search scenarios.| | destinationName | string | Yes | Name of the destination. | ## Developing a Caller Application -1. Import the **ohos.app.ability.common** module. +1. Import the module. ```ts import { common } from '@kit.AbilityKit'; ``` 2. Construct parameters and call the **startAbilityByType** API. You need to obtain the POI IDs of the destination and origin from each map system and pass the parameters **destinationPoiIds** and **originPoiIds** based on the mappings. - - + + ```ts let context = getContext(this) as common.UIAbilityContext; let wantParam: Record = { @@ -63,10 +63,10 @@ If the **type** field in **startAbilityByType** is set to **navigation**, three 'destinationLongitude': 118.78315, 'destinationName': 'No.xx, xx Road, xx City', 'destinationPoiIds': { - 1: '1111', // Key 1 indicates Petal Maps, and the value must be a POI in Petal Maps. + 1:'1111', // Key 1 indicates Petal Maps, and the value must be a POI in Petal Maps. 2:'2222' // Key 2 indicates AutoNavi Map, and the value must be a POI in AutoNavi Map. } as Record, - 'originName': 'xx Park in xx City', + 'originName': 'xx Park in xx City', 'originLatitude': 31.060844, 'originLongitude': 120.78315, 'originPoiIds': { @@ -108,44 +108,43 @@ If the **type** field in **startAbilityByType** is set to **navigation**, three | RoutePlan | The application supports route planning. | | PlaceSearch | The application supports place search. | 2. Set **scheme**, **host**, **port**, and **path** or **pathStartWith** to match the URIs in Want to distinguish different features. - - ```json - { - "abilities": [ + ```json + { + "abilities": [ + { + "skills": [ { - "skills": [ + "uris": [ + { + "scheme": "maps", // It is for reference only. Ensure that the declared URI can be started by external systems. + "host": "navigation", + "path": "", + "linkFeature": "Navigation" // Declare that the application supports navigation. + }, + { + "scheme": "maps", // It is for reference only. Ensure that the declared URI can be started by external systems. + "host": "routePlan", + "path": "", + "linkFeature": "RoutePlan" // Declare that the application supports route planning. + }, { - "uris": [ - { - "scheme": "maps", // It is for reference only. Ensure that the declared URI can be started by external systems. - "host": "navigation", - "path": "", - "linkFeature": "Navigation" // Declare that the application supports navigation. - }, - { - "scheme": "maps", // It is for reference only. Ensure that the declared URI can be started by external systems. - "host": "routePlan", - "path": "", - "linkFeature": "RoutePlan" // Declare that the application supports route planning. - }, - { - "scheme": "maps", // It is for reference only. Ensure that the declared URI can be started by external systems. - "host": "search", - "path": "", - "linkFeature": "PlaceSearch" // Declare that the application supports place search. - } - ] + "scheme": "maps", // It is for reference only. Ensure that the declared URI can be started by external systems. + "host": "search", + "path": "", + "linkFeature": "PlaceSearch" // Declare that the application supports place search. } ] } ] - } - ``` - + } + ] + } + ``` + 2. Parse parameters and perform corresponding processing. ```ts - UIAbility::onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void + UIAbility.onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void ``` The **want.uri** parameter carries the URI corresponding to **linkFeature** configured by the target application. @@ -181,7 +180,7 @@ If the **type** field in **startAbilityByType** is set to **navigation**, three | --------------- | ------ | ---- | -------- | | destinationName | string | Yes | Name of the destination.| - The application can develop different style pages based on the features defined in [linkFeature](../quick-start/module-configuration-file.md#skills), such as route planning, navigation, and place search, as well as the received URI and parameters. +The application can develop different style pages based on the features defined in [linkFeature](../quick-start/module-configuration-file.md#skills), such as route planning, navigation, and place search, as well as the received URI and parameters. **Sample Code** diff --git a/en/application-dev/application-models/storage-switch.md b/en/application-dev/application-models/storage-switch.md index 9a32ebd60f84f7553d906948a1982d7fa82a5869..806f137a7f88401890085c1ba149e05a4ecbd767 100644 --- a/en/application-dev/application-models/storage-switch.md +++ b/en/application-dev/application-models/storage-switch.md @@ -1,15 +1,13 @@ # Storage Switching -| API in the FA Model| Corresponding .d.ts File in the Stage Model| Corresponding API in the Stage Model| + | API in the FA Model| Corresponding .d.ts File in the Stage Model| Corresponding API in the Stage Model| | -------- | -------- | -------- | -| GetStorageOptions | There is no corresponding API in the stage model.| The stage model uses **Prefereces** to replace **Storage** and has redesigned the input parameters.| -| SetStorageOptions | There is no corresponding API in the stage model.| The stage model uses **Prefereces** to replace **Storage** and has redesigned the input parameters.| -| ClearStorageOptions | There is no corresponding API in the stage model.| The stage model uses **Prefereces** to replace **Storage** and has redesigned the input parameters.| -| DeleteStorageOptions | There is no corresponding API in the stage model.| The stage model uses **Prefereces** to replace **Storage** and has redesigned the input parameters.| +| GetStorageOptions | There is no corresponding API in the stage model.| The stage model uses **Preferences** to replace **Storage** and has redesigned the input parameters.| +| SetStorageOptions | There is no corresponding API in the stage model.| The stage model uses **Preferences** to replace **Storage** and has redesigned the input parameters.| +| ClearStorageOptions | There is no corresponding API in the stage model.| The stage model uses **Preferences** to replace **Storage** and has redesigned the input parameters.| +| DeleteStorageOptions | There is no corresponding API in the stage model.| The stage model uses **Preferences** to replace **Storage** and has redesigned the input parameters.| | [static get(options: GetStorageOptions): void;](../reference/apis-arkdata/js-apis-system-storage.md#storageget) | \@ohos.data.preferences.d.ts | [get(key: string, defValue: ValueType, callback: AsyncCallback<ValueType>): void;](../reference/apis-arkdata/js-apis-data-preferences.md#get)
[get(key: string, defValue: ValueType): Promise<ValueType>;](../reference/apis-arkdata/js-apis-data-preferences.md#get-1) | | [static set(options: SetStorageOptions): void;](../reference/apis-arkdata/js-apis-system-storage.md#storageset) | \@ohos.data.preferences.d.ts | [put(key: string, value: ValueType, callback: AsyncCallback<void>): void;](../reference/apis-arkdata/js-apis-data-preferences.md#put)
[put(key: string, value: ValueType): Promise<void>;](../reference/apis-arkdata/js-apis-data-preferences.md#put-1) | | [static clear(options?: ClearStorageOptions): void;](../reference/apis-arkdata/js-apis-system-storage.md#storageclear) | \@ohos.data.preferences.d.ts | [clear(callback: AsyncCallback<void>): void;](../reference/apis-arkdata/js-apis-data-preferences.md#clear)
[clear(): Promise<void>;](../reference/apis-arkdata/js-apis-data-preferences.md#clear-1) | | [static delete(options: DeleteStorageOptions): void;](../reference/apis-arkdata/js-apis-system-storage.md#storagedelete) | \@ohos.data.preferences.d.ts | [delete(key: string, callback: AsyncCallback<void>): void;](../reference/apis-arkdata/js-apis-data-preferences.md#delete)
[delete(key: string): Promise<void>;](../reference/apis-arkdata/js-apis-data-preferences.md#delete-1) | - - \ No newline at end of file diff --git a/en/application-dev/application-models/thread-model-fa.md b/en/application-dev/application-models/thread-model-fa.md index e899f6d1fa25234e53a6cbc6868869f98f3759ae..5826fd43abaad7715db4864e3b2ee27756260e18 100644 --- a/en/application-dev/application-models/thread-model-fa.md +++ b/en/application-dev/application-models/thread-model-fa.md @@ -24,5 +24,3 @@ Based on the thread model, different services run on different threads. Service > **NOTE** > > The FA model provides an independent thread for each ability. Emitter is mainly used for event synchronization within the ability thread, between a pair of ability threads, or between the ability thread and worker thread. - - \ No newline at end of file diff --git a/en/application-dev/application-models/thread-model-stage.md b/en/application-dev/application-models/thread-model-stage.md index 56235db215cd47e6b3d141bbb0aa1ccf7f69d199..d7ba1fcd1dd1540cf3612a46475dcf1720f7de7d 100644 --- a/en/application-dev/application-models/thread-model-stage.md +++ b/en/application-dev/application-models/thread-model-stage.md @@ -1,5 +1,7 @@ # Thread Model (Stage Model) +A thread is the basic unit for the operating system to perform computing and scheduling. It is an execution flow within a [process](./process-model-stage.md) and shares the resources of the process. A process can contain multiple threads. + ## Thread Type There are three types of threads in the stage model: - Main thread diff --git a/en/application-dev/application-models/uiability-lifecycle.md b/en/application-dev/application-models/uiability-lifecycle.md index 0b509dfeb87337941aa62d0ae3db27043e40778c..08d709eedd5be20bbd789b34eeeb9b3457de264e 100644 --- a/en/application-dev/application-models/uiability-lifecycle.md +++ b/en/application-dev/application-models/uiability-lifecycle.md @@ -40,7 +40,7 @@ export default class EntryAbility extends UIAbility { After the [UIAbility](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md) instance is created but before it enters the Foreground state, the system creates a WindowStage instance and triggers the [onWindowStageCreate()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate) callback. You can set UI loading and WindowStage event subscription in the callback. **Figure 2** WindowStageCreate and WindowStageDestroy -![Ability-Life-Cycle-WindowStage](figures/Ability-Life-Cycle-WindowStage.png) +![Ability-Life-Cycle-WindowStage](figures/UIAbility-Life-Cycle-WindowStage.png) In the **onWindowStageCreate()** callback, use [loadContent()](../reference/apis-arkui/js-apis-window.md#loadcontent9) to set the page to be loaded, and call [on('windowStageEvent')](../reference/apis-arkui/js-apis-window.md#onwindowstageevent9) to subscribe to [WindowStage events](../reference/apis-arkui/js-apis-window.md#windowstageeventtype9), for example, having or losing focus, switching to the foreground or background, or becoming interactive or non-interactive in the foreground. @@ -146,7 +146,7 @@ export default class EntryAbility extends UIAbility { onWindowStageWillDestroy(windowStage: window.WindowStage) { // Release the resources obtained through the windowStage object. - // Unsubscribe from the WindowStage events (having or losing focus, switching to the foreground or background, or becoming interactive or non-interactive in the foreground) in the onWindowStageDestroy() callback. + // Unsubscribe from the WindowStage events (having or losing focus, switching to the foreground or background, or becoming interactive or non-interactive in the foreground) in the onWindowStageWillDestroy() callback. try { if (this.windowStage) { this.windowStage.off('windowStageEvent'); diff --git a/en/application-dev/application-models/uiability-overview.md b/en/application-dev/application-models/uiability-overview.md index 17cd69f8491e8e352791c269b81db724fd380546..89643a252c87e4e710e997e5cc224145aaaef99e 100644 --- a/en/application-dev/application-models/uiability-overview.md +++ b/en/application-dev/application-models/uiability-overview.md @@ -3,11 +3,11 @@ ## Overview -UIAbility is a type of application component that provides the UI for user interactions. +[UIAbility](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md) is a type of application component that provides the UI for user interactions. The following design philosophy is behind UIAbility: -1. Native support for cross-device migration and multi-device collaboration at the application component level +1. Support for cross-device migration and multi-device collaboration at the application component level 2. Support for multiple device types and window modes diff --git a/en/application-dev/application-models/uiability-startup-adjust.md b/en/application-dev/application-models/uiability-startup-adjust.md index c41e212a94f421698e7dd0407b8522d550df0602..c75b2710741d3075da53c809cf2f6626085edb47 100644 --- a/en/application-dev/application-models/uiability-startup-adjust.md +++ b/en/application-dev/application-models/uiability-startup-adjust.md @@ -1,8 +1,5 @@ # Switching from Explicit Want Redirection to Linking Redirection - -## Overview - Since API version 12, it is not recommended that third-party applications start other applications by specifying an ability (implicit Want mode). Instead, the [linking mode](app-startup-overview.md#application-links) is recommended. This section describes how to switch from explicit Want mode to linking mode. @@ -12,7 +9,7 @@ This section describes how to switch from explicit Want mode to linking mode. 1. Install the application on your device. In the [module.json5 file](../quick-start/module-configuration-file.md) of the UIAbility, configure **entities**, **actions**, and **uri** under **skills**. - The **actions** field must contain **ohos.want.action.viewData**. - The **entities** field must contain **entity.system.browsable**. - - The **uris** field must contain an element whose **scheme** is **https**. **domainVerify** must be set to **true**. For details about the URI matching rules, see [Matching Rules of uri](explicit-implicit-want-mappings.md#matching-rules-of-uri). If **domainVerify** is set to **true**, domain name verification is enabled. In this case, the target application must pass domain name verification during App Linking. For details about how to configure the App Linking domain name, see [Using App Linking for Application Redirection](app-linking-startup.md). + - The **uris** field must contain an element whose **scheme** is **https**. **domainVerify** must be set to **true**. For details about the URI matching rules, see [Matching Rules of uri](explicit-implicit-want-mappings.md#matching-rules-of-uri). If **domainVerify** is set to **true**, domain name verification is enabled. In this case, the target application must pass domain name verification during App Linking. For details about how to configure the App Linking domain name, see App Linking. ```json { @@ -48,8 +45,6 @@ This section describes how to switch from explicit Want mode to linking mode. - If **appLinkingOnly** in **options** is set to **true**, the target application must pass domain name verification (Internet connection required). A unique matching item or an unmatched result will be returned. - If **appLinkingOnly** in **options** is set to **false**, the system preferentially attempts to start the target application in App Linking mode. If no matching application is found, the system starts the application in Deep Linking mode. - For details, see [Using App Linking for Application Redirection](app-linking-startup.md). - ```ts import { common } from '@kit.AbilityKit'; import OpenLinkOptions from '@ohos.app.ability.OpenLinkOptions'; @@ -69,6 +64,7 @@ This section describes how to switch from explicit Want mode to linking mode. .margin({ bottom: '12vp' }) .onClick(() => { let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext; + // When using startAbility to explicitly start other UIAbilities, the openLink API is recommended. // let want: Want = { // bundleName: "com.test.example", // moduleName: "entry", @@ -113,7 +109,7 @@ This section describes how to switch from explicit Want mode to linking mode. - The **actions** field must contain **ohos.want.action.viewData**. - The **entities** field must contain **entity.system.browsable**. - - The **uris** field must contain an element whose **scheme** is **https**. **domainVerify** must be set to **true**. For details about the URI matching rules, see [Matching Rules of uri](explicit-implicit-want-mappings.md#matching-rules-of-uri). If **domainVerify** is set to **true**, domain name verification is enabled. In this case, the target application must pass domain name verification during App Linking. For details about how to configure the App Linking domain name, see [Using App Linking for Application Redirection](app-linking-startup.md). + - The **uris** field must contain an element whose **scheme** is **https**. **domainVerify** must be set to **true**. For details about the URI matching rules, see [Matching Rules of uri](explicit-implicit-want-mappings.md#matching-rules-of-uri). If **domainVerify** is set to **true**, domain name verification is enabled. In this case, the target application must pass domain name verification during App Linking. For details about how to configure the App Linking domain name, see App Linking. ```json { @@ -145,12 +141,10 @@ This section describes how to switch from explicit Want mode to linking mode. } ``` -2. Call [openLink](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextopenlink12) to trigger redirection. The redirected-to link and [options](../reference/apis-ability-kit/js-apis-app-ability-openLinkOptions.md) must be passed in, but the bundle name, module name, and ability name are not required. The system matches the application that meets the skills configuration based on the link. **AbilityResult** is transferred to the callback function through input parameters and returned to the caller application when the ability is terminated. The startup success or failure result is returned through a promise. +2. Call [openLink](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextopenlink12) to trigger redirection. The redirected-to link and [options](../reference/apis-ability-kit/js-apis-app-ability-openLinkOptions.md) must be passed in, but the bundle name, module name, and ability name are not required. The system matches the application that meets the skills configuration based on the link. **AbilityResult** is transferred to the callback function through input parameters and returned to the caller application when the ability is terminated. The startup success or failure result is returned through a promise.
- If **appLinkingOnly** in **options** is set to **true**, the target application must pass domain name verification (Internet connection required). A unique matching item or an unmatched result will be returned. - If **appLinkingOnly** in **options** is set to **false**, the system preferentially attempts to start the target application in App Linking mode. If no matching application is found, the system starts the application in Deep Linking mode. - For details, see [Using App Linking for Application Redirection](app-linking-startup.md). - ```ts import { common } from '@kit.AbilityKit'; import OpenLinkOptions from '@ohos.app.ability.OpenLinkOptions'; @@ -170,6 +164,7 @@ This section describes how to switch from explicit Want mode to linking mode. .margin({ bottom: '12vp' }) .onClick(() => { let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext; + // When using startAbility to explicitly start other UIAbilities, the openLink API is recommended. // let want: Want = { // bundleName: "com.test.example", // moduleName: "entry", diff --git a/en/application-dev/application-models/uiserviceextension-sys.md b/en/application-dev/application-models/uiserviceextension-sys.md index 726c76bb3b2ebbc939744f4c357d018c90a7e28b..2e11ac17059809df92a7f983e4531f46d77ec8ef 100644 --- a/en/application-dev/application-models/uiserviceextension-sys.md +++ b/en/application-dev/application-models/uiserviceextension-sys.md @@ -7,8 +7,8 @@ In this document, the component that starts or connects to a UIServiceExtensionAbility is called the client, and the UIServiceExtensionAbility is called the server. An application can use a UIServiceExtensionAbility in two modes: -- Call [startUIServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartuiserviceextensionability13) in the [UIAbilityContext](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md), [UIExtensionContext](../reference/apis-ability-kit/js-apis-inner-application-uiExtensionContext.md), or [ServiceExtensionContext](../reference/apis-ability-kit/js-apis-inner-application-serviceExtensionContext-sys.md) class to start a UIServiceExtensionAbility. -- Call [connectUIServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextconnectuiserviceextensionability13) in the [UIAbilityContext](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md) or [UIExtensionContext](../reference/apis-ability-kit/js-apis-inner-application-uiExtensionContext.md) class to connect to a UIServiceExtensionAbility. +- Call [startUIServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartuiserviceextensionability14) in the [UIAbilityContext](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md), [UIExtensionContext](../reference/apis-ability-kit/js-apis-inner-application-uiExtensionContext.md), or [ServiceExtensionContext](../reference/apis-ability-kit/js-apis-inner-application-serviceExtensionContext-sys.md) class to start a UIServiceExtensionAbility. +- Call [connectUIServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextconnectuiserviceextensionability14) in the [UIAbilityContext](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md) or [UIExtensionContext](../reference/apis-ability-kit/js-apis-inner-application-uiExtensionContext.md) class to connect to a UIServiceExtensionAbility. Note the following: @@ -37,7 +37,7 @@ The UIServiceExtensionAbility provides the following lifecycle callbacks: [onCre - **onRequest** - This callback is invoked when another component calls [startUIServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartuiserviceextensionability13) to start a UIServiceExtensionAbility. After this callback is invoked, the UIServiceExtensionAbility is started and runs in the foreground. This callback is invoked each time [startUIServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartuiserviceextensionability13) is called. + This callback is invoked when another component calls [startUIServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartuiserviceextensionability14) to start a UIServiceExtensionAbility. After This callback is invoked, the UIServiceExtensionAbility is started and runs in the foreground. This callback is invoked each time [startUIServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartuiserviceextensionability14) is called. - **onWindowWillCreate** @@ -51,7 +51,7 @@ The UIServiceExtensionAbility provides the following lifecycle callbacks: [onCre - **onConnect** - This callback is invoked when another component calls [connectUIServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextconnectuiserviceextensionability13) to connect to a UIServiceExtensionAbility. In this callback, a remote proxy object, namely, [UIServiceHostProxy](../reference/apis-ability-kit/js-apis-inner-application-uiservicehostproxy-sys.md), is returned, through which the server communicates with the client. For the same client, if the values of **DeviceId**, **BundleName**, **ModuleName**, and **AbilityName** in the want object and the callback object are the same, [onConnect()](../reference/apis-ability-kit/js-apis-app-ability-serviceExtensionAbility-sys.md#serviceextensionabilityonconnect) is invoked only for the first connection. If any of them is different, [onConnect()](../reference/apis-ability-kit/js-apis-app-ability-serviceExtensionAbility-sys.md#serviceextensionabilityonconnect) is invoked again. + This callback is invoked when another component calls [connectUIServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextconnectuiserviceextensionability14) to connect to a UIServiceExtensionAbility. In this callback, a remote proxy object, namely, [UIServiceHostProxy](../reference/apis-ability-kit/js-apis-inner-application-uiservicehostproxy-sys.md), is returned, through which the server communicates with the client. For the same client, if the values of **DeviceId**, **BundleName**, **ModuleName**, and **AbilityName** in the want object and the callback object are the same, [onConnect()](../reference/apis-ability-kit/js-apis-app-ability-serviceExtensionAbility-sys.md#serviceextensionabilityonconnect) is invoked only for the first connection. If any of them is different, [onConnect()](../reference/apis-ability-kit/js-apis-app-ability-serviceExtensionAbility-sys.md#serviceextensionabilityonconnect) is invoked again. - **onData** @@ -59,7 +59,7 @@ The UIServiceExtensionAbility provides the following lifecycle callbacks: [onCre - **onDisconnect** - This callback is invoked when the connection is interrupted, which occurs when the client exits or [disconnectServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextdisconnectuiserviceextensionability13) is called. + This callback is invoked when the connection is interrupted, which occurs when the client exits or [disconnectServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextdisconnectuiserviceextensionability14) is called. - **onDestroy** @@ -79,7 +79,7 @@ Only system applications can implement a UIServiceExtensionAbility. You must mak To manually create a UIServiceExtensionAbility in a project in DevEco Studio, perform the following steps: -1. In the **ets** directory of a module in the project, right-click and choose **New > Directory** to create a directory named **UIServiceExt**. +1. In the **ets** directory of the target module, right-click and choose **New > Directory** to create a directory named [UIServiceExtension](../reference/apis-ability-kit/js-apis-app-ability-uiServiceExtensionAbility-sys.md). 2. In the **UIServiceExt** directory, right-click and choose **New > ArkTS File** to create a file named **UIServiceExt.ets**. @@ -171,7 +171,7 @@ To manually create a UIServiceExtensionAbility in a project in DevEco Studio, pe ### Starting a UIServiceExtensionAbility -An application calls [startUIServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartuiserviceextensionability13) to start a UIServiceExtensionAbility. The [onRequest()](../reference/apis-ability-kit/js-apis-app-ability-uiServiceExtensionAbility-sys.md#uiserviceextensionabilityonrequest) callback is invoked, through which the background service receives the **Want** object passed by the caller. Once the UIServiceExtensionAbility is started, its lifecycle is independent of the client. In other words, even if the client is destroyed, the background service remains alive. However, the service is destroyed if the window fails to be created or is destroyed. Therefore, the background service must be stopped by calling [terminateSelf()](../reference/apis-ability-kit/js-apis-inner-application-uiserviceExtensionContext-sys.md#uiserviceextensioncontextterminateself13) of [UIServiceExtensionContext](../reference/apis-ability-kit/js-apis-inner-application-uiserviceExtensionContext-sys.md) when its work is complete. +An application calls [startUIServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartuiserviceextensionability14) to start a UIServiceExtensionAbility. The [onRequest()](../reference/apis-ability-kit/js-apis-app-ability-uiServiceExtensionAbility-sys.md#uiserviceextensionabilityonrequest) callback is invoked, through which the background service receives the **Want** object passed by the caller. Once the UIServiceExtensionAbility is started, its lifecycle is independent of the client. In other words, even if the client is destroyed, the background service remains alive. However, the service is destroyed if the window fails to be created or is destroyed. Therefore, the background service must be stopped by calling [terminateSelf()](../reference/apis-ability-kit/js-apis-inner-application-uiserviceExtensionContext-sys.md#uiserviceextensioncontextterminateself13) of [UIServiceExtensionContext](../reference/apis-ability-kit/js-apis-inner-application-uiserviceExtensionContext-sys.md) when its work is complete. Start a new UIServiceExtensionAbility in a system application. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). @@ -214,11 +214,11 @@ struct Index { ### Connecting to a UIServiceExtensionAbility -An application can use [connectUIServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextconnectuiserviceextensionability13) to connect to a service (specified in the [Want](../reference/apis-ability-kit/js-apis-app-ability-want.md) object). The [onConnect()](../reference/apis-ability-kit/js-apis-app-ability-serviceExtensionAbility-sys.md#serviceextensionabilityonconnect) callback is invoked, through which the service receives the [Want](../reference/apis-ability-kit/js-apis-app-ability-want.md) object passed by the caller. In this way, a connection is established. +An application can use [connectUIServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextconnectuiserviceextensionability14) to connect to a service (specified in the [Want](../reference/apis-ability-kit/js-apis-app-ability-want.md) object). The [onConnect()](../reference/apis-ability-kit/js-apis-app-ability-serviceExtensionAbility-sys.md#serviceextensionabilityonconnect) callback is invoked, through which the service receives the [Want](../reference/apis-ability-kit/js-apis-app-ability-want.md) object passed by the caller. In this way, a connection is established. -When the client calls [connectUIServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextconnectuiserviceextensionability13) to connect to the server, the client receives a [UIServiceProxy](../reference/apis-ability-kit/js-apis-inner-application-uiserviceproxy.md) object returned by the server and saves it. Through this proxy object, the client sends data to the server, and disconnects from the server by calling [disconnectServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextdisconnectuiserviceextensionability13). +When the client calls [connectUIServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextconnectuiserviceextensionability14) to connect to the server, the client receives a [UIServiceProxy](../reference/apis-ability-kit/js-apis-inner-application-uiserviceproxy.md) object returned by the server and saves it. Through this proxy object, the client sends data to the server, and disconnects from the server by calling [disconnectServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextdisconnectuiserviceextensionability14). -- Call [connectUIServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextconnectuiserviceextensionability13) to connect to a UIServiceExtensionAbility. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). +- Call [connectUIServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextconnectuiserviceextensionability14) to connect to a UIServiceExtensionAbility. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). ```ts import { common, Want } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; @@ -262,7 +262,7 @@ When the client calls [connectUIServiceExtensionAbility()](../reference/apis-abi } ``` -- Call [disconnectUIServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextdisconnectuiserviceextensionability13) to disconnect from a UIServiceExtensionAbility. +- Call [disconnectUIServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextdisconnectuiserviceextensionability14) to disconnect from a UIServiceExtensionAbility. ```ts import { common } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; @@ -297,7 +297,7 @@ When the client calls [connectUIServiceExtensionAbility()](../reference/apis-abi After a UIServiceExtensionAbility is started, the following operations are possible: -1. The client calls [connectUIServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiExtensionContext.md#uiextensioncontextconnectuiserviceextensionability13) to obtain a [UIServiceProxy](../reference/apis-ability-kit/js-apis-inner-application-uiserviceproxy.md) object, through which it can send data to the server. +1. The client calls [connectUIServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiExtensionContext.md#uiextensioncontextconnectuiserviceextensionability14) to obtain a [UIServiceProxy](../reference/apis-ability-kit/js-apis-inner-application-uiserviceproxy.md) object, through which it can send data to the server. 2. The server obtains a [UIServiceHostProxy](../reference/apis-ability-kit/js-apis-inner-application-uiservicehostproxy-sys.md) object through the [onConnect()](../reference/apis-ability-kit/js-apis-app-ability-uiServiceExtensionAbility-sys.md#uiserviceextensionabilityonconnect) callback and sends data to the client through this proxy. ![UIServiceExtensionAbility-bidirectionalcommunication](figures/UIServiceExtension-bidirectionalcommunication.png) @@ -306,7 +306,7 @@ After a UIServiceExtensionAbility is started, the following operations are possi ### Communication Between the Client and Server - Data transmission on the client - The client connects to the server through [connectUIServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiExtensionContext.md#uiextensioncontextconnectuiserviceextensionability13) and obtains a [UIServiceProxy](../reference/apis-ability-kit/js-apis-inner-application-uiserviceproxy.md) object. The client calls [sendData()](../reference/apis-ability-kit/js-apis-inner-application-uiserviceproxy.md#uiserviceproxysenddata) of the proxy object to send data to the server. The server receives data through the [onData()](../reference/apis-ability-kit/js-apis-app-ability-uiServiceExtensionAbility-sys.md#uiserviceextensionabilityondata) callback. + The client connects to the server through [connectUIServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiExtensionContext.md#uiextensioncontextconnectuiserviceextensionability14) and obtains a [UIServiceProxy](../reference/apis-ability-kit/js-apis-inner-application-uiserviceproxy.md) object. The client calls [sendData()](../reference/apis-ability-kit/js-apis-inner-application-uiserviceproxy.md#uiserviceproxysenddata) of the proxy object to send data to the server. The server receives data through the [onData()](../reference/apis-ability-kit/js-apis-app-ability-uiServiceExtensionAbility-sys.md#uiserviceextensionabilityondata) callback. ```ts import { common, Want} from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; diff --git a/en/application-dev/application-models/uiserviceextension.md b/en/application-dev/application-models/uiserviceextension.md index 19f25a7fc5f8e6f60f62aa41bf21ca944d08aa39..eb8ab998d06b3291b3d71e9f0842edd3f87c7fd4 100644 --- a/en/application-dev/application-models/uiserviceextension.md +++ b/en/application-dev/application-models/uiserviceextension.md @@ -7,8 +7,8 @@ UIServiceExtensionAbility is an [ExtensionAbility](../reference/apis-ability-kit In this document, the component that starts or connects to a UIServiceExtensionAbility is called the client, and the UIServiceExtensionAbility is called the server. An application can use a UIServiceExtensionAbility in two modes: -- Call [startUIServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartuiserviceextensionability13) in the [UIExtensionContext](../reference/apis-ability-kit/js-apis-inner-application-uiExtensionContext.md) class to start a UIServiceExtensionAbility. -- Call [connectUIServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextconnectuiserviceextensionability13) in the [UIAbilityContext](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md) or [UIExtensionContext](../reference/apis-ability-kit/js-apis-inner-application-uiExtensionContext.md) class to connect to a UIServiceExtensionAbility. +- Call [startUIServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartuiserviceextensionability14) in the [UIExtensionContext](../reference/apis-ability-kit/js-apis-inner-application-uiExtensionContext.md) class to start a UIServiceExtensionAbility. +- Call [connectUIServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextconnectuiserviceextensionability14) in the [UIAbilityContext](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md) or [UIExtensionContext](../reference/apis-ability-kit/js-apis-inner-application-uiExtensionContext.md) class to connect to a UIServiceExtensionAbility. > **NOTE** @@ -22,7 +22,7 @@ An application can use a UIServiceExtensionAbility in two modes: ## Starting a UIServiceExtensionAbility -An application (client) calls [startUIServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartuiserviceextensionability13) to start a UIServiceExtensionAbility. Once the UIServiceExtensionAbility is started, its lifecycle is independent of the client. Even if the client is destroyed, the background service remains alive. However, the service is destroyed if the window fails to be created or is destroyed. +An application (client) calls [startUIServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartuiserviceextensionability14) to start a UIServiceExtensionAbility. Once the UIServiceExtensionAbility is started, its lifecycle is independent of the client. Even if the client is destroyed, the background service remains alive. However, the service is destroyed if the window fails to be created or is destroyed. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). @@ -65,7 +65,7 @@ struct Index { ## Connecting to a UIServiceExtensionAbility -The client connects to the server through [connectUIServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextconnectuiserviceextensionability13) and obtains a [UIServiceProxy](../reference/apis-ability-kit/js-apis-inner-application-uiserviceproxy.md) object. The client calls [sendData()](../reference/apis-ability-kit/js-apis-inner-application-uiserviceproxy.md#uiserviceproxysenddata) of the proxy object to send data to the server. The server calls the system API **onData()** of the UIServiceExtensionAbility class to receive data from the client. +The client connects to the server through [connectUIServiceExtensionAbility()](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextconnectuiserviceextensionability14) and obtains a [UIServiceProxy](../reference/apis-ability-kit/js-apis-inner-application-uiserviceproxy.md) object. The client calls [sendData()](../reference/apis-ability-kit/js-apis-inner-application-uiserviceproxy.md#uiserviceproxysenddata) of the proxy object to send data to the server. The server calls the system API **onData()** of the UIServiceExtensionAbility class to receive data from the client. ```ts diff --git a/en/application-dev/application-test/Readme-EN.md b/en/application-dev/application-test/Readme-EN.md index e7f7280007a0540f9eb12178adfad4359ec08989..4364e57f6ca6fe8e433d893d157db6c2266250fa 100644 --- a/en/application-dev/application-test/Readme-EN.md +++ b/en/application-dev/application-test/Readme-EN.md @@ -1,4 +1,4 @@ -# Test Kit (Application Test Service) +# Test Kit - [arkXtest User Guide](arkxtest-guidelines.md) - [SmartPerf User Guide](smartperf-guidelines.md) diff --git a/en/application-dev/application-test/arkxtest-guidelines.md b/en/application-dev/application-test/arkxtest-guidelines.md index 1134dff3e3e4e55785a9c6cd5380be054f04c79c..6b6687d521c77c7dadcf4a1266b90685991a3e86 100644 --- a/en/application-dev/application-test/arkxtest-guidelines.md +++ b/en/application-dev/application-test/arkxtest-guidelines.md @@ -203,7 +203,7 @@ The table below lists the keywords in **aa** test commands. | Keyword | Abbreviation| Description | Example | | ------------- | ------------ | -------------------------------------- | ---------------------------------- | -| --bundleName | -b | Application bundle name. | - b com.test.example | +| --bundleName | -b | Application bundle name. | - b com.test.example | | --packageName | -p | Application module name, which is applicable to applications developed in the FA model. | - p com.test.example.entry | | --moduleName | -m | Application module name, which is applicable to applications developed in the stage model. | -m entry | | NA | -s | \ pair.| - s unittest /ets/testrunner/OpenHarmonyTestRunner | @@ -213,7 +213,7 @@ The framework supports multiple test case execution modes, which are triggered b | Name | Description | Value | Example | | ------------ | ----------------------------------------------------------------------------- | ------------------------------------------------------------ | ----------------------------------------- | | unittest | **OpenHarmonyTestRunner** object used for test case execution. | **OpenHarmonyTestRunner** or custom runner name. | - s unittest OpenHarmonyTestRunner | -| class | Test suite or test case to be executed. | {describeName}#{itName}, {describeName} | -s class attributeTest#testAttributeIt | +| class | Test suite or test case to be executed. | {describeName}#{itName}, {describeName} | -s class attributeTest#testAttributeIt | | notClass | Test suite or test case that does not need to be executed. | {describeName}#{itName}, {describeName} | -s notClass attributeTest#testAttributeIt | | itName | Test case to be executed. | {itName} | -s itName testAttributeIt | | timeout | Timeout interval for executing a test case. | Positive integer (unit: ms). If no value is set, the default value **5000** is used. | -s timeout 15000 | @@ -421,7 +421,7 @@ The following describes the fields in the recording data: "MAX_VEL": "40000", // Maximum velocity. "VELO": "0.000000", // Hands-off velocity. "W1_BOUNDS": "{"bottom":361,"left":37,"right":118,"top":280}", // Starting component bounds. - "W1_HIER": "ROOT,3,0,0,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,0", // Starting component hierarchy. + "W1_HIER": "ROOT,3,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0", // Starting component hierarchy. "W1_ID": "", // ID of the starting component. "W1_Text": "", // Text of the starting component. "W1_Type": "Image", // Type of the starting component. @@ -443,18 +443,19 @@ The following describes the fields in the recording data: ### Injecting Simulated UI Operations -| Command | Mandatory| Description | +| Command | Mandatory| Description | |------|------|-----------------| | help | Yes | Displays help information about the uiInput commands.| -| click | Yes | Simulates a click event. | -| doubleClick | Yes | Simulates a double-click event. | -| longClick | Yes | Simulates a long-click event. | -| fling | Yes | Simulates a fling event. | -| swipe | Yes | Simulates a swipe event. | -| drag | Yes | Simulates a drag event. | +| click | Yes | Simulates a click event. | +| doubleClick | Yes | Simulates a double-click event. | +| longClick | Yes | Simulates a long-click event. | +| fling | Yes | Simulates a fling event. | +| swipe | Yes | Simulates a swipe event. | +| drag | Yes | Simulates a drag event. | | dircFling | Yes | Simulates a directional fling event. | -| inputText | Yes | Simulates a text input event. | -| keyEvent | Yes | Simulates a physical key event (such as pressing a keyboard key, pressing the power key, returning to the previous page, or returning to the home screen) or a key combination. | +| inputText | Yes | Simulates text input in a text box at specified coordinates. | +| text | Yes | Simulates text input in a text box at the focused position without specifying coordinates. | +| keyEvent | Yes | Simulates a physical key event (such as pressing a keyboard key, pressing the power key, returning to the previous page, or returning to the home screen) or a key combination. | #### Example of Running the click/doubleClick/longClick Commands @@ -477,30 +478,30 @@ hdc shell uitest uiInput longClick 100 100 #### Example of Running the uiInput fling Command -| Parameter | Mandatory | Description | +| Parameter | Mandatory | Description | |------|------------------|-----------------| -| from_x | Yes | The x-coordinate of the start point.| -| from_y | Yes | The y-coordinate of the start point.| +| from_x | Yes | The x-coordinate of the start point.| +| from_y | Yes | The y-coordinate of the start point.| | to_x | Yes | The x-coordinate of the stop point.| | to_y | Yes | The y-coordinate of the stop point.| -| swipeVelocityPps_ | No | Swipe speed, in px/s. Value range: 200 to 40000.
The default value is 600.| -| stepLength_ | No| The step length. The default value is the sliding distance divided by 50.
To achieve better simulation effect, you are advised to use the default values. | +| swipeVelocityPps_ | No | Swipe speed, in px/s. The value ranges from 200 to 40000.
The default value is **600**.| +| stepLength_ | No| Step length. The default value is the swipe distance divided by 50.
To achieve better simulation effect, you are advised to use the default value. | ```shell # Execute the fling event. The default value of stepLength_ is used. hdc shell uitest uiInput fling 10 10 200 200 500 -``` +``` #### Example of Running the uiInput swipe/drag Command -| Parameter | Mandatory | Description | +| Parameter | Mandatory | Description | |------|------------------|-----------------| -| from_x | Yes | The x-coordinate of the start point.| -| from_y | Yes | The y-coordinate of the start point.| +| from_x | Yes | The x-coordinate of the start point.| +| from_y | Yes | The y-coordinate of the start point.| | to_x | Yes | The x-coordinate of the stop point.| | to_y | Yes | The y-coordinate of the stop point.| -| swipeVelocityPps_ | No | Swipe speed, in px/s. Value range: 200 to 40000.
The default value is 600.| +| swipeVelocityPps_ | No | Swipe speed, in px/s. Value range: 200 to 40000.
The default value is 600.| ```shell # Execute the swipe event. @@ -514,9 +515,9 @@ hdc shell uitest uiInput drag 10 10 100 100 500 | Parameter | Mandatory | Description| |-------------------|-------------|----------| -| direction | No| Fling direction, which can be **0**, **1**, **2**, or **3**. The default value is **0**.
The value **0** indicates leftward fling, **1** indicates rightward fling, **2** indicates upward fling, and **3** indicates downward fling. | -| swipeVelocityPps_ | No| Swipe speed, in px/s. Value range: 200 to 40000.
The default value is 600. | -| stepLength | No | The step length.
The default value is the sliding distance divided by 50. To achieve better simulation effect, you are advised to use the default values.| +| direction | No| Fling direction, which can be **0**, **1**, **2**, or **3**. The default value is **0**.
The value **0** indicates leftward fling, **1** indicates rightward fling, **2** indicates upward fling, and **3** indicates downward fling. | +| swipeVelocityPps_ | No| Swipe speed, in px/s. Value range: 200 to 40000.
The default value is 600. | +| stepLength | No | Step length.
The default value is the swipe distance divided by 50. To achieve better simulation effect, you are advised to use the default value.| ```shell # Execute the leftward fling event. @@ -531,9 +532,9 @@ hdc shell uitest uiInput dircFling 3 #### Example of Running the uiInput inputText Command -| Parameter | Mandatory | Description| +| Parameter | Mandatory | Description| |------|------------------|----------| -| point_x | Yes | The x-coordinate of the input box.| +| point_x | Yes | The x-coordinate of the input box.| | point_y | Yes | The y-coordinate of the input box.| | text | Yes | Text in the input box. | @@ -542,11 +543,22 @@ hdc shell uitest uiInput dircFling 3 hdc shell uitest uiInput inputText 100 100 hello ``` +#### Example of Running the uiInput text Command + +| Parameter | Mandatory | Description| +|------|------------------|----------| +| text | Yes | Text in the input box. | + +```shell +# Execute the text input in the text box at the focused position. If the current focused position does not support text input, no effect is displayed. +hdc shell uitest uiInput text hello +``` + #### Example of Running the uiInput keyEvent Command -| Parameter | Mandatory | Description| +| Parameter | Mandatory | Description| |------|------|----------| -| keyID1 | Yes | ID of a physical key, which can be **KeyCode**, **Back**, **Home**, or **Power**.
When the value is set to **Back**, **Home**, or **Power**, the combination keys are not supported.| +| keyID1 | Yes | ID of a physical key, which can be **KeyCode**, **Back**, **Home**, or **Power**.
When the value is set to **Back**, **Home**, or **Power**, the combination keys are not supported.| | keyID2 | No | ID of a physical key.| | keyID3 | No | ID of a physical key.| @@ -580,7 +592,7 @@ hdc shell uitest start-daemon > > Only the test HAP started by the **aa test** ability can call the ability of the UiTest. > -> The [Ability Privilege Level (APL)](../security/AccessToken/app-permission-mgmt-overview.md#basic-concepts-in-the-permission-mechanism) of the test HAP must be **system_basic** or **normal**. +> The [Ability Privilege Level (APL)](../security/AccessToken/app-permission-mgmt-overview.md#basic-concepts-in-the-permission-mechanism) of the test HAP must be **system_basic** or **normal**. ## Examples @@ -645,7 +657,7 @@ For details about how to simulate a window size adjustment and direction specifi ### FAQs About Unit Test Cases -1. The logs in the test case are printed after the test case result +**1. What should I do if logs in the test case are printed after the test case result?** **Problem** @@ -659,7 +671,7 @@ More than one asynchronous API is called in the test case.
In principle, logs If more than one asynchronous API is called, you are advised to encapsulate the API invoking into the promise mode. -**Error "fail to start ability" is reported during test case execution** +**2. What should I do if the message "error: fail to start ability" is reported during test case execution?** **Problem** @@ -673,7 +685,7 @@ An error occurs during the packaging of the test package, and the test framework Check whether the test package contains the **OpenHarmonyTestRunner.abc** file. If the file does not exist, rebuild and pack the file and perform the test again. -Test case execution timeout +**3. What should I do if a timeout error is reported during case execution?** **Problem** @@ -681,7 +693,7 @@ After the test case execution is complete, the console displays the error messag **Possible Causes** -1. The test case is executed through an asynchronous interface, but the **done** function is not executed during the execution. As a result, the test case execution does not end until it times out. +1. The test case is executed through an asynchronous API, but the **done** function is not executed during the execution. As a result, the test case execution does not end until it times out. 2. The time taken for API invocation is longer than the timeout interval set for test case execution. @@ -696,7 +708,7 @@ After the test case execution is complete, the console displays the error messag 3. Check the code logic and assertion result of the test case and make sure that the assertion is passed. ### FAQs About UI Test Cases -**The failure log contains "Get windows failed/GetRootByWindow failed"** +**1. What should I do if the failure log contains "Get windows failed/GetRootByWindow failed"?** **Problem** @@ -714,7 +726,7 @@ Run the following command, restart the device, and execute the test case again: hdc shell param set persist.ace.testmode.enabled 1 ``` -**The failure log contains "uitest-api does not allow calling concurrently"** +**2. What should I do if the failure log contains "uitest-api does not allow calling concurrently"?** **Problem** @@ -732,7 +744,7 @@ The UI test case fails to be executed. The HiLog file contains the error message 2. Do not execute UI test cases in multiple processes. -The failure log contains "does not exist on current UI! Check if the UI has changed after you got the widget object". +**3. What should I do if the failure log contains "does not exist on current UI! Check if the UI has changed after you got the widget object"?** **Problem** diff --git a/en/application-dev/application-test/smartperf-guidelines.md b/en/application-dev/application-test/smartperf-guidelines.md index 958ff96098f078721176d544292b6fa0cf027cd6..87397233cf85535de299b8f20aa091866c459ba4 100644 --- a/en/application-dev/application-test/smartperf-guidelines.md +++ b/en/application-dev/application-test/smartperf-guidelines.md @@ -4,9 +4,9 @@ SmartPerf Device is a reliable, easy-to-use performance and power consumption test tool. In this tool, you can monitor the performance and power consumption of your application and device with quantitative indicators, such as FPS, CPU, GPU, RAM, and Temp. -Targeted at devices with or without screens, SmartPerf Device provides two modes: Device-hap and Device-daemon. Device-hap is applicable to devices with screens and provides a visualized, intuitive UI that simplifies your operations. You can start and pause a test with a floating window, view performance data in real time, and save the test results for further analysis. Device-daemon is applicable to devices with and without screens and works with shell commands. +Targeted at devices with or without screens, SmartPerf Device provides two modes: Device-hap and Device-daemon. Device-hap is applicable to devices with screens and provides a visualized, intuitive UI that simplifies your operations. You can start and pause a test with a floating window, view performance data in real time, and save the test results for further analysis. Device-daemon is applicable to devices with and without screens and works with shell commands. -### The following are the available indicators: +### Indicators - CPU: The tool reads the frequencies and usage of CPU cores on the test device on a per second basis to measure the CPU usage of the target application. Sustained high CPU may lead to overheating. - GPU: The tool reads the GPU frequency and load information of the test device on a per second basis to measure the GPU usage of the target application. High GPU usage can lead to performance drops and application slowdowns. @@ -17,20 +17,19 @@ SmartPerf Device is a reliable, easy-to-use performance and power consumption te ## Principles -The figure below demonstrates the main functions of SmartPerf Device. Set data collection items and parameters on Device-hap, start the application, and then send data requests for KPIs (such as FPS, RAM, and Trace) from Device-hap to Device-daemon through messages. Device-daemon collects, persists, and analyzes data as requested, and then sends the data to Device-hap for display. +The figure below demonstrates the main functions of SmartPerf Device. Set data collection items and parameters on Device-hap, start the application, and then send data requests for KPIs (such as FPS, RAM, and Trace) from Device-hap to Device-daemon through messages. Device-daemon collects, persists, and analyzes data as requested, and then sends the data to Device-hap for display. ![SmartPerf](figures/SmartPerfStru.png) ## Constraints -1. Device-daemon and Device-hap are pre-installed since API version 9. +1. Device-daemon and Device-hap are pre-installed since API version 9. -2. Device-daemon must be connected to a hardware device, and Device-hap can only be used on devices with a screen. +2. Device-daemon must be connected to a hardware device, and Device-hap can only be used on devices with a screen. -3. Before using the Device-Daemon, configure the [HDC environment](https://gitee.com/openharmony/developtools_hdc). - - +3. Before using Device-Daemon, configure the [hdc environment](https://gitee.com/openharmony/developtools_hdc). + ## SmartPerf Device-hap The RK3568 development board is used as an example below. @@ -47,7 +46,7 @@ Start SmartPerf Device-hap. On the home screen, click **Select an app**. After the target application is selected, return to the start page and set the test indicators. You can also change the test name (which includes the name of the target application and the test time and will be displayed in the report), and specify whether to capture traces and whether to enable the screenshot feature. When you are done, click the **Start** button at the bottom. -### Using the Floating Window to Manage Data Collection. +### Using the Floating Window to Manage Data Collection To start collection, touch **Start** in the floating window. To pause, touch the timer in the floating window. To resume, touch the timer again. To view the collected data in real time, double-touch the timer. To stop, touch and hold the timer.
You can drag the floating window to anywhere you like. @@ -60,22 +59,19 @@ Click **Report** to access the report list. Touch a report to view its details. ![SmartPerfReport1](figures/SmartPerfReport1.png) ![SmartPerfReport2](figures/SmartPerfReport2.png) - - ## SmartPerf Device-daemon - ### Collection Prerequisites -#### Switch to shell. +#### Switching to Shell ``` C:\Users\issusser>hdc shell # ``` -#### Start and view the daemon process. +#### Starting and Viewing the daemon Process ``` C:\Users\issusser>hdc shell @@ -88,9 +84,7 @@ Click **Report** to access the report list. Touch a report to view its details. # ``` -#### View the help information. - - +#### Viewing the Help Information ``` # SP_daemon --help @@ -151,7 +145,6 @@ Click **Report** to access the report list. Touch a report to view its details. command exec finished! # ``` - ### Basic Collection @@ -164,14 +157,13 @@ Click **Report** to access the report list. Touch a report to view its details. | -c |No| Collects the CPU frequency and usage.
When the application bundle name is set, the system and application CPU information is collected.
Otherwise, only the system CPU information is collected. | | -g |No| Collects the GPU frequency and load information. | | -f |No| Collects the screen refresh rate and frame rate of the target application. The application bundle name must be specified. | -| -t |No| Collects the temperature of the GPU and system chip. | +| -t |No| Collects the temperature of GPU and system chip. | | -r |No| Collects the memory.
When the application bundle name is set, the system and application memory information is obtained.
Otherwise, only the system memory information is obtained. | -| -snapshot |No| Takes screenshots. | +| -snapshot |No| Takes a screenshot. | | -net |No| Collects the network speed. | | -VIEW |No| Sets the view layer. You must obtain the layer name first. | | -d |No| Collects the DDR data. | | -sections|No| Sets segment-based collection. | - ##### Samples @@ -180,43 +172,51 @@ Click **Report** to access the report list. Touch a report to view its details. ``` # SP_daemon -N 2 -c - order:0 timestamp=1503078645909 - order:1 cpu0Frequency=1992000 - order:2 cpu0Usage=34.042553 - order:3 cpu0idleUsage=65.957447 - order:4 cpu0ioWaitUsage=0.000000 - order:5 cpu0irqUsage=0.000000 - order:6 cpu0niceUsage=0.000000 - order:7 cpu0softIrqUsage=0.000000 - order:8 cpu0systemUsage=15.957447 - order:9 cpu0userUsage=18.085106 - order:10 cpu1Frequency=1992000 - order:11 cpu1Usage=43.877551 - order:12 cpu1idleUsage=56.122449 - order:13 cpu1ioWaitUsage=0.000000 - order:14 cpu1irqUsage=0.000000 - order:15 cpu1niceUsage=0.000000 - order:16 cpu1softIrqUsage=0.000000 - order:17 cpu1systemUsage=17.346939 - order:18 cpu1userUsage=26.530612 - order:19 cpu2Frequency=1992000 - order:20 cpu2Usage=38.043478 - order:21 cpu2idleUsage=61.956522 - order:22 cpu2ioWaitUsage=0.000000 - order:23 cpu2irqUsage=0.000000 - order:24 cpu2niceUsage=0.000000 - order:25 cpu2softIrqUsage=0.000000 - order:26 cpu2systemUsage=11.956522 - order:27 cpu2userUsage=26.086957 - order:28 cpu3Frequency=1992000 - order:29 cpu3Usage=68.421053 - order:30 cpu3idleUsage=31.578947 - order:31 cpu3ioWaitUsage=0.000000 - order:32 cpu3irqUsage=0.000000 - order:33 cpu3niceUsage=0.000000 - order:34 cpu3softIrqUsage=0.000000 - order:35 cpu3systemUsage=13.684211 - order:36 cpu3userUsage=54.736842 + order:0 timestamp=1501839064260 + order:1 TotalcpuUsage=0.502513 + order:2 TotalcpuidleUsage=99.497487 + order:3 TotalcpuioWaitUsage=0.000000 + order:4 TotalcpuirqUsage=0.000000 + order:5 TotalcpuniceUsage=0.000000 + order:6 TotalcpusoftIrqUsage=0.000000 + order:7 TotalcpusystemUsage=0.251256 + order:8 TotalcpuuserUsage=0.251256 + order:9 cpu0Frequency=1992000 + order:10 cpu0Usage=1.000000 + order:11 cpu0idleUsage=99.000000 + order:12 cpu0ioWaitUsage=0.000000 + order:13 cpu0irqUsage=0.000000 + order:14 cpu0niceUsage=0.000000 + order:15 cpu0softIrqUsage=0.000000 + order:16 cpu0systemUsage=0.000000 + order:17 cpu0userUsage=1.000000 + order:18 cpu1Frequency=1992000 + order:19 cpu1Usage=0.000000 + order:20 cpu1idleUsage=100.000000 + order:21 cpu1ioWaitUsage=0.000000 + order:22 cpu1irqUsage=0.000000 + order:23 cpu1niceUsage=0.000000 + order:24 cpu1softIrqUsage=0.000000 + order:25 cpu1systemUsage=0.000000 + order:26 cpu1userUsage=0.000000 + order:27 cpu2Frequency=1992000 + order:28 cpu2Usage=1.000000 + order:29 cpu2idleUsage=99.000000 + order:30 cpu2ioWaitUsage=0.000000 + order:31 cpu2irqUsage=0.000000 + order:32 cpu2niceUsage=0.000000 + order:33 cpu2softIrqUsage=0.000000 + order:34 cpu2systemUsage=1.000000 + order:35 cpu2userUsage=0.000000 + order:36 cpu3Frequency=1992000 + order:37 cpu3Usage=0.000000 + order:38 cpu3idleUsage=100.000000 + order:39 cpu3ioWaitUsage=0.000000 + order:40 cpu3irqUsage=0.000000 + order:41 cpu3niceUsage=0.000000 + order:42 cpu3softIrqUsage=0.000000 + order:43 cpu3systemUsage=0.000000 + order:44 cpu3userUsage=0.000000 ... @@ -227,56 +227,62 @@ Click **Report** to access the report list. Touch a report to view its details. - Collect twice the frequency and usage of CPU cores and CPU usage and load of processes. ``` - # SP_daemon -N 2 -PKG com.ohos.settings -c - - - - order:0 timestamp=1503078694916 - order:1 ProcAppName=com.ohos.settings - order:2 ProcCpuLoad=0 - order:3 ProcCpuUsage=0 - order:4 ProcId=0 - order:5 ProcSCpuUsage=0 - order:6 ProcUCpuUsage=0 - order:7 cpu0Frequency=1992000 - order:8 cpu0Usage=31.868132 - order:9 cpu0idleUsage=68.131868 - order:10 cpu0ioWaitUsage=0.000000 - order:11 cpu0irqUsage=0.000000 - order:12 cpu0niceUsage=0.000000 - order:13 cpu0softIrqUsage=0.000000 - order:14 cpu0systemUsage=15.384615 - order:15 cpu0userUsage=16.483516 - order:16 cpu1Frequency=1992000 - order:17 cpu1Usage=44.791667 - order:18 cpu1idleUsage=55.208333 - order:19 cpu1ioWaitUsage=0.000000 - order:20 cpu1irqUsage=0.000000 - order:21 cpu1niceUsage=0.000000 - order:22 cpu1softIrqUsage=0.000000 - order:23 cpu1systemUsage=13.541667 - order:24 cpu1userUsage=31.250000 - order:25 cpu2Frequency=1992000 - order:26 cpu2Usage=37.894737 - order:27 cpu2idleUsage=62.105263 - order:28 cpu2ioWaitUsage=0.000000 - order:29 cpu2irqUsage=0.000000 - order:30 cpu2niceUsage=0.000000 - order:31 cpu2softIrqUsage=1.052632 - order:32 cpu2systemUsage=13.684211 - order:33 cpu2userUsage=23.157895 - order:34 cpu3Frequency=1992000 - order:35 cpu3Usage=81.632653 - order:36 cpu3idleUsage=18.367347 - order:37 cpu3ioWaitUsage=0.000000 - order:38 cpu3irqUsage=0.000000 - order:39 cpu3niceUsage=0.000000 - order:40 cpu3softIrqUsage=0.000000 - order:41 cpu3systemUsage=15.306122 - order:42 cpu3userUsage=66.326531 + # SP_daemon -N 2 -PKG ohos.samples.ecg -c + order:0 timestamp=1501839151499 + order:1 ProcAppName=ohos.samples.ecg + order:2 ProcCpuLoad=0.000000 + order:3 ProcCpuUsage=36.177645 + order:4 ProcId=2111 + order:5 ProcSCpuUsage=8.982036 + order:6 ProcUCpuUsage=27.195609 + order:7 TotalcpuUsage=62.500000 + order:8 TotalcpuidleUsage=37.500000 + order:9 TotalcpuioWaitUsage=0.000000 + order:10 TotalcpuirqUsage=0.000000 + order:11 TotalcpuniceUsage=0.000000 + order:12 TotalcpusoftIrqUsage=0.000000 + order:13 TotalcpusystemUsage=21.614583 + order:14 TotalcpuuserUsage=40.885417 + order:15 cpu0Frequency=1992000 + order:16 cpu0Usage=77.083333 + order:17 cpu0idleUsage=22.916667 + order:18 cpu0ioWaitUsage=0.000000 + order:19 cpu0irqUsage=0.000000 + order:20 cpu0niceUsage=0.000000 + order:21 cpu0softIrqUsage=0.000000 + order:22 cpu0systemUsage=21.875000 + order:23 cpu0userUsage=55.208333 + order:24 cpu1Frequency=1992000 + order:25 cpu1Usage=57.731959 + order:26 cpu1idleUsage=42.268041 + order:27 cpu1ioWaitUsage=0.000000 + order:28 cpu1irqUsage=0.000000 + order:29 cpu1niceUsage=0.000000 + order:30 cpu1softIrqUsage=0.000000 + order:31 cpu1systemUsage=21.649485 + order:32 cpu1userUsage=36.082474 + order:33 cpu2Frequency=1992000 + order:34 cpu2Usage=59.793814 + order:35 cpu2idleUsage=40.206186 + order:36 cpu2ioWaitUsage=0.000000 + order:37 cpu2irqUsage=0.000000 + order:38 cpu2niceUsage=0.000000 + order:39 cpu2softIrqUsage=0.000000 + order:40 cpu2systemUsage=19.587629 + order:41 cpu2userUsage=40.206186 + order:42 cpu3Frequency=1992000 + order:43 cpu3Usage=55.789474 + order:44 cpu3idleUsage=44.210526 + order:45 cpu3ioWaitUsage=0.000000 + order:46 cpu3irqUsage=0.000000 + order:47 cpu3niceUsage=0.000000 + order:48 cpu3softIrqUsage=0.000000 + order:49 cpu3systemUsage=23.157895 + order:50 cpu3userUsage=32.631579 + ... - + command exec finished! # ``` @@ -286,12 +292,10 @@ Click **Report** to access the report list. Touch a report to view its details. >- Make sure you are on the application screen when running this command. - Collect once the GPU frequency and load of the system. - + ``` # SP_daemon -N 1 -g - - - + order:0 timestamp=1503078740268 order:1 gpuFrequency=200000000 order:2 gpuLoad=38.000000 @@ -304,16 +308,15 @@ Click **Report** to access the report list. Touch a report to view its details. ``` # SP_daemon -N 2 -t - + order:0 timestamp=1502720711191 order:1 gpu-thermal=42500.000000 order:2 soc-thermal=43.125000 - - + order:0 timestamp=1502720712191 order:1 gpu-thermal=41875.000000 order:2 soc-thermal=42.500000 - + command exec finished! # ``` @@ -326,12 +329,12 @@ Click **Report** to access the report list. Touch a report to view its details. order:1 memAvailable=7339224 order:2 memFree=7164708 order:3 memTotal=11641840 - + order:0 timestamp=1705041563527 order:1 memAvailable=7339136 order:2 memFree=7164684 order:3 memTotal=11641840 - + command exec finished! # ``` @@ -340,7 +343,7 @@ Click **Report** to access the report list. Touch a report to view its details. ``` # SP_daemon -N 1 -PKG ohos.samples.ecg -r - + order:0 timestamp=1720427095197 order:1 arktsHeapPss=17555 order:2 gpuPss=7021 @@ -361,7 +364,6 @@ Click **Report** to access the report list. Touch a report to view its details. order:17 swap=122076 order:18 swapPss=122076 - command exec finished! # ``` @@ -374,41 +376,37 @@ Click **Report** to access the report list. Touch a report to view its details. ``` # SP_daemon -N 2 -snapshot + + order:0 timestamp=1501837609657 + order:1 capture=data/local/tmp/capture/screenCap_1501837609657.png - order:0 timestamp=1705041753321 - order:1 capture=data/local/tmp/capture/screenCap_1705041753321.png - - /data/local/tmp/capture created! - - order:0 timestamp=1705041754324 + order:0 timestamp=1501837610657 order:1 capture=NA - + command exec finished! # ``` >**NOTE** > - >- Screenshots are collected every 2 seconds. - > - >- + >- Screenshots are collected every 2 seconds. > >- When the collection is complete, you can view the screenshots in **data/local/tmp/capture**. > - >- To export the screenshots to drive D, open a new CLI and run the **hdc file recv data/local/tmp/capture/screenCap_1700725192774.png D:\** command. + >- To export the screenshots to drive D, open a new CLI and run the **hdc file recv data/local/tmp/capture/screenCap_1700725192774.png D:\\** command. - Collect the network speeds twice. ``` # SP_daemon -N 2 -net - + order:0 timestamp=1705041904832 order:1 networkDown=0 order:2 networkUp=0 - + order:0 timestamp=1705041905870 order:1 networkDown=22931 order:2 networkUp=2004 - + command exec finished! # ``` @@ -417,27 +415,27 @@ Click **Report** to access the report list. Touch a report to view its details. ``` # SP_daemon -N 5 -PKG ohos.samples.ecg -f - + order:0 timestamp=1705306472232 order:1 fps=43 order:2 fpsJitters=602261688;;8352083;;8267708;;8305209;;8298437;;8308854;;8313542;;8569271;;8061458;;8300521;;8308333;;8309896;;8429167;;8241667;;8258333;;8318229;;8312500;;8304167;;41760937;;16418750;;8298959;;8319270;;8308334;;8313541;;8302605;;8320312;;8298958;;8326042;;8321354;;8301042;;8310417;;8309895;;8308855;;8331250;;8286458;;8343229;;8278125;;8311458;;8306250;;8312500;;8320834;;8346875;;8283333 - order:3 refreshrate=120 - + order:3 refreshrate=69 + order:0 timestamp=1705306473234 order:1 fps=40 order:2 fpsJitters=674427313;;8191145;;8310417;;8319271;;8301562;;8318750;;8302084;;8314062;;8333334;;8283854;;8307812;;8311979;;8310417;;8307813;;8309375;;8323958;;8306250;;8308333;;8317709;;8296875;;8721875;;7895833;;8320833;;8340625;;8276563;;8409896;;8216145;;8310938;;8301042;;8362500;;8252604;;8317708;;8376042;;8256250;;8292187;;8303125;;8313542;;8310417;;8520312 - order:3 refreshrate=120 + order:3 refreshrate=69 ... - + command exec finished! # ``` >**NOTE** > >- When running this command, make sure you are on the application screen, and then swipe on the screen or switch between screens. - >- When dynamic refresh rate (DRR) is enabled, the refresh rate changes in real time (multiple changes may occur within one second). The value of **refreshrate** is collected at a timestamp. + >- When dynamic refresh rate (DRR) is enabled, the refresh rate changes in real time (multiple changes may occur within one second). The value of **refreshrate** is obtained at a timestamp. + - - Collect the frame rate of the specified view layer for 10 times. ``` @@ -445,14 +443,14 @@ Click **Report** to access the report list. Touch a report to view its details. order:0 timestamp=1705306822850 order:1 fps=15 order:2 fpsJitters=876291843;;8314062;;8308334;;8314583;;8310417;;8308333;;8326042;;8314583;;8292708;;8492709;;8143750;;8340104;;8294271;;8302604;;8297396 - order:3 refreshrate=120 - + order:3 refreshrate=69 + order:0 timestamp=1705306823852 order:1 fps=12 order:2 fpsJitters=906667363;;8279167;;8311458;;8315625;;8291146;;8313021;;8323438;;8293750;;8303125;;8313541;;8301563;;8317708 - order:3 refreshrate=120 + order:3 refreshrate=69 ... - + command exec finished! # ``` @@ -475,152 +473,166 @@ Click **Report** to access the report list. Touch a report to view its details. command exec finished! # ``` - - Collect the full information of the system, including the CPU, GPU, temperature, memory, DDR, network speed, and screenshot information. - + ``` # SP_daemon -N 10 -c -g -t -r -d -net -snapshot - - order:0 timestamp=1502725274844 - order:1 cpu0Frequency=1992000 - order:2 cpu0Usage=37.634409 - order:3 cpu0idleUsage=62.365591 - order:4 cpu0ioWaitUsage=0.000000 - order:5 cpu0irqUsage=0.000000 - order:7 cpu0softIrqUsage=1.075269 - order:8 cpu0systemUsage=17.204301 - order:9 cpu0userUsage=19.354839 - order:10 cpu1Frequency=1992000 - order:11 cpu1Usage=87.878788 - order:12 cpu1idleUsage=12.121212 - order:13 cpu1ioWaitUsage=0.000000 - order:14 cpu1irqUsage=0.000000 - order:15 cpu1niceUsage=0.000000 - order:16 cpu1softIrqUsage=0.000000 - order:17 cpu1systemUsage=15.151515 - order:18 cpu1userUsage=72.727273 - order:19 cpu2Frequency=1992000 - order:20 cpu2Usage=45.544554 - order:21 cpu2idleUsage=54.455446 - order:22 cpu2ioWaitUsage=0.000000 - order:23 cpu2irqUsage=0.000000 - order:24 cpu2niceUsage=0.000000 - order:25 cpu2softIrqUsage=0.990099 - order:26 cpu2systemUsage=14.851485 - order:27 cpu2userUsage=29.702970 - order:28 cpu3Frequency=1992000 - order:29 cpu3Usage=39.175258 - order:30 cpu3idleUsage=60.824742 - order:31 cpu3ioWaitUsage=0.000000 - order:32 cpu3irqUsage=0.000000 - order:33 cpu3niceUsage=0.000000 - order:34 cpu3softIrqUsage=1.030928 - order:35 cpu3systemUsage=14.432990 - order:36 cpu3userUsage=23.711340 - order:37 gpuFrequency=300000000 - order:38 gpuLoad=25.000000 - order:39 gpu-thermal=43750.000000 - order:40 soc-thermal=45.555000 - order:41 memAvailable=1118792 - order:42 memFree=688032 - order:43 memTotal=1990104 - order:44 ddrFrequency=0 - order:45 networkDown=0 - order:46 networkUp=0 - order:47 capture=data/local/tmp/capture/screenCap_1502725274893.png - + + order:0 timestamp=1501837838664 + order:1 TotalcpuUsage=0.751880 + order:2 TotalcpuidleUsage=99.248120 + order:3 TotalcpuioWaitUsage=0.000000 + order:4 TotalcpuirqUsage=0.000000 + order:5 TotalcpuniceUsage=0.000000 + order:6 TotalcpusoftIrqUsage=0.000000 + order:7 TotalcpusystemUsage=0.501253 + order:8 TotalcpuuserUsage=0.250627 + order:9 cpu0Frequency=1992000 + order:10 cpu0Usage=0.000000 + order:11 cpu0idleUsage=100.000000 + order:12 cpu0ioWaitUsage=0.000000 + order:13 cpu0irqUsage=0.000000 + order:14 cpu0niceUsage=0.000000 + order:15 cpu0softIrqUsage=0.000000 + order:16 cpu0systemUsage=0.000000 + order:17 cpu0userUsage=0.000000 + order:18 cpu1Frequency=1992000 + order:19 cpu1Usage=0.000000 + order:20 cpu1idleUsage=100.000000 + order:21 cpu1ioWaitUsage=0.000000 + order:22 cpu1irqUsage=0.000000 + order:23 cpu1niceUsage=0.000000 + order:24 cpu1softIrqUsage=0.000000 + order:25 cpu1systemUsage=0.000000 + order:26 cpu1userUsage=0.000000 + order:27 cpu2Frequency=1992000 + order:28 cpu2Usage=1.000000 + order:29 cpu2idleUsage=99.000000 + order:30 cpu2ioWaitUsage=0.000000 + order:31 cpu2irqUsage=0.000000 + order:32 cpu2niceUsage=0.000000 + order:33 cpu2softIrqUsage=0.000000 + order:34 cpu2systemUsage=1.000000 + order:35 cpu2userUsage=0.000000 + order:36 cpu3Frequency=1992000 + order:37 cpu3Usage=0.000000 + order:38 cpu3idleUsage=100.000000 + order:39 cpu3ioWaitUsage=0.000000 + order:40 cpu3irqUsage=0.000000 + order:41 cpu3niceUsage=0.000000 + order:42 cpu3softIrqUsage=0.000000 + order:43 cpu3systemUsage=0.000000 + order:44 cpu3userUsage=0.000000 + order:45 gpuFrequency=200000000 + order:46 gpuLoad=0.000000 + order:47 gpu-thermal=40000.000000 + order:48 soc-thermal=40.625000 + order:49 memAvailable=1142820 + order:50 memFree=687988 + order:51 memTotal=1935948 + order:52 ddrFrequency=800000000 + order:53 networkDown=0 + order:54 networkUp=0 + order:55 capture=data/local/tmp/capture/screenCap_1501837838669.png + ... - + command exec finished! # ``` - Collect the full information of the specified application, including the CPU, GPU, temperature, frame rate, memory, DDR, network speed, and screenshot information. - - + ``` # SP_daemon -N 10 -PKG ohos.samples.ecg -c -g -t -f -r -d -net -snapshot - - order:0 timestamp=1502725340425 - order:1 ProcAppName=com.ohos.settings + + order:0 timestamp=1501837949706 + order:1 ProcAppName=ohos.samples.ecg order:2 ProcCpuLoad=0.000000 - order:3 ProcCpuUsage=35.950135 - order:4 ProcId=3912 - order:5 ProcSCpuUsage=6.721698 - order:6 ProcUCpuUsage=29.228437 - order:7 cpu0Frequency=1992000 - order:8 cpu0Usage=64.539007 - order:9 cpu0idleUsage=35.460993 - order:10 cpu0ioWaitUsage=0.000000 - order:11 cpu0irqUsage=0.000000 - order:12 cpu0niceUsage=0.000000 - order:13 cpu0softIrqUsage=0.000000 - order:14 cpu0systemUsage=26.241135 - order:15 cpu0userUsage=38.297872 - order:16 cpu1Frequency=1992000 - order:17 cpu1Usage=73.758865 - order:18 cpu1idleUsage=26.241135 - order:19 cpu1ioWaitUsage=0.000000 - order:20 cpu1irqUsage=0.000000 - order:21 cpu1niceUsage=0.000000 - order:22 cpu1softIrqUsage=0.000000 - order:23 cpu1systemUsage=29.078014 - order:24 cpu1userUsage=44.680851 - order:25 cpu2Frequency=1992000 - order:26 cpu2Usage=75.172414 - order:27 cpu2idleUsage=24.827586 - order:28 cpu2ioWaitUsage=0.000000 - order:29 cpu2irqUsage=0.000000 - order:30 cpu2niceUsage=0.000000 - order:31 cpu2softIrqUsage=0.000000 - order:32 cpu2systemUsage=18.620690 - order:33 cpu2userUsage=56.551724 - order:34 cpu3Frequency=1992000 - order:35 cpu3Usage=80.419580 - order:36 cpu3idleUsage=19.580420 - order:37 cpu3ioWaitUsage=0.000000 - order:38 cpu3irqUsage=0.000000 - order:39 cpu3niceUsage=0.000000 - order:40 cpu3softIrqUsage=0.699301 - order:41 cpu3systemUsage=21.678322 - order:42 cpu3userUsage=58.041958 - order:43 gpuFrequency=800000000 - order:44 gpuLoad=45.000000 - order:45 gpu-thermal=44375.000000 - order:46 soc-thermal=46.111000 - order:47 fps=40 - order:48 fpsJitters=14482127;;28966003;;28971836;;14484751;;28952878;;28970962;;14480959;;28968337;;14476001;;28967461;;28968045;;14477751;;28966878;;28975337;;14475126;;28962795;;28967461;;14496710;;28953169;;28966003;;14483002;;28963961;;28965711;;28964836;;28966295;;14550085;;28898628;;28964544;;28975628;;14497293;;28938878;;43454546;;28966003;;28973295;;28959878;;28964252;;14476585;;28965128;;28970670;;14478626 - order:49 refreshrate=69 - order:50 arktsHeapPss=8482 - order:51 gpuPss=0 - order:52 graphicPss=10800 - order:53 heapAlloc=0 - order:54 heapFree=0 - order:55 heapSize=0 - order:56 memAvailable=1113084 - order:57 memFree=681968 - order:58 memTotal=1990104 - order:59 nativeHeapPss=24630 - order:60 privateClean=7072 - order:61 privateDirty=43304 - order:62 pss=71001 - order:63 sharedClean=93024 - order:64 sharedDirty=45060 - order:65 stackPss=1784 - order:66 swap=0 - order:67 swapPss=0 - order:68 ddrFrequency=0 - order:69 networkDown=0 - order:70 networkUp=0 - order:71 capture=data/local/tmp/capture/screenCap_1502725341222.png - + order:3 ProcCpuUsage=38.775000 + order:4 ProcId=1960 + order:5 ProcSCpuUsage=8.875000 + order:6 ProcUCpuUsage=29.900000 + order:7 TotalcpuUsage=85.416667 + order:8 TotalcpuidleUsage=14.583333 + order:9 TotalcpuioWaitUsage=0.000000 + order:10 TotalcpuirqUsage=0.000000 + order:11 TotalcpuniceUsage=0.000000 + order:12 TotalcpusoftIrqUsage=0.000000 + order:13 TotalcpusystemUsage=33.072917 + order:14 TotalcpuuserUsage=52.343750 + order:15 cpu0Frequency=1992000 + order:16 cpu0Usage=92.929293 + order:17 cpu0idleUsage=7.070707 + order:18 cpu0ioWaitUsage=0.000000 + order:19 cpu0irqUsage=0.000000 + order:20 cpu0niceUsage=0.000000 + order:21 cpu0softIrqUsage=0.000000 + order:22 cpu0systemUsage=40.404040 + order:23 cpu0userUsage=52.525253 + order:24 cpu1Frequency=1992000 + order:25 cpu1Usage=82.291667 + order:26 cpu1idleUsage=17.708333 + order:27 cpu1ioWaitUsage=0.000000 + order:28 cpu1irqUsage=0.000000 + order:29 cpu1niceUsage=0.000000 + order:30 cpu1softIrqUsage=0.000000 + order:31 cpu1systemUsage=29.166667 + order:32 cpu1userUsage=53.125000 + order:33 cpu2Frequency=1992000 + order:34 cpu2Usage=81.111111 + order:35 cpu2idleUsage=18.888889 + order:36 cpu2ioWaitUsage=0.000000 + order:37 cpu2irqUsage=0.000000 + order:38 cpu2niceUsage=0.000000 + order:39 cpu2softIrqUsage=0.000000 + order:40 cpu2systemUsage=31.111111 + order:41 cpu2userUsage=50.000000 + order:42 cpu3Frequency=1992000 + order:43 cpu3Usage=85.858586 + order:44 cpu3idleUsage=14.141414 + order:45 cpu3ioWaitUsage=0.000000 + order:46 cpu3irqUsage=0.000000 + order:47 cpu3niceUsage=0.000000 + order:48 cpu3softIrqUsage=0.000000 + order:49 cpu3systemUsage=32.323232 + order:50 cpu3userUsage=53.535354 + order:51 gpuFrequency=200000000 + order:52 gpuLoad=29.000000 + order:53 gpu-thermal=41875.000000 + order:54 soc-thermal=45.000000 + order:55 fps=40 + order:56 fpsJitters=14482127;;28966003;;28971836;;14484751;;28952878;;28970962;;14480959;;28968337;;14476001;;28967461;;28968045;;14477751;;28966878;;28975337;;14475126;;28962795;;28967461;;14496710;;28953169;;28966003;;14483002;;28963961;;28965711;;28964836;;28966295;;14550085;;28898628;;28964544;;28975628;;14497293;;28938878;;43454546;;28966003;;28973295;;28959878;;28964252;;14476585;;28965128;;28970670;;14478626 + order:57 refreshrate=69 + order:58 arktsHeapPss=10970 + order:59 gpuPss=0 + order:60 graphicPss=10800 + order:61 heapAlloc=0 + order:62 heapFree=0 + order:63 heapSize=0 + order:64 memAvailable=1137784 + order:65 memFree=682592 + order:66 memTotal=1935948 + order:67 nativeHeapPss=21398 + order:68 privateClean=24816 + order:69 privateDirty=44932 + order:70 pss=91587 + order:71 sharedClean=100512 + order:72 sharedDirty=36832 + order:73 stackPss=1444 + order:74 swap=0 + order:75 swapPss=0 + order:76 ddrFrequency=800000000 + order:77 networkDown=0 + order:78 networkUp=0 + order:79 capture=data/local/tmp/capture/screenCap_1501837950216.png + ... - + command exec finished! # ``` - >**NOTE** > @@ -637,21 +649,25 @@ Run the **start** command to start collection, operate the device or application | -stop |Yes| Stops collection. A report is generated when collection is complete. | ##### Samples - - ``` + + ``` Start data collection. # SP_daemon -start -c SP_daemon Collection begins + + command exec finished! # Stop data collection. # SP_daemon -stop SP_daemon Collection ended - Output Path: data/local/tmp/smartperf/1/t_index_info_csv + Output Path: data/local/tmp/smartperf/1/t_index_info.csv + + command exec finished! # - ``` + ``` >**NOTE** > >- To start collecting the system data, run the **SP_daemon -start -c -g -t -r -d -net -snapshot** command. @@ -668,20 +684,20 @@ If the collection result is saved in a CSV file, perform the following steps to - To check the path to the test result file: - ``` + ``` C:\Users\issusser>hdc shell # cd data/local/tmp # ls data.csv # - ``` + ``` - To export the test result file: ``` C:\Users\issusser>hdc file recv data/local/tmp/data.csv D:\ [I][2023-11-08 16:16:41] HdcFile::TransferSummary success FileTransfer finish, Size:429, File count = 1, time:6ms rate:71.50kB/s - + C:\Users\issusser> ``` @@ -693,23 +709,23 @@ If the collection result is saved in a CSV file, perform the following steps to | :-----| :--------------------- |:-----| | cpuFrequency | CPU core frequency. |Unit: Hz| | cpuUasge | CPU core usage. |%| - | cpuidleUsage | CPU usage in idle state. |%| + | cpuidleUsage | CPU usage in idle state. |%| | cpuioWaitUsage | CPU usage of I/O wait. |%| - | cpuirqUsage | CPU usage of hardware interrupts. |%| + | cpuirqUsage | CPU usage of hardware interrupts. |%| | cpuniceUsage | CPU usage of user level processes with lower scheduling priority. |%| - | cpusoftIrqUsage | CPU usage of software interrupts. |%| + | cpusoftIrqUsage | CPU usage of software interrupts. |%| | cpusystemUsage | CPU usage in kernel mode. |%| - | cpuuserUsage | CPU usage in user mode. |%| - | ProcId | PID. |-| - | ProcAppName | App package name. |-| + | cpuuserUsage | CPU usage in user mode. |%| + | ProcId | Process ID. |-| + | ProcAppName | Application bundle name. |-| | ProcCpuLoad | Process CPU load. |%| - | ProcCpuUsage | CPU usage of the process. |%| + | ProcCpuUsage | CPU usage of the process. |%| | ProcUCpuUsage | CPU usage of the process in user mode. |%| - | ProcSCpuUsage | CPU usage of the process in kernel mode. |%| + | ProcSCpuUsage | CPU usage of the process in kernel mode. |%| | gpuFrequ | GPU frequency of the system. |%| | gpuLoad | GPU load of the system. |%| - | currentNow | Current value. |Unit: mA| - | voltageNow | Voltage value. |Unit: μV| + | currentNow | Current value. |Unit: mA| + | voltageNow | Voltage value. |Unit: μV| | fps | Number of frames per second. |Unit: FPS| | fpsJitters | Frame interval. |Unit: ns| | refreshrate | Screen refresh rate. |Unit: Hz| @@ -736,28 +752,25 @@ If the collection result is saved in a CSV file, perform the following steps to | arktsHeapPss | Used ArkTS memory size. |Unit: KB| | nativeHeapPss | Used native memory size. |Unit: KB| | stackPss | Used stack memory size. |Unit: KB| - | timeStamp | Timestamp. |Collection time.| - + | timeStamp | Timestamp. |Collection time.| ### Scenario Collection - - In addition to basic collection, the response and completion delay can be collected. The scenario collection result is displayed in the CLI instead of being written into the **data.csv** file. | Command |Mandatory| Description | | :-----|:-----| :--------------------- | -| -editor|Yes| Scenario collection tag, which can be followed by parameter configuration options. | -| -responseTime|No| Response delay. | -| -completeTime|No| Completion delay. | +| -editor|Yes| Identifies scenario collection. Parameter options can be added after. | +| -responseTime|No| Collects the response latency. | +| -completeTime|No| Collects the completion delay. | | -fpsohtest|No| A validator used to collect the frame rate every second. The frame rate is collected 10 times by default. | #### Samples -- Collect the application response delay. +- Collect the application response latency. (This command supports only the RK3568 device.) ``` - # SP_daemon -editor responseTime com.ohos.settings + # SP_daemon -editor responseTime ohos.samples.ecg ohtest time:544ms command exec finished! @@ -766,10 +779,10 @@ In addition to basic collection, the response and completion delay can be collec > >- Open the application before collection, press **Enter** in the CLI, switch to the application page, and wait for the collection result to be printed. -- Collect the application completion delay. +- Collect the application completion latency. (This command supports only the RK3568 device.) ``` - # SP_daemon -editor completeTime com.ohos.settings + # SP_daemon -editor completeTime ohos.samples.ecg ohtest time:677ms command exec finished! @@ -788,8 +801,6 @@ In addition to basic collection, the response and completion delay can be collec > >- You need to swipe or switch the current page after running the command, and the collection result will be printed after 10s. - - ### Other Collection The power collection result of the current device can be written into the **data.csv** file. Other data is collected separately and the collection result is displayed only in the command box. @@ -800,7 +811,7 @@ The power collection result of the current device can be written into the **data | -deviceinfo|No| Obtains device information. | | -server|No| Starts a daemon process by starting or stopping collection. | | -clear|No| Clears all the SP_daemon processes. | -| -ohtestfps|No| Obtains the frame rate. The number of collection times can be set (collection is performed every second). | +| -ohtestfps|No| Obtains the frame rate. You can set the number of collection times (collection is performed every second). | | -editorServer|No| Starts a daemon process by using an editor. | | -recordcapacity|No| Obtains the battery level of the current device. | | -profilerfps |No| Collects the frame rate of the current page. | @@ -811,7 +822,9 @@ The power collection result of the current device can be written into the **data ``` # SP_daemon -screen - activeMode: 1260x2720, refreshrate=120 + activeMode: 720x1280, refreshrate=69 + + command exec finished! # ``` @@ -831,15 +844,16 @@ The power collection result of the current device can be written into the **data cpu_c1_max: 1992000 cpu_c1_min: 408000 cpu_cluster_name: policy0 + daemonPerfVersion: 1.0.5 deviceTypeName: rk3568 - fullname: OpenHarmony-5.0.2.43 + fullname: OpenHarmony-5.1.0.46 gpu_max_freq: 800000000 gpu_min_freq: 200000000 model: ohos name: OpenHarmony 3.2 - sn: 7001005458323933328a26dbb7bd3900 - version: OpenHarmony 5.0.2.43 - + sn: 150100424a5444345209d941bec6b900 + version: OpenHarmony 5.1.0.46 + command exec finished! # ``` @@ -852,9 +866,6 @@ The power collection result of the current device can be written into the **data # pidof SP_daemon 7024 # - - command exec finished! - # ``` >**NOTE** > @@ -864,14 +875,14 @@ The power collection result of the current device can be written into the **data ``` # pidof SP_daemon - 9923 11402 + 2725 # SP_daemon -clear + + + command exec finished! # # pidof SP_daemon # - - command exec finished! - # ``` >**NOTE** > @@ -894,9 +905,6 @@ The power collection result of the current device can be written into the **data fps:41|1501926693532 SP_daemon exec finished! # - - command exec finished! - # ``` >**NOTE** > @@ -907,11 +915,9 @@ The power collection result of the current device can be written into the **data ``` # SP_daemon -editorServer - Socket Process called! - Socket TCP Init called! - Socket Process called! - Socket Process called! - — + + + command exec finished! ``` @@ -979,3 +985,6 @@ The power collection result of the current device can be written into the **data >**NOTE** > >- In this command, **100** indicates the number of collection times (collection is performed every second) and can be set to a positive integer. **10** indicates collection by segment. Currently, the number of collection segments can be set to a positive integer ranging from 1 to 10. + + + diff --git a/en/application-dev/application-test/wukong-guidelines.md b/en/application-dev/application-test/wukong-guidelines.md index 5712a6fb1bf3830c8ef2fec416b7c2b7e5621473..5853fadca258d8bf03bd8f3c60bbfe37f68f8648 100644 --- a/en/application-dev/application-test/wukong-guidelines.md +++ b/en/application-dev/application-test/wukong-guidelines.md @@ -114,7 +114,12 @@ The following figure shows the wukong component architecture and the responsibil -r, --rotate rotate event percent -e, --allow ability the ability name of allowlist -E, --block ability the ability name of blocklist + -Y, --blockCompId the id list of block component + -y, --blockCompType the type list of block component -I, --screenshot get screenshot(only in random input) + -B, --checkBWScreen black and white screen detection + -U, --Uri set Uri pages + -x, --Uri-type set Uri-type # wukong special -help // Help menu for wukong special testing. usage: wukong special [] These are wukong special arguments list: @@ -143,12 +148,12 @@ The following figure shows the wukong component architecture and the responsibil | Command | Description | Mandatory| Description | | --------------- | ------------------------------------ | ---- | ---------------------------------------- | | -h,--help | Obtains the help information about the test. | No | - | -| -c,--count | Sets the number of execution times. This command conflicts with the **-T** command. Select either of them. | No | The default value is 10, in times. | +| -c,--count | Sets the number of execution times. This command conflicts with the **-T** command. Set either of them. | No | The default value is 10, in times. | | -i,--interval | Sets the test interval. | No | The default value is 1500, in millisecond. | | -s,--seed | Sets the random seed. | No | If the same random seed is set, the same random event sequence is generated.| -| -b,--bundle[bundlename, ......, bundlename] | Sets the allowed bundles for the test. This command conflicts with the **-p** command.| No | By default, all bundles on the device are allowed. Use commas (,) to separate bundle names. | -| -p,--prohibit[bundlename, ......, bundlename] | Sets the blocked bundles for the test. This command conflicts with the **-b** command.| No | By default, no bundle is blocked. Use commas (,) to separate bundle names. | -| -d,--page[page, ......, page] | Sets the blocked pages for the test.| No | By default, the **pages/system** pages are blocked. Use commas (,) to separate page names.| +| -b,--bundle[bundlename, ......, bundlename] | Sets allowed bundles for the test. This command conflicts with the **-p** command.| No | By default, all bundles on the device are allowed. Use commas (,) to separate bundle names. | +| -p,--prohibit[bundlename, ......, bundlename] | Sets blocked bundles for the test. This command conflicts with the **-b** command.| No | By default, no bundle is blocked. Use commas (,) to separate bundle names. | +| -d,--page[page, ......, page] | Sets blocked pages for the test.| No | By default, the **pages/system** pages are blocked. Use commas (,) to separate page names.| | -a,--appswitch | Sets the proportion of the random application startup event test. | No | The default value is 10%. | | -t,--touch | Sets the proportion of the random touch event test. | No | The default value is 10%. | | -S,--swap | Sets the proportion of the random swipe event test. | No | The default value is 3%. | @@ -244,10 +249,10 @@ The following figure shows the wukong component architecture and the responsibil | -c,--count | Sets the number of test times. This command conflicts with the **-T** command. Set either of them. | No | The default value is 10, in times. | | -i,--interval | Sets the test interval. | No | The default value is 1500, in millisecond. | | -s,--seed | Sets the random seed. | No | If the same random seed is set, the same random event sequence is generated.| -| -b,--bundle[bundlename, ......, bundlename] | Sets the bundle name of allowlist for the test. This command conflicts with the **-p** command.| No | By default, all applications on the device are allowed. (Use commas (,) to separate application names.) | -| -p,--prohibit[bundlename, ......, bundlename] | Sets the bundle name of blocklist for the test. This command conflicts with the **-b** command.| No | By default, no application is blocked. (Use commas (,) to separate application names.) | -| -d,--page[page, ......, page] | Sets the list of blocked pages for the test.| No | By default, the pages/system pages are blocked. (Use commas (,) to separate page names.)| -| -a,--appswitch | Sets the proportion of random application startup test. | No | The default value is 10%. | +| -b,--bundle[bundlename, ......, bundlename] | Sets allowed bundles for the test. This command conflicts with the **-p** command.| No | By default, all bundles on the device are allowed. Use commas (,) to separate bundle names. | +| -p,--prohibit[bundlename, ......, bundlename] | Sets blocked bundles for the test. This command conflicts with the **-b** command.| No | By default, no bundle is blocked. Use commas (,) to separate bundle names. | +| -d,--page[page, ......, page] | Sets blocked pages for the test.| No | By default, the **pages/system** pages are blocked. Use commas (,) to separate page names.| +| -a,--appswitch | Sets the proportion of the random application startup event test. | No | The default value is 10%. | | -t,--touch | Sets the proportion of the random touch event test. | No | The default value is 10%. | | -S,--swap | Sets the proportion of the random swipe event test. | No | The default value is 3%. | | -m,--mouse | Sets the proportion of the random mouse event test. | No | The default value is 1%. | @@ -272,7 +277,7 @@ The following figure shows the wukong component architecture and the responsibil The parameters in the command are described as follows. | Command | Value |Description | | -------------- | -------------- | -------------- | -| wukong exec | - | Works as the main command. | +| wukong focus | - | Works as the main command. | | -s | 10 | Sets the random seed. The seed value is **10**. | | -i | 1000 | Sets the application startup interval to **1000** ms.| | -a | 0.28 | Sets the proportion of the random application startup test to **28%**. | @@ -298,7 +303,7 @@ After the test commands are executed, the test result is automatically generated | wukong_report.csv | Stores the test report summary. | | wukong.log | Indicates the test operation history. | -### Viewing Operation Logs +### View operation logs You can run the hdc command to obtain logs to the local host and view the operation history. @@ -316,3 +321,41 @@ C:\Users\xxx>hdc file recv /data/local/tmp/wukong/report/20170805_170053/wukong. [I][2024-01-03 20:08:02] HdcFile::TransferSummary success FileTransfer finish, Size:76492, File count = 1, time:16ms rate:4780.75kB/s ``` + +## FAQs +### failed to connect to AAMS + **Symptom** + +failed to connect to AAMS. + + **Possible Cause** + +AAMS is occupied by Hypium or the UIViewer of DevEco Testing. AAMS can be connected to only one program at a time. + + **Solution** + +Stop the process that occupies AAMS or restart the device. +### Errorcode:(4005) + **Symptom** + +Errorcode:(4005). + + **Possible Cause** + +The size of the screen display area changes. As a result, the page information fails to be obtained. + + **Solution** + +This error does not affect the test process and does not need to be handled. +### Errorcode:(4007) + **Symptom** + +Errorcode:(4007). + + **Possible Cause** + +The size of the screen display area changes. As a result, the page information fails to be obtained. + + **Solution** + +This error does not affect the test process and does not need to be handled. diff --git a/en/application-dev/arkts-utils/Readme-EN.md b/en/application-dev/arkts-utils/Readme-EN.md index 55909b9d1dbfd9a3e757dcbccad8777129771da1..ab16a647b98fc4b7a90c98bbbf19db211b20bc8c 100644 --- a/en/application-dev/arkts-utils/Readme-EN.md +++ b/en/application-dev/arkts-utils/Readme-EN.md @@ -44,6 +44,7 @@ - [Communication Between the TaskPool Task and Host Thread](taskpool-communicates-with-mainthread.md) - [Real-Time Communication Between the Worker Thread and Host Thread](worker-communicates-with-mainthread.md) - [Synchronous Calls to Host Thread Interfaces from Worker](worker-invoke-mainthread-interface.md) + - [High-Performance Communication Between Multi-Level Workers](worker-postMessage-sendable.md) - Multithreaded Development - [Overview of Multithreaded Development](multithread-develop-overview.md) - Concurrency in Time-Consuming Tasks @@ -65,6 +66,8 @@ - [C++ Inter-Thread Data Sharing](native-interthread-shared.md) - [Specifying Task Concurrency with TaskPool](taskpool-async-task-guide.md) - [ArkUI Waterfall Rendering](taskpool-waterflow.md) + - [Obtaining the Recently Accessed List](sendablelrucache-recent-list.md) + - [Canceling Tasks in Multithreading with TaskPool](multi-thread-cancel-task.md) - [ArkTS Cross-Language Interaction](arkts-cross-language-interaction.md) - ArkTS Runtime - [Overview of ArkTS Runtime](arkts-runtime-overview.md) diff --git a/en/application-dev/arkts-utils/arkoptions-guide.md b/en/application-dev/arkts-utils/arkoptions-guide.md index afb6a1d69d0bdf3266b2e623485e9d60c64211b2..d2b9cc6d33f9631ed3770dfbede4e49ce6e253e4 100644 --- a/en/application-dev/arkts-utils/arkoptions-guide.md +++ b/en/application-dev/arkts-utils/arkoptions-guide.md @@ -66,7 +66,7 @@ Field **maxFlowDepth** in **arkOptions/tscConfig** | Name| Description| Data Type| Optional| | -------- | -------- | -------- | -------- | -| maxFlowDepth | Specifies the custom maximum stack depth for TSC flow analysis during TSC compilation. It helps avoid compilation errors caused by a fixed maximum stack. The minimum value is 2000, and the maximum value is 65535.| Number| Optional, defaults to 2000| +| maxFlowDepth | Specifies the custom maximum stack depth for TSC flow analysis during TSC compilation. It helps avoid stack overflow errors caused by a fixed maximum stack depth. The minimum value is 2000, and the maximum value is 65535.| Number| Optional, defaults to 2000.| ### Example @@ -110,7 +110,7 @@ Field **transformLib** in **arkOptions** | Name| Description| Configuration Scope| Data Type| Optional| | -------- | -------- | -------- | -------- | -------- | -| transformLib | Specifies the bytecode instrumentation plugin configuration, allowing you to modify bytecode during compilation. This field is supported only in the stage model. The format is a relative path pointing to the dynamic library implementing the instrumentation functionality. The dynamic library must be generated on the corresponding platform and cannot be copied or renamed across platforms.| Module-level| String| Optional, defaults to not using this feature| +| transformLib | Specifies the bytecode instrumentation plugin configuration, allowing you to modify bytecode during compilation. This field is supported only in the stage model. The format is a relative path to the dynamic library that does the instrumentation. The dynamic library must be generated on the corresponding platform and cannot be copied or renamed across platforms.| Module-level| String| Optional, defaults to not using this feature| ### Example diff --git a/en/application-dev/arkts-utils/arkts-bytecode-file-format.md b/en/application-dev/arkts-utils/arkts-bytecode-file-format.md index 621488c3b4d0d60c6aaedd0c4054cb0319085e9f..c1cb3fd9602a2a21133236c8c94026e0d17b2de2 100644 --- a/en/application-dev/arkts-utils/arkts-bytecode-file-format.md +++ b/en/application-dev/arkts-utils/arkts-bytecode-file-format.md @@ -20,6 +20,7 @@ This topic is applicable only to Ark bytecode of version 12.0.6.0. The version n ### String + - Alignment: single-byte aligned - Format @@ -30,6 +31,7 @@ This topic is applicable only to Ark bytecode of version 12.0.6.0. The version n ### TaggedValue + - Alignment: single-byte aligned - Format @@ -50,6 +52,7 @@ All multi-byte values in bytecode files are stored in little-endian format. ### Header + - Alignment: single-byte aligned - Format @@ -84,6 +87,7 @@ The bytecode version number consists of four parts in the format of major.minor. ### ForeignClass Represents foreign classes referenced in the bytecode file but declared in other files. + - Alignment: single-byte aligned - Format @@ -94,6 +98,7 @@ Represents foreign classes referenced in the bytecode file but declared in other ### ForeignMethod Represents foreign methods referenced in the bytecode file but declared in other files. + - Alignment: single-byte aligned - Format @@ -104,12 +109,14 @@ Represents foreign methods referenced in the bytecode file but declared in other | `name_off` | `uint32_t` | An offset to a [string](#string) representing the method name.| | `index_data` | `uleb128` | [MethodIndexData](#methodindexdata) data of the method.| -**NOTE**
-The offset of **ForeignMethod** can be used to locate the appropriate **IndexHeader** for parsing **class_idx**. +> **NOTE** +> +> The offset of **ForeignMethod** can be used to locate the appropriate **IndexHeader** for parsing **class_idx**. ### ClassIndex Facilitates quick lookup of class definitions by name. + - Alignment: 4-byte aligned - Format @@ -145,6 +152,7 @@ Represents either a source code file or an internal [Annotation](#annotation). F ### ClassTag + - Alignment: single-byte aligned - Format @@ -154,8 +162,9 @@ Represents either a source code file or an internal [Annotation](#annotation). F | `SOURCE_LANG` | `0x02` | `0-1 ` | `uint8_t` | **data** of a [TaggedValue](#taggedvalue) with this tag is **0**, indicating that the source code language is in ArkTS, TS, or JS.| | `SOURCE_FILE` | `0x07` | `0-1` | `uint32_t`| **data** of a [TaggedValue](#taggedvalue) with this tag is an offset that points to a [string](#string) representing the source file name.| -**NOTE**
-**ClassTag** is a marker of the element ([TaggedValue](#taggedvalue)) in **class_data**. **Quantity** in the table header refers to the number of occurrences of the element with this tag in **class_data** of a [class](#class). +> **NOTE** +> +> **ClassTag** is a marker of the element ([TaggedValue](#taggedvalue)) in **class_data**. **Quantity** in the table header refers to the number of occurrences of the element with this tag in **class_data** of a [class](#class). ### Field @@ -172,8 +181,9 @@ Represents fields within the bytecode file. | `reserved` | `uleb128` | Reserved field for internal use by the Ark bytecode file. | | `field_data` | `TaggedValue[]` | Array with variable length. Each element in the array is of the [TaggedValue](#taggedvalue) type, and the element tag is of the [FieldTag](#fieldtag) type. Elements in the array are sorted in ascending order based on the tag (except the **0x00** tag).| -**NOTE**
-The offset of **Field** can be used to locate the appropriate **IndexHeader** for parsing **class_idx** and **type_idx**. +> **NOTE** +> +> The offset of **Field** can be used to locate the appropriate **IndexHeader** for parsing **class_idx** and **type_idx**. ### FieldTag @@ -187,8 +197,9 @@ The offset of **Field** can be used to locate the appropriate **IndexHeader** fo | `INT_VALUE` | `0x01` | `0-1` | `sleb128` | The **data** type of a [TaggedValue](#taggedvalue) with this tag is of **boolean**, **byte**, **char**, **short**, or **int**.| | `VALUE` | `0x02` | `0-1` | `uint32_t` | The **data** type of a [TaggedValue](#taggedvalue) with this tag is of **FLOAT** or **ID** in [Value formats](#value-formats).| -**NOTE**
-**FieldTag** is a marker of the element ([TaggedValue](#taggedvalue)) in **field_data**. **Quantity** in the table header refers to the number of occurrences of the element with this tag in **field_data** of a [field](#field). +> **NOTE** +> +> **FieldTag** is a marker of the element ([TaggedValue](#taggedvalue)) in **field_data**. **Quantity** in the table header refers to the number of occurrences of the element with this tag in **field_data** of a [field](#field). ### Method @@ -205,8 +216,9 @@ Represents methods within the bytecode file. | `index_data` | `uleb128` | [MethodIndexData](#methodindexdata) data of the method.| | `method_data` | `TaggedValue[]` | Array with variable length. Each element in the array is of the [TaggedValue](#taggedvalue) type, and the element tag is of the [MethodTag](#methodtag) type. Elements in the array are sorted in ascending order based on the tag (except the **0x00** tag).| -**NOTE**
-The offset of **Method** can be used to locate the appropriate **IndexHeader** for parsing **class_idx**. +> **NOTE** +> +> The offset of **Method** can be used to locate the appropriate **IndexHeader** for parsing **class_idx**. ### MethodIndexData @@ -242,8 +254,9 @@ A 32-bit unsigned integer, divided into three parts. | `DEBUG_INFO` | `0x05` | `0-1` | `uint32_t` | **data** of a [TaggedValue](#taggedvalue) with this tag is an offset pointing to [DebugInfo](#debuginfo), indicating the debugging information of the method.| | `ANNOTATION` | `0x06` | `>=0` | `uint32_t` | **data** of a [TaggedValue](#taggedvalue) with this tag is an offset pointing to [Annotation](#annotation), indicating the annotation of the method.| -**NOTE**
-**MethodTag** is a marker of the element ([TaggedValue](#taggedvalue)) in **method_data**. **Quantity** in the table header refers to the number of occurrences of the element with this tag in **method_data** of a [method](#method). +> **NOTE** +> +> **MethodTag** is a marker of the element ([TaggedValue](#taggedvalue)) in **method_data**. **Quantity** in the table header refers to the number of occurrences of the element with this tag in **method_data** of a [method](#method). ### Code @@ -299,8 +312,9 @@ Represents annotations in the bytecode file. | `elements` | AnnotationElement[] | An array of [AnnotationElement](#annotationelement) elements.| | `element_types` | `uint8_t[]` | An array, in which each element is of the [AnnotationElementTag](#annotationelementtag) type and is used to describe an **AnnotationElement.** The position of each element in the **element_types** array is the same as that of the corresponding **AnnotationElement** in the **elements** array.| -**NOTE**
-The offset of **Annotation** can be used to locate the appropriate **IndexHeader** for parsing **class_idx**. +> **NOTE** +> +> The offset of **Annotation** can be used to locate the appropriate **IndexHeader** for parsing **class_idx**. ### AnnotationElementTag @@ -418,8 +432,9 @@ For special operation codes in the range **0x0c** to **0xff** (included), the st | 3 | `line += LINE_BASE + (adjusted_opcode % LINE_RANGE)` | Increments the **line** register. The value of **LINE_BASE** is **-4**, which is the minimum line number increment. The maximum increment is **LINE_BASE + LINE_RANGE - 1**.| | 4 | | Generates a new location entry. | -**NOTE**
-Special operation codes are calculated by using the following formula: **(line_increment - LINE_BASE) + (address_increment * LINE_RANGE) + OPCODE_BASE**. +> **NOTE** +> +> Special operation codes are calculated by using the following formula: (line_increment - LINE_BASE) + (address_increment * LINE_RANGE) + OPCODE_BASE. ### IndexSection @@ -517,3 +532,5 @@ Describes literals in the bytecode file. There are four encoding formats based o | ByteTwo | `uint16_t` | 2 bytes | Double-byte value. | | ByteFour | `uint32_t` | 4 bytes | Four-byte value. | | ByteEight | `uint64_t` | 8 bytes | Eight-byte value. | + + \ No newline at end of file diff --git a/en/application-dev/arkts-utils/arkts-bytecode-fundamentals.md b/en/application-dev/arkts-utils/arkts-bytecode-fundamentals.md index 389411567de2450476f417f93d404d53c63cf2c1..c9c60d6c8e379fcd709f82926582e0f683575c0c 100644 --- a/en/application-dev/arkts-utils/arkts-bytecode-fundamentals.md +++ b/en/application-dev/arkts-utils/arkts-bytecode-fundamentals.md @@ -93,8 +93,10 @@ Related instructions in the bytecode: *tryldglobalbyname 0x0, a*: loads a global variable named **a** to the acc. If this variable does not exist, an exception is thrown.
*trystglobalbyname 0x2, a*: stores the value of the acc to a global variable named **a**. If this variable does not exist, an exception is thrown.
*trystglobalbyname 0x3, b*: stores the value of the acc to a global variable named **b**. If this variable does not exist, an exception is thrown.
-**NOTE**
-**0x0**, **0x2**, and **0x3** in the preceding instructions are reserved for internal use in the Ark Runtime. + +> **NOTE** +> +> **0x0**, **0x2**, and **0x3** in the preceding instructions are reserved for internal use in the Ark Runtime. #### Module Namespaces and Variables All [module namespaces](https://262.ecma-international.org/12.0/#module-namespace-exotic-object) used in the source file are compiled into arrays, referenced by instructions using indexes. For example, *getmodulenamespace 0x1* references the module namespace at index *0x1*.
@@ -105,8 +107,9 @@ Scenarios for generating module instructions include [import](https://262.ecma-i * **import { }**: module variable * **export**: local export -**NOTE**
-Module-related logic is an internal implementation detail of the compiler. As the ArkCompiler evolves, new scenarios involving module instructions may emerge, and existing ones may change due to evolving requirements or code refactoring.
+> **NOTE** +> +> Module-related logic is an internal implementation detail of the compiler. As the ArkCompiler evolves, new scenarios involving module instructions may emerge, and existing ones may change due to evolving requirements or code refactoring.
Example: ```ts diff --git a/en/application-dev/arkts-utils/arkts-condition-variable-introduction.md b/en/application-dev/arkts-utils/arkts-condition-variable-introduction.md index 666e93ad24b14b4e31c51538832d9b706759edb2..53f26ed1af6da49fea158142d884b4c2f9b3def6 100644 --- a/en/application-dev/arkts-utils/arkts-condition-variable-introduction.md +++ b/en/application-dev/arkts-utils/arkts-condition-variable-introduction.md @@ -1,6 +1,6 @@ # Asynchronous Waiting -To address timing control issues in multithreaded tasks, ArkTS has introduced asynchronous waiting and notification capabilities. The [ConditionVariable](../reference/apis-arkts/js-apis-arkts-utils.md#conditionvariable16) object supports pass-by-reference across threads. +To address timing control issues in multithreaded tasks, ArkTS has introduced asynchronous waiting and notification capabilities. The [ConditionVariable](../reference/apis-arkts/js-apis-arkts-utils.md#conditionvariable18) object supports pass-by-reference across threads. ArkTS, which supports asynchronous operations, now provides the capability for asynchronous tasks to wait and be awakened. When a wake-up notification is received or the waiting times out, the asynchronous execution continues. @@ -81,5 +81,3 @@ struct Index { } } ``` - - \ No newline at end of file diff --git a/en/application-dev/arkts-utils/arkts-dynamic-import.md b/en/application-dev/arkts-utils/arkts-dynamic-import.md index aa0f8fe2ce081d9079b28b2c6d570febe48ffaef..9418a3410a53393bc88d05eac443eaad242420ba 100644 --- a/en/application-dev/arkts-utils/arkts-dynamic-import.md +++ b/en/application-dev/arkts-utils/arkts-dynamic-import.md @@ -86,11 +86,11 @@ The following table lists the specifications of dynamic import. | API | @arkui-x.* | - | | Native library module | libNativeLibrary.so| - | -Notes: - -1. Module names used in all imports are the aliases defined under **dependencies** in the **oh-package.json5** file. -2. It is recommended that the alias configured under **dependencies** be the same as the values of **moduleName** and **packageName**, both of which indicate the name of the module to import. **moduleName** is set in the **module.json5** file of the module, and **packageName** is set in the **oh-package.json5** file. -3. Importing a module by name is importing the module's entry file, generally **index.ets/ts**. +>**NOTE** +> +> 1. Module names used in all imports are the aliases defined under **dependencies** in the **oh-package.json5** file. +> 2. It is recommended that the alias configured under **dependencies** be the same as the values of **moduleName** and **packageName**, both of which indicate the name of the module to import. **moduleName** is set in the **module.json5** file of the module, and **packageName** is set in the **oh-package.json5** file. +> 3. Importing a module by name is importing the module's entry file, generally **index.ets/ts**. ## Key Points in Dynamic Import Implementation @@ -289,8 +289,7 @@ During compilation, static imports and dynamic imports with constant expressions **Schema configuration format of the runtimeOnly field** -If you are using dynamic imports with variable expressions to import modules or files, but not APIs, you need to add the **runtimeOnly** field under **buildOption** in the **build-profile.json5** file of the HAP/HSP/HAR module. -The following are some examples. +If you are using dynamic imports with variable expressions to import modules or files, but not APIs, you need to add the **runtimeOnly** field under **buildOption** in the **build-profile.json5** file of the HAP/HSP/HAR module. The following are some examples. ```typescript // Dynamically import a module based on the module name myHar. diff --git a/en/application-dev/arkts-utils/arkts-import-native-module.md b/en/application-dev/arkts-utils/arkts-import-native-module.md index c29631ffa8b8686f779a2258d35a45e13517c163..26ec65049fe972889d4c654b21b2992f24f21a13 100644 --- a/en/application-dev/arkts-utils/arkts-import-native-module.md +++ b/en/application-dev/arkts-utils/arkts-import-native-module.md @@ -68,7 +68,10 @@ export * from 'libentry.so' import { add } from './test1' add(2, 3); ``` -**Note**: Native modules do not support both export and import using namespaces simultaneously. +> **NOTE** +> +> Native modules do not support both export and import using namespaces simultaneously. + **Anti-example:** ```ts // test1.ets @@ -105,7 +108,10 @@ import('./test1').then((ns:ESObject) => { }) ``` -**Note**: Dynamic imports do not support exporting files using namespace exports. +> **NOTE** +> +> Dynamic imports do not support exporting files using namespace exports. + **Anti-example:** ```ts // test1.ets diff --git a/en/application-dev/arkts-utils/arkts-lazy-import.md b/en/application-dev/arkts-utils/arkts-lazy-import.md index e94c5ed2bf430882f0af16dee6ce1aa9c9d93cfb..7317ec24e56e85e6c442ce87f706cc8712ec1c8f 100644 --- a/en/application-dev/arkts-utils/arkts-lazy-import.md +++ b/en/application-dev/arkts-utils/arkts-lazy-import.md @@ -106,10 +106,10 @@ You can use [Trace](../performance/common-trace | Syntax | ModuleRequest | ImportName | LocalName | Supported API Version| |:----------------------------------------------|:---------------|:-----------|:------------|:-----------| -| import lazy { x } from "mod"; | "mod" | "x" | "x" | API 12 | -| import lazy { x as v } from "mod"; | "mod" | "x" | "v" | API 12 | -| import lazy x from "mod"; | "mod" | "default" | "x" | API 16 | -| import lazy { KitClass } from "@kit.SomeKit"; | "@kit.SomeKit" | "KitClass" | "KitClass" | API 16 | +| import lazy { x } from "mod"; | "mod" | "x" | "x" | API 12 | +| import lazy { x as v } from "mod"; | "mod" | "x" | "v" | API 12 | +| import lazy x from "mod"; | "mod" | "default" | "x" | API 18 | +| import lazy { KitClass } from "@kit.SomeKit"; | "@kit.SomeKit" | "KitClass" | "KitClass" | API 18 | - Lazy importing of shared modules or modules within a dependency path that includes shared modules Lazy import remains effective for shared modules. For details about the constraints, see [Shared Module](../arkts-utils/arkts-sendable-module.md). @@ -145,7 +145,7 @@ If the **type** keyword is added to the syntax, an error is reported. ### Syntax Not Recommended - Incomplete **lazy** flags within the same .ets file - + Incomplete marking will cause lazy imports to fail and increase the overhead of identifying lazy-imported modules. ```typescript // main.ets @@ -156,7 +156,7 @@ If the **type** keyword is added to the syntax, an error is reported. // ... ``` - Re-exporting lazy-imported variables within the same .ets file without using them - + The variable **c** is not used in **B.ets**, so **B.ets** does not trigger execution. When **c** is used in **A.ets**, it is not initialized, resulting in a JS exception. ```typescript // A.ets @@ -171,7 +171,7 @@ If the **type** keyword is added to the syntax, an error is reported. let c = "c"; export { c } ``` - The execution result is as follows: + Result: ```typescript ReferenceError: c is not initaliized at func_main_0 (A.ets:2:13) @@ -190,7 +190,7 @@ If the **type** keyword is added to the syntax, an error is reported. let c = "c"; export { c } ``` - The execution result is as follows: + Result: ```typescript ReferenceError: module environment is undefined at func_main_0 (A_ns.js:2:13) diff --git a/en/application-dev/arkts-utils/arkts-sendable.md b/en/application-dev/arkts-utils/arkts-sendable.md index 5d85b206fb945e7b972c6137608fc8a7aa672a93..7d1b53f5331015e174175772fe63969341171cbd 100644 --- a/en/application-dev/arkts-utils/arkts-sendable.md +++ b/en/application-dev/arkts-utils/arkts-sendable.md @@ -44,7 +44,9 @@ A Sendable class must meet the following requirements: > > - Since API version 12, the \@Sendable decorator can be used to verify Sendable functions. > -> - To use a Sendable function in API version 12, you must configure "compatibleSdkVersionStage": "beta3" in the project. Otherwise, the function does not take effect. For details, see [build-profile.json5](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/ide-hvigor-build-profile-V5). +> - For projects with API version 12, to use the \@Sendable decorator to verify Sendable functions, you must configure "compatibleSdkVersionStage": "beta3" in the project. Otherwise, the Sendable feature does not take effect. For details, see [build-profile.json5](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/ide-hvigor-build-profile-V5). +> +> - For projects with API versions later than 12, you can directly use the \@Sendable decorator to verify Sendable functions without any other configuration. A Sendable function must meet the following requirements: @@ -118,7 +120,7 @@ The \@Sendable decorator declares and verifies Sendable classes and functions. | Class inheritance restrictions| Sendable classes can only inherit from other Sendable classes. Regular classes cannot inherit from Sendable classes.| | Property type restrictions| 1. The following types are supported: string, number, boolean, bigint, null, undefined, Sendable class, collections.Array, collections.Map, collections.Set, and ArkTSUtils.locks.AsyncLock.
2. Closure variables are not allowed.
3. Private properties defined with \# are not supported; use **private** instead.
4. Computed properties are not supported.| | Other property restrictions| Member properties must be initialized explicitly. They cannot be followed by exclamation marks (!).| -| Parameter restrictions for decorated functions or class methods| Local variables, parameters, and variables imported through **import** are allowed. Closure variables are not allowed, except for top-level Sendable classes and functions. Since API version 16, functions or class objects decorated by @Sendable can also access variables exported from the same file.| +| Parameter restrictions for decorated functions or class methods| Local variables, parameters, and variables imported through **import** are allowed. Closure variables are not allowed, except for top-level Sendable classes and functions. Since API version 18, functions or class objects decorated by @Sendable can also access variables exported from the same file.| | Restrictions for Sendable classes and functions| Adding or deleting properties is not allowed. Modifying properties is allowed, but the type must remain consistent before and after modification. Modifying methods is not supported.| | Use scenario| 1. Scenarios where class methods or Sendable functions are used in TaskPool or Worker.
2. Scenarios involving large amounts of object data transmission. The time required for serialization increases with the data volume. After transforming data with Sendable, the efficiency of transmitting 100 KB of data is approximately 20 times higher, and for 1 MB of data, it is about 100 times higher.| diff --git a/en/application-dev/arkts-utils/batch-database-operations-guide.md b/en/application-dev/arkts-utils/batch-database-operations-guide.md index 6139215f0dc0785482a8a7b930615e2c079f27f2..ab9413682587ce28a4ea79fa81da1c0b40a5ecb1 100644 --- a/en/application-dev/arkts-utils/batch-database-operations-guide.md +++ b/en/application-dev/arkts-utils/batch-database-operations-guide.md @@ -308,3 +308,211 @@ When handling large volumes of database data, cross-thread data transfer may sti } } ``` + +## Using Sendable for Large-Scale Database Operations with Complex Class Instances + +The properties of regular class instances can contain Sendable class instances. + +For complex regular class instances, you can first wrap the relevant database data fields in Sendable class instances and then let the regular class instances hold these Sendable class instances. This can help lower the cost of cross-thread operations. + +1. Define the data format in the database. Sendable can be used to minimize cross-thread latency. + + ```ts + // SharedValuesBucket.ets + export interface IValueBucket { + id: number; + name: string; + age: number; + salary: number; + } + + @Sendable + export class SharedValuesBucket implements IValueBucket { + id: number = 0; + name: string = ""; + age: number = 0; + salary: number = 0; + + constructor(v: IValueBucket) { + this.id = v.id; + this.name = v.name; + this.age = v.age; + this.salary = v.salary; + } + } + ``` + +2. Define a regular class instance to hold the Sendable class instance. + + ```ts + // Material.ets + import { SharedValuesBucket } from './SharedValuesBucket'; + import { collections } from '@kit.ArkTS'; + + export class Material { + seq: number = 0; + materialName: string = ""; + //... Other properties are omitted. + buckets: collections.Array; + + constructor(seq: number, materialName: string, buckets: collections.Array) { + this.seq = seq; + this.materialName = materialName; + this.buckets = buckets; + } + + getBuckets() : collections.Array{ + return this.buckets; + } + + setBuckets(buckets: collections.Array) { + this.buckets = buckets; + } + } + ``` + +3. Initiate from the UI main thread and perform Create, Read, Update, Delete (CRUD) operations in the background thread. + + ```ts + // Index.ets + import { relationalStore, ValuesBucket } from '@kit.ArkData'; + import { collections, taskpool } from '@kit.ArkTS'; + import { IValueBucket, SharedValuesBucket } from './SharedValuesBucket'; + import { Material } from './Material'; + + @Concurrent + async function create(context: Context) { + const CONFIG: relationalStore.StoreConfig = { + name: "Store.db", + securityLevel: relationalStore.SecurityLevel.S1, + }; + + // The default database file path is context.databaseDir + rdb + StoreConfig.name. + let store: relationalStore.RdbStore = await relationalStore.getRdbStore(context, CONFIG); + console.info(`Create Store.db successfully!`); + + // Create a table. + const CREATE_TABLE_SQL = "CREATE TABLE IF NOT EXISTS test (" + + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + + "name TEXT NOT NULL, " + + "age INTEGER, " + + "salary REAL, " + + "blobType BLOB)"; + await store.executeSql(CREATE_TABLE_SQL); + console.info(`Create table test successfully!`); + } + + @Concurrent + async function insert(context: Context, valueBucketArray: collections.Array) { + const CONFIG: relationalStore.StoreConfig = { + name: "Store.db", + securityLevel: relationalStore.SecurityLevel.S1, + }; + + // The default database file path is context.databaseDir + rdb + StoreConfig.name. + let store: relationalStore.RdbStore = await relationalStore.getRdbStore(context, CONFIG); + console.info(`Create Store.db successfully!`); + + // Insert data. + await store.batchInsert("test", valueBucketArray as Object as Array); + } + + @Concurrent + async function query(context: Context): Promise> { + const CONFIG: relationalStore.StoreConfig = { + name: "Store.db", + securityLevel: relationalStore.SecurityLevel.S1, + }; + + // The default database file path is context.databaseDir + rdb + StoreConfig.name. + let store: relationalStore.RdbStore = await relationalStore.getRdbStore(context, CONFIG); + console.info(`Create Store.db successfully!`); + + // Obtain the result set. + let predicates: relationalStore.RdbPredicates = new relationalStore.RdbPredicates("test"); + let resultSet = await store.query(predicates); // Query all data. + console.info(`Query data successfully! row count:${resultSet.rowCount}`); + let index = 0; + let result = collections.Array.create(resultSet.rowCount, undefined) + resultSet.goToFirstRow() + do { + let v: IValueBucket = { + id: resultSet.getLong(resultSet.getColumnIndex("id")), + name: resultSet.getString(resultSet.getColumnIndex("name")), + age: resultSet.getLong(resultSet.getColumnIndex("age")), + salary: resultSet.getLong(resultSet.getColumnIndex("salary")) + }; + result[index++] = new SharedValuesBucket(v) + } while (resultSet.goToNextRow()); + resultSet.close(); + return result + } + + @Concurrent + async function clear(context: Context) { + const CONFIG: relationalStore.StoreConfig = { + name: "Store.db", + securityLevel: relationalStore.SecurityLevel.S1, + }; + + // The default database file path is context.databaseDir + rdb + StoreConfig.name. + await relationalStore.deleteRdbStore(context, CONFIG); + console.info(`Delete Store.db successfully!`); + } + + function initMaterial() : Material { + // Prepare data. + const count = 5 + let valueBucketArray = collections.Array.create(count, undefined); + for (let i = 0; i < count; i++) { + let v: IValueBucket = { + id: i, + name: "zhangsan" + i, + age: 20, + salary: 5000 + 50 * i + }; + valueBucketArray[i] = new SharedValuesBucket(v); + } + let material = new Material(1, "test", valueBucketArray); + return material; + } + + @Entry + @Component + struct Index { + @State message: string = 'Hello World'; + + build() { + RelativeContainer() { + Text(this.message) + .id('HelloWorld') + .fontSize(50) + .fontWeight(FontWeight.Bold) + .alignRules({ + center: { anchor: '__container__', align: VerticalAlign.Center }, + middle: { anchor: '__container__', align: HorizontalAlign.Center } + }) + .onClick(async () => { + let context = getContext(this); + let material = initMaterial(); + await taskpool.execute(create, context); + await taskpool.execute(insert, context, material.getBuckets()); + let index = 0; + let ret: collections.Array = + await taskpool.execute(query, context) as collections.Array; + material.setBuckets(ret); + for (let v of ret.values()) { + console.info(`Row[${index}].id = ${v.id}`); + console.info(`Row[${index}].name = ${v.name}`); + console.info(`Row[${index}].age = ${v.age}`); + console.info(`Row[${index}].salary = ${v.salary}`); + index++; + } + await taskpool.execute(clear, context); + }) + } + .height('100%') + .width('100%') + } + } + ``` diff --git a/en/application-dev/arkts-utils/concurrent-loading-modules-guide.md b/en/application-dev/arkts-utils/concurrent-loading-modules-guide.md index 9b7e4cab5995a7decb93399d5d07faa98d637f09..56405b98f34d943ba343e63339fb5fc8c7b7827b 100644 --- a/en/application-dev/arkts-utils/concurrent-loading-modules-guide.md +++ b/en/application-dev/arkts-utils/concurrent-loading-modules-guide.md @@ -6,8 +6,8 @@ By leveraging the TaskPool capabilities provided by ArkTS, different service ini 1. Define each service module (SDK) (using Sendable objects as an example). -Define the calculator service module as follows: - + Define the calculator service module as follows: + ```ts // sdk/Calculator.ets import { collections } from '@kit.ArkTS' @@ -63,10 +63,10 @@ Define the calculator service module as follows: this.totalCount = this.history!.unshift(newRecord) } } -``` - -Define the timer service module as follows: - + ``` + + Define the timer service module as follows: + ```ts // sdk/TimerSdk.ets @Sendable @@ -84,9 +84,9 @@ Define the timer service module as follows: }) } } -``` - -2. In the UI main thread, trigger the distribution of service modules to child threads, and use them in the UI main thread after loading is complete. + ``` + +2. In the UI main thread, trigger the distribution of service modules to child threads, and use them in the UI main thread after loading is complete. The following is an example: ```ts // Index.ets diff --git a/en/application-dev/arkts-utils/gc-introduction.md b/en/application-dev/arkts-utils/gc-introduction.md index 24e4047baf296db5482900c7730e8537d54c5934..60a459ad2701e99a4bd7a8d55bd0e2cb68860558 100644 --- a/en/application-dev/arkts-utils/gc-introduction.md +++ b/en/application-dev/arkts-utils/gc-introduction.md @@ -31,7 +31,7 @@ function main() { let parent: Parent = new Parent(); let child: Child = new Child(); parent.child = child; - + child.parent = parent; } ``` In the example above, parent holds a reference to child, and child holds a reference to parent. This circular reference means that neither object's reference count will reach zero, even after the **main** function ends, resulting in a memory leak. @@ -48,6 +48,7 @@ Tracing GC identifies live objects by traversing the object graph starting from Given the limitations of reference counting, especially the critical issue of circular references, ArkTS Runtime uses tracing GC. ### Types of Tracing GC + Tracing GC algorithms identify garbage by traversing the object graph. Based on the collection method, tracing GC can be categorized into three basic types: mark-sweep, mark-copy, and mark-compact. In the diagrams below, blue indicates live objects, whereas yellow indicates garbage. #### Mark-Sweep Collection @@ -69,7 +70,7 @@ This approach eliminates memory fragmentation and completes the GC process in a ![image](./figures/mark-shuffle.png) After the traversal, live objects (blue) are copied to the beginning of the current space (or a designated area), and the copied objects are reclaimed and placed in the free list. -This approach addresses memory fragmentation without wasting half of the memory space, though it incurs slightly higher performance overhead when compared with mark-copy collection. +This approach addresses memory fragmentation without wasting half of the memory space, though it incurs higher performance overhead when compared with mark-copy collection. ### HPP GC @@ -94,9 +95,7 @@ Based on the characteristics of old generation objects, a heuristic collection s The collection policies are as follows: -- Identifies regions with live object sizes below a threshold, places them in the initial CSet, and sorts them by liveness - -(survival rate = live object size/region size). +- Identifies regions with live object sizes below a threshold, places them in the initial CSet, and sorts them by liveness (survival rate = live object size/region size). - Selects a final CSet based on a predefined number of regions for compaction. @@ -108,8 +107,6 @@ This heuristic approach combines the benefits of mark-compact and mark-sweep alg HPP GC introduces extensive concurrency and parallelism optimizations to minimize the impact on application performance. The GC process includes concurrent and parallel marking, sweeping, evacuation, updating, and clearing tasks. - - ## Heap Structure and Parameters ### Heap Structure @@ -137,8 +134,8 @@ You can use related APIs to query memory information by referring to [HiDebug AP #### Heap Size Parameters -| Parameter| Value or Value Range| Description| -| --- | --- | :--- | +| Name| Value or Value Range| Description| +| --- | --- | --- | | HeapSize | 448 MB| Default total heap size for the main thread. The value is adjusted for low-memory devices based on the actual memory pool size.| | SemiSpaceSize | 2–4 MB/2–8 MB/2–16 MB| Size of Semi Space.| | NonmovableSpaceSize | 2 MB/6 MB/64 MB | Size of Non-Movable Space.| @@ -147,32 +144,30 @@ You can use related APIs to query memory information by referring to [HiDebug AP #### Worker Thread Heap Limit -| Parameter| Value| Description| +| Name| Value| Description| | --- | --- | --- | | HeapSize | 768 MB | Heap size for worker threads.| #### Parameters of Semi Space - The heap contains two Semi Spaces for copying. -| Parameter| Value or Value Range| Description| -| --- | --- | :--- | +| Name| Value or Value Range| Description| +| --- | --- | --- | | semiSpaceSize | 2–4 MB/2–8 MB/2–16 MB| Size of Semi Space. The value varies according to the total heap size.| | semiSpaceTriggerConcurrentMark | 1 M/1.5 M/1.5 M| Threshold for independently triggering concurrent marking in Semi Space for the first time.| | semiSpaceStepOvershootSize| 2 MB | Maximum overshoot size of Semi Space.| #### Parameters of Old Space and Huge Object Space - Both spaces are initialized to the remaining unallocated heap size. By default, the upper limit of OldSpaceSize of the main thread on mobile phones approaches 350 MB. -| Parameter| Value| Description| -| --- | --- | :--- | +| Name| Value or Value Range| Description| +| --- | --- | --- | | oldSpaceOvershootSize | 4 MB/8 MB/8 MB | Maximum overshoot size of Old Space.| #### Parameters of Other Spaces -| Parameter| Value| Description| -| --- | --- | :--- | +| Name| Value or Value Range| Description| +| --- | --- | --- | | defaultReadOnlySpaceSize | 256 KB | Default size of Read Only Space.| | defaultNonMovableSpaceSize | 2 MB/6 MB/64 MB | Default size of Non-Movable Space.| | defaultSnapshotSpaceSize | 512 KB/512 KB/ 4 MB | Default size of Snapshot Space.| @@ -180,14 +175,14 @@ Both spaces are initialized to the remaining unallocated heap size. By default, #### Interpreter Stack Size -| Parameter| Value| Description| +| Name| Value or Value Range| Description| | --- | --- | --- | -| maxStackSize | 128 KB| Maximum frame size of the interpreter stack.| +| maxStackSize | 128 KB| Maximum size of the interpreter stack.| #### Concurrency Parameters -| Parameter| Value| Description| -| --- | ---: | --- | +| Name| Value| Description| +| --- | --- | --- | | gcThreadNum | 7 | Number of GC threads. The default value is 7. You can set this parameter using **gc-thread-num**.| | MIN_TASKPOOL_THREAD_NUM | 3 | Minimum number of threads in the thread pool.| | MAX_TASKPOOL_THREAD_NUM | 7 | Maximum number of threads in the thread pool.| @@ -196,7 +191,7 @@ Note: The thread pool is used to execute concurrent tasks in the GC process. Dur #### Other Parameters -| Parameter| Value| Description| +| Name| Value| Description| | --- | --- | --- | | minAllocLimitGrowingStep | 2 M/4 M/8 M| Minimum growth step of **oldSpace**, **heapObject**, and **globalNative** when the heap size is recalculated.| | minGrowingStep | 4 M/8 M/16 M| Minimum growth step of **oldSpace**.| @@ -206,7 +201,6 @@ Note: The thread pool is used to execute concurrent tasks in the GC process. Dur ## GC Process - ![image](./figures/gc-process.png) ### Types of HPP GC @@ -227,7 +221,7 @@ Note: The thread pool is used to execute concurrent tasks in the GC process. Dur #### Full GC -- **When to trigger**: Full GC is not triggered based on the memory threshold. After the application transitions to the background, full GC is triggered if the predicted reclaimable object size exceeds 2 MB. You can also trigger full GC using the DumpHeapSnapshot and AllocationTracker tools or calling native interfaces and JS/TS interfaces. +- **When to trigger**: Full GC is not triggered based on the memory threshold. After the application transitions to the background, full GC is triggered if the predicted reclaimable object size exceeds 2 MB. You can also trigger full GC using the DumpHeapSnapshot and AllocationTracker tools or calling native interfaces and ArkTS interfaces. - **Description**: fully compacts both young and old generations, maximizing memory reclamation in performance-insensitive scenarios. - **Scenario**: background - **Log keywords**: [ CompressGC ] @@ -274,21 +268,22 @@ Subsequent Smart GC or IDLE GC selections are made from the above three types of - Function: **AdjustOldSpaceLimit** - Description: adjusts the Old Space threshold based on the minimum growth step and average survival rate. -- Log keywords: **"AdjustOldSpaceLimit oldSpaceAllocLimit_: "<< oldSpaceAllocLimit <<" globalSpaceAllocLimit_: " << globalSpaceAllocLimit_;** +- Log keyword: **AdjustOldSpaceLimit** #### Adjusting Old Space/Global Space Thresholds and Growth Factors After Subsequent Old GCs - Function: **RecomputeLimits** - Description: recalculates and adjusts **newOldSpaceLimit**, **newGlobalSpaceLimit**, **globalSpaceNativeLimit**, and growth factors based on current GC statistics. -- Log keywords: **"RecomputeLimits oldSpaceAllocLimit_: "<< newOldSpaceLimit_ <<" globalSpaceAllocLimit_: "<< globalSpaceAllocLimit_ <<" globalSpaceNativeLimit_: "<< globalSpaceNativeLimit_;** +- Log keyword: **RecomputeLimits** #### CSet Selection Strategies for Partial GC - Function: **OldSpace::SelectCSet()** - Description: selects regions with fewer live objects and lower collection costs for partial GC. -- Log keywords: **Select CSet failure: number is too few**, - **"Max evacuation size is 6_MB. The CSet region number: " << selectedRegionNumber;**, - and **"Select CSet success: number is " << collectRegionSet_.size();** +- Typical Logs + - Select CSet failure: number is too few + - Max evacuation size is 6_MB. The CSet region number + - Select CSet success: number is ## SharedHeap @@ -309,7 +304,7 @@ Note: The shared heap is designed for objects shared across threads to improve e #### Description -In performance-sensitive scenarios, the GC trigger threshold of the JS thread is temporarily adjusted to the maximum JS heap size (448 MB by default), minimizing GC-triggered frame drops. (Smart GC does not take effect for the Worker thread and TaskPool thread.) However, if a performance-sensitive scenario persists too long and object allocation reaches the maximum heap size, GC is triggered, potentially resulting in longer GC times due to accumulated objects. +In performance-sensitive scenarios, the GC trigger threshold of the thread is temporarily adjusted to the maximum heap size (448 MB for the main thread by default), minimizing GC-triggered frame drops. (Smart GC does not take effect for the Worker thread and TaskPool thread.) However, if a performance-sensitive scenario persists too long and object allocation reaches the maximum heap size, GC is triggered, potentially resulting in longer GC times due to accumulated objects. #### Performance-Sensitive Scenarios @@ -351,7 +346,7 @@ The following logs represent a complete GC execution, with variations based on t // Pre-GC object size (region size) -> Post-GC object size (region size), total duration (+concurrentMark duration), GC trigger reason. C03F00/ArkCompiler: [gc] [ CompressGC ] 26.1164 (35) -> 7.10049 (10.5) MB, 160.626(+0)ms, Switch to background // Various states during GC execution and application name. -C03F00/ArkCompiler: [gc] IsInBackground: 1; SensitiveStatus: 0; OnStartupEvent: 0; BundleName: com.huawei.hmos.filemanager; +C03F00/ArkCompiler: [gc] IsInBackground: 1; SensitiveStatus: 0; OnStartupEvent: 0; BundleName: com.example.demo; // Duration statistics for each GC phase. C03F00/ArkCompiler: [gc] /***************** GC Duration statistic: ****************/ C03F00/ArkCompiler: [gc] TotalGC: 160.626 ms @@ -406,13 +401,13 @@ C03F00/ArkCompiler: Heap average alive rate: 0.635325 ## GC Developer Debugging Interfaces > **NOTE** -> +> > The following interfaces are for debugging purposes only and are not official SDK interfaces. They should not be used in production applications. ### ArkTools.hintGC() - Invocation: **ArkTools.hintGC()** -- Type: JS interface +- Type: ArkTS interface - Description: triggers the VM to assess whether a full GC should be executed. Full GC is initiated in the background or if the expected memory survival rate is below a threshold. It will not trigger in sensitive scenarios. - Use case: developers prompting the system to perform GC. - Log keywords: There is no direct log. Only external trigger (**GCReason::TRIGGER_BY_JS**) can be found. @@ -420,7 +415,7 @@ C03F00/ArkCompiler: Heap average alive rate: 0.635325 Usage example: -``` +```ts // Declare the interface first. declare class ArkTools { static hintGC(): void; diff --git a/en/application-dev/arkts-utils/js-apis-load-native-module.md b/en/application-dev/arkts-utils/js-apis-load-native-module.md index f1e0ac2365b1783be3a2e9b875ad4b41dd3cf210..a1c88c66d572536078bd8ee74fb601bf72539aa7 100644 --- a/en/application-dev/arkts-utils/js-apis-load-native-module.md +++ b/en/application-dev/arkts-utils/js-apis-load-native-module.md @@ -14,7 +14,7 @@ loadNativeModule(moduleName: string): Object; > **NOTE** > -> **moduleName** must be set to the module name configured in the **module.json5** file in the HAP to which the module to load belongs. +> The name of the module loaded by **loadNativeModule** is the name provided in **dependencies** in the **oh-package.json5** file of the dependency. > > **loadNativeModule** can be used only to load modules in the UI main thread. > @@ -22,9 +22,9 @@ loadNativeModule(moduleName: string): Object; ## Supported Scenarios -| Scenario | Example | -| :------------- | :----------------------------- | -| System library module | Load **@ohos.** or **@system.**. | +| Scenario | Example | +| :------------- | :----------------------------- | +| System library module | Load **@ohos.** or **@system.**. | | Native module in an application| Load **libNativeLibrary.so**.| ## Usage Example diff --git a/en/application-dev/arkts-utils/multi-thread-cancel-task.md b/en/application-dev/arkts-utils/multi-thread-cancel-task.md new file mode 100644 index 0000000000000000000000000000000000000000..042bd40afd2dc9bbc246764ef0652fac1c2310a0 --- /dev/null +++ b/en/application-dev/arkts-utils/multi-thread-cancel-task.md @@ -0,0 +1,68 @@ +# Canceling Tasks in Multithreading with TaskPool + +[Task](../reference/apis-arkts/js-apis-taskpool.md#task) objects of the [TaskPool](../reference/apis-arkts/js-apis-taskpool.md) cannot be passed to child threads. Therefore, tasks cannot be canceled from child threads prior to API version 18. Starting from API version 18, tasks have been enhanced with the [task ID](../reference/apis-arkts/js-apis-taskpool.md#properties), allowing tasks to be canceled in child threads using this ID. The following example describes how to cancel a task that has been submitted to the TaskPool in a multithreaded environment. You can store the task ID of a created task in a [Sendable object](./arkts-sendable.md) and use this object to cancel the task from a child thread. + +1. Define a Sendable class and store the task ID in the class properties. + + ```ts + // Mock.ets + + @Sendable + export class SendableTest { + // Store the task ID. + private taskId: number = 0; + + constructor(id: number) { + this.taskId = id; + } + + public getTaskId(): number { + return this.taskId; + } + } + ``` + +2. Submit a delayed task to the TaskPool from the UI main thread and cancel it from a child thread. + + ```ts + // Index.ets + + import { taskpool } from '@kit.ArkTS'; + import { SendableTest } from './Mock' + + @Concurrent + function cancel(send: SendableTest) { + console.info("cancel task finished"); + // Cancel the task in the child thread based on the task ID. + taskpool.cancel(send.getTaskId()); + } + + @Concurrent + function delayed() { + console.info("delayed task finished"); + } + + @Entry + @Component + struct Index { + @State message: string = 'Hello World!'; + @State books: string[] = []; + + build() { + Column({ space: 1 }) { + Button(this.books[3]) + .fontSize(20) + .padding(10) + .fontWeight(FontWeight.Bold) + .onClick(async () => { + let task = new taskpool.Task(delayed); + taskpool.executeDelayed(2000, task); + let send = new SendableTest(task.taskId); + taskpool.execute(cancel, send); + }) + } + .height('100%') + .width('100%') + } + } + ``` diff --git a/en/application-dev/arkts-utils/multi-thread-concurrency-overview.md b/en/application-dev/arkts-utils/multi-thread-concurrency-overview.md index 739719446a6a2cecc99be8e2e1bba7a559f22727..9e8db934f9617d666c00d51d608c4a3ddc8f584b 100644 --- a/en/application-dev/arkts-utils/multi-thread-concurrency-overview.md +++ b/en/application-dev/arkts-utils/multi-thread-concurrency-overview.md @@ -182,6 +182,61 @@ struct Index { } ``` +You can also wait until all the producer's tasks are complete, and then pass the results to the UI thread through serialization. After the UI thread receives the results, the consumer can handle them all together. + +```ts +import { taskpool } from '@kit.ArkTS'; + +// Cross-thread concurrent tasks +@Concurrent +async function produce(): Promise { + // Add production logic here. + console.info("producing..."); + return Math.random(); +} + +class Consumer { + public consume(value: Object) { + // Add consumption logic here. + console.info("consuming value: " + value); + } +} + +@Entry +@Component +struct Index { + @State message: string = 'Hello World' + + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + Button() { + Text("start") + }.onClick(async () => { + let dataArray = new Array(); + let produceTask: taskpool.Task = new taskpool.Task(produce); + let consumer: Consumer = new Consumer(); + for (let index: number = 0; index < 10; index++) { + // Execute the asynchronous concurrent production task. + let result = await taskpool.execute(produceTask) as number; + dataArray.push(result); + } + for (let index: number = 0; index < dataArray.length; index++) { + consumer.consume(dataArray[index]); + } + }) + .width('20%') + .height('20%') + } + .width('100%') + } + .height('100%') + } +} +``` ## TaskPool and Worker diff --git a/en/application-dev/arkts-utils/sendablelrucache-recent-list.md b/en/application-dev/arkts-utils/sendablelrucache-recent-list.md new file mode 100644 index 0000000000000000000000000000000000000000..f62201316a264fc92012dbbd7fcc823f9fe0fda6 --- /dev/null +++ b/en/application-dev/arkts-utils/sendablelrucache-recent-list.md @@ -0,0 +1,312 @@ +# Obtaining the Recently Accessed List + +To quickly access the recently used [Sendable](arkts-sendable.md) objects, ArkTS introduces [SendableLruCache](../reference/apis-arkts/js-apis-arkts-utils.md#sendablelrucachek-v18) since API version 18. With this class, you can add, delete, and obtain Sendable objects from a SendableLruCache instance to quickly access the recently used Sendable objects. This topic describes how to use SendableLruCache to obtain the recently accessed list. It uses a bookshelf as an example. Every time a user opens a book, the book information is updated to the recently accessed list. When the user accesses the bookshelf next time, the list of books that the user has looked at is displayed. + +> **NOTE** +> +> SendableLruCache instances must be locked to prevent data inconsistency caused by concurrent operations from multiple threads. +> +> Only Sendable objects can be put into a SendableLruCache instance. + +1. Create a SendableLruCache instance and set its maximum capacity based on service requirements. + + In this example, the maximum capacity of the SendableLruCache instance is set to 4, the Sendable class is used for management, and the Sendable class instance is exported. + + ```ts + // LruCache.ets + + import { ArkTSUtils } from '@kit.ArkTS'; + + // Use the 'use shared' marker to make the Sendable class instance shareable across different threads. + "use shared" + + @Sendable + class SendableClass { + // Lock the SendableLruCache instances to prevent data inconsistency caused by concurrent operations from multiple threads. + lock_: ArkTSUtils.locks.AsyncLock = new ArkTSUtils.locks.AsyncLock(); + books_: ArkTSUtils.SendableLruCache = new ArkTSUtils.SendableLruCache(4); + + constructor() { + this.books_.put("fourth", "Book4"); + this.books_.put("third", "Book3"); + this.books_.put("second", "Book2"); + this.books_.put("first", "Book1"); + } + + // Wrap the put, get, and keys methods and perform the lock operation. + public async put(key: string, value: string) { + await this.lock_.lockAsync(() => { + this.books_.put(key, value); + }) + } + + public async get(key: string): Promise { + return this.lock_.lockAsync(() => { + return this.books_.get(key); + }); + } + + public async keys(): Promise { + return this.lock_.lockAsync(() => { + return this.books_.keys(); + }); + } + } + + export let lruCache = new SendableClass(); + ``` + +2. In the same directory as the **Index.ets** page, create four book pages. Each page shows its own book information. Register the path of each page in the **main_pages.json** file under **src/main/resources/base/profile/**. + + ```ts + // Book1.ets + + import { router } from '@kit.ArkUI'; + + @Entry + @Component + struct Index1 { + @State message: string = 'Hello World!'; + + build() { + RelativeContainer() { + Text("Content of book 1") + .id('first book') + .fontSize(20) + .padding(10) + .fontWeight(FontWeight.Bold) + .alignRules({ + center: { anchor: 'container', align: VerticalAlign.Center }, + middle: { anchor: 'container', align: HorizontalAlign.Center } + }) + Button('Back') + .fontSize(20) + .padding(10) + .fontWeight(FontWeight.Bold) + .onClick(() => { + router.pushUrl({ + url: 'pages/Index', + }); + }) + } + .height('100%') + .width('100%') + } + } + ``` + ```ts + // Book2.ets + + import { router } from '@kit.ArkUI'; + + @Entry + @Component + struct Index2 { + @State message: string = 'Hello World!'; + + build() { + RelativeContainer() { + Text("Content of book 2") + .id('second book') + .fontSize(20) + .padding(10) + .fontWeight(FontWeight.Bold) + .alignRules({ + center: { anchor: 'container', align: VerticalAlign.Center }, + middle: { anchor: 'container', align: HorizontalAlign.Center } + }) + Button('Back') + .fontSize(20) + .padding(10) + .fontWeight(FontWeight.Bold) + .onClick(() => { + router.pushUrl({ + url: 'pages/Index', + }); + }) + } + .height('100%') + .width('100%') + } + } + ``` + ```ts + // Book3.ets + + import { router } from '@kit.ArkUI'; + + @Entry + @Component + struct Index3 { + @State message: string = 'Hello World!'; + + build() { + RelativeContainer() { + Text("Content of book 3") + .id('third book') + .fontSize(20) + .padding(10) + .fontWeight(FontWeight.Bold) + .alignRules({ + center: { anchor: 'container', align: VerticalAlign.Center }, + middle: { anchor: 'container', align: HorizontalAlign.Center } + }) + Button('Back') + .fontSize(20) + .padding(10) + .fontWeight(FontWeight.Bold) + .onClick(() => { + router.pushUrl({ + url: 'pages/Index', + }); + }) + } + .height('100%') + .width('100%') + } + } + ``` + ```ts + // Book4.ets + + import { router } from '@kit.ArkUI'; + + @Entry + @Component + struct Index4 { + @State message: string = 'Hello World!'; + + build() { + RelativeContainer() { + Text("Content of book 4") + .id('fourth book') + .fontSize(20) + .padding(10) + .fontWeight(FontWeight.Bold) + .alignRules({ + center: { anchor: 'container', align: VerticalAlign.Center }, + middle: { anchor: 'container', align: HorizontalAlign.Center } + }) + Button('Back') + .fontSize(20) + .padding(10) + .fontWeight(FontWeight.Bold) + .onClick(() => { + router.pushUrl({ + url: 'pages/Index', + }); + }) + } + .height('100%') + .width('100%') + } + } + ``` + ```json + // main_pages.json + + { + "src": [ + "pages/Index", + "pages/Book1", + "pages/Book2", + "pages/Book3", + "pages/Book4" + ] + } + ``` + +3. Each time a user accesses the bookshelf page, the application automatically obtains and displays the list of recently accessed books. + + ```ts + // Index.ets + + import { taskpool } from '@kit.ArkTS'; + import { router } from '@kit.ArkUI'; + import { lruCache } from './LruCache' + + @Concurrent + async function updateBooks(key: string, value: string) { + // Update the latest access list in the child thread. + await lruCache.put(key, value); + } + + @Entry + @Component + struct Index { + @State message: string = 'Bookshelf' + @State books: string[] = []; + + async aboutToAppear () { + // The application automatically obtains the list of recently accessed books. + this.books = await lruCache.keys(); + } + + build() { + Column({ space: 1 }) { + Text(this.message) + .id('HelloWorld') + .fontSize(50) + .fontWeight(FontWeight.Bold) + .alignRules({ + center: { anchor: 'container', align: VerticalAlign.Center }, + middle: { anchor: 'container', align: HorizontalAlign.Center } + }) + Button(this.books[3]) + .fontSize(20) + .padding(10) + .fontWeight(FontWeight.Bold) + .onClick(async () => { + // Obtain the bound book information. + let value = await lruCache.get(this.books[3]); + // Update the recently accessed list. + taskpool.execute(updateBooks, this.books[3], value); + router.pushUrl({ + url: 'pages/' + value, + }); + }) + Button(this.books[2]) + .fontSize(20) + .padding(10) + .fontWeight(FontWeight.Bold) + .onClick(async () => { + // Obtain the bound book information. + let value = await lruCache.get(this.books[2]); + // Update the recently accessed list. + taskpool.execute(updateBooks, this.books[2], value); + router.pushUrl({ + url: 'pages/' + value, + }); + }) + Button(this.books[1]) + .fontSize(20) + .padding(10) + .fontWeight(FontWeight.Bold) + .onClick(async () => { + // Obtain the bound book information. + let value = await lruCache.get(this.books[1]); + // Update the recently accessed list. + taskpool.execute(updateBooks, this.books[1], value); + router.pushUrl({ + url: 'pages/' + value, + }); + }) + Button(this.books[0]) + .fontSize(20) + .padding(10) + .fontWeight(FontWeight.Bold) + .onClick(async () => { + // Obtain the bound book information. + let value = await lruCache.get(this.books[0]); + // Update the recently accessed list. + taskpool.execute(updateBooks, this.books[0], value); + router.pushUrl({ + url: 'pages/' + value, + }); + }) + } + .height('100%') + .width('100%') + } + } + ``` \ No newline at end of file diff --git a/en/application-dev/arkts-utils/source-obfuscation-guide.md b/en/application-dev/arkts-utils/source-obfuscation-guide.md index 85369c0e210b36f6d7e8e1cd81cab94c0234b72f..b4affd09dd5ca461856104c39aaf11b9a4b65eb4 100644 --- a/en/application-dev/arkts-utils/source-obfuscation-guide.md +++ b/en/application-dev/arkts-utils/source-obfuscation-guide.md @@ -17,7 +17,7 @@ The source code obfuscation feature is integrated into the system and can be ena "files": ["./obfuscation-rules.txt"], } } -} + } ``` * Configuring obfuscation rules @@ -67,20 +67,20 @@ The source code obfuscation feature is integrated into the system and can be ena For HAR and HSP modules, an additional **arkOptions.obfuscation.consumerFiles** field is available in the **build-profile.json5** file. This field specifies obfuscation rules that should be applied when this package is depended upon in the current compilation process. A default **consumer-rules.txt** file is created when a new HAR or HSP module is set up. The key difference between **consumer-rules.txt** and **obfuscation-rules.txt** is as follows: **obfuscation-rules.txt** applies to the compilation of the current module, whereas **consumer-rules.txt** applies to the compilation of other modules that depend on the current module. ``` - "arkOptions": { - "obfuscation": { - "ruleOptions": { - "enable": true, - "files": ["./obfuscation-rules.txt"], - } - "consumerFiles": ["./consumer-rules.txt"] - } + "arkOptions": { + "obfuscation": { + "ruleOptions": { + "enable": true, + "files": ["./obfuscation-rules.txt"], + } + "consumerFiles": ["./consumer-rules.txt"] + } } ``` - -* `obfuscation.txt` - Unlike the above two files, **obfuscation.txt** is automatically generated based on **consumer-rules.txt** and the obfuscation rules of dependent modules during HAR or HSP compilation. It exists as a compilation product within the released HAR or HSP package. When other applications depend on this package, the obfuscation rules are merged and applied to the current compilation process. For details about the generation and merging logic of **obfuscation.txt**, see [Obfuscation Rule Merging Strategies](source-obfuscation.md#obfuscation-rule-merging-strategies). +* `obfuscation.txt` + + Unlike the above two files, **obfuscation.txt** is automatically generated based on **consumer-rules.txt** and the obfuscation rules of dependent modules during HAR or HSP compilation. It exists as a compilation product within the released HAR or HSP package. When other applications depend on this package, the obfuscation rules are merged and applied to the current compilation process. For details about the generation and merging logic of **obfuscation.txt**, see [Obfuscation Rule Merging Strategies](source-obfuscation.md#obfuscation-rule-merging-strategies). > **NOTE** > diff --git a/en/application-dev/arkts-utils/source-obfuscation-questions.md b/en/application-dev/arkts-utils/source-obfuscation-questions.md index 18f1cbee12f00c3fb2efcdd6a66a3857398c0f6a..304c72b5f72e7750c2f20924fc6446119c3861a9 100644 --- a/en/application-dev/arkts-utils/source-obfuscation-questions.md +++ b/en/application-dev/arkts-utils/source-obfuscation-questions.md @@ -33,17 +33,14 @@ If **-compact** is not configured for the current module, but the code in the ob * Search for **-compact** in the **consumer-rules.txt** file in the local libraries. * Search for **-compact** in all **obfuscation.txt** files in the project-level **oh_modules** directory. -**NOTE** - -You are not advised to configure the following options in the **obfuscation.txt** file of third-party libraries, as they can cause unexpected behavior or crashes when the main module is obfuscated. Contact the library providers to remove these options and repackage the libraries. - -``` --enable-property-obfuscation --enable-string-property-obfuscation --enable-toplevel-obfuscation --remove-log --compact -``` +> **NOTE** +> +> You are not advised to configure the following options in the **obfuscation.txt** file of third-party libraries, as they can cause unexpected behavior or crashes when the main module is obfuscated. Contact the library providers to remove these options and repackage the libraries. +> -enable-property-obfuscation +> -enable-string-property-obfuscation +> -enable-toplevel-obfuscation +> -remove-log +> -compact ## Property Obfuscation Issues @@ -197,7 +194,7 @@ A dependent module may have enabled string property name obfuscation, affecting **Solution** -Solution 1: Check whether any dependent modules have enabled string property name obfuscation. If yes, disable it. +Solution 1: Check whether any dependent modules have enabled string property name obfuscation. If yes, disable it. Solution 2: If the problematic module cannot be identified, add the string literal property names to the trustlist directly. @@ -325,6 +322,6 @@ The HAP and HSP modules execute independent build and obfuscation processes, res **Solution** -Solution 1: Change the shared local source code HAR to a [bytecode HAR](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/ide-hvigor-build-har-V5#section179161312181613). This prevents the HAR from being re-obfuscated when being depended upon. +Solution 1: Change the shared local source code HAR to a [bytecode HAR](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/ide-hvigor-build-har-V5#section179161312181613). This prevents the HAR from being re-obfuscated when being depended upon. -Solution 2: Build the shared local source code HAR in [release mode](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/ide-hvigor-build-har-V5#section19788284410). This ensures that file names and exported interfaces are not obfuscated when the HAR is depended upon. \ No newline at end of file +Solution 2: Build the shared local source code HAR in [release mode](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/ide-hvigor-build-har-V5#section19788284410). This ensures that file names and exported interfaces are not obfuscated when the HAR is depended upon. diff --git a/en/application-dev/arkts-utils/source-obfuscation.md b/en/application-dev/arkts-utils/source-obfuscation.md index b93464682e2f582167bcfb6a6d76c7e8e0592c6f..c0b738136e7bd6e225e7713f54505a0bc46ee611 100644 --- a/en/application-dev/arkts-utils/source-obfuscation.md +++ b/en/application-dev/arkts-utils/source-obfuscation.md @@ -117,6 +117,7 @@ Before using obfuscation, you are advised to learn about the capabilities of [ob | Reducing the default system API trustlist| [`-extra-options strip-system-api-args`](#-extra-options-strip-system-api-args) | | Retaining declaration file parameters| [`-keep-parameter-names`](#-keep-parameter-names) | | Merging dependent module options| [`-enable-lib-obfuscation-options`](#-enable-lib-obfuscation-options) | +| Marking trustlists in source code by comments| [`-use-keep-in-source`](#-use-keep-in-source) | ### -disable-obfuscation @@ -522,6 +523,199 @@ Obfuscation configuration includes [obfuscation options](#obfuscation-options) a For details about the merging logic, see [Obfuscation Rule Merging Strategies](#obfuscation-rule-merging-strategies). +### -use-keep-in-source + +Marks trustlists in .ts or .ets source code using the following two comment annotations (declaration files are not supported): + +// @KeepSymbol: This annotation is used to mark names that should be retained. It is usually placed on the line above the relevant code to ensure that the name is not obfuscated when the code is compiled. + +// @KeepAsConsumer: This annotation is used to mark names that should be retained. It is usually placed on the line above the relevant code to ensure that the name is not obfuscated when the code is compiled. In HAR/HSP modules, names marked with @KeepAsConsumer are also listed in the **obfuscation.txt** file. In HAP modules, @KeepAsConsumer works exactly like @KeepSymbol. + +> **NOTE** +> +> Both types of markings are comments and the slashes (//) should not be removed. + + + +The examples below use // @KeepSymbol, but // @KeepAsConsumer can be used in the same way for the same purposes. + +#### Classes + +You can mark the following elements in a class: + +- Class declarations +- Constructors +- Fields and methods + +**Example** + +```typescript +// Retain the class name and all member names. +// @KeepSymbol +class MyClass01 { + prop01: string = "prop"; // MyClass01 and prop01 are not obfuscated. +} + +// Use the constructor to retain the class name. +class MyClass02 { + prop02: string = "prop"; + // @KeepSymbol + constructor() {}; // MyClass02 is not obfuscated. +} + +// Retain the class name and specified field and method names. MyClass03, prop03_1, and method03_2 in the class are not obfuscated. +class MyClass03 { + // @KeepSymbol + prop03_1: string = "prop"; + prop03_2: number = 1; + constructor() {}; + + method03_1(): void {}; + // @KeepSymbol + method03_2(): void {}; +} +``` + +#### Interfaces + +You can mark the following elements in an interface: + +- Interface declarations +- Fields and methods + +**Example** + +```typescript +// Retain the interface name and all member names. MyInterface01, name01, and foo01 are not obfuscated. +// @KeepSymbol +interface MyInterface01 { + name01: string; + foo01(): void; +} + +// Retain the interface name and specified field and method names. MyInterface02 and name02 are not obfuscated. +interface MyInterface02 { + // @KeepSymbol + name02: string; + foo02(): void; +} +``` + +#### Enums + +You can mark the following elements in an enum: + +- Enum declarations +- Enum members + +**Example** + +```typescript +// Retain the enum name and all member names. Color01, RED01, and BLUE01 are not obfuscated. +// @KeepSymbol +enum Color01 { + RED01, + BLUE01 +} + +// Retain the specified enum member name. +enum Color02 { + RED02, + // @KeepSymbol + BLUE02 // Color02 and BLUE02 are not obfuscated. +} +``` + +#### Functions + +Currently, function names can be marked. + +**Example** + +```typescript +// Retain the function name. MyAdd is not obfuscated. +// @KeepSymbol +function MyAdd(a: number, b:number): number { + return a + b; +} +``` + +#### Namespaces + +Currently, namespace names can be marked. + +**Example** + +```typescript +// Retain the namespace name and the member names directly exported internally. MyNameSpace and foo are not obfuscated. +// @KeepSymbol +namespace MyNameSpace { + export function foo(){}; + function bar(){}; +} +``` + +#### Global Variables + +Currently, only global variables can be marked. Local variables cannot be marked. + +**Example** + +```typescript +// Retain the marked variable name. myVal is not obfuscated. +// @KeepSymbol +const myVal = 1; +``` + +#### Trustlist Addition Rules + +Marked names are added to the obfuscation trustlist based on the following rules. Names kept by **KeepAsConsumer** are also recorded in the **obfuscation.txt** file. + +* If a name is at the top level or directly exported, it goes into -keep-global-name. + +* If a name is directly exported, it also goes into -keep-property-name. + +* If a name is a property, it goes into -keep-property-name. + +* Local variable names are not added to the trustlist (they are not kept). + +**Example** + +```typescript +// @KeepAsConsumer +export class MyClass { + prop01: string = "prop"; +} +``` +In this example, MyClass is added to -keep-global-name and -keep-property-name, and prop01 is added to -keep-property-name. They are also written into the **obfuscation.txt** file. + +#### -Scenarios Not Supported by -use-keep-in-source + +String properties, numeric properties, and computed properties are not supported. + +**Example** + +```typescript +const myMethodName = "myMethod"; + +// 11, aa, and myMethod are not added to the trustlist. +class MyClass01 { + // @KeepSymbol + 11:11; + // @KeepSymbol + 'aa':'aa'; + // @KeepSymbol + [myMethodName](){} +} + +// RED is not added to the trustlist. +enum MyEnum { + // @KeepSymbol + 'RED', + BLUE +} +``` + ## Retention Options ### Summary of Existing Retention Options @@ -796,9 +990,9 @@ Retains all names (such as variable names, class names, and property names) in t ``` // Positive example: -keep -./oh_modules/harName1 // Names in all the files under the harName1 directory and its subdirectories are not confused. -./oh_modules/harName1/src // Names in all the files under the src directory and its subdirectories are not confused. -./oh_modules/folder/harName2 // Names in all the files under the harName2 directory and its subdirectories are not confused. +./oh_modules/harName1 // Names in all the files under the harName1 directory and its subdirectories are not obfuscated. +./oh_modules/harName1/src // Names in all the files under the src directory and its subdirectories are not obfuscated. +./oh_modules/folder/harName2 // Names in all the files under the harName2 directory and its subdirectories are not obfuscated. // Negative example: -keep @@ -809,8 +1003,8 @@ Retains all names (such as variable names, class names, and property names) in t ``` -keep -../oh_modules // Names in all the files under the project-level oh_modules and its subdirectories are not confused. -../oh_modules/harName3 // Names in all the files under the harName3 directory and its subdirectories are not confused. +../oh_modules // Names in all the files under the project-level oh_modules and its subdirectories are not obfuscated. +../oh_modules/harName3 // Names in all the files under the harName3 directory and its subdirectories are not obfuscated. ``` The following figure shows the directory structure of module-level oh_moudles and project-level oh_modules in DevEco Studio. @@ -1013,3 +1207,4 @@ When the obfuscation configuration file specified by **consumerFiles** contains | -keep-comments | Retains the classes, functions, namespaces, enums, structs, interfaces, modules, types, and JsDoc comments above properties in the declaration file generated after compilation.| 4.1.5.3 | | -keep | Retains all names in the specified path.| 5.0.0.18 | | Wildcard | The retention options of the name classes and path classes support wildcards.| 5.0.0.24 | +| -use-keep-in-source | Marks trustlists in source code by comments.| 5.1.0.57 | diff --git a/en/application-dev/arkts-utils/taskpool-async-task-guide.md b/en/application-dev/arkts-utils/taskpool-async-task-guide.md index 0193bd85d79ae1d444c343be9ebf1e24dbd19a9f..211ff76854d42389cf529cce9359a1865d71be31 100644 --- a/en/application-dev/arkts-utils/taskpool-async-task-guide.md +++ b/en/application-dev/arkts-utils/taskpool-async-task-guide.md @@ -1,6 +1,6 @@ # Specifying Task Concurrency with TaskPool -This section describes how to use TaskPool to manage [asynchronous queues](../reference/apis-arkts/js-apis-taskpool.md#asyncrunner16). It uses the operation of collection and processing of camera preview stream data as an example. +This section describes how to use TaskPool to manage [asynchronous queues](../reference/apis-arkts/js-apis-taskpool.md#asyncrunner18). It uses the operation of collection and processing of camera preview stream data as an example. This operation is frequent and time consuming. If the camera captures data too quickly, earlier frames are discarded to ensure only the most recent frame is processed. 1. Import the required modules. diff --git a/en/application-dev/arkts-utils/taskpool-introduction.md b/en/application-dev/arkts-utils/taskpool-introduction.md index 555ed75058405a99a3856e788fd055e02df521f9..bb2ccb9c84c3d31bcf4c4e6d4fd57d69ea9fcb9a 100644 --- a/en/application-dev/arkts-utils/taskpool-introduction.md +++ b/en/application-dev/arkts-utils/taskpool-introduction.md @@ -32,6 +32,10 @@ With TaskPool, you can encapsulate tasks in the host thread and submit the tasks - [AppStorage](../quick-start/arkts-appstorage.md) cannot be used in TaskPool worker threads. +- TaskPool allows you to package tasks in the host thread and submit them to the task queue. While it can theoretically handle an unlimited number of tasks, the actual task execution is influenced by the task priority and the availability of system resources. Once the Worker threads reach their maximum capacity, the efficiency of task execution might be compromised. + +- TaskPool does not allow you to specify the thread where a task runs. Instead, tasks are assigned to run in available threads. If you want to specify the thread for running a task, using [Worker](./worker-introduction.md) is a better approach. + ## \@Concurrent Decorator To pass function verification, concurrent functions executed in a [TaskPool](../reference/apis-arkts/js-apis-taskpool.md) must be decorated using \@Concurrent. @@ -48,7 +52,7 @@ To pass function verification, concurrent functions executed in a [TaskPool](../ | Use scenario| Used only in projects of the stage model and only in .ets files.| | Decorated function types| Used for async functions or regular functions. It cannot be used for generators, arrow functions, or class methods. It does not support class member functions or anonymous functions.| | Variable types in decorated functions| Local variables, parameters, and variables imported via **import** are allowed. Closure variables are prohibited.| -| Return value types in decorated functions| Supported types are listed in [Inter-Thread Communication](interthread-communication-overview.md). | +| Return value types in decorated functions| Supported types are listed in [Inter-Thread Communication](interthread-communication-overview.md).| > **NOTE** > @@ -122,22 +126,22 @@ import { taskpool } from '@kit.ArkTS'; @Concurrent function testPromise(args1: number, args2: number): Promise { - return new Promise((testFuncA, testFuncB)=>{ - testFuncA(args1 + args2); + return new Promise((resolve, reject)=>{ + resolve(args1 + args2); }); } @Concurrent async function testPromise1(args1: number, args2: number): Promise { - return new Promise((testFuncA, testFuncB)=>{ - testFuncA(args1 + args2); + return new Promise((resolve, reject)=>{ + resolve(args1 + args2); }); } @Concurrent async function testPromise2(args1: number, args2: number): Promise { - return await new Promise((testFuncA, testFuncB)=>{ - testFuncA(args1 + args2); + return await new Promise((resolve, reject)=>{ + resolve(args1 + args2); }); } diff --git a/en/application-dev/arkts-utils/taskpool-vs-worker.md b/en/application-dev/arkts-utils/taskpool-vs-worker.md index 342bffd6cb3aeb587a008f7ca1260b7ef2be26a0..f9b92e169731da44cbd71c6e4fd1270cb5df814a 100644 --- a/en/application-dev/arkts-utils/taskpool-vs-worker.md +++ b/en/application-dev/arkts-utils/taskpool-vs-worker.md @@ -21,7 +21,7 @@ This topic compares TaskPool and Worker based on their implementation characteri | Lifecycle management| TaskPool manages its own lifecycle, without considering task load.| Developers are required to manage the number and lifecycle of Worker threads.| | Maximum number of tasks| The number is automatically managed, rather than being manually configured.| A maximum of 64 Worker threads can run simultaneously in the same process. The actual number is determined by the process memory.| | Maximum task duration| 3 minutes (excluding time spent on Promise and async/await calls, such as network downloads and file read/write operations). There is no upper limit on the duration of continuous tasks.| There is no limit.| -| Task priority setting| Setting the task priority is supported.| Since API version 16, the Worker thread priority can be configured.| +| Task priority setting| Setting the task priority is supported.| Since API version 18, the Worker thread priority can be configured.| | Task cancellation| Supported.| Not supported.| | Thread reuse| Supported.| Not supported.| | Delayed task execution| Supported.| Not supported.| @@ -42,7 +42,7 @@ Common use cases are as follows: - Associated synchronous tasks: In scenarios where a series of synchronous tasks is required, such as when creating and using handles that must be permanently stored, Worker is recommended to ensure proper management of these handles. For details, see [Using Worker for Interdependent Synchronous Tasks](./sync-task-development.md#using-worker-for-interdependent-synchronous-tasks). -- Tasks requiring priority setting: In versions earlier than API version 16, Worker does not support setting scheduling priorities, so TaskPool is necessary. Since API version 16, Worker supports priority settings, allowing you to choose between TaskPool and Worker based on your use case and task characteristics. For example, in a Gallery histogram rendering scenario, background calculations for histogram data that affect user experience should be prioritized, making TaskPool the recommended choice. +- Tasks requiring priority setting: In versions earlier than API version 18, Worker does not support setting scheduling priorities, so TaskPool is necessary. Since API version 18, Worker supports priority settings, allowing you to choose between TaskPool and Worker based on your use case and task characteristics. For example, in a Gallery histogram rendering scenario, background calculations for histogram data that affect user experience should be prioritized, making TaskPool the recommended choice. - Frequently canceled tasks: For tasks that need to be canceled often, such as in a Gallery viewing scenario where images on either side of the current image are cached, TaskPool is recommended to efficiently manage the cancellation of a cache task when swiping to the next image. diff --git a/en/application-dev/arkts-utils/worker-introduction.md b/en/application-dev/arkts-utils/worker-introduction.md index 1ce935736ef865e4f70eaca164388dbca93b9409..656507ba9b090d60210b70daf94bc0f97032103b 100644 --- a/en/application-dev/arkts-utils/worker-introduction.md +++ b/en/application-dev/arkts-utils/worker-introduction.md @@ -19,11 +19,11 @@ When creating a Worker, the thread that initiates it is referred to as the host - After a Worker is created, its lifecycle must be managed manually. A maximum of 64 Worker threads can run simultaneously, and the total number cannot exceed 80, including those created with [napi_create_ark_runtime](../reference/native-lib/napi.md#napi_create_ark_runtime). For details, see [Precautions for Lifecycle Management](#precautions-for-lifecycle-management). - The context objects in different threads are different. Therefore, Worker threads can use only thread-safe libraries. For example, non-thread-safe UI-related libraries cannot be used. - A maximum of 16 MB data can be serialized. -- When using the Worker module, you are advised to register the **onAllErrors** callback in the host thread in API version 16 or later to capture various exceptions that may occur during the lifecycle of the Worker thread. In API version 15 or earlier, register the **onerror** callback. If neither of them is registered, JS crash occurs when the Worker thread is abnormal. Note that the **onerror** callback can only capture synchronous exceptions within the **onmessage** callback. Once an exception is captured, the Worker thread will proceed to the destruction process and cannot be used. For details, see [Behavior Differences Between onAllErrors and onerror](#behavior-differences-between-onallerrors-and-onerror). +- When using the Worker module, you are advised to register the **onAllErrors** callback in the host thread in API version 18 or later to capture various exceptions that may occur during the lifecycle of the Worker thread. In API version 15 or earlier, register the **onerror** callback. If neither of them is registered, JS crash occurs when the Worker thread is abnormal. Note that the **onerror** callback can only capture synchronous exceptions within the **onmessage** callback. Once an exception is captured, the Worker thread will proceed to the destruction process and cannot be used. For details, see [Behavior Differences Between onAllErrors and onerror](#behavior-differences-between-onallerrors-and-onerror). - Worker thread files cannot be used across HAPs. - Before referencing a HAR or HSP, configure the dependency on the HAR or HSP. For details, see [Referencing a Shared Package](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/ide-har-import-V5). - [AppStorage](../quick-start/arkts-appstorage.md) cannot be used in Worker threads. -- Starting from API version 16, the priority of the Worker thread can be specified in the [WorkerOptions](../reference/apis-arkts/js-apis-worker.md#workeroptions) parameter of the constructor. +- Starting from API version 18, the priority of the Worker thread can be specified in the [WorkerOptions](../reference/apis-arkts/js-apis-worker.md#workeroptions) parameter of the constructor. ### Precautions for Creating a Worker diff --git a/en/application-dev/arkts-utils/worker-postMessage-sendable.md b/en/application-dev/arkts-utils/worker-postMessage-sendable.md new file mode 100644 index 0000000000000000000000000000000000000000..611967b7f2551b9b24aee7e65fb6a82699371e58 --- /dev/null +++ b/en/application-dev/arkts-utils/worker-postMessage-sendable.md @@ -0,0 +1,187 @@ +# High-Performance Communication Between Multi-Level Workers + +It is a common requirement for communication between multi-level [Workers](worker-introduction.md) (where child Workers are created by parent Workers, forming a hierarchy). Since you are responsible for managing the lifecycles of Worker threads, it is crucial to properly manage the lifecycles of multi-level Workers. You should ensure that all child Workers are destroyed before the parent Worker is destroyed. + +This topic describes how to implement high-performance communication between multi-level Workers. The key is using [Sendable objects](./arkts-sendable.md) with the Worker's [postMessageWithSharedSendable](../reference/apis-arkts/js-apis-worker.md#postmessagewithsharedsendable12) interface for high-performance object passing between threads. For example, in a data cloning scenario with three Workers (one parent and two children), the parent Worker creates the child Workers, sends cloning tasks to them, and receives the results back. + +1. Prepare a Sendable class **CopyEntry** to encapsulate the cloning task data. + + ```ts + // CopyEntry.ets + @Sendable + export class CopyEntry { + // Clone type. + type: string; + // File path. + filePath: string; + constructor(type: string, filePath: string) { + this.type = type; + this.filePath = filePath; + } + } + ``` + +2. Prepare two Worker files: **ParentWorker.ets** for the parent Worker and **ChildWorker.ets** for the child Workers. The parent Worker distributes tasks and closes the child and parent Workers once all tasks are complete. The child Workers receive tasks, perform cloning, and notify the parent Worker when the tasks are complete. + + ```ts + // ParentWorker.ets + import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker, collections, ArkTSUtils } from '@kit.ArkTS' + import { CopyEntry } from './CopyEntry' + + const workerPort: ThreadWorkerGlobalScope = worker.workerPort; + + // Calculate the number of tasks of worker1. + let count1 = 0; + // Calculate the number of tasks of worker2. + let count2 = 0; + // Calculate the total number of tasks. + let sum = 0; + // Asynchronous lock. + const asyncLock = new ArkTSUtils.locks.AsyncLock(); + // Create a child Worker. + const copyWorker1 = new worker.ThreadWorker('entry/ets/pages/ChildWorker'); + const copyWorker2 = new worker.ThreadWorker('entry/ets/pages/ChildWorker'); + + workerPort.onmessage = (e : MessageEvents) => { + let array = e.data as collections.Array; + sum = array.length; + for (let i = 0; i < array.length; i++) { + let entry = array[i]; + if (entry.type === 'copy1') { + count1++; + // If the data type is copy1, transfer the data to copyWorker1. + copyWorker1.postMessageWithSharedSendable(entry); + } else if (entry.type === 'copy2') { + count2++; + // If the data type is copy2, transfer the data to copyWorker2. + copyWorker2.postMessageWithSharedSendable(entry); + } + } + } + + copyWorker1.onmessage = async (e : MessageEvents) => { + console.info('copyWorker1 onmessage:' + e.data); + await asyncLock.lockAsync(() => { + count1--; + if (count1 == 0) { + // If all tasks of copyWorker1 are complete, close copyWorker1. + console.info('copyWorker1 close'); + copyWorker1.terminate(); + } + sum--; + if (sum == 0) { + // If all tasks are complete, close the parent Worker. + workerPort.close(); + } + }) + } + + copyWorker2.onmessage = async (e : MessageEvents) => { + console.info('copyWorker2 onmessage:' + e.data); + await asyncLock.lockAsync(() => { + count2--; + sum--; + if (count2 == 0) { + // If all tasks of copyWorker2 are complete, close copyWorker2. + console.info('copyWorker2 close') + copyWorker2.terminate(); + } + if (sum == 0) { + // If all tasks are complete, close the parent Worker. + workerPort.close(); + } + }) + } + + workerPort.onmessageerror = (e : MessageEvents) => { + console.info('onmessageerror:' + e.data); + } + + workerPort.onerror = (e : ErrorEvent) => { + console.info('onerror:' + e.message); + } + ``` + ```ts + // ChildWorker.ets + import { ErrorEvent, MessageEvents, ThreadWorkerGlobalScope, worker} from '@kit.ArkTS' + import { CopyEntry } from './CopyEntry' + + const workerPort: ThreadWorkerGlobalScope = worker.workerPort; + + workerPort.onmessage = (e : MessageEvents) => { + let data = e.data as CopyEntry; + // The copy operation is omitted. + console.info(data.filePath); + workerPort.postMessageWithSharedSendable("done"); + } + + workerPort.onmessageerror = (e : MessageEvents) => { + console.info('onmessageerror:' + e.data); + } + + workerPort.onerror = (e : ErrorEvent) => { + console.info('onerror:' + e.message); + } + ``` + +3. On the main process page of the UI, create a parent Worker, prepare the data required for the cloning task, and send the data to the parent Worker. + + ```ts + // Index.ets + import { worker, collections } from '@kit.ArkTS'; + import { BusinessError } from '@kit.BasicServicesKit'; + import { CopyEntry } from './CopyEntry' + + function promiseCase() { + let p: Promise = new Promise((resolve: Function, reject: Function) => { + setTimeout(() => { + resolve(1); + }, 100) + }).then(undefined, (error: BusinessError) => { + }) + return p; + } + + async function postMessageTest() { + let ss = new worker.ThreadWorker("entry/ets/pages/ParentWorker"); + let isTerminate = false; + ss.onexit = () => { + isTerminate = true; + } + let array = new collections.Array(); + // Prepare data. + for (let i = 0; i < 4; i++) { + if (i % 2 == 0) { + array.push(new CopyEntry("copy1", "file://copy1.txt")); + } else { + array.push(new CopyEntry("copy2", "file://copy2.txt")); + } + } + // Send a message to the Worker thread. + ss.postMessageWithSharedSendable(array); + while (!isTerminate) { + await promiseCase(); + } + console.info("Worker thread has exited"); + } + + @Entry + @Component + struct Index { + @State message: string = 'Hello World'; + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + .onClick(() => { + postMessageTest(); + }) + } + .width('100%') + } + .height('100%') + } + } + ``` diff --git a/en/application-dev/arkts-utils/xml-parsing.md b/en/application-dev/arkts-utils/xml-parsing.md index d3c5e988dce7cd806734b2460de0d1c8a2a14be8..5be476a952e887fb6157c6eae83ab2b108abf993 100644 --- a/en/application-dev/arkts-utils/xml-parsing.md +++ b/en/application-dev/arkts-utils/xml-parsing.md @@ -10,8 +10,8 @@ The XML module provides the **XmlPullParser** class to parse XML documents. The | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| supportDoctype | boolean | No| Whether to ignore the document type. The default value is **false**, indicating that the document type is not parsed.| -| ignoreNameSpace | boolean | No| Whether to ignore the namespace. The default value is **false**, indicating that the namespace is parsed.| +| supportDoctype | boolean | No| Whether to parse the document type. The value **true** means to parse the document type, and **false** means the opposite. The default value is **false**.| +| ignoreNameSpace | boolean | No| Whether to ignore the namespace. If the namespace is ignored, it will not be parsed. The value **true** means to ignore the namespace, and **false** means the opposite. The default value is **false**.| | tagValueCallbackFunction | (name: string, value: string) => boolean | No| Callback used to return **tagValue**, which consists of a tag and its value. The default value is **null**, indicating that XML tags and values are not parsed.| | attributeValueCallbackFunction | (name: string, value: string) => boolean | No| Callback used to return **attributeValue**, which consists of an attribute and its value. The default value is **null**, indicating that XML attributes and values are not parsed.| | tokenValueCallbackFunction | (eventType: EventType, value: ParseInfo) => boolean | No| Callback used to return **tokenValue**, which consists of the event type and the attributes of **parseInfo**. The default value is **null**, indicating that the event type and the attributes of **parseInfo** are not parsed.| diff --git a/en/application-dev/basic-services/account/Readme-EN.md b/en/application-dev/basic-services/account/Readme-EN.md index 85dc8275321f64b74a80ed5bd2ef7d16bbf3ad68..60c24594bc36553056d2a11b7c882bfdbd6f4caf 100644 --- a/en/application-dev/basic-services/account/Readme-EN.md +++ b/en/application-dev/basic-services/account/Readme-EN.md @@ -1,4 +1,4 @@ -# Account Management +# Account Management - [Account Management Overview](account-overview.md) - System Accounts (for System Applications Only) diff --git a/en/application-dev/basic-services/account/control-os-account-by-constraints.md b/en/application-dev/basic-services/account/control-os-account-by-constraints.md index dae9cfd267c8c2463cdf0662075ca5d93ac7f804..66c1b335895fda1438b9532e1a5e65e96821ce01 100644 --- a/en/application-dev/basic-services/account/control-os-account-by-constraints.md +++ b/en/application-dev/basic-services/account/control-os-account-by-constraints.md @@ -48,8 +48,7 @@ The user can set constraints to restrict the system account behaviors. For examp ## Checking Whether a Constraint Can be Enabled for a System Account -Before a constraint is enabled for a system account, the application needs to check whether the constraint can be enabled. -You can use [isOsAccountConstraintEnabled](../../reference/apis-basic-services-kit/js-apis-osAccount-sys.md#isosaccountconstraintenabled11) to implement this operation. +Before a constraint is enabled for a system account, the application needs to check whether the constraint can be enabled. You can use [isOsAccountConstraintEnabled](../../reference/apis-basic-services-kit/js-apis-osAccount-sys.md#isosaccountconstraintenabled11) to implement this operation. **Procedure** diff --git a/en/application-dev/basic-services/account/manage-os-account.md b/en/application-dev/basic-services/account/manage-os-account.md index fc75038f1a0479eb5816706e122b5a2bae41904c..d6a7b56b5c9c5b3d00e2b80f096725d39c0227f8 100644 --- a/en/application-dev/basic-services/account/manage-os-account.md +++ b/en/application-dev/basic-services/account/manage-os-account.md @@ -1,11 +1,10 @@ # Managing System Accounts (for System Applications Only) -The system provides APIs for managing system accounts. -After applying for required permissions for your system application, you can use the APIs to create, activate, modify, and delete system accounts. For third-party applications, you can use the APIs to query basic information about system accounts to develop service logic related to system accounts. +The system provides APIs for managing system accounts. After applying for required permissions for your system application, you can use the APIs to create, activate, modify, and delete system accounts. For third-party applications, you can use the APIs to query basic information about system accounts to develop service logic related to system accounts. ## Basic Concepts -### System Account Type +### Account Type Currently, only the following types of system accounts can be created: | Name | Value| Description | @@ -13,7 +12,7 @@ Currently, only the following types of system accounts can be created: | ADMIN | 0 | Administrator account.| | NORMAL | 1 | Normal account. | | GUEST | 2 | Guest account. | -| PRIVATE12+ | 1024 | Private account. | +| PRIVATE12+ | 1024 | Private account. | ### Account Information @@ -84,7 +83,7 @@ accountManager.queryOsAccountById(localId, (err: BusinessError, accountInfo: osA }); ``` -## Changing the Profile Photo and Nickname of a System Account +## Changing the ProfilePhoto and Nickname of a System Account Change the profile photo and nickname of a system account as required. diff --git a/en/application-dev/basic-services/basic-services-kit-overview.md b/en/application-dev/basic-services/basic-services-kit-overview.md index 63732bc4dabc182ab24d62a05e9264436f7c53fd..95201066ac5aa98ba0e6c2fb3f75628d750cfbb0 100644 --- a/en/application-dev/basic-services/basic-services-kit-overview.md +++ b/en/application-dev/basic-services/basic-services-kit-overview.md @@ -21,7 +21,7 @@ Basic Services Kit is typically used in the following scenarios: ## Capability Scope -This kit provides the following capabilities: +Depending on different use cases, this kit provides the following capabilities: - Data file processing - [Pasteboard](../reference/apis-basic-services-kit/js-apis-pasteboard.md): provides the copy and paste support. You can use the provided APIs to operate pasteboard content of the plain text, HTML, URI, pixel map, and other types. @@ -40,7 +40,7 @@ This kit provides the following capabilities: - [Power management](../reference/apis-basic-services-kit/js-apis-power.md): provides system power management capabilities, such as querying the screen status. - [Running lock](../reference/apis-basic-services-kit/js-apis-runninglock.md): provides APIs for creating, querying, holding, and releasing running locks. - [Thermal management](../reference/apis-basic-services-kit/js-apis-thermal.md): provides thermal management capabilities, such as thermal level query. - - [USB management](../reference/apis-basic-services-kit/js-apis-usbManager.md): provides USB device management capabilities, including USB device list query, bulk data transfer, control transfer, and permission control. For details about the development guide, see [USB Service Development Overview](usb/usb-overview.md). + - [USB management](../reference/apis-basic-services-kit/js-apis-usbManager.md): provides USB device management capabilities, including USB device list query, bulk data transfer, control transfer, and permission control. For details about the development guide, see [USB Service Development Overview](usb/usbManager/usbHost-overview.md). - Others: - [App account management](../reference/apis-basic-services-kit/js-apis-appAccount.md): provides application account management and data management capabilities. For details, see [Managing App Accounts](account/manage-application-account.md). @@ -54,6 +54,3 @@ This kit provides the following capabilities: - [Ability Kit](../application-models/abilitykit-overview.md): Common events in this kit are required for inter-process communication in Ability Kit. - [Core File Kit](../file-management/core-file-kit-intro.md): Core File Kit provides file access and management capabilities. You can use Core File Kit for application file access, file sharing, and data backup and restore, and use this kit to implement file compression, file upload and download, and file printing. - - - diff --git a/en/application-dev/basic-services/common-event/common-event-static-subscription.md b/en/application-dev/basic-services/common-event/common-event-static-subscription.md index a483307811b2f636579a7e3980a84aa0bed5ec2a..45c284d25fa117f646ecdc76e55b6f7ead179ea0 100644 --- a/en/application-dev/basic-services/common-event/common-event-static-subscription.md +++ b/en/application-dev/basic-services/common-event/common-event-static-subscription.md @@ -122,7 +122,7 @@ The [StaticSubscriberExtensionAbility](../../reference/apis-basic-services-kit/j | name | Name of the ExtensionAbility, which must be the same as the name of **extensionAbility** declared in **module.json5**.| String | No | | permission | Permissions required by the publisher. | String | Yes (initial value: left empty)| | events | List of subscribed target events. | String array | No | - | filter | Filter criteria for static events. This attribute is supported since API version 16.
For details about the values, see the following table.| Object array | Yes (initial value: left empty)| + | filter | Filter criteria for static events. This attribute is supported since API version 18.
For details about the values, see the following table.| Object array | Yes (initial value: left empty)| The **filter** tag identifies the static subscription events that can be filtered by the subscriber as required. The tag value is of the object array type and contains two subtags: **event** and **conditions**. @@ -141,7 +141,7 @@ The [StaticSubscriberExtensionAbility](../../reference/apis-basic-services-kit/j | ------------ | ------------------------------------------ | ------------------ | -------------------------- | | code | Result code to filter. | Integer | Yes (initial value: left empty)| | data | Custom result data to filter.| String | Yes (initial value: left empty)| - | parameters | Additional information to filter. | Boolean/Number/String| Yes (initial value: left empty)| + | parameters | Additional information to filter for a static subscription event. Only data of the Boolean, number, or string type can be configured.| Object| Yes (initial value: left empty)| 4. Modify the [preset configuration file](https://gitee.com/openharmony/vendor_hihope/blob/master/rk3568/preinstall-config/install_list_capability.json) of the device, that is, the **/system/variant/phone/base/etc/app/install_list_capability.json** file. When the device is started, this file is read. During application installation, the common event type specified by **allowCommonEvent** in the file is authorized. The **install_list_capability.json** file contains the following fields: diff --git a/en/application-dev/basic-services/common-event/native-common-event-publish.md b/en/application-dev/basic-services/common-event/native-common-event-publish.md index 2f8523de4a8b19e6ee23a43bea7705e863f70dc8..6ce4d8eb46af9212e403d09ba07247c8fdba3189 100644 --- a/en/application-dev/basic-services/common-event/native-common-event-publish.md +++ b/en/application-dev/basic-services/common-event/native-common-event-publish.md @@ -27,11 +27,9 @@ For details about the APIs, see [CommonEvent](../../reference/apis-basic-service #include #include #include - #include #include #include "hilog/log.h" #include "BasicServicesKit/oh_commonevent.h" - #include "BasicServicesKit/oh_commonevent_support.h" ``` 2. Add dynamic link libraries to the CMake script. @@ -58,50 +56,50 @@ For details about the APIs, see [CommonEvent](../../reference/apis-basic-service // Set the additional information and key of the int type. ret = OH_CommonEvent_SetIntToParameters(param, "intKey", 10); - OH_LOG_INFO(LOG_APP, "OH_CommonEvent_SetIntToParameters ret <%{public}d>.", ret); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "OH_CommonEvent_SetIntToParameters ret <%{public}d>.", ret); // Set the additional information and key of the int array type. int intArray[] = {123, 234, 567}; size_t arraySize = 3; ret = OH_CommonEvent_SetIntArrayToParameters(param, "intArrayKey", intArray, arraySize); - OH_LOG_INFO(LOG_APP, "OH_CommonEvent_SetIntArrayToParameters ret <%{public}d>.", ret); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "OH_CommonEvent_SetIntArrayToParameters ret <%{public}d>.", ret); // Set the additional information and key of the long type. ret = OH_CommonEvent_SetLongToParameters(param, "longKey", 2147483646); - OH_LOG_INFO(LOG_APP, "OH_CommonEvent_SetLongToParameters ret <%{public}d>.", ret); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "OH_CommonEvent_SetLongToParameters ret <%{public}d>.", ret); // Set the additional information and key of the long array type. long longArray[] = {2147483646, 555, 2147483645}; ret = OH_CommonEvent_SetLongArrayToParameters(param, "longArrayKey", longArray, arraySize); - OH_LOG_INFO(LOG_APP, "OH_CommonEvent_SetLongArrayToParameters ret <%{public}d>.", ret); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "OH_CommonEvent_SetLongArrayToParameters ret <%{public}d>.", ret); // Set the additional information and key of the double type. ret = OH_CommonEvent_SetDoubleToParameters(param, "doubleKey", 11.22); - OH_LOG_INFO(LOG_APP, "OH_CommonEvent_SetDoubleToParameters ret <%{public}d>.", ret); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "OH_CommonEvent_SetDoubleToParameters ret <%{public}d>.", ret); // Set the additional information and key of the double array type. double doubleArray[] = {11.22, 33.44, 55.66}; ret = OH_CommonEvent_SetDoubleArrayToParameters(param, "doubleArrayKey", doubleArray, arraySize); - OH_LOG_INFO(LOG_APP, "OH_CommonEvent_SetDoubleArrayToParameters ret <%{public}d>.", ret); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "OH_CommonEvent_SetDoubleArrayToParameters ret <%{public}d>.", ret); // Set the additional information and key of the Boolean type. ret = OH_CommonEvent_SetBoolToParameters(param, "boolKey", true); - OH_LOG_INFO(LOG_APP, "OH_CommonEvent_SetBoolToParameters ret <%{public}d>.", ret); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "OH_CommonEvent_SetBoolToParameters ret <%{public}d>.", ret); // Set the additional information and key of the Boolean array type. bool boolArray[] = {true, false, true}; ret = OH_CommonEvent_SetBoolArrayToParameters(param, "boolArrayKey", boolArray, arraySize); - OH_LOG_INFO(LOG_APP, "OH_CommonEvent_SetBoolArrayToParameters ret <%{public}d>.", ret); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "OH_CommonEvent_SetBoolArrayToParameters ret <%{public}d>.", ret); // Set the additional information and key of the char type. ret = OH_CommonEvent_SetCharToParameters(param, "charKey", 'A'); - OH_LOG_INFO(LOG_APP, "OH_CommonEvent_SetCharToParameters ret <%{public}d>.", ret); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "OH_CommonEvent_SetCharToParameters ret <%{public}d>.", ret); // Set the additional information and key of the char array type. char* value= "AAAAAAAAAAAAAA"; size_t valueLength = strlen(value); ret = OH_CommonEvent_SetCharArrayToParameters(param, "charArrayKey", value, valueLength); - OH_LOG_INFO(LOG_APP, "OH_CommonEvent_SetCharArrayToParameters ret <%{public}d>.", ret); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "OH_CommonEvent_SetCharArrayToParameters ret <%{public}d>.", ret); return param; } @@ -114,25 +112,25 @@ For details about the APIs, see [CommonEvent](../../reference/apis-basic-service // Set the bundle name of a common event. ret = OH_CommonEvent_SetPublishInfoBundleName(info, bundleName); - OH_LOG_INFO(LOG_APP, "OH_CommonEvent_SetPublishInfoBundleName ret <%{public}d>.", ret); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "OH_CommonEvent_SetPublishInfoBundleName ret <%{public}d>.", ret); // Set the common event permission. The parameters consist of the permission array and the number of permissions. ret = OH_CommonEvent_SetPublishInfoPermissions(info, permissions, num); - OH_LOG_INFO(LOG_APP, "OH_CommonEvent_SetPublishInfoPermissions ret <%{public}d>.", ret); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "OH_CommonEvent_SetPublishInfoPermissions ret <%{public}d>.", ret); // Set the result code of a common event. ret = OH_CommonEvent_SetPublishInfoCode(info, code); - OH_LOG_INFO(LOG_APP, "OH_CommonEvent_SetPublishInfoCode ret <%{public}d>.", ret); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "OH_CommonEvent_SetPublishInfoCode ret <%{public}d>.", ret); // Set the result data of a common event. size_t dataLength = strlen(data); ret = OH_CommonEvent_SetPublishInfoData(info, data, dataLength); - OH_LOG_INFO(LOG_APP, "OH_CommonEvent_SetPublishInfoData ret <%{public}d>.", ret); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "OH_CommonEvent_SetPublishInfoData ret <%{public}d>.", ret); // Set the additional information of a common event. CommonEvent_Parameters* param = CreateParameters(); ret = OH_CommonEvent_SetPublishInfoParameters(info, param); - OH_LOG_INFO(LOG_APP, "OH_CommonEvent_SetPublishInfoParameters ret <%{public}d>.", ret); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "OH_CommonEvent_SetPublishInfoParameters ret <%{public}d>.", ret); } ``` @@ -148,7 +146,7 @@ For details about the APIs, see [CommonEvent](../../reference/apis-basic-service void Publish(const char* event) { int32_t ret = OH_CommonEvent_Publish(event); - OH_LOG_INFO(LOG_APP, "OH_CommonEvent_Publish ret <%{public}d>.", ret); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "OH_CommonEvent_Publish ret <%{public}d>.", ret); } ``` @@ -159,7 +157,7 @@ For details about the APIs, see [CommonEvent](../../reference/apis-basic-service { // Create a common event with the attribute object. int32_t ret = OH_CommonEvent_PublishWithInfo(event, info); - OH_LOG_INFO(LOG_APP, "OH_CommonEvent_PublishWithInfo ret <%{public}d>.", ret); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "OH_CommonEvent_PublishWithInfo ret <%{public}d>.", ret); } ``` diff --git a/en/application-dev/basic-services/common-event/native-common-event-subscription.md b/en/application-dev/basic-services/common-event/native-common-event-subscription.md index 06d58fb9fdf20505faed1ef6c58edf3269c7aef4..da6aa2017e46d9034768692c8ccdb958d2e8d086 100644 --- a/en/application-dev/basic-services/common-event/native-common-event-subscription.md +++ b/en/application-dev/basic-services/common-event/native-common-event-subscription.md @@ -28,11 +28,9 @@ For details about the APIs, see [CommonEvent](../../reference/apis-basic-service #include #include #include - #include #include #include "hilog/log.h" #include "BasicServicesKit/oh_commonevent.h" - #include "BasicServicesKit/oh_commonevent_support.h" ``` 2. Add dynamic link libraries to the CMake script. @@ -57,11 +55,11 @@ For details about the APIs, see [CommonEvent](../../reference/apis-basic-service // Set the subscriber permission. ret = OH_CommonEvent_SetPublisherPermission(info, permission); - OH_LOG_INFO(LOG_APP, "OH_CommonEvent_SetPublisherPermission ret <%{public}d>.", ret); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "OH_CommonEvent_SetPublisherPermission ret <%{public}d>.", ret); // Set a bundle name of the subscriber. ret = OH_CommonEvent_SetPublisherBundleName(info, bundleName); - OH_LOG_INFO(LOG_APP, "OH_CommonEvent_SetPublisherBundleName ret <%{public}d>.", ret); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "OH_CommonEvent_SetPublisherBundleName ret <%{public}d>.", ret); return info; } @@ -93,7 +91,7 @@ For details about the APIs, see [CommonEvent](../../reference/apis-basic-service // Obtain the additional information of a common event. const CommonEvent_Parameters *parameters = OH_CommonEvent_GetParametersFromRcvData(data); - OH_LOG_INFO(LOG_APP, "event: %{public}s, code: %{public}d, data: %{public}s, bundle: %{public}s", event, code, retData, bundle); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "event: %{public}s, code: %{public}d, data: %{public}s, bundle: %{public}s", event, code, retData, bundle); } ``` @@ -109,38 +107,38 @@ For details about the APIs, see [CommonEvent](../../reference/apis-basic-service exists = OH_CommonEvent_HasKeyInParameters(parameters, "intKey"); // Obtain the int data from the additional information of a common event. int intValue = OH_CommonEvent_GetIntFromParameters(parameters, "intKey", 10); - OH_LOG_INFO(LOG_APP, "exists = %{public}d, intValue = %{public}d", exists, intValue); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "exists = %{public}d, intValue = %{public}d", exists, intValue); exists = OH_CommonEvent_HasKeyInParameters(parameters, "boolKey"); // Obtain the Boolean data from the additional information of a common event. bool boolValue = OH_CommonEvent_GetBoolFromParameters(parameters, "boolKey", false); - OH_LOG_INFO(LOG_APP, "exists = %{public}d, boolValue = %{public}d", exists, boolValue); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "exists = %{public}d, boolValue = %{public}d", exists, boolValue); exists = OH_CommonEvent_HasKeyInParameters(parameters, "longKey"); // Obtain the long data from the additional information of a common event. long longValue = OH_CommonEvent_GetLongFromParameters(parameters, "longKey", 1111111111); - OH_LOG_INFO(LOG_APP, "exists = %{public}d, longValue = %{public}ld", exists, longValue); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "exists = %{public}d, longValue = %{public}ld", exists, longValue); exists = OH_CommonEvent_HasKeyInParameters(parameters, "doubleKey"); // Obtain the double data from the additional information of a common event. double doubleValue = OH_CommonEvent_GetDoubleFromParameters(parameters, "doubleKey", 11.11); - OH_LOG_INFO(LOG_APP, "exists = %{public}d, doubleValue = %{public}f", exists, doubleValue); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "exists = %{public}d, doubleValue = %{public}f", exists, doubleValue); exists = OH_CommonEvent_HasKeyInParameters(parameters, "charKey"); // Obtain the char data from the additional information of a common event. char charValue = OH_CommonEvent_GetCharFromParameters(parameters, "charKey", 'A'); - OH_LOG_INFO(LOG_APP, "exists = %{public}d, charValue = %{public}c", exists, charValue); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "exists = %{public}d, charValue = %{public}c", exists, charValue); int** arr = new int*; exists = OH_CommonEvent_HasKeyInParameters(parameters, "intArrayKey"); // Obtain the int array from the additional information of a common event. int32_t intArraySize = OH_CommonEvent_GetIntArrayFromParameters(parameters, "intArrayKey", arr); if (intArraySize <= 0 || *arr == nullptr) { - OH_LOG_ERROR(LOG_APP, "exists = %{public}d, Failed to get int array or invalid size: %{public}d", exists, intArraySize); + OH_LOG_Print(LOG_APP, LOG_ERROR, 1, "CES_TEST", "exists = %{public}d, Failed to get int array or invalid size: %{public}d", exists, intArraySize); } else { - OH_LOG_INFO(LOG_APP, "exists = %{public}d, intArraySize = %{public}d", exists, intArraySize); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "exists = %{public}d, intArraySize = %{public}d", exists, intArraySize); for (int i = 0; i < intArraySize; i++) { - OH_LOG_INFO(LOG_APP, "<%{public}d>", *((*arr) + i)); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "<%{public}d>", *((*arr) + i)); } } @@ -149,11 +147,11 @@ For details about the APIs, see [CommonEvent](../../reference/apis-basic-service // Obtain the long array from the additional information of a common event. int32_t longArraySize = OH_CommonEvent_GetLongArrayFromParameters(parameters, "longArrayKey", longArray); if (longArraySize <= 0 || *longArray == nullptr) { - OH_LOG_ERROR(LOG_APP, "exists = %{public}d, Failed to get long array or invalid size: %{public}d", exists, longArraySize); + OH_LOG_Print(LOG_APP, LOG_ERROR, 1, "CES_TEST", "exists = %{public}d, Failed to get long array or invalid size: %{public}d", exists, longArraySize); } else { - OH_LOG_INFO(LOG_APP, "exists = %{public}d, longArraySize = %{public}d", exists, longArraySize); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "exists = %{public}d, longArraySize = %{public}d", exists, longArraySize); for (int i = 0; i < longArraySize; i++) { - OH_LOG_INFO(LOG_APP, "<%{public}ld>", *((*longArray) + i)); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "<%{public}ld>", *((*longArray) + i)); } } @@ -162,11 +160,11 @@ For details about the APIs, see [CommonEvent](../../reference/apis-basic-service // Obtain the double array from the additional information of a common event. int32_t doubleArraySize = OH_CommonEvent_GetDoubleArrayFromParameters(parameters, "doubleArrayKey", doubleArray); if (doubleArraySize <= 0 || *doubleArray == nullptr) { - OH_LOG_ERROR(LOG_APP, "exists = %{public}d, Failed to get double array or invalid size: %{public}d", exists, doubleArraySize); + OH_LOG_Print(LOG_APP, LOG_ERROR, 1, "CES_TEST", "exists = %{public}d, Failed to get double array or invalid size: %{public}d", exists, doubleArraySize); } else { - OH_LOG_INFO(LOG_APP, "exists = %{public}d, doubleArraySize = %{public}d", exists, doubleArraySize); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "exists = %{public}d, doubleArraySize = %{public}d", exists, doubleArraySize); for (int i = 0; i < doubleArraySize; i++) { - OH_LOG_INFO(LOG_APP, "<%{public}f>", *((*doubleArray) + i)); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "<%{public}f>", *((*doubleArray) + i)); } } @@ -175,9 +173,9 @@ For details about the APIs, see [CommonEvent](../../reference/apis-basic-service // Obtain the char array from the additional information of a common event. int32_t charArraySize = OH_CommonEvent_GetCharArrayFromParameters(parameters, "charArrayKey", charArray); if (charArraySize <= 0 || *charArray == nullptr) { - OH_LOG_ERROR(LOG_APP, "exists = %{public}d, Failed to get charArray or invalid size: %{public}d", exists, charArraySize); + OH_LOG_Print(LOG_APP, LOG_ERROR, 1, "CES_TEST", "exists = %{public}d, Failed to get charArray or invalid size: %{public}d", exists, charArraySize); } else { - OH_LOG_INFO(LOG_APP, "charArray as string: %{public}s", *charArray); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "charArray as string: %{public}s", *charArray); } bool** boolArray = new bool*; @@ -185,11 +183,11 @@ For details about the APIs, see [CommonEvent](../../reference/apis-basic-service // Obtain the Boolean array from the additional information of a common event. int32_t boolArraySize = OH_CommonEvent_GetBoolArrayFromParameters(parameters, "boolArrayKey", boolArray); if (boolArraySize <= 0 || *boolArray == nullptr) { - OH_LOG_ERROR(LOG_APP, "exists = %{public}d, Failed to get boolArray or invalid size: %{public}d", exists, boolArraySize); + OH_LOG_Print(LOG_APP, LOG_ERROR, 1, "CES_TEST", "exists = %{public}d, Failed to get boolArray or invalid size: %{public}d", exists, boolArraySize); } else { - OH_LOG_INFO(LOG_APP, "exists = %{public}d, boolArraySize = %{public}d", exists, boolArraySize); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "exists = %{public}d, boolArraySize = %{public}d", exists, boolArraySize); for (int i = 0; i < boolArraySize; i++) { - OH_LOG_INFO(LOG_APP, "<%{public}d>", *((*boolArray) + i)); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "<%{public}d>", *((*boolArray) + i)); } } } @@ -218,7 +216,7 @@ For details about the APIs, see [CommonEvent](../../reference/apis-basic-service void Subscribe(CommonEvent_Subscriber* subscriber) { // Subscribe to an event by passing a subscriber. int32_t ret = OH_CommonEvent_Subscribe(subscriber); - OH_LOG_INFO(LOG_APP, "OH_CommonEvent_Subscribe ret <%{public}d>.", ret); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "OH_CommonEvent_Subscribe ret <%{public}d>.", ret); } ``` @@ -238,17 +236,18 @@ For details about the APIs, see [CommonEvent](../../reference/apis-basic-service void AbortCommonEvent(CommonEvent_Subscriber* subscriber) { // Check whether the event is an ordered common event. if(!OH_CommonEvent_IsOrderedCommonEvent(subscriber)) { - OH_LOG_INFO(LOG_APP, "Not ordered common event."); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "Not ordered common event."); return; } // Abort an ordered common event. if(OH_CommonEvent_AbortCommonEvent(subscriber)) { if(OH_CommonEvent_FinishCommonEvent(subscriber)) { // Obtain the result of the abort state of an ordered common event. - OH_LOG_INFO(LOG_APP, "Abort common event success, Get abort <%{public}d>.", OH_CommonEvent_GetAbortCommonEvent(subscriber)); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "Abort common event success, Get abort <%{public}d>.", OH_CommonEvent_GetAbortCommonEvent(subscriber)); } + } else { + OH_LOG_Print(LOG_APP, LOG_ERROR, 1, "CES_TEST", "Abort common event failed."); } - OH_LOG_ERROR(LOG_APP, "Abort common event failed."); } ``` @@ -260,22 +259,23 @@ For details about the APIs, see [CommonEvent](../../reference/apis-basic-service void ClearAbortCommonEvent(CommonEvent_Subscriber* subscriber) { // Check whether the event is an ordered common event. if(!OH_CommonEvent_IsOrderedCommonEvent(subscriber)) { - OH_LOG_INFO(LOG_APP, "Not ordered common event."); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "Not ordered common event."); return; } // Abort an ordered common event. if(!OH_CommonEvent_AbortCommonEvent(subscriber)) { - OH_LOG_ERROR(LOG_APP, "Abort common event failed."); + OH_LOG_Print(LOG_APP, LOG_ERROR, 1, "CES_TEST", "Abort common event failed."); return; } // Clear the aborted state of an ordered event. if(OH_CommonEvent_ClearAbortCommonEvent(subscriber)) { if(OH_CommonEvent_FinishCommonEvent(subscriber)) { // Obtain the result of the abort state of an ordered common event. - OH_LOG_INFO(LOG_APP, "Clear abort common event success, Get abort <%{public}d>.", OH_CommonEvent_GetAbortCommonEvent(subscriber)); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "Clear abort common event success, Get abort <%{public}d>.", OH_CommonEvent_GetAbortCommonEvent(subscriber)); } + } else { + OH_LOG_Print(LOG_APP, LOG_ERROR, 1, "CES_TEST", "Clear abort common event failed."); } - OH_LOG_ERROR(LOG_APP, "Clear abort common event failed."); } ``` @@ -287,13 +287,13 @@ For details about the APIs, see [CommonEvent](../../reference/apis-basic-service void SetToSubscriber(CommonEvent_Subscriber* subscriber, const int32_t code, const char* data) { // Set the result code of an ordered common event. if(!OH_CommonEvent_SetCodeToSubscriber(subscriber, code)) { - OH_LOG_ERROR(LOG_APP, "OH_CommonEvent_SetCodeToSubscriber failed."); + OH_LOG_Print(LOG_APP, LOG_ERROR, 1, "CES_TEST", "OH_CommonEvent_SetCodeToSubscriber failed."); return; } // Set the result data for an ordered common event. size_t dataLength = strlen(data); if(!OH_CommonEvent_SetDataToSubscriber(subscriber, data, dataLength)) { - OH_LOG_ERROR(LOG_APP, "OH_CommonEvent_SetDataToSubscriber failed."); + OH_LOG_Print(LOG_APP, LOG_ERROR, 1, "CES_TEST", "OH_CommonEvent_SetDataToSubscriber failed."); return; } } @@ -302,7 +302,7 @@ For details about the APIs, see [CommonEvent](../../reference/apis-basic-service // Obtain the result data and code of an ordered common event. const char* data = OH_CommonEvent_GetDataFromSubscriber(subscriber); int32_t code = OH_CommonEvent_GetCodeFromSubscriber(subscriber); - OH_LOG_INFO(LOG_APP, "Subscriber data <%{public}s>, code <%{public}d>.", data, code); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "Subscriber data <%{public}s>, code <%{public}d>.", data, code); } ``` diff --git a/en/application-dev/basic-services/common-event/native-common-event-unsubscription.md b/en/application-dev/basic-services/common-event/native-common-event-unsubscription.md index 8b06e63fcf5b8815adaa0b5305182afb00621cb2..00dfec282f9c81449296af36f7ea00fd952fcb45 100644 --- a/en/application-dev/basic-services/common-event/native-common-event-unsubscription.md +++ b/en/application-dev/basic-services/common-event/native-common-event-unsubscription.md @@ -19,13 +19,8 @@ For details about the APIs, see [CommonEvent](../../reference/apis-basic-service ```c++ #include - #include - #include - #include - #include #include "hilog/log.h" #include "BasicServicesKit/oh_commonevent.h" - #include "BasicServicesKit/oh_commonevent_support.h" ``` 2. Add dynamic link libraries to the CMake script. @@ -47,6 +42,6 @@ For details about the APIs, see [CommonEvent](../../reference/apis-basic-service void Unsubscribe(CommonEvent_Subscriber* subscriber) { // Unsubscribe from a common event by passing a subscriber. int32_t ret = OH_CommonEvent_UnSubscribe(subscriber); - OH_LOG_INFO(LOG_APP, "OH_CommonEvent_UnSubscribe ret <%{public}d>.", ret); + OH_LOG_Print(LOG_APP, LOG_INFO, 1, "CES_TEST", "OH_CommonEvent_UnSubscribe ret <%{public}d>.", ret); } ``` diff --git a/en/application-dev/basic-services/pasteboard/Readme-EN.md b/en/application-dev/basic-services/pasteboard/Readme-EN.md index 687e13712a723f53799f82c21250ef0549080da9..d05269813b724bc64d21a0f8744e90d53b1f54d5 100644 --- a/en/application-dev/basic-services/pasteboard/Readme-EN.md +++ b/en/application-dev/basic-services/pasteboard/Readme-EN.md @@ -1,4 +1,4 @@ -# Pasteboard Service +# Pasteboard Service - [Using the Pasteboard to Copy and Paste](use_pasteboard_to_copy_and_paste.md) - [Using the Delayed Copy and Paste Function of the Pasteboard](pasteboard-time-lapse-copy-and-paste.md) diff --git a/en/application-dev/basic-services/request/Readme-EN.md b/en/application-dev/basic-services/request/Readme-EN.md index e91af915f06edc012f07dc90049b5f372d439298..4a97d96e689bd477cbebabeb18367ac45a49bc04 100644 --- a/en/application-dev/basic-services/request/Readme-EN.md +++ b/en/application-dev/basic-services/request/Readme-EN.md @@ -1,3 +1,3 @@ -# Upload and Download +# Upload and Download - [Uploading and Downloading Application Files](app-file-upload-download.md) \ No newline at end of file diff --git a/en/application-dev/basic-services/request/app-file-upload-download.md b/en/application-dev/basic-services/request/app-file-upload-download.md index ee7e18e5cd347fec73cc250a40cf091b2dadb311..1758d0ade146babbd22d2f72863dab31931948f0 100644 --- a/en/application-dev/basic-services/request/app-file-upload-download.md +++ b/en/application-dev/basic-services/request/app-file-upload-download.md @@ -173,7 +173,12 @@ try { // Way 2: Use request.agent. // pages/xxx.ets // Download the network resource file to the local application file directory, and read data from the file. +import { common } from '@kit.AbilityKit'; +import fs from '@ohos.file.fs'; import { BusinessError, request } from '@kit.BasicServicesKit'; +import { buffer } from '@kit.ArkTS'; + +// Obtain the application file path. let context = getContext(this) as common.UIAbilityContext; let filesDir = context.filesDir; @@ -210,3 +215,46 @@ request.agent.create(context, config).then((task: request.agent.Task) => { console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); }); ``` + +## Adding Network Configuration + +### Intercepting HTTP + +You can set the configuration file to intercept HTTP. After HTTP is disabled for the upload and download module, upload and download tasks using plaintext HTTP cannot be created. The configuration file is stored in the **src/main/resources/base/profile/network_config.json** directory of the application. + +The sample configuration file is as follows: + +```ts +{ + "network-security-config": { + "base-config": { + "cleartextTrafficPermitted": true, + "trust-anchors": [ + { + "certificates": "/etc/security/certificates" + } + ] + }, + "domain-config": [ + { + "cleartextTrafficPermitted": true, + "domains": [ + { + "include-subdomains": true, + "name": "*.example.com" + } + ], + } + ] + } +} + +``` + +The table below lists the description of each field. + +| Field | Type | Description | +| --------------------------| --------------- | -------------------------------------- | +| base-config:
cleartextTrafficPermitted | boolean | Whether plaintext transfer is allowed in the global configuration. The value **true** means that plaintext transfer is allowed, that is, HTTP is not intercepted, and **false** means the opposite.| +| domain-config:
cleartextTrafficPermitted | boolean | Whether plaintext transfer is allowed in a specified domain. The value **true** means that plaintext transfer is allowed, that is, HTTP is not intercepted, and **false** means the opposite.| +| include-subdomains | boolean | Whether a rule applies to subdomains. The value **true** means that the regular expression is used to match the domain name, and **false** means the opposite.| diff --git a/en/application-dev/basic-services/update/Readme-EN.md b/en/application-dev/basic-services/update/Readme-EN.md index 0fa01081de728eb3382f8132e21730c39067b59b..a51e0088e06ff0ddc4467e10dc8c60e329ca0226 100644 --- a/en/application-dev/basic-services/update/Readme-EN.md +++ b/en/application-dev/basic-services/update/Readme-EN.md @@ -1,4 +1,4 @@ -# Update +# Update - [Sample Server Development Overview](sample-server-overview.md) - [Sample Server Development](sample-server-guidelines.md) diff --git a/en/application-dev/basic-services/usb/Readme-EN.md b/en/application-dev/basic-services/usb/Readme-EN.md index cf103267508782de18a57b64d2253400a32079c3..cce5eebb12a15a10a470c8eec0c9475f4b44fcbe 100644 --- a/en/application-dev/basic-services/usb/Readme-EN.md +++ b/en/application-dev/basic-services/usb/Readme-EN.md @@ -1,5 +1,22 @@ -# USB Service +# USB Service + - [USB Service Overview](usb-overview.md) - [USB Service Development](usb-guidelines.md) + +- Developing USB Services + - [USB Service Development Overview](usbManager/usbHost-overview.md) + - USB Host Development + - [USB Device Management](usbManager/usbHost/deviceManager.md) + - [USB Control Transfer](usbManager/usbHost/controlTransfer.md) + - [USB Interrupt Transfer](usbManager/usbHost/interruptTransfer.md) + - [USB Bulk Transfer](usbManager/usbHost/bulkTransfer.md) + - [USB Isochronous Transfer](usbManager/usbHost/isochronousTransfer.md) +- Developing USB Serial Communication Services. + - [USB Serial Communication Development Overview](usbSerial/usbSerial-overview.md) + - [USB Serial Configuration Management](usbSerial/usbSerial-configuration.md) + - [USB Serial Communication Management](usbSerial/usbSerial-communication.md) - [FAQs](faqs-usb.md) +- [Glossary](usb-glossary.md) + + \ No newline at end of file diff --git a/en/application-dev/basic-services/usb/faqs-usb.md b/en/application-dev/basic-services/usb/faqs-usb.md index c92e6d07e5fff983fed668cc1fce3c0be012ca5d..34431bf5df783c6472bf53b2110a893f70f589eb 100644 --- a/en/application-dev/basic-services/usb/faqs-usb.md +++ b/en/application-dev/basic-services/usb/faqs-usb.md @@ -14,11 +14,52 @@ If the current device functions as the USB host, the **usbManager.getDevices** A Based on the preceding description: -- When a device, for example, a phone, is connected to a PC using a USB cable, the PC is the USB host by default, and the phone is a USB device. -It is normal if the device list obtained by calling **usbManager.getDevices** on the phone is empty. -- When a device, for example, a phone, is connected to a mouse or keyboard using a USB cable, the phone is the USB host by default, and the mouse or keyboard is the USB device. -In this case, you can call the **usbManager.getDevices** API on the phone to obtain the device list. +- When a device, for example, a phone, is connected to a PC using a USB cable, the PC is the USB host by default, and the phone is a USB device. It is normal if the device list obtained by calling **usbManager.getDevices** on the phone is empty. +- When a device, for example, a phone, is connected to a mouse or keyboard using a USB cable, the phone is the USB host by default, and the mouse or keyboard is the USB device. In this case, you can call the **usbManager.getDevices** API on the phone to obtain the device list. ### Solution Ensure that the current device is the USB host and the connected device is the USB device. (Some devices can serve both as the USB host and USB device. In this case, you need to set such devices as USB devices so that the device list can be obtained by the USB host.) + +## What should I do if garbled characters are displayed when data is transferred through the USB? + +### Symptom + +Garbled characters are displayed during data transfer. + +### Possible Causes + +The baud rate does not match. + +### Solution + +Check whether the baud rates at both ends are the same. If not, reconfigure the baud rates. + +## What should I do if communication fails when data is transferred through the USB? + +### Symptom + +The connection cannot be set up between the two ends. No data is transferred or received, or the transferred data frames are incomplete (for example, only some bytes are received). + +### Possible Causes + +The parity bit or stop bit is incorrectly configured. + +### Solution + +Check whether the settings of the parity bit or stop bit at both ends are the same as those required by the device. + +## What should I do if packet loss occurs when data is transferred through the USB? + + +### Symptom + +Occasional packet loss occurs during data transfer. + +### Possible Causes + +Noise interference or insufficient stop bit. + +### Solution + +Check whether interference exists. Modify the stop bit to improve the anti-interference capability (for example, change the stop bit from 1 to 2). diff --git a/en/application-dev/basic-services/usb/figures/en-us_image_22989BBB5490.png b/en/application-dev/basic-services/usb/figures/en-us_image_22989BBB5490.png new file mode 100644 index 0000000000000000000000000000000000000000..fe32b8a7db1408d851c3ef85d7f0325591f908f1 Binary files /dev/null and b/en/application-dev/basic-services/usb/figures/en-us_image_22989BBB5490.png differ diff --git a/en/application-dev/basic-services/usb/usb-glossary.md b/en/application-dev/basic-services/usb/usb-glossary.md new file mode 100644 index 0000000000000000000000000000000000000000..c95122e868811e411d8ece89e41b687c3ea01966 --- /dev/null +++ b/en/application-dev/basic-services/usb/usb-glossary.md @@ -0,0 +1,75 @@ +# USB Service Terms + +## B + +### Baud rate + +The baud rate indicates the number of symbols transmitted by a serial port device per second. A symbol is a binary bit, including the data bit, start bit, stop bit, and parity bit. The unit is baud. For example, 9600 baud indicates that 9600 symbols are transmitted per second. The sender and receiver must use the same baud rate. Otherwise, data cannot be correctly parsed. + +### Bulk transfer + +A one-way data transfer mode of the USB service, which is applicable to the scenario where a large amount of data needs to be transferred. During the transfer, the bulk transactions (IN/OUT token packet, data packet, and handshake packet) are used to increase the overall transfer volume, and the error detection and retransfer mechanisms are used to ensure the reliability of data transfer. However, bulk transfer has the lowest priority among the USB transfer modes. It is mainly used in devices that require low real-time performance but high reliability, such as USB flash drives, printers, and scanners. + +## C + +### Control transfer + +A two-way data transfer mode of the USB service, which is applicable to device configuration, status query, and command transfer. Its process consists of three phases: setup phase (SETUP transaction), data phase (optional batch transaction), and status phase (handshake confirmation). This mode is mainly used for basic control operations such as device enumeration (such as descriptor reading), initialization configuration, and firmware upgrade. + +## D + +### Data bit + +The data bit indicates the number of valid binary bits actually transmitted in each data packet, which determines the data capacity of a single character. Commonly, a data bit may consist of five to eight digits. The data bit determines the amount of information transmitted at a time. The more the data bits, the larger the amount of information transmitted at a time, but more time is required for synchronization. + +### Device + +A device is a peripheral connected to the host. It executes specific functions (such as storage and data input/output) and passively responds to instructions from the host. For example, a USB flash drive, mouse, or printer is a device. + +## E + +### Endpoint + +An endpoint is a logical end point for data transfer between a device and a host. It is a basic unit for USB communication. Each endpoint has a unique address and direction (**IN** indicates device-to-host, and **OUT** indicates host-to-device). Each endpoint represents a one-way or two-way data transfer pipe. + +## H + +### Host + +The host is a device that controls and manages the USB. It manages the connected devices on the bus and coordinates data transfer and communication. The host is usually a calculator or another host, such as a PC, a smartphone, or a tablet, which can connect to and control multiple devices through the USB port to provide data transfer and charging. + +## I + +### Interface + +An interface is a logical abstraction of a functional module in a USB device, and represents an independent function (such as audio, storage, or communication) of the device. Each interface contains a group of endpoints and manages their activation status through USB configuration. Through flexible interface configuration, USB devices can reuse multiple functions and dynamically switch functions. This is the core mechanism for the USB protocol to support plug-and-play and complex peripherals. + +### Interrupt transfer + +A one-way data transfer mode of the USB service. The host periodically polls the device (for example, 1 ms to 255 ms) to ensure isochronous performance and accuracy. The transaction structure is similar to that of bulk transfer, but the priority is higher. It is applicable to input devices that require low-latency response, such as keyboard, mouse, and game controller. + +### Isochronous transfer + +A one-way data transfer mode of the USB service. No handshake packet is transferred. The fixed bandwidth is used to ensure isochronous performance but allow data loss. A transaction contains only tokens and data phases and is suitable for streaming media transfer. It is applicable to devices that require high continuity and fault tolerance, such as cameras, USB speakers, and video conferencing devices. + +## P + +### Parity bit + +A parity bit is a 1-bit binary value appended to a data frame. It is generated based on the content of the data bit according to specific rules. Commonly, for an odd parity check, the total number of **1** in the data bits and parity bit is an odd number; for an even parity check, the total number of **1** is an even number; for no parity check, no parity bit is added to the data bit. By verifying the number of **1** in the data bit, the parity bit determines whether errors such as bit flipping and noise interference occur during data transfer. Increasing the parity bit slightly reduces the transfer efficiency but improves the error tolerance. + +### Pipe + +A pipe is a logical communication channel between a host and an endpoint for data transfer. A pipe is not a physical connection, but an abstract communication path between a host and a device endpoint. Each pipe corresponds to a specific endpoint of the device. Pipes provide one-way data transfer, and the direction is determined by the endpoint. For example, the IN endpoint indicates that the data is transferred from a pipe to the host, while the OUT endpoint indicates that the data is transferred from the host to a pipe. + +## S + +### Stop bit + +The stop bit is located at the end of a data frame. It is a logic high-level signal and is used to identify the end of a character (data packet) transfer. Its length can be 1 bit, 1.5 bits, or 2 bits. (In actual development, 1 bit is most commonly used, and 1.5 bits and 2 bits are mainly used in anti-interference scenarios.) A core function of this bit is to provide a space to tolerate the errors that may occur during time-sequence synchronization for a receiver and ensure data integrity. + +## U + +### USBConfiguration + +USBConfiguration indicates a function set of the USB device. A USB device supports multiple configurations, but only one of them can be activated at a time. Each USBconfiguration contains multiple interfaces, and each interface represents an independent function (such as data transfer and audio output). In addition, each interface contains multiple endpoints for data transfer (such as control transfer and bulk transfer). diff --git a/en/application-dev/basic-services/usb/usb-guidelines.md b/en/application-dev/basic-services/usb/usb-guidelines.md index 200789ae157151a23b8271e16a5245965bb4891a..318c234105da7806c74ce83193b87889c5558559 100644 --- a/en/application-dev/basic-services/usb/usb-guidelines.md +++ b/en/application-dev/basic-services/usb/usb-guidelines.md @@ -20,8 +20,8 @@ The following table lists the USB APIs currently available. For details, see the | hasRight(deviceName: string): boolean | Checks whether the user has the device access permissions.| | requestRight(deviceName: string): Promise<boolean> | Requests the device access permissions for the application. This API uses a promise to return the result. | | removeRight(deviceName: string): boolean | Revokes the device access permissions of the application.| -| connectDevice(device: USBDevice): Readonly<USBDevicePipe> | Connects to the USB device based on the device information returned by `getDevices()`. | -| getDevices(): Array<Readonly<USBDevice>> | Obtains the list of USB devices connected to the host. If no device is connected, an empty list is returned. | +| connectDevice(device: USBDevice): Readonly<USBDevicePipe> | Connects to the USB device based on the device information returned by `getDevices()`. If the USB service is abnormal, `undefined` may be returned. Check whether the return value of the API is empty. | +| getDevices(): Array<Readonly<USBDevice>> | Obtains the list of USB devices connected to the host. If no device is connected, an empty list is returned. When the developer mode is disabled, `undefined` may be returned if no device is connected. Check whether the return value of the API is empty. | | setConfiguration(pipe: USBDevicePipe, config: USBConfiguration): number | Sets the USB device configuration. | | setInterface(pipe: USBDevicePipe, iface: USBInterface): number | Sets a USB interface. | | claimInterface(pipe: USBDevicePipe, iface: USBInterface, force ?: boolean): number | Claims a USB interface. | @@ -29,7 +29,7 @@ The following table lists the USB APIs currently available. For details, see the | closePipe(pipe: USBDevicePipe): number | Closes a USB device pipe. | | releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number | Releases a USB interface. | | getFileDescriptor(pipe: USBDevicePipe): number | Obtains the file descriptor. | -| getRawDescriptor(pipe: USBDevicePipe): Uint8Array | Obtains the raw USB descriptor. | +| getRawDescriptor(pipe: USBDevicePipe): Uint8Array | Obtains the raw USB descriptor. If the USB service is abnormal, `undefined` may be returned. Check whether the return value of the API is empty. | | usbControlTransfer(pipe: USBDevicePipe, requestparam: USBDeviceRequestParams, timeout?: number): Promise<number> | Performs control transfer. | diff --git a/en/application-dev/basic-services/usb/usb-overview.md b/en/application-dev/basic-services/usb/usb-overview.md index 1cfdfa215c5dfe606796af3e9848d1373be8843a..fa4af7646a13ef3e340c49d9b63011192ed9e48b 100644 --- a/en/application-dev/basic-services/usb/usb-overview.md +++ b/en/application-dev/basic-services/usb/usb-overview.md @@ -1,4 +1,4 @@ -# USB Service Development Overview +# USB Service Overview ## Basic Concepts diff --git a/en/application-dev/basic-services/usb/usbManager/bulkTransfer.md b/en/application-dev/basic-services/usb/usbManager/usbhost/bulkTransfer.md similarity index 90% rename from en/application-dev/basic-services/usb/usbManager/bulkTransfer.md rename to en/application-dev/basic-services/usb/usbManager/usbhost/bulkTransfer.md index 4e67993b1073d080c043d093bbb11c97e0178397..a07c1cb393c63924ab09bacb821128f1c626f481 100644 --- a/en/application-dev/basic-services/usb/usbManager/bulkTransfer.md +++ b/en/application-dev/basic-services/usb/usbManager/usbhost/bulkTransfer.md @@ -4,9 +4,9 @@ Bulk transfer is used to transfer and receive a large amount of data without bandwidth or interval requirements, for example, file or image transfer. Devices such as printers and scanners support this type of transfer. -## Environment Preparation +## Preparing the Environment -### Requirements +### Environment Requirements - Development tool and configuration: @@ -22,9 +22,9 @@ Bulk transfer is used to transfer and receive a large amount of data without ban HarmonyOS Device Connector (hdc) is a command-line tool for debugging. It can be used to interact with real devices or the Emulators on Windows, Linux, and macOS. For details about the configuration, see [hdc](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/hdc-V5). -### Setting Up the Environment +### Environment Setup -- Download and install DevEco Studio on the PC. For details, see [Downloading Software](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/ide-software-download-V5) and [Installing DevEco Studio](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/ide-software-install-V5). The DevEco Studio version must be 4.1 or later. +- Install [DevEco Studio](https://developer.huawei.com/consumer/cn/download/deveco-studio) 4.1 or later on the PC. - Update the public-SDK to API version 16 or later. For details, see [Switching to Full SDK](https://gitee.com/openharmony/docs/blob/master/en/application-dev/faqs/full-sdk-switch-guide.md). - Install hdc on the PC. You can use it to interact with a real device or emulator on Windows, Linux, or macOS. For details, see [hdc](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/hdc-V5). - Use a USB cable to connect an OpenHarmony device to the PC. @@ -37,7 +37,7 @@ Bulk transfer is used to transfer and receive a large amount of data without ban |-------------------------------------------------------------------------------------------------------------------|-----------------------| | bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout ?: number): Promise<number> | Performs bulk transfer. | -For details about the APIs of device management and transfer modes, see [@ohos.usbManager (USB Manager)](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis-basic-services-kit/js-apis-usbManager.md). +For details about the APIs of device management and transfer modes, see [@ohos.usbManager (USB Manager)](../../../../reference/apis-basic-services-kit/js-apis-usbManager.md). ### Development Procedure @@ -165,7 +165,7 @@ Connect a host to a device and use the **bulkTransfer** API to transfer data. Th }); ``` -6. Release the USB interface, and close the USB device. +6. Release the USB interface, and close the USB device pipe. ```ts usbManager.releaseInterface(pipe, interface1); diff --git a/en/application-dev/basic-services/usb/usbManager/controlTransfer.md b/en/application-dev/basic-services/usb/usbManager/usbhost/controlTransfer.md similarity index 89% rename from en/application-dev/basic-services/usb/usbManager/controlTransfer.md rename to en/application-dev/basic-services/usb/usbManager/usbhost/controlTransfer.md index bc4df13ebe0b630491aee2c9302398965dcf8ecb..6c6e1009c3d72a4f746154c4b867a544b4b4d6e0 100644 --- a/en/application-dev/basic-services/usb/usbManager/controlTransfer.md +++ b/en/application-dev/basic-services/usb/usbManager/usbhost/controlTransfer.md @@ -4,9 +4,9 @@ The control transfer is used to obtain and set the device status, and control the device attribute status. You can determine whether the control transfer can read or write data based on the endpoint types supported by the device. -## Environment Preparation +## Preparing the Environment -### Requirements +### Environment Requirements - Development tool and configuration: @@ -22,9 +22,9 @@ The control transfer is used to obtain and set the device status, and control th HarmonyOS Device Connector (hdc) is a command-line tool for debugging. It can be used to interact with real devices or the Emulators on Windows, Linux, and macOS. For details about the configuration, see [hdc](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/hdc-V5). -### Setting Up the Environment +### Environment Setup -- Download and install DevEco Studio on the PC. For details, see [Downloading Software](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/ide-software-download-V5) and [Installing DevEco Studio](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/ide-software-install-V5). The DevEco Studio version must be 4.1 or later. +- Install [DevEco Studio](https://developer.huawei.com/consumer/cn/download/deveco-studio) 4.1 or later on the PC. - Update the public-SDK to API version 16 or later. For details, see [Switching to Full SDK](https://gitee.com/openharmony/docs/blob/master/en/application-dev/faqs/full-sdk-switch-guide.md). - Install hdc on the PC. You can use it to interact with a real device or the Emulator on Windows, Linux, or macOS. For details, see [hdc](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/hdc-V5). - Use a USB cable to connect an OpenHarmony device to the PC. @@ -37,7 +37,7 @@ The control transfer is used to obtain and set the device status, and control th | ------------------------------------------------------------ |--------| | usbControlTransfer(pipe: USBDevicePipe, requestparam: USBDeviceRequestParams, timeout?: number): Promise<number> | Performs control transfer. | -For details about the APIs of device management and transfer modes, see [@ohos.usbManager (USB Manager)](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis-basic-services-kit/js-apis-usbManager.md). +For details about the APIs of device management and transfer modes, see [@ohos.usbManager (USB Manager)](../../../../reference/apis-basic-services-kit/js-apis-usbManager.md). ### Development Procedure @@ -156,7 +156,7 @@ Connect a host to a device and use the **usbControlTransfer** API to transfer da }) ``` -6. Release the USB interface, and close the USB device. +6. Release the USB interface, and close the USB device pipe. ```ts usbManager.releaseInterface(pipe, interface1); diff --git a/en/application-dev/basic-services/usb/usbManager/usbhost/deviceManager.md b/en/application-dev/basic-services/usb/usbManager/usbhost/deviceManager.md new file mode 100644 index 0000000000000000000000000000000000000000..e3ef88cc5849305fefc05a65a565ada42c9109f2 --- /dev/null +++ b/en/application-dev/basic-services/usb/usbManager/usbhost/deviceManager.md @@ -0,0 +1,159 @@ +# USB Device Management + +## When to Use + +When a USB device is inserted, you can use **usbManager** to obtain basic information about the USB device, such as the device type and supported functions. The host communicates with the USB device through the encapsulated pipe. In OpenHarmony, the USB management service is the core component that manages the connection and communication with USB devices. With the USB management service, applications can detect the USB connection and disconnection, manage permission requests and device configurations of USB devices, and perform data transfer and device control. + +## Environment Preparation + +### Environment Requirements + +- Development tool and configuration: + + DevEco Studio, as the driver development tool, allows you to develop, debug, and package drivers. [Download and install](https://developer.huawei.com/consumer/cn/download/) DevEco Studio and verify basic operations to ensure that it can function properly. For details, see [Creating and Running a Project](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V14/ide-create-new-project-V14) in [DevEco Studio User Guide](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V14/ide-tools-overview-V14). + + +- SDK version configuration: + + The ArkTs APIs for peripheral management can be used only when the SDK is of API version 16 or later. + + +- HDC configuration: + + HarmonyOS Device Connector (hdc) is a command-line tool for debugging. It can be used to interact with real devices or the Emulators on Windows, Linux, and macOS. For details about the configuration, see [hdc](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/hdc-V5). + +### Environment Setup + +- Install [DevEco Studio](https://developer.huawei.com/consumer/cn/download/deveco-studio) 4.1 or later on the PC. +- Update the public SDK to API version 16 or later. For details, see [Update Guide](https://gitee.com/openharmony/docs/blob/master/en/application-dev/faqs/full-sdk-switch-guide.md). +- Install hdc on the PC. You can use it to interact with a real device or the Emulator on Windows, Linux, or macOS. For details, see [hdc](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/hdc-V5). +- Use a USB cable to connect an OpenHarmony device to the PC. + +## How to Develop + +### Available APIs + +USB device management provides the following functions: querying the USB device list, controlling USB device permissions, and setting USB device configurations. + +The following table lists the USB APIs currently available. For details, see [@ohos.usbManager (USB Manager)](../../../../reference/apis-basic-services-kit/js-apis-usbManager.md). + +**Table 1** Open USB APIs + +| API | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| hasRight(deviceName: string): boolean | Checks whether the USB has the device access permissions.| +| requestRight(deviceName: string): Promise<boolean> | Requests the temporary permission for the application to access the USB device. This API uses a promise to return the result. | +| removeRight(deviceName: string): boolean | Removes the device access permissions of the application.| +| connectDevice(device: USBDevice): Readonly<USBDevicePipe> | Connects to the USB device based on the device information returned by **getDevices()**. | +| getDevices(): Array<Readonly<USBDevice>> | Obtains the list of USB devices connected to the host. If no device is connected, an empty list is returned. | +| setConfiguration(pipe: USBDevicePipe, config: USBConfiguration): number | Sets the USB device configuration. | +| setInterface(pipe: USBDevicePipe, iface: USBInterface): number | Sets a USB interface. | +| claimInterface(pipe: USBDevicePipe, iface: USBInterface, force ?: boolean): number | Claims a USB interface. | +| closePipe(pipe: USBDevicePipe): number | Closes a USB device pipe. | +| releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number | Releases a USB interface. | +| getFileDescriptor(pipe: USBDevicePipe): number | Obtains the file descriptor of a USB device. | +| getRawDescriptor(pipe: USBDevicePipe): Uint8Array | Obtains the raw USB descriptor. | + +### How to Develop + +A USB device can be used as a host to connect to a device for management. The procedure is as follows: + + +1. Import modules. + + ```ts + // Import the usbManager module. + import { usbManager } from '@kit.BasicServicesKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + ``` + +2. Obtain the USB device list. + + ```ts + // Obtain the USB device list. + let deviceList : Array = usbManager.getDevices(); + /* + Example deviceList structure: + [ + { + name: "1-1", + serial: "", + manufacturerName: "", + productName: "", + version: "", + vendorId: 7531, + productId: 2, + clazz: 9, + subClass: 0, + protocol: 1, + devAddress: 1, + busNum: 1, + configs: [ + { + id: 1, + attributes: 224, + isRemoteWakeup: true, + isSelfPowered: true, + maxPower: 0, + name: "1-1", + interfaces: [ + { + id: 0, + protocol: 0, + clazz: 9, + subClass: 0, + alternateSetting: 0, + name: "1-1", + endpoints: [ + { + address: 129, + attributes: 3, + interval: 12, + maxPacketSize: 4, + direction: 128, + number: 1, + type: 3, + interfaceId: 0, + } + ] + } + ] + } + ] + } + ] + */ + ``` + +3. Obtain the device operation permissions. + + ```ts + let deviceName : string = deviceList[0].name; + // Request the permissions to operate a specified device. + usbManager.requestRight(deviceName).then((hasRight : boolean) => { + console.info("usb device request right result: " + hasRight); + }).catch((error : BusinessError)=> { + console.info("usb device request right failed : " + error); + }); + ``` + +4. Open the device. + + ```ts + // Open the device, and obtain the USB device pipe for data transfer. + let pipe : usbManager.USBDevicePipe = usbManager.connectDevice(deviceList[0]); + let interface1 : usbManager.USBInterface = deviceList[0].configs[0].interfaces[0]; + /* + Claim the corresponding interface from **deviceList**. + interface1 must be one present in the device configuration. + */ + usbManager.claimInterface(pipe, interface1, true); + ``` + +5. Release the USB interface, and close the USB device. + + ```ts + usbManager.releaseInterface(pipe, interface1); + usbManager.closePipe(pipe); + ``` + diff --git a/en/application-dev/basic-services/usb/usbManager/usbhost/interruptTransfer.md b/en/application-dev/basic-services/usb/usbManager/usbhost/interruptTransfer.md new file mode 100644 index 0000000000000000000000000000000000000000..a497587c8866a1289c7d7ca89af5e6644ed5867a --- /dev/null +++ b/en/application-dev/basic-services/usb/usbManager/usbhost/interruptTransfer.md @@ -0,0 +1,162 @@ +# USB Interrupt Transfer + +## When to Use + +The interrupt transfer is mainly used by the host to receive a data packet sent by a device. The endpoint mode of a device determines whether the interface supports interrupt reading or interrupt writing. This mode is applicable to the transfer of a small number of scattered and unpredictable data input by devices such as the mouse, keyboard, and joystick. In addition, the endpoints of these devices support only interrupt reading. + +## Preparing the Environment + +### Environment Requirements + +- Development tool and configuration: + + DevEco Studio, as the driver development tool, allows you to develop, debug, and package drivers. [Download and install](https://developer.huawei.com/consumer/cn/download/) DevEco Studio and verify basic operations to ensure that it can function properly. For details, see [Creating and Running a Project](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V14/ide-create-new-project-V14) in [DevEco Studio User Guide](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V14/ide-tools-overview-V14). + + +- SDK version configuration: + + The ArkTs APIs for peripheral management can be used only when the SDK is of API version 16 or later. + + +- HDC configuration: + + HarmonyOS Device Connector (hdc) is a command-line tool for debugging. It can be used to interact with real devices or the Emulators on Windows, Linux, and macOS. For details about the configuration, see [hdc](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/hdc-V5). + +### Environment Setup + +- Install [DevEco Studio](https://developer.huawei.com/consumer/cn/download/deveco-studio) 4.1 or later on the PC. +- Update the public SDK to API version 16 or later. For details, see [Switching to Full SDK](https://gitee.com/openharmony/docs/blob/master/en/application-dev/faqs/full-sdk-switch-guide.md). +- Install hdc on the PC. You can use it to interact with a real device or the Emulator on Windows, Linux, or macOS. For details, see [hdc](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/hdc-V5). +- Use a USB cable to connect an OpenHarmony device to the PC. + +## How to Develop + +### Available APIs + +| API | Description | +|------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------| +| usbSubmitTransfer(transfer: UsbDataTransferParams): void | Submits isochronous, bulk, or interrupt transfer in an asynchronous manner. | +| usbCancelTransfer(transfer: UsbDataTransferParams): void | Cancels the submitted asynchronous transfer. | + +For details about the APIs of device management and transfer modes, see [@ohos.usbManager (USB Manager)](../../../../reference/apis-basic-services-kit/js-apis-usbManager.md). + +### How to Develop + +Connect a host to a device and use the **usbSubmitTransfer** API to transfer data. The following steps describe how to implement an interrupt transfer: + +1. Import modules. + + ```ts + // Import the usbManager module. + import { usbManager } from '@kit.BasicServicesKit'; + ``` + +2. Obtain the USB device list. + + ```ts + // Obtain the list of USB devices connected to the host. + let usbDevices: Array = usbManager.getDevices(); + console.info('usbDevices: ', JSON.stringify(usbDevices)); + if(usbDevices.length === 0) { + console.info('usbDevices is empty'); + return; + } + ``` + +3. Obtain the device operation permissions. + + ```ts + // Check whether the first USB device in the list has the access permission. + let usbDevice: usbManager.USBDevice = usbDevices[0]; + if(!usbManager.hasRight(usbDevice.name)) { + await usbManager.requestRight(usbDevice.name).then(result => { + if(!result) { + // If the USB device does not have the access permission and is not granted by the user, the device exits. + console.info('user is not granted the operation permission'); + return; + } + }); + } + ``` + +4. Obtain the endpoint for reading data through interrupt transfer. + + ```ts + let devicePipe: usbManager.USBDevicePipe = usbManager.connectDevice(usbDevice); + let usbConfigs: usbManager.USBConfiguration[] = usbDevice.configs; + let usbInterfaces: usbManager.USBInterface[] = []; + let usbInterface: usbManager.USBInterface | undefined = undefined + let usbEndpoints: usbManager.USBEndpoint[] = []; + let usbEndprint: usbManager.USBEndpoint | undefined = undefined + for (let i = 0; i < usbConfigs.length; i++) { + usbInterfaces = usbConfigs[i].interfaces; + for (let i = 0; i < usbInterfaces.length; i++) { + usbEndpoints = usbInterfaces[i].endpoints; + usbEndprint = usbEndpoints.find((value) => { + return value.direction === 128 && value.type === usbManager.UsbEndpointTransferType.TRANSFER_TYPE_INTERRUPT; + }) + if (usbEndprint !== undefined) { + usbInterface = usbInterfaces[i]; + break; + } + } + } + if (usbEndprint === undefined) { + console.error(`get usbEndprint error`) + return; + } + ``` + +5. Connect to the device and register the communication interface. + + ```ts + // Register a communication interface. If the registration is successful, 0 is returned; otherwise, other error codes are returned. + let claimInterfaceResult: number = usbManager.claimInterface(devicePipe, usbInterface, true); + if (claimInterfaceResult !== 0) { + console.error(`claimInterface error = ${claimInterfaceResult}`) + return; + } + ``` + +6. Perform data transfer. + + ```ts + try { + // The communication interface is successfully registered and performs data transfer. + let transferParams: usbManager.UsbDataTransferParams = { + devPipe: devicePipe, + flags: usbManager.UsbTransferFlags.USB_TRANSFER_SHORT_NOT_OK, + endpoint: usbEndprint.address, + type: usbManager.UsbEndpointTransferType.TRANSFER_TYPE_INTERRUPT, + timeout: 2000, + length: 10, + callback: () => {}, + userData: new Uint8Array(10), + buffer: new Uint8Array(10), + isoPacketCount: 2, + }; + + transferParams.callback = (err: Error, callBackData: usbManager.SubmitTransferCallback) => { + console.info('callBackData = ' + JSON.stringify(callBackData)); + console.info('transfer success, result = ' + transferParams.buffer.toString()); + } + usbManager.usbSubmitTransfer(transferParams); + console.info('USB transfer request submitted.'); + } catch (error) { + console.error('USB transfer failed:', error); + } + ``` + +7. Cancels the data transfer, releases the interface, and closes the USB device pipe. + + ```ts + usbManager.usbCancelTransfer(transferParams); + usbManager.releaseInterface(devicePipe, usbInterface); + usbManager.closePipe(devicePipe); + ``` + +### Verification + +1. Connect the host to a terminal device (such as a mouse or a keyboard) that supports interrupt transfer through a USB interface. +2. Execute the preceding code. +3. Search for the keyword **transfer success** in the log. If the keyword is found, the interrupt transfer interface is successfully called. diff --git a/en/application-dev/basic-services/usb/usbManager/usbhost/isochronousTransfer.md b/en/application-dev/basic-services/usb/usbManager/usbhost/isochronousTransfer.md new file mode 100644 index 0000000000000000000000000000000000000000..a2af8a69e32468706253cd67b48c01c76e73283d --- /dev/null +++ b/en/application-dev/basic-services/usb/usbManager/usbhost/isochronousTransfer.md @@ -0,0 +1,172 @@ +# USB Isochronous Transfer + +## When to Use + +Isochronous transfer is a transfer mode in which data is transferred in a fixed time window through the USB protocol. This ensures the timing stability and low latency of data streams, but allows a small amount of data loss (such as video frame loss and audio noise). This transfer mode is applicable to scenarios that have high requirements on continuity and fault tolerance, such as USB headsets, USB speakers, and video conferencing devices. + +## Preparing the Environment + +### Environment Requirements + +- Development tool and configuration: + + DevEco Studio, as the driver development tool, allows you to develop, debug, and package drivers. [Download and install](https://developer.huawei.com/consumer/cn/download/) DevEco Studio and verify basic operations to ensure that it can function properly. For details, see [Creating and Running a Project](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V14/ide-create-new-project-V14) in [DevEco Studio User Guide](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V14/ide-tools-overview-V14). + + +- SDK version configuration: + + The ArkTs APIs for peripheral management can be used only when the SDK is of API version 16 or later. + + +- HDC configuration: + + HarmonyOS Device Connector (hdc) is a command-line tool for debugging. It can be used to interact with real devices or the Emulators on Windows, Linux, and macOS. For details about the configuration, see [hdc](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/hdc-V5). + +### Environment Setup + +- Install [DevEco Studio](https://developer.huawei.com/consumer/cn/download/deveco-studio) 4.1 or later on the PC. +- Update the public SDK to API version 16 or later. For details, see [Switching to Full SDK](https://gitee.com/openharmony/docs/blob/master/en/application-dev/faqs/full-sdk-switch-guide.md). +- Install hdc on the PC. You can use it to interact with a real device or the Emulator on Windows, Linux, or macOS. For details, see [hdc](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/hdc-V5). +- Use a USB cable to connect an OpenHarmony device to the PC. + +## How to Develop + +### Available APIs + +| API | Description | +|------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------| +| usbSubmitTransfer(transfer: UsbDataTransferParams): void | Submits isochronous, bulk, or interrupt transfer in an asynchronous manner. | +| usbCancelTransfer(transfer: UsbDataTransferParams): void | Cancels the submitted asynchronous transfer. | + +For details about the APIs of device management and transfer modes, see [@ohos.usbManager (USB Manager)](../../../../reference/apis-basic-services-kit/js-apis-usbManager.md). + +### How to Develop + +Connect a host to a device and use the **usbSubmitTransfer** API to transfer data. The following steps describe how to implement an interrupt transfer: + +1. Import modules. + + ```ts + // Import the usbManager module. + import { usbManager } from '@kit.BasicServicesKit'; + ``` + +2. Obtain the USB device list. + + ```ts + // Obtain the list of USB devices connected to the host. + let usbDevices: Array = usbManager.getDevices(); + console.info('usbDevices: ', JSON.stringify(usbDevices)); + if(usbDevices.length === 0) { + console.info('usbDevices is empty'); + return; + } + ``` + +3. Obtain the device operation permissions. + + ```ts + // Check whether the first USB device in the list has the access permission. + let usbDevice: usbManager.USBDevice = usbDevices[0]; + if(!usbManager.hasRight(usbDevice.name)) { + await usbManager.requestRight(usbDevice.name).then(result => { + if(!result) { + // If the USB device does not have the access permission and is not granted by the user, the device exits. + console.info('user is not granted the operation permission'); + return; + } + }); + } + ``` + +4. Obtain the endpoint for reading data through interrupt transfer. + + ```ts + let devicePipe: usbManager.USBDevicePipe = usbManager.connectDevice(usbDevice); + let usbConfigs: usbManager.USBConfiguration[] = usbDevice.configs; + let usbInterfaces: usbManager.USBInterface[] = []; + let usbInterface: usbManager.USBInterface | undefined = undefined + let usbEndpoints: usbManager.USBEndpoint[] = []; + let usbEndprint: usbManager.USBEndpoint | undefined = undefined + for (let i = 0; i < usbConfigs.length; i++) { + usbInterfaces = usbConfigs[i].interfaces; + for (let i = 0; i < usbInterfaces.length; i++) { + usbEndpoints = usbInterfaces[i].endpoints; + usbEndprint = usbEndpoints.find((value) => { + // direction indicates the request direction. The value 0 indicates the written data, and the value 128 indicates the read data. + return value.direction === 128 && value.type === usbManager.UsbEndpointTransferType.TRANSFER_TYPE_ISOCHRONOUS; + }) + if (usbEndprint !== undefined) { + usbInterface = usbInterfaces[i]; + break; + } + } + } + if (usbEndprint === undefined) { + console.error(`get usbEndprint error`) + return; + } + ``` + +5. Connect to the device and register the communication interface. + + ```ts + // Register a communication interface. If the registration is successful, 0 is returned; otherwise, other error codes are returned. + let claimInterfaceResult: number = usbManager.claimInterface(devicePipe, usbInterface, true); + if (claimInterfaceResult !== 0) { + console.error(`claimInterface error = ${claimInterfaceResult}`) + return; + } + + // When the transfer is of the isochronous type, you need to register a device interface. If the registration is successful, 0 is returned; otherwise, other error codes are returned. + if (this.type === usbManager.UsbEndpointTransferType.TRANSFER_TYPE_ISOCHRONOUS) { + let setInterfaceResult = usbManager.setInterface(devicePipe, usbInterface); + if (setInterfaceResult !== 0) { + console.info(`setInterfaceResult error = ${setInterfaceResult}`) + return; + } + } + ``` + +6. Perform data transfer. + + ```ts + try { + // The communication interface is successfully registered and performs data transfer. + let transferParams: usbManager.UsbDataTransferParams = { + devPipe: devicePipe, + flags: usbManager.UsbTransferFlags.USB_TRANSFER_SHORT_NOT_OK, + endpoint: usbEndprint.address, + type: usbManager.UsbEndpointTransferType.TRANSFER_TYPE_ISOCHRONOUS, + timeout: 2000, + length: 10, + callback: () => {}, + userData: new Uint8Array(10), + buffer: new Uint8Array(10), + isoPacketCount: 2, + }; + + transferParams.callback = (err: Error, callBackData: usbManager.SubmitTransferCallback) => { + console.info('callBackData = ' + JSON.stringify(callBackData)); + console.info('transfer success, result = ' + transferParams.buffer.toString()); + } + usbManager.usbSubmitTransfer(transferParams); + console.info('USB transfer request submitted.'); + } catch (error) { + console.error('USB transfer failed:', error); + } + ``` + +7. Cancels the data transfer, releases the interface, and closes the USB device pipe. + + ```ts + usbManager.usbCancelTransfer(transferParams); + usbManager.releaseInterface(devicePipe, usbInterface); + usbManager.closePipe(devicePipe); + ``` + +### Verification + +1. Connect the host to a device (such as a USB headset) that supports isochronous transfer through a USB interface. +2. Execute the preceding code. +3. Search for the keyword **transfer success** in the log. If the keyword is found, the isochronous transfer interface is successfully called. diff --git a/en/application-dev/basic-services/usb/usbserial/usbSerial-communication.md b/en/application-dev/basic-services/usb/usbserial/usbSerial-communication.md new file mode 100644 index 0000000000000000000000000000000000000000..91a8bfb47caaa5bbca9f564668feda13c81b5794 --- /dev/null +++ b/en/application-dev/basic-services/usb/usbserial/usbSerial-communication.md @@ -0,0 +1,136 @@ +# USB Serial Communication Management + +## Overview + +In the USB serial communication service, the USB port of the host is connected to the serial port of the serial port device for serial data transmission. The core objective of communication management is to implement efficient and stable data transmission and collaborative control between devices. It is mainly used in scenarios such as industrial automation and remote management, IoT device interconnection, and medical device management. + +## Preparing the Environment + +For details, see [Preparing the Environment](usbSerial-overview.md#preparing-the-environment) in *USB Serial Communication Development Overview*. + +## How to Develop + +### Available APIs + +| API | Description | +|------------------------------------------------------------------------------|--------------------------| +| getPortList(): Readonly<SerialPort>[] | Obtains the serial port device list. | +| hasSerialRight(portId: number): boolean | Checks whether the application has the permission to access the serial port device. | +| requestSerialRight(portId: number): Promise<boolean> | Requests the permission to access the serial port device. | +| open(portId: number): void | Opens a serial port device. | +| close(portId: number): void | Closes a serial port device. | +| read(portId: number, buffer: Uint8Array, timeout?: number): Promise<number> | Reads data from a serial port device. This API uses a promise to return the result.| +| readSync(portId: number, buffer: Uint8Array, timeout?: number): number | Reads data from a serial port device in a synchronous manner. | +| write(portId: number, buffer: Uint8Array, timeout?: number): Promise<number> | Writes data to a serial port device. This API uses a promise to return the result.| +| writeSync(portId: number, buffer: Uint8Array, timeout?: number): number | Writes data to a serial port device in a synchronous manner. | + + +### Development Procedure + +You can read and write data as follows: + +1. Import the **usbManager** module. + + ```ts + // Import the usbManager module. + import serial from '@ohos.usbManager.serial'; + import { buffer } from '@kit.ArkTS'; + ``` + +2. Obtain the USB device list. + + ```ts + // Obtain the list of USB devices connected to the host. + let portList: serial.SerialPort[] = serial.getPortList(); + console.info('usbSerial portList: ' + JSON.stringify(portList)); + if (portList === undefined || portList.length === 0) { + console.info('usbSerial portList is empty'); + return; + } + ``` + +3. Obtain the device operation permissions. + + ```ts + // Check whether the first USB device in the list has the access permission. + let portId: number = portList[0].portId; + if (!serial.hasSerialRight(portId)) { + await serial.requestSerialRight(portId).then(result => { + if(!result) { + // If the device does not have the access permission and is not granted by the user, the device exits. + console.info('usbSerial user is not granted the operation permission'); + return; + } + }); + } + ``` + +4. Open the device based on the serial port. + + ```ts + try { + serial.open(portId) + console.info('open usbSerial success, portId: ' + portId); + } catch (error) { + console.error('open usbSerial error, ' + JSON.stringify(error)); + } + ``` + +5. Read data through the serial port. + + ```ts + // Read data asynchronously. + let readBuffer: Uint8Array = new Uint8Array(64); + serial.read(portId, readBuffer, 2000).then((size: number) => { + console.info('read usbSerial success, readBuffer: ' + readBuffer.toString()); + }).catch((error: Error) => { + console.error('read usbSerial error, ' + JSON.stringify(error)); + }) + + // Read data synchronously. + let readSyncBuffer: Uint8Array = new Uint8Array(64); + try { + serial.readSync(portId, readSyncBuffer, 2000); + console.info('readSync usbSerial success, readSyncBuffer: ' + readSyncBuffer.toString()); + } catch (error) { + console.error('readSync usbSerial error, ' + JSON.stringify(error)); + } + ``` + +6. Write data through the serial port. + + ```ts + // Write data asynchronously. + let writeBuffer: Uint8Array = new Uint8Array(buffer.from('Hello World', 'utf-8').buffer) + serial.write(portId, writeBuffer, 2000).then((size: number) => { + console.info('write usbSerial success, writeBuffer: ' + writeBuffer.toString()); + }).catch((error: Error) => { + console.error('write usbSerial error, ' + JSON.stringify(error)); + }) + + // Write data synchronously. + let writeSyncBuffer: Uint8Array = new Uint8Array(buffer.from('Hello World', 'utf-8').buffer) + try { + serial.writeSync(portId, writeSyncBuffer, 2000); + console.info('writeSync usbSerial success, writeSyncBuffer: ' + writeSyncBuffer.toString()); + } catch (error) { + console.error('writeSync usbSerial error, ' + JSON.stringify(error)); + } + ``` + +7. Close a serial port device. + + ```ts + try { + serial.close(portId); + console.info('close usbSerial success, portId: ' + portId); + } catch (error) { + console.error('close usbSerial error, ' + JSON.stringify(error)); + } + ``` + +### Debugging and Verification + +1. Prepare a USB-to-serial cable. Connect the USB port and the serial port of the cable to that of the OpenHarmony device. +2. Execute the preceding sample code on the OpenHarmony device. +3. Return **usbSerial success** if the related API is successfully called and the serial port communication of the device runs properly; return **usbSerial error** otherwise. diff --git a/en/application-dev/basic-services/usb/usbserial/usbSerial-configuration.md b/en/application-dev/basic-services/usb/usbserial/usbSerial-configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..578792167a9b89b1f075960aef7f2bce5a2c1fec --- /dev/null +++ b/en/application-dev/basic-services/usb/usbserial/usbSerial-configuration.md @@ -0,0 +1,128 @@ +# USB Serial Configuration Management + +## Overview + +In the USB serial configuration management, the baud rate, data bit, parity bit, and stop bit are the core parameters of the serial port communication protocol. They define the format and rules of data transmission. By properly setting these parameters, you can significantly improve the reliability and efficiency of serial port communication. + +### Basic Concepts + +Before developing the USB serial port, you should have a basic understanding of the following concepts: + +- Baud rate + + The baud rate indicates the number of symbols transmitted by a serial port device per second. A symbol is a binary bit, including the data bit, start bit, stop bit, and parity bit. The unit is baud. For example, 9600 baud indicates that 9600 symbols are transmitted per second. The sender and receiver must use the same baud rate. Otherwise, data cannot be correctly parsed. + + +- Data bit + + The data bit indicates the number of valid binary bits actually transmitted in each data packet, which determines the data capacity of a single character. Commonly, a data bit may consist of five to eight digits. The data bit determines the amount of information transmitted at a time. The more the data bits, the larger the amount of information transmitted at a time, but more time is required for synchronization. + + +- Parity bit + + A parity bit is a 1-bit binary value appended to a data frame. It is generated based on the content of the data bit according to specific rules. Commonly, for an odd parity check, the total number of **1** in the data bits and parity bit is an odd number; for an even parity check, the total number of **1** is an even number; for no parity check, no parity bit is added to the data bit. By verifying the number of **1** in the data bit, the parity bit determines whether errors such as bit flipping and noise interference occur during data transfer. Increasing the parity bit slightly reduces the transfer efficiency but improves the error tolerance. + + +- Stop bit + + The stop bit is located at the end of a data frame. It is a logic high-level signal and is used to identify the end of a character (data packet) transfer. Its length can be 1 bit, 1.5 bits, or 2 bits. (In actual development, 1 bit is most commonly used, and 1.5 bits and 2 bits are mainly used in anti-interference scenarios.) A core function of this bit is to provide a space to tolerate the errors that may occur during time-sequence synchronization for a receiver and ensure data integrity. + + +## Preparing the Environment + +For details, see [Preparing the Environment](usbSerial-overview.md#preparing-the-environment) in *USB Serial Communication Development Overview*. + +## How to Develop + +### Available APIs + +| API | Description | +|------------------------------------------------------------------------------|-----------| +| getAttribute(portId: number): Readonly<SerialAttribute> | Obtains the serial port device configuration.| +| setAttribute(portId: number, attribute: SerialAttribute): void | Sets the serial port device configuration.| + +### Development Procedure + +You can obtain and set the serial port configuration as follows: + +1. Import the **usbManager** module. + + ```ts + // Import the usbManager module. + import serial from '@ohos.usbManager.serial'; + ``` + +2. Obtain the USB device list. + + ```ts + // Obtain the list of USB devices connected to the host. + let portList: serial.SerialPort[] = serial.getPortList(); + console.info('usbSerial portList: ' + JSON.stringify(portList)); + if (portList === undefined || portList.length === 0) { + console.info('usbSerial portList is empty'); + return; + } + ``` + +3. Obtain the device operation permissions. + + ```ts + // Check whether the first USB device in the list has the access permission. + let portId: number = portList[0].portId; + if (!serial.hasSerialRight(portId)) { + await serial.requestSerialRight(portId).then(result => { + if(!result) { + // If the device does not have the access permission and is not granted by the user, the device exits. + console.info('usbSerial user is not granted the operation permission'); + return; + } + }); + } + ``` + +4. Open the device based on the serial port. + + ```ts + try { + serial.open(portId) + console.info('open usbSerial success, portId: ' + portId); + } catch (error) { + console.error('open usbSerial error, ' + JSON.stringify(error)); + } + ``` + +5. Obtain and modify serial port configurations. + + ```ts + // Obtain the serial port configuration. + try { + let attribute: serial.SerialAttribute = serial.getAttribute(portId); + if (attribute === undefined) { + console.error('getAttribute usbSerial error, attribute is undefined'); + } else { + console.info('getAttribute usbSerial success, attribute: ' + JSON.stringify(attribute)); + } + } catch (error) { + console.error('getAttribute usbSerial error, ' + JSON.stringify(error)); + } + + // Set the serial port configuration. + try { + let attribute: serial.SerialAttribute = { + baudRate: serial.BaudRates.BAUDRATE_9600, + dataBits: serial.DataBits.DATABIT_8, + parity: serial.Parity.PARITY_NONE, + stopBits: serial.StopBits.STOPBIT_1 + } + serial.setAttribute(portId, attribute); + console.info('setAttribute usbSerial success, attribute: ' + JSON.stringify(attribute)); + } catch (error) { + console.error('setAttribute usbSerial error, ' + JSON.stringify(error)); + } + ``` + +### Debugging and Verification + +1. Prepare a USB-to-serial cable. Connect the USB port and the serial port of the cable to that of the OpenHarmony device. +2. Execute the preceding sample code on the OpenHarmony device. +3. Return **getAttribute usbSerial success** and **setAttribute usbSerial success** if related APIs are successfully called. You can view the current serial port configuration. diff --git a/en/application-dev/basic-services/usb/usbserial/usbSerial-overview.md b/en/application-dev/basic-services/usb/usbserial/usbSerial-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..8b93123b3a2572d3c94938b4e4237c9df32c7c3c --- /dev/null +++ b/en/application-dev/basic-services/usb/usbserial/usbSerial-overview.md @@ -0,0 +1,62 @@ +# USB Serial Communication Development Overview + +## Overview + +The USB serial communication service provides the USB host-to-serial port communication. With this service, you can obtain the list of connected ports that comply with the USB host-to-serial protocol and be able to enable and disable ports, set parameters, obtain parameters, read data, write data, and manage device permissions. + +For details about configuration management and communication management, see [USB Serial Configuration Management](usbSerial-configuration.md) and [USB Serial Communication Management](usbSerial-communication.md) respectively. + +### Basic Concepts + +Before developing the service, you should have a basic understanding of the following concepts: + +- Serial port + + It is an expansion interface that uses serial communication, where data is transmitted sequentially one bit at a time. The serial port features simple communication lines. Only one pair of transmission lines is required to implement a two-way communication in a long distance. + +### Implementation Principles + +The USB serial port service consists of two phases: + +- Identify the device and load the driver. + + After a USB-to-serial device is inserted, the USB host initiates an enumeration process over the USB bus to obtain the device descriptor (such as the vendor ID, device ID, and USB identifier of the communication device class). The OS matches the driver based on the descriptor to initialize the device and register the virtual serial port. + +- Transmit and receive data. + + Transmitting data: + The application layer sends data. → The driver transmits the data to the device through the USB channel. → The device parses the data and sends the data to the serial port device through the physical serial port. + + Receiving data: + The device receives the data from the physical serial port. → The device packages and uploads data to the USB host. → The driver receives and stores data in the serial port buffer. → The application layer reads the data. + + +**Figure 1** Process of transmitting and receiving data + +![Data Receiving and Transmission Through the Serial Port](../figures/en-us_image_22989BBB5490.png) + +### Constraints + +- Before data transmission between the host and the serial port device, you need to request a permission to access the device. Data can be transmitted only after the user grants the permission. + +- If the configuration parameters during data transmission are not set, the default configuration parameters are used (baud rate: 9600 bit/s; data bit: 8; parity bit: 0; stop bit: 1). + +## Preparing the Environment + +### Environment Requirements + +- Development tool and configuration: + + As a development tool, DevEco Studio is a prerequisite for developing the USB serial communication service. You can use DevEco Studio to perform development, debugging, and packaging. [Download and install](https://developer.huawei.com/consumer/cn/download/) DevEco Studio and verify basic operations to ensure that it can function properly. For details, see [Creating and Running a Project](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V14/ide-create-new-project-V14) in [DevEco Studio User Guide](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V14/ide-tools-overview-V14). + +- SDK version configuration: + + API version 18 or later. + +### Environment Setup + +- Install [DevEco Studio](https://developer.huawei.com/consumer/cn/download/deveco-studio) 4.1 or later on the PC. +- Update the public-SDK to API version 18 or later. For details, see [OpenHarmony SDK Upgrade Assistant](../../../tools/openharmony_sdk_upgrade_assistant.md). +- Prepare a USB-to-serial cable. Connect the USB port and the serial port of the cable to that of the OpenHarmony device. + + \ No newline at end of file diff --git a/en/application-dev/calendarmanager/calendarmanager-calendar-developer.md b/en/application-dev/calendarmanager/calendarmanager-calendar-developer.md index 9ebc03f067f085348abc94860a4f29efebc732ec..00d6bb3b11e9dd9960644bcb38d9a3d0685d88c4 100644 --- a/en/application-dev/calendarmanager/calendarmanager-calendar-developer.md +++ b/en/application-dev/calendarmanager/calendarmanager-calendar-developer.md @@ -11,15 +11,15 @@ You can create an application-specific calendar, and add, delete, update, and qu The table below lists the main APIs used for calendar management. For details about more APIs and their usage, see [@ohos.calendarManager](../reference/apis-calendar-kit/js-apis-calendarManager.md). | API | Description | -| ------------------------------------------------------------ | ------------------------------------------------------------ | -| getCalendarManager(context : Context): CalendarManager | Obtains the **CalendarManager** object based on the context to manage calendars. | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| getCalendarManager(context: Context): CalendarManager | Obtains the **CalendarManager** object based on the context to manage calendars. | | createCalendar(calendarAccount: CalendarAccount): Promise\ | Creates a **Calendar** object based on the calendar account information. This API uses a promise to return the result.| | getCalendar(calendarAccount?: CalendarAccount): Promise\ | Obtains the default or specified **Calendar** object. This API uses a promise to return the result.
The default **Calendar** object is created when the data storage runs for the first time. You can call this API instead of **createCalendar()** to use the default calendar for a new event.| -| getAllCalendars(): Promise\ | Obtains the created and default **Calendar** objects of the current application. This API uses a promise to return the result.| -| deleteCalendar(calendar: Calendar): Promise\ | Deletes a specified **Calendar** object. This API uses a promise to return the result. | -| getConfig(): CalendarConfig | Obtains the calendar configuration information. | -| setConfig(config: CalendarConfig): Promise\ | Sets the calendar configuration information. This API uses a promise to return the result. | -| getAccount(): CalendarAccount | Obtains the calendar account information. | +| getAllCalendars(): Promise\ | Obtains the created and default **Calendar** objects of the current application. This API uses a promise to return the result.| +| deleteCalendar(calendar: Calendar): Promise\ | Deletes a specified **Calendar** object. This API uses a promise to return the result. | +| getConfig(): CalendarConfig | Obtains the calendar configuration information. | +| setConfig(config: CalendarConfig): Promise\ | Sets the calendar configuration information. This API uses a promise to return the result. | +| getAccount(): CalendarAccount | Obtains the calendar account information. | ## How to Develop @@ -28,7 +28,7 @@ The table below lists the main APIs used for calendar management. For details ab ```ts // EntryAbility.ets - import {abilityAccessCtrl,AbilityConstant, common, PermissionRequestResult, Permissions, UIAbility, Want } from '@kit.AbilityKit'; + import { abilityAccessCtrl, AbilityConstant, common, PermissionRequestResult, Permissions, UIAbility, Want } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; import { calendarManager } from '@kit.CalendarKit'; import { window } from '@kit.ArkUI'; @@ -67,7 +67,7 @@ The table below lists the main APIs used for calendar management. For details ab const permissions: Permissions[] = ['ohos.permission.READ_CALENDAR', 'ohos.permission.WRITE_CALENDAR']; let atManager = abilityAccessCtrl.createAtManager(); atManager.requestPermissionsFromUser(mContext, permissions).then((result: PermissionRequestResult) => { - console.log(`get Permission success, result: ${JSON.stringify(result)}`); + console.info(`get Permission success, result: ${JSON.stringify(result)}`); calendarMgr = calendarManager.getCalendarManager(mContext); }).catch((error: BusinessError) => { console.error(`get Permission error, error. Code: ${error.code}, message: ${error.message}`); @@ -122,7 +122,7 @@ The table below lists the main APIs used for calendar management. For details ab }); ``` -5. After a calendar is created, it is displayed in black. You need to call the **setConfig()** API to set calendar configuration information, including event reminder and calendar color. +5. After a calendar is created, it is displayed in black. You need to call **setConfig()** to set calendar configuration information, including event reminder and calendar color. ```ts // Index.ets @@ -150,7 +150,7 @@ The table below lists the main APIs used for calendar management. For details ab }).catch((err: BusinessError) => { console.error(`Failed to get calendar. Code: ${err.code}, message: ${err.message}`); }); - ``` + ``` 7. Query a default calendar. The default **Calendar** object is created when the data storage runs for the first time. You can use the default calendar for a new event. @@ -161,7 +161,7 @@ The table below lists the main APIs used for calendar management. For details ab }).catch((err: BusinessError) => { console.error(`Failed to get calendar. Code: ${err.code}, message: ${err.message}`); }); - ``` + ``` 8. Obtain the created and default **Calendar** objects of the current application. @@ -189,4 +189,4 @@ The table below lists the main APIs used for calendar management. For details ab }).catch((err: BusinessError) => { console.error(`Failed to delete calendar. Code: ${err.code}, message: ${err.message}`); }); - ``` + ``` diff --git a/en/application-dev/calendarmanager/calendarmanager-event-developer.md b/en/application-dev/calendarmanager/calendarmanager-event-developer.md index 47c592b12309fd6330e40e1e3eed7af409949a60..73c45066d6ce9965fa9bebc4233a522964719e56 100644 --- a/en/application-dev/calendarmanager/calendarmanager-event-developer.md +++ b/en/application-dev/calendarmanager/calendarmanager-event-developer.md @@ -10,14 +10,14 @@ After obtaining the **Calendar** object, you can create, delete, modify and quer The table below lists the main APIs used for event management. For details about more APIs and their usage, see [@ohos.calendarManager](../reference/apis-calendar-kit/js-apis-calendarManager.md). -| API | Description | -| ------------------------------------------------------------ | ------------------------------------------------------------ | -| getCalendarManager(context : Context): CalendarManager | Obtains a **CalendarManager** object based on the context. | +| API | Description | +| ----------------------------------------- | ------------------------------------------------------------ | +| getCalendarManager(context: Context): CalendarManager | Obtains a **CalendarManager** object based on the context. | | createCalendar(calendarAccount: CalendarAccount): Promise\ | Creates a **Calendar** object based on the calendar account information. This API uses a promise to return the result.| -| addEvent(event: Event): Promise\ | Creates an event, with no event ID specified in **Event**. This API uses a promise to return the result. | -| editEvent(event: Event): Promise\ | Creates a single event. If the input parameter **Event** is not set to the event ID, the event creation screen is displayed when this API is called. This API uses a promise to return the result.| -| deleteEvent(id: number): Promise\ | Deletes an event with the specified ID. This API uses a promise to return the result. | -| updateEvent(event: Event): Promise\ | Updates an event. This API uses a promise to return the result. | +| addEvent(event: Event): Promise\ | Creates an event, with no event ID specified in **Event**. This API uses a promise to return the result. | +| editEvent(event: Event): Promise\ | Creates a single event. If the input parameter **Event** is not set to the event ID, the event creation screen is displayed when this API is called. This API uses a promise to return the result.| +| deleteEvent(id: number): Promise\ | Deletes an event with the specified ID. This API uses a promise to return the result. | +| updateEvent(event: Event): Promise\ | Updates an event. This API uses a promise to return the result. | | getEvents(eventFilter?: EventFilter, eventKey?: (keyof Event)[]): Promise\ | Obtains all events in a calendar that match the filter criteria. This API uses a promise to return the result. | ## How to Develop @@ -26,7 +26,7 @@ The table below lists the main APIs used for event management. For details about ```ts // entry/src/main/ets/entryability/EntryAbility.ets - import {abilityAccessCtrl,AbilityConstant, common, PermissionRequestResult, Permissions, UIAbility, Want } from '@kit.AbilityKit'; + import { abilityAccessCtrl, AbilityConstant, common, PermissionRequestResult, Permissions, UIAbility, Want } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; import { calendarManager } from '@kit.CalendarKit'; import { window } from '@kit.ArkUI'; @@ -65,7 +65,7 @@ The table below lists the main APIs used for event management. For details about const permissions: Permissions[] = ['ohos.permission.READ_CALENDAR', 'ohos.permission.WRITE_CALENDAR']; let atManager = abilityAccessCtrl.createAtManager(); atManager.requestPermissionsFromUser(mContext, permissions).then((result: PermissionRequestResult) => { - console.log(`get Permission success, result: ${JSON.stringify(result)}`); + console.info(`get Permission success, result: ${JSON.stringify(result)}`); calendarMgr = calendarManager.getCalendarManager(mContext); }).catch((error: BusinessError) => { console.error(`get Permission error, error. Code: ${error.code}, message: ${error.message}`); @@ -138,9 +138,9 @@ The table below lists the main APIs used for event management. For details about Currently, you can create an event in either of the following methods: - Method 1: Use the **addEvent()** or **addEvents()** API to create an event in the calendar. You can use the **addEvent()** API to create a single event or use the **addEvents()** API to create events in batches. The following describes how to create a single event. + Method 1: Use **addEvent()** to create a single event or **addEvents()** to create events in batches. The following describes how to create a single event. - Method 2: After obtaining the **calendarManager** object, you can use the **editEvent()** API to create a single event. In this case, the event creation page is displayed, where you can perform related operations to create an event. Note that **editEvent()** does not support the creation of custom periodic events. + Method 2: After obtaining the **calendarManager** object, you can use **editEvent()** to create a single event. In this case, the event creation page is displayed, where you can perform related operations to create an event. Note that **editEvent()** does not support the creation of custom periodic events. ```ts // Index.ets @@ -190,7 +190,7 @@ The table below lists the main APIs used for event management. For details about console.error(`Failed to addEvent. Code: ${err.code}, message: ${err.message}`); }); // Method 2 - const eventInfo: calendarManager.Event = { + const eventInfo: calendarManager.Event = { // Event title. title: 'title', // Event type. @@ -265,7 +265,7 @@ The table below lists the main APIs used for event management. For details about }); ``` -8. Delete a specified event by event ID. You can use the **deleteEvent()** API to create a single event or use the **deleteEvents()** API to delete events in batches. The following describes how to delete a single event. +8. Delete a specified event by event ID. You can use **deleteEvent()** to create a single event or use **deleteEvents()** to delete events in batches. The following describes how to delete a single event. ```ts // Index.ets diff --git a/en/application-dev/connectivity/Readme-EN.md b/en/application-dev/connectivity/Readme-EN.md index a349609ea828b0c0a7feb3e7312a60d93afbc3b0..179cc92dc7f5867c18ceafd536a2865c3de9d379 100755 --- a/en/application-dev/connectivity/Readme-EN.md +++ b/en/application-dev/connectivity/Readme-EN.md @@ -1,16 +1,16 @@ -# Connectivity Kit (Short-Range Communication Service) +# Connectivity Kit - [Introduction to Connectivity Kit](connectivity-kit-intro.md) -- Bluetooth +- Bluetooth - [Bluetooth Overview](bluetooth/bluetooth-overview.md) - [Bluetooth Setting Development](bluetooth/br-development-guide.md) - [BLE Development](bluetooth/ble-development-guide.md) - [GATT Development](bluetooth/gatt-development-guide.md) - [SPP Development](bluetooth/spp-development-guide.md) -- NFC +- NFC - [NFC Tag Read/Write Development](nfc/nfc-tag-access-guide.md) - [HCE Development](nfc/nfc-hce-guide.md) - [SE Access Development](nfc/nfc-se-access-guide.md) -- WLAN +- WLAN - [WLAN Service Development Overview](wlan/wlan-overview.md) - - [P2P Mode Development](wlan/p2p-development-guide.md) + - [P2P Development Guide](wlan/p2p-development-guide.md) diff --git a/en/application-dev/connectivity/bluetooth/Readme-EN.md b/en/application-dev/connectivity/bluetooth/Readme-EN.md index 37cd9847b51c1a13e73633994173952dd80bf73a..22f9501bad4d0368774d7a451494279425d16edc 100644 --- a/en/application-dev/connectivity/bluetooth/Readme-EN.md +++ b/en/application-dev/connectivity/bluetooth/Readme-EN.md @@ -1,6 +1,9 @@ - # Bluetooth - - [Bluetooth Overview](bluetooth-overview.md) +# Bluetooth + +- [Bluetooth Overview](bluetooth-overview.md) +- Classic Bluetooth - [Bluetooth Setting Development](br-development-guide.md) - - [BLE Development](ble-development-guide.md) - - [GATT Development](gatt-development-guide.md) - - [SPP Development](spp-development-guide.md) + - [SPP-based Data Transmission Development](spp-development-guide.md) +- Bluetooth Low Energy + - [BLE Advertising and Scanning Development](ble-development-guide.md) + - [GATT-based BLE Connection and Data Transmission Development](gatt-development-guide.md) diff --git a/en/application-dev/connectivity/bluetooth/ble-development-guide.md b/en/application-dev/connectivity/bluetooth/ble-development-guide.md index d75c1af4b8b15593ab312eb785d183f49226686f..77ac90c0adf6ce6a02efe5734d605fd16048ce4a 100644 --- a/en/application-dev/connectivity/bluetooth/ble-development-guide.md +++ b/en/application-dev/connectivity/bluetooth/ble-development-guide.md @@ -1,4 +1,4 @@ -# BLE Development +# BLE Advertising and Scanning Development ## Introduction Bluetooth advertising and scanning help discover Bluetooth-enabled devices and implement BLE communication. This topic walks you through on how to start and stop Bluetooth advertising and scanning. @@ -13,7 +13,7 @@ You can use the APIs provided by the **ble** module to: For details about the APIs and sample code, see [@ohos.bluetooth.ble](../../reference/apis-connectivity-kit/js-apis-bluetooth-ble.md). -The following table describes the APIs used in this topic. +The following table describes the related APIs. | API | Description | | ---------------------------------- | ------------------------------------------------------------------------------ | @@ -33,363 +33,363 @@ The following table describes the APIs used in this topic. ### Starting and Stopping BLE Advertising 1. Import the **ble** module. 2. Enable Bluetooth on the device. -3. Check that the SystemCapability.Communication.Bluetooth.Core capability is available. -4. Start BLE advertising. The peer device scans the advertisement. -5. Stop BLE advertising. - -Example: - -```ts -import { ble } from '@kit.ConnectivityKit'; -import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; - -const TAG: string = 'BleAdvertisingManager'; - -export class BleAdvertisingManager { - private advHandle: number = 0xFF; // default invalid value - - // 1. Subscribe to BLE advertising state changes. - public onAdvertisingStateChange() { - try { - ble.on('advertisingStateChange', (data: ble.AdvertisingStateChangeInfo) => { - console.info(TAG, 'bluetooth advertising state = ' + JSON.stringify(data)); - AppStorage.setOrCreate('advertiserState', data.state); - }); - } catch (err) { - console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); - } - } - - // 2. Start BLE advertising the first time. - public async startAdvertising() { - // 2.1 Set BLE advertising parameters. - let setting: ble.AdvertiseSetting = { - interval: 160, - txPower: 0, - connectable: true - }; - // 2.2 Construct the data to be advertised. - let manufactureValueBuffer = new Uint8Array(4); - manufactureValueBuffer[0] = 1; - manufactureValueBuffer[1] = 2; - manufactureValueBuffer[2] = 3; - manufactureValueBuffer[3] = 4; - let serviceValueBuffer = new Uint8Array(4); - serviceValueBuffer[0] = 5; - serviceValueBuffer[1] = 6; - serviceValueBuffer[2] = 7; - serviceValueBuffer[3] = 8; - let manufactureDataUnit: ble.ManufactureData = { - manufactureId: 4567, - manufactureValue: manufactureValueBuffer.buffer - }; - let serviceDataUnit: ble.ServiceData = { - serviceUuid: "00001888-0000-1000-8000-00805f9b34fb", - serviceValue: serviceValueBuffer.buffer - }; - let advData: ble.AdvertiseData = { - serviceUuids: ["00001888-0000-1000-8000-00805f9b34fb"], - manufactureData: [manufactureDataUnit], - serviceData: [serviceDataUnit], - includeDeviceName: false // Whether the device name is carried. This parameter is optional. Note that the length of an advertising packet including the device name cannot exceed 31 bytes. - }; - let advResponse: ble.AdvertiseData = { - serviceUuids: ["00001888-0000-1000-8000-00805f9b34fb"], - manufactureData: [manufactureDataUnit], - serviceData: [serviceDataUnit] - }; - // 2.3 Construct AdvertisingParams for starting the BLE advertising. - let advertisingParams: ble.AdvertisingParams = { - advertisingSettings: setting, - advertisingData: advData, - advertisingResponse: advResponse, - duration: 0 // This parameter is optional. If the value is greater than 0, the advertising stops temporarily after a period of time. You can restart it as required. - } +3. Apply for the **ohos.permission.ACCESS_BLUETOOTH** permission. +4. Check that the SystemCapability.Communication.Bluetooth.Core capability is available. +5. Start BLE advertising. The peer device scans the advertisement. +6. Stop BLE advertising. +7. Example: + + ```ts + import { ble } from '@kit.ConnectivityKit'; + import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; + + const TAG: string = 'BleAdvertisingManager'; + + export class BleAdvertisingManager { + private advHandle: number = 0xFF; // default invalid value + + // 1. Subscribe to BLE advertising state changes. + public onAdvertisingStateChange() { + try { + ble.on('advertisingStateChange', (data: ble.AdvertisingStateChangeInfo) => { + console.info(TAG, 'bluetooth advertising state = ' + JSON.stringify(data)); + AppStorage.setOrCreate('advertiserState', data.state); + }); + } catch (err) { + console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); + } + } - // 2.4 Start BLE advertising the first time. The ID of the BLE advertising is returned. - try { - this.onAdvertisingStateChange(); - this.advHandle = await ble.startAdvertising(advertisingParams); - } catch (err) { - console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); - } - } + // 2. Start BLE advertising the first time. + public async startAdvertising() { + // 2.1 Set BLE advertising parameters. + let setting: ble.AdvertiseSetting = { + interval: 160, + txPower: 0, + connectable: true + }; + // 2.2 Construct the data to be advertised. + let manufactureValueBuffer = new Uint8Array(4); + manufactureValueBuffer[0] = 1; + manufactureValueBuffer[1] = 2; + manufactureValueBuffer[2] = 3; + manufactureValueBuffer[3] = 4; + let serviceValueBuffer = new Uint8Array(4); + serviceValueBuffer[0] = 5; + serviceValueBuffer[1] = 6; + serviceValueBuffer[2] = 7; + serviceValueBuffer[3] = 8; + let manufactureDataUnit: ble.ManufactureData = { + manufactureId: 4567, + manufactureValue: manufactureValueBuffer.buffer + }; + let serviceDataUnit: ble.ServiceData = { + serviceUuid: "00001888-0000-1000-8000-00805f9b34fb", + serviceValue: serviceValueBuffer.buffer + }; + let advData: ble.AdvertiseData = { + serviceUuids: ["00001888-0000-1000-8000-00805f9b34fb"], + manufactureData: [manufactureDataUnit], + serviceData: [serviceDataUnit], + includeDeviceName: false // Whether the device name is carried. This parameter is optional. Note that the length of an advertising packet including the device name cannot exceed 31 bytes. + }; + let advResponse: ble.AdvertiseData = { + serviceUuids: ["00001888-0000-1000-8000-00805f9b34fb"], + manufactureData: [manufactureDataUnit], + serviceData: [serviceDataUnit] + }; + // 2.3 Construct AdvertisingParams for starting the BLE advertising. + let advertisingParams: ble.AdvertisingParams = { + advertisingSettings: setting, + advertisingData: advData, + advertisingResponse: advResponse, + duration: 0 // This parameter is optional. If the value is greater than 0, the advertising stops temporarily after a period of time. You can restart it as required. + } + + // 2.4 Start BLE advertising the first time. The ID of the BLE advertising is returned. + try { + this.onAdvertisingStateChange(); + this.advHandle = await ble.startAdvertising(advertisingParams); + } catch (err) { + console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); + } + } - // 4. Disable the BLE advertising temporarily. The advertising resources still exist. - public async disableAdvertising() { - // 4.1 Construct parameters for temporarily disabling the BLE advertising. - let advertisingDisableParams: ble.AdvertisingDisableParams = { - advertisingId: this.advHandle // Use the ID of the first BLE advertising. - } - // 4.2 Disable the BLE advertising temporarily. - try { - await ble.disableAdvertising(advertisingDisableParams); - } catch (err) { - console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); - } - } - - // 5. Enable the BLE advertising again. - public async enableAdvertising(enableDuration: number) { - // 5.1 Construct the parameters for temporarily enabling the advertising. - let advertisingEnableParams: ble.AdvertisingEnableParams = { - advertisingId: this.advHandle // Use the ID of the first BLE advertising. - duration: enableDuration - } - // 5.2 Enable BLE advertising again. - try { - await ble.enableAdvertising(advertisingEnableParams); - } catch (err) { - console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); - } - } - - // 6. Stop BLE advertising and release related resources. - public async stopAdvertising() { - try { - await ble.stopAdvertising(this.advHandle); - ble.off('advertisingStateChange', (data: ble.AdvertisingStateChangeInfo) => { - console.info(TAG, 'bluetooth advertising state = ' + JSON.stringify(data)); - }); - } catch (err) { - console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); + // 4. Disable the BLE advertising temporarily. The advertising resources still exist. + public async disableAdvertising() { + // 4.1 Construct parameters for temporarily disabling the BLE advertising. + let advertisingDisableParams: ble.AdvertisingDisableParams = { + advertisingId: this.advHandle // Use the ID of the first BLE advertising. + } + // 4.2 Disable the BLE advertising temporarily. + try { + await ble.disableAdvertising(advertisingDisableParams); + } catch (err) { + console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); + } + } + + // 5. Enable the BLE advertising again. + public async enableAdvertising(enableDuration: number) { + // 5.1 Construct the parameters for temporarily enabling the advertising. + let advertisingEnableParams: ble.AdvertisingEnableParams = { + advertisingId: this.advHandle // Use the ID of the first BLE advertising. + duration: enableDuration + } + // 5.2 Enable BLE advertising again. + try { + await ble.enableAdvertising(advertisingEnableParams); + } catch (err) { + console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); + } + } + + // 6. Stop BLE advertising and release related resources. + public async stopAdvertising() { + try { + await ble.stopAdvertising(this.advHandle); + ble.off('advertisingStateChange', (data: ble.AdvertisingStateChangeInfo) => { + console.info(TAG, 'bluetooth advertising state = ' + JSON.stringify(data)); + }); + } catch (err) { + console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); + } + } } - } -} -let bleAdvertisingManager = new BleAdvertisingManager(); -export default bleAdvertisingManager as BleAdvertisingManager; -``` + let bleAdvertisingManager = new BleAdvertisingManager(); + export default bleAdvertisingManager as BleAdvertisingManager; + ``` -For details about the error codes, see [Bluetooth Error Codes](../../reference/apis-connectivity-kit/errorcode-bluetoothManager.md). +7. For details about the error codes, see [Bluetooth Error Codes](../../reference/apis-connectivity-kit/errorcode-bluetoothManager.md). ### Starting and Stop BLE Scanning 1. Import the **ble** module. 2. Enable Bluetooth on the device. -3. Check that the SystemCapability.Communication.Bluetooth.Core capability is available. -4. Start BLE advertising on the peer device. -5. Start BLE scanning on the local device. -6. Stop BLE scanning. - -Example: - -```ts -import { ble } from '@kit.ConnectivityKit'; -import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; - -const TAG: string = 'BleScanManager'; -const BLE_ADV_TYPE_FLAG = 0x01; -const BLE_ADV_TYPE_16_BIT_SERVICE_UUIDS_INCOMPLETE = 0x02; -const BLE_ADV_TYPE_16_BIT_SERVICE_UUIDS_COMPLETE = 0x03; -const BLE_ADV_TYPE_32_BIT_SERVICE_UUIDS_INCOMPLETE = 0x04; -const BLE_ADV_TYPE_32_BIT_SERVICE_UUIDS_COMPLETE = 0x05; -const BLE_ADV_TYPE_128_BIT_SERVICE_UUIDS_INCOMPLETE = 0x06; -const BLE_ADV_TYPE_128_BIT_SERVICE_UUIDS_COMPLETE = 0x07; -const BLE_ADV_TYPE_LOCAL_NAME_SHORT = 0x08; -const BLE_ADV_TYPE_LOCAL_NAME_COMPLETE = 0x09; -const BLE_ADV_TYPE_TX_POWER_LEVEL = 0x0A; -const BLE_ADV_TYPE_16_BIT_SERVICE_SOLICITATION_UUIDS = 0x14; -const BLE_ADV_TYPE_128_BIT_SERVICE_SOLICITATION_UUIDS = 0x15; -const BLE_ADV_TYPE_32_BIT_SERVICE_SOLICITATION_UUIDS = 0x1F; -const BLE_ADV_TYPE_16_BIT_SERVICE_DATA = 0x16; -const BLE_ADV_TYPE_32_BIT_SERVICE_DATA = 0x20; -const BLE_ADV_TYPE_128_BIT_SERVICE_DATA = 0x21; -const BLE_ADV_TYPE_MANUFACTURER_SPECIFIC_DATA = 0xFF; - -const BLUETOOTH_UUID_16_BIT_LENGTH = 2; -const BLUETOOTH_UUID_32_BIT_LENGTH = 4; -const BLUETOOTH_UUID_128_BIT_LENGTH = 16; - -const BLUETOOTH_MANUFACTURE_ID_LENGTH = 2; - -export class BleScanManager { - // 1. Subscribe to the scanning result. - public onScanResult() { - ble.on('BLEDeviceFind', (data: Array) => { - if (data.length > 0) { - console.info(TAG, 'BLE scan result = ' + data[0].deviceId); - this.parseScanResult(data[0].data); +3. Apply for the **ohos.permission.ACCESS_BLUETOOTH** permission. +4. Check that the SystemCapability.Communication.Bluetooth.Core capability is available. +5. Start BLE advertising on the peer device. +6. Start BLE scanning on the local device. +7. Stop BLE scanning. +8. Example: + + ```ts + import { ble } from '@kit.ConnectivityKit'; + import { AsyncCallback, BusinessError } from '@kit.BasicServicesKit'; + + const TAG: string = 'BleScanManager'; + const BLE_ADV_TYPE_FLAG = 0x01; + const BLE_ADV_TYPE_16_BIT_SERVICE_UUIDS_INCOMPLETE = 0x02; + const BLE_ADV_TYPE_16_BIT_SERVICE_UUIDS_COMPLETE = 0x03; + const BLE_ADV_TYPE_32_BIT_SERVICE_UUIDS_INCOMPLETE = 0x04; + const BLE_ADV_TYPE_32_BIT_SERVICE_UUIDS_COMPLETE = 0x05; + const BLE_ADV_TYPE_128_BIT_SERVICE_UUIDS_INCOMPLETE = 0x06; + const BLE_ADV_TYPE_128_BIT_SERVICE_UUIDS_COMPLETE = 0x07; + const BLE_ADV_TYPE_LOCAL_NAME_SHORT = 0x08; + const BLE_ADV_TYPE_LOCAL_NAME_COMPLETE = 0x09; + const BLE_ADV_TYPE_TX_POWER_LEVEL = 0x0A; + const BLE_ADV_TYPE_16_BIT_SERVICE_SOLICITATION_UUIDS = 0x14; + const BLE_ADV_TYPE_128_BIT_SERVICE_SOLICITATION_UUIDS = 0x15; + const BLE_ADV_TYPE_32_BIT_SERVICE_SOLICITATION_UUIDS = 0x1F; + const BLE_ADV_TYPE_16_BIT_SERVICE_DATA = 0x16; + const BLE_ADV_TYPE_32_BIT_SERVICE_DATA = 0x20; + const BLE_ADV_TYPE_128_BIT_SERVICE_DATA = 0x21; + const BLE_ADV_TYPE_MANUFACTURER_SPECIFIC_DATA = 0xFF; + + const BLUETOOTH_UUID_16_BIT_LENGTH = 2; + const BLUETOOTH_UUID_32_BIT_LENGTH = 4; + const BLUETOOTH_UUID_128_BIT_LENGTH = 16; + + const BLUETOOTH_MANUFACTURE_ID_LENGTH = 2; + + export class BleScanManager { + // 1. Subscribe to the scanning result. + public onScanResult() { + ble.on('BLEDeviceFind', (data: Array) => { + if (data.length > 0) { + console.info(TAG, 'BLE scan result = ' + data[0].deviceId); + this.parseScanResult(data[0].data); + } + }); } - }); - } - - private parseScanResult(data: ArrayBuffer) { - let advData = new Uint8Array(data); - if (advData.byteLength == 0) { - console.warn(TAG, 'nothing, adv data length is 0'); - return; - } - console.info(TAG, 'advData: ' + JSON.stringify(advData)); - - let advFlags: number = -1; - let txPowerLevel: number = -1; - let localName: string = ""; - let serviceUuids: string[] = []; - let serviceSolicitationUuids: string[] = []; - let serviceDatas: Record = {}; - let manufactureSpecificDatas: Record = {}; - - let curPos = 0; - while (curPos < advData.byteLength) { - let length = advData[curPos++]; - if (length == 0) { - break; + + private parseScanResult(data: ArrayBuffer) { + let advData = new Uint8Array(data); + if (advData.byteLength == 0) { + console.warn(TAG, 'nothing, adv data length is 0'); + return; + } + console.info(TAG, 'advData: ' + JSON.stringify(advData)); + + let advFlags: number = -1; + let txPowerLevel: number = -1; + let localName: string = ""; + let serviceUuids: string[] = []; + let serviceSolicitationUuids: string[] = []; + let serviceDatas: Record = {}; + let manufactureSpecificDatas: Record = {}; + + let curPos = 0; + while (curPos < advData.byteLength) { + let length = advData[curPos++]; + if (length == 0) { + break; + } + let advDataLength = length - 1; + let advDataType = advData[curPos++]; + switch (advDataType) { + case BLE_ADV_TYPE_FLAG: + advFlags = advData[curPos]; + break; + case BLE_ADV_TYPE_LOCAL_NAME_SHORT: + case BLE_ADV_TYPE_LOCAL_NAME_COMPLETE: + localName = advData.slice(curPos, curPos + advDataLength).toString(); + break; + case BLE_ADV_TYPE_TX_POWER_LEVEL: + txPowerLevel = advData[curPos]; + break; + case BLE_ADV_TYPE_16_BIT_SERVICE_UUIDS_INCOMPLETE: + case BLE_ADV_TYPE_16_BIT_SERVICE_UUIDS_COMPLETE: + this.parseServiceUuid(BLUETOOTH_UUID_16_BIT_LENGTH, curPos, advDataLength, advData, serviceUuids); + break; + case BLE_ADV_TYPE_32_BIT_SERVICE_UUIDS_INCOMPLETE: + case BLE_ADV_TYPE_32_BIT_SERVICE_UUIDS_COMPLETE: + this.parseServiceUuid(BLUETOOTH_UUID_32_BIT_LENGTH, curPos, advDataLength, advData, serviceUuids); + break; + case BLE_ADV_TYPE_128_BIT_SERVICE_UUIDS_INCOMPLETE: + case BLE_ADV_TYPE_128_BIT_SERVICE_UUIDS_COMPLETE: + this.parseServiceUuid(BLUETOOTH_UUID_128_BIT_LENGTH, curPos, advDataLength, advData, serviceUuids); + break; + case BLE_ADV_TYPE_16_BIT_SERVICE_SOLICITATION_UUIDS: + this.parseServiceSolicitationUuid(BLUETOOTH_UUID_16_BIT_LENGTH, curPos, advDataLength, + advData, serviceSolicitationUuids); + break; + case BLE_ADV_TYPE_32_BIT_SERVICE_SOLICITATION_UUIDS: + this.parseServiceSolicitationUuid(BLUETOOTH_UUID_32_BIT_LENGTH, curPos, advDataLength, + advData, serviceSolicitationUuids); + break; + case BLE_ADV_TYPE_128_BIT_SERVICE_SOLICITATION_UUIDS: + this.parseServiceSolicitationUuid(BLUETOOTH_UUID_128_BIT_LENGTH, curPos, advDataLength, + advData, serviceSolicitationUuids); + break; + case BLE_ADV_TYPE_16_BIT_SERVICE_DATA: + this.parseServiceData(BLUETOOTH_UUID_16_BIT_LENGTH, curPos, advDataLength, advData, serviceDatas); + break; + case BLE_ADV_TYPE_32_BIT_SERVICE_DATA: + this.parseServiceData(BLUETOOTH_UUID_32_BIT_LENGTH, curPos, advDataLength, advData, serviceDatas); + break; + case BLE_ADV_TYPE_128_BIT_SERVICE_DATA: + this.parseServiceData(BLUETOOTH_UUID_128_BIT_LENGTH, curPos, advDataLength, advData, serviceDatas); + break; + case BLE_ADV_TYPE_MANUFACTURER_SPECIFIC_DATA: + this.parseManufactureData(curPos, advDataLength, advData, manufactureSpecificDatas); + break; + default: + break; + } + curPos += advDataLength; + } } - let advDataLength = length - 1; - let advDataType = advData[curPos++]; - switch (advDataType) { - case BLE_ADV_TYPE_FLAG: - advFlags = advData[curPos]; - break; - case BLE_ADV_TYPE_LOCAL_NAME_SHORT: - case BLE_ADV_TYPE_LOCAL_NAME_COMPLETE: - localName = advData.slice(curPos, curPos + advDataLength).toString(); - break; - case BLE_ADV_TYPE_TX_POWER_LEVEL: - txPowerLevel = advData[curPos]; - break; - case BLE_ADV_TYPE_16_BIT_SERVICE_UUIDS_INCOMPLETE: - case BLE_ADV_TYPE_16_BIT_SERVICE_UUIDS_COMPLETE: - this.parseServiceUuid(BLUETOOTH_UUID_16_BIT_LENGTH, curPos, advDataLength, advData, serviceUuids); - break; - case BLE_ADV_TYPE_32_BIT_SERVICE_UUIDS_INCOMPLETE: - case BLE_ADV_TYPE_32_BIT_SERVICE_UUIDS_COMPLETE: - this.parseServiceUuid(BLUETOOTH_UUID_32_BIT_LENGTH, curPos, advDataLength, advData, serviceUuids); - break; - case BLE_ADV_TYPE_128_BIT_SERVICE_UUIDS_INCOMPLETE: - case BLE_ADV_TYPE_128_BIT_SERVICE_UUIDS_COMPLETE: - this.parseServiceUuid(BLUETOOTH_UUID_128_BIT_LENGTH, curPos, advDataLength, advData, serviceUuids); - break; - case BLE_ADV_TYPE_16_BIT_SERVICE_SOLICITATION_UUIDS: - this.parseServiceSolicitationUuid(BLUETOOTH_UUID_16_BIT_LENGTH, curPos, advDataLength, - advData, serviceSolicitationUuids); - break; - case BLE_ADV_TYPE_32_BIT_SERVICE_SOLICITATION_UUIDS: - this.parseServiceSolicitationUuid(BLUETOOTH_UUID_32_BIT_LENGTH, curPos, advDataLength, - advData, serviceSolicitationUuids); - break; - case BLE_ADV_TYPE_128_BIT_SERVICE_SOLICITATION_UUIDS: - this.parseServiceSolicitationUuid(BLUETOOTH_UUID_128_BIT_LENGTH, curPos, advDataLength, - advData, serviceSolicitationUuids); - break; - case BLE_ADV_TYPE_16_BIT_SERVICE_DATA: - this.parseServiceData(BLUETOOTH_UUID_16_BIT_LENGTH, curPos, advDataLength, advData, serviceDatas); - break; - case BLE_ADV_TYPE_32_BIT_SERVICE_DATA: - this.parseServiceData(BLUETOOTH_UUID_32_BIT_LENGTH, curPos, advDataLength, advData, serviceDatas); - break; - case BLE_ADV_TYPE_128_BIT_SERVICE_DATA: - this.parseServiceData(BLUETOOTH_UUID_128_BIT_LENGTH, curPos, advDataLength, advData, serviceDatas); - break; - case BLE_ADV_TYPE_MANUFACTURER_SPECIFIC_DATA: - this.parseManufactureData(curPos, advDataLength, advData, manufactureSpecificDatas); - break; - default: - break; + + private parseServiceUuid(uuidLength: number, curPos: number, advDataLength: number, + advData: Uint8Array, serviceUuids: string[]) { + while (advDataLength > 0) { + let tmpData: Uint8Array = advData.slice(curPos, curPos + uuidLength); + serviceUuids.push(this.getUuidFromUint8Array(uuidLength, tmpData)); + advDataLength -= uuidLength; + curPos += uuidLength; + } } - curPos += advDataLength; - } - } - - private parseServiceUuid(uuidLength: number, curPos: number, advDataLength: number, - advData: Uint8Array, serviceUuids: string[]) { - while (advDataLength > 0) { - let tmpData: Uint8Array = advData.slice(curPos, curPos + uuidLength); - serviceUuids.push(this.getUuidFromUint8Array(uuidLength, tmpData)); - advDataLength -= uuidLength; - curPos += uuidLength; - } - } - - private parseServiceSolicitationUuid(uuidLength: number, curPos: number, advDataLength: number, - advData: Uint8Array, serviceSolicitationUuids: string[]) { - while (advDataLength > 0) { - let tmpData: Uint8Array = advData.slice(curPos, curPos + uuidLength); - serviceSolicitationUuids.push(this.getUuidFromUint8Array(uuidLength, tmpData)); - advDataLength -= uuidLength; - curPos += uuidLength; - } - } - private getUuidFromUint8Array(uuidLength: number, uuidData: Uint8Array): string { - let uuid = ""; - let temp: string = ""; - for (let i = uuidLength - 1; i > -1; i--) { - temp += uuidData[i].toString(16).padStart(2, "0"); - } - switch (uuidLength) { - case BLUETOOTH_UUID_16_BIT_LENGTH: - uuid = `0000${temp}-0000-1000-8000-00805F9B34FB`; - break; - case BLUETOOTH_UUID_32_BIT_LENGTH: - uuid = `${temp}-0000-1000-8000-00805F9B34FB`; - break; - case BLUETOOTH_UUID_128_BIT_LENGTH: - uuid = `${temp.substring(0, 8)}-${temp.substring(8, 12)}-${temp.substring(12, 16)}-${temp.substring(16, 20)}-${temp.substring(20, 32)}`; - break; - default: - break; - } - return uuid; - } - - private parseServiceData(uuidLength: number, curPos: number, advDataLength: number, - advData: Uint8Array, serviceDatas: Record) { - let tmpUuid: Uint8Array = advData.slice(curPos, curPos + uuidLength); - let tmpValue: Uint8Array = advData.slice(curPos + uuidLength, curPos + advDataLength); - serviceDatas[tmpUuid.toString()] = tmpValue; - } - - private parseManufactureData(curPos: number, advDataLength: number, - advData: Uint8Array, manufactureSpecificDatas: Record) { - let manufactureId: number = (advData[curPos + 1] << 8) + advData[curPos]; - let tmpValue: Uint8Array = advData.slice(curPos + BLUETOOTH_MANUFACTURE_ID_LENGTH, curPos + advDataLength); - manufactureSpecificDatas[manufactureId] = tmpValue; - } - - // 2. Start scanning. - public startScan() { - // 2.1 Construct a scan filter that matches the expected advertising packet content. - let manufactureId = 4567; - let manufactureData: Uint8Array = new Uint8Array([1, 2, 3, 4]); - let manufactureDataMask: Uint8Array = new Uint8Array([0xFF, 0xFF, 0xFF, 0xFF]); - let scanFilter: ble.ScanFilter = {// Define the filter based on service requirements. - manufactureId: manufactureId, - manufactureData: manufactureData.buffer, - manufactureDataMask: manufactureDataMask.buffer - }; - - // 2.2 Construct scanning parameters. - let scanOptions: ble.ScanOptions = { - interval: 0, - dutyMode: ble.ScanDuty.SCAN_MODE_LOW_POWER, - matchMode: ble.MatchMode.MATCH_MODE_AGGRESSIVE - } - try { - this.onScanResult(); // Subscribe to the scanning result. - ble.startBLEScan([scanFilter], scanOptions); - console.info(TAG, 'startBleScan success'); - } catch (err) { - console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); - } - } - - // 3. Stop scanning. - public stopScan() { - try { - ble.off('BLEDeviceFind', (data: Array) => { // Unsubscribe from the scanning result. - console.info(TAG, 'off success'); - }); - ble.stopBLEScan(); - console.info(TAG, 'stopBleScan success'); - } catch (err) { - console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); + private parseServiceSolicitationUuid(uuidLength: number, curPos: number, advDataLength: number, + advData: Uint8Array, serviceSolicitationUuids: string[]) { + while (advDataLength > 0) { + let tmpData: Uint8Array = advData.slice(curPos, curPos + uuidLength); + serviceSolicitationUuids.push(this.getUuidFromUint8Array(uuidLength, tmpData)); + advDataLength -= uuidLength; + curPos += uuidLength; + } + } + + private getUuidFromUint8Array(uuidLength: number, uuidData: Uint8Array): string { + let uuid = ""; + let temp: string = ""; + for (let i = uuidLength - 1; i > -1; i--) { + temp += uuidData[i].toString(16).padStart(2, "0"); + } + switch (uuidLength) { + case BLUETOOTH_UUID_16_BIT_LENGTH: + uuid = `0000${temp}-0000-1000-8000-00805F9B34FB`; + break; + case BLUETOOTH_UUID_32_BIT_LENGTH: + uuid = `${temp}-0000-1000-8000-00805F9B34FB`; + break; + case BLUETOOTH_UUID_128_BIT_LENGTH: + uuid = `${temp.substring(0, 8)}-${temp.substring(8, 12)}-${temp.substring(12, 16)}-${temp.substring(16, 20)}-${temp.substring(20, 32)}`; + break; + default: + break; + } + return uuid; + } + + private parseServiceData(uuidLength: number, curPos: number, advDataLength: number, + advData: Uint8Array, serviceDatas: Record) { + let tmpUuid: Uint8Array = advData.slice(curPos, curPos + uuidLength); + let tmpValue: Uint8Array = advData.slice(curPos + uuidLength, curPos + advDataLength); + serviceDatas[tmpUuid.toString()] = tmpValue; + } + + private parseManufactureData(curPos: number, advDataLength: number, + advData: Uint8Array, manufactureSpecificDatas: Record) { + let manufactureId: number = (advData[curPos + 1] << 8) + advData[curPos]; + let tmpValue: Uint8Array = advData.slice(curPos + BLUETOOTH_MANUFACTURE_ID_LENGTH, curPos + advDataLength); + manufactureSpecificDatas[manufactureId] = tmpValue; + } + + // 2. Start scanning. + public startScan() { + // 2.1 Construct a scan filter that matches the expected advertising packet content. + let manufactureId = 4567; + let manufactureData: Uint8Array = new Uint8Array([1, 2, 3, 4]); + let manufactureDataMask: Uint8Array = new Uint8Array([0xFF, 0xFF, 0xFF, 0xFF]); + let scanFilter: ble.ScanFilter = {// Define the filter based on service requirements. + manufactureId: manufactureId, + manufactureData: manufactureData.buffer, + manufactureDataMask: manufactureDataMask.buffer + }; + + // 2.2 Construct scanning parameters. + let scanOptions: ble.ScanOptions = { + interval: 0, + dutyMode: ble.ScanDuty.SCAN_MODE_LOW_POWER, + matchMode: ble.MatchMode.MATCH_MODE_AGGRESSIVE + } + try { + this.onScanResult(); // Subscribe to the scanning result. + ble.startBLEScan([scanFilter], scanOptions); + console.info(TAG, 'startBleScan success'); + } catch (err) { + console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); + } + } + + // 3. Stop scanning. + public stopScan() { + try { + ble.off('BLEDeviceFind', (data: Array) => { // Unsubscribe from the scanning result. + console.info(TAG, 'off success'); + }); + ble.stopBLEScan(); + console.info(TAG, 'stopBleScan success'); + } catch (err) { + console.error(TAG, 'errCode: ' + (err as BusinessError).code + ', errMessage: ' + (err as BusinessError).message); + } + } } - } -} -let bleScanManager = new BleScanManager(); -export default bleScanManager as BleScanManager; -``` + let bleScanManager = new BleScanManager(); + export default bleScanManager as BleScanManager; + ``` -For details about the error codes, see [Bluetooth Error Codes](../../reference/apis-connectivity-kit/errorcode-bluetoothManager.md). \ No newline at end of file +8. For details about the error codes, see [Bluetooth Error Codes](../../reference/apis-connectivity-kit/errorcode-bluetoothManager.md). diff --git a/en/application-dev/connectivity/bluetooth/br-development-guide.md b/en/application-dev/connectivity/bluetooth/br-development-guide.md index 3ee82e5ec230c370a0ba2f8c1b3073023e7c7129..6a12c4dac1f0a90af375689738c7afc6545c52d5 100644 --- a/en/application-dev/connectivity/bluetooth/br-development-guide.md +++ b/en/application-dev/connectivity/bluetooth/br-development-guide.md @@ -4,8 +4,9 @@ This topic walks you through on how to implement basic Bluetooth settings, including enabling and disabling Bluetooth and obtaining Bluetooth status. ## When to Use -You can use the APIs provided by the **access** module to enable and disable Bluetooth. +You can use the APIs provided by the **access** module to: +- Enable and disable Bluetooth. ## Available APIs @@ -27,9 +28,10 @@ The following table describes the related APIs. ### Enabling and Disabling Bluetooth 1. Import the **access** module. 2. Check that the SystemCapability.Communication.Bluetooth.Core capability is available. -3. Enable Bluetooth. -4. Disable Bluetooth. -Example: +3. Apply for the **ohos.permission.ACCESS_BLUETOOTH** permission. +4. Enables Bluetooth. +5. Disables Bluetooth. +6. Example: ```ts import { access } from '@kit.ConnectivityKit'; @@ -108,7 +110,6 @@ Example: }) ``` -For details about the error codes, see [Bluetooth Error Codes](../../reference/apis-connectivity-kit/errorcode-bluetoothManager.md). -**Verification** -1. Execute the code for enabling Bluetooth.
If "bluetooth statues: STATE_ON" is logged, Bluetooth is enabled. -2. Execute the code for disabling Bluetooth.
If "bluetooth statues: STATE_OFF" is logged, Bluetooth is disabled. \ No newline at end of file +6. For details about the error codes, see [Bluetooth Error Codes](../../reference/apis-connectivity-kit/errorcode-bluetoothManager.md). +7. Verification: +Execute the code for enabling Bluetooth.
If "bluetooth statues: STATE_ON" is logged, Bluetooth is enabled. Execute the code for disabling Bluetooth.
If "bluetooth statues: STATE_OFF" is logged, Bluetooth is disabled. diff --git a/en/application-dev/connectivity/bluetooth/gatt-development-guide.md b/en/application-dev/connectivity/bluetooth/gatt-development-guide.md index 4d0ff29cc951ced93b6fa18b3d10eed6d5ddb1ce..65d3621e6ce5efbf6ef7b79a2bbe7ca546345bf0 100644 --- a/en/application-dev/connectivity/bluetooth/gatt-development-guide.md +++ b/en/application-dev/connectivity/bluetooth/gatt-development-guide.md @@ -1,9 +1,7 @@ -# GATT Development +# GATT-based BLE Connection and Data Transmission Development ## Introduction -Generic Attribute Profile (GATT) provides profile discovery and description services for BLE protocol. It defines how ATT attributes are organized and exchanged over a BLE connection. - -A GATT server (referred to as server in this topic) is a device that stores attribute data locally and provides data access to a remote GATT client paired via BLE. A GATT client (referred to as client in this topic) is a device that accesses data on the remote GATT server via read, write, notify, or indicate operations. +Generic Attribute Profile (GATT) provides profile discovery and description services for the BLE protocol. It defines how ATT attributes are organized and exchanged over a BLE connection.
A GATT server (referred to as server in this topic) is a device that stores attribute data locally and provides data access to a remote GATT client paired via BLE. A GATT client (referred to as client in this topic) is a device that accesses data on the remote GATT server via read, write, notify, or indicate operations. ## When to Use @@ -60,12 +58,14 @@ The following table describes the related APIs. ### Reading and Writing Data on the Server 1. Import the **ble** module. -2. Create a **gattClient** instance. -3. Connect to the server. -4. Read characteristics and descriptors from the server. -5. Write characteristics and descriptors to the server. -6. Disconnect from the server and destroy the **gattClient** instance. -Example: +2. Enable Bluetooth. +3. Apply for the **ohos.permission.ACCESS_BLUETOOTH** permission. +4. Create a **gattClient** instance. +5. Connect to the server. +6. Read characteristics and descriptors from the server. +7. Write characteristics and descriptors to the server. +8. Disconnect from the server and destroy the **gattClient** instance. +9. Example: ```ts import { ble } from '@kit.ConnectivityKit'; @@ -353,17 +353,19 @@ Example: export default gattClientManager as GattClientManager; ``` -For details about the error codes, see [Bluetooth Error Codes](../../reference/apis-connectivity-kit/errorcode-bluetoothManager.md). +9. For details about the error codes, see [Bluetooth Error Codes](../../reference/apis-connectivity-kit/errorcode-bluetoothManager.md). ### Managing Services on the Server and Notifying the Client 1. Import the **ble** module. -2. Create a **gattServer** object. -3. Add services. -4. Notify the client after a characteristic is written to the server. -5. Remove services. -6. Close the gattServer instance. -Example: +2. Enable Bluetooth. +3. Apply for the **ohos.permission.ACCESS_BLUETOOTH** permission. +4. Create a **gattServer** object. +5. Add services. +6. Notify the client after a characteristic is written to the server. +7. Remove services. +8. Close the gattServer instance. +9. Example: ```ts import { ble } from '@kit.ConnectivityKit'; @@ -638,4 +640,4 @@ Example: export default gattServerManager as GattServerManager; ``` -For details about the error codes, see [Bluetooth Error Codes](../../reference/apis-connectivity-kit/errorcode-bluetoothManager.md). +8. For details about the error codes, see [Bluetooth Error Codes](../../reference/apis-connectivity-kit/errorcode-bluetoothManager.md). diff --git a/en/application-dev/connectivity/bluetooth/spp-development-guide.md b/en/application-dev/connectivity/bluetooth/spp-development-guide.md index 8ef5b5c53d434e20d439f3a8c8e49af24fdb6cb1..f351d3105d2264cc307d6f0f348debeb10a7f3d7 100644 --- a/en/application-dev/connectivity/bluetooth/spp-development-guide.md +++ b/en/application-dev/connectivity/bluetooth/spp-development-guide.md @@ -1,4 +1,4 @@ -# SPP Development +# SPP-based Data Transmission Development ## Introduction Serial Port Profile (SPP) is a Bluetooth protocol used to establish serial communication connections between Bluetooth devices. With SPP, Bluetooth devices can transmit data, such as files and text, just like using a serial port. @@ -31,14 +31,15 @@ The following table describes the related APIs. ### Writing Data to the Client 1. Import the **socket** module. 2. Check that the SystemCapability.Communication.Bluetooth.Core capability is available. -3. Enable Bluetooth on the device. -4. Creates a server socket. If the operation is successful, **serverId** is returned. -5. Create a communication channel between the server socket and the client socket. If the operation is successful, **clientId** is returned. -6. Write data to the client. -7. (Optional) Subscribe to the data written by the client. -8. Close the server socket. -9. Close the client socket. -Example: +3. Apply for the **ohos.permission.ACCESS_BLUETOOTH** permission. +4. Enable Bluetooth on the device. +5. Creates a server socket. If the operation is successful, **serverId** is returned. +6. Create a communication channel between the server socket and the client socket. If the operation is successful, **clientId** is returned. +7. Write data to the client. +8. (Optional) Subscribe to the data written by the client. +9. Close the server socket. +10. Close the client socket. +11. Example: ```ts import { socket } from '@kit.ConnectivityKit'; @@ -112,7 +113,7 @@ Example: console.info('sppCloseClientSocket success'); ``` -For details about the error codes, see [Bluetooth Error Codes](../../reference/apis-connectivity-kit/errorcode-bluetoothManager.md). +11. For details about the error codes, see [Bluetooth Error Codes](../../reference/apis-connectivity-kit/errorcode-bluetoothManager.md). ### Connecting to the Peer Device over a Socket 1. Import the **socket** module. @@ -120,7 +121,7 @@ For details about the error codes, see [Bluetooth Error Codes](../../reference/a 3. Enable Bluetooth on the device. 4. Start Bluetooth scanning to obtain the MAC address of the peer device. 5. Connect to the peer device. -Example: +6. Example: ```ts import { socket } from '@kit.ConnectivityKit'; @@ -143,4 +144,4 @@ Example: }) ``` -For details about the error codes, see [Bluetooth Error Codes](../../reference/apis-connectivity-kit/errorcode-bluetoothManager.md). +7. For details about the error codes, see [Bluetooth Error Codes](../../reference/apis-connectivity-kit/errorcode-bluetoothManager.md). diff --git a/en/application-dev/connectivity/nfc/Readme-EN.md b/en/application-dev/connectivity/nfc/Readme-EN.md index 4be7067f6380d287fc8f3f86181ab765f831bd37..02089c9d307089143c4f94375f87cd004f816c70 100644 --- a/en/application-dev/connectivity/nfc/Readme-EN.md +++ b/en/application-dev/connectivity/nfc/Readme-EN.md @@ -1,4 +1,4 @@ - # NFC +# NFC - [NFC Tag Read/Write Development](nfc-tag-access-guide.md) - [HCE Development](nfc-hce-guide.md) - [SE Access Development](nfc-se-access-guide.md) diff --git a/en/application-dev/connectivity/nfc/nfc-hce-guide.md b/en/application-dev/connectivity/nfc/nfc-hce-guide.md index a20a5e0e66ff70cb6f45da3872488d9396ead22f..7a5ab517a8a098bbfe31ee79f4ce0483866a1b9f 100644 --- a/en/application-dev/connectivity/nfc/nfc-hce-guide.md +++ b/en/application-dev/connectivity/nfc/nfc-hce-guide.md @@ -5,21 +5,12 @@ Near Field Communication (NFC) is a high-frequency radio technology that enables ## When to Use An application emulates a card and communicates with an NFC card reader through the NFC service. The device can communicate with an NFC card reader by using a started application (foreground mode) or without starting an application (background mode). -- HCE foreground mode - - The application started by the user communicates with the NFC card reader. Specifically, the user starts the application, opens the application page, and taps the device on the NFC card reader. In this case, the transaction data is distributed only to the foreground application. - -- HCE background mode - - The user taps the device on an NFC card reader without starting any HCE application. Then, the device selects an HCE application based on the application ID (AID) provided by the NFC card reader, and completes the card swiping transaction. If multiple HCE applications are matched, an application selector will be displayed, listing all the available applications for the user to choose. - -- Constraints - - No matter whether the foreground mode or background mode is used, the NFC service can be implemented only when the device screen is unlocked and illuminated. - - The permission for NFC card emulation must be declared in the **module.json5** file. For details, see the example below. - - The foreground application needs to call **start()** to register AIDs and call **stop()** to release the registered AIDs. For details, see the example below. +- HCE foreground mode
+The application started by the user communicates with the NFC card reader. Specifically, the user starts the application, opens the application page, and taps the device on the NFC card reader. In this case, the transaction data is distributed only to the foreground application. +- HCE background mode
+The user taps the device on an NFC card reader without starting any HCE application. Then, the device selects an HCE application based on the application ID (AID) provided by the NFC card reader, and completes the card swiping transaction. If multiple HCE applications are matched, an application selector will be displayed, listing all the available applications for the user to choose. +- Constraints
+1. No matter whether the foreground mode or background mode is used, the NFC service can be implemented only when the device screen is unlocked and illuminated.
2. The NFC card emulation permission must be declared in the **module.json5** file. For details, see the example below.
3. For foreground applications, the **start** and **stop** functions need to be called to register and deregister the AID. See the following development example for details.
## Available APIs @@ -30,8 +21,8 @@ The following table describes the APIs for implementing HCE. | API | Description | | ---------------------------------- | ------------------------------------------------------------------------------ | | start(elementName: ElementName, aidList: string[]): void | Starts HCE, including enabling this application to run in the foreground preferentially and dynamically registering the AID list. | -| stop(elementName: ElementName): void | Stops HCE, including canceling the subscription of APDU data, exiting this application from the foreground, and releasing the dynamically registered AID list.| -| on(type: 'hceCmd', callback: AsyncCallback\): void | Registers a callback to receive APDUs from the peer card reader.| +| stop(elementName: ElementName): void | Stops HCE, including canceling the subscription of APDU data, exiting this application from the foreground, and releasing the dynamically registered AID list. +| on(type: 'hceCmd', callback: AsyncCallback\): void | Registers a callback to receive APDUs from the peer card reader. | transmit(response: number[]): Promise\ | Transmits APDU data to the peer card reader.| | ## How to Develop @@ -64,7 +55,7 @@ The following table describes the APIs for implementing HCE. "actions": [ "action.system.home", - // Add the nfc card emulation action to filter out for this application. + // Make sure that ohos.nfc.cardemulation.action.HOST_APDU_SERVICE is present in actions. "ohos.nfc.cardemulation.action.HOST_APDU_SERVICE" ] } @@ -73,7 +64,7 @@ The following table describes the APIs for implementing HCE. ], "requestPermissions": [ { - // Add the permission for nfc card emulation. + // Add the permission required for NFC card emulation. "name": "ohos.permission.NFC_CARD_EMULATION", "reason": "$string:app_name", } @@ -96,9 +87,9 @@ const hceCommandCb : AsyncCallback = (error : BusinessError, hceComman hilog.error(0x0000, 'testTag', 'hceCommandCb has invalid hceCommand.'); return; } - // check the command, then transmit the response. + // Check the command and send a response. hilog.info(0x0000, 'testTag', 'hceCommand = %{public}s', JSON.stringify(hceCommand)); - let responseData = [0x90, 0x00]; // change the response depend on different received command. + let responseData = [0x90, 0x00]; // Modify the response based on the received command. hceService.transmit(responseData).then(() => { hilog.info(0x0000, 'testTag', 'hceService transmit Promise success.'); }).catch((err: BusinessError) => { @@ -132,12 +123,12 @@ export default class EntryAbility extends UIAbility { } onForeground() { - // Ability is brought to foreground. + // Switch the application to the foreground. hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground'); if (hceElementName != undefined) { try { // Enable the foreground HCE application to preferentially process NFC card swiping. - let aidList = ["A0000000031010", "A0000000031011"]; // Change the AIDs to match your case. + let aidList = ["A0000000031010," "A0000000031011"]; // Set the AID list correctly. hceService.start(hceElementName, aidList); // Subscribe to the reception of HCE APDU data. @@ -149,7 +140,7 @@ export default class EntryAbility extends UIAbility { } onBackground() { - // Ability is in the background. + // Switch the application to the background. hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground'); // When exiting the NFC tag page of the application, call the tag module API to exit the foreground mode. if (hceElementName != undefined) { @@ -190,7 +181,7 @@ export default class EntryAbility extends UIAbility { "actions": [ "action.system.home", - // Add the nfc card emulation action to filter out for this application. + // Make sure that ohos.nfc.cardemulation.action.HOST_APDU_SERVICE is present in actions. "ohos.nfc.cardemulation.action.HOST_APDU_SERVICE" ] } @@ -198,18 +189,18 @@ export default class EntryAbility extends UIAbility { "metadata": [ { "name": "payment-aid", - "value": "A0000000031010" // change it tobe correct + "value": "A0000000031010" // Set a correct AID. }, { "name": "other-aid", - "value": "A0000000031011" // change it tobe correct + "value": "A0000000031011" // Set a correct AID. } ] } ], "requestPermissions": [ { - // Add the permission for nfc card emulation. + // Add the permission required for NFC card emulation. "name": "ohos.permission.NFC_CARD_EMULATION", "reason": "$string:app_name", } @@ -233,7 +224,7 @@ const hceCommandCb : AsyncCallback = (error : BusinessError, hceComman return; } - // check the command, then transmit the response. + // Check the command and send a response. hilog.info(0x0000, 'testTag', 'hceCommand = %{public}s', JSON.stringify(hceCommand)); let responseData = [0x90, 0x00]; // change the response depend on different received command. hceService.transmit(responseData).then(() => { @@ -270,12 +261,12 @@ export default class EntryAbility extends UIAbility { } onForeground() { - // Ability is brought to foreground. + // Switch the application to the foreground. hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground'); } onDestroy() { - // Ability has back to destroy + // Exit the application. hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy'); // When exiting the NFC tag page of the application, call the tag module API to exit the foreground mode. if (hceElementName != undefined) { diff --git a/en/application-dev/connectivity/nfc/nfc-se-access-guide.md b/en/application-dev/connectivity/nfc/nfc-se-access-guide.md index dbf0878a81ed80e21f506f50bd8b5f37ab62f479..d7ba68e70518230bc13dfc85c3276a1aae9f52da 100644 --- a/en/application-dev/connectivity/nfc/nfc-se-access-guide.md +++ b/en/application-dev/connectivity/nfc/nfc-se-access-guide.md @@ -67,7 +67,7 @@ export default class EntryAbility extends UIAbility { return; }); - // get readers + // Obtain readers. try { seReaders = seService.getReaders(); } catch (error) { @@ -92,7 +92,7 @@ export default class EntryAbility extends UIAbility { } hilog.info(0x0000, 'testTag', 'reader is %{public}s', reader?.getName()); - // get session + // Obtain the session. try { seSession = reader?.openSession() as omapi.Session; } catch (error) { @@ -104,9 +104,10 @@ export default class EntryAbility extends UIAbility { return; } - // get channel + // Obtain the channel. try { - // change the aid value for open logical channel. + // change the aid value for open logical channel + // Change the value to the AID of the application for which the logical channel is opened. seChannel = await seSession.openLogicalChannel(aidArray, p2); } catch (exception) { hilog.error(0x0000, 'testTag', 'openLogicalChannel exception %{public}s', JSON.stringify(exception)); @@ -117,8 +118,8 @@ export default class EntryAbility extends UIAbility { return; } - // transmit data - let cmdData = [0x01, 0x02, 0x03, 0x04]; // please change the raw data to be correct. + // Send data. + let cmdData = [0x01, 0x02, 0x03, 0x04]; // Set command data correctly. try { let response: number[] = await seChannel.transmit(cmdData) hilog.info(0x0000, 'testTag', 'seChannel.transmit() response = %{public}s.', JSON.stringify(response)); @@ -126,7 +127,7 @@ export default class EntryAbility extends UIAbility { hilog.error(0x0000, 'testTag', 'seChannel.transmit() exception = %{public}s.', JSON.stringify(exception)); } - // close channel. must make sure the channel is closed at last. + // Close the channel. After performing the operation, make sure that the channel is truly closed. try { seChannel.close(); } catch (exception) { diff --git a/en/application-dev/connectivity/nfc/nfc-tag-access-guide.md b/en/application-dev/connectivity/nfc/nfc-tag-access-guide.md index e4b587deff2c67c27d0ace2cd2a7213b7d5ca27a..fedf51bd0be53113921e6dde78752b09de4b06dc 100644 --- a/en/application-dev/connectivity/nfc/nfc-tag-access-guide.md +++ b/en/application-dev/connectivity/nfc/nfc-tag-access-guide.md @@ -15,7 +15,7 @@ NFC tags support one or more communications technologies listed as follows: ## When to Use An electronic device touches an NFC tag via the NFC antenna to read and write the NFC tag data. NFC tags can be read and written by a started application (foreground mode) on a device or without starting an application (background mode). - Reading/Writing an NFC tag by a started application
-An application started on a device reads or writes the NFC tag. That is, the user starts the application to read and write the NFC tag. The user starts the application, opens the application page, and taps the device on the NFC tag. In this case, the tag data read can be distributed only to the foreground application. +An application started on a device reads or writes the NFC tag. That is, the user starts the application to read and write the NFC tag. The user starts the application, opens the application page, and taps the device on the NFC tag. In this case, the retrieved tag data can be distributed only to the foreground application. - Reading/Writing an NFC tag without starting an application
The user taps the device on an NFC tag without starting any application. Then, the device selects an application based on the type of the NFC tag technology. If multiple applications are matched, an application selector will be displayed, listing all the available applications for the user to choose. After the user selects an application, the NFC tag read/write page of the application is automatically displayed. - Constraints
@@ -68,7 +68,7 @@ The following table describes the APIs for obtaining objects of the tags that us "actions": [ "action.system.home", - // Add the NFC tag action to match this application. + // Make sure that ohos.nfc.tag.action.TAG_FOUND is present in actions. "ohos.nfc.tag.action.TAG_FOUND" ] } @@ -77,7 +77,7 @@ The following table describes the APIs for obtaining objects of the tags that us ], "requestPermissions": [ { - // Add the permission required for NFC tag operations. + // Add the NFC tag operation permission. "name": "ohos.permission.NFC_TAG", "reason": "$string:app_name", } @@ -110,7 +110,7 @@ async function readerModeCb(error : BusinessError, tagInfo : tag.TagInfo) { } // Read and write the tag data. - // Use ISO-DEP to access this NFC tag. + // Access the NFC tag using IsoDep. let isoDep : tag.IsoDepTag | null = null; for (let i = 0; i < tagInfo.technology.length; i++) { if (tagInfo.technology[i] == tag.ISO_DEP) { @@ -121,14 +121,14 @@ async function readerModeCb(error : BusinessError, tagInfo : tag.TagInfo) { return; } } - // use other technology to access this nfc tag if necessary. + // Access the NFC tag using other technologies. } if (isoDep == undefined) { hilog.error(0x0000, 'testTag', 'readerModeCb getIsoDep is invalid'); return; } - // Connect to this NFC tag using ISO-DEP. + // Connect to the NFC tag using IsoDep. try { isoDep.connect(); } catch (error) { @@ -140,8 +140,8 @@ async function readerModeCb(error : BusinessError, tagInfo : tag.TagInfo) { return; } - // Transmit data to the connected tag. - let cmdData = [0x01, 0x02, 0x03, 0x04]; // please change the raw data to be correct. + // Send an instruction to the connected tag. + let cmdData = [0x01, 0x02, 0x03, 0x04]; // Specify the instruction of the protocol corresponding to the tag type. try { isoDep.transmit(cmdData).then((response : number[]) => { hilog.info(0x0000, 'testTag', 'readerModeCb isoDep.transmit() response = %{public}s.', JSON.stringify(response)); @@ -176,7 +176,7 @@ export default class EntryAbility extends UIAbility { } onForeground() { - // Ability is brought to foreground. + // Switch the application to the foreground. hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground'); if (nfcTagElementName != undefined) { // Register a listener for the NFC tag read event so that the tag can be preferentially dispatched to a foreground application. @@ -191,7 +191,7 @@ export default class EntryAbility extends UIAbility { } onBackground() { - // Ability is back to background. + // Switch the application to the background. hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground'); // When exiting the NFC tag page of the application, call the tag module API to exit the foreground mode. if (foregroundRegister) { @@ -231,7 +231,7 @@ export default class EntryAbility extends UIAbility { "actions": [ "action.system.home", - // Add the NFC tag action to match this application. + // Make sure that ohos.nfc.tag.action.TAG_FOUND is present in actions. "ohos.nfc.tag.action.TAG_FOUND" ], "uris": [ @@ -241,8 +241,8 @@ export default class EntryAbility extends UIAbility { { "type":"tag-tech/IsoDep" } - // Add other technologies if necessary, - // such as: NfcB/NfcF/NfcV/Ndef/MifareClassic/MifareUL/NdefFormatable + // Add other technologies if necessary. + // Example: NfcB/NfcF/NfcV/Ndef/MifareClassic/MifareUL/NdefFormatable ] } ] @@ -250,7 +250,7 @@ export default class EntryAbility extends UIAbility { ], "requestPermissions": [ { - // Add the permission required for NFC tag operations. + // Add NFC tag operation permission. "name": "ohos.permission.NFC_TAG", "reason": "$string:app_name", } @@ -290,7 +290,7 @@ export default class EntryAbility extends UIAbility { } // Read and write the tag data. - // Use ISO-DEP to access this NFC tag. + // Access the NFC tag using IsoDep. let isoDep : tag.IsoDepTag | null = null; for (let i = 0; i < tagInfo.technology.length; i++) { if (tagInfo.technology[i] == tag.ISO_DEP) { @@ -301,14 +301,14 @@ export default class EntryAbility extends UIAbility { return; } } - // use other technology to access this nfc tag if necessary. + // Access the NFC tag using other technologies. } if (isoDep == undefined) { hilog.error(0x0000, 'testTag', 'getIsoDep is invalid'); return; } - // Connect to this NFC tag using ISO-DEP. + // Connect to the NFC tag using IsoDep. try { isoDep.connect(); } catch (error) { @@ -320,8 +320,8 @@ export default class EntryAbility extends UIAbility { return; } - // Transmit data to the connected tag. - let cmdData = [0x01, 0x02, 0x03, 0x04]; // please change the raw data to be correct. + // Send an instruction to the connected tag. + let cmdData = [0x01, 0x02, 0x03, 0x04]; // Specify the instruction of the protocol corresponding to the tag type. try { isoDep.transmit(cmdData).then((response : number[]) => { hilog.info(0x0000, 'testTag', 'isoDep.transmit() response = %{public}s.', JSON.stringify(response)); diff --git a/en/application-dev/connectivity/wlan/Readme-EN.md b/en/application-dev/connectivity/wlan/Readme-EN.md index 7bd988c69ec950012e0d60b40ca0da7cde900c87..2055733a92f0d8e658a85e922e4e4d322b849ca5 100644 --- a/en/application-dev/connectivity/wlan/Readme-EN.md +++ b/en/application-dev/connectivity/wlan/Readme-EN.md @@ -1,3 +1,4 @@ - # WLAN +# WLAN + - [WLAN Service Development Overview](wlan-overview.md) - [P2P Mode Development](p2p-development-guide.md) diff --git a/en/application-dev/database/Readme-EN.md b/en/application-dev/database/Readme-EN.md index d23b60222b581c7a54f937d1ebbc2af3fbf53f41..8af6068f201985545a5d7bfb05dd1a173fcf8988 100644 --- a/en/application-dev/database/Readme-EN.md +++ b/en/application-dev/database/Readme-EN.md @@ -1,36 +1,45 @@ # ArkData (Ark Data Management) - [Introduction to ArkData](data-mgmt-overview.md) -- Unified Data Definition +- Unified Data Definition - [Unified Data Definition Overview](unified-data-definition-overview.md) - [UTDs](uniform-data-type-descriptors.md) - [Uniform Data Structs](uniform-data-structure.md) - [Prebuilt UTDs](uniform-data-type-list.md) -- Application Data Persistence +- Application Data Persistence - [Application Data Persistence Overview](app-data-persistence-overview.md) - [Persisting Preferences Data](data-persistence-by-preferences.md) - [Persisting KV Store Data](data-persistence-by-kv-store.md) - [Persisting RDB Store Data](data-persistence-by-rdb-store.md) -- Distributed Application Data Sync - - [Distributed Application Data Sync Overview](sync-app-data-across-devices-overview.md) + - [Persisting Vector Store Data (ArkTS)](data-persistence-by-vector-store.md) + - [Persisting Vector Store Data (C/C++)](native-vector-store-guidelines.md) + + - [Persisting Graph Store Data (for System Applications Only)](data-persistence-by-graph-store.md) + +- Distributed Application Data Sync + - [Overview of Distributed Application Data Sync](sync-app-data-across-devices-overview.md) - [Cross-Device Sync of KV Stores](data-sync-of-kv-store.md) - [Cross-Device Sync of RDB Stores](data-sync-of-rdb-store.md) - [Cross-Device Sync of Distributed Data Objects](data-sync-of-distributed-data-object.md) -- Data Reliability and Security +- Data Reliability and Security - [Data Reliability and Security Overview](data-reliability-security-overview.md) - [Database Backup and Restore](data-backup-and-restore.md) - [Database Encryption](data-encryption.md) - [Access Control by Device and Data Level](access-control-by-device-and-data-level.md) - [Using an EL5 Database](encrypted_estore_guidelines.md) -- Cross-Application Data Sharing - - [Data Sharing Overview](data-share-overview.md) +- Cross-Application Data Sharing + - [Overview of Cross-Application Data Sharing](data-share-overview.md) - - One-to-Many Data Sharing (for System Applications Only) + - One-to-Many Data Sharing (for System Applications Only) - [Sharing Data via DataShareExtensionAbility](share-data-by-datashareextensionability.md) - [Silent Access via DatamgrService](share-data-by-silent-access.md) - - Many-to-Many Data Sharing - - [Sharing Data Using Unified Data Channels](unified-data-channels.md) + - Many-to-Many Data Sharing + - [Sharing Data via Unified Data Channels](unified-data-channels.md) +- Intelligent Data Construction and Retrieval + - [AIP Overview](aip-data-intelligence-overview.md) + - [Application Data Vectorization](aip-data-intelligence-embedding.md) - [RelationalStore Development (C/C++)](native-relational-store-guidelines.md) - [UDMF Development Guide (C/C++)](native-unified-data-management-framework-guidelines.md) - [Persisting User Preferences (C/C++)](preferences-guidelines.md) + diff --git a/en/application-dev/database/aip-data-intelligence-embedding.md b/en/application-dev/database/aip-data-intelligence-embedding.md new file mode 100644 index 0000000000000000000000000000000000000000..d0ef8909c53fc95a93de5b11ed6b0626342d7586 --- /dev/null +++ b/en/application-dev/database/aip-data-intelligence-embedding.md @@ -0,0 +1,194 @@ +# Application Data Vectorization + +## When to Use + +Application data vectorization leverages embedding models to convert multi-modal data such as unstructured text and images into semantic vectors. In scenarios like intelligent retrieval and Retrieval-Augmented Generation (RAG), embedding models act as a bridge, mapping discrete textual and visual data into a unified vector space for cross-modal data retrieval. Vectorization applies to the following scenarios: + +- Efficient retrieval: enables rapid recall of document fragments that are most relevant to query terms from a vector database by calculating vector similarities. Compared with traditional inverted indexing, efficient retrieval can identify implicit semantic associations, enhancing the contextual relevance of retrieved content. +- RAG: a leading approach to addressing the hallucination problem in large language models (LLMs). A vector knowledge base plays a crucial role in RAG technology. By retrieving precise context from the knowledge base (Top-K relevant vectors corresponding to text) and using it as input prompts for the generation model, RAG significantly reduces the occurrence of hallucinations. + +## Basic Concepts + +### Multi-Modal Embedding Model +Embedding models are used to implement application data vectorization. The system supports multimodal embedding models, which can map different data modalities, such as text and images, into a unified vector space. These models support both single-modal semantic representation (text-to-text and image-to-image retrieval) and cross-modal capabilities (text-to-image and image-to-text retrieval). + +### Text Segmentation +To address length limitations when textual data is vectorized, you can use the APIs provided by the ArkData Intelligence Platform (AIP) to split the input text into smaller sections based on the specified maximum length. This approach ensures efficient and effective data vectorization. + +## Working Principles +Application data vectorization involves converting raw application data into vector formats and storing them in a vector database (store). + +## Constraints +- The model can process up to 512 characters of text per inference, supporting both Chinese and English. +- The model can handle images below 20 MB in size in a single inference. + +## Available APIs + +The following table lists the APIs related to application data vectorization. For more APIs and their usage, see [ArkData Intelligence Platform](../reference/apis-arkdata/js-apis-data-intelligence.md). + +| API| Description| +| -------- | -------- | +| getTextEmbeddingModel(config: ModelConfig): Promise<TextEmbedding> | Obtains a text embedding model.| +| loadModel(): Promise<void> | Loads this embedding model.| +| splitText(text: string, config: SplitConfig): Promise<Array<string>> | Splits text.| +| getEmbedding(text: string): Promise<Array<number>> | Obtains the embedding vector of the given text.| +| getEmbedding(batchTexts: Array<string>): Promise<Array<Array<number>>> | Obtains the embedding vector of a given batch of text.| +| releaseModel(): Promise<void> | Releases this text embedding model.| +| getImageEmbeddingModel(config: ModelConfig): Promise<ImageEmbedding> | Obtains an image embedding model.| +| loadModel(): Promise<void> | Loads this image embedding model.| +| getEmbedding(image: Image): Promise<Array<number>> | Obtains the embedding vector of the given image.| +| releaseModel(): Promise<void> | Releases this image embedding model.| + + +## How to Develop + +1. Import the **intelligence** module. + + ```ts + import { intelligence } from '@kit.ArkData'; + ``` + +2. Obtain a text embedding model. + + ```ts + import { BusinessError } from '@kit.BasicServicesKit'; + + let textConfig:intelligence.ModelConfig = { + version:intelligence.ModelVersion.BASIC_MODEL, + isNpuAvailable:false, + cachePath:"/data" + } + let textEmbedding:intelligence.TextEmbedding; + + intelligence.getTextEmbeddingModel(textConfig) + .then((data:intelligence.TextEmbedding) => { + console.info("Succeeded in getting TextModel"); + textEmbedding = data; + }) + .catch((err:BusinessError) => { + console.error("Failed to get TextModel and code is " + err.code); + }) + ``` + +3. Load this embedding model. + + ```ts + textEmbedding.loadModel() + .then(() => { + console.info("Succeeded in loading Model"); + }) + .catch((err:BusinessError) => { + console.error("Failed to load Model and code is " + err.code); + }) + ``` + +4. Split text. If the data to be vectorized is too long, call **splitText()** to split the data into smaller text blocks and then vectorize them. + + ```ts + let splitConfig:intelligence.SplitConfig = { + size:10, + overlapRatio:0.1 + } + let splitText = 'text'; + + intelligence.splitText(splitText, splitConfig) + .then((data:Array) => { + console.info("Succeeded in splitting Text"); + }) + .catch((err:BusinessError) => { + console.error("Failed to split Text and code is " + err.code); + }) + ``` + +5. Obtain the embedding vector of the given text. The given text can be a single piece of text or a collection of multiple text entries. + + ```ts + let text = 'text'; + textEmbedding.getEmbedding(text) + .then((data:Array) => { + console.info("Succeeded in getting Embedding"); + }) + .catch((err:BusinessError) => { + console.error("Failed to get Embedding and code is " + err.code); + }) + ``` + + ```ts + let batchTexts = ['text1','text2']; + textEmbedding.getEmbedding(batchTexts) + .then((data:Array>) => { + console.info("Succeeded in getting Embedding"); + }) + .catch((err:BusinessError) => { + console.error("Failed to get Embedding and code is " + err.code); + }) + ``` + +6. Release this text embedding model. + + ```ts + textEmbedding.releaseModel() + .then(() => { + console.info("Succeeded in releasing Model"); + }) + .catch((err:BusinessError) => { + console.error("Failed to release Model and code is " + err.code); + }) + ``` + +7. Obtain an image embedding model. + + ```ts + let imageConfig:intelligence.ModelConfig = { + version:intelligence.ModelVersion.BASIC_MODEL, + isNpuAvailable:false, + cachePath:"/data" + } + let imageEmbedding:intelligence.ImageEmbedding; + + intelligence.getImageEmbeddingModel(imageConfig) + .then((data:intelligence.ImageEmbedding) => { + console.info("Succeeded in getting ImageModel"); + imageEmbedding = data; + }) + .catch((err:BusinessError) => { + console.error("Failed to get ImageModel and code is " + err.code); + }) + ``` + +8. Load this image embedding model. + + ```ts + imageEmbedding.loadModel() + .then(() => { + console.info("Succeeded in loading Model"); + }) + .catch((err:BusinessError) => { + console.error("Failed to load Model and code is " + err.code); + }) + ``` + +9. Obtain the embedding vector of the given image. + + ```ts + let image = "file:///data/storage/el2/base/haps/entry/files/xxx.jpg"; + imageEmbedding.getEmbedding(image) + .then((data:Array) => { + console.info("Succeeded in getting Embedding"); + }) + .catch((err:BusinessError) => { + console.error("Failed to get Embedding and code is " + err.code); + }) + ``` + +10. Release this image embedding model. + + ```ts + imageEmbedding.releaseModel() + .then(() => { + console.info("Succeeded in releasing Model"); + }) + .catch((err:BusinessError) => { + console.error("Failed to release Model and code is " + err.code); + }) + ``` diff --git a/en/application-dev/database/aip-data-intelligence-overview.md b/en/application-dev/database/aip-data-intelligence-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..9656a54edc4e3f729c59905e9f083016631d998d --- /dev/null +++ b/en/application-dev/database/aip-data-intelligence-overview.md @@ -0,0 +1,29 @@ +# AIP Overview + +## When to Use + +In the pivotal shift from digital transformation to AI advancement, creating intelligent services is essential for boosting product competitiveness. + +The system provides the ArkData Intelligence Platform (AIP) to offer on-device intelligent data solution with four fundamental features: semantic data processing, structured data storage, knowledge generation, and integrated knowledge retrieval — implementing AI-powered data processing on devices. + +For example, in personal office scenarios, you can vectorize the semantics of user documents, save them in a vector store (database), and uncover similar documents to generate personalized knowledge, which supports intelligent retrieval, recommendation, content generation, and Q&A. + +## Basic Concepts + +To get started, it's helpful to understand the following concepts: + +### Vectorization +The process of vectorization uses embedding models to convert high-dimensional unstructured data (such as text and images) into low-dimensional continuous vector representations. This approach captures the semantic relationships with the data, translating abstract information into a format that can be analyzed and processed by computers. Embedding technology is widely used in fields such as natural language processing (semantic search), image recognition (feature extraction), and recommendation systems (user/item representation). + +## Implementation Mechanism + +By leveraging the AIP, you can implement intelligent data construction and retrieval. All these capabilities operate within the application processes, ensuring that data always remains in the application environment. This ensures data security and safeguards user privacy. + +Intelligent data construction is a process that converts application data into computable vectors for intelligent data storage and retrieval. For details about the development guide, see application data vectorization. + +Intelligent data retrieval involves integrated queries across various data types, such as images and text, or multiple databases. It supports condition filtering and relationship inference. Currently, the intelligent data retrieval capability is not supported. + +## Restrictions + +- Considering the significant computing workload and resources of data vectorization processing, the APIs are only available to 2-in-1 device applications. +- You can use NPUs to accelerate the inference process of embedding models. NPUs are recommended because pure CPU computation falls far behind in latency and energy efficiency. diff --git a/en/application-dev/database/app-data-persistence-overview.md b/en/application-dev/database/app-data-persistence-overview.md index c46d3552d43db21ad61f713c091fc5ffc448e422..289a5d4844957184b98c28490733683548f23713 100644 --- a/en/application-dev/database/app-data-persistence-overview.md +++ b/en/application-dev/database/app-data-persistence-overview.md @@ -14,4 +14,8 @@ You can use proper data storage forms to implement data persistence: - **KV-Store**: used to store data in KV pairs, in which the key uniquely identifies the data. A KV store is a kind of non-relational database. It is ideal for storing service data with few data and service relationships. It has been widely used because it poses fewer database version compatibility issues in distributed scenarios and simplifies conflict handling in data sync. KV databases feature higher cross-device and cross-version compatibility than relational databases. -- **RelationalStore**: used to store data in rows and columns. It is widely used to process relational data in applications. RelationalStore provides a set of APIs for adding, deleting, modifying, and querying data. You can also define and use SQL statements for complex service scenarios. +- **RelationalStore**: used to store data in rows and columns. It is widely used to process relational data in applications. RelationalStore provides a set of APIs for adding, deleting, modifying, and querying data. You can also define and use SQL statements for complex service scenarios. **RelationalStore** also provides the vector store capabilities to calculate the similarity between vector data. It is applicable to recommendation scenarios, similar image retrieval, and natural language processing. + + +- **GraphStore**: Used to store and query graph data in vertexes and edges. It provides APIs for read, write, and transaction operations and can run customized GQL statements to meet the requirements of complex service scenarios. Compared with RDB stores, graph stores can process a large number of complex relational operations more efficiently. Common use cases include social network and relationship analysis, knowledge graph, and real-time recommendation systems. + diff --git a/en/application-dev/database/data-backup-and-restore.md b/en/application-dev/database/data-backup-and-restore.md index bd71b55a47f2069fadb4a6ad5dcf84b88416a39a..89572dd93f2f7f7ab38df50261be145d7427a6df 100644 --- a/en/application-dev/database/data-backup-and-restore.md +++ b/en/application-dev/database/data-backup-and-restore.md @@ -73,7 +73,7 @@ You can use **backup()** to back up a KV store, use **restore()** to restore a K } ``` -2. Use **put()** to insert data to the KV store. +2. Call **put()** to insert data to the KV store. ```ts const KEY_TEST_STRING_ELEMENT = 'key_test_string'; @@ -92,7 +92,7 @@ You can use **backup()** to back up a KV store, use **restore()** to restore a K } ``` -3. Use **backup()** to back up the KV store. +3. Call **backup()** to back up the KV store. ```ts let backupFile = 'BK001'; @@ -110,7 +110,7 @@ You can use **backup()** to back up a KV store, use **restore()** to restore a K } ``` -4. Use **delete()** to delete data to simulate unexpected deletion or data tampering. +4. Call **delete()** to delete data to simulate unexpected deletion or data tampering. ```ts try { @@ -127,7 +127,7 @@ You can use **backup()** to back up a KV store, use **restore()** to restore a K } ``` -5. Use **restore()** to restore the KV store. +5. Call **restore()** to restore the KV store. ```ts try { @@ -144,7 +144,7 @@ You can use **backup()** to back up a KV store, use **restore()** to restore a K } ``` -6. Use **deleteBackup()** to delete the backup file to release storage space. +6. Call **deleteBackup()** to delete the backup file to release storage space. ```ts let files = [backupFile]; @@ -162,13 +162,13 @@ You can use **backup()** to back up a KV store, use **restore()** to restore a K ## Backing Up an RDB Store -A database backup can be used to quickly restore a corrupted RDB store. +A database backup can be used to quickly restore an RDB store in abnormal state. Two backup modes are available: manual backup and automatic backup. Automatic backup is available only for system applications. ### Manual Backup -Use [backup()](../reference/apis-arkdata/js-apis-data-relationalStore.md#backup) to manually back up an RDB store.
Example: +Call [backup()](../reference/apis-arkdata/js-apis-data-relationalStore.md#backup) to manually back up an RDB store.
Example: ```ts import { relationalStore } from '@kit.ArkData'; @@ -190,17 +190,19 @@ Use [backup()](../reference/apis-arkdata/js-apis-data-relationalStore.md#backup) console.error(`Failed to get RdbStore. Code:${err.code},message:${err.message}`); return; } - store.executeSql('CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)', (err) => { - }) console.info('Succeeded in getting RdbStore.'); - - // Backup.db indicates the name of the database backup file. By default, it is in the same directory as the RdbStore file. You can also specify the directory in the customDir + backup.db format. + store.executeSql('CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)', (err) => { + /** + * Backup.db specifies the database backup file. By default, it is in the same directory as the RDB store. + * You can also specify an absolute path, for example, /data/storage/el2/database/Backup.db. The file path must exist and will not be automatically created. + */ (store as relationalStore.RdbStore).backup("Backup.db", (err: BusinessError) => { if (err) { console.error(`Failed to backup RdbStore. Code:${err.code}, message:${err.message}`); return; } console.info(`Succeeded in backing up RdbStore.`); + }) }) }) ``` @@ -220,7 +222,7 @@ To implement hot backup of an RDB store, set **haMode** in [StoreConfig](../refe allowRebuild: true } - // Use getRdbStore() to create an RDB store instance. + // Call getRdbStore() to create an RDB store instance. relationalStore.getRdbStore(context, AUTO_BACKUP_CONFIG, (err, store) => { if (err) { console.error(`Failed to get RdbStore. Code:${err.code}, message:${err.message}`); @@ -234,11 +236,11 @@ To implement hot backup of an RDB store, set **haMode** in [StoreConfig](../refe ## Rebuilding an RDB Store -If error code 14800011 is reported during the creation or use of an RDB store, the database is corrupted. If this occurs, you can rebuild the RDB store and restore data from a backup. +If error 14800011 is displayed when an RDB store is created or used, an exception occurs in the database. You can delete the database and restore data. -To enable automatic rebuild of an RDB store, set **allowRebuild** in [StoreConfig](../reference/apis-arkdata/js-apis-data-relationalStore.md#storeconfig) to **true**. The newly rebuilt RDB store is empty. You need to create tables and restore data from the database backup. For details about how to back up RDB store data, see [Backing Up an RDB Store](#backing-up-an-rdb-store). For details about how to restore RDB store data, see [Restoring RDB Store Data](#restoring-rdb-store-data). +You can set **allowRebuild** in [StoreConfig](../reference/apis-arkdata/js-apis-data-relationalStore.md#storeconfig) to **true**, which allows the database to be automatically deleted when an exception occurs. The newly rebuilt RDB store is empty. You need to create tables and restore data from the database backup. For details about how to back up RDB store data, see [Backing Up an RDB Store](#backing-up-an-rdb-store). For details about how to restore RDB store data, see [Restoring RDB Store Data](#restoring-rdb-store-data). -If **allowRebuild** in **StoreConfig** is set to **true** before the database is corrupted, the database will be automatically rebuilt when corrupted. +If **allowRebuild** in **StoreConfig** is set to **true** before the database is abnormal, the database will be automatically deleted when an exception occurs. If **allowRebuild** in **StoreConfig** is not set or is set to **false**, set **allowRebuild** to **true** and open the rebuilt RDB store.
Example: @@ -269,7 +271,7 @@ If **allowRebuild** in **StoreConfig** is not set or is set to **false**, set ** ## Restoring RDB Store Data -If an RDB store is corrupted, you can restore it by using the database backup. +If an RDB store is abnormal, you can restore it by using the database backup. You can restore data from either the manual backup data or automatic backup data. The latter is available only for system applications. @@ -279,7 +281,7 @@ You can use **backup()** to [perform manual backup](#manual-backup) and use **re The following example contains only the code snippet for the restore process. The complete code must also contain the code for backing up data and rebuilding an RDB store. -1. Throw an exception that indicates database corruption. +1. Throws an error code to indicate a database exception. ```ts let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); @@ -332,12 +334,15 @@ The following example contains only the code snippet for the restore process. Th ```ts try { let context = getContext(); - // Backup.db indicates the name of the database backup file. By default, it is in the same directory as the RdbStore file. You can also specify the directory in the customDir + backup.db format. - let backup = context.databaseDir + '/backup/test_backup.db'; - if(!fileIo.access(backup)) { + /** + * Backup.db specifies the database backup file. By default, it is in the same directory as the current database. + * If an absolute path is specified for the database backup file, for example, /data/storage/el2/database/Backup.db, pass in the absolute path. + */ + let backup = context.databaseDir + '/entry/rdb/Backup.db'; + if (!fileIo.access(backup)) { console.info("no backup file"); try { - (store as relationalStore.RdbStore).close; + (store as relationalStore.RdbStore).close(); store = undefined; } catch (e) { if (e.code != 14800014) { @@ -354,7 +359,7 @@ The following example contains only the code snippet for the restore process. Th return } // Call restore() to restore data. - (store as relationalStore.RdbStore).restore(backup); + (store as relationalStore.RdbStore).restore("Backup.db"); } catch (e) { console.error(`Code:${e.code}, message:${e.message}`); } @@ -364,7 +369,7 @@ The following example contains only the code snippet for the restore process. Th ### Restoring from Automatic Backup Data (for System Applications Only) -Use [restore()](../reference/apis-arkdata/js-apis-data-relationalStore-sys.md#restore12) to restore data from the [automatic backup data](#automatic-backup-for-system-applications-only). Only system applications support this operation. +Call [restore()](../reference/apis-arkdata/js-apis-data-relationalStore-sys.md#restore12) to restore data from the [automatic backup data](#automatic-backup-for-system-applications-only). Only system applications support this operation. The following example contains only the code snippet for the restore process. The complete code must also contain the code for backing up data and rebuilding an RDB store. diff --git a/en/application-dev/database/data-mgmt-overview.md b/en/application-dev/database/data-mgmt-overview.md index da68e74b82d3eca4e27d821d46e5eadc0aa412d6..19ecda86af74974164da8bc3aa3f9802fc1212f2 100644 --- a/en/application-dev/database/data-mgmt-overview.md +++ b/en/application-dev/database/data-mgmt-overview.md @@ -4,9 +4,9 @@ ## Function ArkData provides data storage, management, and sync capabilities. For example, you can store the Contacts application data in database for secure management and shared access, and synchronize the contacts information with a smart watch. -- Unified data definition: OpenHarmony provides unified data definitions, including the data types and structs, for different applications and devices. +- Unified data definition: provides unified data definitions, including the data types and structs, for different applications and devices. -- Data storage: provides capabilities for persisting user preference data, key-value (KV) store data, and relational database (RDB) store data. +- Data storage: provides data persistence capabilities, including preferences, key-value (KV) stores, relational database (RDB stores), and graph stores (available only to system applications). - Data management: provides efficient data management capabilities, including permission management, data backup and restore, and dataShare framework. @@ -19,7 +19,7 @@ The database stores created by an application are saved to the application sandb The data management module includes preferences, KV data management (KV-Store), relational data management (RelatoinalStore), distributed data object (DataObject), cross-application data management (DataShare), and unified data management framework (UDMF). The interface layer provides standard JavaScript APIs for application development. The Frameworks & System service layer implements storage and sync of component data, and provides dependencies for SQLite and other subsystems. -**Figure 1** Data management architecture + **Figure 1** Data management architecture ![dataManagement](figures/dataManagement.jpg) @@ -28,12 +28,12 @@ The data management module includes preferences, KV data management (KV-Store), - **KV-Store**: implements read, write, encryption, and manual backup of data in KV stores and notification subscription. When an application needs to use the distributed capabilities of a KV store, KV-Store sends a sync request to DatamgrService, which implements data sync across devices. -- **RelationalStore**: implements addition, deletion, modification, query, encryption, manually backup of data in RDB stores, and notification subscription. When an application needs to use the distributed capabilities of an RDB store, RelationalStore sends a sync request to DatamgrService, which implements data sync across devices. +- **RelationalStore**: provides the capabilities for managing an RDB store, including create, read, update, delete (CRUD) operations, encryption, manual backup, and subscription notifications. It also provides the capabilities of storing and managing data in a vector store, searching for vector data, and calculating vector data similarity. When an application needs to use the distributed capabilities of an RDB store, RelationalStore sends a sync request to DatamgrService, which implements data sync across devices. - **DataObject**: independently provides distributed capabilities for data objects. **DatamgrService** implements temporary storage of the object data, which is still required after the application (either the application of your device or cross-device application) is restarted. - **DataShare**: provides the data provider-consumer mode to implement addition, deletion, modification, and query of cross-application data on a device, and notification subscription. **DataShare** is not bound to any database and can interact with RDB and KV stores. You can also encapsulate your own databases for C/C++ applications.
In addition to the provider-consumer mode, **DataShare** provides silent access, which allows direct access to the provider's data via the DatamgrService proxy instead of starting the provider. Currently, only the RDB stores support silent access. -- **UDMF**: defines the language and data standards for cross-application and cross-device data interaction, improving data interaction efficiency. The UDMF provides secure and standard data transmission channels and supports different levels of data access permissions and lifecycle management policies. It helps implement efficient data sharing across applications and devices. +- UDMF: defines the data standards for cross-application and cross-device data interaction, improving data interaction efficiency. The UDMF provides secure and standard data transmission channels and supports different levels of data access permissions and lifecycle management policies. It helps implement efficient data sharing across applications and devices. - **DatamgrService**: implements sync and cross-application sharing for other components, including cross-device sync of **RelationalStore** and **KV-Store**, silent access to provider data of **DataShare**, and temporary storage of **DataObject** data. diff --git a/en/application-dev/database/data-persistence-by-graph-store.md b/en/application-dev/database/data-persistence-by-graph-store.md new file mode 100644 index 0000000000000000000000000000000000000000..a4d4a6cd3330083098f9c1211f52d75bc70e2d8a --- /dev/null +++ b/en/application-dev/database/data-persistence-by-graph-store.md @@ -0,0 +1,460 @@ +# Persisting Graph Store Data (for System Applications Only) + + +## When to Use + +A graph store is a database management system dedicated to processing complex relational data. It stores and queries data through the structure of nodes (vertexes) and relationships (edges), enabling efficient processing of large-scale complex relational operations. A graph store stands out with its ability to directly traverse relationships through stored edges, which is more efficient than the RDB store that relies on multi-table joins. Common use cases include social network and relationship analysis, knowledge graph, and real-time recommendation systems. Currently, all the APIs for graph stores are available only to system applications. + + +## Basic Concepts + +- Graph: a data struct consisting of nodes (vertexes) and relationships (edges), which represent entities and their relationships. + +- Schema: outlines the structural definition of data, similar to the table structure design in an RDB store. It defines how nodes, relationships, and properties are organized in a graph store and constraints to ensure data consistency and query efficiency. + +- Node (vertex): a fundamental unit in a graph store, representing an entity or object. + +- Relationship (edge): connects nodes and defines how nodes are related. + +- Path: a sequence of connected vertexes and edges from the starting point to the end point. + +- Label: used to classify or group nodes or relationships in a graph store, for example, **Person** and **Friend** in the following graph creation statements. + +- Property: a key-value (KV) pair attached to a node or relationship to provide additional information. Examples include **name: 'name_1'** and **age: 11** in the following vertex insertion statement. + +- Vertex table: a table used to store vertex information in a graph store. It provides a structured view of all the nodes in the grph. The table name is the vertex label (for example, **Person** in the graph creation statement below). The table includes the vertex IDs and properties. + +- Edge table: a table used to store edge information. It visualizes and stores connections between nodes. The table name is the label of the edge (for example, **Friend** in the graph creation statement below). The table includes the edge IDs, start and end point IDs, and properties. + +- Variable: an identifier used in a Graph Query language (GQL) statement to temporarily store and reference graph data (a node, edge, or path) in queries. There are three types of variables: + - Vertex variable: indicates a vertex in a graph. A variable name is used to reference the property or and label of a node (for example, **person** in the GQL statement for querying a vertex below). + - Edge variable: indicates an edge in a graph. A variable name is used to reference the property or and label of an edge (for example, **relation** in the GQL statement for querying an edge below). + - Path variable: indicates a path in a graph, that is, a sequence of connected vertexes and edges, which is usually generated by a path traversal operation (for example, **path** in the GQL statement for querying a path below). +```ts +const CREATE_GRAPH = "CREATE GRAPH test { (person:Person {name STRING, age INT}),(person)-[:Friend {year INT}]->(person) };" + +const INSERT_VERTEX = "INSERT (:Person {name: 'name_1', age: 11});" + +const QUERY_VERTEX = "MATCH (person:Person) RETURN person;" + +const QUERY_EDGE = "MATCH ()-[relation:Friend]->() RETURN relation;" + +const QUERY_PATH = "MATCH path=(a:Person {name: 'name_1'})-[]->{2, 2}(b:Person {name: 'name_3'}) RETURN path;" +``` + + +## Working Principles + +The **graphStore** module provides APIs for applications. The underlying uses its own component as the persistent storage engine to support features such as transactions, indexes, and encryption. + + +## Constraints + +### Supported Data Types and Specifications + +ArkTS supports number, string, and boolean. The following table lists the specifications and restrictions of each data type. + +| Data Type| Specifications| +| - | - | +| NULL | **nullptr**, which indicates an item without a value. The data type cannot be set to **NULL** during graph creation.| +| number | 1. INTEGER, with the same value range as int64_t. NUMERIC, DATE, DATETIME, and INT are mapped to int64_t.
2. DOUBLE, with the same value range as double. REAL and FLOAT are mapped to double.| +| string | 1. The maximum length is 64 x 1024 bytes, including the terminator '\0'.
2. CHARACTER(20), VARXHAR(255), VARYING CHARACTER(255), NCHAR(55), NATIVE CHARACTER(70), and NVARCHAR (100) are mapped to STRING, and the numbers have no practical significance.
3. A string literal must be enclosed in matching single quotes. Double quotes are not allowed. Single quotes are not allowed inside a string.| +| boolean | The value can be **true** or **false**. BOOL and BOOLEAN are mapped to int64_t.| + +### Property Graph DDL Specifications + +Data Definition Language (DDL) is used to define the schema of a graph. Common DDL statement keywords include **CREATE**. The following table lists the DDL specifications and constraints. + +> **NOTE** +> +> The current implementation is a subset of the GQL standard syntax. Except the content in "Column constraints", other specifications and constraints are not specified in the GQL standards. + +| Category| Specifications| +| - | - | +| Property graph creation| 1. A database instance can be used to create only one property graph.
2. A vertex table and an edge table cannot be defined in the same clause, for example, **(person:Person {name STRING, age INT})-[:Friend {year INT}]->(person)**.
3. When creating a property graph, you must specify the direction in the edge table. Currently, only the left-to-right direction is allowed, that is, '-[',']->'.
4. The property graph name is case-insensitive and cannot exceed 128 bytes.
5. Variable names are case sensitive. Variable names must be specified for a vertex table. The variable name cannot start with **anon_** or exceed 128 bytes. Variable names should not be specified for edge tables. Variable names corresponding to different vertex tables must be unique.
6. No space is allowed in **-[**, **]->**, **]-**, and **<-[**. For example, **- [** is not allowed.
7. When creating a property graph, you must define a vertex table and then an edge table. At least one vertex table must be defined. The edge table does not need to be defined.
8. The vertex label and edge label cannot have the same name.
9. The GQL system table uses variable-length fields to hold graph creation statements. Therefore, the length of a graph creation statement must be less than 64 x 1024 bytes.| +| Total number of vertex or edge tables| 1. The name of the vertex or edge table created by the user cannot be the same as the system table name (starting with table prefix **GM_**).
2. System tables cannot be modified.
3. Currently, system tables cannot be queried.
4. For a single process in non-sharing mode, a database instance allows a maximum of 2000 vertex tables and 10,000 edge tables.
5. Due to the 64 x 1024 bytes limit of variable-length fields, the actual maximum number of vertex or edge tables that can be created may be less than the upper limit. For example, if the graph creation statements for 10,000 edge tables exceed 64 x 1024 bytes, the creation of the property graph will fail.| +| Number of vertex or edge table properties| 1. A vertex or edge table can contain a maximum of 1023 properties (excluding the default **identity** properties added in the database).
2. The property name cannot be **rowid** or **identity**. The database adds the **identity** property to each vertex and edge label by default.
3. The property name is case-insensitive and cannot exceed 128 bytes.
4. The **identity** property cannot have its value specified during insertion, cannot be updated, or queried using the property name **identity**. It can only be retrieved by using **element_id (v)**.| +| Table name length| The table name is case-insensitive and cannot exceed 128 bytes. For example, **table** and **TABLE** refer to the same table.| +| Property name length| The property name is case-insensitive and cannot exceed 128 bytes.| +| Length of the variable-length field type| The property value of the string type cannot exceed 64 x 1024 bytes.| +| Default value| 1. Only constant expressions can be used to set default values, such as **100** and **China**.
2. If the default value is a time keyword (**CURRENT_DATE**, **CURRENT_TIMESTAMP**, or **CURRENT_TIME**), the corresponding data type should be string rather than int64_t.| +| Column constraints| If **NOT NULL** is set for a property, the property value cannot be **NULL**.| + +### Property Graph DML/DQL Specifications + +Data Manipulation Language (DML) is used to add, delete, and modify data. Common DML statement keywords include **INSERT**, **SET**, and **DETACH DELETE**.
Data Query Language (DQL) is used to query data. Common DQL statement keywords include **MATCH** and **WHERE**. + +#### Keyword Specifications and Constraints + +| Keyword| Specifications| Difference with the GQL Standard| +| - | - | - | +| MATCH | 1. Unlimited variable-length hops ( 0 ≤ next N hops ≤ 3) are not supported.
2. The variable name is case-sensitive and cannot start with **anon_**.
3. Variable-length edges and fixed-length edges cannot appear together. An incorrect example is **MATCH p = (a: A)-[e1]->(b)-[e2]->{1, 2}(c)**, where **e1** is a fixed-length edge and **e2** is a variable-length edge.
4. The number of paths cannot exceed 2 in the **MATCH** clause of the **INSERT** statement, and cannot exceed 1 in other statements.
5. The next variable-length hops (N hops) can appear only once. The table name, property filter list (for example, **{id: 1}**), and **WHERE** clause cannot be specified for the edges of variable-length hops.
6. The same variable name cannot correspond to multiple paths or edges. However, the same variable name can correspond to multiple vertex tables. If a vertex table is specified, the same label name must be specified.
7. No space is allowed in **-[**, **]->**, **]-**, and **<-[**. For example, **- [** is not allowed.
8. A GQL statement cannot contain two or more **MATCH** clauses.
9. Empty {} is not allowed in a matching pattern. For example, **MATCH (n: Person {}) RETURN n** will result in a syntax error.| The GQL standard does not clearly define the constraints except for No 9.| +| WHERE | 1. Variable-length variables and path variables cannot be used after **WHERE**. Property names must be specified for vertex variables and edge variables.
2. If **WHERE** is followed by a property column (for example, **WHERE id**), it will be converted into a bool value and then evaluated. **id=0** converts to **false**; otherwise, it converts to **true**.
3. The **WHERE** clause cannot be followed by graph matching forms like **()-[]->()**.| The GQL standard does not include the constraints except for No. 3.| +| INSERT | 1. The **INSERT** statement must be specified with the label (table) name, to which the vertex and edge are to be inserted.
2. **INSERT** cannot be followed by **RETURN**.
3. A vertex and an edge cannot be inserted together.
4. The combination of **MATCH+WHERE+INSERT** is not supported.
5. Empty {} is not allowed in a matching pattern. For example, **INSERT (: Person {})** will result in a syntax error.| The GQL standard does not include the constraints except for No. 5.| +| SET | 1. Updating the label (table) name of a vertex or edge is not supported. A vertex cannot have multiple labels.
2. **SET** cannot be followed by **RETURN**.
3. Updating without setting any property value (for example, **SET p = {}**) is not supported. At least one property must be set.
4. The **SET** clause cannot be followed by graph matching forms like **()-[]->()**.| The GQL standard does not include the constraints except for No. 4.| +| DETACH DELETE | 1. When a vertex is deleted from a graph, all edges connected to it will also be deleted. When an edge is deleted, only the edge itself is removed.
2. **DETACH DELETE** cannot be followed by **RETURN**.
3. Variable-length variables and path variables cannot be deleted. The **DELETE** clause cannot be followed by graph matching forms like **()-[]->()**.
4. **DELETE** without keywords (synonyms: **NODETACH DELETE**) is not supported.| The GQL standard does not include the constraints except for No. 1 and No. 3.| +| RETURN | 1. Returning variable-length edge variables is not supported. For example, in **MATCH p=(a: Person)-[e]->{0, 2}(d) RETURN e;**, only variables **p**, **a**, and **b** can be returned, not the variable-length edge variable **e**.
2. **RETURN \*** is not supported.
3. The **RETURN** clause cannot be followed by graph matching forms like **()-[]->()**.
4. Each column in the returned result (variables, properties, and expressions) is limited to 64 x 1024 bytes, including the null terminator **\0**.
5. If vertex, edge, or path variables are returned, the results (JSON strings) will not include columns with null values.
6. For aggregate queries without explicitly specified **GROUP KEY**, returning **variable.property** fields is not allowed. Duplicate columns are permitted, including duplicate field columns, aggregate function extended columns, and **COUNT (\*)**.
7. For aggregate queries with explicitly specified **GROUP KEY**, the **variable.property** fields in **RETURN** must match **GROUP KEY**. It is not allowed to return partial **GROUP KEY** fields, non-existent **variable.property** fields, or duplicate columns (including duplicate field columns, aggregate function extended columns, and **COUNT (\*)**).
8. For aggregate queries with explicitly specified **GROUP KEY**, the columns returned are arranged as: **GROUP KEY** fields followed by extended columns of the aggregate function.
9. In aggregate queries, expressions and basic functions cannot be returned in **RETURN**.
10. If a GQL statement includes an aggregate function, only the property column or aggregate function column can be returned. Returning vertex, edge, or path variables is not supported.
11. Column aliases can be used in **ORDER BY**, but not in **GROUP BY**.
12. Duplicate column aliases are not allowed.
13. Column aliases are case-insensitive.| The GQL standard does not include the constraints except for No. 3.| +| LIMIT | Using negative numbers after **LIMIT** is not supported.| None| +| OFFSET | Using negative numbers after **OFFSET** is not supported.| **SKIP** cannot be used as a synonym for **OFFSET**.| +| ORDER BY | 1. Numeric references to projection columns in the **RETURN** clause for sorting are not supported.
2. Sorting entire variables is not supported.
3. Aggregate functions cannot be used after **ORDER BY**.
4. The following keywords are added:
Reserved keywords **ORDER**, **BY**, **ASC**, **ASCENDING**, **DESC**, **DESCENDING** and **NULLS**, and non-reserved keywords **FIRST** and **LAST**.
5. When performing aggregate queries, **ORDER BY** must be used with **GROUP BY**.
6. When **ORDER BY** is used with **GROUP BY**, the property column used in the sorting key must exist in the projection result.
7. The default sorting order is ascending order.
8. If the priority for **NULL** values is not specified, the **NULL** values have the lowest priority by default.| The GQL standard does not clearly define constraint 1 and not include constraints 2 and 3.| +| GROUP BY | 1. The maximum number of group keys is 32.
2. **GROUP KEY** does not support grouping of variables without labels. That is, the variables in the **MATCH** clause that are used as keys in **GROUP BY** must have labels.
3. **GROUP KEY** can only be in the format **variable.property**, for example, **a.prop**. It cannot be used to group vertex or edge labels, vertex or edge variables, paths, variable-length edges, and their fields.
4. Duplicate **Group Key** values are not allowed, including duplicate field columns and duplicate extension focus columns.| The constraints are a subset of the GQL standard.| + +#### Operation and Function Specifications + +| Operation/Function| Specifications| Difference with the GQL Standard| +| - | - | - | +| Arithmetic operations| 1. Addition (+), subtraction (-), multiplication (*), division(/), and modulus (%) are supported.
2. Operations between fixed-length types are supported. Arithmetic operations involving variable-length types or between fixed-length and variable-length types are not supported.
3. When high-precision data is assigned to low-precision fields, precision loss will occur.| The GQL standard does not include constraint 2.| +| Comparison operations| 1. Operations equal to (=), not equal to (!=), greater than (>), greater than or equal to (>=), less than (<), less than and equal to (<=), and exclusive inequality (<>) are supported.
2. Consecutive operations are not supported. For example, **0<=F1<=10** is not supported. It must be rewritten as **0<=F1 AND F1<=10**. The operation **0<=F1<=10** is equivalent to **(0<=F1)<=10**.
3. Operations between fixed-length types or variable-length types are supported. Operations between fixed-length and variable-length types are not supported.
4. Floating-point precision error is +/-0.000000000000001.
5. Comparisons like **(a, b) < (1, 2)** are not supported.| The GQL standard does not include the constraints except for No.1.| +| Logical operation| 1. Supported operations include **AND**, **OR**, **NOT**, **IS NULL**, **IS NOT NULL**, **IN**, **NOT IN**, **LIKE**, **NOT LIKE** and **\|\|** (string concatenation).
2. For operators **AND**, **OR**, and **NOT**, their operands are forcibly converted to bool type. For example, in **WHERE 0.00001 AND '0.1'**, **0.00001** is a floating-point number. Given a precision error of +/-0.000000000000001, **0.00001** is not equal to **0** and is converted to **true**. **'0.1'** is a string that is first converted to a double type (**0.1**), which is also not equal to **0**. Therefore, it is converted to **true**.
3. For operators **LIKE** and **NOT LIKE**, their operands are forcibly converted to string type. For example, in **WHERE 0.5 LIKE 0.5**, **0.5** is forcibly converted to string **'0.5'**. This is equivalent to **WHERE '0.5' LIKE '0.5'**, which evaluates to **true**.
4. Currently, **IN** and **NOT IN** do not support right-hand subqueries and will trigger error code 31300009. | The GQL standard does not include the constraints except for No.1.| +| Time functions| 1. Only **DATE()**, **LOCAL_TIME()**, and **LOCAL_DATETIME()** are supported.
2. The input parameters support the following time-value formats:
YYYY-MM-DD
YYYY-MM-DD HH:MM
YYYY-MM-DD HH:MM:SS
YYYY-MM-DDTHH:MM
YYYY-MM-DDTHH:MM:SS
HH:MM
HH:MM:SS
3. Function nesting is not supported.
4. The input parameters must be string literals.| Date parsed from records, for example, **date({year: 1984, month: 11, day: 27})** is not supported.| +| Rounding functions| 1. **FLOOR()** and **CEIL()**/**CEILING()** are supported.
2. The input parameters must be numeric.
3. Function nesting is not supported.
4. Scientific notation cannot be used as a function parameter.| The GQL standard does not include constraint 4.| +| String functions| 1. **CHAR_LENGTH()**/**CHARACTER_LENGTH()**, **LOWER()**, **UPPER()**, **SUBSTR()**/**SUBSTRING()** and **SUBSET_OF()** are supported.
2. Except **SUBSTR()** and **SUBSTRING()**, the parameters of other functions must be strings. For **SUBSTR()**/**SUBSTRING()**, the first parameter must be a string, and the second and third parameters must be numeric.
3. When the string concatenation operator **\|\|** is used, numeric types can be concatenated.
4. The parameters of **SUBSTR()**/**SUBSTRING()** and **SUBSET_OF()** can be nested. Other functions do not support function nesting.
5. Scientific notation cannot be used as a function parameter.
6. The number of parameters for **SUBSTR()**/**SUBSTRING()** must be 3. The first parameter is the original string. The second parameter specifies the start position for the substring (**1** for the first character from the left and **-1** for the first character from the right). The third parameter indicates the length of the substring. If the second and third parameters are floating-point numbers, the values will be rounded down.
7. For **SUBSET_OF()**, the first parameter is the original string, the second parameter is the query string, and the third parameter is the delimiter. The return value is a boolean (**1** or **0**). The length of the delimiter string must be 1. The first and last characters of the first two parameters cannot contain extra delimiters, and consecutive delimiters are not allowed. | The GQL standard does not include constraint 4.| +| Aggregate functions| 1. Only **SUM**, **MAX**, **MIN**, **AVG**, and **COUNT** are supported. **FIRST** and **LAST** are not supported.
2. Only single, valid **variable.property** fields are allowed in aggregate functions. Null values, multiple fields, non-existent fields, expressions, and variables are not allowed. Properties of unlabelled variables are not supported.
3. Expression calculations (intra/inter) and nesting of aggregate functions are not supported.
4. The field types used in aggregate function calculations must be one of the following: INTEGER, BOOLEAN, DOUBLE, and STRING, consistent with the data types supported by GQL.
5. If a single query in GQL scenarios exceeds 100 MB, temporary files will not be used and error code 31300004 will be triggered.| The constraints are a subset of the GQL standard.| +| Type conversion functions| 1. Function nesting is not supported.
2. Scientific notation cannot be used as a function parameter.
3. CAST AS INT
  i. Parameters of the STRING, INTEGER, BOOLEAN, or DOUBLE type are supported.
  ii. If the input parameter is **true**, **1** is returned. If the input parameter is **false**, **0** is returned.
  iii. Strings that cannot be converted to INT will result in an error.
  iv. If the input parameter is a floating-point number, the value is truncated to return an integer.
4. CAST AS BOOL
  i. Parameters of the INTEGER, BOOLEAN, or DOUBLE type are supported.
  ii. **CAST('true' AS BOOL)** is not supported.
  ii. Internally, BOOLEAN is represented as INT: **0** represents **false**, and **1** represents **true**. Converting any other INTEGER to BOOLEAN will return its value unchanged.
5. CAST AS DOUBLE
  i. Parameters of the STRING, INTEGER, BOOLEAN, or DOUBLE type are supported.
  ii. Strings that cannot be converted to DOUBLE will result in an error.
6. CAST AS STRING
  i. Parameters of the STRING, INTEGER, BOOLEAN, or DOUBLE type are supported.
  ii. The return value of **CAST(true AS STRING)** is **1**.| The GQL standard does not support conversions between BOOL and INT or DOUBLE.| + +### Index Specifications + +Indexes are essential for optimizing query performance, primarily accelerating property lookups for nodes and edges. The following table lists the specifications and constraints. + +> **NOTE** +> +> The GQL standard does not contain index-related syntax. + +| Category| Specifications| +| - | - | +| Index name length| The index name is case-insensitive and cannot exceed 128 bytes or be the same as a label name (also case-insensitive).| +| Index size| In a single index, the total size of all index columns cannot exceed 1024 bytes.| +| Length of the variable-length field index| If a variable-length field is used as a key, its size must be less than 1024 bytes.| +| Index usage constraints| Indexes must follow the continuous leftmost match principle; otherwise, the indexing functionality will not be effective and will result in a full table scan.
1. **BTree** does not support range queries on multiple fields with a composite index, for example, **{02. **BTree** does not support non-continuous field queries with a composite index. For example, given a composite index on **F1**, **F2**, **F3**, and **F4**, a condition like **{F1, F3}** violates the continuous prefix rule.| +| Composite index| A composite index can contain a maximum of 32 columns.| +| Index name uniqueness| Index names can be identical across different labels. For example, **t1.id** and **t2.id** can both use the index name **id**.| +| Index creation| 1. In unique indexes, duplicate NULL values will not trigger index conflicts.
2. A maximum of 10 indexes can be created for a single label.
3. When creating a property graph, you cannot use the **Primary Key** and **Unique** keywords to create an index. Indexes must be created explicitly using index creation statements.
4. Unique indexes can be created by specifying the **Unique** keyword.| +| Index deletion| When deleting an index, you must specify the name of the label to which the index belongs, for example, **Drop Index label.index**.| +| Index sorting order| **ASC** indicates ascending order; **DESC** indicates descending order. The default value is **ASC**. Currently, custom sorting order is not supported.| +| Expression index| It is not supported currently.| + +### Transaction Specifications + +| Category| Specifications| Difference with the GQL Standard| +| - | - | - | +| Explicit transactions| 1. The default isolation level is **serializable**.
2. **SAVEPOINT** is not supported. **SAVEPOINT** is an important mechanism in database transaction management that allows markers to be created in transactions for partial rollbacks.
3. Mixed transactions of DDL and DML, standalone DDL transactions, and DDL transaction rollbacks are not supported.
4. If a single statement in the current transaction fails to be executed, only that statement will be rolled back.
5. Transactions must be explicitly committed or rolled back. Otherwise, the transaction will be rolled back.
6. It is not allowed to commit or roll back a transaction that is not in the transaction state.
7. When two transactions are created at the same time, write-write operations, read-write operations, and write-read operations are mutually exclusive, and read-read operations can execute concurrently.
8. The operation limit and cache size of a transaction depend on **undo log** and are limited by the file system space. The number of threads waiting for locks correlates with the maximum connections allowed in the database.| The GQL standard supports basic transaction syntax, including enabling read-only and read-write transactions, but does not support **SAVEPOINT**.| +| Concurrent operations| Multi-concurrency is supported. Only the serializable isolation level is supported. Concurrent threads involving write operations may encounter some degree of blocking.| The GQL standard supports all isolation levels used in SQL.| + +### Other Specifications and Constraints + +- By default, the Write Ahead Log (WAL) and the **FULL** flushing mode are used. + +- To ensure data accuracy, only one write operation is allowed at a time. + +- Once an application is uninstalled, related database files and temporary files are automatically deleted from the device. + +- The multi-process mode is not supported. + +- Currently, backup and restore of graph stores are not supported. + + +## Available APIs + +The following lists only the APIs for persisting graph store data. For details about more APIs and their usage, see [Graph Store (System APIs)](../reference/apis-arkdata/js-apis-data-graphStore-sys.md). + +| API| Description| +| -------- | -------- | +| getStore(context: Context, config: StoreConfig): Promise<GraphStore> | Obtains a **GraphStore** instance for graph store operations. You can set **GraphStore** parameters based on actual requirements and use the created instance to call related APIs to perform data operations.| +| read(gql: string): Promise<Result> | Reads data from the graph store.| +| write(gql: string): Promise<Result> | Writes data to the graph store.| +| close(): Promise<void> | Closes the graph store. All uncommitted transactions will be rolled back.| +| createTransaction(): Promise<Transaction> | Creates a transaction instance.| +| Transaction.read(gql: string): Promise<Result> | Reads data with the transaction instance.| +| Transaction.write(gql: string): Promise<Result> | Writes data with the transaction instance. | +| Transaction.commit(): Promise<void> | Commits the GQL statements that have been executed in this transaction.| +| Transaction.rollback(): Promise<void> | Rolls back the GQL statements that have been executed in this transaction.| +| deleteStore(context: Context, config: StoreConfig): Promise<void> | Deletes a graph store.| + + +## How to Develop + +The following provides only the sample code in the stage model. + +1. Call **getStore()** to obtain a **GraphStore** instance, including creating a database, setting the security level, and changing the database to an encrypted database. The example code is as follows: + + ```ts + import { graphStore } from '@kit.ArkData'; // Import the graphStore module. + import { UIAbility } from '@kit.AbilityKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + import { window } from '@kit.ArkUI'; + + let store: graphStore.GraphStore | null = null; + + const STORE_CONFIG: graphStore.StoreConfig = { + name: "testGraphDb," // Database file name without the file name extension .db. + securityLevel: graphStore.SecurityLevel.S2, // Database security level. + encrypt: false, // Whether to encrypt the database. This parameter is optional. By default, the database is not encrypted. + }; + + const STORE_CONFIG_NEW: graphStore.StoreConfig = { + name: "testGraphDb", // The database file name must be the same as the file name used for creating the database. + securityLevel: graphStore.SecurityLevel.S3, + encrypt: true, + }; + + // In this example, EntryAbility is used to obtain a GraphStore instance. You can use other implementations as required. + class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + graphStore.getStore(this.context, STORE_CONFIG).then(async (gdb: graphStore.GraphStore) => { + store = gdb; + console.info('Get GraphStore successfully.') + }).catch((err: BusinessError) => { + console.error(`Get GraphStore failed, code is ${err.code}, message is ${err.message}`); + }) + + // Before changing the database security level and encryption property, call close() to close the database. + if(store != null) { + (store as graphStore.GraphStore).close().then(() => { + console.info(`Close successfully`); + + graphStore.getStore(this.context, STORE_CONFIG_NEW).then(async (gdb: graphStore.GraphStore) => { + store = gdb; + console.info('Update StoreConfig successfully.') + }).catch((err: BusinessError) => { + console.error(`Update StoreConfig failed, code is ${err.code}, message is ${err.message}`); + }) + }).catch ((err: BusinessError) => { + console.error(`Close failed, code is ${err.code}, message is ${err.message}`); + }) + } + } + } + ``` + +2. Call **write()** to create a graph. The example code is as follows: + + ```ts + const CREATE_GRAPH = "CREATE GRAPH test " + + "{ (person:Person {name STRING, age INT}),(person)-[:Friend {year INT}]->(person) };" + + if(store != null) { + (store as graphStore.GraphStore).write(CREATE_GRAPH).then(() => { + console.info('Create graph successfully'); + }).catch((err: BusinessError) => { + console.error(`Create graph failed, code is ${err.code}, message is ${err.message}`); + }) + } + ``` + +3. Call **write()** to insert or update vertexes and edges. The example code is as follows: + + > **NOTE** + > + > **graphStore** does not provide explicit flush operations for data persistence. The data inserted is persisted. + + ```ts + const INSERT_VERTEX_1 = "INSERT (:Person {name: 'name_1', age: 11});"; + const INSERT_VERTEX_2 = "INSERT (:Person {name: 'name_2', age: 22});"; + const INSERT_VERTEX_3 = "INSERT (:Person {name: 'name_3', age: 0});"; + + const UPDATE_VERTEX_3 = "MATCH (p:Person) WHERE p.name='name_3' SET p.age=33;" + + const INSERT_EDGE_12 = "MATCH (p1:Person {name: 'name_1'}), (p2:Person {name: 'name_2'}) " + + "INSERT (p1)-[:Friend {year: 12}]->(p2);"; + const INSERT_EDGE_23 = "MATCH (p2:Person {name: 'name_2'}), (p3:Person {name: 'name_3'}) " + + "INSERT (p2)-[:Friend {year: 0}]->(p3);"; + + const UPDATE_EDGE_23 = "MATCH (p2:Person {name: 'name_2'})-[relation:Friend]->(p3:Person {name: 'name_3'})" + + " SET relation.year=23;"; + + let writeList = [ + INSERT_VERTEX_1, + INSERT_VERTEX_2, + INSERT_VERTEX_3, + UPDATE_VERTEX_3, + INSERT_EDGE_12, + INSERT_EDGE_23, + UPDATE_EDGE_23, + ] + + if(store != null) { + writeList.forEach((gql) => { + (store as graphStore.GraphStore).write(gql).then(() => { + console.info('Write successfully'); + }).catch((err: BusinessError) => { + console.error(`Write failed, code is ${err.code}, message is ${err.message}`); + }); + }); + } + ``` + +4. Call **read()** to query vertexes, edges, and paths. The example code is as follows: + + ```ts + const QUERY_VERTEX = "MATCH (person:Person) RETURN person;" + + const QUERY_EDGE = "MATCH ()-[relation:Friend]->() RETURN relation;" + + const QUERY_PATH = "MATCH path=(a:Person {name: 'name_1'})-[]->{2, 2}(b:Person {name: 'name_3'}) RETURN path;" + + if(store != null) { + (store as graphStore.GraphStore).read(QUERY_VERTEX).then((result: graphStore.Result) => { + console.info('Query vertex successfully'); + result.records?.forEach((data) => { + for (let item of Object.entries(data)) { + const key = item[0]; + const value = item[1]; + const vertex = value as graphStore.Vertex; + console.info(`key : ${key}, vertex.properties : ${JSON.stringify(vertex.properties)}`); + } + }); + }).catch((err: BusinessError) => { + console.error(`Query vertex failed, code is ${err.code}, message is ${err.message}`); + }); + + (store as graphStore.GraphStore).read(QUERY_EDGE).then((result: graphStore.Result) => { + console.info('Query edge successfully'); + result.records?.forEach((data) => { + for (let item of Object.entries(data)) { + const key = item[0]; + const value = item[1]; + const edge = value as graphStore.Edge; + console.info(`key : ${key}, edge.properties : ${JSON.stringify(edge.properties)}`); + } + }); + }).catch((err: BusinessError) => { + console.error(`Query edge failed, code is ${err.code}, message is ${err.message}`); + }); + + (store as graphStore.GraphStore).read(QUERY_PATH).then((result: graphStore.Result) => { + console.info('Query path successfully'); + result.records?.forEach((data) => { + for (let item of Object.entries(data)) { + const key = item[0]; + const value = item[1]; + const path = value as graphStore.Path; + console.info(`key : ${key}, path.length : ${path.length}`); + } + }); + }).catch((err: BusinessError) => { + console.error(`Query path failed, code is ${err.code}, message is ${err.message}`); + }) + } + ``` + +5. Call **write()** to delete vertexes and edges. The example code is as follows: + + ```ts + const DELETE_VERTEX_AND_RELATED_EDGE = "MATCH (p:Person {name: 'name_1'}) DETACH DELETE p;" + + const DELETE_EDGE_ONLY = "MATCH (p2:Person {name: 'name_2'})-[relation: Friend]->(p3:Person {name: 'name_3'})" + + " DETACH DELETE relation;" + + if(store != null) { + (store as graphStore.GraphStore).write(DELETE_VERTEX_AND_RELATED_EDGE).then(() => { + console.info('Delete vertex and related edge successfully'); + }).catch((err: BusinessError) => { + console.error(`Delete vertex and related edge failed, code is ${err.code}, message is ${err.message}`); + }); + + (store as graphStore.GraphStore).write(DELETE_EDGE_ONLY).then(() => { + console.info('Delete edge only successfully'); + }).catch((err: BusinessError) => { + console.error(`Delete edge only failed, code is ${err.code}, message is ${err.message}`); + }) + } + ``` + +6. Create a transaction instance and use it to write, query, commit, and roll back data. The example code is as follows: + + ```ts + let transactionRead: graphStore.Transaction | null = null; + let transactionWrite: graphStore.Transaction | null = null; + + const INSERT = "INSERT (:Person {name: 'name_5', age: 55});"; + + const QUERY = "MATCH (person:Person) RETURN person;"; + + if(store != null) { + (store as graphStore.GraphStore).createTransaction().then((trans: graphStore.Transaction) => { + transactionRead = trans; + console.info('Create transactionRead successfully'); + }).catch((err: BusinessError) => { + console.error(`Create transactionRead failed, code is ${err.code}, message is ${err.message}`); + }); + + (store as graphStore.GraphStore).createTransaction().then((trans: graphStore.Transaction) => { + transactionWrite = trans; + console.info('Create transactionWrite successfully'); + }).catch((err: BusinessError) => { + console.error(`Create transactionWrite failed, code is ${err.code}, message is ${err.message}`); + }); + + if(transactionRead != null) { + (transactionRead as graphStore.Transaction).read(QUERY).then((result: graphStore.Result) => { + console.info('Transaction read successfully'); + result.records?.forEach((data) => { + for (let item of Object.entries(data)) { + const key = item[0]; + const value = item[1]; + const vertex = value as graphStore.Vertex; + console.info(`key : ${key}, vertex.properties : ${JSON.stringify(vertex.properties)}`); + } + }); + }).catch((err: BusinessError) => { + console.error(`Transaction read failed, code is ${err.code}, message is ${err.message}`); + }); + + (transactionRead as graphStore.Transaction).rollback().then(() => { + console.info(`Rollback successfully`); + transactionRead = null; + }).catch ((err: BusinessError) => { + console.error(`Rollback failed, code is ${err.code}, message is ${err.message}`); + }) + } + + if(transactionWrite != null) { + (transactionWrite as graphStore.Transaction).write(INSERT).then(() => { + console.info('Transaction write successfully'); + }).catch((err: BusinessError) => { + console.error(`Transaction write failed, code is ${err.code}, message is ${err.message}`); + }); + + (transactionWrite as graphStore.Transaction).commit().then(() => { + console.info(`Commit successfully`); + transactionWrite = null; + }).catch ((err: BusinessError) => { + console.error(`Commit failed, code is ${err.code}, message is ${err.message}`); + }) + } + } + ``` + +7. Delete the graph store. Call **deleteStore()** to delete the graph store and related database files. The example code is as follows: + + ```ts + const DROP_GRAPH_GQL = "DROP GRAPH test;" + + class EntryAbility extends UIAbility { + onWindowStageDestroy() { + if(store != null) { + // Delete the graph. This process is skipped here. + (store as graphStore.GraphStore).write(DROP_GRAPH_GQL).then(() => { + console.info('Drop graph successfully'); + }).catch((err: BusinessError) => { + console.error(`Drop graph failed, code is ${err.code}, message is ${err.message}`); + }); + + // Close the database. EntryAbility is used as an example. + (store as graphStore.GraphStore).close().then(() => { + console.info(`Close successfully`); + }).catch ((err: BusinessError) => { + console.error(`Close failed, code is ${err.code}, message is ${err.message}`); + }) + } + + // The StoreConfig used for deleting a database must be the same as that used for creating the database. + graphStore.deleteStore(this.context, STORE_CONFIG_NEW).then(() => { + store = null; + console.info('Delete GraphStore successfully.'); + }).catch((err: BusinessError) => { + console.error(`Delete GraphStore failed, code is ${err.code},message is ${err.message}`); + }) + } + } + ``` diff --git a/en/application-dev/database/data-persistence-by-preferences.md b/en/application-dev/database/data-persistence-by-preferences.md index fa4f2cdcebe235d500dce3a2cf5e029a874bc546..e355f343a04b0a76e683ebc2fe4700b5b1a61112 100644 --- a/en/application-dev/database/data-persistence-by-preferences.md +++ b/en/application-dev/database/data-persistence-by-preferences.md @@ -17,38 +17,44 @@ The preference persistent file of an application is stored in the application sa ![preferences](figures/preferences.jpg) ## Storage Types -By default, user preferences are stored in XML format. Since API version 16, the CLKV format is provided. +By default, user preferences are stored in XML format. Since API version 18, the GSKV format is provided. ### XML Data is stored in the form of XML files, which allow high versatility and cross-platform operations. When XML is used, preference data operations are primarily performed in the memory. You can call **flush()** to persist the data when necessary. This storage type is recommended for single-process, small data volume scenarios. -### CLKV -CLKV is available since API version 16. It supports concurrent read and write in multiple processes. When CLKV is used, preference data operations are flushed to the storage device in real time. This storage type is recommended for multi-process concurrency scenarios. +### GSKV +GSKV is available since API version 18. It supports concurrent read and write in multiple processes. When GSKV is used, preference data operations are flushed to the storage device in real time. This storage type is recommended for multi-process concurrency scenarios. ## Constraints ### Preferences Constraints - The key in a KV pair must be a string and cannot be empty or exceed 1024 bytes. + - If the value is of the string type, use the UTF-8 encoding format. It can be empty. If not empty, it cannot exceed 16 MB. +- If the data to be stored contains a string that is not in UTF-8 format, store it in an Uint8Array. Otherwise, the persistent file may be damaged due to format errors. + +- After **removePreferencesFromCache** or **deletePreferences** is called, the subscription to data changes will be automatically canceled. After **getPreferences** is called again, you need to subscribe to data changes again. + +- Do not call **deletePreferences** concurrently with other APIs in multi-thread or multi-process mode. Otherwise, unexpected behavior may occur. + ### XML Constraints - The XML type (default for preferences) cannot ensure process concurrency safety, posing risks of file corruption and data loss. It is not recommended for use in multi-process scenarios. - Memory usage will increase with the amount of stored data. You are advised to keep the stored data below 50 MB. When the stored data is large, using synchronous APIs to create **Preferences** objects and persist data will become time consuming. Avoid using it in the main thread, as it may cause appfreeze problems. -### CLKV Constraints +### GSKV Constraints -- CLKV does not support cross-platform operations. Before using this type, call **isStorageTypeSupported** to check whether it is supported. -- Do not call **deletePreferences** concurrently with other APIs in multi-thread or multi-process mode. Otherwise, unexpected behavior may occur. -- In OpenHarmony, a user group is a logical collection of users with the same characteristics. These users share certain rights. User groups are used to facilitate system management and control user access rights. If the user group is involved when CLKV is used by multiple processes, ensure that the processes belong to the same group. +- GSKV does not support cross-platform operations. Before using it, call **isStorageTypeSupported** to check whether it is supported. +- In OpenHarmony, a user group is a logical collection of users with the same characteristics. These users share certain rights. User groups are used to facilitate system management and control user access rights. If the user group is involved when GSKV is used by multiple processes, ensure that the processes belong to the same group. ## Available APIs -The following table lists the APIs used for persisting user preference data. For more information about the APIs, see [User Preferences](../reference/apis-arkdata/js-apis-data-preferences.md). +The following table lists the APIs related to user preference persistence. For more information about the APIs, see [User Preferences](../reference/apis-arkdata/js-apis-data-preferences.md). | API | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | @@ -74,15 +80,15 @@ The following table lists the APIs used for persisting user preference data. For 2. (Optional) Set the storage type. - This step is optional. By default, preferences data is stored in XML format. Since API version 16, CLKV is supported. + This step is optional. By default, preferences data is stored in XML format. Since API version 18, GSKV is supported. - Before using CLKV, call **isStorageTypeSupported()** to check whether the current platform supports CLKV. + Before using GSKV, call **isStorageTypeSupported()** to check whether the current platform supports it. - If **false** is returned, the platform does not support CLKV. In this case, use XML. + If **false** is returned, the platform does not support GSKV. In this case, use XML. ```ts - let isClkvSupported = preferences.isStorageTypeSupported(preferences.StorageType.CLKV); - console.info("Is clkv supported on this platform: " + isClkvSupported); + let isGskvSupported = preferences.isStorageTypeSupported(preferences.StorageType.GSKV); + console.info("Is gskv supported on this platform: " + isGskvSupported); ``` 3. Obtain a **Preferences** instance. @@ -119,9 +125,9 @@ The following table lists the APIs used for persisting user preference data. For ``` - Obtain a **Preferences** instance in CLKV format. + Obtain a **Preferences** instance in GSKV format. - If you want to use CLKV and the platform supports it, you can obtain the **Preferences** instance as follows. However, the storage type cannot be changed once selected. + If you want to use GSKV and the platform supports it, you can obtain the **Preferences** instance as follows. However, the storage type cannot be changed once selected. Stage model: ```ts @@ -133,7 +139,7 @@ The following table lists the APIs used for persisting user preference data. For class EntryAbility extends UIAbility { onWindowStageCreate(windowStage: window.WindowStage) { - let options: preferences.Options = { name: 'myStore' , storageType: preferences.StorageType.CLKV}; + let options: preferences.Options = { name: 'myStore' , storageType: preferences.StorageType.GSKV}; dataPreferences = preferences.getPreferencesSync(this.context, options); } } @@ -147,7 +153,7 @@ The following table lists the APIs used for persisting user preference data. For import { BusinessError } from '@kit.BasicServicesKit'; let context = featureAbility.getContext(); - let options: preferences.Options = { name: 'myStore' , storageType: preferences.StorageType.CLKV}; + let options: preferences.Options = { name: 'myStore' , storageType: preferences.StorageType.GSKV}; let dataPreferences: preferences.Preferences = preferences.getPreferencesSync(context, options); ``` @@ -159,7 +165,7 @@ The following table lists the APIs used for persisting user preference data. For For the data stored in the default mode (XML), you can call **flush()** to persist the data written if required. - If CLKV is used, the data is persisted in a file on realtime basis after being written. + If GSKV is used, the data is persisted in a file on realtime basis after being written. > **NOTE** > @@ -251,7 +257,7 @@ The following table lists the APIs used for persisting user preference data. For }) ``` - If the preferences data is stored in CLKV format, the observer callback will be triggered after the subscribed value changes (without the need for calling **flush()**). + If the preferences data is stored in GSKV format, the observer callback will be triggered after the subscribed value changes (without the need for calling **flush()**). Example: ```ts @@ -278,7 +284,7 @@ The following table lists the APIs used for persisting user preference data. For > > - The deleted data and files cannot be restored. > - > - If CLKV is used, this API cannot be called concurrently with other APIs (including multiple processes). Otherwise, unexpected behavior may occur. + > - If GSKV is used, this API cannot be called concurrently with other APIs (including multiple processes). Otherwise, unexpected behavior may occur. Example: diff --git a/en/application-dev/database/data-persistence-by-rdb-store.md b/en/application-dev/database/data-persistence-by-rdb-store.md index 220aee5eab45f0229f7f16f593828147dff0c4b0..5b64287d1e68d89adec3bbbed0e7f94b58fa981c 100644 --- a/en/application-dev/database/data-persistence-by-rdb-store.md +++ b/en/application-dev/database/data-persistence-by-rdb-store.md @@ -20,10 +20,10 @@ Querying data from a large amount of data may take time or even cause applicatio ## Working Principles -**RelationalStore** provides APIs for applications to perform data operations. With SQLite as the underlying persistent storage engine, **RelationalStore** provides SQLite database features, including transactions, indexes, views, triggers, foreign keys, parameterized queries, prepared SQL statements, and more. +**RelationalStore** provides APIs for data operations. With SQLite as the underlying persistent storage engine, **RelationalStore** provides SQLite database features, including transactions, indexes, views, triggers, foreign keys, parameterized queries, prepared SQL statements, and more. **Figure 1** Working mechanism - + ![relationStore_local](figures/relationStore_local.jpg) @@ -31,13 +31,13 @@ Querying data from a large amount of data may take time or even cause applicatio - The default logging mode is Write Ahead Log (WAL), and the default flushing mode is **FULL** mode. -- The RDB store supports a maximum of four read connections and one write connection. A thread performs the read operation when acquiring a read connection. When there is no read connection available but the write connection is idle, the write connection can be used to perform the read operation. +- The RDB store supports a maximum of four read connections and one write connection. A thread performs the read operation when acquiring a read connection. When there is no read connection available but the write connection is idle, the write connection can be used to read data. - To ensure data accuracy, only one write operation is allowed at a time. - Once an application is uninstalled, related database files and temporary files on the device are automatically deleted. -- ArkTS supports the following basic data types: number, string, binary data, and boolean. +- ArkTS supports the following basic data types: number, string, binary, and boolean. - The maximum size of a data record is 2 MB. If a data record exceeds 2 MB, it can be inserted successfully but cannot be read. @@ -45,26 +45,26 @@ Querying data from a large amount of data may take time or even cause applicatio The following table lists the APIs used for RDB data persistence. Most of the APIs are executed asynchronously, using a callback or promise to return the result. The following table uses the callback-based APIs as an example. For more information about the APIs, see [RDB Store](../reference/apis-arkdata/js-apis-data-relationalStore.md). -| API| Description| +| API| Description| | -------- | -------- | -| getRdbStore(context: Context, config: StoreConfig, callback: AsyncCallback<RdbStore>): void | Obtains an **RdbStore** instance to implement RDB store operations. You can set **RdbStore** parameters based on actual requirements and use **RdbStore** APIs to perform data operations.| -| executeSql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<void>):void | Executes an SQL statement that contains specified arguments but returns no value.| -| insert(table: string, values: ValuesBucket, callback: AsyncCallback<number>):void | Inserts a row of data into a table.| -| update(values: ValuesBucket, predicates: RdbPredicates, callback: AsyncCallback<number>):void | Updates data in the RDB store based on the specified **predicates** instance.| -| delete(predicates: RdbPredicates, callback: AsyncCallback<number>):void | Deletes data from the RDB store based on the specified **predicates** instance.| -| query(predicates: RdbPredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void | Queries data in the RDB store based on specified conditions.| -| deleteRdbStore(context: Context, name: string, callback: AsyncCallback<void>): void | Deletes an RDB store.| - +| getRdbStore(context: Context, config: StoreConfig, callback: AsyncCallback<RdbStore>): void | Obtains an **RdbStore** instance to implement RDB store operations. You can set **RdbStore** parameters based on actual requirements and use **RdbStore** APIs to perform data operations.| +| executeSql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<void>):void | Executes an SQL statement that contains specified arguments but returns no value.| +| insert(table: string, values: ValuesBucket, callback: AsyncCallback<number>):void | Inserts a row of data into a table.| +| update(values: ValuesBucket, predicates: RdbPredicates, callback: AsyncCallback<number>):void | Updates data in the RDB store based on the specified **predicates** instance.| +| delete(predicates: RdbPredicates, callback: AsyncCallback<number>):void | Deletes data from the RDB store based on the specified **predicates** instance.| +| query(predicates: RdbPredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void | Queries data in the RDB store based on specified conditions.| +| deleteRdbStore(context: Context, name: string, callback: AsyncCallback<void>): void | Deletes an RDB store.| +| isTokenizerSupported(tokenizer: Tokenizer): boolean | Checks whether the specified tokenizer is supported.| ## How to Develop Unless otherwise specified, the sample code without "stage model" or "FA model" applies to both models. -If error code 14800011 is reported, the RDB store is corrupted and needs to be rebuilt. For details, see [Rebuilding an RDB Store](data-backup-and-restore.md#rebuilding-an-rdb-store). +If error 14800011 is thrown, you need to rebuild the database and restore data to ensure normal application development. For details, see [Rebuilding an RDB Store](data-backup-and-restore.md#rebuilding-an-rdb-store). 1. Obtain an **RdbStore** instance, which includes operations of creating an RDB store and tables, and upgrading or downgrading the RDB store.
Example: Stage model: - + ```ts import { relationalStore} from '@kit.ArkData'; // Import the relationalStore module. import { UIAbility } from '@kit.AbilityKit'; @@ -74,12 +74,19 @@ If error code 14800011 is reported, the RDB store is corrupted and needs to be r // In this example, Ability is used to obtain an RdbStore instance. You can use other implementations as required. class EntryAbility extends UIAbility { onWindowStageCreate(windowStage: window.WindowStage) { + // Before using a tokenizer, call isStorageTypeSupported to check whether the tokenizer is supported by the current platform. + let tokenType = relationalStore.Tokenizer.ICU_TOKENIZER; + let tokenTypeSupported = relationalStore.isTokenizerSupported(tokenType); + if (!tokenTypeSupported) { + console.error(`ICU_TOKENIZER is not supported on this platform.`); + } const STORE_CONFIG :relationalStore.StoreConfig= { name: 'RdbTest.db', // Database file name. securityLevel: relationalStore.SecurityLevel.S3, // Database security level. encrypt: false, // Whether to encrypt the database. This parameter is optional. By default, the database is not encrypted. customDir: 'customDir/subCustomDir' // (Optional) Customized database path. The database is created in the context.databaseDir + '/rdb/' + customDir directory, where context.databaseDir indicates the application sandbox path, '/rdb/' indicates a relational database, and customDir indicates the customized path. If this parameter is not specified, an RdbStore instance is created in the sandbox directory of the application. isReadOnly: false // (Optional) Specify whether the RDB store is opened in read-only mode. The default value is false, which means the RDB store is readable and writable. If this parameter is true, data can only be read from the RDB store. If write operation is performed, error code 801 is returned. + tokenizer: tokenType // (Optional) Type of the tokenizer used in full-text search (FTS). If this parameter is left blank, only English word segmentation is supported in FTS. }; // Check the RDB store version. If the version is incorrect, upgrade or downgrade the RDB store. @@ -95,7 +102,7 @@ If error code 14800011 is reported, the RDB store is corrupted and needs to be r // When the RDB store is created, the default version is 0. if (store.version === 0) { - store.executeSql(SQL_CREATE_TABLE); // Create a data table. + store.executeSql(SQL_CREATE_TABLE); // Create a table. // Set the RDB store version, which must be an integer greater than 0. store.version = 3; } @@ -114,9 +121,8 @@ If error code 14800011 is reported, the RDB store is corrupted and needs to be r (store as relationalStore.RdbStore).executeSql('ALTER TABLE EMPLOYEE DROP COLUMN ADDRESS TEXT'); store.version = 3; } + // Before adding, deleting, modifying, and querying data in an RDB store, obtain an RdbStore instance and create a table. }); - - // Before performing data operations on the database, obtain an RdbStore instance. } } ``` @@ -147,7 +153,7 @@ If error code 14800011 is reported, the RDB store is corrupted and needs to be r // When the RDB store is created, the default version is 0. if (store.version === 0) { - store.executeSql(SQL_CREATE_TABLE); // Create a data table. + store.executeSql(SQL_CREATE_TABLE); // Create a table. // Set the RDB store version, which must be an integer greater than 0. store.version = 3; } @@ -166,9 +172,9 @@ If error code 14800011 is reported, the RDB store is corrupted and needs to be r store.executeSql('ALTER TABLE EMPLOYEE DROP COLUMN ADDRESS TEXT'); store.version = 3; } + // Before adding, deleting, modifying, and querying data in an RDB store, obtain an RdbStore instance and create a table. }); - // Before performing data operations on the database, obtain an RdbStore instance. ``` > **NOTE** @@ -179,8 +185,8 @@ If error code 14800011 is reported, the RDB store is corrupted and needs to be r > > - For details about the error codes, see [Universal Error Codes](../reference/errorcode-universal.md) and [RDB Store Error Codes](../reference/apis-arkdata/errorcode-data-rdb.md). -2. Use **insert()** to insert data to the RDB store.
Example: - +2. Call **insert()** to insert data.
Example: + ```ts let store: relationalStore.RdbStore | undefined = undefined; @@ -229,7 +235,7 @@ If error code 14800011 is reported, the RDB store is corrupted and needs to be r 3. Modify or delete data based on the specified **Predicates** instance. - Use **update()** to modify data and **delete()** to delete data.
Example: + Call **update()** to modify data and **delete()** to delete data.
Example: ```ts let value6 = 'Rose'; @@ -289,7 +295,7 @@ If error code 14800011 is reported, the RDB store is corrupted and needs to be r 4. Query data based on the conditions specified by **Predicates**. - Use **query()** to query data. The data obtained is returned in a **ResultSet** object.
Example: + Call **query()** to query data. The data obtained is returned in a **ResultSet** object.
Example: ```ts let predicates2 = new relationalStore.RdbPredicates('EMPLOYEE'); @@ -387,7 +393,7 @@ If error code 14800011 is reported, the RDB store is corrupted and needs to be r 7. Delete the RDB store. - Use **deleteRdbStore()** to delete the RDB store and related database files.
Example: + Call **deleteRdbStore()** to delete the RDB store and related database files.
Example: Stage model: diff --git a/en/application-dev/database/data-persistence-by-vector-store.md b/en/application-dev/database/data-persistence-by-vector-store.md new file mode 100644 index 0000000000000000000000000000000000000000..af5fd2e55448b8064bc837254e472bf465d01bbd --- /dev/null +++ b/en/application-dev/database/data-persistence-by-vector-store.md @@ -0,0 +1,337 @@ +# Persisting Vector Store Data (ArkTS) + + +## When to Use + +Vector stores are designed to store, manage, and retrieve vector data while also supporting relational data processing for scalar values. The data type **floatvector** is used to store data vectorization results, enabling rapid retrieval and similarity searches for such data. + +## Basic Concepts + +- **ResultSet**: a set of query results, which allows access to the required data in flexible modes. +- **floatvector**: vector data, for example, **[1.0, 3.0, 2.4, 5.1, 6.2, 11.7]**. + +## Constraints + +- By default, the Write Ahead Log (WAL) and the **FULL** flushing mode are used. + +- A vector store supports a maximum of four read connections and one write connection at a time by default. A thread can perform the read operation when acquiring an idle read connection. If there is no idle read connection, a new read connection will be created. + +- To ensure data accuracy, the database supports only one write operation at a time. Concurrent write operations are performed in serial mode. + +- Once an application is uninstalled, related database files and temporary files are automatically deleted from the device. + +- ArkTS supports basic data types such as number, string, binary, and boolean, and the special data type ValueType. + +- To ensure successful data access, limit the size of a data record to 2 MB. Data records larger than this may be inserted correctly but fail to read. + +## Available APIs + +The following lists only the APIs for persisting vector store data. For details about more APIs and their usage, see [RDB Store](../reference/apis-arkdata/js-apis-data-relationalStore.md). + +| API| Description| +| -------- | -------- | +| getRdbStore(context: Context, config: StoreConfig): Promise<RdbStore> | Obtains an **RdbStore** instance for data operations.| +| execute(sql: string, txId: number, args?: Array<ValueType>): Promise<ValueType> | Executes SQL statements that contain specified parameters. The number of operators (such as =, >, and <) in the SQL statements cannot exceed 1000.| +| querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSet> | Queries data in the RDB store using the specified SQL statement. The number of operators (such as =, >, and <) in the SQL statements cannot exceed 1000.| +| beginTrans(): Promise<number> | Starts the transaction before executing the SQL statements.| +| commit(txId : number):Promise<void> | Commits the executed SQL statements. This API must be used together with **beginTrans**.| +| rollback(txId : number):Promise<void> | Rolls back the executed SQL statements. This API must be used together with **beginTrans**.| +| deleteRdbStore(context: Context, config: StoreConfig): Promise<void> | Deletes an RDB store.| +| isVectorSupported(): boolean | Checks whether the system supports vector stores.| + +## How to Develop + +1. Check whether the current system supports vector stores. The sample code is as follows: + + ```ts + import { relationalStore } from '@kit.ArkData'; // Import the relationalStore module. + import { UIAbility } from '@kit.AbilityKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + import { window } from '@kit.ArkUI'; + // In this example, Ability is used to obtain an RdbStore instance. You can use other implementations as required. + class EntryAbility extends UIAbility { + async onWindowStageCreate(windowStage: window.WindowStage) { + // Check whether the current system supports vector stores. + let ret = relationalStore.isVectorSupported(); + if (!ret) { + console.error(`vectorDB is not supported .`); + return; + } + // Open the database, and add, delete, and modify data. + } + } + ``` + +2. If the system supports vector stores, obtain an **RdbStore** instance. Call **getRdbStore()** to create a database and create a table. + + > **NOTE** + > + > - The RDB store created by an application varies with the context. Multiple RDB stores are created for the same database name with different application contexts. For example, each UIAbility has its own context. + > + > - When an application calls **getRdbStore()** to obtain an RDB store instance for the first time, the corresponding database file is generated in the application sandbox. When the RDB store is used, temporary files ended with **-wal** and **-shm** may be generated in the same directory as the database file. If you want to move the database files to other places, you must also move these temporary files. After the application is uninstalled, the database files and temporary files generated on the device are also removed. + > + > - For details about the error codes, see [Universal Error Codes](../reference/errorcode-universal.md) and [RDB Store Error Codes](../reference/apis-arkdata/errorcode-data-rdb.md). + + The sample code is as follows: + + ```ts + let store: relationalStore.RdbStore | undefined = undefined; + const STORE_CONFIG :relationalStore.StoreConfig= { + name: 'VectorTest.db', // Database file name. + securityLevel: relationalStore.SecurityLevel.S1 // Database security level. + vector: true // Optional. This parameter must be true for a vector store. + }; + + relationalStore.getRdbStore(this.context, STORE_CONFIG).then(async (rdbStore: relationalStore.RdbStore) => { + store = rdbStore; + // Create a table. floatvector (2) indicates that repr is 2-dimensional. + const SQL_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY, repr floatvector(2));'; + // The second parameter indicates that transaction is not enabled. The third parameter undefined indicates that parameter binding is not used. + await store!.execute(SQL_CREATE_TABLE, 0, undefined); + }).catch((err: BusinessError) => { + console.error(`Get RdbStore failed, code is ${err.code}, message is ${err.message}`); + }); + ``` + +3. Call **execute()** to insert data to the vector store. + + > **NOTE** + > + > **RelationalStore** does not provide explicit flush operations for data persistence. The data inserted is persisted. + + The sample code is as follows: + + ```ts + try { + // Use parameter binding. + const vectorValue: Float32Array = Float32Array.from([1.2, 2.3]); + await store!.execute("insert into test VALUES(?, ?);", 0, [0, vectorValue]); + // Do not use parameter binding. + await store!.execute("insert into test VALUES(1, '[1.3, 2.4]');", 0, undefined); + } catch (err) { + console.error(`execute insert failed, code is ${err.code}, message is ${err.message}`); + } + ``` + +4. Call **execute()** to modify or delete data. The sample code is as follows: + + ```ts + // Modify data. + try { + // Use parameter binding. + const vectorValue1: Float32Array = Float32Array.from([2.1, 3.2]); + await store!.execute("update test set repr = ? where id = ?", 0, [vectorValue1, 0]); + // Do not use parameter binding. + await store!.execute("update test set repr = '[5.1, 6.1]' where id = 0", 0, undefined); + } catch (err) { + console.error(`execute update failed, code is ${err.code}, message is ${err.message}`); + } + + // Delete data. + try { + // Use parameter binding. + await store!.execute("delete from test where id = ?", 0, [0]); + // Do not use parameter binding. + await store!.execute("delete from test where id = 0", 0, undefined); + } catch (err) { + console.error(`execute delete failed, code is ${err.code}, message is ${err.message}`); + } + ``` + +5. Call **querySql()** to query data. A **ResultSet** instance is returned. + + > **NOTE** + > + > Use **close()** to close the **ResultSet** that is no longer used in a timely manner so that the memory allocated can be released. + + The sample code is as follows: + + ```ts + // Perform single-table queries. + try { + // Use parameter binding. + const QUERY_SQL = "select id, repr <-> ? as distance from test where id > ? order by repr <-> ? limit 5;"; + const vectorValue2: Float32Array = Float32Array.from([6.2, 7.3]); + let resultSet = await store!.querySql(QUERY_SQL, [vectorValue2, 0, vectorValue2]); + while (resultSet!.goToNextRow()) { + let id = resultSet.getValue(0); + let dis = resultSet.getValue(1); + } + resultSet!.close(); + + // Do not use parameter binding. + const QUERY_SQL1 = "select id, repr <-> '[6.2, 7.3]' as distance from test where id > 0 order by repr <-> '[6.2, 7.3]' limit 5;"; + resultSet = await store!.querySql(QUERY_SQL1); + resultSet!.close(); + } catch (err) { + console.error(`query failed, code is ${err.code}, message is ${err.message}`); + } + + // Perform subqueries. + try { + // Create the second table. + let CREATE_SQL = "CREATE TABLE IF NOT EXISTS test1(id text PRIMARY KEY);"; + await store!.execute(CREATE_SQL); + let resultSet = await store!.querySql("select * from test where id in (select id from test1);"); + resultSet!.close(); + } catch (err) { + console.error(`query failed, code is ${err.code}, message is ${err.message}`); + } + + // Perform aggregate queries. + try { + let resultSet = await store!.querySql("select * from test where repr <-> '[1.0, 1.0]' > 0 group by id having max(repr <=> '[1.0, 1.0]');"); + resultSet!.close(); + } catch (err) { + console.error(`query failed, code is ${err.code}, message is ${err.message}`); + } + + // Perform multi-table queries. + try { + // Different union all, union will delete duplicate data. + let resultSet = await store!.querySql("select id, repr <-> '[1.5, 5.6]' as distance from test union select id, repr <-> '[1.5, 5.6]' as distance from test order by distance limit 5;"); + resultSet!.close(); + } catch (err) { + console.error(`query failed, code is ${err.code}, message is ${err.message}`); + } + ``` + +6. Create a view and query data. The sample code is as follows: + + ```ts + // Perform view queries. + try { + // Create a view. + await store!.execute("CREATE VIEW v1 as select * from test where id > 0;"); + let resultSet = await store!.querySql("select * from v1;"); + resultSet!.close(); + } catch (err) { + console.error(`query failed, code is ${err.code}, message is ${err.message}`); + } + ``` + +7. Query data using vector indexes. + + The vector store uses vectors as keys to provide efficient and fast search capabilities. + + It supports the basic syntax and extended syntax as follows: + + - Basic syntax: + + ```sql + // index_name indicates the index name, index_type indicates the index type, and dist_function indicates the type of distance function for similarity measurement. + CREATE INDEX [IF NOT EXISTS] index_name ON table_name USING index_type (column_name dist_function); + + DROP INDEX table_name.index_name; + ``` + - Extended syntax: + + ```sql + CREATE INDEX [Basic syntax] [WITH(parameter = value [, ...])]; + ``` + + **Table 1** index_type + + | Type | Description | + | --------- | ------------------------------------------------------------ | + | gsdiskann | Index for processing high-dimensional dense vector data, such as text embedding and image features. | + + **Table 2** dist_function + + | Type | Operator| Description | + | ------ | -------- | ---------- | + | L2 | <-> | Euclidean distance.| + | COSINE | <=> | Cosine distance.| + + **Table 3** parameter (extended syntax parameters) + + | Parameter | Value Range| Description | + | ------ | -------- | ---------- | + | QUEUE_SIZE | Value range: [10, 1000]
Default value: **20** | Size of the candidate queue when an index is created for nearest neighbor search. A larger value indicates a lower construction speed and a slightly higher recall rate.| + | OUT_DEGREE | Value range: [1, 1200]
Default value: **60** | Number of outgoing edges of a node in the graph. The value of **OUT_DEGREE** cannot exceed **pageSize**. Otherwise, the error GRD_INVALID_ARGS will be thrown.| + + > **NOTE** + > + > - When deleting an index, you need to specify the table name, that is, **Drop Index table.index_name**. + > + > - The index created with a table cannot be deleted, for example, the primary key cannot be deleted. + > + > - When querying data based on vector indexes, you must use **ORDER BY** and **LIMIT**. **ORDER BY** has only one sorting condition, that is, the vector distance condition. If **ORDER BY** is used with **DESC**, vector indexes will not be used. The distance metric used for querying must match the metric used when the index is created. For example, if the vector index is created using **L2**, <-> must be used for the query. Otherwise, the index cannot be hit. + + The sample code is as follows: + + ```ts + // Basic syntax + try { + // Create an index using the basic syntax. The index name is diskann_l2_idx, index column is repr, type is gsdiskann, and the distance metric is L2. + await store!.execute("CREATE INDEX diskann_l2_idx ON test USING GSDISKANN(repr L2);"); + // Delete the diskann_l2_idx index from the test table. + await store!.execute("DROP INDEX test.diskann_l2_idx;"); + } catch (err) { + console.error(`create index failed, code is ${err.code}, message is ${err.message}`); + } + + // Extended syntax + try { + // Set QUEUE_SIZE to 20 and OUT_DEGREE to 50. + await store!.execute("CREATE INDEX diskann_l2_idx ON test USING GSDISKANN(repr L2) WITH (queue_size=20, out_degree=50);"); + } catch (err) { + console.error(`create ext index failed, code is ${err.code}, message is ${err.message}`); + } + ``` + +8. Configure the data aging policy, which allows the application data to be automatically deleted by time or space. + + The syntax is as follows: + + ```sql + CREATE TABLE table_name(column_name type [, ...]) [WITH(parameter = value [, ...])]; + ``` + + **parameter** specifies the parameter to set, and **value** specifies the value of the parameter. The following table describes the fields contained in **parameter**. + + **Table 4** parameter (data aging policy parameters) + + | Parameter| Mandatory| Value Range| + | ------ | -------- | ---------- | + | time_col | Yes| Column name. The value must be an integer and cannot be empty.| + | interval | No| Interval for executing the aging task thread. If a write operation is performed after the interval, an aging task will be triggered to delete the data that meets the aging conditions. If the write operation is performed within the interval, no aging task will be triggered.
Value range: [5 second, 1 year]
Default value: **1 day**
Time units supported include **second**, **minute**, **hour**, **day**, **month** and **year**. The value is case-insensitive and supports both singular and plural forms (for example, **2 hour** and **2 hours** are acceptable).| + | ttl | No| Data retention period.
Value range: [1 hour, 1 year]
Default value: **3 month**
Time units supported include **second**, **minute**, **hour**, **day**, **month** and **year**. The value is case-insensitive and supports both singular and plural forms (for example, **2 hour** and **2 hours** are acceptable).| + | max_num | No| Maximum data volume allowed.
Value range: [100, 1024]
Default value: **1024**
After the aging task deletes expired data, if the remaining data in the table exceeds the value of **max_num**, data tied to the nearest expiration-adjacent time point will be deleted until the total row count falls below **max_num**.| + + Time-related parameters are converted into seconds as follows. + + | Unit| Value in Seconds| + | ------ | -------- | + | year | 365 * 24 * 60 * 60 | + | month | 30 * 24 * 60 * 60 | + | day | 24 * 60 * 60 | + | hour | 60 * 60 | + | minute | 60 | + + For example, if **ttl** is set to **3 months**, the value will be converted into 7,776,000 seconds (3 x (30 * 24 * 60 * 60)). + + The sample code is as follows: + + ```ts + try { + // The write operation performed every 5 minutes will trigger a data aging task. + await store!.execute("CREATE TABLE test2(rec_time integer not null) WITH (time_col = 'rec_time', interval = '5 minute');"); + } catch (err) { + console.error(`configure data aging failed, code is ${err.code}, message is ${err.message}`); + } + ``` + +9. Delete the database. + + Call **deleteRdbStore()** to delete the vector store and related database files. The sample code is as follows: + + ```ts + try { + await relationalStore.deleteRdbStore(this.context, STORE_CONFIG); + } catch (err) { + console.error(`delete rdbStore failed, code is ${err.code},message is ${err.message}`); + } + ``` + + diff --git a/en/application-dev/database/data-share-overview.md b/en/application-dev/database/data-share-overview.md index 58c50930f6b7d0ee6ea7b45932e8bd6773be39a7..440384ea3efd42584151ab42dcb4c84f10d9d61a 100644 --- a/en/application-dev/database/data-share-overview.md +++ b/en/application-dev/database/data-share-overview.md @@ -1,4 +1,4 @@ -# Cross-Application Data Sharing +# Overview of Cross-Application Data Sharing ## Introduction diff --git a/en/application-dev/database/data-sync-of-kv-store.md b/en/application-dev/database/data-sync-of-kv-store.md index 75aed5cab3ac4e860048cc5b4864ee5c30d218d0..f6738acc38b10e013800809795c2fa6a5b658823 100644 --- a/en/application-dev/database/data-sync-of-kv-store.md +++ b/en/application-dev/database/data-sync-of-kv-store.md @@ -81,14 +81,14 @@ When data is added, deleted, or modified, a notification is sent to the subscrib The following table lists the APIs for cross-device data sync of the single KV store. Most of the APIs are executed asynchronously, using a callback or promise to return the result. The following table uses the callback-based APIs as an example. For more information about the APIs, see [Distributed KV Store](../reference/apis-arkdata/js-apis-distributedKVStore.md). -| API| Description| +| API| Description| | -------- | -------- | -| createKVManager(config: KVManagerConfig): KVManager | Creates a **KvManager** instance to manage database objects.| -| getKVStore<T>(storeId: string, options: Options, callback: AsyncCallback<T>): void | Obtains a KV store of the specified type.| -| put(key: string, value: Uint8Array \| string \| number \| boolean, callback: AsyncCallback<void>): void | Inserts and updates data.| -| on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void | Subscribes to data changes in the KV store.| -| get(key: string, callback: AsyncCallback<boolean \| string \| number \| Uint8Array>): void | Queries the value of the specified key.| -| sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void | Triggers a manual sync of the KV store.| +| createKVManager(config: KVManagerConfig): KVManager | Creates a **KvManager** instance to manage database objects.| +| getKVStore<T>(storeId: string, options: Options, callback: AsyncCallback<T>): void | Obtains a KV store of the specified type.| +| put(key: string, value: Uint8Array \| string \| number \| boolean, callback: AsyncCallback<void>): void | Inserts and updates data.| +| on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void | Subscribes to data changes in the KV store.| +| get(key: string, callback: AsyncCallback<boolean \| string \| number \| Uint8Array>): void | Queries the value of the specified key.| +| sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void | Triggers a manual sync of the KV store.| ## How to Develop @@ -102,7 +102,7 @@ The following uses a single KV store as an example to describe how to implement > The security level of the destination device (to which data is synced) cannot be higher than that of the source device. For details, see [Access Control Mechanism in Cross-Device Sync](access-control-by-device-and-data-level.md#access-control-mechanism-in-cross-device-sync). 1. Import the module. - + ```ts import { distributedKVStore } from '@kit.ArkData'; ``` @@ -117,7 +117,7 @@ The following uses a single KV store as an example to describe how to implement (1) Create a **kvManagerConfig** object based on the application context. (2) Create a **KvManager** instance. - + ```ts // Obtain the context of the stage model. import { window } from '@kit.ArkUI'; @@ -164,7 +164,7 @@ The following uses a single KV store as an example to describe how to implement (1) Declare the ID of the distributed KV store to create, for example, **'storeId'** in the sample code. (2) Disable the auto sync function (**autoSync:false**) to facilitate subsequent verification of the sync function. If sync is required, call the **sync()** interface. - + ```ts let kvStore: distributedKVStore.SingleKVStore | undefined = undefined; try { @@ -219,7 +219,7 @@ The following uses a single KV store as an example to describe how to implement ``` 5. Subscribe to distributed data changes. To unsubscribe from the data changes, call [off('dataChange')](../reference/apis-arkdata/js-apis-distributedKVStore.md#offdatachange). - + ```ts try { kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_ALL, (data) => { @@ -236,7 +236,7 @@ The following uses a single KV store as an example to describe how to implement (1) Construct the key and value to be written to the single KV store. (2) Write KV pairs to the single KV store. - + ```ts const KEY_TEST_STRING_ELEMENT = 'key_test_string'; // If schema is not defined, pass in other values that meet the requirements. @@ -260,7 +260,7 @@ The following uses a single KV store as an example to describe how to implement (1) Construct the key to be queried from the single KV store. (2) Query data from the single KV store. - + ```ts try { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, (err) => { @@ -320,4 +320,3 @@ The following uses a single KV store as an example to describe how to implement console.error("createDeviceManager errCode:" + error.code + ",errMessage:" + error.message); } ``` - diff --git a/en/application-dev/database/data-sync-of-rdb-store.md b/en/application-dev/database/data-sync-of-rdb-store.md index 1c85c7c8da15f770281eac3054755ce9c2487905..1a6e14721afad10ae134f5440eace33636bbe6ad 100644 --- a/en/application-dev/database/data-sync-of-rdb-store.md +++ b/en/application-dev/database/data-sync-of-rdb-store.md @@ -44,6 +44,7 @@ When data is added, deleted, or modified, a notification is sent to the subscrib - Each RDB store supports a maximum of eight callbacks for subscription of data change notifications. +- A table containing composite keys cannot be set as a distributed table. ## Available APIs diff --git a/en/application-dev/database/encrypted_estore_guidelines.md b/en/application-dev/database/encrypted_estore_guidelines.md index 471a6404d26a3ec13e11d1669e14a03eb756692b..842da21544a552265714d3eeba70cbd41d78ecf1 100644 --- a/en/application-dev/database/encrypted_estore_guidelines.md +++ b/en/application-dev/database/encrypted_estore_guidelines.md @@ -14,9 +14,7 @@ Both the KV store and RDB store can be used as an EL5 database. The following classes are encapsulated to implement the data operations and transfer between EL2 and EL5 databases: - **Mover** class: provides APIs for moving data from an EL2 database to an EL5 database after the screen is unlocked. - - **Store** class: provides APIs for obtaining a database instance, adding, deleting, and updating data, and obtaining the data count in the database. - - **SecretKeyObserver** class: provides APIs for obtaining the key status. After the key is destroyed, the EL5 database will be closed. - **ECStoreManager** class: provides APIs for managing the EL2 and EL5 databases. @@ -388,7 +386,7 @@ export default class EntryAbility extends UIAbility { autoSync: false, // If kvStoreType is left empty, a device KV store is created by default. kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, - // kvStoreType is distributedKVStore.KVStoreType.DEVICE_COLLABORATION for a device KV store. + // The value distributedKVStore.KVStoreType.DEVICE_COLLABORATION indicates a device KV store. securityLevel: distributedKVStore.SecurityLevel.S3 } } @@ -407,7 +405,7 @@ export default class EntryAbility extends UIAbility { autoSync: false, // If kvStoreType is left empty, a device KV store is created by default. kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, - // kvStoreType is distributedKVStore.KVStoreType.DEVICE_COLLABORATION for a device KV store. + // The value distributedKVStore.KVStoreType.DEVICE_COLLABORATION indicatates a device KV store. securityLevel: distributedKVStore.SecurityLevel.S3 } } diff --git a/en/application-dev/database/figures/dataManagement.jpg b/en/application-dev/database/figures/dataManagement.jpg index 6555d34202927dc202fcb0ab233bc42740f39dbe..af428d9659944731a4731da326c430a7c383c62e 100644 Binary files a/en/application-dev/database/figures/dataManagement.jpg and b/en/application-dev/database/figures/dataManagement.jpg differ diff --git a/en/application-dev/database/native-relational-store-guidelines.md b/en/application-dev/database/native-relational-store-guidelines.md index 1b339381391919057ba41a2a1a2fa91077000e01..58c9aa5ddcca63050c555ae03356e37f0e43a9ce 100644 --- a/en/application-dev/database/native-relational-store-guidelines.md +++ b/en/application-dev/database/native-relational-store-guidelines.md @@ -35,15 +35,15 @@ For details about the interfaces, see [RDB](../reference/apis-arkdata/_r_d_b.md) | OH_Rdb_GetOrOpen(const OH_Rdb_Config *config, int *errCode) | Obtains an **OH_Rdb_Store** instance for RDB store operations.| | OH_Rdb_Execute(OH_Rdb_Store *store, const char *sql) | Executes an SQL statement that contains specified arguments but returns no value.| | OH_Rdb_Insert(OH_Rdb_Store *store, const char *table, OH_VBucket *valuesBucket) | Inserts a row of data into a table.| -| OH_Rdb_Update(OH_Rdb_Store *store, OH_VBucket *valuesBucket, OH_Predicates *predicates) | Updates data in an RDB store. | -| OH_Rdb_Delete(OH_Rdb_Store *store, OH_Predicates *predicates) | Deletes data from an RDB store. | -| OH_Rdb_Query(OH_Rdb_Store *store, OH_Predicates *predicates, const char *const *columnNames, int length) | Queries data in an RDB store. | +| OH_Rdb_Update(OH_Rdb_Store *store, OH_VBucket *valuesBucket, OH_Predicates *predicates) | Updates data in an RDB store.| +| OH_Rdb_Delete(OH_Rdb_Store *store, OH_Predicates *predicates) | Deletes data from an RDB store.| +| OH_Rdb_Query(OH_Rdb_Store *store, OH_Predicates *predicates, const char *const *columnNames, int length) | Queries data in an RDB store.| | OH_Rdb_DeleteStore(const OH_Rdb_Config *config) | Deletes an RDB store.| | OH_VBucket_PutAsset(OH_VBucket *bucket, const char *field, Rdb_Asset *value) | Puts an RDB asset into an **OH_VBucket** object.| | OH_VBucket_PutAssets(OH_VBucket *bucket, const char *field, Rdb_Asset *value, uint32_t count) | Puts RDB assets into an **OH_VBucket** object.| | OH_Rdb_SetDistributedTables(OH_Rdb_Store *store, const char *tables[], uint32_t count, Rdb_DistributedType type, const Rdb_DistributedConfig *config) | Sets distributed database tables.| -| OH_Rdb_FindModifyTime(OH_Rdb_Store *store, const char *tableName, const char *columnName, OH_VObject *values) | Obtains the last modification time of the data in the specified column of a table. | -| OH_Rdb_CloudSync(OH_Rdb_Store *store, Rdb_SyncMode mode, const char *tables[], uint32_t count, const Rdb_ProgressObserver *observer) | Manually performs device-cloud sync for a table. The cloud service must be available. | +| OH_Rdb_FindModifyTime(OH_Rdb_Store *store, const char *tableName, const char *columnName, OH_VObject *values) | Obtains the last modification time of the data in the specified column of a table.| +| OH_Rdb_CloudSync(OH_Rdb_Store *store, Rdb_SyncMode mode, const char *tables[], uint32_t count, const Rdb_ProgressObserver *observer) | Manually performs device-cloud sync for a table. The cloud service must be available.| | int OH_Data_Asset_SetName(Data_Asset *asset, const char *name) | Sets the name for a data asset.| | int OH_Data_Asset_SetUri(Data_Asset *asset, const char *uri) | Sets the absolute path for a data asset.| | int OH_Data_Asset_SetPath(Data_Asset *asset, const char *path) | Sets the relative path in the application sandbox directory for a data asset.| @@ -90,11 +90,7 @@ libnative_rdb_ndk.z.so #include ``` -1. Obtain an **OH_Rdb_Store** instance and create a database file. - - The **dataBaseDir** variable specifies the application sandbox path. In the stage model, you are advised to use the database directory. For details, see the **databaseDir** attribute of [Context](../reference/apis-ability-kit/js-apis-inner-application-context.md). The FA model does not provide any API for obtaining the database sandbox path. Use the application directory instead. For details, see **getFilesDir** of [Context](../reference/apis-ability-kit/js-apis-inner-app-context.md). - - **area** indicates the security level of the directory for database files. For details, see [contextConstant](../reference/apis-ability-kit/js-apis-app-ability-contextConstant.md). During development, you need to implement the conversion from **AreaMode** to **Rdb_SecurityArea**.
Example: +1. Obtain an **OH_Rdb_Store** instance and create a database file.
The **dataBaseDir** variable specifies the application sandbox path. In the stage model, you are advised to use the database directory. For details, see the **databaseDir** attribute of [Context](../reference/apis-ability-kit/js-apis-inner-application-context.md). The FA model does not provide any API for obtaining the database sandbox path. Use the application directory instead. For details, see **getFilesDir** of [Context](../reference/apis-ability-kit/js-apis-inner-app-context.md).
**area** indicates the security level of the directory for database files. For details, see [contextConstant](../reference/apis-ability-kit/js-apis-app-ability-contextConstant.md). During development, you need to implement the conversion from **AreaMode** to **Rdb_SecurityArea**.
Example: ```c // Create an OH_Rdb_Config object. @@ -147,7 +143,7 @@ libnative_rdb_ndk.z.so > > **RelationalStore** does not provide explicit flush operations for data persistence. The **insert()** API stores data persistently. -3. Modify or delete data based on the conditions specified by **OH_Predicates**. +3. Modify or delete data based on the conditions specified by **OH_Predicates**.
Call **OH_Rdb_Update** to modify data, and call **OH_Rdb_Delete** to delete data.
Example: @@ -189,7 +185,7 @@ libnative_rdb_ndk.z.so predicates->destroy(predicates); ``` -4. Query data based on the conditions specified by **OH_Predicates**. +4. Query data based on the conditions specified by **OH_Predicates**.
Call **OH_Rdb_Query** to query data. The data obtained is returned in an **OH_Cursor** object.
Example: @@ -300,9 +296,7 @@ libnative_rdb_ndk.z.so cursor->destroy(cursor); ``` -7. Obtain the last modification time of data. - - Call **OH_Rdb_FindModifyTime** to obtain the last modification time of data in the specified column of a table. This API returns an **OH_Cursor** object with two columns of data. The first column is the input primary key or row ID, and the second column is the last modification time.
Example: +7. Obtain the last modification time of data.
Call **OH_Rdb_FindModifyTime** to obtain the last modification time of data in the specified column of a table. This API returns an **OH_Cursor** object with two columns of data. The first column is the input primary key or row ID, and the second column is the last modification time.
Example: ```c OH_VObject *values = OH_Rdb_CreateValueObject(); @@ -312,9 +306,7 @@ libnative_rdb_ndk.z.so cursor = OH_Rdb_FindModifyTime(store_, "EMPLOYEE", "ROWID", values); ``` -8. Create distributed tables. - - Call **OH_Rdb_SetDistributedTables** to set distributed tables for the table (created by using **OH_Rdb_Execute**). Before using this API, ensure that the cloud service is available.
Example: +8. Create distributed tables.
Call **OH_Rdb_SetDistributedTables** to set distributed tables for the table (created by using **OH_Rdb_Execute**). Before using this API, ensure that the cloud service is available.
Example: ```c constexpr int TABLE_COUNT = 1; @@ -323,11 +315,9 @@ libnative_rdb_ndk.z.so int errcode = OH_Rdb_SetDistributedTables(store_, table, TABLE_COUNT, Rdb_DistributedType::DISTRIBUTED_CLOUD, &config); ``` -9. Manually perform device-cloud sync for the distributed tables. - - Call **OH_Rdb_CloudSync** to perform device-cloud sync for the tables. Before using this API, ensure that the cloud service is available.
Example: - - ```c +9. Manually perform device-cloud sync for the distributed tables.
Call **OH_Rdb_CloudSync** to perform device-cloud sync for the tables. Before using this API, ensure that the cloud service is available.
Example: + + ```c // Define a callback. void CloudSyncObserverCallback(void *context, Rdb_ProgressDetails *progressDetails) { @@ -338,7 +328,7 @@ libnative_rdb_ndk.z.so ``` 10. Register a data observer for the specified event type for an RDB store. When the data changes, the registered callback will be invoked to process the observation. Call **OH_Rdb_Subscribe** to subscribe to data changes. Before using this API, ensure that the cloud service is available.
Example: - + ```c // Define a callback. void RdbSubscribeBriefCallback(void *context, const char *values[], uint32_t count) @@ -374,7 +364,7 @@ libnative_rdb_ndk.z.so Rdb_DataObserver observer = { nullptr, { callback } }; // Subscribe to the local database data changes. OH_Rdb_Subscribe(store_, Rdb_SubscribeType::RDB_SUBSCRIBE_TYPE_LOCAL_DETAILS, &observer); - + OH_VBucket* valueBucket = OH_Rdb_CreateValuesBucket(); valueBucket->putText(valueBucket, "NAME", "Lisa"); valueBucket->putInt64(valueBucket, "AGE", 18); @@ -388,34 +378,38 @@ libnative_rdb_ndk.z.so valueBucket->destroy(valueBucket); ``` -11. Unsubscribe from the events of the specified type for an RDB store. After that, the callback will not be invoked to process the observation. Call **OH_Rdb_Unsubscribe** to unsubscribe from data changes. Before using this API, ensure that the cloud service is available.
Example: - - ```c - // Define a callback. - void RdbSubscribeBriefCallback(void *context, const char *values[], uint32_t count) - { - // Do something. - } - Rdb_BriefObserver briefObserver = RdbSubscribeBriefCallback; - const Rdb_DataObserver briefObs = { .context = nullptr, .callback.briefObserver = briefObserver }; - // Unsubscribe from data changes. - OH_Rdb_Unsubscribe(store_, Rdb_SubscribeType::RDB_SUBSCRIBE_TYPE_CLOUD, &briefObs); - ``` +11. Unsubscribe from the events of the specified type for an RDB store. After that, the callback will not be invoked to process the observation. + + Call **OH_Rdb_Unsubscribe** to unsubscribe from data changes. Before using this API, ensure that the cloud service is available.
Example: + + ```c + // Define a callback. + void RdbSubscribeBriefCallback(void *context, const char *values[], uint32_t count) + { + // Do something. + } + Rdb_BriefObserver briefObserver = RdbSubscribeBriefCallback; + const Rdb_DataObserver briefObs = { .context = nullptr, .callback.briefObserver = briefObserver }; + // Unsubscribe from data changes. + OH_Rdb_Unsubscribe(store_, Rdb_SubscribeType::RDB_SUBSCRIBE_TYPE_CLOUD, &briefObs); + ``` Call **OH_Rdb_Unsubscribe** to unsubscribe from local database data changes.
Example: - ```c - // Define a callback. - void LocalDataChangeObserverCallback1(void *context, const Rdb_ChangeInfo **changeInfo, uint32_t count) - { - // Do something. - } - Rdb_DetailsObserver callback = LocalDataChangeObserverCallback1; - Rdb_DataObserver observer = { nullptr, { callback } }; - // Unsubscribe from the local database data changes. - OH_Rdb_Unsubscribe(store_, Rdb_SubscribeType::RDB_SUBSCRIBE_TYPE_LOCAL_DETAILS, &observer); - ``` - - -12. Register an observer for auto sync progress of an RDB store. When auto sync is performed on the RDB store, the registered callback will be invoked to process the observation. Call **OH_Rdb_SubscribeAutoSyncProgress** to subscribe to the auto sync progress. Before using this API, ensure that the cloud service is available.
Example: + ```c + // Define a callback. + void LocalDataChangeObserverCallback1(void *context, const Rdb_ChangeInfo **changeInfo, uint32_t count) + { + // Do something. + } + Rdb_DetailsObserver callback = LocalDataChangeObserverCallback1; + Rdb_DataObserver observer = { nullptr, { callback } }; + // Unsubscribe from the local database data changes. + OH_Rdb_Unsubscribe(store_, Rdb_SubscribeType::RDB_SUBSCRIBE_TYPE_LOCAL_DETAILS, &observer); + ``` + + +12. Register an observer for auto sync progress of an RDB store. When auto sync is performed on the RDB store, the registered callback will be invoked to process the observation. + + Call **OH_Rdb_SubscribeAutoSyncProgress** to subscribe to the auto sync progress. Before using this API, ensure that the cloud service is available.
Example: ```c // Define a callback. @@ -424,11 +418,13 @@ libnative_rdb_ndk.z.so // Do something. } const Rdb_ProgressObserver observer = { .context = nullptr, .callback = RdbProgressObserverCallback }; - OH_Rdb_SubscribeAutoSyncProgress(store_, &observer); +OH_Rdb_SubscribeAutoSyncProgress(store_, &observer); ``` - -13. Unsubscribe from the auto sync progress from an RDB store. After that, the callback will not be invoked to process the observation. Call **OH_Rdb_UnsubscribeAutoSyncProgress** to unsubscribe from the auto sync progress. Before using this API, ensure that the cloud service is available.
Example: +13. Unsubscribe from the auto sync progress from an RDB store. After that, the callback will not be invoked to process the observation. + + Call **OH_Rdb_UnsubscribeAutoSyncProgress** to unsubscribe from the auto sync progress. Before using this API, ensure that the cloud service is available.
Example: + ```c // Define a callback. void RdbProgressObserverCallback(void *context, Rdb_ProgressDetails *progressDetails) @@ -439,17 +435,15 @@ libnative_rdb_ndk.z.so OH_Rdb_UnsubscribeAutoSyncProgress(store_, &observer); ``` -14. Delete an RDB store. - - Call **OH_Rdb_DeleteStore** to delete the RDB store and related database file.
Example: - +14. Delete the database.
Call **OH_Rdb_DeleteStore** to delete the RDB store and related database file.
Example: + ```c // Close the database instance. OH_Rdb_CloseStore(store_); // Delete the database file. -OH_Rdb_DeleteStore(&config); + OH_Rdb_DeleteStore(&config); ``` - + diff --git a/en/application-dev/database/native-vector-store-guidelines.md b/en/application-dev/database/native-vector-store-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..f2e38f7b7638cea23b94a87f3890ba87f5cb93dd --- /dev/null +++ b/en/application-dev/database/native-vector-store-guidelines.md @@ -0,0 +1,298 @@ +# Persisting Vector Store Data (C/C++) + + +## When to Use + +Vector stores are designed to store, manage, and retrieve vector data while also supporting relational data processing for scalar values. The data type **floatvector** is used to store data vectorization results, enabling rapid retrieval and similarity searches for such data. + +## Basic Concepts + +- **ResultSet**: a set of query results, which allows access to the required data in flexible modes. +- **floatvector**: vector data, for example, **[1.0, 3.0, 2.4, 5.1, 6.2, 11.7]**. + +## Constraints + +- By default, the Write Ahead Log (WAL) and the **FULL** flushing mode are used. + +- A vector store supports a maximum of four read connections and one write connection at a time by default. A thread can perform the read operation when acquiring an idle read connection. If there is no idle read connection, a new read connection will be created. + +- To ensure data accuracy, the database supports only one write operation at a time. Concurrent write operations are performed in serial mode. + +- Once an application is uninstalled, related database files and temporary files are automatically deleted from the device. + +- To ensure successful data access, limit the size of a data record to 2 MB. Data records larger than this may be inserted correctly but fail to read. + +## Available APIs + +For details about the APIs, see [RDB](../reference/apis-arkdata/_r_d_b.md). + +| API| Description| +| -------- | -------- | +| int OH_Rdb_SetDbType(OH_Rdb_ConfigV2 *config, int dbType) | Sets the database type.| +| OH_Rdb_Store *OH_Rdb_CreateOrOpen(const OH_Rdb_ConfigV2 *config, int *errCode) | Obtains an **OH_Rdb_Store** instance (**dbType** is set to **RDB_CAYLEY** by using **OH_Rdb_SetDbType**) for vector operations.| +| int OH_Rdb_ExecuteV2(OH_Rdb_Store *store, const char *sql, const OH_Data_Values *args, OH_Data_Value **result) | Executes SQL statements with a return value to perform write operations. Parameter binding is supported. The number of operators (such as =, >, and <) in the SQL statements cannot exceed 1000.| +| int OH_Rdb_ExecuteByTrxId(OH_Rdb_Store *store, int64_t trxId, const char *sql) | Executes the SQL statement that does not return a value with the specified transaction ID. If the transaction ID is **0**, no transaction is used.| +| OH_Cursor *OH_Rdb_ExecuteQuery(OH_Rdb_Store *store, const char *sql) | Queries data in a store using the specified SQL statements.| +| OH_Cursor *OH_Rdb_ExecuteQueryV2(OH_Rdb_Store *store, const char *sql, const OH_Data_Values *args) | Queries data in a store using the specified SQL statements. Parameter binding is supported. The number of operators (such as =, >, and <) in the SQL statements cannot exceed 1000.| +| int OH_Rdb_DeleteStoreV2(const OH_Rdb_ConfigV2 *config) | Deletes a vector store.| +| int OH_Cursor_GetFloatVectorCount(OH_Cursor *cursor, int32_t columnIndex, size_t *length) | Obtains the length of the floating-point array in the specified column of the current row.| +| int OH_Cursor_GetFloatVector(OH_Cursor *cursor, int32_t columnIndex, float *val, size_t inLen, size_t *outLen) | Obtains the value in the specified column of the current row as a floating-point array. The value of **inLen** cannot be less than the actual array size.| + +## How to Develop + +**Adding Dynamic Link Libraries** + +Add the following libraries to **CMakeLists.txt**. + +```txt +libnative_rdb_ndk.z.so +``` + +**Including Header Files** + +```c++ +#include +#include +#include +``` + +1. Check whether the system supports vector stores. The sample code is as follows: + + ```c + int numType = 0; + // If numType is 2, the system supports vector stores. If numType 1, the system does not support vector stores. + OH_Rdb_GetSupportedDbType(&numType); + ``` + +2. If the system supports vector stores, obtain an **OH_Rdb_Store** instance. The sample code is as follows: + + ```c + // Create an OH_Rdb_Config instance. + OH_Rdb_ConfigV2 *config = OH_Rdb_CreateConfig(); + // The path must be an application sandbox path. + OH_Rdb_SetDatabaseDir(config, "xxx"); + // Set the store name, which is the database file name. + OH_Rdb_SetStoreName(config, "rdb_vector_test.db"); + // Set the application bundle name. + OH_Rdb_SetBundleName(config, "xxx"); + // Specify whether the database is encrypted. + OH_Rdb_SetEncrypted(config, false); + // Set the security level of the database files. + OH_Rdb_SetSecurityLevel(config, OH_Rdb_SecurityLevel::S1); + // Set the encryption level for the directory holding the database files. + OH_Rdb_SetArea(config, RDB_SECURITY_AREA_EL1); + // Set the storage type. + OH_Rdb_SetDbType(config, RDB_CAYLEY); + + // Create an OH_Rdb_Store instance. + int errCode = 0; + OH_Rdb_Store *store_ = OH_Rdb_CreateOrOpen(config, &errCode); + ``` + +3. Create a table and insert data into the table. + + > **NOTE** + > + > **VectorStore** does not provide explicit flush operations for data persistence. The data inserted is persisted. + + The sample code is as follows: + + ```c + char createTableSql[] = "CREATE TABLE test (id INTEGER PRIMARY KEY AUTOINCREMENT, data1 floatvector(2));"; + // Create a table. + OH_Rdb_ExecuteByTrxId(store_, 0, createTableSql); + + // Insert data without parameter binding. + OH_Rdb_ExecuteV2(store_, "INSERT INTO test (id, data1) VALUES (0, '[3.4, 4.5]');", nullptr, nullptr); + // Insert data with parameter binding. + OH_Data_Values *values = OH_Values_Create(); + OH_Values_PutInt(values, 1); + float test[] = { 1.2, 2.3 }; + size_t len = sizeof(test) / sizeof(test[0]); + OH_Values_PutFloatVector(values, test, len); + char insertSql[] = "INSERT INTO test (id, data1) VALUES (?, ?);"; + OH_Rdb_ExecuteV2(store_, insertSql, values, nullptr); + OH_Values_Destroy(values); + ``` + +4. Modify or delete data. The sample code is as follows: + + ```c + // Modify data without parameter binding. + OH_Rdb_ExecuteV2(store_, "update test set data1 = '[5.1, 6.1] where id = 0;", nullptr, nullptr); + + // Modify data with parameter binding. + float test1[2] = { 5.5, 6.6 }; + OH_Data_Values *values1 = OH_Values_Create(); + OH_Values_PutFloatVector(values1, test1, 2); + OH_Values_PutInt(values1, 1); + OH_Rdb_ExecuteV2(store_, "update test set data1 = ? where id = ?", values1, nullptr); + OH_Values_Destroy(values1); + + // Delete data without parameter binding. + OH_Rdb_ExecuteV2(store_, "delete from test where id = 0", nullptr, nullptr); + + // Delete data with parameter binding. + OH_Data_Values *values2 = OH_Values_Create(); + OH_Values_PutInt(values2, 01); + OH_Rdb_ExecuteV2(store_, "delete from test where id = ?", values2, nullptr); + OH_Values_Destroy(values2); + ``` + +5. Query data. + + > **NOTE** + > + > Use **destroy()** to destroy the **ResultSet** that is no longer used in a timely manner so that the memory allocated can be released. + + The sample code is as follows: + + ```c + // Query data without parameter binding. + OH_Cursor *cursor = OH_Rdb_ExecuteQueryV2(store_, "select * from test where id = 1;", nullptr); + int rowCount = 0; + cursor->getRowCount(cursor, &rowCount); + cursor->goToNextRow(cursor); + size_t count = 0; + // The floatvector array is the second column of data. + OH_Cursor_GetFloatVectorCount(cursor, 1, &count); + float test2[count]; + size_t outLen; + OH_Cursor_GetFloatVector(cursor, 1, test2, count, &outLen); + cursor->destroy(cursor); + + // Query data with parameter binding. + char querySql[] = "select * from test where id = ?;"; + OH_Data_Values *values3 = OH_Values_Create(); + OH_Values_PutInt(values3, 1); + cursor = OH_Rdb_ExecuteQueryV2(store_, querySql, values3); + OH_Values_Destroy(values3); + cursor->destroy(cursor); + + // Query data in another table, and create the table if it does not exist. + OH_Rdb_ExecuteV2(store_, "CREATE TABLE IF NOT EXISTS test1(id text PRIMARY KEY);", nullptr, nullptr); + cursor = OH_Rdb_ExecuteQueryV2(store_, "select * from test where id in (select id from test1);", nullptr); + cursor->destroy(cursor); + + // Perform aggregate query. + cursor = OH_Rdb_ExecuteQueryV2(store_, "select * from test where data1 <-> '[1.0, 1.0]' > 0 group by id having max(data1 <=> '[1.0, 1.0]');", nullptr); + cursor->destroy(cursor); + + // Perform multi-table query. + cursor = OH_Rdb_ExecuteQueryV2(store_, "select id, data1 <-> '[1.5, 5.6]' as distance from test union select id, data1 <-> '[1.5, 5.6]' as distance from test order by distance limit 5;", nullptr); + cursor->destroy(cursor); + ``` + +6. Create a view and query data. The sample code is as follows: + + ```c + OH_Rdb_ExecuteV2(store_, "CREATE VIEW v1 as select * from test where id > 0;", nullptr, nullptr); + OH_Cursor *cursor = OH_Rdb_ExecuteQueryV2(store_, "select * from v1;", nullptr); + cursor->destroy(cursor); + ``` + +7. Query data using vector indexes. + + The vector store uses vectors as keys to provide efficient and fast search capabilities. + + It supports the basic syntax and extended syntax as follows: + + - Basic syntax: + + ```sql + // index_name indicates the index name, index_type indicates the index type, and dist_function indicates the type of distance function for similarity measurement. + CREATE INDEX [IF NOT EXISTS] index_name ON table_name USING index_type (column_name dist_function); + + DROP INDEX table_name.index_name; + ``` + - Extended syntax: + + ```sql + CREATE INDEX [Basic syntax] [WITH(parameter = value [, ...])]; + ``` + + **Table 1** index_type + + | Type | Description | + | --------- | ------------------------------------------------------------ | + | gsdiskann | Index for processing high-dimensional dense vector data, such as text embedding and image features. | + + **Table 2** dist_function + + | Type | Operator| Description | + | ------ | -------- | ---------- | + | L2 | <-> | Euclidean distance.| + | COSINE | <=> | Cosine distance.| + + **Table 3** parameter (extended syntax parameters) + + | Name | Value Range| Description | + | ------ | -------- | ---------- | + | QUEUE_SIZE | Value range: [10, 1000]
Default value: **20** | Size of the candidate queue when an index is created for nearest neighbor search. A larger value indicates a lower construction speed and a slightly higher recall rate.| + | OUT_DEGREE | Value range: [1, 1200]
Default value: **60** | Number of outgoing edges of a node in the graph. The value of **OUT_DEGREE** cannot exceed **pageSize**. Otherwise, the error GRD_INVALID_ARGS will be thrown.| + + > **NOTE** + > + > - When deleting an index, you need to specify the table name, that is, **Drop Index table.index_name**. + > + > - The index created with a table cannot be deleted, for example, the primary key cannot be deleted. + > + > - When querying data based on vector indexes, you must use **ORDER BY** and **LIMIT**. **ORDER BY** has only one sorting condition, that is, the vector distance condition. If **ORDER BY** is used with **DESC**, vector indexes will not be used. The distance metric used for querying must match the metric used when the index is created. For example, if the vector index is created using **L2**, <-> must be used for the query. Otherwise, the index cannot be hit. + + The sample code is as follows: + + ```c + // Create an index using the basic syntax. The index name is diskann_l2_idx, index column is repr, type is gsdiskann, and the distance metric is L2. + OH_Rdb_ExecuteV2(store_, "CREATE INDEX diskann_l2_idx ON test USING GSDISKANN(data1 L2);", nullptr, nullptr); + + // Delete the diskann_l2_idx index from the test table. + OH_Rdb_ExecuteV2(store_, "DROP INDEX test.diskann_l2_idx;", nullptr, nullptr); + + // Set QUEUE_SIZE to 20 and OUT_DEGREE to 50 using the extended syntax. + OH_Rdb_ExecuteV2(store_, "CREATE INDEX diskann_l2_idx ON test USING GSDISKANN(repr L2) WITH (queue_size=20, out_degree=50);", nullptr, nullptr); + ``` + +8. Configure the data aging policy, which allows the application data to be automatically deleted by time or space. + + The syntax is as follows: + + ```sql + CREATE TABLE table_name(column_name type [, ...]) [WITH(parameter = value [, ...])]; + ``` + + **parameter** specifies the parameter to set, and **value** specifies the value of the parameter. The following table describes the fields contained in **parameter**. + + **Table 4** parameter (data aging policy parameters) + + | Name| Mandatory| Description| + | ------ | -------- | ---------- | + | time_col | Yes| Column name The value must be an integer and cannot be empty.| + | interval | No| Interval for executing the aging task thread. If a write operation is performed after the interval, an aging task will be triggered to delete the data that meets the aging conditions. If the write operation is performed within the interval, no aging task will be triggered.
Value range: [5 second, 1 year]
Default value: **1 day**
Time units supported include **second**, **minute**, **hour**, **day**, **month** and **year**. The value is case-insensitive and supports both singular and plural forms (for example, **2 hour** and **2 hours** are acceptable).| + | ttl | No| Data retention period.
Value range: [1 hour, 1 year]
Default value: **3 month**
Time units supported include **second**, **minute**, **hour**, **day**, **month** and **year**. The value is case-insensitive and supports both singular and plural forms (for example, **2 hour** and **2 hours** are acceptable).| + | max_num | No| Maximum data volume allowed.
Value range: [100, 1024]
Default value: **1024**
After the aging task deletes expired data, if the remaining data in the table exceeds the value of **max_num**, data tied to the nearest expiration-adjacent time point will be deleted until the total row count falls below **max_num**.| + + Time-related parameters are converted into seconds as follows. + + | Unit| Value in Seconds| + | ------ | -------- | + | year | 365 * 24 * 60 * 60 | + | month | 30 * 24 * 60 * 60 | + | day | 24 * 60 * 60 | + | hour | 60 * 60 | + | minute | 60 | + + For example, if **ttl** is set to **3 months**, the value will be converted into 7,776,000 seconds (3 x (30 x 24 x 60 x 60)). + + The sample code is as follows: + + ```c + // The write operation performed every 5 minutes will trigger a data aging task. + OH_Rdb_ExecuteV2(store_, "CREATE TABLE test2(rec_time integer not null) WITH (time_col = 'rec_time', interval = '5 minute');", nullptr, nullptr); + ``` + +9. Delete the database. The sample code is as follows: + + ```c + OH_Rdb_CloseStore(store_); + OH_Rdb_DeleteStoreV2(config); + ``` diff --git a/en/application-dev/database/preferences-guidelines.md b/en/application-dev/database/preferences-guidelines.md index 124854c6c82cad52a94cd125b26ab8db3e7785c9..d09c884021078b30991ebc4aeb9377dba3804b45 100644 --- a/en/application-dev/database/preferences-guidelines.md +++ b/en/application-dev/database/preferences-guidelines.md @@ -5,7 +5,8 @@ The **Preferences** module allows quick access to data in KV pairs and storage o ## Constraints -The C APIs and ArkTS APIs of the **Preferences** module cannot be used together. +- The C APIs and ArkTS APIs of the **Preferences** module cannot be used together. +- The maximum key length is 1024 bytes, and the maximum value length is 16 MB. ## Available APIs @@ -28,7 +29,7 @@ For details about the APIs, see [Preferences](../reference/apis-arkdata/_prefere | int OH_Preferences_UnregisterDataObserver (OH_Preferences \*preference, void \*context, OH_PreferencesDataObserver observer, const char \*keys[], uint32_t keyCount) | Unsubscribes from data changes of the specified keys.| | int OH_Preferences_IsStorageTypeSupported (Preferences_StorageType type, bool \*isSupported) | Checks whether the specified storage type is supported.| | OH_PreferencesOption \* OH_PreferencesOption_Create (void) | Creates an **OH_PreferencesOption** instance and a pointer to it. If this pointer is no longer required, use **OH_PreferencesOption_Destroy** to destroy it. Otherwise, memory leaks may occur.| -| int OH_PreferencesOption_SetFileName (OH_PreferencesOption \*option, const char \*fileName) | Sets the file name for an **OH_PreferencesOption** instance.| +| int OH_PreferencesOption_SetFileName (OH_PreferencesOption \*option, const char \*fileName) | Sets the file name for an **OH_PreferencesOption** instance. The name must be longer than 0 bytes and less than or equal to 255 bytes, and cannot contain or end with slashes (/).| | int OH_PreferencesOption_SetBundleName (OH_PreferencesOption \*option, const char \*bundleName) | Sets the bundle name for an OH_PreferencesOption instance.| | int OH_PreferencesOption_SetDataGroupId (OH_PreferencesOption \*option, const char \*dataGroupId) | Sets the application group ID for an **OH_PreferencesOption** instance.| | int OH_PreferencesOption_SetStorageType (OH_PreferencesOption \*option, Preferences_StorageType type) | Sets the storage type for an **OH_PreferencesOption** instance.| @@ -128,14 +129,14 @@ if (ret != PREFERENCES_OK) { } // Set the storage type for the PreferencesOption instance. Before the setting, call OH_Preferences_IsStorageTypeSupported to check whether the storage type is supported. -bool isClkvSupported = false; -ret = OH_Preferences_IsStorageTypeSupported(Preferences_StorageType::PREFERENCES_STORAGE_CLKV, &isClkvSupported); +bool isGskvSupported = false; +ret = OH_Preferences_IsStorageTypeSupported(Preferences_StorageType::PREFERENCES_STORAGE_GSKV, &isGskvSupported); if (ret != PREFERENCES_OK) { (void)OH_PreferencesOption_Destroy(option); // Error handling. } -if (isClkvSupported) { - ret = OH_PreferencesOption_SetStorageType(option, Preferences_StorageType::PREFERENCES_STORAGE_CLKV); +if (isGskvSupported) { + ret = OH_PreferencesOption_SetStorageType(option, Preferences_StorageType::PREFERENCES_STORAGE_GSKV); if (ret != PREFERENCES_OK) { (void)OH_PreferencesOption_Destroy(option); // Error handling. diff --git a/en/application-dev/database/share-data-by-datashareextensionability.md b/en/application-dev/database/share-data-by-datashareextensionability.md index b3de68a61fd9c54cc0d6f5013b95e18df6e20c72..56555ab4f1eb86fef8fc2964d9dfb44d32fb4656 100644 --- a/en/application-dev/database/share-data-by-datashareextensionability.md +++ b/en/application-dev/database/share-data-by-datashareextensionability.md @@ -5,7 +5,7 @@ If complex services are involved in cross-application data access, you can use **DataShareExtensionAbility** to start the application of the data provider to implement data access. -You need to implement flexible service logics via callbacks of the service provider. +You need to implement flexible service logics via callbacks of the service provider. ## Working Principles @@ -27,7 +27,6 @@ There are two roles in **DataShare**: - The **ResultSet** module is implemented through shared memory. Shared memory stores the result sets, and interfaces are provided to traverse result sets. - ## How to Develop @@ -144,24 +143,28 @@ Before implementing a **DataShare** service, you need to create a **DataShareExt | -------- | -------- | -------- | | name | Ability name, corresponding to the **ExtensionAbility** class name derived from **Ability**.| Yes| | type | Ability type. The value **dataShare** indicates that the development is based on the **datashare** template.| Yes| - | uri | Unique identifier for the data consumer to access the data provider.| Yes| + | uri | Unique identifier for the data consumer to access the data provider.
You can add suffix parameters to set the target access object. The suffix parameters must be added to the end of the URI and start with a question mark (?).
- Currently, only the **user** parameter is supported.
- The value of **user** must be an integer. It indicates the user ID of the data provider. If It is not specified, the user ID of the data consumer is used. For details about the definition of **user** and how to obtain it, see [user](../reference/apis-basic-services-kit/js-apis-osAccount.md#getactivatedosaccountlocalids9).
- Currently, the data consumer in cross-user access must have the ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS permission.| Yes| | exported | Whether it is visible to other applications. Data sharing is allowed only when the value is **true**.| Yes| - | readPermission | Permission required for accessing data. If this parameter is not set, read permission verification is not performed by default.| No| - | writePermission | Permission required for modifying data. If this parameter is not set, write permission verification is not performed by default.| No| + | readPermission | Permission required for accessing data. If this parameter is not set, read permission verification is not performed by default.
**NOTE**: The permission constraints for **DataShareExtensionAbility** are different from that for silent access. It is important to understand the difference and prevent confusion. For details, see [Silent Access via DatamgrService](share-data-by-silent-access.md).| No| + | writePermission | Permission required for modifying data. If this parameter is not set, write permission verification is not performed by default.
**NOTE**: The permission constraints for **DataShareExtensionAbility** are different from that for silent access. It is important to understand the difference and prevent confusion. For details, see [Silent Access via DatamgrService](share-data-by-silent-access.md).| No| | metadata | Silent access configuration, which includes the following:
- **name**: identifies the configuration, which has a fixed value of **ohos.extension.dataShare**.
- **resource**: has a fixed value of **$profile:data_share_config**, which indicates that the profile name is **data_share_config.json**.| **metadata** is mandatory when the ability launch type is **singleton**. For details about the ability launch type, see **launchType** in the [Internal Structure of the abilities Attribute](../quick-start/module-structure.md#internal-structure-of-the-abilities-attribute).| **module.json5 example** ```json + // The following uses settingsdata as an example. "extensionAbilities": [ { - "srcEntry": "./ets/DataShareExtAbility/DataShareExtAbility.ets", - "name": "DataShareExtAbility", + "srcEntry": "./ets/DataAbility/DataExtAbility.ets", + "name": "DataExtAbility", "icon": "$media:icon", "description": "$string:description_datashareextability", "type": "dataShare", - "uri": "datashare://com.samples.datasharetest.DataShare", + "uri": "datashare://com.ohos.settingsdata.DataAbility", "exported": true, + // Configure permissions based on actual situation. The permissions configured here are examples only. + "readPermission": "ohos.permission.MANAGE_SECURE_SETTINGS", + "writePermission": "ohos.permission.MANAGE_SECURE_SETTINGS", "metadata": [{"name": "ohos.extension.dataShare", "resource": "$profile:data_share_config"}] } ] @@ -172,8 +175,8 @@ Before implementing a **DataShare** service, you need to create a **DataShareExt | Field | Description | Mandatory| | ------------------- | ------------------------------------------------------------ | ---- | | tableConfig | Configuration label, which includes **uri** and **crossUserMode**.
- **uri**: specifies the range for which the configuration takes effect. The URI supports the following formats in descending order by priority:
1. *****: indicates all databases and tables.
2. **datashare:///{*bundleName*}/{*moduleName*}/{*storeName*}**: specifies a database.
3. **datashare:///{*bundleName*}/{*moduleName*}/{*storeName*}/{*tableName*}**: specifies a table.
If URIs of different formats are configured, only the URI with the higher priority takes effect.
- **crossUserMode**: Whether to share data between multiple users.
The value **1** means to share data between multiple users, and the value **2** means the opposite.| Yes | - | isSilentProxyEnable | Whether to enable silent access for this ExtensionAbility.
The value **true** means to enable silent access, and the value **false** means the opposite.
The default value is **true**.
If an application has multiple ExtensionAbilities and this field is set to **false** for one of them, silent access is disabled for the application.
If the data provider has called **enableSilentProxy** or **disableSilentProxy**, silent access is enabled or disabled based on the API settings. Otherwise, the setting here takes effect.| No | - | launchInfos | Launch information, which includes **storeId** and **tableNames**.
If the data in a table involved in the configuration changes, an extensionAbility will be started based on the URI in **extensionAbilities**. You need to set this parameter only when the service needs to start an extensionAbility to process data that is not actively changed by the service.
- **storeId**: database name, excluding the file name extension. For example, if the database name is **test.db**, set this parameter to **test**.
- **tableNames**: names of the database tables. Any change in a table will start an an extensionAbility. | No | + | isSilentProxyEnable | Whether to enable silent access for this ExtensionAbility.
The value **true** means to enable silent access, and the value **false** means the opposite.
The default value is **true**.
If an application has multiple ExtensionAbilities and this field is set to **false** for one of them, silent access is disabled for the application.
If the data provider has called **enableSilentProxy** or **disableSilentProxy**, silent access is enabled or disabled based on the API settings. Otherwise, the setting here takes effect.| No | + | launchInfos | Launch information, which includes **storeId** and **tableNames**.
If the data in a table involved in the configuration changes, an extensionAbility will be started based on the URI in **extensionAbilities**. You need to set this parameter only when the service needs to start an extensionAbility to process data that is not actively changed by the service.
- **storeId**: database name, excluding the file name extension. For example, if the database name is **test.db**, set this parameter to **test**.
- **tableNames**: names of the database tables. Any change in a table will start an extensionAbility.| No | **data_share_config.json Example** @@ -185,7 +188,7 @@ Before implementing a **DataShare** service, you need to create a **DataShareExt "crossUserMode":1 }, { - "uri":"datashare:///com.acts.datasharetest/entry/DB00", + "uri":"datashare:///com.ohos.settingsdata/entry/DB00", "crossUserMode":1 }, { @@ -219,7 +222,7 @@ Before implementing a **DataShare** service, you need to create a **DataShareExt ```ts // Different from the URI defined in the module.json5 file, the URI passed in the parameter has an extra slash (/), because there is a DeviceID parameter between the second and the third slash (/). - let dseUri = ('datashare:///com.samples.datasharetest.DataShare'); + let dseUri = ('datashare:///com.ohos.settingsdata.DataAbility'); ``` 3. Create a **DataShareHelper** instance. @@ -307,4 +310,4 @@ Before implementing a **DataShare** service, you need to create a **DataShareExt // Close the DataShareHelper instance. (dsHelper as dataShare.DataShareHelper).close(); } - ``` \ No newline at end of file + ``` diff --git a/en/application-dev/database/share-data-by-silent-access.md b/en/application-dev/database/share-data-by-silent-access.md index 6fc7a1679e48f29f07737310ccdcc26f46209048..d7f1e22b3e916acf05a5962dce3ae4626e114219 100644 --- a/en/application-dev/database/share-data-by-silent-access.md +++ b/en/application-dev/database/share-data-by-silent-access.md @@ -24,7 +24,7 @@ If the service processing is too complex to be encapsulated, use [DataShareExten - Process data: process data, in the JSON or byte format, managed by **DatamgrService**. It is stored in the **DatamgrService** sandbox directory, and is automatically deleted 10 days after no subscription. -- Dynamic data: data stored in the memory of a device. It is automatically deleted after the device is restarted. Currently, the dynamic data refers to only the data set by **enableSilentProxy** and **disableSilentProxy**. +- Dynamic data: data stored in the memory of a device. It is automatically deleted after the device is restarted. The dynamic data refers to only the data set by **enableSilentProxy** and **disableSilentProxy**. | Data Type | Location | Data Format | Validity Period | Usage | @@ -49,13 +49,17 @@ If the service processing is too complex to be encapsulated, use [DataShareExten - You can add parameters to the URI to specify the access mode and target object. When adding parameters to a URI, note that the URI must be in the **datashareproxy://{*bundleName*}/{*dataPath*}?{*arg1*}&{*arg2*}** format. Otherwise, the parameters do not take effect. - The parameters to add start with a question mark (?) and separated by an ampersand (&). Consecutive symbols (for example, ???? or &&&) are considered as one. Currently, only **Proxy** and **appIndex** can be added. If the URI contains multiple question marks (?), the parameter following the question mark (?) must be **Proxy**. Otherwise, this parameter does not take effect. + The parameters to add start with a question mark (?) and separated by an ampersand (&). Consecutive symbols (for example, ???? or &&&) are considered as one. Currently, only the **Proxy**, **appIndex**, and **user** parameters are supported. If the URI contains multiple question marks (?), the parameter following the question mark (?) must be **Proxy**. Otherwise, this parameter does not take effect. - **Proxy** specifies the data access mode used by the data consumer. The value can be **true** or **false**. The value **true** indicates the silent access mode, and **false** indicates the non-silent access mode. - - **appIndex** specifies the index of an application clone. The value must be an integer starting from 1. This parameter takes effect only for cloned applications. For details about **appIndex**, see [BundleInfo](../reference/apis-ability-kit/js-apis-bundleManager-bundleInfo.md). If **appIndex** is **0** or left empty, the data consumer accesses the data provider application. + - **appIndex** specifies the index of an application clone. The value must be an integer starting from 1. This parameter takes effect only for cloned applications. For details about **appIndex**, see [BundleInfo](../reference/apis-ability-kit/js-apis-bundleManager-bundleInfo.md). If **appIndex** is **0** or left empty, the data consumer accesses the application of the data provider. - Currently, cloned applications can be accessed only in silent mode. When setting the URI and parameters for accessing an application clone, both **Proxy** and **appIndex** are mandatory. For example, **datashareproxy://{bundleName}/{dataPath}?Proxy=true&appIndex=1** indicates that the data consumer accesses the first clone of the application in silent access mode. + Currently, cloned applications are supported only in silent access mode. When setting the URI and parameters for accessing an application clone, both **Proxy** and **appIndex** must be set. For example, **datashareproxy://{bundleName}/{dataPath}?Proxy=true&appIndex=1** indicates that the data consumer will access the first clone of the application in silent access mode. + + - The value of **user** must be an integer. It is the user ID of the data provider. For details about the definition of **user** and how to obtain it, see [user](../reference/apis-basic-services-kit/js-apis-osAccount.md#getactivatedosaccountlocalids9). If **user** is not set, the user ID of the data consumer is used. + + Currently, only the main space and privacy space support cross-user access, and the data consumer must have the ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS permission. ## Constraints @@ -84,7 +88,7 @@ Most of the APIs for silent access are executed asynchronously in callback or pr | query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>, callback: AsyncCallback<DataShareResultSet>): void | Queries data in the database. | | update(uri: string, predicates: dataSharePredicates.DataSharePredicates, value: ValuesBucket, callback: AsyncCallback<number>): void | Updates data in the database. | | addTemplate(uri: string, subscriberId: string, template: Template): void | Adds a data template with the specified subscriber. | -| on(type: 'rdbDataChange', uris: Array<string>, templateId: TemplateId, callback: AsyncCallback<RdbDataChangeNode>): Array<OperationResult | Subscribes to the changes of the data corresponding to the specified URI and template.| +| on(type: 'rdbDataChange', uris: Array<string>, templateId: TemplateId, callback: AsyncCallback<RdbDataChangeNode>): Array<OperationResult> | Subscribes to the changes of the data corresponding to the specified URI and template.| ### APIs for Accessing Process Data @@ -106,7 +110,7 @@ Most of the APIs for silent access are executed asynchronously in callback or pr The following walks you through on how to share an RDB store. -### Data Provider Application +### Data Provider Application Development 1. In the **module.json5** file, set the data to be shared in **proxyData**. For details about the configuration, see [module.json5 Configuration File](../quick-start/module-configuration-file.md). @@ -115,18 +119,22 @@ The following walks you through on how to share an RDB store. | Name | Description | Mandatory | | ----------------------- | ---------------------------------------- | ---- | | uri | URI of the data proxy, which is the unique identifier for cross-application data access. | Yes | - | requiredReadPermission | Permission required for reading data from the data proxy. If this parameter is not set, other applications are not allowed to access data. For details about the permissions, see [Application Permissions](../security/AccessToken/app-permissions.md). | No | - | requiredWritePermission | Permission required for writing data to the data proxy. If this parameter is not set, other applications are not allowed to write data to the data proxy. For details about the permissions, see [Application Permissions](../security/AccessToken/app-permissions.md). | No | + | requiredReadPermission | Permission required for reading data from the data proxy. If this parameter is not set, other applications are not allowed to access data. For details about the permissions, see [Application Permissions](../security/AccessToken/app-permissions.md).
**NOTE**: The permission constraints for silent access are different from that for **DataShareExtensionAbility**. It is important to understand the difference and prevent confusion. For details, see [DataShareExtensionAbility](share-data-by-datashareextensionability.md). | No | + | requiredWritePermission | Permission required for writing data to the data proxy. If this parameter is not set, other applications are not allowed to write data to the data proxy. For details about the permissions, see [Application Permissions](../security/AccessToken/app-permissions.md).
**NOTE**: The permission constraints for silent access are different from that for **DataShareExtensionAbility**. It is important to understand the difference and prevent confusion. For details, see [DataShareExtensionAbility](share-data-by-datashareextensionability.md). | No | | metadata | Metadata of the data source, including the **name** and **resource** fields.
The **name** field identifies the configuration, which has a fixed value of **dataProperties**.
The value of **resource** is **$profile:{fileName}**, indicating that the name of the configuration file is **{fileName}.json**.| Yes | + A data table contains all the data accessible through a URI. Ensure that all data in a table falls under the same permission scope. To effectively implement data isolation at the table level, you are advised to store data with different scopes in separate tables and configure appropriate permission constraints for each table. For security-critical data, you are advised to configure an allowlist of data consumers to prevent unauthorized access. For details, see the **allowLists** field in the **my_config.json** example. + **module.json5 example** ```json - "proxyData":[ + // The following uses settingsdata as an example. + "proxyData": [ { - "uri": "datashareproxy://com.acts.ohos.data.datasharetest/test", - "requiredReadPermission": "ohos.permission.GET_BUNDLE_INFO", - "requiredWritePermission": "ohos.permission.KEEP_BACKGROUND_RUNNING", + "uri": "datashareproxy://com.ohos.settingsdata/entry/settingsdata/USER_SETTINGSDATA_SECURE", + // Configure permissions based on actual situation. The permissions configured here are examples only. + "requiredReadPermission": "ohos.permission.MANAGE_SECURE_SETTINGS", + "requiredWritePermission": "ohos.permission.MANAGE_SECURE_SETTINGS", "metadata": { "name": "dataProperties", "resource": "$profile:my_config" @@ -138,9 +146,10 @@ The following walks you through on how to share an RDB store. | Name | Description | Mandatory | | ----- | ---------------------------------------- | ---- | - | path | Data source path, in the **Database_name/Table_name** format. Currently, only RDB stores are supported. | Yes | + | path | Data source path, in the **Database_name/Table_name** format. Currently, only RDB stores are supported. | Yes | | type | Database type. Currently, only **rdb** is supported. | Yes | - | scope | Scope of the database.
- **module** indicates that the database is located in this module.
- **application** indicates that the database is located in this application.| No | + | scope | Scope of the database.
1. **module** indicates that the database is located in this module.
2. **application** indicates that the database is located in this application.| No | + | allowLists | List of applications that can access the data.
It allows a maximum of 256 records. In cross-application data access, the data consumers are checked against the settings here. If the data consumer is not listed in **allowlists**, the data access will be rejected.
If **allowLists** is not configured, allowlist verification is skipped. No matter whether **allowLists** is configured, the read and write permissions in [Table 1](#data-provider-application-development) are always verified.
**allowLists** consists of two fields:
- **appIdentifier**: unique identifier (string) of the application allocated by the cloud. The data provider should obtain it from the data consumer. For details about **appIdentifier**, see [SignatureInfo](../reference/apis-ability-kit/js-apis-bundleManager-bundleInfo.md#signatureinfo).
- **onlyMain**: a Boolean value indicating whether the data is accessible only to the application. The value **true** means only the application can access the data. The value **false** means both the application and its clone can access the data. This feature is available only to silent access. | No | **my_config.json example** @@ -148,11 +157,15 @@ The following walks you through on how to share an RDB store. { "path": "DB00/TBL00", "type": "rdb", - "scope": "application" + "scope": "application", + "allowLists":[ + {"appIdentifier": "appIdentifier1", "onlyMain": false}, + {"appIdentifier": "appIdentifier2", "onlyMain": true} + ] } ``` -### Data Consumer Application +### Data Consumer Application Development 1. Import dependencies. @@ -167,7 +180,7 @@ The following walks you through on how to share an RDB store. 2. Define the URI string for communicating with the data provider. ```ts - let dseUri = ('datashareproxy://com.acts.ohos.data.datasharetest/test'); + let dseUri = ('datashareproxy://com.ohos.settingsdata/entry/settingsdata/USER_SETTINGSDATA_SECURE'); ``` 3. Create a **DataShareHelper** instance. @@ -256,7 +269,7 @@ The following walks you through on how to share an RDB store. } let templateId: dataShare.TemplateId = { subscriberId: "111", - bundleNameOfOwner: "com.acts.ohos.data.datasharetestclient" + bundleNameOfOwner: "com.ohos.settingsdata" } if(dsHelper != undefined) { // When DatamgrService modifies data, onCallback is invoked to return the data queried based on the rules in the template. @@ -268,7 +281,7 @@ The following walks you through on how to share an RDB store. The following walks you through on how to host process data. -### (Optional) Data Provider Application +### (Optional) Data Provider Application Development In the **module.json5** file, set the data to be hosted in **proxyData**. For details about the configuration, see [module.json5 Configuration File](../quick-start/module-configuration-file.md). @@ -283,22 +296,24 @@ In the **module.json5** file, set the data to be hosted in **proxyData**. For de | Name | Description | Mandatory | | ----------------------- | ----------------------------- | ---- | | uri | URI of the data proxy, which is the unique identifier for cross-application data access. | Yes | -| requiredReadPermission | Permission required for reading data from the data proxy. If this parameter is not set, other applications are not allowed to access data. For details about the permissions, see [Application Permissions](../security/AccessToken/app-permissions.md).| No | -| requiredWritePermission | Permission required for writing data to the data proxy. If this parameter is not set, other applications are not allowed to write data to the dta proxy. For details about the permissions, see [Application Permissions](../security/AccessToken/app-permissions.md).| No | +| requiredReadPermission | Permission required for reading data from the data proxy. If this parameter is not set, other applications are not allowed to access data. For details about the permissions, see [Application Permissions](../security/AccessToken/app-permissions.md).
**NOTE**: The permission constraints for silent access are different from that for **DataShareExtensionAbility**. It is important to understand the difference and prevent confusion. For details, see [DataShareExtensionAbility](share-data-by-datashareextensionability.md).| No | +| requiredWritePermission | Permission required for writing data to the data proxy. If this parameter is not set, other applications are not allowed to write data to the dta proxy. For details about the permissions, see [Application Permissions](../security/AccessToken/app-permissions.md).
**NOTE**: The permission constraints for silent access are different from that for **DataShareExtensionAbility**. It is important to understand the difference and prevent confusion. For details, see [DataShareExtensionAbility](share-data-by-datashareextensionability.md).| No | **module.json5 example** ```json +// The following is an example only. Configure it as required. "proxyData": [ { "uri": "datashareproxy://com.acts.ohos.data.datasharetest/weather", - "requiredReadPermission": "ohos.permission.GET_BUNDLE_INFO", + // Configure permissions based on actual situation. The permissions configured here are examples only. + "requiredReadPermission": "ohos.permission.READ_WEATHER_DATA", "requiredWritePermission": "ohos.permission.KEEP_BACKGROUND_RUNNING" } ] ``` -### Data Consumer Application +### Data Consumer Application Development 1. Import dependencies. @@ -360,7 +375,7 @@ In the **module.json5** file, set the data to be hosted in **proxyData**. For de Only the data provider is involved. The following walks you through on how to dynamically enable silent access. -### Data Provider Application +### Data Provider Application Development The data provider calls the **enableSilentProxy** API to dynamically enable silent access. This API must be used with the **isSilentProxyEnable** field in the **data_share_config.json** file. For details, see [**data_share_config.json** configuration](./share-data-by-datashareextensionability.md). @@ -382,7 +397,7 @@ The data provider calls the **enableSilentProxy** API to dynamically enable sile 2. Define the URI string for communicating with the data provider. ```ts - let dseUri = ('datashare:///com.acts.datasharetest/entry/DB00/TBL00'); + let dseUri = ('datashare:///com.ohos.settingsdata/entry/DB00/TBL00'); ``` 3. Create a **DataShareHelper** instance. @@ -397,3 +412,5 @@ The data provider calls the **enableSilentProxy** API to dynamically enable sile } } ``` + + diff --git a/en/application-dev/database/sync-app-data-across-devices-overview.md b/en/application-dev/database/sync-app-data-across-devices-overview.md index 131d8a3ac85dd78e0cc3331d19eb2aece714094c..0405ce79d275337fbb9a15025004bb8759b0417e 100644 --- a/en/application-dev/database/sync-app-data-across-devices-overview.md +++ b/en/application-dev/database/sync-app-data-across-devices-overview.md @@ -1,4 +1,4 @@ -# Distributed Application Data Sync Overview +# Overview of Distributed Application Data Sync ## When to Use diff --git a/en/application-dev/database/unified-data-channels.md b/en/application-dev/database/unified-data-channels.md index 437895deac49ed04ef87531d23b6effa5f5bb609..59d69b606f87fa8f58de61640f967c27fc9b7932 100644 --- a/en/application-dev/database/unified-data-channels.md +++ b/en/application-dev/database/unified-data-channels.md @@ -13,6 +13,8 @@ The unified data channel provides cross-application data access for various serv The unified data channel is implemented by the system ability provided by the UDMF. When an application (data provider) needs to share data, it calls the **insertData()** method provided by the UDMF to write the data to the UDMF data channel, and calls UDMF **updateData()** or **deleteData()** to update or delete the data saved by the application. The target application (data consumer) can access the data by the APIs provided by the UDMF. The UDMF manages the data lifecycle in a unified manner and deletes the data that has been stored for more than one hour every hour. +Avoid using **unifiedDataChannel** APIs in multi-threaded calls. + The unified data object (**UnifiedData**) is uniquely identified by a URI in the UDMF data channel. The URI is in the **udmf://*intention*/*bundleName*/*groupId*** format, where: + **udmf**: protocol used to provide the data channel. diff --git a/en/application-dev/database/uniform-data-structure.md b/en/application-dev/database/uniform-data-structure.md index 5fb9204e287fbcdd7ede8374c5337e18d49e19e5..3534ea4d32eaa8e98a4a33a0fde32757fb181244 100644 --- a/en/application-dev/database/uniform-data-structure.md +++ b/en/application-dev/database/uniform-data-structure.md @@ -13,11 +13,11 @@ The following table lists the uniform data structs provided by the UDMF. | Data Struct | Data Type | Description | |-----------------------------------------------------------------------------------------------------| :-------------------: |------| -| [PlainText](../reference/apis-arkdata/js-apis-data-uniformDataStruct.md#plaintext) | 'general.plain-text' | Plain text | -| [Hyperlink](../reference/apis-arkdata/js-apis-data-uniformDataStruct.md#hyperlink) | 'general.hyperlink' | Hyperlink | -| [HTML](../reference/apis-arkdata/js-apis-data-uniformDataStruct.md#html) | 'general.html' | HyperText Markup Language (HTML) | -| [OpenHarmonyAppItem](../reference/apis-arkdata/js-apis-data-uniformDataStruct.md#openharmonyappitem) | 'openharmony.app-item' | Icon | -| [ContentForm](../reference/apis-arkdata/js-apis-data-uniformDataStruct.md#contentform14) | 'general.content-form' | Content widget| +| [PlainText](../reference/apis-arkdata/js-apis-data-uniformDataStruct.md#plaintext) | 'general.plain-text' | Plain text. | +| [Hyperlink](../reference/apis-arkdata/js-apis-data-uniformDataStruct.md#hyperlink) | 'general.hyperlink' | Hyperlink. | +| [HTML](../reference/apis-arkdata/js-apis-data-uniformDataStruct.md#html) | 'general.html' | HyperText Markup Language (HTML). | +| [OpenHarmonyAppItem](../reference/apis-arkdata/js-apis-data-uniformDataStruct.md#openharmonyappitem) | 'openharmony.app-item' | Icon. | +| [ContentForm](../reference/apis-arkdata/js-apis-data-uniformDataStruct.md#contentform14) | 'general.content-form' | Content widget.| ## How to Develop diff --git a/en/application-dev/database/uniform-data-type-list.md b/en/application-dev/database/uniform-data-type-list.md index 18d61615b81ba229db9b95459034763ee3656190..d782b0cbd1f97335d074f40bf72168a2674b8ff5 100644 --- a/en/application-dev/database/uniform-data-type-list.md +++ b/en/application-dev/database/uniform-data-type-list.md @@ -17,12 +17,12 @@ Generic UTDs define universal data types that can be identified by a majority of | general.file | general.entity | - | - | Generic file type. | | general.directory | general.entity | - | - | Generic directory type. | | general.folder | general.directory | - | - | Generic folder type. | -| general.symlink | general.entity | - | - | Generic symbolic link type. | +| general.symlink | general.entity | - | - | Generic symbolic link type. | | general.composite-object | general.object | - | - | Generic composite content type, for example, a PDF file that contains text and images.| | general.media | general.object | - | - | Generic media type. | -| general.content-form | general.object | - | - | Data content card type| +| general.content-form | general.object | - | - | Data content widget type.| | general.image | general.media | - | - | Generic image type. | -| general.png | general.image | .png | image/png | PNG image format. | +| general.png | general.image | .png | image/png | PNG image format. | | general.jpeg | general.image | .jpg, .jpeg,.jpe | image/jpeg | JPEG image format. | | general.tiff | general.image | .tif, .tiff | image/tiff | TIFF image format. | | general.raw-image | general.image | - | - | Generic raw image type. | @@ -51,7 +51,7 @@ Generic UTDs define universal data types that can be identified by a majority of | general.mpeg-4 | general.video | .mp4, .mp4v, .mpeg4 | video/mp4, video/mp4v | MPEG-4 video format. | | general.3gpp | general.video | .3gp, .3gpp | video/3gpp | 3GPP video format. | | general.3gpp2 | general.video | .3g2, .3gp2, .3gpp2 | video/3gpp2 | 3GPP2 video format. | -| general.vob | general.video | .vob | video/mpeg, video/x-ms-vob | Video Object (VOB) format, a container format in DVD video media. | +| general.vob | general.video | .vob | video/mpeg, video/x-ms-vob | Video Object (VOB) format, a container format in DVD video media. | | general.dif-video | general.video | .dif | video/dv | DIF video format. | | general.dv-video | general.video | .dv | video/dv | DV video format. | | general.flc-animation | general.video | .fli, .flc | video/fli, video/flc | FLIC animation file format. | @@ -85,7 +85,7 @@ Generic UTDs define universal data types that can be identified by a majority of | general.mp2 | general.audio | .mp2 | audio/mpeg | MP2 audio format. | | general.mpeg-audio | general.audio | .mpga | audio/mpeg | MPEG audio format. | | general.mxmf | general.audio | .mxmf | audio/mobile-xmf | Mobile XMF audio format. | -| general.ota | general.audio | .ota | audio/midi | OTA ringtone audio format. | +| general.ota | general.audio | .ota | audio/midi | OTA ringtone audio format. | | general.pls | general.audio | .pls | audio/x-scpls | Multimedia playlist format. | | general.rtttl | general.audio | .rtttl | audio/midi | RTTTL format. | | general.psid | general.audio | .sid, .psid | audio/prs.sid | SID audio format. | @@ -139,7 +139,7 @@ Generic UTDs define universal data types that can be identified by a majority of | general.calendar | general.text | - | - | Generic calendar data type. | | general.vcs | general.calendar | .vcs | text/calendar | vCalendar format. | | general.ics | general.calendar | .ics | text/calendar | iCalendar format. | -| general.comma-separated-values-text | general.delimited-values-text | .csv | text/csv | Comma-separated values (CSV). | +| general.comma-separated-values-text | general.delimited-values-text | .csv | text/csv | Comma-separated values (CSV). | | general.tab-separated-values-text | general.delimited-values-text | .tsv | text/tab-separated-values | Tab-separated values (TSV). | | general.mathml | general.xml | .mml | text/mathml,application/mathml+xml | Mathematical markup language file format. | | general.xhtml | general.xml | .xhtml | application/xhtml+xml | Extended hypertext markup language file format. | @@ -152,9 +152,9 @@ Generic UTDs define universal data types that can be identified by a majority of | general.c-source | general.source-code | .c | text/x-csrc | C source code. | | general.c-header | general.source-code | .h | text/x-chdr | C header file. | | general.c-plus-plus-source | general.source-code | .cp, .cpp, .c++, .cc, .cxx | text/x-c++src | C++ source code. | -| general.c-plus-plus-header | general.source-code | .hpp, .h++ , .hxx, .hh | text/x-c++hdr | C++ header file. | +| general.c-plus-plus-header | general.source-code | .hpp, .h++ , .hxx, .hh | text/x-c++hdr | C++ header file. | | general.java-source | general.source-code | .java, .jav | text/x-java | Java source code. | -| general.boo-source | general.source-code | .boo | text/x-boo | BOO source code. | +| general.boo-source | general.source-code | .boo | text/x-boo | BOO source code. | | general.d-source | general.source-code | .d | text/x-dsrc | D source code. | | general.html-component | general.source-code | .htc | text/x-component | HTML component. | | general.pascal-source | general.source-code | .p,.pas | text/x-pascal | Pascal source code. | @@ -177,7 +177,7 @@ Generic UTDs define universal data types that can be identified by a majority of | general.python-script | general.shell-script | .py | text/x-python-script | Python script. | | general.ruby-script | general.shell-script | .rb, .rbw | text/ruby-script | Ruby script. | | general.php-script | general.shell-script | .php, .php3, .php4, .ph3, .ph4, .phtml | text/x-php-script, text/php, application/php | PHP script. | -| general.uri | general.object | - | - | Uniform Resource Identifier (URI). | +| general.uri | general.object | - | - | Uniform Resource Identifier (URI). | | general.file-uri | general.uri | - | - | File URI. | | general.navigation | general.object | - | - | Generic navigation data type. | | general.location | general.navigation | - | - | Navigation location. | @@ -189,7 +189,7 @@ Generic UTDs define universal data types that can be identified by a majority of | general.c-object | general.executable | .o | application/x-object | Compiled C file. | | general.octet-stream | general.object | - | application/octet-stream - | Any binary data type. | | general.mesh-model | general.object | .msh,.mesh,.silo | model/mesh | 3D mesh model format. | -| general.certificate | general.object | - | - | Basic certificate type. | +| general.certificate | general.object | - | - | Generic certificate type. | | general.cer-certificate | general.certificate | .cer | application/pkix-cert | Internet certificate format. | | general.crt-certificate | general.certificate | .crt | application/x-x509-ca-cert,application/x-x509-server-cert,application/x-x509-user-cert | Certificate format. | | general.crl-certificate | general.certificate | .crl | application/x-pkix-crl | Certificate revocation list (CRL) format. | @@ -201,7 +201,7 @@ Generic UTDs define universal data types that can be identified by a majority of | general.opentype-font | general.font | .otf | font/otf | OpenType font. | | general.ofd | general.composite-object | .ofd | - | Open Fixed-layout Document (OFD) format. | | general.prn | general.composite-object | .prn | - | PRN format. | -| general.ebook | general.composite-object | - | - | Generic eBook type. | +| general.ebook | general.composite-object | - | - | Generic eBook type. | | general.epub | general.ebook | .epub | application/epub+zip | Electronic Publication (EPUB) format. | @@ -209,20 +209,20 @@ Generic UTDs define universal data types that can be identified by a majority of The system-specific UTDs are closely related to a platform or an operating system and are used for cross-application interaction within the system or platform. The IDs of system-specific UTDs are in the **os-name**.xxx format. The following table lists the system-specific UTDs prebuilt in the system. | UTD ID | **BelongingTo** | **File Name Extension** | **MIME Type** | **Description** | |----------------------------|--------------------------|---------------------------------------|--------------------------------------------------------------------|----------------------------------| -| openharmony.form | general.object | - |- | Form type defined for OpenHarmony. | -| openharmony.app-item | general.object | - |- | Home screen icon defined for OpenHarmony. | -| openharmony.want | general.object | - |- | Want data type defined for OpenHarmony. | -| openharmony.atomic-service | general.object | - |- | Atomic service defined for OpenHarmony. | -| openharmony.package | general.directory | - |- | Package defined for OpenHarmony. | -| openharmony.hap | openharmony.package | .hap |- | Harmony Ability Package (HAP) defined for OpenHarmony. | +| openharmony.form | general.object | - |- | Form type defined by OpenHarmony. | +| openharmony.app-item | general.object | - |- | Home screen icon defined by OpenHarmony. | +| openharmony.want | general.object | - |- | Want data type defined by OpenHarmony. | +| openharmony.atomic-service | general.object | - |- | Atomic service defined by OpenHarmony. | +| openharmony.package | general.directory | - |- | Package defined by OpenHarmony. | +| openharmony.hap | openharmony.package | .hap |- | Harmony Ability Package (HAP) defined by OpenHarmony. | | openharmony.app | openharmony.package | .app |- | Application package type defined by the system. | | openharmony.hsp | openharmony.package | .hsp |- | Dynamic shared package defined by the system. | | openharmony.har | openharmony.package | .har |- | Static shared package defined by the system. | -| openharmony.hdoc | general.composite-object | .hdoc |- | Notepad file format defined for OpenHarmony. | -| openharmony.hinote | general.composite-object | .hinote |- | Note file format defined for OpenHarmony. | -| openharmony.styled-string | general.composite-object | - |- | String type defined for OpenHarmony. | -| openharmony.moving-photo | general.media | - |- | Moving photo defined for OpenHarmony.| -| openharmony.pixel-map | general.image | - |- | Pixel Map defined for OpenHarmony. | +| openharmony.hdoc | general.composite-object | .hdoc |- | Notepad file format defined by OpenHarmony. | +| openharmony.hinote | general.composite-object | .hinote |- | Note file format defined by OpenHarmony. | +| openharmony.styled-string | general.composite-object | - |- | String type defined by OpenHarmony. | +| openharmony.moving-photo | general.media | - |- | Moving photo defined by OpenHarmony.| +| openharmony.pixel-map | general.image | - |- | Pixel Map defined by OpenHarmony. | | macos.dmg | general.disk-image | .dmg | application/x-apple-diskimage | Installation package format defined by MacOS. | | debian.deb | general.archive | .deb,.udeb | application/x-debian-package,application/vnd.debian.binary-package | Software package format defined by Debian. | | com.android.apk | general.archive | .apk, .apks, .aab, .xapk, .apkm, .akp | application/vnd.android.package-archive | Android application installation package format. | @@ -240,7 +240,7 @@ Application-specific UTDs are defined and maintained by a specific application o | com.microsoft.windows-media-wm | general.video,com.microsoft.advanced-systems-format | .wm | video/x-ms-wm | Microsoft Windows WM video format. | | com.microsoft.windows-media-wmv | general.video,com.microsoft.advanced-systems-format | .wmv | video/x-ms-wmv | Microsoft Windows WMV video format. | | com.microsoft.windows-media-wmp | general.video,com.microsoft.advanced-systems-format | .wmp | video/x-ms-wmp | Microsoft Windows WMP video format. | -| com.microsoft.windows-media-wma | general.audio,com.microsoft.advanced-systems-format | .wma | audio/x-ms-wma | Microsoft Windows WMA video format. | +| com.microsoft.windows-media-wma | general.audio,com.microsoft.advanced-systems-format | .wma | audio/x-ms-wma | Microsoft Windows WMA video format. | | com.microsoft.windows-media-wmx | general.video,com.microsoft.advanced-systems-format | .wmx | video/x-ms-wmx | Microsoft Windows WMX video format. | | com.microsoft.windows-media-wvx | general.video,com.microsoft.advanced-systems-format | .wvx | video/x-ms-wvx | Microsoft Windows WVX video format. | | com.microsoft.windows-media-wax | general.audio,com.microsoft.advanced-systems-format | .wax | audio/x-ms-wax | Microsoft Windows WAX audio format. | @@ -273,7 +273,7 @@ Application-specific UTDs are defined and maintained by a specific application o | com.microsoft.powerpoint.pot | general.composite-object | .pot | application/vnd.ms-powerpoint | Microsoft PowerPoint template. | | com.microsoft.excel.xlt | general.composite-object | .xlt | application/vnd.ms-excel | Microsoft Excel template. | | com.microsoft.visio.vsd | general.composite-object | .vsd | application/vnd.visio | Microsoft Visio. | -| com.microsoft.excel.dif | general.composite-object | .dif | - | Microsoft Excel Data Interchange Format. | +| com.microsoft.excel.dif | general.composite-object | .dif | - | Microsoft Excel Data Interchange Format. | | com.microsoft.lsf-video | general.video | .lsf, .lsx | video/x-la-asf | Streaming media format.| | org.openxmlformats.openxml | general.archive | - | - | Generic OpenXML format. | | org.openxmlformats.wordprocessingml.document | org.openxmlformats.openxml, general.composite-object | .docx | application/vnd.openxmlformats-officedocument.wordprocessingml.document | OpenXML-formatted Microsoft Word document. | @@ -292,18 +292,18 @@ Application-specific UTDs are defined and maintained by a specific application o | org.openxmlformats.spreadsheetml.binary.macroenabled | org.openxmlformats.openxml, general.composite-object, general.executable | .xlsb | application/vnd.ms-excel.sheet.binary.macroEnabled.12 | OpenXML-formatted, macro-enabled Excel file in binary format. | | org.openxmlformats.spreadsheetml.sheet.macroenabled | org.openxmlformats.openxml, general.composite-object, general.executable | .xlsm | application/vnd.ms-excel.sheet.macroEnabled.12 | OpenXML-formatted Excel file with macros written in VBA. | | org.openxmlformats.presentationml.addin.macroenabled | org.openxmlformats.openxml, general.composite-object, general.executable | .ppam | application/vnd.ms-powerpoint.addin.macroEnabled.12 | OpenXML-formatted PowerPoint add-in file with enabled macros. | -| org.openxmlformats.presentationml.presentation.macroenabled | org.openxmlformats.openxml, general.composite-object, general.executable | .pptm | application/vnd.ms-powerpoint.presentation.macroEnabled.12 | OpenXML-formatted PowerPoint file with macros written in VBA. | -| org.openxmlformats.presentationml.slideshow.macroenabled | org.openxmlformats.openxml, general.composite-object, general.executable | .ppsm | application/vnd.ms-powerpoint.slideshow.macroEnabled.12 | OpenXML-formatted PowerPoint slideshow file with enabled macros. | -| org.openxmlformats.presentationml.template.macroenabled | org.openxmlformats.openxml, general.composite-object, general.executable | .potm | application/vnd.ms-powerpoint.template.macroEnabled.12 | OpenXML-formatted PowerPoint template file with enabled macros. | -| org.openxmlformats.drawingml.visio.macroenabled | org.openxmlformats.openxml, general.composite-object | .vsdm | - | OpenXML-formatted Visio drawing with enabled macros. | -| org.openxmlformats.drawingml.template.macroenabled | org.openxmlformats.openxml, general.composite-object | .vstm | - | OpenXML-formatted Visio template with enabled macros. | +| org.openxmlformats.presentationml.presentation.macroenabled | org.openxmlformats.openxml, general.composite-object, general.executable | .pptm | application/vnd.ms-powerpoint.presentation.macroEnabled.12 | OpenXML-formatted PowerPoint file with macros written in VBA. | +| org.openxmlformats.presentationml.slideshow.macroenabled | org.openxmlformats.openxml, general.composite-object, general.executable | .ppsm | application/vnd.ms-powerpoint.slideshow.macroEnabled.12 | OpenXML-formatted PowerPoint slideshow file with enabled macros. | +| org.openxmlformats.presentationml.template.macroenabled | org.openxmlformats.openxml, general.composite-object, general.executable | .potm | application/vnd.ms-powerpoint.template.macroEnabled.12 | OpenXML-formatted PowerPoint template file with enabled macros. | +| org.openxmlformats.drawingml.visio.macroenabled | org.openxmlformats.openxml, general.composite-object | .vsdm | - | OpenXML-formatted Visio drawing with enabled macros. | +| org.openxmlformats.drawingml.template.macroenabled | org.openxmlformats.openxml, general.composite-object | .vstm | - | OpenXML-formatted Visio template with enabled macros. | | com.kingsoft.office | general.archive | - | - | Generic Kingsoft Office document type. | | com.kingsoft.office.writer.wps | com.kingsoft.office,general.composite-object | .wps | - | Kingsoft WPS Office document. | | com.kingsoft.office.writer.wpt | com.kingsoft.office,general.composite-object | .wpt | - | Kingsoft WPS Office document template. | | com.kingsoft.office.presentation.dps | com.kingsoft.office,general.composite-object | .dps | - | Kingsoft WPS Presentation. | | com.kingsoft.office.presentation.template | com.kingsoft.office,general.composite-object | .dpt | - | Kingsoft WPS Presentation template. | -| com.kingsoft.office.spreadsheets.et | com.kingsoft.office,general.composite-object | .et | - | Kingsoft electronic spreadsheet. | -| com.kingsoft.office.spreadsheets.template | com.kingsoft.office,general.composite-object | .ett | - | Kingsoft electronic spreadsheet template. | +| com.kingsoft.office.spreadsheets.et | com.kingsoft.office,general.composite-object | .et | - | Kingsoft electronic spreadsheet. | +| com.kingsoft.office.spreadsheets.template | com.kingsoft.office,general.composite-object | .ett | - | Kingsoft electronic spreadsheet template. | | com.kingsoft.office.spreadsheets.etx | com.kingsoft.office,general.composite-object | .etx | - | Kingsoft electronic spreadsheet in plain text format for exchanging data between different applications. | | com.kingsoft.office.spreadsheets.ettx | com.kingsoft.office,general.composite-object | .ettx | - | Kingsoft encrypted electronic spreadsheet. | | org.oasis.opendocument | general.archive | - | - | Generic OpenDocument type. | @@ -356,7 +356,7 @@ Application-specific UTDs are defined and maintained by a specific application o | com.adobe.photoshop-image | general.image | .psd | image/x-photoshop, image/photoshop, image/psd, application/photoshop | Adobe Photoshop document. | | com.adobe.illustrator.ai-image | general.image | .ai | - | Adobe Illustrator document. | | com.adobe.dcr | general.video | .dcr | application/x-director | Adobe Shockwave document. | -| com.adobe.dir | general.video | .dir | application/x-director | Adobe Director document. | +| com.adobe.dir | general.video | .dir | application/x-director | Adobe Director document. | | com.adobe.dxr | general.video | .dxr | application/x-director | Adobe Director Protected Movie document. | | com.adobe.futuresplash | general.video | .spl | application/futuresplash, application/x-futuresplash | FutureSplash animation format. | | com.adobe.flash | general.video | .swf, .flv | application/x-shockwave-flash, video/x-flv | Adobe Flash file format. | @@ -372,13 +372,13 @@ Application-specific UTDs are defined and maintained by a specific application o | com.amazon.mobi | general.ebook | .mobi | application/x-mobipocket-ebook | MOBI eBook format. | | com.amazon.azw | general.ebook | .azw | application/vnd.amazon.ebook | AZW eBook format. | | com.amazon.azw3 | general.ebook | .azw3 | application/vnd.amazon.mobi8-ebook, application/x-mobi8-ebook | AZW3 eBook format. | -| com.amazon.kfx | general.ebook | .kfx | - | KFX eBook format. | +| com.amazon.kfx | general.ebook | .kfx | - | KFX eBook format. | | com.autodesk.dwg | general.composite-object | .dwg | image/vnd.dwg | AutoCAD file format. | | com.autodesk.dxf | general.composite-object | .dxf | image/vnd.dxf | AutoCAD Drawing Exchange Format (DXF). | | com.autodesk.dws | general.composite-object | .dws | - | AutoCAD drawing standards file. | | com.autodesk.dwt | general.composite-object | .dwt | - | AutoCAD drawing template. | | com.autodesk.dwf | general.composite-object | .dwf | model/vnd.dwf | AutoCAD Design Web Format (DWF). | -| com.autodesk.dwfx | general.composite-object | .dwfx | - | Autodesk format used for sharing 2D/3D design data. | +| com.autodesk.dwfx | general.composite-object | .dwfx | - | Autodesk format used for sharing 2D/3D design data. | | com.autodesk.shp | general.composite-object | .shp | - | AutoCAD 3D vector data format. | | com.autodesk.shx | general.composite-object | .shx | - | Format of a shape index file associated with AutoCAD. | | com.autodesk.slide-library | general.composite-object | .slb | - | AutoCAD slide library file format. | @@ -421,7 +421,7 @@ Application-specific UTDs are defined and maintained by a specific application o | com.j2.jfx-fax | general.fax | .jfx | - | J2 jConnect fax file format. | | com.js.efx-fax | general.fax | .efx | image/efax | Electronic fax file format. | | com.canon.cr2-raw-image | general.raw-image | .cr2 | image/x-canon-cr2 | Canon Raw 2 image file format. | -| com.canon.cr3-raw-image | general.raw-image | .cr3 | image/x-canon-cr3 | Canon Raw 3 image file format. | +| com.canon.cr3-raw-image | general.raw-image | .cr3 | image/x-canon-cr3 | Canon Raw 3 image file format. | | com.canon.crw-raw-image | general.raw-image | .crw | image/x-canon-crw | Canon Raw CIFF image file format. | | com.sony.arw-raw-image | general.raw-image | .arw | image/x-sony-arw | Sony Raw image format used by Sony digital cameras. | | com.nikon.nef-raw-image | general.raw-image | .nef | image/x-nikon-nef | Nikon Raw image format used by Nikon digital cameras. | diff --git a/en/application-dev/device/driver/Readme-EN.md b/en/application-dev/device/driver/Readme-EN.md index 9756b0ad993c6a8883c63371e46e8d021e440b13..8418d8c91f1bb84c466e7fef7f51a96721aa53c8 100644 --- a/en/application-dev/device/driver/Readme-EN.md +++ b/en/application-dev/device/driver/Readme-EN.md @@ -1,6 +1,14 @@ -# Driver Development Kit +# Driver Development Kit - - [Introduction to Driver Development Kit](driverdevelopment-overview.md) - - [Peripheral Driver Client Development](externaldevice-guidelines.md) - - [DriverExtensionAbility Development](driverextensionability.md) - - [FAQs](externaldevice-faqs.md) +- [Introduction to Driver Development Kit](driverdevelopment-overview.md) +- [Environment Preparation](environmental-preparation.md) +- Basic Peripheral Driver Development + - [UI-free Driver Development](driverextensionability.md) + - [UI-based Driver Development](externaldevice-guidelines.md) +- Dedicated Peripheral Driver Development + - [USB DDK Development](usb-ddk-guidelines.md) + - [HID DDK Development](hid-ddk-guidelines.md) + - [USB Serial DDK Development](usb-serial-ddk-guidelines.md) + - [SCSI Peripheral DDK Development](scsi-peripheral-ddk-guidelines.md) +- [FAQs](externaldevice-faqs.md) +- [Terms](terms.md) diff --git a/en/application-dev/device/driver/driverdevelopment-overview.md b/en/application-dev/device/driver/driverdevelopment-overview.md index 39415998f29ce12b0530c2806c5bdce9d309043d..ece2d5083b9eb42c9f41a02918a315af16c2a594 100644 --- a/en/application-dev/device/driver/driverdevelopment-overview.md +++ b/en/application-dev/device/driver/driverdevelopment-overview.md @@ -1,16 +1,12 @@ # Introduction to Driver Development Kit -Empowered by the C-API solution, Driver Development Kit provides easy-to-use, secure, and diversified C APIs to elevate your experience in developing peripheral drivers, which bring ultimate plug-and-play experience to users. - -1. You can develop advanced peripheral functions to meet user requirements. - -2. The extended driver framework supports lifecycle management of peripheral drivers and provides APIs for querying and binding peripheral devices. +Empowered by the C-API solution, Driver Development Kit provides easy-to-use, secure, and diversified ArkTs-API and C APIs to elevate your experience in developing peripheral drivers, which bring ultimate plug-and-play experience to users. ## When to Use -You can use Driver Development Kit to: +With Driver Development Kit, you can develop dedicated or extended peripheral drivers in an efficient and secure manner. -1. Develop drivers of special +1. Develop drivers of dedicated peripherals for bank counters, enterprise office, and medical detection, such as high-speed document scanners, ID card scanners, fingerprint scanners, and blood oxygen and blood glucose meters. @@ -18,33 +14,68 @@ You can use Driver Development Kit to: such as customizing handwriting pad shortcut keys, setting the pressure sensing/drawing area, setting extended enhancement capabilities, setting the mouse lighting effect, customizing mouse extended buttons, and setting DPI and X and Y axes. -## Working Principles +## Typical Use Cases + +- You can develop advanced peripheral functions to meet user requirements. + +- The extended driver framework supports lifecycle management of peripheral drivers and provides APIs for querying and binding peripheral devices. + +## Basic Concepts + +- Peripheral driver client: [basic UI-based driver](externaldevice-guidelines.md), which is used to query and bind drivers, and customize the communication mode and data processing mode. +- Peripheral driver: [basic UI-free driver](driverextensionability.md), which is the dedicated peripheral driver or enhanced peripheral driver developed based on the DDK. +- External Device Manager: performs lifecycle management of peripheral devices and driver packages. +- Bundle Manager Service (BMS): manages application installation, uninstallation, and data on the system. +- Ability Manager Service (AMS): starts and stops **DriverExtensionAbility**. + +## Implementation Principles The HDF extended driver framework provides unified APIs for you to leverage the DDK capabilities for user-mode peripheral driver development. -The driver extension system ability (SA), the core service of user-mode peripheral management, performs lifecycle management of peripherals and peripheral drivers. In addition, standard ArkTS APIs are provided to query, bind, and unbind peripherals. +External Device Manager, the core service of user-mode peripheral management, performs lifecycle management of peripherals and peripheral drivers. In addition, standard ArkTS APIs are provided to query, bind, and unbind peripherals. + +### Peripheral Driver Architecture **Figure 1** Peripheral driver working mechanism ![driverExtension](figures/driverExtension.png) -### **Module Functions** -- Peripheral application: queries and binds the driver, and customizes the device-driver communication mode and data processing mode. For details, see [Peripheral Driver Client Development](externaldevice-guidelines.md). -- Peripheral driver (application): dedicated peripheral driver or enhanced peripheral driver developed using HDF-DDK. For details, see [Peripheral Driver Development](driverextensionability.md). -- Driver extension SA: performs lifecycle management of peripheral devices and driver packages. -- AMS: starts and disables **DriverExtensionAbility**. +### Operation Process -### **Process Description** +Figure 2 shows the process for matching a peripheral driver client with a peripheral driver when a peripheral is connected. -Figure 2 shows the process of matching a peripheral with a driver when a peripheral is connected. - -**Figure 2** Process for matching a peripheral with a driver +**Figure 2** Process for matching a peripheral driver client with a peripheral driver ![timeSeries1](figures/timeSeries1.png) -Figure 2 shows the process of binding the peripheral driver client with a peripheral driver when a peripheral application is run. +Figure 3 shows the process for binding the peripheral driver client with a peripheral driver. **Figure 3** Process of binding the peripheral driver client with a peripheral driver ![timeSeries2](figures/timeSeries2.png) + +## Notes and Constraints + +To call the ArkTs or C APIs provided by Driver Development Kit, you need to apply for specified permissions. + +The following table lists the required permissions. + +| API Type| DDK Type| Permission| +| --------- | --------- | --------- | +| ArkTs-API | NA| ohos.permission.ACCESS_EXTENSIONAL_DEVICE_DRIVER | +| C-API | USB DDK | ohos.permission.ACCESS_DDK_USB | +| C-API | HID DDK | ohos.permission.ACCESS_DDK_HID | +| C-API | USB Serial DDK | ohos.permission.ACCESS_DDK_USB_SERIAL | +| C-API | SCSI Peripheral DDK | ohos.permission.ACCESS_DDK_SCSI_PERIPHERAL | + +## Associated Modules + +The following table lists the associated modules you may use during development of peripheral drivers. + +| Name| Description| +| --------- | --------- | +| PerformanceAnalysisKit | Introduces {hilog} for log printing.| +| BasicServicesKit | Introduces {BusinessError} to capture error information.| +| IPCKit | Introduces {rpc} to implement inter-process communication between the driver and the client.| +| AbilityKit | Introduces {want} for lifecycle management.| diff --git a/en/application-dev/device/driver/driverextensionability.md b/en/application-dev/device/driver/driverextensionability.md index 7b830a8abc7378b68f4d6a1109feca65c4380173..1a69a0317c2d3b5898414c8e1933cb993c8f15c0 100644 --- a/en/application-dev/device/driver/driverextensionability.md +++ b/en/application-dev/device/driver/driverextensionability.md @@ -1,43 +1,41 @@ -# Peripheral Driver Development +# UI-free Driver Development ## When to Use -[DriverExtensionAbility](../../reference/apis-driverdevelopment-kit/js-apis-app-ability-driverExtensionAbility.md) is an **ExtensionAbility** of the driver type that provides the driver-related extension framework. If the capabilities of a device can be expanded by inserting an external hardware module, you can install the driver of the hardware module through an application. **DriverExtensionAbility** can be used to develop such applications. +Basic UI-free drivers are applicable to simple devices that do not require setting of driver capabilities via a UI, such as mouse devices and keyboards. These drivers are designed to ensure that these devices can be used immediately upon connection, enabling seamless plug-and-play functionality. You can use **DriverExtensionAbility** to develop such applications. +## Basic Concepts -You can bind a [DriverExtensionAbility](../../reference/apis-driverdevelopment-kit/js-apis-app-ability-driverExtensionAbility.md) object to an application through **DriverExtensionManager** so that related transactions can be processed in the background based on the application request information. -Each type of **ExtensionAbility** has its own context. The **DriverExtensionAbility** provides related capabilities through the [DriverExtensionContext](../../reference/apis-driverdevelopment-kit/js-apis-inner-application-driverExtensionContext.md). + - DriverExtensionAbility -## Environment Setup - -Set up the environment following the instructions in [Peripheral Driver Client Development](externaldevice-guidelines.md). + [DriverExtensionAbility](../../reference/apis-driverdevelopment-kit/js-apis-app-ability-driverExtensionAbility.md) is an **ExtensionAbility** of the driver type that provides the driver-related extension framework. If the capabilities of a device can be expanded by inserting an external hardware module, you can install the driver of the hardware module through an application. You can bind a [DriverExtensionAbility](../../reference/apis-driverdevelopment-kit/js-apis-app-ability-driverExtensionAbility.md) object to an application through **DriverExtensionManager** so that related transactions can be processed in the background based on the application request information. + Each type of **ExtensionAbility** has its own context. The **DriverExtensionAbility** provides related capabilities through the [DriverExtensionContext](../../reference/apis-driverdevelopment-kit/js-apis-inner-application-driverExtensionContext.md). -The following table lists the SDK version requirements. +## Environment Setup -| NDK API| SDK Version| -|---------|--------| -| USB DDK | API version 10 or later| -| HID DDK | API version 11 or later| +Before you get started, make necessary preparations by following instructions in [Environment Preparation](environmental-preparation.md). ## How to Develop To implement a driver, create a DriverExtensionAbility in the DevEco Studio project. The procedure is as follows: -1. In the **ets** directory of a module in the project, right-click and choose **New > Directory** to create a directory named **driverextability**. +1. Create an OpenHarmony project. For details, see [Creating a Project] (https://developer.huawei.com/consumer/en/doc/harmonyos-guides/ide-create-new-project). (If a project has been created in [UI-based Driver Development](externaldevice-guidelines.md), skip this step.) + +2. In the **ets** directory of the project, right-click **New** > **Directory** to create a directory named **driverextability**. -2. In the **driverextability** directory, right-click and choose **New > ArkTS File** to create a file named **DriverExtAbility.ets**. +3. In the **driverextability** directory, right-click and choose **New > ArkTS File** to create a file named **DriverExtAbility.ets**. -3. Import the related kit, and define the request code. +4. Import the related kit, and define the request code. ```ts import { DriverExtensionAbility } from '@kit.DriverDevelopmentKit'; import { Want } from '@kit.AbilityKit'; import { rpc } from '@kit.IPCKit'; - const REQUEST_CODE = 99; // Negotaite the request code with the peripheral client. + const REQUEST_CODE = 99; // Negotiate the request code with the peripheral client. ``` -4. Open the **DriverExtAbility.ets** file, import the [RPC module](../../reference/apis-ipc-kit/js-apis-rpc.md), and overload the **onRemoteMessageRequest()** method to receive messages from the application and return the processing result to the application. **REQUEST_VALUE** is used to verify the service request code sent by the application. +5. Open the **DriverExtAbility.ets** file, import the [RPC module](../../reference/apis-ipc-kit/js-apis-rpc.md), and overload the **onRemoteMessageRequest()** method to receive messages from the application and return the processing result to the application. **REQUEST_VALUE** is used to verify the service request code sent by the application. ```ts class StubTest extends rpc.RemoteObject { @@ -49,7 +47,7 @@ To implement a driver, create a DriverExtensionAbility in the DevEco Studio proj // When the application calls data.writeString() multiple times to write data, the driver can receive the corresponding data by calling data.readString() for multiple times. let optFir: string = data.readString(); // The driver returns the data processing result to the application. - // In the example, Hello is received and Hello World is returned to the application. + // In the example, Hello is received and Hello World is returned to the application. reply.writeString(optFir + ` World`); } return true; @@ -57,7 +55,7 @@ To implement a driver, create a DriverExtensionAbility in the DevEco Studio proj } ``` -5. In the **DriverExtAbility.ets** file, import the dependency package [DriverExtensionAbility](../../reference/apis-driverdevelopment-kit/js-apis-app-ability-driverExtensionAbility.md), which provides the **onInit()**, **onRelease()**, **onConnect()**, and **onDisconnect()** lifecycle callbacks. Then, customize a class to inherit from [DriverExtensionAbility](../../reference/apis-driverdevelopment-kit/js-apis-app-ability-driverExtensionAbility.md) and override the lifecycle callbacks as required. +6. In the **DriverExtAbility.ets** file, import the dependency package [DriverExtensionAbility](../../reference/apis-driverdevelopment-kit/js-apis-app-ability-driverExtensionAbility.md), which provides the **onInit()**, **onRelease()**, **onConnect()**, and **onDisconnect()** lifecycle callbacks. Then, customize a class to inherit from [DriverExtensionAbility](../../reference/apis-driverdevelopment-kit/js-apis-app-ability-driverExtensionAbility.md) and override the lifecycle callbacks as required. ```ts export default class DriverExtAbility extends DriverExtensionAbility { @@ -85,7 +83,7 @@ To implement a driver, create a DriverExtensionAbility in the DevEco Studio proj } ``` -6. Register **DriverExtensionAbility** in the [**module.json5** file](../../quick-start/module-configuration-file.md) of the module in the project. Set **type** to **service** and **srcEntry** to the code path of **DriverExtensionAbility**. +7. Register **DriverExtensionAbility** in the [**module.json5** file](../../quick-start/module-configuration-file.md) of the module in the project. Set **type** to **service** and **srcEntry** to the code path of **DriverExtensionAbility**. ```json { @@ -101,6 +99,9 @@ To implement a driver, create a DriverExtensionAbility in the DevEco Studio proj "requestPermissions": [ { "name": "ohos.permission.ACCESS_EXTENSIONAL_DEVICE_DRIVER" // Peripheral-specific permission, which is mandatory. + }, + { + "name": "ohos.permission.ACCESS_DDK_DRIVERS" // Peripheral access permission, which is mandatory in API version 18 or later. } ], "deliveryWithInstall": true, @@ -138,7 +139,7 @@ To implement a driver, create a DriverExtensionAbility in the DevEco Studio proj "srcEntry": "./ets/driverextability/DriverExtAbility.ets", "metadata": [ { - "name": "bus", // The bus is mandatory. + "name": "bus", // Bus, which is mandatory. "value": "USB" }, { @@ -156,6 +157,14 @@ To implement a driver, create a DriverExtensionAbility in the DevEco Studio proj { "name": "pid," // List of USB product IDs. Enter a hex value. Here, the value is the hex value of 4258. "value": "0x10A2" + }, + { + "name": "launchOnBind," // Whether to enable delayed driver startup. This parameter is optional. The value true indicates delayed startup, and the value false indicates immediate startup. The value is false by default if the specified value is incorrect or the value is left unspecified. + "value": "true" + }, + { + "name": "ohos.permission.ACCESS_DDK_ALLOWED," // Whether to allow DDK access. This parameter is optional. The value true indicates that DDK access is allowed, and the value false indicates the opposite. The default value is false. + "value": "true" } ] } @@ -164,23 +173,41 @@ To implement a driver, create a DriverExtensionAbility in the DevEco Studio proj } ``` -7. After completing development of the client and driver sample code, import the HAP to the device by following instructions in [Running Your App/Service on a Local Real Device](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V13/ide-run-device-V13), and run **Hello** in the HAP to check whether **Hello world** is displayed. If yes, the IPC communication is ready for use. +8. After completing development of the client and driver sample code, import the HAP to the device by following instructions in [Running Your App/Service on a Local Real Device](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V13/ide-run-device-V13), and run **Hello** in the HAP to check whether **Hello world** is displayed. If yes, the IPC communication is ready for use. ## Driver Development -**DriverExtensionAbility** provides two development modes, namely, HID DDK and USB DDK, for driver development. - -Choose either mode depending on your need: +Currently, **DriverExtensionAbility** provides four capabilities: HID DDK, USB DDK, USB serial DDK, and SCSI peripheral DDK, which are used to develop dedicated drivers for extended peripherals. Choose either mode depending on your need: -* [HID DDK Development](https://gitee.com/openharmony/docs/blob/master/en/application-dev/napi/hid-ddk-guidelines.md) -* [USB DDK Development](https://gitee.com/openharmony/docs/blob/master/en/application-dev/napi/usb-ddk-guidelines.md) +* [HID DDK Development](hid-ddk-guidelines.md) +* [USB DDK Development](usb-ddk-guidelines.md) +* [USB Serial DDK Development](usb-serial-ddk-guidelines.md) +* [SCSI Peripheral DDK Development](scsi-peripheral-ddk-guidelines.md) + ## Application Signing -You need to configure a signature file for your application to run on a device. Besides, to develop a peripheral driver client, you need to declare the **ohos.permission.ACCESS_EXTENSIONAL_DEVICE_DRIVER** permission for the peripheral. +**NOTE**
Configure the permission before enabling automatic signing. + +You need to configure a signature file for your application to run on a device. Besides, to develop a peripheral driver client, you need to declare the **ohos.permission.ACCESS_EXTENSIONAL_DEVICE_DRIVER** and **ohos.permission.ACCESS_DDK_DRIVERS** permissions for the peripheral. +- ohos.permission.ACCESS_EXTENSIONAL_DEVICE_DRIVER (This permission is required for API version 10 or later.) + + To obtain authorization on this access permission, [declare it](../../security/AccessToken/declare-permissions.md) in the **requestPermissions** field in the **module.json5** file. -If the HID DDK or USB DDK is used, configure the required permission as described above. +- ohos.permission.ACCESS_DDK_DRIVERS (This permission is required for API version 18 or later.) -Automatic signing: [Signing Your App/Service Automatically](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/ide-signing-V5#section18815157237) + 1. [Declare the required permissions](../../security/AccessToken/declare-permissions.md) in the **requestPermissions** field in the **module.json5** file. + 2. Modify the **acls** field in the **HarmonyAppProvision** configuration file to request permissions via ACL. For details, see [Requesting Restricted Permissions](../../security/AccessToken/declare-permissions-in-acl.md). + 3. In the **HarmonyAppProvision** configuration file (that is, **Sdk/openharmony/_{Version} _/toolchains /lib/UnsgnedReleasedProfileTemplate.json** file), configure the bundle name of the driver server to connect. If there are multiple servers, separate their bundle names with a comma. + + The configuration procedure is as follows: + + Add the **app-services-capabilities** node to the root node of the file and configure the node as follows: + ```json + "app-services-capabilities": { + "ohos.permission.ACCESS_DDK_DRIVERS": {"bundleNames": "bundleName0,bundleName1,bundleName2"} + } + ``` -Permission configuration: [Requesting ACL Permissions and Signing Your App/Service](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/ide-signing-V5#section157591551175916). +Automatic signing: [Signing Your App/Service Automatically](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V13/ide-signing-V13#section18815157237) + diff --git a/en/application-dev/device/driver/environmental-preparation.md b/en/application-dev/device/driver/environmental-preparation.md new file mode 100644 index 0000000000000000000000000000000000000000..8bee0406cb70818f7a601c7054122af09e739341 --- /dev/null +++ b/en/application-dev/device/driver/environmental-preparation.md @@ -0,0 +1,40 @@ +# Setting Up the Environment + +## Development Tool and Configuration + +DevEco Studio, as the driver development tool, allows you to develop, debug, and package drivers. [Download and install](https://developer.huawei.com/consumer/en/download/) DevEco Studio and verify basic operations to ensure that it can function properly. + +[Download and install](https://developer.huawei.com/consumer/en/download/) DevEco Studio and verify basic operations to ensure that it can function properly. For details, see [Creating and Running a Project](https://developer.huawei.com/consumer/en/doc/harmonyos-guides/ide-create-new-project) in [DevEco Studio User Guide](https://developer.huawei.com/consumer/en/doc/harmonyos-guides/ide-tools-overview). + +## SDK Version Configuration + +The ArkTs APIs for peripheral management can be used only when the SDK is of API version 10 or later. For details about how to update the SDK, see [OpenHarmony SDK Upgrade Assistant](../../tools/openharmony_sdk_upgrade_assistant.md). + +The SDK version must meet the following requirements when you develop dedicated peripheral drivers or enhanced peripheral drivers based on the DDK. + +| NDK API | SDK Version | +|----------------|----------| +| USB DDK | API version 10 or later| +| HID DDK | API version 11 or later| +| USB Serial DDK | API version 18 or later| +| SCSI Peripheral DDK | API version 18 or later| + +## Verifying the Environment + +Check whether DevEco Studio is connected to the OpenHarmony device. + +![Device connection](figures/device-connected.png) + +## HDC Configuration + +HarmonyOS Device Connector (hdc) is a command-line tool for debugging. It can be used to interact with real devices or the Emulators on Windows, Linux, and macOS. For details about the configuration, see [hdc](https://developer.huawei.com/consumer/en/doc/harmonyos-guides/hdc). + +**NOTE**
Configuration of the environment variable **hdc_server_port** and global environment variables is mandatory. + +## Development Device + +* Currently, RK3568 is used as the device for development, debugging, and verification. For details about how to compile and burn the RK3568, see [Quick Start](https://gitee.com/openharmony/docs/blob/master/en/device-dev/quick-start/quickstart-pkg-3568-burn.md). +* During peripheral client and driver development, you need to connect an external USB device for debugging. Currently, **only an external USB device is supported**. +* The product ID and vendor ID of the USB device are required for defining drivers and implementing IPC. + + \ No newline at end of file diff --git a/en/application-dev/device/driver/externaldevice-faqs.md b/en/application-dev/device/driver/externaldevice-faqs.md index 4d918650b2b68e5c3a08ae8b155cd1e432d19c54..39c1546a7f43a37a31c7a3a639f866b9eaf54163 100644 --- a/en/application-dev/device/driver/externaldevice-faqs.md +++ b/en/application-dev/device/driver/externaldevice-faqs.md @@ -25,10 +25,12 @@ The message "compileSdkVersion and releaseType of the app do not match the apiVe ### Version Mapping | API Type| Minimum API Version| OpenHarmony Version| -| ------------ | ------------ | ------------ | +| --------- | --------- | --------- | | Application development APIs (ArkTS APIs)| API10 | 4.0 Release or later| | USB DDK APIs| API10 | 4.0 Release or later| | HID DDK APIs| API11 | 4.0 Release or later| +| USB Serial DDK API| API18 | 5.1 Release or later| +| SCSI Peripheral DDK API| API18 | 5.1 Release or later| ## Failed to Parse the Local .so File During HAP Installation @@ -39,4 +41,4 @@ The message "code:9568347 error: install parse native so failed" is displayed du ### Solution -Configure the value of `abiFilters` in `buildOption/externalNativeOptions` in the `build-profile.json5` file. For details, see [Application Debugging](https://developer.huawei.com/consumer/en/doc/harmonyos-faqs-V5/faqs-app-debugging-14-V5). +Configure the value of `abiFilters` in `buildOption/externalNativeOptions` in the `build-profile.json5` file. For details, see [Application Debugging] (https://developer.huawei.com/consumer/en/doc/harmonyos-faqs-V5/faqs-app-debugging-14-V5). diff --git a/en/application-dev/device/driver/externaldevice-guidelines.md b/en/application-dev/device/driver/externaldevice-guidelines.md index e1bed3da53110573d70efd2cfd091855d24ce6f7..c3f8fb8aa46a5ea3b36d86e199649abdeacc4b51 100644 --- a/en/application-dev/device/driver/externaldevice-guidelines.md +++ b/en/application-dev/device/driver/externaldevice-guidelines.md @@ -1,34 +1,12 @@ -# Peripheral Driver Client Development +# UI-based Driver Development ## When to Use -Peripheral devices (or simply peripherals) are auxiliary devices connected to a device through physical ports, such as handwriting tablets, printers, and scanners. Applications can query and bind peripherals via peripheral management, so that the peripherals can use the customized capabilities provided by the peripheral drivers, such as the printer software. - -Peripheral management applies to all devices that can be ported to the OpenHarmony. +UI-based basic drivers are applicable to a wide variety of composite devices. When developing these drivers, you may set the corresponding unique driver capabilities through the UI, or display the information retrieved from the devices on the UI. Examples of such devices include mice with side buttons, handwriting tablets, and ID card readers. ## Environment Setup -### Development Tool and Configuration - -DevEco Studio, as the driver development tool, allows you to develop, debug, and package drivers. - -[Download and install](https://developer.huawei.com/consumer/en/download/) DevEco Studio and verify basic operations to ensure that it can function properly. For details, see [Creating and Running a Project](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V13/ide-create-new-project-V13) in [DevEco Studio User Guide](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V13/ide-tools-overview-V13). - -### SDK Version Configuration - -The ArkTs APIs for peripheral management can be used only when the SDK is of API version 10 or later. - -### HDC Configuration - -HarmonyOS Device Connector (HDC) is a command-line tool for debugging. It can be used to interact with real devices or emulators on Windows, Linux, and Mac. For details, see [HDC Configuration](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/hdc-V5). - -**NOTE**
Configuration of the environment variable **hdc_server_port** and global environment variables is mandatory. - -### Development Device - -* Currently, RK3568 is used as the device for development, debugging, and verification. For details about how to compile and burn the RK3568, see [Quick Start](https://gitee.com/openharmony/docs/blob/master/en/device-dev/quick-start/quickstart-pkg-3568-burn.md). -* During client and driver development, you need to connect an external USB device for debugging. **Currently, only an external USB device is supported.** -* The product ID and vendor ID of the USB device are required for defining drivers and implementing IPC. +Before you get started, make necessary preparations by following instructions in [Environment Preparation](environmental-preparation.md). ## Available APIs @@ -36,15 +14,11 @@ The following table describes the basic peripheral management capabilities. For **Table 1** APIs for basic peripheral management -| Name | Description | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- | -| queryDevices(busType?: number): Array<Readonly<Device>> | Queries the peripheral list. | -| bindDevice(deviceId: number, onDisconnect: AsyncCallback<number>, callback: AsyncCallback<{deviceId: number; remote: rpc.IRemoteObject;}>): void | Binds a peripheral device. This API uses an asynchronous callback to return the result. If the peripheral device is bound, the **IRemoteObject** of the device driver is returned for subsequent interaction with the device driver.| -| bindDevice(deviceId: number, onDisconnect: AsyncCallback<number>): Promise<{deviceId: number; remote: rpc.IRemoteObject;}> | Binds a peripheral. This API uses a promise to return the result. | -| bindDeviceDriver(deviceId: number, onDisconnect: AsyncCallback<number>, callback: AsyncCallback>RemoteDeviceDriver>): void; | Binds a peripheral. This API uses an asynchronous callback to return the result. It is supported since API version 11. | -| bindDeviceDriver(deviceId: number, onDisconnect: AsyncCallback<number>): Promise<RemoteDeviceDriver>; | Binds a peripheral. This API uses a promise to return the result. It is supported since API version 11. -| unbindDevice(deviceId: number, callback: AsyncCallback<number>): void | Unbinds a peripheral device. This API uses an asynchronous callback to return the result. | -| unbindDevice(deviceId: number): Promise<number> | Unbinds a peripheral device. This API uses a promise to return the result. | +| Name | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| queryDevices(busType?: number): Array<Readonly<Device>> | Queries the peripheral list. | +| bindDriverWithDeviceId(deviceId: number, onDisconnect: AsyncCallback<number>): Promise<RemoteDeviceDriver>; | Binds a peripheral. This API uses a promise to return the result. It is supported since API version 18. | +| unbindDriverWithDeviceId(deviceId: number): Promise<number> | Unbinds a peripheral device. This API uses a promise to return the result. It is supported since API version 18. | The following table lists the APIs for extended peripheral management. For details, see [deviceManager API Reference](../../reference/apis-driverdevelopment-kit/js-apis-driver-deviceManager-sys.md). @@ -63,7 +37,7 @@ You can use the APIs to query and bind peripheral devices so as to use the custo The following sample code is a demo that illustrates how to develop both the client and server and implement IPC. -1. Create an OpenHarmony project. For details, see [Creating a Project](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V13/ide-create-new-project-V13). +1. Create an OpenHarmony project. For details, see [Creating a Project] (https://developer.huawei.com/consumer/en/doc/harmonyos-guides/ide-create-new-project). **NOTE** @@ -126,24 +100,24 @@ The following sample code is a demo that illustrates how to develop both the cli } ``` -5. Define the **bindDeviceDriver** API, and use it to obtain the remote driver object. +5. Define the **bindDriverWithDeviceId** API, and use it to obtain the remote driver object. ```ts private async getDriverRemote(deviceId: number): Promise { try { - let remoteDeviceDriver: deviceManager.RemoteDeviceDriver = await deviceManager.bindDeviceDriver(deviceId, + let remoteDeviceDriver: deviceManager.RemoteDeviceDriver = await deviceManager.bindDriverWithDeviceId(deviceId, (err: BusinessError, id: number) => { hilog.info(0, 'testTag', `device[${id}] id disconnect, err: ${JSON.stringify(err)}}`); }); return remoteDeviceDriver.remote; } catch (error) { - hilog.error(0, 'testTag', `bindDeviceDriver failed, err: ${JSON.stringify(error)}`); + hilog.error(0, 'testTag', `bindDriverWithDeviceId failed, err: ${JSON.stringify(error)}`); } return null; } ``` -6. Define the **sendMessageRequest** API, and use it to perform IPC with the remote driver object. +6. Defines the **sendMessageRequest** API, and use it to perform IPC with the remote driver object. ```ts private async communicateWithRemote(): Promise { @@ -195,7 +169,7 @@ The following sample code is a demo that illustrates how to develop both the cli } ``` -8. Develop the driver code. For details, see [Peripheral Driver Development](driverextensionability.md). +8. Develop peripheral drivers by following instructions in [UI-free Driver Development](driverextensionability.md). System applications can query detailed information about peripherals and drivers to implement management. The development procedure is as follows: @@ -237,13 +211,30 @@ System applications can query detailed information about peripherals and drivers } ``` - + ## Application Signing **NOTE**
Configure the permission before enabling automatic signing. -You need to configure a signature file for your application to run on a device. Besides, to develop a peripheral driver client, you need to declare the **ohos.permission.ACCESS_EXTENSIONAL_DEVICE_DRIVER** permission for the peripheral. +You need to configure a signature file for your application to run on a device. Besides, to develop a peripheral driver client, you need to declare the **ohos.permission.ACCESS_EXTENSIONAL_DEVICE_DRIVER** and **ohos.permission.ACCESS_DDK_DRIVERS** permissions for the peripheral. +- ohos.permission.ACCESS_EXTENSIONAL_DEVICE_DRIVER (This permission is required for API version 10 or later.) -Automatic signing: [Signing Your App/Service Automatically](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V13/ide-signing-V13#section18815157237) + To obtain authorization on this access permission, [declare it](../../security/AccessToken/declare-permissions.md) in the **requestPermissions** field in the **module.json5** file. + +- ohos.permission.ACCESS_DDK_DRIVERS (This permission is required for API version 18 or later.) + + 1. [Declare the required permissions](../../security/AccessToken/declare-permissions.md) in the **requestPermissions** field in the **module.json5** file. + 2. Modify the **acls** field in the **HarmonyAppProvision** configuration file to request permissions via ACL. For details, see [Requesting Restricted Permissions](../../security/AccessToken/declare-permissions-in-acl.md). + 3. In the **HarmonyAppProvision** configuration file (that is, **Sdk/openharmony/_{Version} _/toolchains /lib/UnsgnedReleasedProfileTemplate.json** file), configure the bundle name of the driver server to connect. If there are multiple servers, separate their bundle names with a comma. -Permission configuration: [Requesting ACL Permissions and Signing Your App/Service](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V13/ide-signing-V13#section157591551175916). + The configuration procedure is as follows: + + Add the **app-services-capabilities** node to the root node of the file and configure the node as follows: + ```json + "app-services-capabilities": { + "ohos.permission.ACCESS_DDK_DRIVERS": {"bundleNames": "bundleName0,bundleName1,bundleName2"} + } + ``` + +Automatic signing: [Signing Your App/Service Automatically](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V13/ide-signing-V13#section18815157237) + diff --git a/en/application-dev/device/driver/figures/ddk-schematic-diagram.png b/en/application-dev/device/driver/figures/ddk-schematic-diagram.png new file mode 100644 index 0000000000000000000000000000000000000000..a71aaafa9ac220c2177ca02572198bdeca9dd36c Binary files /dev/null and b/en/application-dev/device/driver/figures/ddk-schematic-diagram.png differ diff --git "a/zh-cn/application-dev/napi/figures/\350\256\276\345\244\207\350\277\236\346\216\245.png" b/en/application-dev/device/driver/figures/device-connected.png similarity index 100% rename from "zh-cn/application-dev/napi/figures/\350\256\276\345\244\207\350\277\236\346\216\245.png" rename to en/application-dev/device/driver/figures/device-connected.png diff --git a/en/application-dev/device/driver/hid-ddk-guidelines.md b/en/application-dev/device/driver/hid-ddk-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..977130072ae89d566074074da5ce57eaeac86954 --- /dev/null +++ b/en/application-dev/device/driver/hid-ddk-guidelines.md @@ -0,0 +1,315 @@ +# HID DDK Development + +## Overview + +The Human Interface Device (HID) Driver Development Kit (DDK) is a toolset that helps you develop HID drivers at the application layer based on the user mode. It provides APIs for accessing HID devices on a host, including creating a HID device, sending events to a device, destroying a device, opening or closing a device, reading and writing a report, and obtaining device information. + +The HID DDK can be used to develop drivers for devices that use HID protocol to transfer data over a USB bus, or for devices that use peripheral drivers to create virtual devices to exchange information with non-standard devices. + +### Basic Concepts + +Before developing the HID DDK, you must understand the following basic concepts: + +- **HID** + + HID is a type of hardware device that implements interaction between a person and a computer or another electronic device. The primary function of HID is to convert user input (such as a key, a click, or a movement) into a data signal, and send the signal to a host device (such as a computer, tablet, or game console), so that the user can control and operate the device. + +- **DDK** + + DDK is a tool package provided by OpenHarmony for developing drivers for non-standard USB serial port devices based on the peripheral framework. + +### Implementation Principles + +A non-standard peripheral application obtains the HID device ID by using the peripheral management service, and delivers the ID and the action to the HID device driver application through RPC. The driver application calls the HID DDK API to create and destroy a HID device, send events to a HID device, or obtain and parse packets sent from a HID device. The DDK API uses the HDI service to deliver instructions to the kernel driver, and the kernel driver uses instructions to communicate with the device. + +**Figure 1** Principles of invoking the HID DDK + +![HID_DDK schematic diagram](figures/ddk-schematic-diagram.png) + +## Constraints + +* The APIs provided by the HID DDK can be used to develop drivers of non-standard HID devices. + +* The open APIs of HID DDK can be used only within the lifecycle of **DriverExtensionAbility**. + +* Before using the open APIs of the HID DDK, you must declare the matching ACL permissions in **module.json5**, for example, **ohos.permission.ACCESS_DDK_HID**. + +## Available APIs + +| Name| Description| +| -------- | -------- | +| OH_Hid_CreateDevice(Hid_Device *hidDevice, Hid_EventProperties *hidEventProperties) | Creates a HID device. When the device is no longer required, call **OH_Hid_DestroyDevice** to destroy it.| +| OH_Hid_EmitEvent(int32_t deviceId, const Hid_EmitItem items[], uint16_t length) | Sends an event to a HID device.| +| OH_Hid_DestroyDevice(int32_t deviceId) | Destroys a HID device.| +| int32_t OH_Hid_Init(void) | Initializes the HID DDK.| +| int32_t OH_Hid_Release(void) | Releases the HID DDK.| +| int32_t OH_Hid_Open(uint64_t deviceId, uint8_t interfaceIndex, Hid_DeviceHandle **dev) | Opens the device specified by **deviceId** and **interfaceIndex**.| +| int32_t OH_Hid_Close(Hid_DeviceHandle **dev) | Closes a HID device.| +| int32_t OH_Hid_Write(Hid_DeviceHandle *dev, uint8_t *data, uint32_t length, uint32_t *bytesWritten) | Writes a report to a HID device.| +| int32_t OH_Hid_ReadTimeout(Hid_DeviceHandle *dev, uint8_t *data, uint32_t buffSize, int timeout, uint32_t *bytesRead) | Reads a report from a HID device within the specified time.| +| int32_t OH_Hid_Read(Hid_DeviceHandle *dev, uint8_t *data, uint32_t buffSize, uint32_t *bytesRead) | Reads a report from a HID device in the specified mode. The blocking mode (blocking remains active until data can be read) is used by default. You can call **OH_Hid_SetNonBlocking** to change the mode.| +| int32_t OH_Hid_SetNonBlocking(Hid_DeviceHandle *dev, int nonblock) | Sets the device read mode to non-blocking mode.| +| int32_t OH_Hid_GetRawInfo(Hid_DeviceHandle *dev, Hid_RawDevInfo *rawDevInfo) | Obtains the raw information of a HID device.| +| int32_t OH_Hid_GetRawName(Hid_DeviceHandle *dev, char *data, uint32_t buffSize) | Obtains the raw name of a HID device.| +| int32_t OH_Hid_GetPhysicalAddress(Hid_DeviceHandle *dev, char *data, uint32_t buffSize) | Obtains the physical address of a HID device.| +| int32_t OH_Hid_GetRawUniqueId(Hid_DeviceHandle *dev, uint8_t *data, uint32_t buffSize) | Obtains the raw unique identifier of a HID device.| +| int32_t OH_Hid_SendReport(Hid_DeviceHandle *dev, Hid_ReportType reportType, const uint8_t *data, uint32_t length) | Sends a report to a HID device.| +| int32_t OH_Hid_GetReport(Hid_DeviceHandle *dev, Hid_ReportType reportType, uint8_t *data, uint32_t buffSize) | Obtains a report from a HID device.| +| int32_t OH_Hid_GetReportDescriptor(Hid_DeviceHandle *dev, uint8_t *buf, uint32_t buffSize, uint32_t *bytesRead) | Obtains the report descriptor of a HID device.| + +For details about the APIs, see [HID DDK](../../reference/apis-driverdevelopment-kit/_hid_ddk.md). + +## How to Develop + +### Developing a Basic HID Driver + +The following steps you through on how to develop a HID device driver using the HID DDK. + +**Adding Dynamic Link Libraries** + +Add the following libraries to **CMakeLists.txt**. +```txt +libhid.z.so +``` + +**Including Header Files** +```c++ +#include +#include +``` + +1. Create a HID device. + + Call **OH_Hid_CreateDevice** in **hid_ddk_api.h** to create a HID device. If the operation is successful, **deviceId** (a non-negative number) is returned. If the operation fails, an error code (a negative number) is returned. + + ```c++ + // Construct HID device properties. + std::vector deviceProp = {HID_PROP_DIRECT}; + std::string deviceName = "keyboard" + Hid_Device hidDevice = { + .deviceName = deviceName.c_str(), + .vendorId = 0x6006, + .productId = 0x6006, + .version = 1, + .bustype = 3, + .properties = deviceProp.data(), + .propLength = (uint16_t)deviceProp.size() + }; + // Construct the event properties related to the HID device. + std::vector eventType = {HID_EV_ABS, HID_EV_KEY, HID_EV_SYN, HID_EV_MSC}; + Hid_EventTypeArray eventTypeArray = {.hidEventType = eventType.data(), .length = (uint16_t)eventType.size()}; + std::vector keyCode = {HID_BTN_TOOL_PEN, HID_BTN_TOOL_RUBBER, HID_BTN_TOUCH, HID_BTN_STYLUS, HID_BTN_RIGHT}; + Hid_KeyCodeArray keyCodeArray = {.hidKeyCode = keyCode.data(), .length = (uint16_t)keyCode.size()}; + std::vector mscEvent = {HID_MSC_SCAN}; + Hid_MscEventArray mscEventArray = {.hidMscEvent = mscEvent.data(), .length = (uint16_t)mscEvent.size()}; + std::vector absAxes = {HID_ABS_X, HID_ABS_Y, HID_ABS_PRESSURE}; + Hid_AbsAxesArray absAxesArray = {.hidAbsAxes = absAxes.data(), .length = (uint16_t)absAxes.size()}; + Hid_EventProperties hidEventProp = { + .hidEventTypes = eventTypeArray, + .hidKeys = keyCodeArray, + .hidAbs = absAxesArray, + .hidMiscellaneous = mscEventArray + }; + // Create a device. The device ID of the device created is returned. + int32_t deviceId = OH_Hid_CreateDevice(&hidDevice, &hidEventProp); + ``` + +2. Send an event to the HID device. + + Call **OH_Hid_EmitEvent** in **hid_ddk_api.h** to send an event to the device with the specified **deviceId**. + + ```c++ + // Construct the event to be sent. + Hid_EmitItem event = {.type = HID_EV_MSC, .code = HID_MSC_SCAN, .value = 0x000d0042}; + std::vector itemVec; + itemVec.push_back(event); + // Send the event to a HID device. + int32_t ret = OH_Hid_EmitEvent(deviceId, itemVec.data(), (uint16_t)itemVec.size()); + ``` + +3. Release resources. + + Call **OH_Hid_DestroyDevice** in **hid_ddk_api.h** to destroy the device after all requests are processed and before the application exits. + + ```c++ + // Destroy a HID device. + int32_t ret = OH_Hid_DestroyDevice(deviceId); + ``` + +### Developing a HID Packet Communication Driver + +The following steps you through on how to develop a HID packet communication driver using the HID DDK. + +**Adding Dynamic Link Libraries** + +Add the following libraries to **CMakeLists.txt**. +```txt +libhid.z.so +``` + +**Including Header Files** +```c++ +#include +#include +``` + +1. Initialize the HID DDK. + + Call **OH_Hid_Init** in **hid_ddk_api.h** to initialize the HID DDK. + + ```c++ + // Initialize the HID DDK. + OH_Hid_Init(); + ``` + +2. Open the device. + + Call **OH_Hid_Open** in **hid_ddk_api.h** to open a HID device. + + ```c++ + uint64_t deviceId = 0x100000003; + uint8_t interfaceIndex1 = 0; + uint8_t interfaceIndex2 = 1; + Hid_DeviceHandle *dev = NULL; + Hid_DeviceHandle *devFeature = NULL; + // Open the HID device specified by deviceId and interfaceIndex1. Generally, it is a /dev/hidraw0 file. + OH_Hid_Open(deviceId, interfaceIndex1, &dev); + // Open the HID device specified by deviceId and interfaceIndex2. Generally, it is a /dev/hidraw1 file. + OH_Hid_Open(deviceId, interfaceIndex2, &devFeature); + ``` + +3. Write/Send a report (a data packet exchanged between a HID device and a host) to the HID device. + - If the report type is **HID_OUTPUT_REPORT** (output report), you can write/send the report in any of the following ways: + - Call **OH_Hid_Write** in **hid_ddk_api.h** to write an output report to the HID device. + + ```c++ + uint8_t data[] = {0x02, 0x02}; + uint32_t bytesWritten = 0; + // Write a report. + int32_t ret = OH_Hid_Write(dev, data, sizeof(data), &bytesWritten); + ``` + + - Call **OH_Hid_SendReport** in **hid_ddk_api.h** to send an output report to the HID device. + + ```c++ + uint8_t data1[2] = {0x00}; + // Specify the report ID. + data1[0] = 0x02; + // Set the report data. + data1[1] = 0x02; + + // Send an output report. + int32_t ret = OH_Hid_SendReport(dev, HID_OUTPUT_REPORT, data1, sizeof(data1)); + ``` + + - If the report type is **HID_FEATURE_REPORT** (feature report), call **OH_Hid_SendReport** in **hid_ddk_api.h** to send a feature report to the HID device. + + ```c++ + uint8_t data2[2] = {0x00}; + // Specify the report ID. + data2[0] = 0x02; + // Set the report data. + data2[1] = 0x02; + + // Send a feature report. + int32_t ret = OH_Hid_SendReport(devFeature, HID_FEATURE_REPORT, data2, sizeof(data2)); + ``` + +4. Read a report from the HID device. + - If the report type is **HID_INPUT_REPORT** (input report), you can read the report in any of the following ways: + - Call **OH_Hid_Read** or **OH_Hid_ReadTimeout** in **hid_ddk_api.h** to read an input report from the HID device in blocking mode. + + ```c++ + uint8_t data3[9] = {0x00}; + uint32_t bytesRead = 0; + // Read a report from a HID device. + int32_t ret = OH_Hid_Read(dev, data3, sizeof(data3), &bytesRead); + + uint8_t data4[9] = {0x00}; + uint32_t bytesRead = 0; + // Read a report from a HID device within the specified time. + ret = OH_Hid_ReadTimeout(dev, data4, sizeof(data4), 10000, &bytesRead); + ``` + + - Call **OH_Hid_SetNonBlocking** and **OH_Hid_Read** in **hid_ddk_api.h** to read an input report from the HID device in non-blocking mode. + + ```c++ + // 1 means to enable non-blocking, and 0 means to disable non-blocking. + int32_t ret = OH_Hid_SetNonBlocking(dev, 1); + + // Wait for user input if no data is input when the code is executed. + sleep(1); + uint8_t data5[9] = {0}; + uint32_t bytesRead = 0; + // Read a report from a HID device. + ret = OH_Hid_Read(dev, data5, sizeof(data5), &bytesRead); + ``` + + - Call **OH_Hid_GetReport** in **hid_ddk_api.h** to obtain an input report from the HID device. + + ```c++ + uint8_t data6[9] = {0}; + // Specify the report ID. + data6[0] = 0x00; + + // Obtain an input report. + int32_t ret = OH_Hid_GetReport(dev, HID_INPUT_REPORT, data6, sizeof(data6)); + ``` + + - If the report type is **HID_FEATURE_REPORT** (feature report), call **OH_Hid_GetReport** in **hid_ddk_api.h** to obtain a feature report from a HID device. + + ```c++ + uint8_t data7[8] = {0}; + // Specify the report ID. + data7[0] = 0x07; + + // Obtain a feature report. + int32_t ret = OH_Hid_GetReport(devFeature, HID_FEATURE_REPORT, data7, sizeof(data7)); + ``` + +5. Obtain the raw device information, raw name, physical address, and raw unique identifier of a HID device. + + Call **OH_Hid_GetRawInfo** in **hid_ddk_api.h** to obtain the raw information about a HID device.
Call **OH_Hid_GetRawName** to obtain the raw name of a HID device.
Call **OH_Hid_GetPhysicalAddress** to obtain the physical address of a HID device.
Call **OH_Hid_GetRawUniqueId** to obtain the raw unique identifier of a HID device. The obtained information can be referenced by applications, for example, displaying device information on the GUI. + + ```c++ + struct Hid_RawDevInfo rawDevInfo; + int32_t ret = OH_Hid_GetRawInfo(dev, &rawDevInfo); + + char rawName[1024] = {0}; + ret = OH_Hid_GetRawName(dev, rawName, sizeof(rawName)); + + char physicalAddress[1024] = {0}; + ret = OH_Hid_GetPhysicalAddress(dev, physicalAddress, sizeof(physicalAddress)); + + uint8_t uniqueIdData[64] = {0}; + ret = OH_Hid_GetRawUniqueId(dev, uniqueIdData, sizeof(uniqueIdData)); + ``` + +6. Obtain the report descriptor. + + Call **OH_Hid_GetReportDescriptor** in **hid_ddk_api.h** to obtain the HID device report descriptor. + + ```c++ + uint8_t desData[1024] = {0}; + uint32_t bytesRead = 0; + int32_t ret = OH_Hid_GetReportDescriptor(dev, desData, sizeof(desData), &bytesRead); + ``` + +7. Close the HID device. + + Call **OH_Hid_Close** in **hid_ddk_api.h** to close the device. + + ```c++ + // Close the device. + OH_Hid_Close(&dev); + OH_Hid_Close(&devFeature); + ``` + +8. Release the HID DDK. + + After the HID device is closed, call **OH_Hid_Release** in **hid_ddk_api.h** to release the HID DDK. + + ```c++ + // Release the HID DDK. + OH_Hid_Release(); + ``` diff --git a/en/application-dev/device/driver/scsi-peripheral-ddk-guidelines.md b/en/application-dev/device/driver/scsi-peripheral-ddk-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..ba16e88b374a3748460057c8d64d34277d410c00 --- /dev/null +++ b/en/application-dev/device/driver/scsi-peripheral-ddk-guidelines.md @@ -0,0 +1,297 @@ +# SCSI Peripheral DDK Development + +## Overview + +Small Computer System Interface (SCSI) devices, such as disk arrays, tape libraries, and specific types of storage servers, are widely used in enterprise-level storage solutions and industrial application scenarios. If the operating system does not have an adaptation driver for these devices, the devices cannot be identified or used after being connected. SCSI Peripheral Driver Development Kit (DDK) is a suite provided for SCSI device driver development. It allows you to develop SCSI device drivers at the application layer based on the user mode. + +The SCSI Peripheral DDK supports seven common commands (including INQUIRY, READ CAPACITY, TEST UNIT READY, REQUEST SENSE, READ, WRITE, and VERIFY) in the three command sets: SCSI Primary Commands (SPC), SCSI Block Commands (SBC), and Multimedia Commands (MMC). You can use these commands at your preference. + +### Basic Concepts + +Before developing the SCSI Peripheral DDK, you must understand the following basic concepts: + +- **SCSI** + + SCSI is a standard protocol set used for communication between computers and peripherals such as hard disk drives, tape drives, optical disk drives, and scanners. + +- **AMS** + + The Ability Manager Service (AMS) is a system service used to coordinate the running relationships of abilities and schedule the lifecycle of abilities. + +- **BMS** + + The Bundle Manager Service (BMS) is responsible for application installation, uninstallation, and data management on OpenHarmony. + +- **DDK** + + The Driver Development Kit (DDK) is a tool package provided by OpenHarmony for developing drivers for non-standard SCSI peripherals based on the peripheral framework. + +- **Non-standard peripherals** + + Non-standard peripherals (also called custom peripherals or dedicated peripherals) are peripherals that do not comply with general standards or are customized for specific application scenarios. This type of device usually requires special software support or special interfaces to implement communication with the host system. + +- **Standard peripherals** + + Standard peripherals refer to peripherals (such as USB keyboards and mouse devices) that comply with industry standards and specifications. Such devices typically have uniform interface protocols, physical dimensions, and electrical characteristics, so that they can be used interchangeably between different systems. + +- **Logical block** + + A logical block is a basic data storage unit. It represents a data area of a fixed size on a device and is usually used for data read and write operations. The size of a logical block may be 512 bytes, 1024 bytes, 2048 bytes, and so on. A specific size depends on a configuration of the device and a design of the file system. + +- **CDB** + + A command descriptor block (CDB) is a standard data structure used to send commands in the SCSI protocol. A CDB is a byte array with a fixed length. It contains the operation code (Opcode) and related parameters of the SCSI command and is used to instruct the device to perform operations (such as read, write, and query). + +### Implementation Principles + +A non-standard peripheral application obtains the SCSI device ID by using the peripheral management service, and delivers the ID and the action to the SCSI driver application through RPC. The SCSI driver application can obtain the basic information about the SCSI device and read and write data by invoking the SCSI Peripheral DDK API. Then, the DDK API uses the HDI service to deliver instructions to the kernel driver, and the kernel driver uses instructions to communicate with the device. + +**Figure 1** Principle of invoking the SCSI Peripheral DDK + +![SCSI_Peripheral_DDK schematic diagram](figures/ddk-schematic-diagram.png) + +### Constraints + +- The open APIs of SCSI Peripheral DDK support the development of standard SCSI peripheral drivers. + +- The open APIs of SCSI Peripheral DDK can be used only within the lifecycle of **DriverExtensionAbility**. + +- To use the open APIs of SCSI Peripheral DDK, you need to declare the corresponding ACL permission **ohos.permission.ACCESS_DDK_SCSI_PERIPHERAL** in **module.json5**. + +## Environment Setup + +Before you get started, make necessary preparations by following instructions in [Environment Preparation](environmental-preparation.md). + +## How to Develop + +### Available APIs + +| **Name**| Description| +| -------- | -------- | +| int32_t OH_ScsiPeripheral_Init(void) | Initializes the SCSI Peripheral DDK.| +| int32_t OH_ScsiPeripheral_Release(void) | Releases the SCSI Peripheral DDK.| +| int32_t OH_ScsiPeripheral_Open(uint64_t deviceId, uint8_t interfaceIndex, ScsiPeripheral_Device **dev) | Opens the SCSI device specified by **deviceId** and **interfaceIndex**.| +| int32_t OH_ScsiPeripheral_Close(ScsiPeripheral_Device **dev) | Disables the SCSI device.| +| int32_t OH_ScsiPeripheral_TestUnitReady(ScsiPeripheral_Device *dev, ScsiPeripheral_TestUnitReadyRequest *request, ScsiPeripheral_Response *response) | Checks whether the logical units are ready.| +| int32_t OH_ScsiPeripheral_Inquiry(ScsiPeripheral_Device *dev, ScsiPeripheral_InquiryRequest *request, ScsiPeripheral_InquiryInfo *inquiryInfo, ScsiPeripheral_Response *response) | Queries basic information about the SCSI device.| +| int32_t OH_ScsiPeripheral_ReadCapacity10(ScsiPeripheral_Device *dev, ScsiPeripheral_ReadCapacityRequest *request, ScsiPeripheral_CapacityInfo *capacityInfo, ScsiPeripheral_Response *response) | Obtains the capacity information about the SCSI device.| +| int32_t OH_ScsiPeripheral_RequestSense(ScsiPeripheral_Device *dev, ScsiPeripheral_RequestSenseRequest *request, ScsiPeripheral_Response *response) | Obtains sense data, that is, information returned by the SCSI device to the host, which is used to report the device status, error information, and diagnosis information.| +| int32_t OH_ScsiPeripheral_Read10(ScsiPeripheral_Device *dev, ScsiPeripheral_IORequest *request, ScsiPeripheral_Response *response) | Reads data from a specified logical block.| +| int32_t OH_ScsiPeripheral_Write10(ScsiPeripheral_Device *dev, ScsiPeripheral_IORequest *request, ScsiPeripheral_Response *response) | Writes data to a specified logical block of a device.| +| int32_t OH_ScsiPeripheral_Verify10(ScsiPeripheral_Device *dev, ScsiPeripheral_VerifyRequest *request, ScsiPeripheral_Response *response) | Verifies a specified logical block.| +| int32_t OH_ScsiPeripheral_SendRequestByCdb(ScsiPeripheral_Device *dev, ScsiPeripheral_Request *request, ScsiPeripheral_Response *response) | Sends the SCSI command in CDB mode.| +| int32_t OH_ScsiPeripheral_CreateDeviceMemMap(ScsiPeripheral_Device *dev, size_t size, ScsiPeripheral_DeviceMemMap **devMmap) | Creates a buffer.| +| int32_t OH_ScsiPeripheral_DestroyDeviceMemMap(ScsiPeripheral_DeviceMemMap *devMmap) | Destroys a buffer.| +| int32_t OH_ScsiPeripheral_ParseBasicSenseInfo(uint8_t *senseData, uint8_t senseDataLen, ScsiPeripheral_BasicSenseInfo *senseInfo) | Parses basic sense data, including the **Information**, **Command specific information**, and **Sense key specific** fields.| + +For details about the interface, see [SCSI Peripheral DDK](../../reference/apis-driverdevelopment-kit/_s_c_s_i.md). + +### How to Develop + +The following describes how to use the SCSI Peripheral DDK to develop non-standard SCSI peripheral drivers. + +**Adding Dynamic Link Libraries** + +Add the following libraries to **CMakeLists.txt**. +```txt +libscsi.z.so +``` + +**Including Header Files** +```c++ +#include +#include +``` + +1. Initialize the SCSI Peripheral DDK. + + Use **OH_ScsiPeripheral_Init** in **scsi_peripheral_api.h** to initialize the SCSI Peripheral DDK. + + ```c++ + // Initialize the SCSI Peripheral DDK. + int32_t ret = OH_ScsiPeripheral_Init(); + ``` + +2. Open the device. + + After the SCSI Peripheral DDK is initialized, use **OH_ScsiPeripheral_Open** in **scsi_peripheral_api.h** to open the SCSI device. + + ```c++ + uint64_t deviceId = 0x100000003; + uint8_t interfaceIndex = 0; + ScsiPeripheral_Device *dev = NULL; + // Open the SCSI device specified by deviceId and interfaceIndex1. + ret = OH_ScsiPeripheral_Open(deviceId, interfaceIndex, &dev); + ``` + +3. Create a buffer. + + Use **OH_ScsiPeripheral_CreateDeviceMemMap** in **scsi_peripheral_api.h** to create the memory buffer **devMmap**. + + ```c++ + constexpr size_t DEVICE_MEM_MAP_SIZE = 1024; + ScsiPeripheral_DeviceMemMap *g_scsiDeviceMemMap = nullptr; + ret = OH_ScsiPeripheral_CreateDeviceMemMap(dev, DEVICE_MEM_MAP_SIZE, &g_scsiDeviceMemMap); + ``` + +4. Check whether the logical units are ready. + + Use **OH_ScsiPeripheral_TestUnitReady** in **scsi_peripheral_api.h** to check whether the logical unit is ready. + + ```c++ + ScsiPeripheral_TestUnitReadyRequest testUnitReadyRequest = {0}; + testUnitReadyRequest.timeout = 5000; + ScsiPeripheral_Response testUnitReadyResponse = {0}; + ret = OH_ScsiPeripheral_TestUnitReady(dev, &testUnitReadyRequest, &testUnitReadyResponse); + ``` + +5. Query basic information about the SCSI device. + + Use **OH_ScsiPeripheral_Inquiry** in **scsi_peripheral_api.h** to obtain the basic information about the SCSI device. + + ```c++ + ScsiPeripheral_InquiryRequest inquiryRequest = {0}; + inquiryRequest.allocationLength = 512; + inquiryRequest.timeout = 5000; + ScsiPeripheral_InquiryInfo inquiryInfo = {0}; + inquiryInfo.data = g_scsiDeviceMemMap; + ScsiPeripheral_Response inquiryResponse = {0}; + ret = OH_ScsiPeripheral_Inquiry(dev, &inquiryRequest, &inquiryInfo, &inquiryResponse); + ``` + +6. Obtain the capacity information about the SCSI device. + + Use **OH_ScsiPeripheral_ReadCapacity10** in **scsi_peripheral_api.h** to obtain the SCSI device capacity information. + + ```c++ + ScsiPeripheral_ReadCapacityRequest readCapacityRequest = {0}; + readCapacityRequest.lbAddress = 0; + readCapacityRequest.control = 0; + readCapacityRequest.byte8 = 0; + readCapacityRequest.timeout = 5000; + ScsiPeripheral_CapacityInfo capacityInfo = {0}; + ScsiPeripheral_Response readCapacityResponse = {0}; + ret = OH_ScsiPeripheral_ReadCapacity10(dev, &readCapacityRequest, &capacityInfo, &readCapacityResponse); + ``` + +7. Obtain sense data. + + Use **OH_ScsiPeripheral_RequestSense** in **scsi_peripheral_api.h** to obtain sense data. + + ```c++ + ScsiPeripheral_RequestSenseRequest senseRequest = {0}; + senseRequest.allocationLength = SCSIPERIPHERAL_MAX_SENSE_DATA_LEN + 1; + senseRequest.control = 0; + senseRequest.byte1 = 0; + senseRequest.timeout = 5000; + ScsiPeripheral_Response senseResponse = {0}; + // Information returned by the SCSI device to the host, used to report the device status, error information, and diagnosis information. + ret = OH_ScsiPeripheral_RequestSense(dev, &senseRequest, &senseResponse); + ``` + +8. Parse the sense data. + + Use **OH_ScsiPeripheral_ParseBasicSenseInfo** in **scsi_peripheral_api.h** to parse basic sense data, including the **Information**, **Command specific information**, and **Sense key specific** fields. + + ```c++ + ScsiPeripheral_BasicSenseInfo senseInfo = {0}; + ret = OH_ScsiPeripheral_ParseBasicSenseInfo(senseResponse.senseData, SCSIPERIPHERAL_MAX_SENSE_DATA_LEN, &senseInfo); + ``` + +9. Read data. + + Use **OH_ScsiPeripheral_Read10** in **scsi_peripheral_api.h** to read data from a specified logical block. + + ```c++ + ScsiPeripheral_IORequest readRequest = {0}; + readRequest.lbAddress = 1; + readRequest.transferLength = 1; + readRequest.control = 0; + readRequest.byte1 = 0; + readRequest.byte6 = 0; + readRequest.timeout = 20000; + readRequest.data = g_scsiDeviceMemMap; + ScsiPeripheral_Response readResponse = {0}; + ret = OH_ScsiPeripheral_Read10(dev, &readRequest, &readResponse); + ``` + +10. Write data. + + Use **OH_ScsiPeripheral_Write10** in **scsi_peripheral_api.h** to write data to a specified logical block of the device. + + ```c++ + ScsiPeripheral_IORequest writeRequest = {0}; + writeRequest.lbAddress = 1; + writeRequest.transferLength = 1; + writeRequest.control = 0; + writeRequest.byte1 = 0; + writeRequest.byte6 = 0; + writeRequest.timeout = 5000; + writeRequest.data = g_scsiDeviceMemMap; + ScsiPeripheral_Response writeResponse = {0}; + ret = OH_ScsiPeripheral_Write10(dev, &writeRequest, &writeResponse); + ``` + +11. Verifies a specified logical block. + + Use **OH_ScsiPeripheral_Verify10** in **scsi_peripheral_api.h** to verify a specified logical block. + + ```c++ + ScsiPeripheral_VerifyRequest verifyRequest = {0}; + verifyRequest.lbAddress = 1; + verifyRequest.verificationLength = 1; + verifyRequest.timeout = 5000; + ScsiPeripheral_Response verifyResponse = {0}; + ret = OH_ScsiPeripheral_Verify10(dev, &verifyRequest, &verifyResponse); + ``` + +12. Send SCSI commands in CDB mode. + + Use **OH_SCSIPeripheral_SendRequestByCdb** in **scsi_peripheral_api.h** to send SCSI commands. + + ```c++ + ScsiPeripheral_Request sendRequest = {0}; + uint8_t cdbData[SCSIPERIPHERAL_MAX_CMD_DESC_BLOCK_LEN] = {0x28, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; // The cstring header file needs to be imported. + memcpy(sendRequest.commandDescriptorBlock, cdbData, SCSIPERIPHERAL_MAX_CMD_DESC_BLOCK_LEN); + sendRequest.cdbLength = 10; + sendRequest.dataTransferDirection = -3; + sendRequest.timeout = 5000; + sendRequest.data = g_scsiDeviceMemMap; + ScsiPeripheral_Response sendResponse = {0}; + ret = OH_ScsiPeripheral_SendRequestByCdb(dev, &sendRequest, &sendResponse); + ``` + +13. Destroy the buffer. + + After all requests are processed and before the program exits, use **OH_ScsiPeripheral_DestroyDeviceMemMap** in **scsi_peripheral_api.h** to destroy the buffer. + + ```c++ + ret = OH_ScsiPeripheral_DestroyDeviceMemMap(g_scsiDeviceMemMap); + ``` + +14. Close the HID device. + + After the buffer is destroyed, use **OH_ScsiPeripheral_Close** in **scsi_peripheral_api.h** to close the device. + + ```c++ + // Stop the SCSI device. + ret = OH_ScsiPeripheral_Close(&dev); + ``` + +15. Release the SCSI Peripheral DDK. + + After the SCSI device is closed, use **OH_ScsiPeripheral_Release** in **scsi_peripheral_api.h** to release the SCSI Peripheral DDK. + + ```c++ + // Release the SCSI Peripheral DDK. + ret = OH_ScsiPeripheral_Release(); + ``` + +### Debugging and Verification + +Upon completion of driver application development, you can install the application on the OpenHarmony device. The test procedure is as follows: + +1. Click the driver application on the device. The application is started on the device. +2. Check whether the application can read the basic information about the SCSI device. +3. Select a SCSI command, enter parameters, and click the **Send** button. +4. (Optional) Set the direction, CDB data, and CDB length, and click the **Send** button to run the corresponding SCSI command. diff --git a/en/application-dev/device/driver/terms.md b/en/application-dev/device/driver/terms.md new file mode 100644 index 0000000000000000000000000000000000000000..8ff2ccf5d32cd9747f80c9e8f00cb1058eff069f --- /dev/null +++ b/en/application-dev/device/driver/terms.md @@ -0,0 +1,61 @@ +# Terms + +## A + +### AMS + + The Ability Manager Service (AMS) is a system service used to coordinate the running relationships of abilities and schedule the lifecycle of abilities. You can use it to start and disable **DriverExtensionAbility** during driver development. + +## B + +### BMS + + The Bundle Manager Service (BMS) is responsible for application installation, uninstallation, and data management on OpenHarmony. + +## C + +### CDB + + A command descriptor block (CDB) is a standard data structure used to send commands in the SCSI protocol. A CDB is a byte array with a fixed length. It contains the operation code (Opcode) and related parameters of the SCSI command and is used to instruct the device to perform operations (such as read, write, and query). + +## D + +### DDK + + The Driver Development Kit (DDK) is a tool package provided by OpenHarmony for developing drivers for non-standard USB serial port devices based on the peripheral framework. + +## H + +### HID device + + HID is short for Human Interface Device. An HID device is used for interaction between a person and a computer or another electronic device, and is mainly used for input and output operations. + +### HID protocol + + The HID protocol is a standard communication protocol specially designed for human-machine interaction devices. It implements efficient communication between devices and hosts through report descriptors and data reports. It boasts features like plug-and-play, low latency, low bandwidth, and high compatibility, and is widely used in various input and control devices. + +## L + +### Logical Block + + A logical block is a basic data storage unit. It represents a data area of a fixed size on a device and is usually used for data read and write operations. The size of a logical block may be 512 bytes, 1024 bytes, 2048 bytes, and so on. A specific size depends on a configuration of the device and a design of the file system. + +## S + +### SCSI + + SCSI is a standard protocol set used for communication between computers and peripherals such as hard disk drives, tape drives, optical disk drives, and scanners. + +## U + +### USB serial port + + USB-to-Serial is an interface conversion technology that allows data communication with traditional serial ports (such as RS-232 and RS-485) over USB interfaces. This technology is usually implemented by using a dedicated hardware adapter or a specific built-in chip. + +## Non-standard peripherals + + Non-standard peripherals (also called custom peripherals or dedicated peripherals) are peripherals that do not comply with general standards or are customized for specific application scenarios. This type of device usually requires special software support or special interfaces to implement communication with the host system. + +## Standard peripherals + + Standard peripherals refer to peripherals (such as USB keyboards and mouse devices) that comply with industry standards and specifications. Such devices typically have uniform interface protocols, physical dimensions, and electrical characteristics, so that they can be used interchangeably between different systems. diff --git a/en/application-dev/device/driver/usb-ddk-guidelines.md b/en/application-dev/device/driver/usb-ddk-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..fb73b7385451d1ad21ebac1de9ca6c7513c8611e --- /dev/null +++ b/en/application-dev/device/driver/usb-ddk-guidelines.md @@ -0,0 +1,195 @@ +# USB DDK Development + +## Overview + +The USB Driver Development Kit (DDK) is a toolset that helps you develop USB device drivers at the application layer based on the user mode. It provides a series of device access APIs, for example, opening and closing USB interfaces, and performing non-isochronous transfer, isochronous transfer, control transfer, and interrupt transfer over USB pipes. + +The USB DDK can be used to develop device drivers for all devices that use the USB protocol to transfer data over a USB bus. For the peripherals that are not supported by standard kernel drivers, you can use the peripheral driver application developed based on the USB DDK to implement unique device capabilities. + +### Basic Concepts + +Before developing the USB DDK, you must understand the following basic concepts: + +- **USB** + + Universal Serial Bus (USB) is a widely used interface technology that connects a computer to various external devices, such as a keyboard, mouse, printer, storage device, and smartphone. The USB is designed to provide a standardized, efficient, and easy-to-use connection mode that replaces the traditional serial and parallel interface communication. + +- **DDK** + + DDK is a tool package provided by OpenHarmony for developing drivers for non-standard USB serial port devices based on the peripheral framework. + +### Implementation Principles + +A non-standard peripheral application obtains the USB device ID by using the peripheral management service, and delivers the ID and the action to the USB driver application through RPC. The USB driver application can obtain or set the device descriptor and initiate a control transfer or interrupt transfer request by calling the USB DDK API. Then, the DDK API uses the HDI service to deliver instructions to the kernel driver, and the kernel driver uses instructions to communicate with the device. + +**Figure 1** Principles of invoking the USB DDK + +![USB_DDK schematic diagram](figures/ddk-schematic-diagram.png) + +## Constraints + +* The open APIs of USB DDK can be used to develop drivers of non-standard USB peripherals. + +* The open APIs of USB DDK can be used only within the lifecycle of **DriverExtensionAbility**. + +* To use the open APIs of the USB DDK, you need to declare the matching ACL permissions in **module.json5**, for example, **ohos.permission.ACCESS_DDK_USB**. + +## Environment Setup + +Before you get started, make necessary preparations by following instructions in [Environment Preparation](environmental-preparation.md). + +## How to Develop + +### Available APIs + +| Name| Description| +| -------- | -------- | +| OH_Usb_Init(void) | Initializes the USB DDK.| +| OH_Usb_Release(void) | Releases the USB DDK.| +| OH_Usb_GetDeviceDescriptor(uint64_t deviceId, struct UsbDeviceDescriptor *desc) | Obtains the device descriptor of a USB device.| +| OH_Usb_GetConfigDescriptor(uint64_t deviceId, uint8_t configIndex, struct UsbDdkConfigDescriptor **const config) | Obtains a USB configuration descriptor. To avoid memory leakage, use **OH_Usb_FreeConfigDescriptor()** to release a descriptor after use.| +| OH_Usb_FreeConfigDescriptor(const struct UsbDdkConfigDescriptor *const config) | Releases a configuration descriptor. To avoid memory leakage, release a descriptor in time after use.| +| OH_Usb_ClaimInterface(uint64_t deviceId, uint8_t interfaceIndex, uint64_t *interfaceHandle) | Declares a USB interface.| +| OH_Usb_SelectInterfaceSetting(uint64_t interfaceHandle, uint8_t settingIndex) | Activates the alternate setting of a USB interface.| +| OH_Usb_GetCurrentInterfaceSetting(uint64_t interfaceHandle, uint8_t \*settingIndex) | Obtains the alternate setting of a USB interface.| +| OH_Usb_SendControlReadRequest(uint64_t interfaceHandle, const struct UsbControlRequestSetup \*setup, uint32_t timeout, uint8_t \*data, uint32_t \*dataLen) | Sends a control read transfer request. This API returns the result synchronously.| +| OH_Usb_SendControlWriteRequest(uint64_t interfaceHandle, const struct UsbControlRequestSetup \*setup, uint32_t, const uint8_t \*data, uint32_t dataLen) | Sends a control write transfer request. This API returns the result synchronously.| +| OH_Usb_ReleaseInterface(uint64_t interfaceHandle) | Releases a USB interface.| +| OH_Usb_SendPipeRequest(const struct UsbRequestPipe *pipe, UsbDeviceMemMap *devMmap) | Sends a pipe request. This API returns the result synchronously. It applies to interrupt transfer and bulk transfer.| +| OH_Usb_CreateDeviceMemMap(uint64_t deviceId, size_t size, UsbDeviceMemMap **devMmap) | Create a buffer. To avoid resource leakage, use **OH_Usb_DestroyDeviceMemMap()** to destroy a buffer after use.| +| OH_Usb_DestroyDeviceMemMap(UsbDeviceMemMap *devMmap) | Destroy a buffer. To avoid resource leakage, destroy a buffer in time after use.| +| OH_Usb_GetDevices(struct Usb_DeviceArray *devices) | Obtains the USB device ID list. Ensure that the input pointer is valid and the number of devices does not exceed 128. To prevent resource leakage, release the member memory after usage. Besides, make sure that the obtained USB device ID has been filtered by **vid** in the driver configuration information.| + +For details about the APIs, see [USB DDK](../../reference/apis-driverdevelopment-kit/_usb_ddk.md). + +### How to Develop + +To develop a USB driver using the USB DDK, perform the following steps: + +**Adding Dynamic Link Libraries** + +Add the following libraries to **CMakeLists.txt**. +```txt +libusb_ndk.z.so +``` + +**Including Header Files** +```c++ +#include +#include +``` + +1. Obtain the device descriptor of a USB device. + + Call **OH_Usb_Init** of **usb_ddk_api.h** to initialize the USB DDK, and call **OH_Usb_GetDeviceDescriptor** to obtain the device descriptor. + + ```c++ + // Initialize the USB DDK. + OH_Usb_Init(); + struct UsbDeviceDescriptor devDesc; + uint64_t deviceId = 0; + // Obtain the device descriptor. + OH_Usb_GetDeviceDescriptor(deviceId, &devDesc); + ``` + +2. Obtain a configuration descriptor, and declare the USB interface. + + Call **OH_Usb_GetConfigDescriptor** of **usb_ddk_api.h** to obtain the configuration descriptor **config**, and call **OH_Usb_ClaimInterface** to declare claiming of the USB interface. + + ```c++ + struct UsbDdkConfigDescriptor *config = nullptr; + // Obtain the configuration descriptor. + OH_Usb_GetConfigDescriptor(deviceId, 1, &config); + // Obtain the index of the target USB interface based on the configuration descriptor. + uint8_t interfaceIndex = 0; + // Declare the USB interface. + uint64_t interfaceHandle = 0; + OH_Usb_ClaimInterface(deviceId, interfaceIndex, &interfaceHandle); + // Release the configuration descriptor. + OH_Usb_FreeConfigDescriptor(config); + ``` +3. Obtain the activated alternate setting of a USB interface. + + Call **OH_Usb_GetCurrentInterfaceSetting** of **usb_ddk_api.h** to obtain the alternate setting, and call **OH_Usb_SelectInterfaceSetting** to activate it. + + ```c++ + uint8_t settingIndex = 0; + // Obtain the alternate setting. + OH_Usb_GetCurrentInterfaceSetting(interfaceHandle, &settingIndex); + + // Activate the alternate setting. + OH_Usb_SelectInterfaceSetting(interfaceHandle, &settingIndex); + ``` +4. Send control read requests and control write requests. + + Call **OH_Usb_SendControlReadRequest** of **usb_ddk_api.h** to send a control read request, or call **OH_Usb_SendControlWriteRequest** to send a control write request. + + ```c++ + // Timeout interval. Set it to 1s. + uint32_t timeout = 1000; + + struct UsbControlRequestSetup setupRead; + setupRead.bmRequestType = 0x80; + setupRead.bRequest = 0x08; + setupRead.wValue = 0; + setupRead.wIndex = 0; + setupRead.wLength = 0x01; + uint8_t dataRead[256] = {0}; + uint32_t dataReadLen = 256; + // Send a control read request. + OH_Usb_SendControlReadRequest(interfaceHandle, &setupRead, timeout, dataRead, &dataReadLen); + + struct UsbControlRequestSetup setupWrite; + setupWrite.bmRequestType = 0; + setupWrite.bRequest = 0x09; + setupWrite.wValue = 1; + setupWrite.wIndex = 0; + setupWrite.wLength = 0; + uint8_t dataWrite[256] = {0}; + uint32_t dataWriteLen = 256; + // Send a control write request. + OH_Usb_SendControlWriteRequest(interfaceHandle, &setupWrite, timeout, dataWrite, &dataWriteLen); + ``` + +5. Create a buffer, and send a request. + + Call **OH_Usb_CreateDeviceMemMap** of **usb_ddk_api.h** to create the buffer **devMmap**, and call **OH_Usb_SendPipeRequest** to send a request. + + ```c++ + struct UsbDeviceMemMap *devMmap = nullptr; + // Create a buffer for storing data. + size_t bufferLen = 10; + OH_Usb_CreateDeviceMemMap(deviceId, bufferLen, &devMmap); + struct UsbRequestPipe pipe; + pipe.interfaceHandle = interfaceHandle; + // Obtain the target endpoint based on the configuration descriptor. + pipe.endpoint = 128; + pipe.timeout = UINT32_MAX; + // Send a request. + OH_Usb_SendPipeRequest(&pipe, devMmap); + ``` + +6. Release resources. + + After all requests are processed and before the application exits, call **OH_Usb_DestroyDeviceMemMap** of **usb_ddk_api.h** to destroy the buffer, call **OH_Usb_ReleaseInterface** to release the USB interface, , and call **OH_Usb_Release** to release the USB DDK. + + ```c++ + // Destroy the buffer. + OH_Usb_DestroyDeviceMemMap(devMmap); + // Release the USB interface. + OH_Usb_ReleaseInterface(interfaceHandle); + // Release the USB DDK. + OH_Usb_Release(); + ``` +7. (Optional) Obtain the USB device ID list. + + After the driver is started, call **OH_Usb_GetDevices** to obtain the device ID that matches the VID in the driver configuration for subsequent application development. (VID is the ID of the device vendor and is configured in the driver application to indicate the applicable devices. The queried device IDs need to be filtered by VID.) + + ```c++ + OH_Usb_Init(); + constexpr size_t MAX_USB_DEVICE_NUM = 128; + struct Usb_DeviceArray deviceArray; + deviceArray.deviceIds = new uint64_t[MAX_USB_DEVICE_NUM]; + // Obtain the USB device list. + OH_Usb_GetDevices(&deviceArray); + ``` diff --git a/en/application-dev/device/driver/usb-serial-ddk-guidelines.md b/en/application-dev/device/driver/usb-serial-ddk-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..7046e252637c96542656a8dc23c466025c271ed1 --- /dev/null +++ b/en/application-dev/device/driver/usb-serial-ddk-guidelines.md @@ -0,0 +1,194 @@ +# USB Serial DDK Development + +## Overview + +Non-standard serial port devices, such as temperature and humidity meters and special identity card readers, are used in industrial scenarios and on some legacy devices. If the system does not have a driver that adapts to the devices, the devices cannot be used after being connected. The USB Serial Driver Development Kit (DDK) is a toolset that helps you develop USB serial drivers at the application layer based on the user mode. The USB Serial DDK provides a series of APIs for the host to access devices, including APIs for enabling and disabling devices on the host and read/write data through serial ports. With the driver development APIs provided by OpenHarmony, third-party peripherals are able to access the ecosystem conveniently. + +### Basic Concepts + +Before developing the SCSI Peripheral DDK, you must understand the following basic concepts: + +- **USB serial port** + + USB-to-Serial is an interface conversion technology that allows data communication with traditional serial ports (such as RS-232 and RS-485) over USB interfaces. This technology is usually implemented by using a dedicated hardware adapter or a specific built-in chip. + +- **AMS** + + The Ability Manager Service (AMS) is a system service used to coordinate the running relationships of abilities and schedule the lifecycle of abilities. You can use it to start and disable **DriverExtensionAbility** during driver development. + +- **BMS** + + The Bundle Manager Service (BMS) is responsible for application installation, uninstallation, and data management on OpenHarmony. + +- **DDK** + + DDK is a tool package provided by OpenHarmony for developing drivers for non-standard USB serial port devices based on the peripheral framework. + +- **Non-standard peripherals** + + Non-standard peripherals (also called custom peripherals or dedicated peripherals) are peripherals that do not comply with general standards or are customized for specific application scenarios. This type of device usually requires special software support or special interfaces to implement communication with the host system. + +- **Standard peripherals** + + Standard peripherals refer to peripherals (such as USB keyboards and mouse devices) that comply with industry standards and specifications. Such devices typically have uniform interface protocols, physical dimensions, and electrical characteristics, so that they can be used interchangeably between different systems. + +### Implementation Principles + +A non-standard peripheral application obtains the USB serial port device ID by using the peripheral management service, and delivers the ID and the action to the USB serial port driver application through RPC. The USB serial port driver application can set the serial port attributes (such as the baud rate, data bit, and parity bit) and read the serial port data by calling the USB Serial DDK API. Then, the DDK API uses the HDI service to deliver instructions to the kernel driver, and the kernel driver uses instructions to communicate with the device. + +**Figure 1** Principles of invoking the USB Serial DDK + +![USBSerial_DDK schematic diagram](figures/ddk-schematic-diagram.png) + +### Constraints + +- The open APIs of USB Serial DDK can be used to develop drivers of non-standard USB peripherals that use USB serial ports. + +- The open APIs of USB Serial DDK can be used only within the **DriverExtensionAbility** lifecycle. + +- To use the open APIs of USB Serial DDK, you need to declare the matching ACL permissions in **module.json5**, for example, **ohos.permission.ACCESS_DDK_USB_SERIAL**. + +## Environment Setup + +Before you get started, make necessary preparations by following instructions in [Environment Preparation](environmental-preparation.md). + +## How to Develop + +### Available APIs + +| Name| Description| +| -------- | -------- | +| OH_UsbSerial_Init(void) | Initializes the USB Serial DDK.| +| OH_UsbSerial_Release(void) | Releases the USB Serial DDK.| +| OH_UsbSerial_Open(uint64_t deviceId, uint8_t interfaceIndex, UsbSerial_Device **dev) | Opens the USB serial port device based on the specified **deviceId** and **interfaceIndex**. Call **OH_UsbSerial_Close ()** to close the device after use. Otherwise, memory leakage occurs.| +| OH_UsbSerial_Close(UsbSerial_Device **dev) | Closes the USB serial port device after use. Otherwise, memory leakage occurs.| +| OH_UsbSerial_Read(UsbSerial_Device *dev, uint8_t *buff, uint32_t bufferSize, uint32_t *bytesRead) | Reads data from the USB serial port device to the buffer.| +| OH_UsbSerial_Write(UsbSerial_Device *dev, uint8_t *buff, uint32_t bufferSize, uint32_t *bytesWritten) | Writes the data in the buffer to the USB serial port device.| +| OH_UsbSerial_SetBaudRate(UsbSerial_DeviceHandle *dev, uint32_t baudRate) | Sets the baud rate for a USB serial port device. Call this API if the data bit of the serial port is **8**, the stop bit is **1**, and parity check is not performed.| +| OH_UsbSerial_SetParams(UsbSerial_Device *dev, UsbSerial_Params *params) | Sets the parameters of the USB serial port device, including the baud rate, data transfer bit, stop bit, and parity check.| +| OH_UsbSerial_SetTimeout(UsbSerial_Device *dev, int timeout) | Sets the timeout interval for reading data reported by a USB serial port device. The default value is **0**.| +| OH_UsbSerial_SetFlowControl(UsbSerial_Device *dev, UsbSerial_FlowControl flowControl) | Sets flow control parameters.| +| OH_UsbSerial_Flush(UsbSerial_Device *dev) | Flushes the input and output buffers after the write operation is complete.| +| OH_UsbSerial_FlushInput(UsbSerial_Device *dev) | Refreshes the input buffer. The data in the buffer is cleared immediately.| +| OH_UsbSerial_FlushOutput(UsbSerial_Device *dev) | Refreshes the output buffer. The data in the buffer is cleared immediately.| + +For details about the APIs, see [USB Serial DDK](../../reference/apis-driverdevelopment-kit/_serial_ddk.md). + +### How to Develop + +To develop the USB serial port driver by using the USB Serial DDK, perform the following steps: + +**Adding Dynamic Link Libraries** + +Add the following libraries to **CMakeLists.txt**. +```txt +libusb_serial_ndk.z.so +``` + +**Including Header Files** +```c++ +#include +#include +``` + +1. Initialize the USB Serial DDK. + + Use **OH_UsbSerial_Init** in **usb_serial_api.h** to initialize the USB Serial DDK. + + ```c++ + // Initialize the USB Serial DDK. + OH_UsbSerial_Init(); + ``` + +2. Open the USB serial port device. + + Use **OH_UsbSerial_Open** in **usb_serial_api.h** to enable the device. + + ```c++ + UsbSerial_Device *dev = NULL; + uint64_t deviceId = 1688858450198529; + uint8_t interfaceIndex = 0; + // Open the USB serial port device specified by deviceId and interfaceIndex. + OH_UsbSerial_Open(deviceId, interfaceIndex, &dev); + ``` + +3. Sets the parameters of the USB serial port device. + + Use **OH_UsbSerial_SetParams** in **usb_serial_api.h** to set the serial port parameters, or directly use **OH_UsbSerial_SetBaudRate** to set the baud rate, and use **OH_UsbSerial_SetTimeout** to set the timeout interval for reading data. + + ```c++ + UsbSerial_Params params; + params.baudRate = 9600; + params.nDataBits = 8; + params.nStopBits = 1; + params.parity = 0; + // Set serial port parameters. + OH_UsbSerial_SetParams(dev, ¶ms); + + // Set the baud rate. + uint32_t baudRate = 9600; + OH_UsbSerial_SetBaudRate(dev, baudRate); + + // Set the timeout interval. + int timeout = 500; + OH_UsbSerial_SetTimeout(dev, timeout); + ``` + +4. Set flow control and flush the buffer. + + Use **OH_UsbSerial_SetFlowControl** in **usb_serial_api.h** to set the flow control mode, use **OH_UsbSerial_Flush** to flush the buffer, use **OH_UsbSerial_FlushInput** to flush the input buffer, and use **OH_UsbSerial_FlushOutput** to flush the output buffer. + + ```c++ + // Set flow control. + OH_UsbSerial_SetFlowControl(dev, USB_SERIAL_SOFTWARE_FLOW_CONTROL); + + // Flush the buffer. + OH_UsbSerial_Flush(dev); + + // Flush the input buffer. + OH_UsbSerial_FlushInput(dev); + + // Flush the output buffer. + OH_UsbSerial_FlushOutput(dev); + ``` +5. Write or read data to or from a USB serial port device. + + Use **OH_UsbSerial_Write** in **usb_serial_api.h** to send data to the device, and use **OH_UsbSerial_Read** to read the data sent by the device. + + ```c++ + uint32_t bytesWritten = 0; + // Command used by the test device to read data. The command varies depending on the device protocol. + uint8_t writeBuff[8] = {0x01, 0x03, 0x00, 0x00, 0x00, 0x01, 0x84, 0xA}; + // Send data over the connection. + OH_UsbSerial_Write(dev, writeBuff, sizeof(writeBuff), &bytesWritten); + + // Callback invoked to receive data. + uint8_t readBuff[100]; + uint32_t bytesRead = 0; + OH_UsbSerial_Read(dev, readBuff, sizeof(readBuff), &bytesRead); + ``` + +6. Close the USB serial port device. + + After all requests are processed and before the program exits, use **OH_UsbSerial_Close** in **usb_serial_api.h** to close the device. + ```c++ + // Close the device. + OH_UsbSerial_Close(&dev); + ``` + +7. Release the USB Serial DDK. + + After the USB serial port device is closed, use **OH_UsbSerial_Release** in **usb_serial_api.h** to release the USB Serial DDK. + + ```c++ + // Release the USB Serial DDK. + OH_UsbSerial_Release(); + ``` + +### Debugging and Verification + +Upon completion of driver application development, you can install the application on the OpenHarmony device. The test procedure is as follows: + +1. Click the driver application on the device. The application is started on the device. +2. Click the set button to set serial port attributes such as the baud rate. +3. Click the data read button to read the data of the serial port device. diff --git a/en/application-dev/device/input/Readme-EN.md b/en/application-dev/device/input/Readme-EN.md index 42388f2623b378adc5885b19435b2a9317fc44f8..9c00dae272a1e09b8d427cb17be9481950ee9a38 100644 --- a/en/application-dev/device/input/Readme-EN.md +++ b/en/application-dev/device/input/Readme-EN.md @@ -1,4 +1,4 @@ -# Input Kit (Multimodal Input) +# Input Kit (Multimodal Input) - [Introduction to Input Kit](input-overview.md) - [Input Device Development](inputdevice-guidelines.md) @@ -6,7 +6,6 @@ - [Input Monitor Development](inputmonitor-guidelines.md) - [Event Injection Development](inputeventclient-guidelines.md) - [Input Consumer Development](inputconsumer-guidelines.md) -- [Shortcut Key Development](shortkey-guidelines.md) +- [Shortcut Key Development](shortkey-guidelines.md) - [Event Listening Development (C/C++)](monitor-guidelines.md) - [Event Interception Development (C/C++)](interceptor-guidelines.md) - diff --git a/en/application-dev/device/input/inputmonitor-guidelines.md b/en/application-dev/device/input/inputmonitor-guidelines.md index 10ccbe54147342dec9779f82094c2b14c937bf3b..db2ebbfbd334dbdeb534bc745f9950ddfb255387 100644 --- a/en/application-dev/device/input/inputmonitor-guidelines.md +++ b/en/application-dev/device/input/inputmonitor-guidelines.md @@ -16,20 +16,20 @@ The following table lists the common APIs provided by the **inputMonitor** modul | API | Description| | ------------------------------------------------------------ | -------------------------- | -| on(type: 'mouse', receiver: Callback): void |Listens for mouse events.| +| on(type: 'mouse', receiver: Callback<MouseEvent>): void |Listens for mouse events.| | on(type: 'touch', receiver: TouchEventReceiver): void | Listens for touchscreen events.| | on(type: 'pinch', receiver: TouchEventReceiver): void | Listens for pinch events.| -| on(type: 'threeFingersSwipe', receiver: Callback): void | Listens for three-finger swipe-up events.| -| on(type: 'threeFingersTap', receiver: Callback): void | Listens for three-finger tap events.| -| on(type: 'fourFingersSwipe', receiver: Callback): void | Listens for four-finger swipe events.| -| on(type: 'rotate', fingers: number, receiver: Callback): void | Listens for rotation events.| -| off(type: 'mouse', receiver: Callback): void |Cancels listening for mouse events.| +| on(type: 'threeFingersSwipe', receiver: Callback<ThreeFingersSwipe>): void | Listens for three-finger swipe-up events.| +| on(type: 'threeFingersTap', receiver: Callback<ThreeFingersSwipe>): void | Listens for three-finger tap events.| +| on(type: 'fourFingersSwipe', receiver: Callback<FourFingersSwipe>): void | Listens for four-finger swipe events.| +| on(type: 'rotate', fingers: number, receiver: Callback<Rotate>): void | Listens for rotation events.| +| off(type: 'mouse', receiver: Callback<MouseEvent>): void |Cancels listening for mouse events.| | off(type: 'touch', receiver: TouchEventReceiver): void | Cancels listening for touchscreen events.| | off(type: 'pinch', receiver: TouchEventReceiver): void | Cancels listening for pinch events.| -| off(type: 'threeFingersSwipe', receiver: Callback): void | Cancels listening for three-finger swipe-up events.| -| off(type: 'threeFingersTap', receiver: Callback): void | Cancels listening for three-finger tap events.| -| off(type: 'fourFingersSwipe', receiver: Callback): void | Cancels listening for four-finger swipe events.| -| off(type: 'rotate', fingers: number, receiver: Callback): void | Cancels listening for rotation events.| +| off(type: 'threeFingersSwipe', receiver: Callback<ThreeFingersSwipe>): void | Cancels listening for three-finger swipe-up events.| +| off(type: 'threeFingersTap', receiver: Callback<ThreeFingersSwipe>): void | Cancels listening for three-finger tap events.| +| off(type: 'fourFingersSwipe', receiver: Callback<FourFingersSwipe>): void | Cancels listening for four-finger swipe events.| +| off(type: 'rotate', fingers: number, receiver: Callback<Rotate>): void | Cancels listening for rotation events.| ## How to Develop diff --git a/en/application-dev/device/input/monitor-guidelines.md b/en/application-dev/device/input/monitor-guidelines.md index 5f274e29d05d54bdf0a13484f1c170b33d506831..7cb8f2e61632d84ed829c415f21d47b8f78cef11 100644 --- a/en/application-dev/device/input/monitor-guidelines.md +++ b/en/application-dev/device/input/monitor-guidelines.md @@ -23,9 +23,9 @@ The following table lists the APIs for event listening. For details, see [Input] ## How to Develop -### Linking a Dynamic Library +### Linking Dynamic Libraries -Before calling interception-related APIs, you need to link the related dynamic library. You can do this by editing the **CMakeList.txt** file as follows: +Before calling interception-related APIs, you need to link the related dynamic libraries. To link dynamic libraries, add the following configuration to the **CMakeList.txt** file: ```txt target_link_libraries(entry PUBLIC libohinput.so) @@ -38,7 +38,7 @@ Declare the required permission in the **module.json5** file. For details, see [ ```json "requestPermissions": [ { - "name": "ohos.permission.INTERCEPT_INPUT_EVENT" + "name": "ohos.permission.INPUT_MONITORING" } ] ``` diff --git a/en/application-dev/device/location/Readme-EN.md b/en/application-dev/device/location/Readme-EN.md index ecc5b857748c228cc7f753c2130fa174cc7e72cf..9aed37d6597a953b046a35dab5bfc2c8fa040181 100644 --- a/en/application-dev/device/location/Readme-EN.md +++ b/en/application-dev/device/location/Readme-EN.md @@ -1,8 +1,10 @@ -# Location Kit +# Location Kit - [Introduction to Location Kit](location-kit-intro.md) -- [Applying for Location Permissions](location-permission-guidelines.md) -- [Obtaining Device Location Information](location-guidelines.md) -- [Geocoding and Reverse Geocoding](geocode-guidelines.md) -- [Geofencing](geofence-guidelines.md) -- [Samples](app-samples.md) \ No newline at end of file +- [Applying for Location Permissions (ArkTS)](location-permission-guidelines.md) +- [Obtaining Device Location Information (C/C++)](location-guidelines-capi.md) +- [Obtaining Device Location Information (ArkTS)](location-guidelines.md) +- [Geocoding and Reverse Geocoding (ArkTS)](geocode-guidelines.md) +- [Geofencing (ArkTS)](geofence-guidelines.md) +- [FenceExtensionAbility](fenceExtensionAbility.md) +- [Samples](app-samples.md) diff --git a/en/application-dev/device/location/app-samples.md b/en/application-dev/device/location/app-samples.md index 4b1267ac1937e359f89bd45c772c704f489ef17a..1b9fec311bd9d00256143df7a20811055af12054 100644 --- a/en/application-dev/device/location/app-samples.md +++ b/en/application-dev/device/location/app-samples.md @@ -2,4 +2,4 @@ The following sample is provided to help you better understand how to develop location services: -- [Location (ArkTS)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/DeviceManagement/Location) +- [Location (ArkTS)] (https://gitee.com/harmonyos_samples/location-service) diff --git a/en/application-dev/device/location/fenceExtensionAbility.md b/en/application-dev/device/location/fenceExtensionAbility.md new file mode 100644 index 0000000000000000000000000000000000000000..75390bd68b73180ecaa7da3210ca379789e95b83 --- /dev/null +++ b/en/application-dev/device/location/fenceExtensionAbility.md @@ -0,0 +1,93 @@ +# FenceExtensionAbility + +## Overview +[FenceExtensionAbility](../../reference/apis-location-kit/js-apis-app-ability-FenceExtensionAbility.md) is an ExtensionAbility of the geofence type. It enables you to efficiently implement geofencing functionalities. + +## When to Use + +1. Subscribe to geofence status change events through the [geoLocationManager.on('gnssFenceStatusChange')](../../reference/apis-location-kit/js-apis-geoLocationManager.md#geolocationmanagerongnssfencestatuschange) API of the location service, and pass the FenceExtensionAbility parameters in the **want** parameter. +2. After the event is triggered, the system reports the geofence event and data through the **onFenceStatusChange** API. Based on the event received, the application can perform corresponding service processing, for example, sending notifications. + +## Available APIs +For details about the APIs, see [FenceExtensionAbility](../../reference/apis-location-kit/js-apis-app-ability-FenceExtensionAbility.md). +| Available APIs| Description| +| ---- | ---- | +| onFenceStatusChange(transition: geoLocationManager.GeofenceTransition, additions: Record<string, string>): void | Callback invoked when a geofence status change event is received. Service processing is then performed based on the event type and data.| +| onDestroy(): void | Callback invoked when a FenceExtensionAbility destruction event is received.| + +## How to Develop + +### Implementing a FenceExtensionAbility + +Implement the capability of the [FenceExtensionAbility](../../reference/apis-location-kit/js-apis-app-ability-FenceExtensionAbility.md) provider. + +To manually create a FenceExtensionAbility in a project in DevEco Studio, perform the following steps: + +1. In the **ets** directory of a module in the project, right-click and choose **New > Directory** to create a directory named **fenceextensionability**. +2. Right-click the **fenceextensionability** directory, and choose **New** > **File** to create a file named **MyFenceExtensionAbility.ets**. +3. Open the **MyFenceExtensionAbility.ets** file and import its dependencies. Customize a class that inherits from **FenceExtensionAbility** and implement the **onFenceStatusChange** and **onDestroy** APIs. + +The sample code is as follows: + +```ts +import { FenceExtensionAbility, geoLocationManager } from '@kit.LocationKit'; +import { notificationManager } from '@kit.NotificationKit'; +import { Want, wantAgent } from '@kit.AbilityKit'; + +export class MyFenceExtensionAbility extends FenceExtensionAbility { + onFenceStatusChange(transition: geoLocationManager.GeofenceTransition, additions: Record): void { + // Receive the geofence status change event and process the service logic. + console.info(`on geofence transition,id:${transition.geofenceId},event:${transition.transitionEvent},additions:${JSON.stringify(additions)}`); + + // Send a geofence notification. + let wantAgentInfo: wantAgent.WantAgentInfo = { + wants: [ + { + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + parameters: + { + "geofenceId": transition?.geofenceId, + "transitionEvent": transition?.transitionEvent, + } + } as Want + ], + actionType: wantAgent.OperationType.START_ABILITY, + requestCode: 100 + }; + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentMy) => { + let notificationRequest: notificationManager.NotificationRequest = { + id: 1, + content: { + notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + normal: { + title: `Geofence Notification`, + text: `on geofence transition,id:${transition.geofenceId},event:${transition.transitionEvent},additions:${JSON.stringify(additions)}`, + } + }, + notificationSlotType: notificationManager.SlotType.SOCIAL_COMMUNICATION, + wantAgent: wantAgentMy + }; + notificationManager.publish(notificationRequest); + }); + } +} +``` + +4. Register the FenceExtensionAbility in the [module.json5 file](../../quick-start/module-configuration-file.md) of the module in the project. Set **type** to **"fence"** and **srcEntry** to the code path of the FenceExtensionAbility component. + +```json +{ + "module": { + "extensionAbilities": [ + { + "name": "MyFenceExtensionAbility", + "srcEntry": "./ets/fenceExtensionability/MyFenceExtensionAbility.ets", + "description": "MyFenceExtensionAbility", + "type": "fence", + "exported": true + }, + ] + } +} +``` diff --git a/en/application-dev/device/location/figures/001.png b/en/application-dev/device/location/figures/001.png new file mode 100644 index 0000000000000000000000000000000000000000..71722d671b3bb5cee09c698e904b0a59fbe77765 Binary files /dev/null and b/en/application-dev/device/location/figures/001.png differ diff --git a/en/application-dev/device/location/geocode-guidelines.md b/en/application-dev/device/location/geocode-guidelines.md index 092ddc6cdce62006107a87b8e4b1d42c8494b604..f041325197d7f15ead4ea441f6283dd4cb2fe81d 100644 --- a/en/application-dev/device/location/geocode-guidelines.md +++ b/en/application-dev/device/location/geocode-guidelines.md @@ -1,4 +1,4 @@ -# Geocoding and Reverse Geocoding +# Geocoding and Reverse Geocoding (ArkTS) ## Scenario @@ -14,8 +14,6 @@ The geocoding information describes a location using several attributes, includi The following table lists the APIs used for mutual conversion between coordinates and geographic descriptions. For details, see [Location Kit](../../reference/apis-location-kit/js-apis-geoLocationManager.md). -**Table 3** Geocoding and reverse geocoding APIs - | API| Description| | -------- | -------- | | [isGeocoderAvailable(): boolean;](../../reference/apis-location-kit/js-apis-geoLocationManager.md#geolocationmanagerisgeocoderavailable) | Checks whether the geocoding and reverse geocoding services are available.| @@ -53,9 +51,9 @@ The following table lists the APIs used for mutual conversion between coordinate try { geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => { if (err) { - console.log('getAddressesFromLocation err: ' + JSON.stringify(err)); + console.error('getAddressesFromLocation err: ' + JSON.stringify(err)); } else { - console.log('getAddressesFromLocation data: ' + JSON.stringify(data)); + console.info('getAddressesFromLocation data: ' + JSON.stringify(data)); } }); } catch (err) { @@ -70,9 +68,9 @@ The following table lists the APIs used for mutual conversion between coordinate try { geoLocationManager.getAddressesFromLocationName(geocodeRequest, (err, data) => { if (err) { - console.log('getAddressesFromLocationName err: ' + JSON.stringify(err)); + console.error('getAddressesFromLocationName err: ' + JSON.stringify(err)); } else { - console.log('getAddressesFromLocationName data: ' + JSON.stringify(data)); + console.info('getAddressesFromLocationName data: ' + JSON.stringify(data)); } }); } catch (err) { diff --git a/en/application-dev/device/location/geofence-guidelines.md b/en/application-dev/device/location/geofence-guidelines.md index 0af05095f9b5ee10a26d9a99c444aab0701c2536..bf37a5571488d920cefbbe941d39ebcbcff8d19a 100644 --- a/en/application-dev/device/location/geofence-guidelines.md +++ b/en/application-dev/device/location/geofence-guidelines.md @@ -1,4 +1,4 @@ -# Geofencing +# Geofencing (ArkTS) ## Scenario @@ -12,85 +12,121 @@ A typical application of geofencing is to create a geofence around an enterprise Geo-fencing uses the following interfaces. For details, see [Location Kit](../../reference/apis-location-kit/js-apis-geoLocationManager.md). -**Table 4** Geofencing APIs - | API| Description| | -------- | -------- | -| [on(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): void;](../../reference/apis-location-kit/js-apis-geoLocationManager.md#geolocationmanagerongnssfencestatuschange) | Registers a listener for status change events of the specified geofence.| -| [off(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): void;](../../reference/apis-location-kit/js-apis-geoLocationManager.md#geolocationmanageroffgnssfencestatuschange) | Unregisters the listener for status change events of the specified geofence.| +| [addGnssGeofence(fenceRequest: GnssGeofenceRequest): Promise<number>](../../reference/apis-location-kit/js-apis-geoLocationManager.md#geolocationmanageraddgnssgeofence12) | Adds a GNSS geofence and subscribes to geofence transition events. This API uses a promise to return the result.| +| [removeGnssGeofence(geofenceId: number): Promise<void>](../../reference/apis-location-kit/js-apis-geoLocationManager.md#geolocationmanagerremovegnssgeofence12) | Removes a GNSS geofence and unsubscribes from geofence transition events. This API uses a promise to return the result.| ## How to Develop 1. Declare the **ohos.permission.APPROXIMATELY_LOCATION** permission. For details, see [Applying for Location Permissions](#location-permission-guidelines.md). 2. Import the **geoLocationManager**, **wantAgent**, and **BusinessError** modules. - + ```ts import { geoLocationManager } from '@kit.LocationKit'; - import { wantAgent } from '@kit.AbilityKit'; - import { BusinessError } from '@kit.BasicServicesKit' + import { BusinessError } from '@kit.BasicServicesKit'; + import { notificationManager } from '@kit.NotificationKit'; ``` -3. Create a **WantAgentInfo** object. - - Scenario 1: Create a **WantAgentInfo** object for starting an ability. +3. Create a geofence. ```ts // Set the action type through operationType of WantAgentInfo. - let wantAgentInfo:wantAgent.WantAgentInfo = { - wants: [ - { - deviceId: '', - bundleName: 'com.example.myapplication', - abilityName: 'EntryAbility', - action: '', - entities: [], - uri: '', - parameters: {} - } - ], - operationType: wantAgent.OperationType.START_ABILITY, - requestCode: 0, - wantAgentFlags:[wantAgent.WantAgentFlags.CONSTANT_FLAG] - }; + let geofence: geoLocationManager.Geofence = { + "latitude": 34.12, "longitude": 124.11, "radius": 10000.0, "expiration": 10000.0 + } ``` - Scenario 2: Create a **WantAgentInfo** object for releasing a public event. +4. Specify the types of geofence transition events to listen for. Geofence entry and exit events are used as an example. ```ts - // Set the action type through operationType of WantAgentInfo. - let wantAgentInfo:wantAgent.WantAgentInfo = { - wants: [ - { - action: 'event_name', // Set the action name. - parameters: {}, - } - ], - operationType: wantAgent.OperationType.SEND_COMMON_EVENT, - requestCode: 0, - wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG], - } + let transitionStatusList: Array = [ + geoLocationManager.GeofenceTransitionEvent.GEOFENCE_TRANSITION_EVENT_ENTER, + geoLocationManager.GeofenceTransitionEvent.GEOFENCE_TRANSITION_EVENT_EXIT, + ]; ``` -4. Call **getWantAgent()** to create a **WantAgent** object. +4. Create a notification object for **GEOFENCE_TRANSITION_EVENT_ENTER** and **GEOFENCE_TRANSITION_EVENT_EXIT**. - Call the geofencing API to add a geofence after obtaining the **WantAgent** object, and have the system automatically trigger the action defined for the **WantAgent** object when a device enters or exits the geofence. + ```ts + // GEOFENCE_TRANSITION_EVENT_ENTER event + let notificationRequest1: notificationManager.NotificationRequest = { + id: 1, + content: { + notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + normal: { + title: "Geofence Notification", + text: "Geofence Entry", + additionalText: "" + } + } + }; + // Create a notification object for GEOFENCE_TRANSITION_EVENT_EXIT. + let notificationRequest2: notificationManager.NotificationRequest = { + id: 2, + content: { + notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + normal: { + title: "Geofence Notification", + text: 'Geofence Exit', + additionalText: "" + } + } + }; + ``` + +5. Add a geofence. ```ts - let wantAgentObj : object | undefined = undefined; - // Create a WantAgent object. - wantAgent.getWantAgent(wantAgentInfo, (err, data) => { + // Save the created notification objects to Array in the same sequence as in transitionStatusList. + let notificationRequestList: Array = + [notificationRequest1, notificationRequest2]; + // Construct a gnssGeofenceRequest object. + let gnssGeofenceRequest: geoLocationManager.GnssGeofenceRequest = { + // Geofence attributes, including the circle center and radius. + geofence: geofence, + // Specify the types of geofence transition events to listen for. + monitorTransitionEvents: transitionStatusList, + // Specify the notification objects for geofence transition events. This parameter is optional. + notifications: notificationRequestList, + // Specify the callback used to receive geofence transition events. + geofenceTransitionCallback: (err : BusinessError, transition : geoLocationManager.GeofenceTransition) => { if (err) { - console.error('getWantAgent err=' + JSON.stringify(err)); - return; - } - console.info('getWantAgent success'); - wantAgentObj = data; - let requestInfo:geoLocationManager.GeofenceRequest = {'scenario': 0x301, "geofence": {"latitude": 31.12, "longitude": 121.11, "radius": 100, "expiration": 10000}}; - try { - geoLocationManager.on('gnssFenceStatusChange', requestInfo, wantAgentObj); - } catch (err) { - console.error("errCode:" + JSON.stringify(err)); + console.error('geofenceTransitionCallback: err=' + JSON.stringify(err)); } - }); + if (transition) { + console.info("GeofenceTransition: %{public}s", JSON.stringify(transition)); + } + } + } + try { + // Add a geofence. + geoLocationManager.addGnssGeofence(gnssGeofenceRequest).then((id) => { + // Obtain the geofence ID after the geofence is successfully added. + console.info("addGnssGeofence success, fence id: " + id); + let fenceId = id; + }).catch((err: BusinessError) => { + console.error("addGnssGeofence failed, promise errCode:" + (err as BusinessError).code + + ",errMessage:" + (err as BusinessError).message); + }); + } catch(error) { + console.error("addGnssGeofence failed, err:" + JSON.stringify(error)); + } + ``` + +6. Delete a geofence. + + ```ts + // fenceId is obtained after geoLocationManager.addGnssGeofence is successfully executed. + let fenceId = 1; + try { + geoLocationManager.removeGnssGeofence(fenceId).then(() => { + console.info("removeGnssGeofence success fenceId:" + fenceId); + }).catch((error : BusinessError) => { + console.error("removeGnssGeofence: error=" + JSON.stringify(error)); + }); + } catch(error) { + console.error("removeGnssGeofence: error=" + JSON.stringify(error)); + } ``` diff --git a/en/application-dev/device/location/location-guidelines-capi.md b/en/application-dev/device/location/location-guidelines-capi.md new file mode 100644 index 0000000000000000000000000000000000000000..d45d035fa3c691704639fe25bbd05c331371526a --- /dev/null +++ b/en/application-dev/device/location/location-guidelines-capi.md @@ -0,0 +1,154 @@ +# Obtaining Device Location Information (C/C++) + + +## When to Use + +You can call location-related APIs to listen for device location changes. + +## Function Description + +| Name | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| OH_Location_IsLocatingEnabled(bool* enabled) | Checks whether the location switch is enabled. | +| OH_Location_StartLocating(const Location_RequestConfig* requestConfig) | Starts locating and subscribes to location changes.| +| Location_ResultCode OH_Location_StopLocating(const Location_RequestConfig* requestConfig) | Stops locating and unsubscribes from location changes.| +| OH_LocationInfo_GetBasicInfo(Location_Info* location) | Obtains basic information from the location result, such as the longitude, latitude, altitude, and speed.| +| OH_LocationInfo_GetAdditionalInfo(Location_Info* location, char* additionalInfo, uint32_t length) | Obtains additional information from the location result. The additional information is a string in JSON format.| +| OH_Location_CreateRequestConfig(void) | Creates a **Location_RequestConfig** instance. | +| OH_Location_DestroyRequestConfig(Location_RequestConfig* requestConfig) | Destroys the **Location_RequestConfig** instance and reclaims the memory. | +| OH_LocationRequestConfig_SetUseScene(Location_RequestConfig* requestConfig, Location_UseScene useScene) | Sets the user activity scenario in a location request.
If **useScene** is set, **powerConsumptionScene** is invalid.
Otherwise, **powerConsumptionScene** takes effect.
If neither of the two parameters is set, **useScene** is defaulted to **LOCATION_USE_SCENE_DAILY_LIFE_SERVICE**, and **powerConsumptionCenario** is invalid. | +| OH_LocationRequestConfig_SetPowerConsumptionScene(Location_RequestConfig* requestConfig, Location_PowerConsumptionScene powerConsumptionScene) | Sets the power consumption scenario in a location request. | +| OH_LocationRequestConfig_SetInterval(Location_RequestConfig* requestConfig, int interval) | Sets the interval for reporting location results. | +| OH_LocationRequestConfig_SetCallback(Location_RequestConfig* requestConfig, Location_InfoCallback callback, void* userData) | Sets the callback for receiving reported location information. | + + +## How to Develop +1. Create a native C++ project. + ![](figures/001.png) + +2. Before using system basic location capabilities, check whether your application has been granted the permission to access the device location information. If not, your application first needs to apply for the required permission. For details, see [Applying for Location Permissions](location-permission-guidelines.md). + + +3. Add the dynamic dependency libraries into the **CMakeLists.txt** file. + + ```c + target_link_libraries(entry PUBLIC libace_napi.z.so) + target_link_libraries(entry PUBLIC libhilog_ndk.z.so) + target_link_libraries(entry PUBLIC liblocation_ndk.so) + ``` + +4. Write the **napi_init.cpp** file to import related modules. + + ```c + #include "napi/native_api.h" + #include "LocationKit/oh_location.h" + #include "LocationKit/oh_location_type.h" + #include "hilog/log.h" + #include + ``` + +5. Call **isLocationEnabled** to check whether the location switch is enabled. + The return result is a Boolean value. The value **true** indicates that the location switch is enabled, and the value **false** indicates the opposite. + + ```c + static napi_value OhLocationIsEnabled(napi_env env, napi_callback_info info) + { + bool isEnabled = false; + int resultCode = OH_Location_IsLocatingEnabled(&isEnabled); + napi_value result = NULL; + napi_get_boolean(env, isEnabled, &result); + return result; + } + // Add related APIs to the Init function. + EXTERN_C_START + static napi_value Init(napi_env env, napi_value exports) + { + napi_property_descriptor desc[] = { + {"ohLocationIsEnabled", NULL, OhLocationIsEnabled, NULL, NULL, NULL, napi_default, NULL}, + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); + return exports; + } + EXTERN_C_END + ``` + +6. Start positioning and subscribe to location changes. + + ```c + // Define a location request. + struct Location_RequestConfig *g_requestConfig = NULL; + void *mydata = NULL; + + // Define a callback to receive location information. + void reportLocation(Location_Info* location, void* userData) + { + Location_BasicInfo baseInfo = OH_LocationInfo_GetBasicInfo(location); + char additionalInfo[1024] = ""; + Location_ResultCode result = OH_LocationInfo_GetAdditionalInfo(location, additionalInfo, sizeof(additionalInfo)); + if (mydata == userdata) { + OH_LOG_INFO(LOG_APP, "userData is mydata"); + } + return; + } + + // Subscribe to location information. + static napi_value OhLocationStartLocating(napi_env env, napi_callback_info info) + { + if (g_requestConfig == NULL) { + g_requestConfig = OH_Location_CreateRequestConfig(); + } + OH_LocationRequestConfig_SetUseScene(g_requestConfig, LOCATION_USE_SCENE_NAVIGATION); + OH_LocationRequestConfig_SetInterval(g_requestConfig, 1); + mydata = (void *) malloc (sizeof ("mydata")); // Custom data, which is transparently returned through callback. + OH_LocationRequestConfig_SetCallback(g_requestConfig, reportLocation, mydata); + OH_Location_StartLocating(g_requestConfig); + int32_t ret = 0; + napi_value result = NULL; + napi_create_int32(env, ret, &result); + return result; + } + + // Unsubscribe from location information. The value of g_requestConfig must be the same as the object passed during subscription. + static napi_value OhLocationStopLocating(napi_env env, napi_callback_info info) + { + OH_Location_StopLocating(g_requestConfig); + if (g_requestConfig != NULL) { + OH_Location_DestroyRequestConfig(g_requestConfig); + g_requestConfig = NULL; + } + free(mydata); + mydata = NULL; + int32_t ret = 0; + napi_value result = NULL; + napi_create_int32(env, ret, &result); + return result; + } + + // Add related APIs to the Init function. + EXTERN_C_START + static napi_value Init(napi_env env, napi_value exports) + { + napi_property_descriptor desc[] = { + {"ohLocationStartLocating", NULL, OhLocationStartLocating, NULL, NULL, NULL, napi_default, NULL}, + {"ohLocationStopLocating", NULL, OhLocationStopLocating, NULL, NULL, NULL, napi_default, NULL}, + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); + return exports; + } + EXTERN_C_END + ``` + +6. Introduce the NAPI APIs to the **index.d.ts** file in **types/libentry**. + ```c + export const ohLocationIsEnabled: () => boolean; + export const ohLocationStartLocating: () => number; + export const ohLocationStopLocating: () => number; + ``` + +7. Delete deprecated functions from the **Index.ets** file. + + ```js + .onClick(() => { + hilog.info(0x0000, 'testTag', 'Test NAPI 2 + 3 = %{public}d', testNapi.add(2, 3)); + }) + ``` diff --git a/en/application-dev/device/location/location-guidelines.md b/en/application-dev/device/location/location-guidelines.md index 7e2274feb9024fad06fbea47c920baf11af1bfc7..afdd6c1200724b302fc2933688e535d604226356 100644 --- a/en/application-dev/device/location/location-guidelines.md +++ b/en/application-dev/device/location/location-guidelines.md @@ -1,4 +1,4 @@ -# Obtaining Device Location Information +# Obtaining Device Location Information (ArkTS) ## When to Use @@ -12,8 +12,6 @@ The following table lists the APIs used to obtain the device location informatio This module supports only the WGS-84 coordinate system. -**Table 2** APIs for obtaining device location information - | API| Description| | -------- | -------- | | [on(type: 'locationChange', request: LocationRequest | ContinuousLocationRequest, callback: Callback<Location>): void](../../reference/apis-location-kit/js-apis-geoLocationManager.md#geolocationmanageronlocationchange) | Registers a listener for location changes with a location request initiated.| @@ -81,7 +79,7 @@ This module supports only the WGS-84 coordinate system. } try { geoLocationManager.getCurrentLocation(request).then((result) => { // Call getCurrentLocation to obtain the current device location by using a promise. - console.log('current location: ' + JSON.stringify(result)); + console.info('current location: ' + JSON.stringify(result)); }) .catch((error:BusinessError) => { // Receive the reported error code. console.error('promise, getCurrentLocation: error=' + JSON.stringify(error)); @@ -110,7 +108,7 @@ This module supports only the WGS-84 coordinate system. 'locationScenario': geoLocationManager.UserActivityScenario.NAVIGATION } let locationCallback = (location:geoLocationManager.Location):void => { - console.log('locationCallback: data: ' + JSON.stringify(location)); + console.info('locationCallback: data: ' + JSON.stringify(location)); }; try { geoLocationManager.on('locationChange', request, locationCallback); @@ -120,5 +118,6 @@ This module supports only the WGS-84 coordinate system. ``` If your application no longer needs the device location, stop obtaining the device location to avoid high power consumption. ```ts + // The callback must be the same as that passed by the **on** API. geoLocationManager.off('locationChange', locationCallback); ``` diff --git a/en/application-dev/device/location/location-kit-intro.md b/en/application-dev/device/location/location-kit-intro.md index 3676c363f35c61c2c398cbffe734db4fbbcb7a63..c749d15226a0247a9f98d46fc57db2094e6c60a8 100644 --- a/en/application-dev/device/location/location-kit-intro.md +++ b/en/application-dev/device/location/location-kit-intro.md @@ -18,7 +18,7 @@ These advanced location technologies make it possible to obtain the accurate loc A coordinate describes a location on the earth using the longitude and latitude in reference to the World Geodetic Coordinate System 1984. - **GNSS positioning**
- GNSS positioning locates a mobile device by using the location algorithm offered by the device chip to compute the location information provided by the Global Navigation Satellite System, for example, GPS, GLONASS, BeiDou, and Galileo. Whichever positioning system will be used during the location process depends on a hardware capability of the device. + GNSS positioning locates a mobile device by using the location algorithm offered by the device chip to compute the location information provided by the global navigation satellite system (GNSS), for example, GPS, GLONASS, BeiDou, and Galileo. Whichever positioning system will be used during the location process depends on a hardware capability of the device. - **Base station positioning**
Base station positioning estimates the current location of a mobile device based on the location of the resident base station in reference to the neighboring base stations. This technology provides only a low accuracy and requires access to the cellular network. @@ -35,3 +35,4 @@ Your application can use the location function only after the user has granted t Since the location information is considered sensitive, your application still needs to obtain the location access permission from the user even if the user has turned on the location function. The system will provide the location service for your application only after it has been granted the permission to access the device location information. +Depending on the hardware support, Location Kit provides different capabilities on different devices. For example, a GPS or Beidou positioning chip provides devices with the GNSS positioning capabilities. If a WLAN or cellular network module, instead of a positioning chip, is available, then the devices can use the WLAN or base station positioning capabilities. diff --git a/en/application-dev/device/location/location-permission-guidelines.md b/en/application-dev/device/location/location-permission-guidelines.md index bb125c16f728f05fcbdb02a85abc33e69801333f..99bb145bc29975e76bd8a6f5a9bde5216cf4e162 100644 --- a/en/application-dev/device/location/location-permission-guidelines.md +++ b/en/application-dev/device/location/location-permission-guidelines.md @@ -1,4 +1,4 @@ -# Applying for Location Permissions +# Applying for Location Permissions (ArkTS) ## Scenario @@ -20,8 +20,6 @@ For details about the permissions required for each API of Location Kit, see [Lo 2. If your application needs to access the device location when running in the foreground, declare the location permission as described in the following table. -**Table 1** Description of location permissions - | Permission| Declarable or Not| Location Accuracy| | -------- | -------- | -------- | | ohos.permission.APPROXIMATELY_LOCATION| Yes| Location accurate to 5 kilometers.| diff --git a/en/application-dev/device/sensor/Readme-EN.md b/en/application-dev/device/sensor/Readme-EN.md index 705bcaf33a661c34467c7c380c6e962baa7b0653..42e6e8e308772fa2f57f0df00c5c221f00d550e5 100644 --- a/en/application-dev/device/sensor/Readme-EN.md +++ b/en/application-dev/device/sensor/Readme-EN.md @@ -1,11 +1,11 @@ -# Sensor Service Kit +# Sensor Service Kit - [Introduction to Sensor Service Kit](sensorservice-kit-intro.md) -- Sensor +- Sensor - [Sensor Overview](sensor-overview.md) - [Sensor Development (ArkTS)](sensor-guidelines.md) - [Sensor Development (C/C++)](sensor-guidelines-capi.md) -- Vibrator +- Vibrator - [Vibrator Overview](vibrator-overview.md) - [Vibrator Development (ArkTS)](vibrator-guidelines.md) - [Vibrator Development (C/C++)](vibrator-guidelines-capi.md) diff --git a/en/application-dev/device/sensor/sensor-overview.md b/en/application-dev/device/sensor/sensor-overview.md index df3402eb42fddd0ffd32f7f215bb9fd705dce85e..daa978986d742dad5cc1db332325ac2f44d2460a 100644 --- a/en/application-dev/device/sensor/sensor-overview.md +++ b/en/application-dev/device/sensor/sensor-overview.md @@ -1,4 +1,4 @@ -# Introduction to Sensor Service Kit +# Sensor Overview ## Sensor Types diff --git a/en/application-dev/device/sensor/sensorservice-kit-intro.md b/en/application-dev/device/sensor/sensorservice-kit-intro.md index 9c789861e0d352a162987fe1ef5b7c4650462a13..6f10e0a7bab477b5364013ff119116d4df8e3382 100644 --- a/en/application-dev/device/sensor/sensorservice-kit-intro.md +++ b/en/application-dev/device/sensor/sensorservice-kit-intro.md @@ -6,7 +6,7 @@ Sensor Service Kit enables applications to obtain raw data from sensors and prov - The sensor module provides APIs for applications to access the underlying sensor hardware. Using these APIs, you can query sensors on your device and subscribe to sensor data. Based on the sensor data obtained, you can customize algorithms and develop various sensor-based applications, such as compass, motion-controlled games, and fitness and health applications. -- The vibrator module is built on the native vibrator service, bolstered by the capabilities of the vibrator hardware. By innovatively integrating vibration and interaction, the module takes user interaction efficiency and usability to the next level. +- The vibrator module maximally unlocks the capabilities of the vibrator device. By expanding the vibrator services, it achieves an integrated design of vibration and interaction, creating a delicate and sophisticated vibration experience that takes user interaction efficiency and usability to the next level. ## Constraints diff --git a/en/application-dev/device/sensor/vibrator-guidelines.md b/en/application-dev/device/sensor/vibrator-guidelines.md index 5a010faea53a2dd15ec726cdbaf5d03e1b417683..bb46a551395e3fc0e0638348a34171ef25b83182 100644 --- a/en/application-dev/device/sensor/vibrator-guidelines.md +++ b/en/application-dev/device/sensor/vibrator-guidelines.md @@ -97,7 +97,7 @@ The custom vibration configuration file is in JSON format. An example file is as } ``` -This JSON file contains two attributes: **MetaData** and **Channels**. +This JSON file contains three attributes: **MetaData**, **Channels**, and **Parameters**. 1. **MetaData** contains information about the file header. You can add the following attributes under **MetaData**. | Name | Mandatory| Description | diff --git a/en/application-dev/device/sensor/vibrator-overview.md b/en/application-dev/device/sensor/vibrator-overview.md index f762904928fc4bb63f395d7d857a739b33210436..abd42d5fd1a9f2b9d5e28207664349d144720fe6 100644 --- a/en/application-dev/device/sensor/vibrator-overview.md +++ b/en/application-dev/device/sensor/vibrator-overview.md @@ -1,7 +1,7 @@ # Vibrator Overview -The **vibrator** module extends the native vibrator service via maximizing utilization of vibrator hardware capabilities. By innovatively integrating vibration and interaction, the module takes user interaction efficiency and usability to the next level. +The **vibrator** module extends the vibrator service via maximizing utilization of vibrator hardware capabilities. By innovatively integrating vibration and interaction, the module takes user interaction efficiency and usability to the next level. ## Working Principles diff --git a/en/application-dev/device/stationary/Readme-EN.md b/en/application-dev/device/stationary/Readme-EN.md index f896237291f3af1bf677a758bfdd57b65696e89f..9bdcf57c91e901a49c12d83ce8f7249aa256dcd9 100644 --- a/en/application-dev/device/stationary/Readme-EN.md +++ b/en/application-dev/device/stationary/Readme-EN.md @@ -1,4 +1,6 @@ -# Multimodal Awareness Kit +# Multimodal Awareness Kit - [Introduction to Multimodal Awareness Kit](multimodalawareness-kit-intro.md) -- [Stationary Development](stationary-guidelines.md) \ No newline at end of file +- [Stationary Development](stationary-guidelines.md) +- [Motion Sensing Development](motion-guidelines.md) +- [Device Status Awareness Development](deviceStatus-guidelines.md) \ No newline at end of file diff --git a/en/application-dev/device/stationary/deviceStatus-guidelines.md b/en/application-dev/device/stationary/deviceStatus-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..d213b4b177c2643a822a32226a1dde127578bb15 --- /dev/null +++ b/en/application-dev/device/stationary/deviceStatus-guidelines.md @@ -0,0 +1,82 @@ +# Device Status Awareness Development + +The DeviceStatus module provides device status awareness capabilities such as obtaining the steady standing state (that is, stand mode). + +For details about the APIs, see the [API Reference](../../reference/apis-multimodalawareness-kit/js-apis-awareness-deviceStatus.md). + +## Concepts + +Understanding the following concepts would be helpful for you in device status awareness development: + +- Stand moe + + A device enters stand mode when it is stationary, and its screen is at an angle between 45 and 135 degrees relative to the horizontal plane. For foldable smartphones, the device must be in a folded state or fully unfolded state. + +## How to Develop + +### Overview + +During development, subscribe to steady standing state change events and obtain the current state through the callback passed in during subscription. + +### Constraints + +The device must support the accelerometer and specific chips. + +### APIs + +| API | Description | +| ------------------------------------------------------------ | -------------------------------------- | +| on(type: 'steadyStandingDetect', callback: Callback<SteadyStandingStatus>): void; | Subscribes to steady standing state change events. This API returns the result through a callback.| +| off(type: 'steadyStandingDetect', callback: Callback<SteadyStandingStatus>): void; | Unsubscribes from steady standing state change events. This API returns the result through a callback. | + +### Development Procedure + +1. Import the **deviceStatus** module. + + ```ts + import { deviceStatus } from '@kit.MultimodalAwarenessKit'; + ``` + +2. Subscribe to steady standing state change events. + + ```ts + try { + deviceStatus.on('steadyStandingDetect', (data:deviceStatus.SteadyStandingStatus) => { + console.info('now status = ' + data); + }); + } catch (err) { + console.info('on failed, err = ' + err); + } + ``` + +3. Unsubscribe from all callbacks of steady standing state change events. + + ```ts + try { + deviceStatus.off('steadyStandingDetect'); + } catch (err) { + console.info('off failed, err = ' + err); + } + ``` + +4. Unsubscribe from the specific callback of steady standing state change events. + + ```ts + import { Callback } from '@ohos.base'; + // Define the callback variable. + let callback : Callback = (data : deviceStatus.SteadyStandingStatus) => { + console.info('now status = ' + data); + }; + // Subscribe to a specific callback of steady standing state change events. + try { + deviceStatus.on('steadyStandingDetect', callback); + } catch (err) { + console.info('on failed, err = ' + err); + } + // Unsubscribe from the specific callback of steady standing state change events. + try { + deviceStatus.off('steadyStandingDetect', callback); + } catch (err) { + console.info('off failed, err = ' + err); + } + ``` diff --git a/en/application-dev/device/stationary/motion-guidelines.md b/en/application-dev/device/stationary/motion-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..551c9e6bfbf34f09e50082191cf086e589efd6bf --- /dev/null +++ b/en/application-dev/device/stationary/motion-guidelines.md @@ -0,0 +1,83 @@ +# Motion Awareness Development + +## When to Use + +An application can call the motion module to identify user actions, for example, whether the user is operating the device screen with the left hand or the right hand. + +For details about the APIs, see [Motion API Reference](../../reference/apis-multimodalawareness-kit/js-apis-awareness-motion.md). + +## Available APIs + +| API | Description | +| ------------------------------------------------------------ | -------------------------------------- | +| on(type:'operatingHandChanged',callback:Callback<OperatingHandStatus>):void; | Subscribes to operating hand change events. This API uses a callback to return the result.| +| off(type: 'operatingHandChanged', callback?: Callback<OperatingHandStatus>): void; | Unsubscribes from operating hand change events. | +| getRecentOperatingHandStatus(): OperatingHandStatus; | Obtains the latest operating hand status. | + +## Constraints + + - The device must support the touchscreen and be compatible with specific chips. + + - Knuckle operations are not categorized as hand operations. + + - Multi-finger operations are not supported in window rotation scenarios. + + - The effective range does not include the area within 8 mm from the screen edge. + + + + +## How to Develop + +1. Import the related modules. + + ```ts + import { motion } from '@kit.MultimodalAwarenessKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + ``` + +2. Define a callback to receive operating hand change results. + + ``` + callback(data:motion.OperatingHandStatus) { + console.info('callback success' + data); + } + ``` + +3. Subscribe to operating hand change results. + + ``` + try { + motion.on('operatingHandChanged', this.callback); + console.info("on succeeded"); + } catch (err) { + let error = err as BusinessError; + console.error("Failed on and err code is " + error.code); + } + ``` + +4. Unsubscribe from operating hand change events. + + ``` + try { + motion.off('operatingHandChanged'); + console.info("off succeeded"); + } catch (err) { + let error = err as BusinessError; + console.error("Failed off and err code is " + error.code); + } + ``` + +5. Obtain the latest operating hand status. + + ``` + try { + let data:motion.OperatingHandStatus = motion.getRecentOperatingHandStatus(); + console.info('get success' + data); + } catch (err) { + let error = err as BusinessError; + console.error("Failed get and err code is " + error.code); + } + ``` + + diff --git a/en/application-dev/device/stationary/multimodalawareness-kit-intro.md b/en/application-dev/device/stationary/multimodalawareness-kit-intro.md index e13522cf83444aa640d01e5a723cdd1936002e99..dae09e456e928588931dbc0c7f885e4b0b602916 100644 --- a/en/application-dev/device/stationary/multimodalawareness-kit-intro.md +++ b/en/application-dev/device/stationary/multimodalawareness-kit-intro.md @@ -1,11 +1,11 @@ # Introduction to Multimodal Awareness Kit -Multimodal Awareness Kit allows an application to identify user activities (walking, running, driving, etc.) or postures based on the data collected by sensors including gyroscopes and acceleration sensors built in a device. +Multimodal Awareness Kit allows an application to identify user activities (walking, running, driving, etc.) or postures based on the data collected by sensors including gyroscopes and acceleration sensors built in a HarmonyOS device. -## How MultimodalAwareness Kit Works +## How Multimodal Awareness Kit Works -MultimodalAwareness Kit is offered by the system as a basic service for applications. Depending on the service scenario, an application needs to initiate a subscription request to the system and cancel the subscription when the service scenario ends. In this process, the system reports the device status information to the application on a real-time basis. +Multimodal Awareness Kit is offered by the system as a basic service for applications. Depending on the service scenario, an application needs to initiate a subscription request to the system and cancel the subscription when the service scenario ends. In this process, the system reports the device status information to the application on a real-time basis. ## Constraints -To use MultimodalAwareness Kit, you need to apply for required permissions. The device must support the sensors required by the corresponding capabilities. +To use Multimodal Awareness Kit, you need to apply for required permissions. The device must support the sensors required by the corresponding capabilities. diff --git a/en/application-dev/dfx/Readme-EN.md b/en/application-dev/dfx/Readme-EN.md index b441654d3958b4925a0d14d5f6642555440d6cc7..a379642780ceae3216180d3464d68d8bdeed8327 100644 --- a/en/application-dev/dfx/Readme-EN.md +++ b/en/application-dev/dfx/Readme-EN.md @@ -1,62 +1,65 @@ -# Performance Analysis Kit +# Performance Analysis Kit - [Introduction to Performance Analysis Kit](performance-analysis-kit-overview.md) -- HiLog +- HiLog - [Using HiLog (ArkTS)](hilog-guidelines-arkts.md) - [Using HiLog (C/C++)](hilog-guidelines-ndk.md) -- HiAppEvent +- HiAppEvent - [Introduction to HiAppEvent](hiappevent-intro.md) - - Event Subscription - - Application Event + - Event Subscription + - Application Events - [Subscribing to Application Events (ArkTS)](hiappevent-watcher-app-events-arkts.md) - [Subscribing to Application Events (C/C++)](hiappevent-watcher-app-events-ndk.md) - - System Event - - Crash Event + - System Events + - Crash Events - [Crash Event Overview](hiappevent-watcher-crash-events.md) - [Subscribing to Crash Events (ArkTS)](hiappevent-watcher-crash-events-arkts.md) - [Subscribing to Crash Events (C/C++)](hiappevent-watcher-crash-events-ndk.md) - - Freeze Event + - Freeze Events - [Freeze Event Overview](hiappevent-watcher-freeze-events.md) - [Subscribing to Freeze Events (ArkTS)](hiappevent-watcher-freeze-events-arkts.md) - [Subscribing to Freeze Events (C/C++)](hiappevent-watcher-freeze-events-ndk.md) - - Resource Leak Event + - Resource Leak Events - [Resource Leak Event Overview](hiappevent-watcher-resourceleak-events.md) - [Subscribing to Resource Leak Events (ArkTS)](hiappevent-watcher-resourceleak-events-arkts.md) - [Subscribing to Resource Leak Events (C/C++)](hiappevent-watcher-resourceleak-events-ndk.md) - - Address Sanitizer Event + - Address Sanitizer Events - [Address Sanitizer Event Overview](hiappevent-watcher-address-sanitizer-events.md) - [Subscribing to Address Sanitizer Events (ArkTS)](hiappevent-watcher-address-sanitizer-events-arkts.md) - [Subscribing to Address Sanitizer Events (C/C++)](hiappevent-watcher-address-sanitizer-events-ndk.md) - - Main Thread Jank Event + - Main Thread Jank Events - [Main Thread Jank Event Overview](hiappevent-watcher-mainthreadjank-events.md) - [Subscribing to Main Thread Jank Events (ArkTS)](hiappevent-watcher-mainthreadjank-events-arkts.md) - [Subscribing to Main Thread Jank Events (C/C++)](hiappevent-watcher-mainthreadjank-events-ndk.md) + - Task Execution Timeout Events + - [Task Execution Timeout Event Overview](hiappevent-watcher-apphicollie-events.md) + - [Subscribing to Task Execution Timeout Events (C/C++)](hiappevent-watcher-apphicollie-events-ndk.md) - [Event Reporting](hiappevent-event-reporting.md) -- HiTraceMeter +- HiTraceMeter - [Using HiTraceMeter (ArkTS/JS)](hitracemeter-guidelines-arkts.md) - [Using HiTraceMeter (C/C++)](hitracemeter-guidelines-ndk.md) - [Viewing HiTraceMeter Logs](hitracemeter-view.md) -- HiTraceChain +- HiTraceChain - [Using HiTraceChain (ArkTS/JS)](hitracechain-guidelines-arkts.md) - [Using HiTraceChain (C/C++)](hitracechain-guidelines-ndk.md) -- HiChecker +- HiChecker - [Using HiChecker (ArkTS/JS)](hichecker-guidelines-arkts.md) -- HiDebug +- HiDebug - [Using HiDebug (ArkTS)](hidebug-guidelines-arkts.md) - [Using HiDebug (C/C++)](hidebug-guidelines-ndk.md) -- HiCollie +- HiCollie - [Using HiCollie to Detect Service Thread Stuck and Jank Events](hicollie-guidelines-ndk.md) - [Using HiCollie to Monitor the Function Execution Time (C/C++)](hicollie-settimer-guidelines-ndk.md) -- Error Management +- Error Management - [Development of Error Manager](errormanager-guidelines.md) - [Development of Application Recovery](apprecovery-guidelines.md) -- Fault Analysis +- Fault Analysis - [Analyzing JS Crash](jscrash-guidelines.md) - - [Analyzing CPP Crash](cppcrash-guidelines.md) - - [Analyzing AppFreeze](appfreeze-guidelines.md) -- Command Line Tools + - [Analyzing Cpp Crash](cppcrash-guidelines.md) + - [Analyzing App Freeze](appfreeze-guidelines.md) +- Command Line Tools - [hdc](hdc.md) - [hilog](hilog.md) - [hidumper](hidumper.md) @@ -66,3 +69,4 @@ - [hisysevent](hisysevent.md) - [uinput](uinput.md) + diff --git a/en/application-dev/dfx/appfreeze-guidelines.md b/en/application-dev/dfx/appfreeze-guidelines.md index c95be185a4a7ebb7184a27e49d79228d28cf0583..68483a43640e907714637a020178348f5ee76ad9 100644 --- a/en/application-dev/dfx/appfreeze-guidelines.md +++ b/en/application-dev/dfx/appfreeze-guidelines.md @@ -1,8 +1,9 @@ # Analyzing App Freeze -Appfreeze occurs when an application does not respond a click event within a certain period of time. OpenHarmony provides a mechanism for detecting appfreeze and generates appfreeze logs for fault analysis. +App freeze (appfreeze) means that an application does not respond to a click event within a certain period of time. OpenHarmony provides a mechanism for detecting appfreeze and generates appfreeze logs for fault analysis. > **NOTE** +> > This guide applies only to applications in the stage model. Before using this guide, you must have basic knowledge about the JS applications, C++ program stacks, and application-related subsystems. ## AppFreeze Detection @@ -19,7 +20,7 @@ Currently, appfreeze detection supports the fault types listed in the following This fault indicates that the main thread of this application is suspended or too many tasks are executed, which affects task execution smoothness and experience. -Such a fault can be detected as follows: The watchdog thread of the application periodically inserts an activation detection to the main thread and inserts a timeout reporting mechanism to its own thread. If the activation detection is not executed within 3 seconds, the **THREAD_BLOCK_3S** event is reported. If the activation detection is not executed within 6 seconds, the **THREAD_BLOCK_6S** event is reported. The two events together form an appfreeze log. +Such a fault can be detected as follows: The watchdog thread of the application periodically inserts an activation detection to the main thread and inserts a timeout reporting mechanism to its own thread. If the activation detection is not executed within 3 seconds, the **THREAD_BLOCK_3S** event is reported. If the activation detection is not executed within 6 seconds, the **THREAD_BLOCK_6S** event is reported. The two events constitute an AppFreeze log. The following figure shows the working principle. @@ -64,14 +65,14 @@ To identify the cause of appfreeze, analyze the appfreeze logs together with HiL The following example shows an appfreeze log analysis. You can analyze the fault based on actual situation. -Appfreeze logs consist of header information, and general and specific information in the body. +AppFreeze logs consist of header information, and general and specific information in the body. ### Header Information | Field| Description| | -------- | -------- | -| Reason | Reason why the application does not respond. For details, see [appfreeze Detection](#appfreeze-detection).| -| PID | PID of the failed process, which can be used to search for related process information in the Hilog logs.| +| Reason | Reason why the application does not respond. For details, see [AppFreeze Detection](#appfreeze-detection).| +| PID | PID of the failed process, which can be used to search for related process information in the HiLog logs.| | PACKAGE_NAME | Application process package name.| ``` @@ -92,7 +93,7 @@ PID:1561 UID:20010039 PACKAGE_NAME:com.xxx.xxx PROCESS_NAME:com.xxx.xxx -MSG:ablity:EntryAbility background timeout +MSG:ability:EntryAbility background timeout ``` ### General Information in the Log Body @@ -101,9 +102,9 @@ General information is present in all the aforementioned logs. It contains the f | Field| Description| | -------- | -------- | -| EVENTNAME | One or more fault events that constitute the cause of main thread freeze event.| -| TIMESTAMP | Time when the fault event is reported. You can narrow down the time range to view HiLog logs based on the timeout duration described in [AppFreeze Detection](#appfreeze-detection).| -| PID | PID of the failed process, which can be used with the timestamp and timeout duration to search for related process information in the Hilog logs.| +| EVENTNAME | One or more fault events that constitute the cause of main thread freeze.| +| TIMESTAMP | Time when a fault event is reported. You can narrow down the time range to view HiLog logs based on the timeout duration described in [AppFreeze Detection](#appfreeze-detection).| +| PID | PID of the failed process, which can be used with the timestamp and timeout duration to search for related process information in the HiLog logs.| | PACKAGE_NAME | Application process package name.| | MSG | Dump information or description of the fault.| | BinderCatcher | Information about IPC calls between a process and other system processes, such as the call waiting time.| @@ -130,12 +131,12 @@ The task information in the main thread queue includes: Locate the application stack information by searching for the **PID**. In the following stack, the window stays in the IPC communication phase when it sends events to the system through the IPC. ``` -OpenStacktraceCatcher -pid==1561 packageName is com.ohos.huawei.myapplication +OpenStacktraceCatcher -pid==1561 packageName is com.example.myapplication Result: 0 ( no error ) Timestamp:2017-08-0817:06:53.000 Pid:1561 Uid:20010039 -Process name:com.ohos.huawei.myapplication +Process name:com.example.myapplication Tid:1561,Name:i.myapplication #00 pc 0017888c /system/lib/libark_jsruntime.so #01 pc 00025779 /system/lib/platformsdk/libipc_core.z.so(OHOS:BinderConnector:WriteBinder(unsigned Long,void*)+56) @@ -278,8 +279,8 @@ TIMESTAMP = 2017/08/08-17:06:24:363 PID = 1561 UID = 20010039 TID = 1566 -PACKAGE_NAME com.ohos.huawei.myapplication -PROCESS_NAME com.ohos.huawei.myapplication +PACKAGE_NAME com.example.myapplication +PROCESS_NAME com.example.myapplication eventLog_action pb:1 eventLog_interval 10 MSG = App main thread is not response!EventHandler dump begin curTime:2017-08-08 05:06:24.362 Event runner (Thread name =Thread ID 1561)is running @@ -298,9 +299,9 @@ MSG = App main thread is not response!EventHandler dump begin curTime:2017-08-08 Timestamp: 2017-08-0817:06:24.4142447784 Pid: 1561 Uid: 20010039 - Process name: com.ohos.huawei.myapplication + Process name: com.example.myapplication Tid:1561 Name:i.myapplication - at anonymous entry (D:/project/OpenHarmonyOS/MyApplication_test/entry/build/default/intermediates/loader_out/default/ets,pages/Index_.js:0:1) + at anonymous entry (D:/project/MyApplication_test/entry/build/default/intermediates/loader_out/default/ets/pages/Index_.js:0:1) #00 pc 0017909c /system/lib/libark_jsruntime.so #01 pc 00177ebb /system/lib/libark_jsruntime.so #02 pc 0024b4bb /system/lib/libark_jsruntime.so @@ -309,7 +310,7 @@ MSG = App main thread is not response!EventHandler dump begin curTime:2017-08-08 ... ``` -THREAD_BLOCK_6S: +THREAD_BLOCK_6S: ``` start time: 2017/08/08-17:06:27:299 DOMAIN = AAFWK @@ -318,8 +319,8 @@ TIMESTAMP = 2017/08/08-17:06:27:292 PID = 1561 UID = 20010039 TID = 1566 -PACKAGE_NAME com.ohos.huawei.myapplication -PROCESS NAME com.ohos.huawei.myapplication eventLog_action cmd:c,cmd:m,tr,k:SysRqFile +PACKAGE_NAME com.example.myapplication +PROCESS NAME com.example.myapplication eventLog_action cmd:c,cmd:m,tr,k:SysRqFile eventLog_interval 10 MSG = App main thread is not response!EventHandler dump begin curTime:2017-08-08 05:06:27.291 Event runner (Thread name =Thread ID =1561)is running @@ -339,9 +340,9 @@ MSG = App main thread is not response!EventHandler dump begin curTime:2017-08-08 Timestamp:2017-08-0817:0k:27,4142447784 Pid:1561 Uid:20010039 -Process name:com.ohos.huawei.myapplication +Process name:com.example.myapplication Tid:1561 Name:i.myapplication - at anonymous entry (D:/project/OpenHarmony0S/MyApplication_test/entry/build/default/intermediates/loader_out/default/ets/pages/Index_.js:0:1) + at anonymous entry (D:/project/MyApplication_test/entry/build/default/intermediates/loader_out/default/ets/pages/Index_.js:0:1) #00 pc 00178dcc /system/lib/libark_jsruntime.so #01 pc 00177ebb /system/lib/libark_jsruntime.so #02 pc 0024b4bb /system/lib/libark_jsruntime.so(panda:FunctionRef:Call(panda:ecmascript:EcmaVM const*,panda:Local,par @@ -350,7 +351,7 @@ Tid:1561 Name:i.myapplication #05 pc 00d7af1b /system/lib/libace.z.so ``` -Check the code being executed on the application side based on the Hilog log. +Check the code being executed on the application side based on the HiLog log. Generally, you can view the [General Information in the Log Body](#general-information-in-the-log-body) to determine the cause of an appfreeze event, including peer communication suspension, high CPU usage, memory leaks, or a large amount of memory. @@ -368,7 +369,7 @@ For details, see [General Information in the Log Body](#general-information-in-t **MSG** indicates the lifecycle that encounters a timeout. -In the following example, **LIFECYCLE_TIMEOUT** indicates that the process times out when **Ability** is switched to background. You can find Hilog information based on the timeout duration of [Lifecycle Switching Timeout](#lifecycle-switching-timeout). +In the following example, **LIFECYCLE_TIMEOUT** indicates that the process times out when **Ability** is switched to background. You can find HiLog information based on the timeout duration of [Lifecycle Switching Timeout](#lifecycle-switching-timeout). LIFECYCLE_TIMEOUT: @@ -378,8 +379,8 @@ STRINGID:LIFECYCLE TIMEOUT TIMESTAMP:2023/03/10-17:06:53:65 PID:1561 UID:20010039 -PACKAGE_NAME:com.ohos.huawei.myapplication -PROCESS_NAME:com.ohos.huawei.myapplication +PACKAGE_NAME:com.example.myapplication +PROCESS_NAME:com.example.myapplication MSG:ability:EntryAbility background timeout ``` @@ -407,7 +408,7 @@ The appfreeze log is managed together with the native process crash, JS applicat DevEco Studio collects device fault logs and saves them to **FaultLog**. For details, see [DevEco Studio User Guide-FaultLog](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/ide-fault-log-V5). -- Method 2: hiAppEvent APIs +- Method 2: HiAppEvent APIs hiAppEvent provides APIs to subscribe to various fault information. For details, see [Introduction to HiAppEvent](hiappevent-intro.md). @@ -442,7 +443,7 @@ DisplayPowerInfo:powerState: AWAKE >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ``` -#### Obtain the fault occurrence time. +#### Obtain the fault occurrence time Fault report time: @@ -478,7 +479,7 @@ The fault occurrence time can be obtained based on the detection duration and th You can search for the keyword **mainHandler dump is** to view the **eventHandler dump** information in logs. -1. dump begin curTime & Current Running +1. **dump begin curTime** & **Current Running**. ``` mainHandler dump is: @@ -494,7 +495,7 @@ If the task running duration is longer than the fault detection duration, the ru If the current task running duration is short, the task is only one of the tasks running in the main thread within the detection duration and may not be the task that consumes most time. You are advised to check the task that consumes the longest time recently (in **History event queue information**). In this case, the watchdog cannot be scheduled because the thread is busy. -2. History event queue information +2. **History event queue information**. ``` Current Running: start at 2024-08-08 12:17:16.629, Event { send thread = 35882, send time = 2024-08-08 12:17:16.628, handle time = 2024-08-08 12:17:16.629, trigger time = 2024-08-08 12:17:16.630, task name = , caller = [extension_ability_thread.cpp(ScheduleAbilityTransaction:393)]} @@ -507,11 +508,11 @@ If the current task running duration is short, the task is only one of the tasks No. 5 : Event { send thread = 35852, send time = 2024-08-08 12:17:16.629, handle time = 2024-08-08 12:17:16.629, trigger time = 2024-08-08 12:17:16.629, completeTime time = , priority = Low, task name = } ``` -You can search for time-consuming tasks in History event queue information. The task whose **completeTime time** is empty is the current task. -Task running duration = completeTime time – trigger time. +You can search for time-consuming tasks in History event queue information. The task whose **completeTime time** is empty is the current task. +Task running duration = completeTime time – trigger time. Filter out the tasks that take a longer time and check the running status of the tasks. -3. VIP priority event queue information +3. **VIP priority event queue information**. ``` VIP priority event queue information: @@ -529,7 +530,7 @@ Filter out the tasks that take a longer time and check the running status of the To ensure timely response to the user, all tasks in the user input event propagation are high-priority tasks. The VIP priority event queue is created by the system and records the transmission process of user input -> screen -> window -> ArkUI -> application. It is irrelevant to third-party application events and does not need to be concerned. -4. High priority event queue information +4. **High priority event queue information**. ``` High priority event queue information: @@ -576,7 +577,7 @@ In the preceding example, the block queue is longer than the warning queue, but Check the stack using the obtained PID and TID. The result may show as follows: -1. The stack information is clearly displayed. +1. The stack information shows that the process is suspended. ``` Tid:3025, Name: xxx @@ -717,7 +718,7 @@ As shown in the stack, the number of threads in the ready state of process 1386 3. Check whether the value of **waitTime** is too small. -**waitTime** indicates the IPC duration. If the value of **waitTime** is far less than the fault detection duration, the suspension is not caused by the IPC request. +**waitTime** indicates the IPC duration. If the value of **waitTime** is far less than the fault detection duration, the suspension is not caused by the IPC request. If the main thread on the application sends multiple IPC requests in a short period of time, the value of **waitTime** will be large. As a result, the thread is suspended. In this case, you can check the following items: @@ -726,32 +727,32 @@ In this case, you can check the following items: 4. Check whether there is no calling relationship and whether the stack is an IPC stack. -Check whether the stack is a temporary stack, that is, whether the warning stack is the same as the block stack. It is possible that the warning stack is an IPC stack, and the block stack is a temporary stack because the IPC request has ended when the binder is captured, and the IPC request takes a short time. +Check whether the stack is a temporary stack, that is, whether the warning stack is the same as the block stack. It is possible that the warning stack is an IPC stack, and the block stack is a temporary stack because the IPC request has ended when the binder is captured, and the IPC request takes a short time. It should be noted that binder information is not obtained in real time when a fault occurs and is delayed. For faults that require half-period detection, binder information is accurately captured because most binder information can be collected within the fault period. For other faults, the off-site binder information may be captured when the reporting is delayed. You can view the execution duration of binder based on [Analyzing Trace Logs](#analyzing-trace logs). -### Analyzing Hilog logs +### Analyzing HiLog logs #### DFX-related Logs -1. Fault report (reportEvent): +1. Fault report (reportEvent). ![appfreeze_2024061401](figures/appfreeze_2024061401.png) -2. Stack capture (signal: 35): +2. Stack capture (signal: 35). ![appfreeze_2024061402](figures/appfreeze_2024061402.png) -3. Background application check for five times before reporting, about 21s: +3. Background application check for five times before reporting, about 21s. ![appfreeze_2024061403](figures/appfreeze_2024061403.png) -4. Exit reason record: +4. Application exit reason record. ![appfreeze_2024061404](figures/appfreeze_2024061404.png) -5. APP_FREEZE kills the application: +5. APP_FREEZE kills the application. ![appfreeze_2024061405](figures/appfreeze_2024061405.png) @@ -759,7 +760,7 @@ You can view the execution duration of binder based on [Analyzing Trace Logs](#a View [Obtain the fault occurrence time](#obtain-the-fault-occurrence-time), and determine the fault occurrence time based on the fault type. Analyze the HiLog logs in the specific period to obtain the status of the running thread. -- If no application log is printed, the application is frozen when the logging API is invoked. +- If no application log is printed, the application freezes when the logging API is called. ![appfreeze_2024061406](figures/appfreeze_2024061406.png) @@ -787,7 +788,7 @@ The possible causes are as follows: ![appfreeze_2024061410](figures/appfreeze_2024061410.png) -In the preceding figure, the **ohos.animator** in **PriviewArea::updateShotComponent** is executed for 9.2s. +In the preceding figure, the **animator** in **PriviewArea::updateShotComponent** is executed for 9.2s. The thread is busy executing a service cyclically and analyzing each service segment. @@ -835,11 +836,11 @@ The background application freezes and related functions are unavailable, but it Extract the key fault logs. ``` -appfreeze: com.huawei.hmsapp.xxx THREAD_BLOCK_6S at 20240408082432 +appfreeze: com.example.hmsapp.xxx THREAD_BLOCK_6S at 20240408082432 DisplayPowerInfo:powerState:AWAKE ``` -The value of **Foreground** indicates that **hiai** is a background application. Therefore, it can be inferred that when the 3s event is reported, the background application freezes for **18s**. +The value of **Foreground** indicates that the application is a background application. Therefore, it can be inferred that when the 3s event is reported, the background application is frozen for 18s. ``` Module name:com.xxx.xxx.xxx @@ -852,7 +853,7 @@ Uid:20020029 Reason:THREAD_BLOCK_6S ``` -The **THREAD_BLOCK_3S** event is reported at **08:24:29:612**. +The **THREAD_BLOCK_3S** event is reported at **08:24:29:612**. The **THREAD_BLOCK_6S** event is reported at **08:24:32:638**. The interval is 3s as expected. ``` @@ -1050,7 +1051,7 @@ which severely affect user experience. Extract the key fault logs. ``` -appfreeze: com.ohos.sceneboard APP_INPUT_BLOCK at 20240319022527 +appfreeze: com.example.sceneboard APP_INPUT_BLOCK at 20240319022527 DisplayPowerInfo:powerState:AWAKE ``` @@ -1062,11 +1063,11 @@ STRINGID:APP_INPUT_BLOCK TIMESTAMP:2024/03/14-14:40:59:440 --> Fault report time. PID:2918 UID:20020017 -PACKAGE_NAME:com.ohos.sceneboard -PROCESS_NAME:com.ohos.sceneboard +PACKAGE_NAME:com.example.sceneboard +PROCESS_NAME:com.example.sceneboard ``` -The reported cause is "User input does not respond!". +The reported cause is "User input does not respond!". There is no response to the user input event. The running task of the main thread (Thread ID == PID) starts at **14:40:53.499** and is not complete until the **Fault time** **14:40:58**. ``` @@ -1112,13 +1113,13 @@ In the following example, more than 200 input events are blocked in the queue. No.205 : Event { send thread = 3370, send time = 2024-03-14 02:40:56.305, handle time = 2024-03-14 02:40:56.305, task name = , caller = [input_manager_impl.cpp(OnPointerEvent:465)] } ``` -The input event triggers the main thread task of the application. However, the execution is not complete within 6 seconds and no response is returned. As a result, the ANR times out. +The input event triggers the main thread task of the application. However, the execution is not complete within 6 seconds and no response is returned. As a result, the ANR times out. In this case, you only need to find out the task that the input triggers and why the task execution times out. In the running main thread stack, the **ark_jsruntime GetCurrentThreadId** function at the stack top does not hold a lock or is time-consuming. The captured stack is a transient stack that is useless for analysis. ``` -Tid:2918, Name:ohos.sceneboard +Tid:2918, Name:example.sceneboard # 00 pc 000000000009f73c /system/lib/ld-musl-aarch64.so.1(8fa55898166cd804dad43d909b5319cc) # 01 pc 000000000054b7b4 /system/lib64/platformsdk/libark_jsruntime.so(panda::os::thread::GetCurrentThreadId()+12)(7715646e48f750f3dc31e660b056eb43) # 02 pc 00000000002107a4 /system/lib64/platformsdk/libark_jsruntime.so(panda::ecmascript::EcmaVM::CheckThread() const+200)(7715646e48f750f3dc31e660b056eb43) @@ -1137,9 +1138,9 @@ Tid:2918, Name:ohos.sceneboard ... ``` -Check the Hilog logs. +Check the HiLog logs. -The **APP_INPUT_BLOCK** event is reported at about **13:40:59.448**, and then DFX kills the freezed SCB. +The **APP_INPUT_BLOCK** event is reported at about **13:40:59.448**, and then DFX kills the suspended SCB. ![appfreeze_2024061412](figures/appfreeze_2024061412.png) @@ -1157,9 +1158,9 @@ Check the trace log within the 6 seconds. It shows that the SCB main thread is fully occupied. The **CustomNodeUpdate SwiperPage** task takes a longer time. Therefore, you need to check why this component keeps refreshing. -It is found that **themeStyle** is added to the **key** on **swiperPage**. When the **key** value changes, a new control is created. +It is found that **themeStyle** is added to the **key** on **swiperPage**. When the **key** value changes, a new component is created. -When a user switches the theme or icon style, all controls on the home screen are created. As a result, the main thread is busy and cannot respond the input event. +When a user switches the theme or icon style, all components on the home screen are created. As a result, the main thread is busy and cannot respond the input event. #### Solution @@ -1222,7 +1223,7 @@ client: 312522; AbilityThread::ScheduleAbilityTransaction; the foreground lifecycle. ``` -The **LIFECYCLE_HALF_TIMEOUT** event is reported at **10:04:57:538**. +The **LIFECYCLE_HALF_TIMEOUT** event is reported at **10:04:57:538**. The **LIFECYCLE_TIMEOUT** event is reported at **10:04:59:965**. The interval of the two events is about 2.5s, which is as expected. ``` @@ -1232,8 +1233,8 @@ STRINGID:LIFECYCLE_TIMEOUT TIMESTAMP:2024/02/01-10:04:59:965 PID:18083 UID:20020041 -PACKAGE_NAME:com.huawei.hmos.notepad -PROCESS_NAME:com.huawei.hmos.notepad +PACKAGE_NAME:com.example.notepad +PROCESS_NAME:com.example.notepad ******************************************* start time: 2024/02/01-10:04:57:555 DOMAIN = AAFWK @@ -1242,8 +1243,8 @@ TIMESTAMP = 2024/02/01-10:04:57:538 PID = 18083 UID = 20020041 TID = 17286 -PACKAGE_NAME = com.huawei.hmos.notepad -PROCESS_NAME = com.huawei.hmos.notepad +PACKAGE_NAME = com.example.notepad +PROCESS_NAME = com.example.notepad ``` The task starts at **10:04:54.798**, and the interval between the start time and **LIFECYCLE_HALF_TIMEOUT** is about 2.5s, which is as expected. @@ -1263,10 +1264,10 @@ mainHandler dump is: ... ``` -Check the stack information at **libfs.z.so -> libdatashare_consumer.z.so -> libipc_core.z.so**. +Check the stack information at **libfs.z.so > libdatashare_consumer.z.so > libipc_core.z.so**. ``` -Tid:18083, Name:ei.hmos.notepad +Tid:18083, Name:ei.example.notepad # 00 pc 00000000001617a4 /system/lib/ld-musl-aarch64.so.1(ioctl+180)(4ca73cff61bea7c4a687eb0f71c9df69) # 01 pc 000000000003e8a0 /system/lib64/platformsdk/libipc_core.z.so(OHOS::BinderConnector::WriteBinder(unsigned long, void*)+72)(3248fceb1fa676994734e0437430ce37) # 02 pc 0000000000049f38 /system/lib64/platformsdk/libipc_core.z.so(OHOS::BinderInvoker::TransactWithDriver(bool)+296)(3248fceb1fa676994734e0437430ce37) @@ -1303,7 +1304,7 @@ Result: 0 ( no error ) Timestamp:2024-02-01 10:04:57.000 Pid:5235 Uid:20020079 -Process name:com.ohos.medialibrary.medialibrarydata +Process name:com.medialibrary.medialibrarydata Tid:5235, Name:edialibrarydata # 00 pc 0000000000142d1c /system/lib/ld-musl-aarch64.so.1(epoll_wait+84)(4ca73cff61bea7c4a687eb0f71c9df69) # 01 pc 000000000000fb74 /system/lib64/chipset-pub-sdk/libeventhandler.z.so(OHOS::AppExecFwk::EpollIoWaiter::WaitFor(std::__h::unique_lock&, long)+224)(a4d21072c08fd3ac639d5cf5b8fb8b51) diff --git a/en/application-dev/dfx/apprecovery-guidelines.md b/en/application-dev/dfx/apprecovery-guidelines.md index c514d3b877e0c81050113e4e01c7e3996fb62482..d2437eeab8686fbd682677d60ee5ca00a62e8ecc 100644 --- a/en/application-dev/dfx/apprecovery-guidelines.md +++ b/en/application-dev/dfx/apprecovery-guidelines.md @@ -15,15 +15,15 @@ In API version 10, application recovery is applicable to multiple abilities of a The application recovery APIs are provided by the **appRecovery** module, which can be imported via **import**. For details, see [Development Example](#development-example). -### Application Recovery APIs +### Available APIs | API | Description | | ------------------------------------------------------------ | ---------------------------------------------------- | -| enableAppRecovery(restart?: RestartFlag, saveOccasion?: SaveOccasionFlag, saveMode?: SaveModeFlag) : void;9+ | Enables application recovery. After this API is called, the first ability that is displayed when the application is started from the initiator can be restored.| -| saveAppState(): boolean;9+ | Saves the state of the ability that supports recovery in the current application.| -| restartApp(): void;9+ | Restarts the current process and starts the ability specified by **setRestartWant**. If no ability is specified, a foreground ability that supports recovery is restarted.| -| saveAppState(context?: UIAbilityContext): boolean;10+ | Saves the ability state specified by **Context**.| -| setRestartWant(want: Want): void;10+ | Sets the abilities to restart when **restartApp** is actively called and **RestartFlag** is not **NO_RESTART**. The abilities must be under the same bundle name and must be a **UIAbility**.| +| enableAppRecovery(restart?: RestartFlag, saveOccasion?: SaveOccasionFlag, saveMode?: SaveModeFlag) : void9+ | Enables application recovery. After this API is called, the first ability that is displayed when the application is started from the initiator can be restored.| +| saveAppState(): boolean9+ | Saves the state of the ability that supports recovery in the current application.| +| restartApp(): void9+ | Restarts the current process and starts the ability specified by **setRestartWant**. If no ability is specified, a foreground ability that supports recovery is restarted.| +| saveAppState(context?: UIAbilityContext): boolean10+ | Saves the ability state specified by **Context**.| +| setRestartWant(want: Want): void10+ | Sets the abilities to restart when **restartApp** is actively called and **RestartFlag** is not **NO_RESTART**. The abilities must be under the same bundle name and must be a **UIAbility**.| No error will be thrown if the preceding APIs are used in the troubleshooting scenario. The following are some notes on API usage: @@ -60,6 +60,7 @@ Fault management is an important way for applications to deliver a better user e The figure below does not illustrate the time when [faultLogger](../reference/apis-performance-analysis-kit/js-apis-faultLogger.md) is called. You can refer to the [LastExitReason](../reference/apis-ability-kit/js-apis-app-ability-abilityConstant.md#abilityconstantlastexitreason) passed during application initialization to determine whether to call [faultLogger](../reference/apis-performance-analysis-kit/js-apis-faultLogger.md) to query information about the previous fault. ![Fault rectification process](./figures/fault_rectification.png) + It is recommended that you call [errorManager](../reference/apis-ability-kit/js-apis-app-ability-errorManager.md) to handle the exception. After the processing is complete, you can call the **saveAppState** API and restart the application. If you do not register an [ErrorObserver](../reference/apis-ability-kit/js-apis-inner-application-errorObserver.md) instance or enable application recovery, the application process will exit according to the default processing logic of the system. Users can restart the application from the home screen. If you have enabled application recovery, the recovery framework first checks whether application state saving is supported and whether the application state saving is enabled. If so, the recovery framework invokes [onSaveState](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityonsavestate) of the [ability](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md). Finally, the application is restarted. diff --git a/en/application-dev/dfx/cppcrash-guidelines.md b/en/application-dev/dfx/cppcrash-guidelines.md index e2ba7ce073a9e61ac809023ed71af1faeb14ae64..2e6dbb3c86ab9a32efedea5746b0f2c020fe82b9 100644 --- a/en/application-dev/dfx/cppcrash-guidelines.md +++ b/en/application-dev/dfx/cppcrash-guidelines.md @@ -19,69 +19,69 @@ Process crash detection is based on the posix signal mechanism. Currently, the e | 16 | SIGSTKFLT | Stack error| The processor performs an incorrect stack operation, such as a pop when the stack is empty or a push when the stack is full.| | 31 | SIGSYS | Incorrect system call| An incorrect or invalid parameter is used in a system call.| -Some of the preceding fault signals are classified into codes based on specific scenarios. +Some of the preceding fault signals are classified into codes based on specific scenarios. **SIGILL** occurs in Unix and Unix-like operating systems. It indicates an invalid instruction exception. The **SIGILL** signal is usually triggered by the following causes: -| No.| Code| Description| Trigger Cause| +| Code| Signal| Description| Trigger Cause| | -------- | -------- | -------- | -------- | -| 1 | ILL_ILLOPC | Illegal operation code| A privileged instruction or an instruction that is unsupported by the CPU is executed.| -| 2 | ILL_ILLOPN | Illegal operand| An incorrect operand or improper operand type is used.| -| 3 | ILL_ILLADR | Illegal address| A program accesses an invalid memory address or an unaligned memory address.| -| 4 | ILL_ILLTRP | Illegal trap| A program performs an illegal trap instruction or an undefined operation.| -| 5 | ILL_PRVOPC | Illegal privileged operation code| A common user executes a privileged instruction.| -| 6 | ILL_PRVREG | Illegal privileged register| A common user accesses a privileged register.| -| 7 | ILL_COPROC | Illegal coprocessor| A program performs an undefined coprocessor instruction.| -| 8 | ILL_BADSTK | Illegal stack| A program performs an operation at an invalid stack address, or when the stack overflows.| +| 1 | ILL_ILLOPC | Illegal operation code.| A privileged instruction or an instruction that is unsupported by the CPU is executed.| +| 2 | ILL_ILLOPN | Illegal operand.| An incorrect operand or improper operand type is used.| +| 3 | ILL_ILLADR | Illegal address.| A program accesses an invalid memory address or an unaligned memory address.| +| 4 | ILL_ILLTRP | Illegal trap.| A program performs an illegal trap instruction or an undefined operation.| +| 5 | ILL_PRVOPC | Illegal privileged operation code.| A common user executes a privileged instruction.| +| 6 | ILL_PRVREG | Illegal privileged register.| A common user accesses a privileged register.| +| 7 | ILL_COPROC | Illegal coprocessor.| A program performs an undefined coprocessor instruction.| +| 8 | ILL_BADSTK | Illegal stack.| A program performs an operation at an invalid stack address, or when the stack overflows.| **SIGTRAP** usually occurs in debugging and tracking. The four scenarios of the **SIGTRAP** signal are described as follows. -| No.| Code| Description| Trigger Cause| +| Code| Signal| Description| Trigger Cause| | -------- | -------- | -------- | -------- | -| 1 | TRAP_BRKPT | Software breakpoint| The software breakpoint is reached in a program. When debugging a program, a software breakpoint at the key position can be used to pause the program execution and check information such as variable values.| -| 2 | TRAP_TRACE | Single-step debugging| A single instruction is executed in a program. Single instruction can be used to check the execution result of each instruction.| -| 3 | TRAP_BRANCH | Branch Tracing| A branch instruction is executed in a program. Branch instruction can be used to control the execution process of a program, such as if statements and loop statements.| -| 4 | TRAP_HWBKPT | Hardware breakpoint| The hardware breakpoint is reached in a program. When debugging a program, a hardware breakpoint at the key position can be used to pause the program execution and check information such as variable values. Different from a software breakpoint, a hardware breakpoint is implemented in CPU hardware. Therefore, whether a hardware breakpoint is triggered can be detected in real time during program execution.| +| 1 | TRAP_BRKPT | Software breakpoint.| The software breakpoint is reached in a program. When debugging a program, a software breakpoint at the key position can be used to pause the program execution and check information such as variable values.| +| 2 | TRAP_TRACE | Single-step debugging.| A single instruction is executed in a program. Single instruction can be used to check the execution result of each instruction.| +| 3 | TRAP_BRANCH | Branch tracing.| A branch instruction is executed in a program. Branch instruction can be used to control the execution process of a program, such as if statements and loop statements.| +| 4 | TRAP_HWBKPT | Hardware breakpoint.| The hardware breakpoint is reached in a program. When debugging a program, a hardware breakpoint at the key position can be used to pause the program execution and check information such as variable values. Different from a software breakpoint, a hardware breakpoint is implemented in CPU hardware. Therefore, whether a hardware breakpoint is triggered can be detected in real time during program execution.| The **SIGBUS** signal is sent by the operating system to a process. It usually indicates a memory access error. The codes of the **SIGBUS** signal are described as follows: -| No.| Code| Description| Trigger Cause| +| Code| Signal| Description| Trigger Cause| | -------- | -------- | -------- | -------- | -| 1 | BUS_ADRALN | Unaligned memory address| A program accesses an unaligned memory address, for example, a non-even address of a 4-byte integer.| -| 2 | BUS_ADRERR | Invalid memory address| A program accesses a memory address that does not exist in the Process Address Space, such as a null pointer.| -| 3 | BUS_OBJERR | Invalid object access| A program accesses an object that is deleted or not initialized.| -| 4 | BUS_MCEERR_AR | Invalid hardware memory check| A checksum error is detected when the hardware memory is accessed.| -| 5 | BUS_MCEERR_AO | Invalid hardware memory check| An address check error is detected when the hardware memory is accessed.| +| 1 | BUS_ADRALN | Unaligned memory address.| A program accesses an unaligned memory address, for example, a non-even address of a 4-byte integer.| +| 2 | BUS_ADRERR | Invalid memory address.| A program accesses a memory address that does not exist in the Process Address Space, such as a null pointer.| +| 3 | BUS_OBJERR | Invalid object access.| A program accesses an object that is deleted or not initialized.| +| 4 | BUS_MCEERR_AR | Invalid hardware memory check.| A checksum error is detected when the hardware memory is accessed.| +| 5 | BUS_MCEERR_AO | Invalid hardware memory check.| An address check error is detected when the hardware memory is accessed.| The **SIGFPE** signal indicates a floating-point exception or an arithmetic exception. The codes of the **SIGFPE** signal are described as follows: -| No.| Code| Description| Trigger Cause| +| Code| Signal| Description| Trigger Cause| | -------- | -------- | -------- | -------- | -| 1 | FPE_INTDIV | Invalid integer division| The divisor in an integer division is zero. | -| 2 | FPE_INTOVF | Integer overflow| The divisor in an integer division is negative. | -| 3 | FPE_FLTDIV | Invalid floating-point division| The divisor in a floating-point division is zero. | -| 4 | FPE_FLTOVF | Floating-point overflow| The divisor in a floating-point division is negative. | -| 5 | FPE_FLTUND | Floating-point underflow| The divisor in a floating-point division is zero. | -| 6 | FPE_FLTRES | Invalid floating-point result| The divisor in a floating-point division is positive. | -| 7 | FPE_FLTINV | Invalid floating-point operation| The divisor in a floating-point division is negative. | -| 8 | FPE_FLTSUB | Floating-point trap| The divisor in a floating-point division is zero. | +| 1 | FPE_INTDIV | Invalid integer division.| The divisor in an integer division is zero. | +| 2 | FPE_INTOVF | Integer overflow.| The divisor in an integer division is negative. | +| 3 | FPE_FLTDIV | Invalid floating-point division.| The divisor in a floating-point division is zero. | +| 4 | FPE_FLTOVF | Floating-point overflow.| The divisor in a floating-point division is negative. | +| 5 | FPE_FLTUND | Floating-point underflow.| The divisor in a floating-point division is zero. | +| 6 | FPE_FLTRES | Invalid floating-point result.| The divisor in a floating-point division is positive. | +| 7 | FPE_FLTINV | Invalid floating-point operation.| The divisor in a floating-point division is negative. | +| 8 | FPE_FLTSUB | Floating-point trap.| The divisor in a floating-point division is zero. | The **SIGSEGV** signal occurs when a process accesses a non-existent memory address or an inaccessible address. The codes of the **SIGSEGV** signal are described as follows: -| No.| Code| Description| Trigger Cause| +| Code| Signal| Description| Trigger Cause| | -------- | -------- | -------- | -------- | -| 1 | SEGV_MAPERR | Non-existent memory address| A process accesses a memory address that does not exist or that is not mapped to the Process Address Space. This exception is usually caused by pointer errors or memory leaks.| -| 2 | SEGV_ACCERR | Inaccessible memory address| A process accesses an inaccessible memory address marked by the operating system, such as a read-only memory address or a memory address without execution permission. This exception is usually caused by buffer overflow or modifying read-only memory.| +| 1 | SEGV_MAPERR | Non-existent memory address.| A process accesses a memory address that does not exist or that is not mapped to the Process Address Space. This exception is usually caused by pointer errors or memory leaks.| +| 2 | SEGV_ACCERR | Inaccessible memory address.| A process accesses an inaccessible memory address marked by the operating system, such as a read-only memory address or a memory address without execution permission. This exception is usually caused by buffer overflow or modifying read-only memory.| The classification of codes cannot only be based on **signo**, but also be based on the causes of the signal. The preceding describes the codes classified based on the **signo** of each signal, while the following describes the codes classified based on causes of all signals: -| No.| Code| Description| Trigger Cause| +| Code| Signal| Description| Trigger Cause| | -------- | -------- | -------- | -------- | -| 0 | SI_USER | User space signal|This signal is sent by a process in user space to another process, usually using the **kill()**. For example, when a user presses **Ctrl+C** on the terminal, a **SIGINT** signal is sent to all foreground processes.| -| 0x80 | SI_KERNEL | Kernel signal|This signal is sent by the kernel to the process. It is usually sent when the kernel detects some errors or exceptions. For example, when a process accesses an invalid memory address or executes an invalid instruction, the kernel sends a **SIGSEGV** signal to the process.| -| -1 | SI_QUEUE | **sigqueue()** signal|This signal is sent by **sigqueue()**, and an additional integer value and a pointer can be carried. It is usually used for advanced communication between processes, such as transferring data or notifying a process that an event occurs.| -| -2 | SI_TIMER | Timer signal|This signal is sent by a timer and is usually used to execute a scheduled task or a periodic task. For example, when a timer expires, the kernel sends a **SIGALRM** signal to the process.| -| -3 | SI_MESGQ | Message queue signal|This signal is sent by a message queue and is usually used for communication across processes. For example, when a process sends a message to a message queue, the kernel sends a **SIGIO** signal to the receiving process.| -| -4 | SI_ASYNCIO | Asynchronous I/O signal|This signal is sent by an asynchronous I/O and is usually used for a non-blocking I/O. For example, when an I/O operation on a file descriptor is complete, the kernel sends a **SIGIO** signal to the process.| -| -5 | SI_SIGIO | Synchronous I/O signal|This signal is sent by a synchronous I/O and is usually used for a non-blocking I/O. For example, when an I/O operation on a file descriptor is complete, the kernel sends a **SIGIO** signal to the process.| -| -6 | SI_TKILL | **tkill()** signal|This signal is sent by the function **tkill()**, which is similar to the function **kill()**. In addition, you can specify the ID of the thread that sends the signal. It is usually used to send a signal to a specified thread in a multithreaded program.| +| 0 | SI_USER | User space.|This signal is sent by a process in user space to another process, usually using the **kill()**. For example, when a user presses **Ctrl+C** on the terminal, a **SIGINT** signal is sent to all foreground processes.| +| 0x80 | SI_KERNEL | Kernel.|This signal is sent by the kernel to the process. It is usually sent when the kernel detects some errors or exceptions. For example, when a process accesses an invalid memory address or executes an invalid instruction, the kernel sends a **SIGSEGV** signal to the process.| +| -1 | SI_QUEUE | The **sigqueue()** function.|This signal is sent by **sigqueue()**, and an additional integer value and a pointer can be carried. It is usually used for advanced communication between processes, such as transferring data or notifying a process that an event occurs.| +| -2 | SI_TIMER | Timer.|This signal is sent by a timer and is usually used to execute a scheduled task or a periodic task. For example, when a timer expires, the kernel sends a **SIGALRM** signal to the process.| +| -3 | SI_MESGQ | Message queue.|This signal is sent by a message queue and is usually used for communication across processes. For example, when a process sends a message to a message queue, the kernel sends a **SIGIO** signal to the receiving process.| +| -4 | SI_ASYNCIO | Asynchronous I/O.|This signal is sent by an asynchronous I/O and is usually used for a non-blocking I/O. For example, when an I/O operation on a file descriptor is complete, the kernel sends a **SIGIO** signal to the process.| +| -5 | SI_SIGIO | Synchronous I/O.|This signal is sent by an asynchronous I/O and is usually used for a non-blocking I/O. For example, when an I/O operation on a file descriptor is complete, the kernel sends a **SIGIO** signal to the process.| +| -6 | SI_TKILL | The **tkill()** function.|This signal is sent by the function **tkill()**, which is similar to the function **kill()**. In addition, you can specify the ID of the thread that sends the signal. It is usually used to send a signal to a specified thread in a multithreaded program.| ## Fault Analysis @@ -356,7 +356,7 @@ OpenFiles: <- FD information of the file opened by the process when the fault 25->/dev/ptmx native object of unknown type 0 26->/dev/ptmx native object of unknown type 0 -HiLog: <- Hilog logs when the fault occurs +HiLog: <- HiLog logs when the fault occurs 05-06 20:10:51.301 9623 9623 E C03f00/MUSL-SIGCHAIN: signal_chain_handler call 2 rd sigchain action for signal: 11 05-06 20:10:51.306 9623 9623 I C02d11/DfxSignalHandler: DFX_SigchainHandler :: sig(11), pid(9623), tid(9623). 05-06 20:10:51.307 9623 9623 I C02d11/DfxSignalHandler: DFX_SigchainHandler :: sig(11), pid(9623), processName(./crasher_cpp), threadName(crasher_cpp). @@ -450,7 +450,7 @@ Tid:18257, Name:crasher_cpp <- Thread ID, thread name **Logs of Custom Information About System Framework Services** -When a process crashes, the custom maintenance and test information of the system framework service can be printed to help you locate faults. The information can be the string, memory, callback, or stack type. Currently, the ARM64 architecture is supported. Since API 16, the **LastFatalMessage** field carries only the last fatal-level log printed by using HiLog or the last message set by using the **set_fatal_memssage** API of libc before the process crashes. The callback type information and stack type information are moved from the **LastFatalMessage** field to the **ExtraCrashInfo** (Callback) and **ExtraCrashInfo** (Unwindstack) fields, respectively. The following is the core content of the process crash logs archived by DevEco Studio in FaultLog, which contains four types of custom information about system framework services. +When a process crashes, the custom maintenance and test information of the system framework service can be printed to help you locate faults. The information can be the string, memory, callback, or stack type. Currently, the ARM64 architecture is supported. Since API 18, the **LastFatalMessage** field carries only the last fatal-level log printed by using HiLog or the last message set by using the **set_fatal_message** API of libc before the process crashes. The callback type information and stack type information are moved from the **LastFatalMessage** field to the **ExtraCrashInfo** (Callback) and **ExtraCrashInfo** (Unwindstack) fields, respectively. The following is the core content of the process crash logs archived by DevEco Studio in FaultLog, which contains four types of custom information about system framework services. - String information: @@ -497,7 +497,7 @@ When a process crashes, the custom maintenance and test information of the syste 3. Callback information: - From API 16, the callback information is moved from the **LastFatalMessage** field to the **ExtraCrashInfo(Callback)** field. + From API 18, the callback information is moved from the **LastFatalMessage** field to the **ExtraCrashInfo(Callback)** field. ```text ... @@ -508,7 +508,7 @@ When a process crashes, the custom maintenance and test information of the syste 4. Stack information: - From API 16, the stack information is moved from the **LastFatalMessage** field to the **ExtraCrashInfo(Unwindstack)** field. + From API 18, the callback information is moved from the **LastFatalMessage** field to the **ExtraCrashInfo(Unwindstack)** field. ```text ... @@ -531,8 +531,8 @@ In application development, you can locate the problematic code in the cppcrash #### Method 2: SDK llvm-addr2line -- Obtain the symbol list - Obtain the .so file with symbols in the crash stack, which should be the same as that of the application or system. +- Obtain the symbol list. + Obtain the .so file with symbols in the crash stack, which should be the same as that of the application or system. Compiled and built in DevEco Studio, the .so file of dynamic library is generated with symbols by default in **/build/default/intermediates/libs**. You can run the **Linux file** command to check whether the BuildID of two .so files match. Generated by a compiler, BuildID is the unique identifier of a binary file, in which "not stripped" indicates that a symbol table is included. ```text @@ -540,10 +540,10 @@ In application development, you can locate the problematic code in the cppcrash libbabel.so: ELF 64-bit LSB shared object, ARM aarch64, version 1 (SYSV), dynamically linked, BuildID[sha1]=fdb1b5432b9ea4e2a3d29780c3abf30e2a22da9d, with debug_info, not stripped ``` - Note: The symbol table of the system dynamic library is archived with the version. + **Note**: The symbol table of the system dynamic library is archived with the version. -- Locate the line number using llvm-addr2line - You can find llvm-addr2line in **[SDK DIR PATH]\OpenHarmony\11\native\llvm\bin**, or you need to search for the path as it varies based on the SDK version. +- Locate the line number using llvm-addr2line. + You can find llvm-addr2line in **[SDK DIR PATH]\OpenHarmony\11\native\llvm\bin**, or you need to search for the path as it varies based on the SDK version. The sample stack is as follows (part are omitted): ```text @@ -631,7 +631,7 @@ Procedure: Obtain the PC address at the top of the stack from the CPPCRASH log file and disassemble the corresponding ELF file (using the unstrip .so file and the **llvm-objdump -d -l xxx.so** command). - For example, when a **data_abort** issue occurs during the execution of the instruction corresponding to the **00000000000a87e4** address, decompile the libc.so file corresponding to the buildId (**3c3e7fb27680dc2ee99aa08dd0f81e85**). + For example, when a **data_abort** issue occurs during the execution of the instruction corresponding to the **00000000000a87e4** address, decompile the libc.so file corresponding to the buildId **3c3e7fb27680dc2ee99aa08dd0f81e85**. Disassemble the code to view the information displayed in the **a87e4** offset address: @@ -685,7 +685,7 @@ Procedure: 3. Determine the fault type of the code object. - Check the memory address near the register in **Memory near registers** in the CPPCRASH log. + Check **Memory near registers** in the CPPCRASH log. ```text x1(/data/medialibrary/database/kvdb/3ddb6fb8b2fcb38d2f431e86bfb806dab771637860d6e86bb9430fa15df04248/single_ver/main/gen_natural_st): @@ -761,15 +761,15 @@ Procedure: ### Common CppCrash Faults and Causes -- Null pointer dereference - When a crash log is in format **SIGSEGV(SEGV_MAPERR)@0x00000000** or the values of the input parameter registers such as **r0** and **r1** printed in the **Register** are **0**, check whether a null pointer is input when invoking a method. +- Null pointer dereference. + When a crash log is in format **SIGSEGV(SEGV_MAPERR)@0x00000000** or the values of the input parameter registers such as **r0** and **r1** printed in the **Register** are **0**, check whether a null pointer is input when invoking a method. When a crash log is in format **SIGSEGV(SEGV_MAPERR)@0x0000000c** or the value of the input parameter register such as **r1** printed in the **Register** is small, check whether the called structs contain a null pointer. -- SIGABRT +- SIGABRT. Generally, this fault is triggered by the user, framework, or C library, and you can locate the problematic code in the first frame of the framework library. In this case, check whether resources such as thread and file descriptor are properly used, and whether the invoking sequence of APIs is correct. -- SIGSEGV - - Multithreading operation collection in STD library is not thread-safe. If the collection is added or deleted on multiple threads, the **SIGSEGV** crash occurs. If **llvm-addr2line** is used and the result code involve operations on collections, this could be the reason for the crash. +- SIGSEGV. + - Multithreading operation collection in STD library is not thread-safe. If the collection is added or deleted on multiple threads, the **SIGSEGV** crash occurs. If **llvm-addr2line** is used and the result code involve operations on collections, this could be the reason for the crash. - If the pointer does not match the lifecycle of an object, for example, using a raw pointer to store the **sptr** type and **shared_ptr** type, can lead to memory leak and dangling pointer. A raw pointer is a pointer that does not have features such as encapsulation and automatic memory management. It is only a simple pointer to the memory address. The memory to which the pointer points is not protected or managed. A raw pointer can directly access the pointed memory, but problems such as memory leak and null pointer reference may also occur. Therefore, when using a raw pointer, pay attention to potential security problems. You are advised to use smart pointers to manage memory. -- Use after free +- Use after free. This fault occurs when the reference of a released stack variable is not set to null and the access continues. ```text @@ -812,18 +812,18 @@ Procedure: } ``` - When a **RecursiveClass** object is created, its constructor is called. When this object is destroyed, its destructor is called. In the destructor, a new **RecursiveClass** object is created, which causes recursive calls until the stack overflows. Recursive calls are infinite. As a result, the stack space is used up and the application crashes. + When a **RecursiveClass** object is created, its constructor is called. When this object is destroyed, its destructor is called. In the destructor, a new **RecursiveClass** object is created, which causes recursive calls until the stack overflows. Recursive calls are infinite. As a result, the stack space is used up and the application crashes. - Binary mismatch usually indicates the mismatch of the Application Binary Interface (ABI). For example, when a compiled binary interface or its data structure definition does not match the ABI, a random crash stack is generated. - Memory corruption occurs when the memory of a valid wild pointer is changed to an invalid value, which results in out-of-bounds access and data overwrite. In this case, a random crash stack is generated. -- SIGBUS (Aligment) occurs when the address is in the unaligned state after the pointer is forcibly converted. +- SIGBUS (Alignment) occurs when the address is in the unaligned state after the pointer is forcibly converted. - When the length of a function name exceeds 256 bytes, the stack frame does not contain the function name. - If the ELF file does not contain **.note.gnu.build-id**, the stack frame does not contain the **build-id** information. ## Case Study -The following analyzes the typical CppCrash cases based on signals, scenarios, and tools respectively. -The analysis based on signals introduces common crash signals and provides a typical case for each type of signal. -The analysis based on scenarios concludes a common scenario for frequent problems, and provides a typical case for each scenario. +The following analyzes the typical CppCrash cases based on signals, scenarios, and tools respectively. +The analysis based on signals introduces common crash signals and provides a typical case for each type of signal. +The analysis based on scenarios concludes a common scenario for frequent problems, and provides a typical case for each scenario. The analysis based on tools describes how to use various maintenance and debugging tools, and provides a typical case for each tool. ### Analyzing CppCrash Based on Signals @@ -839,7 +839,7 @@ The **SIGSEGV** signal indicates a Segmentation Fault of the program. This fault In most cases, **SIGSEGV** is caused by pointer overwriting. However, not all pointer overwriting causes **SIGSEGV**. The **SIGSEGV** crash would not be triggered unless an out-of-bounds pointer is dereferenced. In addition, even if an out-of-bounds pointer is dereferenced, the **SIGSEGV** crash may not be caused. The **SIGSEGV** crash involves the operating system, C library, compiler, and linker. The examples are as follows: -- The memory area is read-only memory. +- The memory area is read-only memory. The sample code is as follows: ```text @@ -855,8 +855,7 @@ In most cases, **SIGSEGV** is caused by pointer overwriting. However, not all po ![cppcrash-demo2](figures/cppcrash_image_005.png) -- The memory area is out of the process address space. - +- The memory area is out of the process address space. The sample code is as follows: ```text @@ -900,7 +899,7 @@ In most cases, **SIGSEGV** is caused by pointer overwriting. However, not all po # 40 pc 00000000000a4b98 /system/lib/ld-musl-aarch64.so.1(libc_start_main_stage2+64)(ff4c94d996663814715bedb2032b2bbc) ``` -3. The memory does not exist. +3. The memory does not exist. The sample code is as follows: ```text @@ -916,7 +915,7 @@ In most cases, **SIGSEGV** is caused by pointer overwriting. However, not all po ![cppcrash-demo3](figures/cppcrash_image_006.png) -4. Double free. +4. Double free. The sample code is as follows: ```text @@ -940,8 +939,8 @@ In most cases, **SIGSEGV** is caused by pointer overwriting. However, not all po The **SIGABRT** signal is sent to abort the process. This signal can be called by the process executing **abort()** in C standard library, or it can be sent to the process from outside like other signals. -- Executing the **abort()** function. - The sample code is as follows: +- + The sample code of executing the **abort()** function: ```text static napi_value TriggerCrash(napi_env env, napi_callback_info info) @@ -956,8 +955,8 @@ The **SIGABRT** signal is sent to abort the process. This signal can be called b ![cppcrash-demo4](figures/cppcrash_image_008.png) -- Executing the **assert()** function. - The sample code is as follows: +- + The sample code of executing the **assert()** function: ```text static napi_value TriggerCrash(napi_env env, napi_callback_info info) @@ -1049,7 +1048,6 @@ previously allocated by thread T0 (thread name) here: ... ``` -Continue the analysis based on the stack. When **JsiWeak** is destructed or reset, **CopyableGlobal** in the parent class **JsiType** of its member (**JsiObject**/**JsiValue**/**JsiFunction**) is released, as shown in the following figure. ![cppcrash-demo5](figures/cppcrash_image_011.png) @@ -1092,7 +1090,7 @@ The **env** created by a thread should not be transferred to another thread. **Suggestions** -You can select the **Multi Thread Check** option to locate multi thread faults. For details, see "Ark Multi Thread Check" in guideline. +You can select the **Multi Thread Check** option to locate multi thread faults. For details, see "Ark Runtime Multi Thread Check" in guideline. Note: **env** in the **napi** interface is the **arkNativeEngine** when the engine is created. @@ -1143,13 +1141,13 @@ Add protective null checks for the pointer. Pointers should be null-checked before using it to prevent null pointers and process crashes and exits. -### Analyzing CppCrash Based on Tools +### Analyzing Cpp Crash Based on Tools #### Tool 1: ASAN -[ASan Check](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/ide-asan-V5) +[ASan Check](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/ide-asan-V5). -#### Tool 2: Ark Multi Thread Check +#### Tool 2: Ark Runtime Multi Thread Check **Fundamentals** @@ -1167,7 +1165,7 @@ If the stack of crash logs is difficult to analyze and the probability of this p **Cases** -After the function is enabled, the crash is triggered again. If the problem is caused by multiple threads, fatal information is displayed. The following is an example: +After the multi thread check is enabled, the crash is triggered again. If the problem is caused by multiple threads, fatal information is displayed. The following is an example: ```text Fatal: ecma_vm cannot run in multi-thread! thread:xxx currentThread:yyy @@ -1190,8 +1188,8 @@ Tid:17585, Name:xxxxx # 06 pc 00000000005d9770 /data/ storage/el1/bundle/libs/arm64/xxxxx.so (c0f1735eada49fadc5197745f5afOc0a52246270) ``` -To analyze the multi-thread problem, perform the following steps: -i. Check the first stack frame under **libace_napi.z.so**. The preceding figure shows **xxxxx.so**. Check whether the **napi_env** of thread **17688** is transferred to thread **17585**. +To analyze the multi-thread problem, perform the following steps: +i. Check the first stack frame under **libace_napi.z.so**. The preceding figure shows **xxxxx.so**. Check whether the **napi_env** of thread **17688** is transferred to thread **17585**. ii. If the stack frame under **libace_napi.z.so** does not transfer the **napi_env** parameter, check whether the parameter is transferred as a struct member variable. #### Tool 3: objdump @@ -1256,5 +1254,5 @@ Registers: x0:0000007f0fe31560 x1:0000000000000003 x2:0000000000000000 x3:000000 x28:0000007f9f21a1c0 x29:00000055a0e19700 lr:0000007f9cb4b584 sp:00000055a0e19700 pc:0000007f9cb492d4 ``` -**ldrb w8, [x20]** corresponds to **packedData_.flags_.spaceFlag_** because **packedData_** is the first field of **region**, **flags_** is the first field of **packedData_**, and **spaceFlag_** is the first field of **flags_**. Therefore, the first byte corresponding to the **objectRegion** address is used. +**ldrb w8, [x20]** corresponds to **packedData_.flags_.spaceFlag_** because **packedData_** is the first field of **region**, **flags_** is the first field of **packedData_**, and **spaceFlag_** is the first field of **flags_**. Therefore, the first byte corresponding to the **objectRegion** address is used. To view assembly code, you need to be familiar with common assembly instructions and parameter transfer rules. For example, the non-inline member function **r0** in C++ stores the **this** pointer. In addition, due to compiler optimization, the mapping between source code and assembly code may not be clear. The mapping can be quickly obtained based on some feature values (constants) in the code. diff --git a/en/application-dev/dfx/errormanager-guidelines.md b/en/application-dev/dfx/errormanager-guidelines.md index f8684acd4ecc6a58b822cfc490247662c7614bd6..9dc23a6d43de6487b288de358d5c4d7ef083e31f 100644 --- a/en/application-dev/dfx/errormanager-guidelines.md +++ b/en/application-dev/dfx/errormanager-guidelines.md @@ -23,6 +23,8 @@ Application error management APIs are provided by the [errorManager](../referenc | off(type: 'globalUnhandledRejectionDetected', observer?: GlobalObserver): void | Unregisters the previously registered callback observer. (**Recommended**) | | on(type: 'loopObserver', timeout: number, observer: LoopObserver): void12+ | Registers an observer for the message processing duration of the main thread. A callback will be invoked if a main thread jank event occurs. This API can be called only in the main thread. A new observer will overwrite the previous one. | | off(type: 'loopObserver', observer?: LoopObserver): void12+ | Unregisters the observer for message processing timeouts of the main thread. | +| on(type: 'freeze', observer: FreezeObserver): void18+ | Registers an observer for the main thread freeze event of the application. This API can be called only in the main thread. A new observer will overwrite the previous one. | +| off(type: 'freeze', observer?: FreezeObserver): void18+ | Unregisters an observer for the main thread freeze event of the application. This API can be called only in the main thread. | When an asynchronous callback is used, the return value can be processed directly in the callback. If a promise is used, the return value can also be processed in the promise in a similar way. For details about the result codes, see [Result Codes for Unregistering an Observer](#result-codes-for-unregistering-an-observer). @@ -250,3 +252,60 @@ export default class EntryAbility extends UIAbility { } }; ``` + +### Listening for Main Thread Freeze Exceptions + +```ts +import { AbilityConstant, errorManager, UIAbility, Want } from '@kit.AbilityKit'; +import { window } from '@kit.ArkUI'; +import process from '@ohos.process'; + +// Define freezeCallback +function freezeCallback() { + console.log("freezecallback"); +} + + +let abilityWant: Want; + +export default class EntryAbility extends UIAbility { + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { + console.log("[Demo] EntryAbility onCreate"); + errorManager.on("freeze", freezeCallback); + abilityWant = want; + } + + onDestroy() { + console.log("[Demo] EntryAbility onDestroy"); + errorManager.off("freeze", freezeCallback); + } + + onWindowStageCreate(windowStage: window.WindowStage) { + // Main window is created, set main page for this ability + console.log("[Demo] EntryAbility onWindowStageCreate"); + + windowStage.loadContent("pages/index", (err, data) => { + if (err.code) { + console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); + }); + } + + onWindowStageDestroy() { + // Main window is destroyed, release UI related resources + console.log("[Demo] EntryAbility onWindowStageDestroy"); + } + + onForeground() { + // Ability has brought to foreground + console.log("[Demo] EntryAbility onForeground"); + } + + onBackground() { + // Ability has back to background + console.log("[Demo] EntryAbility onBackground"); + } +}; +``` diff --git a/en/application-dev/dfx/hdc.md b/en/application-dev/dfx/hdc.md index 797a7f8a83922edffb44089ab1ee174468ac767e..1da120002618b766fb3d3749f6993e22afb35389 100644 --- a/en/application-dev/dfx/hdc.md +++ b/en/application-dev/dfx/hdc.md @@ -177,23 +177,23 @@ When multiple devices are connected, use the **-t** parameter to specify the tar ``` **Parameters** -| Name| Description| -| -------- | -------- | -| connect-key| Device ID, which is the return value of the **hdc list targets** command.| -| command | Command to be executed.| + | Name| Description| + | -------- | -------- | + | connect-key| Device ID, which is the return value of the **hdc list targets** command.| + | command | Command to be executed.| > **NOTE** > > The *connect-key* uniquely identifies a device. If the device is connected over the network, the *connect-key* is the IP address and port number. If the device is connected through USB, the *connect-key* is the USB SN. **Return value** -| Return Value| Description| -| -------- | -------- | -| Command output| Command execution result, which may vary with the command.| -| [Fail]Not match target founded, check connect-key please | No device matches the *connect-key*.| -| [Fail]Device not founded or connected | The device is not found or connected.| -| [Fail]ExecuteCommand need connect-key? please confirm a device by help info | You must specify one device if there are multiple devices available.| -| Unknown operation command... | The command is not supported.| + | Return Value| Description| + | -------- | -------- | + | Command output| Command execution result, which may vary with the command.| + | [Fail]Not match target founded, check connect-key please | No device matches the *connect-key*.| + | [Fail]Device not founded or connected | The device is not found or connected.| + | [Fail]ExecuteCommand need connect-key? please confirm a device by help info | You must specify one device if there are multiple devices available.| + | Unknown operation command... | The command is not supported.| > **NOTE** > @@ -218,9 +218,9 @@ Run the following commands: ``` **Return value** -| Return Value| Description| -| -------- | -------- | -| None| The **hdc wait** command ends when a properly connected device is identified.| + | Return Value| Description| + | -------- | -------- | + | None| The **hdc wait** command ends when a properly connected device is identified.| **Usage** @@ -461,29 +461,29 @@ You are advised to enable or disable the USB debugging and network debugging on ## Running the Interactive Command -The command format is as follows: +Run the following commands: ```shell hdc shell [-b bundlename] [command] ``` **Parameters** -| Parameter| Description| -| -------- | -------- | -| [-b _bundlename_] | The bundle name of a debug application. The command is executed in non-interactive mode in the data directory of the debug application.
Currently, this parameter can be used only in non-interactive mode, and the **command** parameter must be specified to enter an interactive shell session.
Otherwise, commands are executed in the system root directory by default.| -| [command] | A single command to execute on the device. The command varies depending on the system type or version. You can run the **hdc shell ls /system/bin** command to obtain the supported command list. Currently, many commands are provided by [toybox](../tools/toybox.md). You can run the **hdc shell toybox --help** command to obtain the help information.
If this parameter is not specified, hdc starts an interactive shell session, in which you can enter commands such as **ls**, **cd**, and **pwd** at the command prompt.| + | Parameter| Description| + | -------- | -------- | + | [-b _bundlename_] | The bundle name of a debug application. The command is executed in non-interactive mode in the data directory of the debug application.
Currently, this parameter can be used only in non-interactive mode, and the **command** parameter must be specified to enter an interactive shell session.
Otherwise, commands are executed in the system root directory by default.| + | [command] | A single command to execute on the device. The command varies depending on the system type or version. You can run the **hdc shell ls /system/bin** command to obtain the supported command list. Currently, many commands are provided by [toybox](../tools/toybox.md). You can run the **hdc shell toybox --help** command to obtain the help information.
If this parameter is not specified, hdc starts an interactive shell session, in which you can enter commands such as **ls**, **cd**, and **pwd** at the command prompt.| **Return value** -| Return Value| Description| -| -------- | -------- | -| Command execution result| Execution result of the command. For details, see the corresponding command output.| -| /bin/sh: XXX : inaccessible or not found | The specified command is not supported.| -| [Fail]Error information| The execution fails. For details, see [hdc Error Codes](#hdc-error-codes).| + | Return Value| Description| + | -------- | -------- | + | Command execution result| Execution result of the command. For details, see the corresponding command output.| + | /bin/sh: XXX : inaccessible or not found | The specified command is not supported.| + | [Fail]Error information| The execution fails. For details, see [hdc Error Codes](#hdc-error-codes).| **Usage** ```shell - # Enter the interactive mode to run a commands + # Enter the interactive mode to run a command. hdc shell # Run the command in non-interactive mode. @@ -799,7 +799,7 @@ Port forwarding type supported by the device: TCP, DEV, localabstract, localfile **Return value** | Return Value| Description| | -------- | -------- | - | Connect server failed | Fails to connect to the server.| + | Connect server failed | Fails to connect to the server.| **Usage** @@ -1055,7 +1055,7 @@ Port forwarding type supported by the device: TCP, DEV, localabstract, localfile ### Server Logs -#### Log level +#### Log Level Specify the hdc log level. The default value is **LOG_INFO**. @@ -1064,10 +1064,10 @@ Specify the hdc log level. The default value is **LOG_INFO**. ``` **Parameters** -| Parameter| Description| -| -------- | -------- | -| [level] | Log level.
0: LOG_OFF
1: LOG_FATAL
2: LOG_WARN
3: LOG_INFO
4: LOG_DEBUG
5: LOG_ALL
6: LOG_LIBUSB| -| command | Command to be executed.| + | Parameter| Description| + | -------- | -------- | + | [level] | Log level.
0: LOG_OFF
1: LOG_FATAL
2: LOG_WARN
3: LOG_INFO
4: LOG_DEBUG
5: LOG_ALL
6: LOG_LIBUSB| + | command | Command to be executed.| > **NOTE** > @@ -1075,10 +1075,10 @@ Specify the hdc log level. The default value is **LOG_INFO**. > 2. You can change only the log levels of the current client and server processes. **Return value** -| Return Value| Description| -| -------- | -------- | -| Command output| Command execution result, which may vary with the command.| -| Log information| Logs of the specified level.| + | Return Value| Description| + | -------- | -------- | + | Command output| Command execution result, which may vary with the command.| + | Log information| Logs of the specified level.| **Usage** @@ -1117,28 +1117,17 @@ hdc -l5 start The collected logs are stored in the following path. -| OS| Path
(Version 3.1.0c or later)| Path
(Versions earlier than 3.1.0c)| Remarks| -| -------- | -------- | -------- | -------- | -| Windows | %temp%\hdc_logs | %temp% | The following are examples. Replace *Username* with the actual one.
**C:\Users\Username\AppData\Local\Temp\hdc_logs** (Version 3.1.0c or later)
**C:\Users\Username\AppData\Local\Temp** (Versions earlier than 3.1.0c)| -| Linux | /tmp/hdc_logs | /tmp | - | -| macOS| $TMPDIR/hdc_logs | $TMPDIR | - | - -The hdc_logs folder contains the following types of logs: - -|Type| Name Format| Function| Remarks| -| -------- | -------- | -------- | -------- | -| Real-time log| hdc.log | Records hdc server logs in real time.| Each time the hdc server is restarted, the original log is renamed and a new **hdc.log** file is recorded.| -| Temporary historical log| hdc-%Y%m%d-%H%M%S.log | Dumps intermediate files generated during historical log archiving.| For example, **16:18:57.921 on September 19, 2024** is recorded as
**20240919-161857921**.
The temporary log file is stored in the format of **hdc-20240919-161857921.log**.| -| Archived historical logs| hdc-%Y%m%d-%H%M%S.log.tgz | Compresses and stores historical logs.| The archive file is a compressed file of the **.tgz** type. You can use a decompression tool to obtain the file.
For example, if the name of a temporary historical log file is **hdc-20240919-161857921.log**,
the name of the corresponding archived historical log file is **hdc-20240919-161857921.log.tgz**.
After an archived historical log file is generated, the corresponding temporary historical log file is automatically deleted.| -| Temporary real-time log| .hdc.cache.log | Records temporary caches generated by real-time logs.| | +| OS| Path| Remarks| +| -------- | -------- | -------- | +| Windows | %temp% | Example: **C:\Users\Username\AppData\Local\Temp**.
Replace *Username* with the actual one.| +| Linux | /tmp | - | +| macOS| $TMPDIR | - | Log-related environment variables | Environment Variable | Default Value| Description | |--------------------|-----|--------------------------------| | OHOS_HDC_LOG_LEVEL | 5 | The log level of the server process.
For details, see [Server Logs](#server-logs). | -| OHOS_HDC_LOG_LIMIT | 300 | The threshold of the number of log entries.
When the number of log entries exceeds the threshold,
the system automatically starts the log deletion mechanism
to optimize the log storage space.
In the current system, the upper limit of the log storage space is 3 GB,
which cannot be adjusted.| - Configure environment variables as follows: @@ -1156,8 +1145,8 @@ Enable HiLog to obtain the corresponding logs. ```shell hdc shell hilog -w start // Enable the function of storing HiLog logs. -hdc shell ls /data/log/hilog // View the stored HilLog logs. -hdc file recv /data/log/hilog // Obtain the stored HilLog logs (including kernel logs). +hdc shell ls /data/log/hilog // View the stored HiLog logs. +hdc file recv /data/log/hilog // Obtain the stored HiLog logs (including kernel logs). ``` ## FAQs @@ -1346,7 +1335,7 @@ The **hdc.exe**/hdc binary file cannot be executed using the CLI. 1. Run the **hdc list targets** command. 2. Check whether **HDC Device** exists in **Device Manager**. -3. Run the **hdc kill** command to terminate the server, and then run the **hdc -l5 start** command to collect logs. (The **hdc.log** file is stored in the **hdc_logs** folder of the **TEMP** directory on the execution end. The directory location varies with the OS. For details, see [Server Logs](#server-logs).) +3. Run the **hdc kill** command to terminate the server, and then run the **hdc -l5 start** command to collect logs. (The **hdc.log** file is stored in the **TEMP** directory on the execution end. The directory location varies with the OS. For details, see [Server Logs](#server-logs).) 4. Locate the problem based on the **hdc.log** file. ## hdc Error Codes diff --git a/en/application-dev/dfx/hiappevent-watcher-apphicollie-events-ndk.md b/en/application-dev/dfx/hiappevent-watcher-apphicollie-events-ndk.md new file mode 100644 index 0000000000000000000000000000000000000000..21ef34101463ed8e7c14fe9fe921d61cf923a33b --- /dev/null +++ b/en/application-dev/dfx/hiappevent-watcher-apphicollie-events-ndk.md @@ -0,0 +1,326 @@ +# Subscribing to Task execution timeout events (C/C++) + +## Available APIs + +For details about how to use the APIs (such as parameter usage restrictions and value ranges), see [HiAppEvent](../reference/apis-performance-analysis-kit/_hi_app_event.md#hiappevent). + +**Subscription APIs** + +| API | Description | +| ------------------------------------------------------------ | -------------------------------------------- | +| int OH_HiAppEvent_AddWatcher (HiAppEvent_Watcher *watcher) | Adds a watcher to listen for application events.| +| int OH_HiAppEvent_RemoveWatcher (HiAppEvent_Watcher *watcher) | Removes a watcher for the specified application events.| + +## How to Develop + +The following describes how to subscribe to the freeze event triggered by a button click. + +1. Create a native C++ project and import the **jsoncpp** file to the project. The directory structure is as follows: + + ```yml + entry: + src: + main: + cpp: + - json: + - json.h + - json-forwards.h + - types: + libentry: + - index.d.ts + - CMakeLists.txt + - napi_init.cpp + - jsoncpp.cpp + ets: + - entryability: + - EntryAbility.ets + - pages: + - Index.ets + ``` + +2. In the **CMakeLists.txt** file, add the source file and dynamic libraries. + + ```cmake + # Add the jsoncpp.cpp file, which is used to parse the JSON strings in the subscription events. + add_library(entry SHARED napi_init.cpp jsoncpp.cpp) + # Add libhiappevent_ndk.z.so, libhilog_ndk.z.so (log output), and libohhicollie.so (HiCollie detection). + target_link_libraries(entry PUBLIC libace_napi.z.so libhilog_ndk.z.so libohhicollie.so libhiappevent_ndk.z.so) + ``` + +3. Import the dependencies to the **napi_init.cpp** file, and define **LOG_TAG**. + + ```c++ + #include "napi/native_api.h" + #include "json/json.h" + #include "hilog/log.h" + #include "hiappevent/hiappevent.h" + + #undef LOG_TAG + #define LOG_TAG "testTag" + ``` + +4. Subscribe to system events. + + - Watcher of the onReceive type. + + In the **napi_init.cpp** file, define the methods related to the watcher of the **onReceive** type. + + ```c++ + // Define a variable to cache the pointer to the created watcher. + static HiAppEvent_Watcher *systemEventWatcher; + + static void OnReceive(const char *domain, const struct HiAppEvent_AppEventGroup *appEventGroups, uint32_t groupLen) { + for (int i = 0; i < groupLen; ++i) { + for (int j = 0; j < appEventGroups[i].infoLen; ++j) { + OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.domain=%{public}s", appEventGroups[i].appEventInfos[j].domain); + OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.name=%{public}s", appEventGroups[i].appEventInfos[j].name); + OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.eventType=%{public}d", appEventGroups[i].appEventInfos[j].type); + if (strcmp(appEventGroups[i].appEventInfos[j].domain, DOMAIN_OS) == 0 && + strcmp(appEventGroups[i].appEventInfos[j].name, EVENT_APP_HICOLLIE) == 0) { + Json::Value params; + Json::Reader reader(Json::Features::strictMode()); + Json::FastWriter writer; + if (reader.parse(appEventGroups[i].appEventInfos[j].params, params)) { + auto time = params["time"].asInt64(); + auto foreground = params["foreground"].asBool(); + auto bundleVersion = params["bundle_version"].asString(); + auto processName = params["process_name"].asString(); + auto pid = params["pid"].asInt(); + auto uid = params["uid"].asInt(); + auto uuid = params["uuid"].asString(); + auto exception = writer.write(params["exception"]); + auto hilogSize = params["hilog"].size(); + auto peerBindSize = params["peer_binder"].size(); + auto memory = writer.write(params["memory"]); + auto externalLog = writer.write(params["external_log"]); + auto logOverLimit = params["log_over_limit"].asBool(); + OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.time=%{public}lld", time); + OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.foreground=%{public}d", foreground); + OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.bundle_version=%{public}s", bundleVersion.c_str()); + OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.process_name=%{public}s", processName.c_str()); + OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.pid=%{public}d", pid); + OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.uid=%{public}d", uid); + OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.uuid=%{public}s", uuid.c_str()); + OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.exception=%{public}s", exception.c_str()); + OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.hilog.size=%{public}d", hilogSize); + OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.peer_binder.size=%{public}d", peerBindSize); + OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.memory=%{public}s", memory.c_str()); + OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.external_log=%{public}s", externalLog.c_str()); + OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.log_over_limit=%{public}d", logOverLimit); + } + } + } + } + } + + static napi_value RegisterWatcher(napi_env env, napi_callback_info info) { + // Set the watcher name. The system identifies different watchers based on their names. + systemEventWatcher = OH_HiAppEvent_CreateWatcher("onReceiverWatcher"); + // Set the event to watch to EVENT_APP_HICOLLIE. + const char *names[] = {EVENT_APP_HICOLLIE}; + // Add the events to watch, for example, system events. + OH_HiAppEvent_SetAppEventFilter(systemEventWatcher, DOMAIN_OS, 0, names, 1); + // Set the implemented callback. After receiving the event, the watcher immediately triggers the OnReceive callback. + OH_HiAppEvent_SetWatcherOnReceive(systemEventWatcher, OnReceive); + // Add a watcher to listen for the specified event. + OH_HiAppEvent_AddWatcher(systemEventWatcher); + return {}; + } + ``` + + - Watcher of the **onTrigger** type: + + In the **napi_init.cpp** file, define the methods related to the watcher of the **OnTrigger** type. + + ```c++ + // Define a variable to cache the pointer to the created watcher. + static HiAppEvent_Watcher *systemEventWatcher; + + // Implement the callback function used to return the listened events. The content pointed to by the events pointer is valid only in this function. + static void OnTake(const char *const *events, uint32_t eventLen) { + Json::Reader reader(Json::Features::strictMode()); + Json::FastWriter writer; + for (int i = 0; i < eventLen; ++i) { + Json::Value eventInfo; + if (reader.parse(events[i], eventInfo)) { + auto domain = eventInfo["domain_"].asString(); + auto name = eventInfo["name_"].asString(); + auto type = eventInfo["type_"].asInt(); + OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.domain=%{public}s", domain.c_str()); + OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.name=%{public}s", name.c_str()); + OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.eventType=%{public}d", type); + if (domain == DOMAIN_OS && name == EVENT_APP_HICOLLIE) { + auto time = eventInfo["time"].asInt64(); + auto foreground = eventInfo["foreground"].asBool(); + auto bundleVersion = eventInfo["bundle_version"].asString(); + auto processName = eventInfo["process_name"].asString(); + auto pid = eventInfo["pid"].asInt(); + auto uid = eventInfo["uid"].asInt(); + auto uuid = eventInfo["uuid"].asString(); + auto exception = writer.write(eventInfo["exception"]); + auto hilogSize = eventInfo["hilog"].size(); + auto peerBindSize = eventInfo["peer_binder"].size(); + auto memory = writer.write(eventInfo["memory"]); + auto externalLog = writer.write(eventInfo["external_log"]); + auto logOverLimit = eventInfo["log_over_limit"].asBool(); + OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.time=%{public}lld", time); + OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.foreground=%{public}d", foreground); + OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.bundle_version=%{public}s", bundleVersion.c_str()); + OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.process_name=%{public}s", processName.c_str()); + OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.pid=%{public}d", pid); + OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.uid=%{public}d", uid); + OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.uuid=%{public}s", uuid.c_str()); + OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.exception=%{public}s", exception.c_str()); + OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.hilog.size=%{public}d", hilogSize); + OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.peer_binder.size=%{public}d", peerBindSize); + OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.memory=%{public}s", memory.c_str()); + OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.external_log=%{public}s", externalLog.c_str()); + OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.log_over_limit=%{public}d", logOverLimit); + } + } + } + } + + // Implement the subscription callback function to apply custom processing to the obtained event logging data. + static void OnTrigger(int row, int size) { + // After the callback is received, obtain the specified number of received events. + OH_HiAppEvent_TakeWatcherData(systemEventWatcher, row, OnTake); + } + + static napi_value RegisterWatcher(napi_env env, napi_callback_info info) { + // Set the watcher name. The system identifies different watchers based on their names. + systemEventWatcher = OH_HiAppEvent_CreateWatcher("onTriggerWatcher"); + // Set the event to watch to EVENT_APP_HICOLLIE. + const char *names[] = {EVENT_APP_HICOLLIE}; + // Add the events to watch, for example, system events. + OH_HiAppEvent_SetAppEventFilter(systemEventWatcher, DOMAIN_OS, 0, names, 1); + // Set the implemented callback function. The callback function will be triggered when the conditions set by OH_HiAppEvent_SetTriggerCondition are met. + OH_HiAppEvent_SetWatcherOnTrigger(systemEventWatcher, OnTrigger); + // Set the conditions for triggering the subscription callback. For example, trigger this onTrigger callback when the number of new event logs is 1. + OH_HiAppEvent_SetTriggerCondition(systemEventWatcher, 1, 0, 0); + // Add a watcher to listen for the specified event. + OH_HiAppEvent_AddWatcher(systemEventWatcher); + return {}; + } + ``` + +5. Register **RegisterWatcher** as an ArkTS API. + + In the **napi_init.cpp** file, register **RegisterWatcher** as an ArkTS API. + + ```c++ + static napi_value Init(napi_env env, napi_value exports) + { + napi_property_descriptor desc[] = { + { "registerWatcher", nullptr, RegisterWatcher, nullptr, nullptr, nullptr, napi_default, nullptr }, + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); + return exports; + } + ``` + + In the **index.d.ts** file, define the ArkTS API. + + ```typescript + export const registerWatcher: () => void; + ``` + +6. Register **TestHiCollieTimerNdk** as an ArkTS API. + + In the **napi_init.cpp** file, register **testHiCollieTimerNdk** as an ArkTS API. + + ```c++ + static napi_value Init(napi_env env, napi_value exports) + { + napi_property_descriptor desc[] = { + { "registerWatcher", nullptr, RegisterWatcher, nullptr, nullptr, nullptr, napi_default, nullptr }, + { "testHiCollieTimerNdk", nullptr, TestHiCollieTimerNdk, nullptr, nullptr, nullptr, napi_default, nullptr }, + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); + return exports; + } + + // Import the hicollie.h file. + #include "hicollie/hicollie.h" + static napi_value TestHiCollieTimerNdk(napi_env env, napi_value exports) + { + // Define the task execution timeout ID. + int id; + // Define the task timeout detection parameters. When a task times out for 1s, logs are generated. + HiCollie_SetTimerParam param = {"testTimer", 1, nullptr, nullptr, HiCollie_Flag::HICOLLIE_FLAG_LOG}; + // Set the detection. + HiCollie_ErrorCode = OH_HiCollie_SetTimer(param, &id); + if (errorCode == HICOLLIE_SUCCESS) { + OH_LOG_INFO(LogType::LOG_APP, "Timer Id is %{public}d", id); + // Construct a timeout interval of 2s. + sleep(2); + OH_HiCollie_CancelTimer(id); + } + return 0; + } + ``` + +7. In the **EntryAbility.ets** file, add the following API to **onCreate()**. + + ```typescript + // Import the dependent module. + import testNapi from 'libentry.so' + + // Add the API to onCreate(). + // Register the system event watcher at startup. + testNapi.registerWatcher(); + ``` + +8. In the **Index.ets** file, add a button to trigger the task execution timeout event. + + ```typescript + Button("testHiCollieTimerNdk") + .fontSize(50) + .fontWeight(FontWeight.Bold) + .onClick(testNapi.testHiCollieTimerNdk); + ``` + +9. In DevEco Studio, click the **Run** button to run the project. Then, click the **testHiCollieTimerNdk** button to trigger a task execution timeout event. + +10. The application crashes. After restarting the application, you can view the following event information in the **Log** window. + + ```text + HiAppEvent eventInfo.domain=OS + HiAppEvent eventInfo.name=APP_HICOLLIE + HiAppEvent eventInfo.eventType=1 + HiAppEvent eventInfo.params.time=1740993639620 + HiAppEvent eventInfo.params.foreground=1 + HiAppEvent eventInfo.params.bundle_version=1.0.0 + HiAppEvent eventInfo.params.process_name=com.example.myapplication + HiAppEvent eventInfo.params.pid=26251 + HiAppEvent eventInfo.params.uid=20020172 + HiAppEvent eventInfo.params.uuid=4e5d7d0e18f5d6d84cf4f0c9e80d66d0b646c1cc2343d3595f07abb0d3547feb + HiAppEvent eventInfo.params.exception={"message":"","name":"APP_HICOLLIE"} + HiAppEvent eventInfo.params.hilog.size=77 + HiAppEvent eventInfo.params.peer_binder.size=18 + HiAppEvent eventInfo.params.threads.size=28 + HiAppEvent eventInfo.params.memory={"pss":0,"rss":124668,"sys_avail_mem":2220032,"sys_free_mem":526680,"sys_total_mem":11692576,"vss":4238700} + HiAppEvent eventInfo.params.external_log=["/data/storage/el2/log/hiappevent/APP_HICOLLIE_1740993644458_26215.log"] + HiAppEvent eventInfo.params.log_over_limit=0 + ``` + +11. Remove the event watcher. + + ```c++ + static napi_value RemoveWatcher(napi_env env, napi_callback_info info) { + // Remove the watcher. + OH_HiAppEvent_RemoveWatcher(systemEventWatcher); + return {}; + } + ``` + +12. Destroy the event watcher. + + ```c++ + static napi_value DestroyWatcher(napi_env env, napi_callback_info info) { + // Destroy the created watcher and set systemEventWatcher to nullptr. + OH_HiAppEvent_DestroyWatcher(systemEventWatcher); + systemEventWatcher = nullptr; + return {}; + } + ``` diff --git a/en/application-dev/dfx/hiappevent-watcher-apphicollie-events.md b/en/application-dev/dfx/hiappevent-watcher-apphicollie-events.md new file mode 100644 index 0000000000000000000000000000000000000000..70826f977ef29165937c1070d808831be492c7cd --- /dev/null +++ b/en/application-dev/dfx/hiappevent-watcher-apphicollie-events.md @@ -0,0 +1,43 @@ +# Task Execution Timeout Event Overview + +HiAppEvent provides APIs for subscribing to task execution timeout events. + +- [Subscribing to Task Execution Timeout Events (C/C++)](hiappevent-watcher-apphicollie-events-ndk.md) + +The **params** parameter in the event information is described as follows: + +**params** + +| Name | Type | Description | +| ------- | ------ | ------------------------- | +| time | number | Event triggering time, in ms.| +| foreground | boolean | Whether the application is running in the foreground.| +| bundle_version | string | Application version.| +| process_name | string | Process name of the application.| +| pid | number | Process ID of the application.| +| uid | number | User ID of the application.| +| uuid | string | Error ID.| +| exception | object | Exception information. For details, see **exception**.| +| hilog | string[] | Log information.| +| peer_binder | string[] | Binder call, binder call chain, and related stack capture information.| +| memory | object | Memory information. For details, see **memory**.| +| external_log | string[] | Path of the error log file. If the directory files exceed the threshold (for details, see **log_over_limit**), new log files may fail to be written. Therefore, delete the log files immediately after they are processed.| +| log_over_limit | boolean | Whether the size of generated fault log files and existing log files exceeds the upper limit (5 MB). The value **true** indicates that the upper limit is exceeded and logs fail to be written. The value **false** indicates that the upper limit is not exceeded.| + +**exception** + +| Name | Type | Description | +| ------- | ------ | ------------------------- | +| name | string | Exception type.| +| message | string | Exception cause.| + +**memory** + +| Name | Type | Description | +| ------- | ------ | ------------------------- | +| rss | number | Size of the memory allocated for a process, in KB.| +| vss | number | Size of the virtual memory applied by a process from the system, in KB.| +| pss | number | Size of the physical memory actually used by a process, in KB.| +| sys_free_mem | number | Size of free memory, in KB.| +| sys_avail_mem | number | Size of available memory, in KB.| +| sys_total_mem | number | Total memory size, in KB.| diff --git a/en/application-dev/dfx/hiappevent-watcher-crash-events-arkts.md b/en/application-dev/dfx/hiappevent-watcher-crash-events-arkts.md index 93c2b84d7a37debeb50ea796eb901e131a4d44e4..311252e471472db6459f798b61ba6fdfc47fc927 100644 --- a/en/application-dev/dfx/hiappevent-watcher-crash-events-arkts.md +++ b/en/application-dev/dfx/hiappevent-watcher-crash-events-arkts.md @@ -111,7 +111,10 @@ The following describes how to subscribe to a crash event triggered by a button 5. In DevEco Studio, click the **Run** button to run the project. Then, click the **appCrash** button to trigger a crash event. After a crash occurs, the system uses different stack backtracking methods to generate crash logs based on the crash type (JsError or NativeCrash) and then invokes callback. The NativeCrash stack backtracking takes about 2s. In practice, the duration depends on the number of service threads and the duration of inter-process communication. JsError triggers in-process stack backtracking, and NativeCrash triggers out-of-process stack backtracking. Therefore, NativeCrash stack backtracking is more time-consuming than JsError stack backtracking. You can subscribe to crash events so that the stack backtracking result is asynchronously reported without blocking the current service. -6. When the application is restarted, HiAppEvent reports the crash event to the registered watcher. You can view the following event information in the **Log** window. +6. If the application does not capture the crash event, the application exits after the system crashes. When the application is restarted, HiAppEvent reports the crash event to the registered watcher. +
If the application captures the crash event. HiAppEvent reports the event before the application exits in the following scenarios: +
  Scenario 1: The application does not exit during exception handling. For example, when [errorManger.on](../reference/apis-ability-kit/js-apis-app-ability-errorManager.md#errormanageronerror) is used to capture JsError, the application registers the NativeCrash signal processing function and does not exit.
  Scenario 2: Exception handling takes a long time, and the application exit time is delayed. +
After HiAppEvent reports the event, you can view the processing logs of the system event data in the **Log** window. ```text HiAppEvent onReceive: domain=OS diff --git a/en/application-dev/dfx/hiappevent-watcher-crash-events-ndk.md b/en/application-dev/dfx/hiappevent-watcher-crash-events-ndk.md index 3ef89f18ae499da6c93491d1d5f1db39b1a515f0..8a8bb8503e656efcb1dc61215272ea9cd45b71f8 100644 --- a/en/application-dev/dfx/hiappevent-watcher-crash-events-ndk.md +++ b/en/application-dev/dfx/hiappevent-watcher-crash-events-ndk.md @@ -246,7 +246,10 @@ The following describes how to subscribe to the crash event triggered by a butto 8. In DevEco Studio, click the **Run** button to run the project. Then, click the **appCrash** button to trigger a crash event. After a crash occurs, the system uses different stack backtracking methods to generate crash logs based on the crash type (JsError or NativeCrash) and then invokes callback. The NativeCrash stack backtracking takes about 2s. In practice, the duration depends on the number of service threads and the duration of inter-process communication. JsError triggers in-process stack backtracking, and NativeCrash triggers out-of-process stack backtracking. Therefore, NativeCrash stack backtracking is more time-consuming than JsError stack backtracking. You can subscribe to crash events so that the stack backtracking result is asynchronously reported without blocking the current service. -9. When the application is started next time, HiAppEvent reports the crash event to the registered watcher. You can view the processing logs of system event data in the **Log** window. +9. If the application does not capture the crash event, the application exits after the system crashes. When the application is restarted, HiAppEvent reports the crash event to the registered watcher. +
If the application captures the crash event. HiAppEvent reports the event before the application exits in the following scenarios: +
  Scenario 1: The application does not exit during exception handling. For example, when [errorManger.on](../reference/apis-ability-kit/js-apis-app-ability-errorManager.md#errormanageronerror) is used to capture JsError, the application registers the NativeCrash signal processing function and does not exit.
  Scenario 2: Exception handling takes a long time, and the application exit time is delayed. +
After HiAppEvent reports the event, you can view the processing logs of the system event data in the **Log** window. ```text HiAppEvent eventInfo.domain=OS diff --git a/en/application-dev/dfx/hiappevent-watcher-crash-events.md b/en/application-dev/dfx/hiappevent-watcher-crash-events.md index 1dc2f8a6aa53bf6e0e7d1889806e4be9f47d9313..c62b342ae44148550e929881ccf1b90214f2befd 100644 --- a/en/application-dev/dfx/hiappevent-watcher-crash-events.md +++ b/en/application-dev/dfx/hiappevent-watcher-crash-events.md @@ -47,9 +47,9 @@ The **params** parameter in the event information is described as follows. | Name | Type | Description | | ------- | ------ | ------------------------- | -| signo | number | Signal value (**si_signo** in **siginfo_t**)| -| code | number | Level-2 classification of signal values (**si_code** in **siginfo_t**)| -| address | string | Signal error address (**si_address** attribute in **siginfo_t**)| +| signo | number | Signal value (**si_signo** in **siginfo_t**).| +| code | number | Level-2 classification of signal values (**si_code** in **siginfo_t**).| +| address | string | Signal error address (**si_address** attribute in **siginfo_t**).| [Signal Value & Level-2 Classification of Signal Values](cppcrash-guidelines.md) diff --git a/en/application-dev/dfx/hiappevent-watcher-mainthreadjank-events-arkts.md b/en/application-dev/dfx/hiappevent-watcher-mainthreadjank-events-arkts.md index 4877cbbe4e9c31331ec609aa323fbc399369c69a..2f2a9f96eccffbb3609d18221aa062fd77102af1 100644 --- a/en/application-dev/dfx/hiappevent-watcher-mainthreadjank-events-arkts.md +++ b/en/application-dev/dfx/hiappevent-watcher-mainthreadjank-events-arkts.md @@ -148,7 +148,7 @@ The following describes how to subscribe to the main thread jank event in sampli // The number of event reporting times. "report_times_per_app": "3", }; - hiAppEvent.setEventConfig("MAIN_THREAD_JANK", params).then(() => { + hiAppEvent.setEventConfig(hiAppEvent.event.MAIN_THREAD_JANK, params).then(() => { hilog.info(0x0000, 'testTag', `HiAppEvent success to set event params.`) }).catch((err: BusinessError) => { hilog.error(0x0000, 'testTag', `HiAppEvent err.code: ${err.code}, err.message: ${err.message}`) diff --git a/en/application-dev/dfx/hiappevent-watcher-resourceleak-events-ndk.md b/en/application-dev/dfx/hiappevent-watcher-resourceleak-events-ndk.md index f7692264f694b44db67cd81cc9ae2a7b55575a6f..59812255573e2aef93324c4a15b237a430686979 100644 --- a/en/application-dev/dfx/hiappevent-watcher-resourceleak-events-ndk.md +++ b/en/application-dev/dfx/hiappevent-watcher-resourceleak-events-ndk.md @@ -123,6 +123,9 @@ For details about how to use the APIs (such as parameter usage restrictions and In the **napi_init.cpp** file, define the methods related to the watcher of the OnTrigger type. ```c++ + // Define a variable to cache the pointer to the created watcher. + static HiAppEvent_Watcher *systemEventWatcher; + // Implement the callback function used to return the listened events. The content pointed to by the events pointer is valid only in this function. static void OnTake(const char *const *events, uint32_t eventLen) { Json::Reader reader(Json::Features::strictMode()); diff --git a/en/application-dev/dfx/hichecker-guidelines-arkts.md b/en/application-dev/dfx/hichecker-guidelines-arkts.md index df2b9d048599d5aa3d8bb432230d831f664e9bf7..d9d5c3691deffb67f5a546ec419e94646acee67c 100644 --- a/en/application-dev/dfx/hichecker-guidelines-arkts.md +++ b/en/application-dev/dfx/hichecker-guidelines-arkts.md @@ -10,8 +10,7 @@ HiChecker is provided to check issues that may be easily ignored during applicat ## Working Principles -1. The application calls HiChecker APIs to add, remove, query, and modify rules. - +1. The application calls HiChecker APIs to add, remove, query, and modify rules. \n 2. When a time-consuming call or ability resource leakage occurs, HiChecker reports an event based on the rule triggered. ## Constraints diff --git a/en/application-dev/dfx/hicollie-guidelines-ndk.md b/en/application-dev/dfx/hicollie-guidelines-ndk.md index 8dae16baeeecb395cceeeb5a7bbee7a7f9838dd2..5643113881bcb058b6d11203eaeefbe091ac0dfc 100644 --- a/en/application-dev/dfx/hicollie-guidelines-ndk.md +++ b/en/application-dev/dfx/hicollie-guidelines-ndk.md @@ -1,27 +1,29 @@ # Using HiCollie to Detect Service Thread Stuck and Jank Events (C/C++) +## Overview + HiCollie provides APIs for detecting service thread stuck and jank events and reporting stuck events. ## Availability APIs + | API | Description | | ------------------------------- | --------------------------------- | | OH_HiCollie_Init_StuckDetection | Registers a callback to periodically detect service thread stuck events. | -| OH_HiCollie_Init_JankDetection | Registers a callback to detect service thread jank events. To monitor thread jank events, you should implement two callbacks as instrumentation functions, placing them before and after the service thread processing event. | +| OH_HiCollie_Init_StuckDetectionWithTimeout | Registers a callback to periodically detect service thread stuck events. You can set the detection time.| +| OH_HiCollie_Init_JankDetection | Registers a callback to detect service thread jank events. To monitor service thread jank events, you can implement two callbacks as instrumentation functions, placing them before and after the service thread event. | | OH_HiCollie_Report | Reports service thread stuck events and generates timeout logs to help locate application timeout events. This API is used together with **OH_HiCollie_Init_StuckDetection()**, which initializes the stuck event detection at first, and then **OH_HiCollie_Report()** reports the stuck event when it occurs.| -> **NOTE** -> -> The service thread stuck faultlog starts with **appfreeze-** and is generated in **Device/data/log/faultlog/faultlogger/**. The log files are named in the format of **appfreeze-application bundle name-application UID-time (seconds)**. For details, see [appfreeze Log Analysis](./appfreeze-guidelines.md#appfreeze-log-analysis). -> -> For details about the specifications of service thread jank event logs, see [Main Thread Jank Event Specifications](./hiappevent-watcher-mainthreadjank-events.md#main-thread-jank-event-specifications). +The usage of HiCollie: - -For details (such as parameter usage and value ranges), see [HiCollie](../reference/apis-performance-analysis-kit/_hi_hicollie.md). +- For details (such as parameter usage and value ranges), see [HiCollie](../reference/apis-performance-analysis-kit/_hi_collie.md). +- The service thread stuck faultlog starts with **appfreeze-** and is generated in **Device/data/log/faultlog/faultlogger/**. The log files are named in the format of **appfreeze-application bundle name-application UID-time (seconds)**. For details, see [appfreeze Log Analysis](./appfreeze-guidelines.md#appfreeze-log-analysis). +- For details about the specifications of service thread jank event logs, see [Main Thread Jank Event Specifications](./hiappevent-watcher-mainthreadjank-events.md#main-thread-jank-event-specifications). ## How to Develop + The following describes how to add a button in the application and click the button to call the HiCollie APIs. -1. Create a native C++ project and import the **jsoncpp** file to the project. The directory structure is as follows: +1. Create a native C++ project. The directory structure is as follows: ```yml entry: @@ -47,169 +49,402 @@ The following describes how to add a button in the application and click the but target_link_libraries(entry PUBLIC libace_napi.z.so libhilog_ndk.z.so libohhicollie.so) ``` -3. Import the dependencies to the **napi_init.cpp** file, and define **LOG_TAG** and the test method. - - ```c++ - #include "napi/native_api.h" - #include "hilog/log.h" - #include "hicollie/hicollie.h" - #include - #include - #include - #include - - #undef LOG_TAG - #define LOG_TAG "testTag" - - static OH_HiCollie_BeginFunc beginFunc_; // Define the callback object used before the processing event. - static OH_HiCollie_EndFunc endFunc_; // Define the callback object used after the processing event. - HiCollie_DetectionParam param {.sampleStackTriggerTime = 150, .reserved = 0}; // Define a struct. - int64_t lastWatchTime = 0; // Record the last detection time. - const int64_t CHECK_INTERNAL_TIME = 3000; // Set the detection interval. - std::shared_ptr> isReport = std::make_shared>(false); // Set the flag for reporting stuck events. - int count = 0; // Record the first initialization. - bool needReport = false; // Set whether to report the stuck events. - - // Define the callback. - void InitBeginFunc(const char* eventName) - { - std::string str(eventName); - OH_LOG_INFO(LogType::LOG_APP, "InitBeginFunc eventName: %{public}s", str.c_str()); - } - void InitEndFunc(const char* eventName) - { - std::string str(eventName); - OH_LOG_INFO(LogType::LOG_APP, "OH_HiCollie_EndFunc eventName: %{public}s", str.c_str()); - } - // Define the callback of the subthread. - void TestJankDetection() - { - beginFunc_ = InitBeginFunc; // Initialize the callback. - endFunc_ = InitEndFunc; - int initResult = OH_HiCollie_Init_JankDetection(&beginFunc_, &endFunc_, param); // Initialize the function for detecting thread jank events. - OH_LOG_INFO(LogType::LOG_APP, "OH_HiCollie_Init_JankDetection: %{public}d", initResult); // Display the success result 0. - int count = 0; - while (count < 2) { - beginFunc_("TestBegin"); // Set the callback used to record the start time of the processing event. - usleep(350 * 1000); // Simulate a thread jank event by putting the thread to sleep for 350 ms. - endFunc_("TestEnd"); // Set the callback used to record the end time of the processing event. - count++; - } - } +3. Import the dependencies to the **napi_init.cpp** file, and define **LOG_TAG**. The following code steps are used to simulate the jank and stuck scenarios. Use the code based on service requirements. The sample code is as follows: - static napi_value TestHiCollieJankNdk(napi_env env, napi_callback_info info) - { - std::thread threadObj(TestJankDetection); // Create a subthread. - threadObj.join(); // Execute the callback. - return 0; - } + (1) **OH_HiCollie_Init_JankDetection**: - int64_t GetCurrentTime() - { - return std::chrono::duration_cast(std::chrono:: - system_clock::now().time_since_epoch()).count(); - } + ```c++ + #include + #include + #include + #include + #include "napi/native_api.h" + #include "hilog/log.h" + #include "hicollie/hicollie.h" + + #undef LOG_TAG + #define LOG_TAG "JankTest" + + //Define two callback objects. + static OH_HiCollie_BeginFunc beginFunc_; + static OH_HiCollie_EndFunc endFunc_; + + //Define the callbacks for monitoring application display start and end. + void InitBeginFunc(const char* eventName) + { + std::string str(eventName); + OH_LOG_INFO(LogType::LOG_APP, "InitBeginFunc eventName: %{public}s", str.c_str()); + } + void InitEndFunc(const char* eventName) + { + std::string str(eventName); + OH_LOG_INFO(LogType::LOG_APP, "OH_HiCollie_EndFunc eventName: %{public}s", str.c_str()); + } - bool ReportEvent() - { - if ((GetCurrentTime() - lastWatchTime) > CHECK_INTERNAL_TIME) { - return true; + void StartDelayTimer() + { + //Wait for 10s. + std::chrono::seconds delay(10); + OH_LOG_INFO(LogType::LOG_APP, "OH_HiCollie_Init_JankDetection delay before"); + std::this_thread::sleep_for(delay); + OH_LOG_INFO(LogType::LOG_APP, "OH_HiCollie_Init_JankDetection delay after"); + } + + // Define the callback of the subthread. + void TestJankDetection() + { + // Initialize the callback parameters. + beginFunc_ = InitBeginFunc; + endFunc_ = InitEndFunc; + HiCollie_DetectionParam param {0}; + // Initialize the thread jank detection function. + int initResult = OH_HiCollie_Init_JankDetection(&beginFunc_, &endFunc_, param); + // Set the thread to be not detected within 10s after being started. + StartDelayTimer(); + // Success result: 0 + OH_LOG_INFO(LogType::LOG_APP, "OH_HiCollie_Init_JankDetection: %{public}d", initResult); + int count = 0; + while (count < 3) { + // Set the callback used to record the start time of the processing event. + beginFunc_("TestBegin"); + // Simulate a thread jank event by putting the thread to sleep for 350 ms. + usleep(350 * 1000); + // Set the callback used to record the end time of the processing event. + endFunc_("TestEnd"); + count++; } - return false; + } + + static napi_value TestHiCollieJankNdk(napi_env env, napi_callback_info info) + { + // Create a subthread. + std::thread threadObj(TestJankDetection); + // Execute the TestJankDetection task. + threadObj.detach(); + return 0; + } + + EXTERN_C_START + static napi_value Init(napi_env env, napi_value exports) + { + napi_property_descriptor desc[] = { + { "testHiCollieJankNdk", nullptr, TestHiCollieJankNdk, nullptr, nullptr, nullptr, napi_default, nullptr }, + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); + return exports; + } + EXTERN_C_END + + static napi_module demoModule = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = Init, + .nm_modname = "entry", + .nm_priv = ((void*)0), + .reserved = { 0 }, + }; + + extern "C" __attribute__((constructor)) void RegisterEntryModule(void) + { + napi_module_register(&demoModule); + } + ``` + + (2) **OH_HiCollie_Init_StuckDetection**: + + ```c++ + #include "napi/native_api.h" + #include "hilog/log.h" + #include "hicollie/hicollie.h" + #include + #include + #include + + #undef LOG_TAG + #define LOG_TAG "StruckTest" + + // Check whether the thread is running properly. The value 1 indicates that the thread is running properly, and the value 0 indicates that the thread is stuck. + const int64_t CHECK_BUSSINESS_THREAD_IS_ALIVE = 1; + // Simulate a thread stuck event by putting the thread to sleep for a custom time. + const int64_t BLOCK_TIME = 3; + // Set the task execution status flag of the application thread. The value true indicates the thread is normal and the value false indicates the thread is stuck. + std::shared_ptr> appThreadIsAlive_ = std::make_shared>(true); + // Set the flag for reporting the application thread stuck event. + std::shared_ptr> isSixSecondEvent_ = std::make_shared>(false); + + void ReportEvent() { + bool temp = isSixSecondEvent_->load(); + int reportResult = OH_HiCollie_Report(&temp); + // Success result: 0 + OH_LOG_INFO(LogType::LOG_APP, "OH_HiCollie_Report: %{public}d, isSixSecondEvent: %{public}d", reportResult, isSixSecondEvent_->load()); + isSixSecondEvent_->store(temp); + } + + void SetTimeout() + { + int64_t now = std::chrono::duration_cast(std::chrono:: + system_clock::now().time_since_epoch()).count(); + sleep(BLOCK_TIME); + int64_t currentTime = std::chrono::duration_cast(std::chrono:: + system_clock::now().time_since_epoch()).count(); + if (currentTime - now < BLOCK_TIME) { + appThreadIsAlive_->store(true); + return; } + appThreadIsAlive_->store(false); + } - void TestTask() - { - if (needReport && ReportEvent()) { - bool temp = isReport->load(); - int reportResult = OH_HiCollie_Report(&temp); - OH_LOG_INFO(LogType::LOG_APP, "OH_HiCollie_Report: %{public}d", reportResult); // Display the success result 0. - OH_LOG_INFO(LogType::LOG_APP, "OH_HiCollie_Report isReport: %{public}d", temp); - needReport = false; - } - int64_t now = GetCurrentTime(); - if ((now - lastWatchTime) >= (CHECK_INTERNAL_TIME / 2)) { - lastWatchTime = now; - } + // You can customize periodic detection tasks. + void Timer() + { + // Check whether the application thread runs properly every 3 seconds. + if (appThreadIsAlive_->load()) { + OH_LOG_INFO(LogType::LOG_APP, "Check appThread isAlive."); + // Update appThreadIsAlive_. The value true indicates that the application thread runs properly. + appThreadIsAlive_->store(false); + // Simulate a timeout scenario. + SetTimeout(); + return; } + ReportEvent(); + } - // Define the callback of the subthread. - void TestStuckDetection() - { - int initResult = -1; - if(count == 0) { - initResult = OH_HiCollie_Init_StuckDetection(TestTask); // Initialize the function for detecting thread stuck events. - OH_LOG_INFO(LogType::LOG_APP, "OH_HiCollie_Init_StuckDetection: %{public}d", initResult); // Display the success result 0. - count++; - } + // Define the callback of the subthread. + void InitStuckDetection() + { + // Initialize the thread stuck detection function. + int initResult = OH_HiCollie_Init_StuckDetection(Timer); + // Success result: 0 + OH_LOG_INFO(LogType::LOG_APP, "OH_HiCollie_Init_StuckDetection: %{public}d", initResult); + } + + static napi_value TestHiCollieStuckNdk(napi_env env, napi_callback_info info) + { + // Create a subthread. + std::thread threadObj(InitStuckDetection); + // Execute a task. + threadObj.join(); + return 0; + } + + EXTERN_C_START + static napi_value Init(napi_env env, napi_value exports) + { + napi_property_descriptor desc[] = { + { "testHiCollieStuckNdk", nullptr, TestHiCollieStuckNdk, nullptr, nullptr, nullptr, napi_default, nullptr }, + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); + return exports; + } + EXTERN_C_END + + static napi_module demoModule = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = Init, + .nm_modname = "entry", + .nm_priv = ((void*)0), + .reserved = { 0 }, + }; + + extern "C" __attribute__((constructor)) void RegisterEntryModule(void) + { + napi_module_register(&demoModule); + } + ``` + + (3) **OH_HiCollie_Init_StuckDetectionWithTimeout**: + + ```c++ + #include "napi/native_api.h" + #include "hilog/log.h" + #include "hicollie/hicollie.h" + #include + #include + #include + + #undef LOG_TAG + #define LOG_TAG "StruckTest" + + // Check whether the thread is running properly. The value 1 indicates that the thread is running properly, and the value 0 indicates that the thread is stuck. + const int64_t CHECK_BUSSINESS_THREAD_IS_ALIVE = 1; + // Simulate a thread stuck event by putting the thread to sleep for a custom time. + const int64_t BLOCK_TIME = 5; + // Set the task execution status flag of the application thread. The value true indicates the thread is normal and the value false indicates the thread is stuck. + std::shared_ptr> appThreadIsAlive_ = std::make_shared>(true); + // Set the flag for reporting the application thread stuck event. + std::shared_ptr> isSixSecondEvent_ = std::make_shared>(false); + + void ReportEvent() { + bool temp = isSixSecondEvent_->load(); + int reportResult = OH_HiCollie_Report(&temp); + // Success result: 0 + OH_LOG_INFO(LogType::LOG_APP, "OH_HiCollie_Report: %{public}d, isSixSecondEvent: %{public}d", reportResult, isSixSecondEvent_->load()); + isSixSecondEvent_->store(temp); + } + + void SetTimeout() + { + int64_t now = std::chrono::duration_cast(std::chrono:: + system_clock::now().time_since_epoch()).count(); + sleep(BLOCK_TIME); + int64_t currentTime = std::chrono::duration_cast(std::chrono:: + system_clock::now().time_since_epoch()).count(); + if (currentTime - now < BLOCK_TIME) { + appThreadIsAlive_->store(true); + return; } - static napi_value TestHiCollieStuckNdk(napi_env env, napi_callback_info info) - { - std::thread threadObj(TestStuckDetection); // Create a subthread. - threadObj.join(); // Execute the callback. - return 0; + appThreadIsAlive_->store(false); + } + + // You can customize periodic detection tasks. + void Timer() + { + // Check whether the application thread runs properly every 5 seconds. + if (appThreadIsAlive_->load()) { + OH_LOG_INFO(LogType::LOG_APP, "Check appThread isAlive."); + // Update appThreadIsAlive_. The value true indicates that the application thread runs properly. + appThreadIsAlive_->store(false); + // Simulate a timeout scenario. + SetTimeout(); + return; } - ``` + ReportEvent(); + } + + // Define the callback of the subthread. + void InitStuckDetectionWithTimeout() + { + // Initialize the thread stuck detection function. + int initResult = OH_HiCollie_Init_StuckDetectionWithTimeout(Timer, BLOCK_TIME); + // Success result: 0 + OH_LOG_INFO(LogType::LOG_APP, "OH_HiCollie_Init_StuckDetection: %{public}d", initResult); + } + + static napi_value TestHiCollieStuckWithTimeoutNdk(napi_env env, napi_callback_info info) + { + // Create a subthread. + std::thread threadObj(InitStuckDetectionWithTimeout); + // Execute a task. + threadObj.join(); + return 0; + } + + EXTERN_C_START + static napi_value Init(napi_env env, napi_value exports) + { + napi_property_descriptor desc[] = { + { "testHiCollieStuckWithTimeoutNdk", nullptr, TestHiCollieStuckWithTimeoutNdk, nullptr, nullptr, nullptr, napi_default, nullptr }, + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); + return exports; + } + EXTERN_C_END + + static napi_module demoModule = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = Init, + .nm_modname = "entry", + .nm_priv = ((void*)0), + .reserved = { 0 }, + }; + + extern "C" __attribute__((constructor)) void RegisterEntryModule(void) + { + napi_module_register(&demoModule); + } + ``` 4. Register **TestHiCollieNdk** as an ArkTS API. - In the **napi_init.cpp** file, register **TestHiCollieNdk** as an ArkTS API. - - ```c++ - static napi_value Init(napi_env env, napi_value exports) - { - napi_property_descriptor desc[] = { - { "testHiCollieJankNdk", nullptr, TestHiCollieJankNdk, nullptr, nullptr, nullptr, napi_default, nullptr }, - { "testHiCollieStuckNdk", nullptr, TestHiCollieStuckNdk, nullptr, nullptr, nullptr, napi_default, nullptr }}; - }; - napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); - return exports; - } - ``` + (1) **OH_HiCollie_Init_JankDetection**: - In the **index.d.ts** file, define the ArkTS API. + ```typescript + export const testHiCollieJankNdk: () => void; + ``` - ```typescript - export const testHiCollieJankNdk: () => void; - export const testHiCollieStuckNdk: () => void; - ``` + (2) **OH_HiCollie_Init_StuckDetection**: + + ```typescript + export const testHiCollieStuckNdk: () => void; + ``` + + (3) **OH_HiCollie_Init_StuckDetectionWithTimeout**: + + ```typescript + export const testHiCollieStuckWithTimeoutNdk: () => void; + ``` 5. Edit the **Index.ets** file. - ```ts - import testNapi from 'libentry.so' - - @Entry - @Component - struct Index { - @State message: string = 'Hello World' - - build() { - Row() { - Column() { - Button("testHiCollieJankNdk") - .fontSize(50) - .fontWeight(FontWeight.Bold) - .onClick(testNapi.testHiCollieJankNdk);// Add a click event to trigger testHiCollieJankNdk(). - Button("testHiCollieStuckNdk") - .fontSize(50) - .fontWeight(FontWeight.Bold) - .onClick(testNapi.testHiCollieStuckNdk);// Add a click event to trigger testHiCollieStuckNdk(). - } - .width('100%') - } - .height('100%') - } - } - ``` + ```ts + import testNapi from 'libentry.so' + + @Entry + @Component + struct Index { + build() { + RelativeContainer() { + Column() { + //Add the click event corresponding to the detection. + + }.width('100%') + } + .height('100%') + .width('100%') + } + } + ``` + + (1) Add a click event to trigger **OH_HiCollie_Init_JankDetection()**. + + ```ts + Button("testHiCollieJankNdk", { stateEffect:true, type: ButtonType.Capsule}) + .width('75%') + .height(50) + .margin(15) + .fontSize(20) + .fontWeight(FontWeight.Bold) + .onClick(testNapi.testHiCollieJankNdk); + ``` + + (2) Add a click event to trigger **OH_HiCollie_Init_StuckDetection()**. + + ```ts + Button("testHiCollieStuckNdk", { stateEffect:true, type: ButtonType.Capsule}) + .width('75%') + .height(50) + .margin(15) + .fontSize(20) + .fontWeight(FontWeight.Bold) + .onClick(testNapi.testHiCollieStuckNdk); + ``` + + (3) Add a click event to trigger **OH_HiCollie_Init_StuckDetectionWithTimeout()**. + + ```ts + Button("testHiCollieStuckWithTimeoutNdk", { stateEffect:true, type: ButtonType.Capsule}) + .width('75%') + .height(50) + .margin(15) + .fontSize(20) + .fontWeight(FontWeight.Bold) + .onClick(testNapi.testHiCollieStuckWithTimeoutNdk); + ``` 6. Click the **Run** button in DevEco Studio to run the project. -7. At the bottom of DevEco Studio, switch to the **Log** tab and set the filter criteria to **testTag**. +7. At the bottom of DevEco Studio, switch to the **Log** tab and filter the custom **LOG_TAG**. + + (1) Wait for 10s and click the **testHiCollieJankNdk** button. (The jank event detection is not performed within 10s after the thread starts.) + The thread timeout information of the sampling stack obtained through **OH_HiCollie_Init_JankDetection()** is displayed. You can obtain the corresponding event by [subscribing to the main thread timeout event](./hiappevent-watcher-mainthreadjank-events-arkts.md). - (1) Wait for 10s and click the **testHiCollieJankNdk** button. (The jank event detection is not performed within 10s after the thread starts.) - The thread timeout information of the sampling stack obtained through **OH_HiCollie_Init_JankDetection()** is displayed - in **/data/app/el2/100/log/application bundle name/watchdog/BUSSINESS_THREAD_JANK_XXX.txt.** + (2) Click the **testHiCollieStuckNdk** button. + The callback used for detecting stuck events is initialized through **OH_HiCollie_Init_StuckDetection()**. You can define the detection function for stuck events as required. - (2) Click the **testHiCollieStuckNdk** button. - The callback used for detecting stuck events is initialized through **OH_HiCollie_Init_StuckDetection()**. You can define the detection function for stuck events as required. + (3) Click the **testHiCollieStuckWithTimeoutNdk** button. + The callback used for detecting stuck events is initialized through **OH_HiCollie_Init_StuckDetectionWithTimeout**. You can define the detection function and time for stuck events as required. diff --git a/en/application-dev/dfx/hicollie-settimer-guidelines-ndk.md b/en/application-dev/dfx/hicollie-settimer-guidelines-ndk.md index ed2a5bb05b0725f9c8f27d1d25f02ea866042f4e..ab973d30eeafc1a4d77d6ad50fd5b8e755a2b854 100644 --- a/en/application-dev/dfx/hicollie-settimer-guidelines-ndk.md +++ b/en/application-dev/dfx/hicollie-settimer-guidelines-ndk.md @@ -3,6 +3,7 @@ HiCollie provides APIs for detecting the function execution timeout events. ## Available APIs + | API | Description | | ------------------------------ | --------------------------------- | | OH_HiCollie_SetTimer | Enables a timer for checking the function execution duration. Use this function before calling a time-consuming function or code block. | @@ -10,12 +11,14 @@ HiCollie provides APIs for detecting the function execution timeout events. > **NOTE** > -> You can obtain the function execution timeout logs in the following paths: 1. The **APP_HICOLLIE-*process ID*-*time*.log** file in **device/data/log/eventlog/**. 2. The **syswarning-*bundle name*-*application UID*-*second-level time*** file in **device/data/log/faultlog/faultlogger/**. - +> You can obtain the function execution timeout log in the following paths: +> 1. The **APP_HICOLLIE-*process ID*-*time*.log** file in **device/data/log/eventlog/**. +> 2. 2. The **syswarning-*bundle name*-*application UID*-*second-level time*** file in **device/data/log/faultlog/faultlogger/**. -For details (such as parameter usage and value ranges), see [HiCollie](../reference/apis-performance-analysis-kit/_hi_hicollie.md). +For details (such as parameter usage and value ranges), see [HiCollie](../reference/apis-performance-analysis-kit/_hi_collie.md). ## How to Develop + The following describes how to add a button in the application and click the button to call the HiCollie APIs. 1. Create a native C++ project. The directory structure is as follows: @@ -128,5 +131,8 @@ The following describes how to add a button in the application and click the but 6. Click the **Run** button in DevEco Studio to run the project. -7. At the bottom of DevEco Studio, switch to the **Log** tab and set the filter criteria to **testTag**. Click the **testHiCollieTimerNdk** button to execute the program. In the log window, the task ID is displayed. After 2 seconds, the callback content is displayed. +7. At the bottom of DevEco Studio, switch to the **Log** tab and set the filter criteria to **testTag**. + + Click the **testHiCollieTimerNdk** button to execute the program. In the log window, the task ID is displayed. After 2 seconds, the callback content is displayed. + The timeout logs are stored in: **data/log/eventlog/APP_HICOLLIE-*process ID*-*time*.log** and **syswarning-*bundle name*-*application UID*-*second-level time***. diff --git a/en/application-dev/dfx/hidebug-guidelines-arkts.md b/en/application-dev/dfx/hidebug-guidelines-arkts.md index 55a800e7e326e670f93a337e4f914a2cc8e35f48..0c808e9a6536cf191081da24f26c72c25cc3b65b 100644 --- a/en/application-dev/dfx/hidebug-guidelines-arkts.md +++ b/en/application-dev/dfx/hidebug-guidelines-arkts.md @@ -14,6 +14,7 @@ HiDebug provides APIs for system debugging, which allow you to obtain the inform | hidebug.getSharedDirty | Obtains the size of the shared dirty memory of a process. | | hidebug.getPrivateDirty | Obtains the size of the private dirty memory of a process. | | hidebug.getCpuUsage | Obtains the CPU usage of a process. | +| hidebug.getServiceDump | Obtains system service information. | | hidebug.dumpJsHeapData | Exports the heap data. | | hidebug.startJsCpuProfiling | Starts the VM profiling method. | | hidebug.stopJsCpuProfiling | Stops the VM profiling method. | @@ -28,8 +29,10 @@ HiDebug provides APIs for system debugging, which allow you to obtain the inform | hidebug.getSystemMemInfo | Obtains system memory information. | | hidebug.getVMRuntimeStats | Obtains all system GC statistics. | | hidebug.getVMRuntimeStat | Obtains the specified system GC statistics based on parameters. | +| hidebug.isDebugState | Obtains the debugging state of an application process. | | hidebug.getGraphicsMemory | Obtains the size of the GPU memory asynchronously. | | hidebug.getGraphicsMemorySync | Obtains the size of the GPU memory synchronously. | +| hidebug.dumpJsRawHeapData | Dumps the original heap snapshot of the VM for the calling thread. | For details about how to use HiDebug, see the API Reference (../reference/apis-performance-analysis-kit/js-apis-hidebug.md). @@ -83,6 +86,7 @@ The following describes how to add a button in the application and click the but 4. Run the project on a real device and click "Hello World" on the app/service. 5. At the bottom of DevEco Studio, switch to the **Log** tab and set the filter criteria to **testTag**. + Then, the CPU usage logs obtained using **hidebug.getSystemCpuUsage()** are displayed in the window. ```Text 08-20 11:06:01.891 1948-1948 A03d00/JSAPP com.examp...lication I getSystemCpuUsage: 0.4722222222222222 diff --git a/en/application-dev/dfx/hilog-guidelines-arkts.md b/en/application-dev/dfx/hilog-guidelines-arkts.md index 0656b47bd3e9c328822236692ad9fa51cb683544..323bf661db351c582393e759ffd93067d62e1740 100644 --- a/en/application-dev/dfx/hilog-guidelines-arkts.md +++ b/en/application-dev/dfx/hilog-guidelines-arkts.md @@ -115,7 +115,7 @@ Add a click event in a button, which prints a log when the button is clicked. ```txt '%{public}s World %{public}d' ``` - *%{public}s* indicates a string, and *%{public}d* indicates an integer. Both of them are displayed in plaintext. + *%{public}s* indicates a string, and *%{public}d* indicates an integer. Both of them are displayed in plaintext. 4. Run the project on a real device, and click the **Next** button on the app/service. diff --git a/en/application-dev/dfx/hilog-guidelines-ndk.md b/en/application-dev/dfx/hilog-guidelines-ndk.md index e0f744f51a4c3b7222b4ef4c1430ef9be5425b74..f76efe8bad934202eb073382b6d7b60ab38614a7 100644 --- a/en/application-dev/dfx/hilog-guidelines-ndk.md +++ b/en/application-dev/dfx/hilog-guidelines-ndk.md @@ -118,7 +118,7 @@ static void Test(void) // 1. Register a callback. OH_LOG_SetCallback(MyHiLog); - // 2. Call the hilog API to print logs. Logs are output to HiLog and returned to **MyHiLog()** through the registered callback. Then, **MyHiLog()** is called to process the logs. + // 2. Call the hilog API to print logs. Logs are output to HiLog and returned to MyHiLog() through the registered callback. Then, MyHiLog() is called to process the logs. HiLog::Info(LABEL, "hello world"); } ``` diff --git a/en/application-dev/dfx/hilog.md b/en/application-dev/dfx/hilog.md index a5eff8d7f8936d4ae419cad83b3b239ded319953..d9fe8433d3a67afb206272cfe3a8689774e7111f 100644 --- a/en/application-dev/dfx/hilog.md +++ b/en/application-dev/dfx/hilog.md @@ -15,21 +15,21 @@ HiLog is a log system that provides logging for the system framework, services, | Short Option| Long Option| Parameter| Description| | -------- | -------- | -------- | -------- | -| -h | --help | | Shows help information.| -| Default| Default| | Performs a blocking read on logs, with no exiting after the read finishes.| -| -x | --exit | | Performs a non-blocking read on logs, with exiting after the read finishes.| -| -g | | | Checks the buffer size for logs of a specified type. This option is used together with **-t**, which specifies a log type. By default, the **app** or **core** types are used.| +| -h | --help | - | Shows help information.| +| Default| Default| - | Performs a blocking read on logs, with no exiting after the read finishes.| +| -x | --exit | - | Performs a non-blocking read on logs, with exiting after the read finishes.| +| -g | - | - | Checks the buffer size for logs of a specified type. This option is used together with **-t**, which specifies a log type. By default, the **app** or **core** types are used.| | -G | --buffer-size | <size> | Sets the size of the buffer for logs of a specified type. This option is used together with **-t**, which specifies a log type. By default, the **app** or **core** types are used. The unit can be B, KB, MB, or GB. The value ranges from 64 KB to 16 MB.| -| -r | | | Clears the buffer for logs of a specified type. This option is used together with **-t**, which specifies a log type. By default, the **app** or **core** types are used.| +| -r | - | - | Clears the buffer for logs of a specified type. This option is used together with **-t**, which specifies a log type. By default, the **app** or **core** types are used.| | -p | --privacy | <on/off> | Specifies whether to enable privacy for logs during system debugging.| | | | on | Enables privacy so that parameters are displayed as **\** in printed logs.| | | | off | Disables privacy so that parameters are displayed as they are in printed logs.| -| -k | | <on/off> | Specifies whether to enable kernel logging.| +| -k | - | <on/off> | Specifies whether to enable kernel logging.| | | | on | Enables kernel logging.| | | | off | Disables kernel logging.| -| -s | --statistics | | Shows statistics. This option must be used together with **-t** or **-D**.| -| -S | | | Clears statistics. This option must be used together with **-t** or **-D**.| -| -Q | | <control-type> | Specifies whether to enable the default quota for flow control.| +| -s | --statistics | - | Shows statistics. This option must be used together with **-t** or **-D**.| +| -S | - | - | Clears statistics. This option must be used together with **-t** or **-D**.| +| -Q | - | <control-type> | Specifies whether to enable the default quota for flow control.| | | | pidon | Enables process flow control.| | | | pidoff | Disables process flow control.| | | | domainon | Enables domain flow control.| @@ -56,7 +56,7 @@ HiLog is a log system that provides logging for the system framework, services, | | | none | Indicates that data is flushed to disks in non-compression mode.| | | | zlib | Indicates that data is flushed to disks using the zlib compression algorithm. The flushed file is in .gz format.| | | | zstd | Indicates that data is flushed to disks using the zstd compression algorithm. The flushed file is in .zst format.| -| -v | --format | <format> | | +| -v | --format | <format> | Sets the display format.| | | | time | Displays the local time.| | | | color | Adds colors to logs at different levels. By default, logs are displayed in black and white.| | | | epoch | Displays the amount of time elapsed since the epoch time.| @@ -67,7 +67,7 @@ HiLog is a log system that provides logging for the system framework, services, | | | zone | Displays the time with the local time zone.| | | | wrap | Displays logs in different lines without adding prefixes such as the timestamp to the new line.| | -b | --baselevel | <loglevel> | Sets the lowest level of logs that can be printed: D(DEBUG)/I(INFO)/W(WARN)/E(ERROR)/F(FATAL).| -| | --persist||Persists the log level setting command. (The setting will not be lost after the system is restarted.)| +| | --persist| - |Persists the log level setting command. (The setting will not be lost after the system is restarted.)| ## Examples @@ -263,7 +263,7 @@ HiLog is a log system that provides logging for the system framework, services, ``` $ hilog -L E - 08-28 09:01:25.730 2678 2678 E A00F00/com.huawei.hmos.aidataservice/AiDataService_5.10.7.320: DataChangeNotifyManager: notifyDataChange CommonEntity no valid entity to notify + 08-28 09:01:25.730 2678 2678 E A00F00/com.aidataservice/AiDataService_5.10.7.320: DataChangeNotifyManager: notifyDataChange CommonEntity no valid entity to notify 08-28 09:01:56.058 8560 8560 E A00500/com.ohos.settingsdata/SettingsData: DB not ready request = datashare:///com.ohos.settingsdata/entry/settingsdata/SETTINGSDATA?Proxy=true&key=analysis_service_switch_on , retry after DB startup 08-28 09:01:56.082 8560 8560 E A00500/com.ohos.settingsdata/SettingsData: decoder failure: /data/migrate/settings_global.xml , error code:-1 08-28 09:01:56.082 8560 8560 E A00500/com.ohos.settingsdata/SettingsData: clearXml failed:No such file or directory, error code:13900002 @@ -337,13 +337,13 @@ HiLog is a log system that provides logging for the system framework, services, ``` $ hilog -a 8 11-15 16:04:08.628 0 0 I I00000/HiLog: ========Zeroth log of type: init - 11-15 16:04:08.603 506 506 I I02C01/hmos_cust_carrier_mount/CustCarrierMount: MountCarrierToShared start - 11-15 16:04:08.604 506 506 I I02C01/hmos_cust_carrier_mount/CustCarrierMount: success to mount carrier to shared - 11-15 16:04:15.394 972 972 I I02C01/hmos_cust_carrier_mount/CustCarrierMount: UpdateCotaOpkeyLink start - 11-15 16:04:15.396 972 972 W I02C01/hmos_cust_carrier_mount/CustCarrierMount: not exsit CUST_GLOBAL_CARRIER_DIR or COTA_PARAM_CARRIER_DIR - 11-15 16:04:15.887 972 972 I I02C01/hmos_cust_carrier_mount/CustCarrierMount: success to update cota carrier - 11-15 16:04:48.749 5777 5901 I A00001/com.huawei.hmsapp.hiai.core/HiAI_Metadata: metadata is null - 11-15 16:04:48.749 5777 5901 I A00001/com.huawei.hmsapp.hiai.core/HiAI_PluginAbilityInfo: abilityInfo is null + 11-15 16:04:08.603 506 506 I I02C01/cust_carrier_mount/CustCarrierMount: MountCarrierToShared start + 11-15 16:04:08.604 506 506 I I02C01/cust_carrier_mount/CustCarrierMount: success to mount carrier to shared + 11-15 16:04:15.394 972 972 I I02C01/cust_carrier_mount/CustCarrierMount: UpdateCotaOpkeyLink start + 11-15 16:04:15.396 972 972 W I02C01/cust_carrier_mount/CustCarrierMount: not exsit CUST_GLOBAL_CARRIER_DIR or COTA_PARAM_CARRIER_DIR + 11-15 16:04:15.887 972 972 I I02C01/cust_carrier_mount/CustCarrierMount: success to update cota carrier + 11-15 16:04:48.749 5777 5901 I A00001/com.hiai.core/HiAI_Metadata: metadata is null + 11-15 16:04:48.749 5777 5901 I A00001/com.hiai.core/HiAI_PluginAbilityInfo: abilityInfo is null ``` ### Displaying Logs in the Last N Lines of the Buffer diff --git a/en/application-dev/dfx/hiperf.md b/en/application-dev/dfx/hiperf.md index 2df004cfb21b76d72a5ab5ab4e7177cc2d7385e3..4deeb5dab1e96eecbe302af71907e8cfda32b93f 100644 --- a/en/application-dev/dfx/hiperf.md +++ b/en/application-dev/dfx/hiperf.md @@ -125,7 +125,7 @@ Specifies the target program for sampling and saves the sampled data to a file ( | --dumpoptions | Dumps the command options.| ``` -Usage: hiperf record [options] [command [command-args]] +Usage: hiperf record [options] [command [command-args]] ``` Sample the process 267 for 10 seconds and use **dwarf** to collect and unwind stack memory of the process. @@ -252,7 +252,7 @@ You can use a script to sample data and generate flame graphs. You can obtain th Run **command_script.py** to sample data. This script packages the **report** command. ``` - usage: command_script.py [-h] + usage: command_script.py [-h] (-app PACKAGE_NAME | -lp LOCAL_PROGRAM | -cmd CMD | -p [PID [PID ...]] | -t [TID [TID ...]] | -sw) [-a ABILITY] [-r RECORD_OPTIONS] [-lib LOCAL_LIB_DIR] [-o OUTPUT_PERF_DATA] [--not_hdc_root] diff --git a/en/application-dev/dfx/hitrace.md b/en/application-dev/dfx/hitrace.md index d5ccfdc8763e8061639acc33c142fc1d152f7b92..c50760d483830f28596b010cf3cbb23e8c044834 100644 --- a/en/application-dev/dfx/hitrace.md +++ b/en/application-dev/dfx/hitrace.md @@ -5,27 +5,27 @@ ## Environment Requirements - The [environment setup](hdc.md#environment-setup) is complete. - - The devices are properly connected. ## Command Description -| Command| Description| -| -------- | -------- | -| -h | Displays help information.| -| -l | Displays the tag list.| -| --trace_begin | Starts capturing trace data.| -| --trace_finish | Stops capturing trace data.| -| --trace_dump | Dumps trace information.| -| -b N | Sets the buffer size (in KB) for trace data. The default buffer size is 2048 KB.| -| -t N | Sets the trace uptime in seconds, which depends on the time required for analysis. The default value is 5 seconds.| -| -o | Specifies the target file name (**stdout** by default).| -| -z | Compresses the trace data.| -| --trace_clock | Sets the type of the clock for adding a timestamp to a trace. The value can be **boot** (default), **global**, **mono**, **uptime**, or **perf**.| -| --trace_finish_nodump | Stops printing when trace capturing is stopped.| -| --start_bgsrv | Starts trace collection in the snapshot mode.| -| --dump_bgsrv | Dumps the trace data in the snapshot mode to a file.| -| --stop_bgsrv | Stops trace collection in the snapshot mode.| +| Command | Description | +| --------------------- | ------------------------------------------------------------ | +| -h | Displays help information. | +| -l | Displays the tag list. | +| --trace_begin | Starts capturing trace data. | +| --trace_finish | Stops capturing trace data. | +| --trace_dump | Dumps trace information. | +| -b N | Sets the buffer size (in KB) for trace data. The default buffer size is 2048 KB.| +| -t N | Sets the trace uptime in seconds, which depends on the time required for analysis. The default value is 5 seconds.| +| -o | Specifies the target file name (**stdout** by default). | +| -z | Compresses the trace data. | +| --trace_clock | Sets the type of the clock for adding a timestamp to a trace. The value can be **boot** (default), **global**, **mono**, **uptime**, or **perf**.| +| --trace_finish_nodump | Stops printing when trace capturing is stopped. | +| --start_bgsrv | Starts trace collection in the snapshot mode. | +| --dump_bgsrv | Dumps the trace data in the snapshot mode to a file. | +| --stop_bgsrv | Stops trace collection in the snapshot mode. | +| --trace_level | Sets the trace level threshold. The trace level lower than the threshold does not take effect. The value can be **Debug**, **Info**, **Critical**, **Commercial**, or **D**, **I**, **C**, or **M**. The logging level priority is **D** < **I** < **C** < **M**. You can use the logging APIs with the trace level in [js-apis-hitracemeter](../reference/apis-performance-analysis-kit/js-apis-hitracemeter.md) and [_hitrace](../reference/apis-performance-analysis-kit/_hitrace.md) to check whether the trace output of different thresholds meets the expectation.| > **Description** > @@ -37,13 +37,12 @@ Run the following commands in the hdc shell: 1. Display the tag list in hitrace. - ``` + ```shell hitrace -l ``` - **Example** - ``` + ```shell $ hitrace -l 2024/11/14 11:43:00 hitrace enter, running_state is SHOW_LIST_CATEGORY tagName: description: @@ -123,78 +122,73 @@ Run the following commands in the hdc shell: zimage - OpenHarmony Image Module zmedia - OpenHarmony Media Module ``` - 2. Start to capture the trace data of a specified tag. - ``` + ```shell hitrace --trace_begin --record app ``` - **Example** - ``` + ```shell $ hitrace --trace_begin --record app 2024/11/14 11:48:45 hitrace enter, running_state is RECORDING_LONG_BEGIN_RECORD 2024/11/14 11:48:45 args: tags:app bufferSize:18432 overwrite:1 2024/11/14 11:48:45 OpenRecording done. ``` - 3. Stop to capture the trace data. - ``` - hitrace --trace_finish --record: Display the trace data in the CLI by default. - ``` + By default, the trace data is displayed in the CLI. + ```shell + hitrace --trace_finish --record + ``` **Example 1** - ``` + ```shell $ hitrace --trace_finish --record 2024/11/14 11:50:33 hitrace enter, running_state is RECORDING_LONG_FINISH_RECORD 2024/11/14 11:50:33 capture done, output files: /data/log/hitrace/record_trace_20241114115033@3010728-656499531.sys ``` + Add the output path to export the trace data to the corresponding file. + ```shell + hitrace --trace_finish -o /data/local/tmp/test.ftrace ``` - hitrace --trace_finish -o /data/local/tmp/test.ftrace: Add the output path to export the trace data to the corresponding file. - ``` - **Example 2** - ``` + ```shell $ hitrace --trace_finish -o /data/local/tmp/test.ftrace 2024/11/14 11:50:33 start to read trace. 2024/11/14 11:50:33 trace read done, output: /data/local/tmp/test.ftrace ``` +4. Capture trace data with the following settings: -4. Run the **hitrace -b 10240 -t 10 -o /data/local/tmp/test2.ftrace app ability** command to capture trace data with the following settings: - - ``` - hitrace -b 10240 -t 10 -o /data/local/tmp/test2.ftrace app ability. + ```shell + hitrace -b 10240 -t 10 -o /data/local/tmp/test2.ftrace app ability ``` - **Example** - ``` + ```shell $ hitrace -b 10240 -t 10 -o /data/local/tmp/test2.ftrace app ability 2024/11/14 11:52:13 start capture, please wait 10s ... 2024/11/14 11:52:23 capture done, start to read trace. 2024/11/14 11:52:23 trace read done, output: /data/local/tmp/test2.ftrace ``` - - Buffer size: 10240 KB - Trace uptime: 10s - - Output path: **/data/local/tmp/test1.htrace** + - Output path: **/data/local/tmp/test2.ftrace**. - Tags: app and ability - 5. Dump trace information. - ``` - hitrace --trace_dump: Display the information in the CLI by default. - ``` + By default, the trace data is displayed in the CLI. + ```shell + hitrace --trace_dump + ``` **Example 1** - ``` + ```shell $ hitrace --trace_dump 2024/11/14 11:54:23 start to read trace. # tracer: nop @@ -208,112 +202,113 @@ Run the following commands in the hdc shell: # ||| / delay # TASK-PID TGID CPU# |||| TIMESTAMP FUNCTION # | | | | |||| | | - <...>-21829 ( 19280) [003] .... 3011033.731844: tracing_mark_write: trace_event_clock_sync: realtime_ts=1732002022239 - <...>-21829 ( 19280) [003] .... 3011033.731865: tracing_mark_write: trace_event_clock_sync: parent_ts=3011033.750000 + <...>-21829 ( 19280) [003] .... 3011033.731844: tracing_mark_write: trace_event_clock_sync: realtime_ts=1732002022239 + <...>-21829 ( 19280) [003] .... 3011033.731865: tracing_mark_write: trace_event_clock_sync: parent_ts=3011033.750000 # ``` + Add the output path to export the trace data to the corresponding file. + ```shell + hitrace --trace_dump -o /data/local/tmp/test3.ftrace ``` - hitrace --trace_dump -o /data/local/tmp/test3.ftrace: Add the output path to export the trace information to the corresponding file. - ``` - **Example 2** - ``` - $ hitrace -b 10240 -t 10 -o /data/local/tmp/test2.ftrace app ability + ```shell + $ hitrace --trace_dump -o /data/local/tmp/test3.ftrace 2024/11/14 11:54:23 start to read trace. - 2024/11/14 11:54:23 trace read done, output: /data/local/tmp/test3 - ``` - - ``` - You can also run the **`hitrace --trace_dump |grep \***\***\***`** command to dump trace data based on keywords. + 2024/11/14 11:54:23 trace read done, output: /data/local/tmp/test3.ftrace ``` - + You can also run the **hitrace --trace_dump | grep xxx** command to dump trace data based on keywords. 6. Start trace collection in the snapshot mode. - ``` + ```shell hitrace --start_bgsrv ``` - **Example** - ``` - $ `hitrace --start_bgsrv + ```shell + $ hitrace --start_bgsrv 2024/11/14 11:55:53 hitrace enter, running_state is SNAPSHOT_START 2024/11/14 11:55:54 OpenSnapshot done. ``` - 7. Dump the trace data in snapshot mode. By default, the trace data is stored in the binary format in **/data/log/hitrace/**. The file is named in the format of **trace-YYMMDDHHmmSS@[BOOT_TIME].sys**. You can view the file using [SmartPerf](https://www.smartperf.host). - ``` + ```shell hitrace --dump_bgsrv ``` - **Example** - ``` + ```shell $ hitrace --dump_bgsrv 2024/11/14 12:12:56 hitrace enter, running_state is SNAPSHOT_DUMP 2024/11/14 12:12:57 DumpSnapshot done, output: /data/log/hitrace/record_trace_20241114121257@2566589-103807063.sys ``` - 8. Stop trace collection in the snapshot mode. - ``` + ```shell hitrace --stop_bgsrv ``` - **Example** - ``` + ```shell $ hitrace --stop_bgsrv 2024/11/14 11:59:43 hitrace enter, running_state is SNAPSHOT_STOP 2024/11/14 11:59:43 CloseSnapshot done. ``` - 9. Compress the trace data. - ``` + ```shell hitrace -z -b 102400 -t 10 sched freq idle disk -o /data/local/tmp/test.ftrace ``` - **Example** - ``` + ```shell $ hitrace -z -b 102400 -t 10 sched freq idle disk -o /data/local/tmp/test.ftrace 2024/11/14 12:00:18 start capture, please wait 10s ... 2024/11/14 12:00:28 capture done, start to read trace. 2024/11/14 12:00:29 trace read done, output: /data/local/tmp/test.ftrace ``` - 10. Set the trace output clock to **boot** (system time of the device). - ``` - hitrace --trace_clock boot -b 102400 -t 10 sched freq idle disk -o /data/local/tmp/test.ftrace - ``` + ```shell + hitrace --trace_clock boot -b 102400 -t 10 sched freq idle disk -o /data/local/tmp/test.ftrace + ``` + **Example** + + ```shell + $ hitrace --trace_clock boot -b 102400 -t 10 sched freq idle disk -o /data/local/tmp/test.ftrace + 2024/11/14 12:01:42 start capture, please wait 10s ... + 2024/11/14 12:01:52 capture done, start to read trace. + 2024/11/14 12:01:52 trace read done, output: /data/local/tmp/test.ftrace + ``` +11. Stop capturing and printing trace data in the CLI. - **Example** + By default, the trace data is saved in **/data/log/hitrace/**. - ``` - $ hitrace --trace_clock boot -b 102400 -t 10 sched freq idle disk -o /data/local/tmp/test.ftrace - 2024/11/14 12:01:42 start capture, please wait 10s ... - 2024/11/14 12:01:52 capture done, start to read trace. - 2024/11/14 12:01:52 trace read done, output: /data/local/tmp/test.ftrace - ``` + ```shell + hitrace --trace_finish_nodump + ``` + **Example** -11. Stop capturing and printing trace data in the CLI. + ```shell + $ hitrace --trace_finish_nodump + 2024/11/14 12:03:07 hitrace enter, running_state is RECORDING_LONG_FINISH_NODUMP + 2024/11/14 12:03:07 end capture trace. + ``` +12. Set the trace level threshold to **Info**. - ``` - hitrace --trace_finish_nodump: Saves the trace data to the /data/log/hitrace/ directory by default. - ``` + ```shell + hitrace --trace_level Info + ``` + **Example** - **Example** + ```shell + $ hitrace --trace_level Info + 2024/11/14 12:05:07 hitrace enter, running_state is SET_TRACE_LEVEL + 2024/11/14 12:05:07 success to set trace level. + ``` - ``` - $ hitrace --trace_finish_nodump - 2024/11/14 12:03:07 hitrace enter, running_state is RECORDING_LONG_FINISH_NODUMP - 2024/11/14 12:03:07 end capture trace. - ``` + \ No newline at end of file diff --git a/en/application-dev/dfx/hitracemeter-guidelines-arkts.md b/en/application-dev/dfx/hitracemeter-guidelines-arkts.md index 702f2bacb728febb8f2da6b9048b153089149809..a864bc9bf9548fa00bb615f68a770996a9e22649 100644 --- a/en/application-dev/dfx/hitracemeter-guidelines-arkts.md +++ b/en/application-dev/dfx/hitracemeter-guidelines-arkts.md @@ -1,40 +1,53 @@ -# Using hiTraceMeter (ArkTS/JS) +# Using HiTraceMeter (ArkTS/JS) ## Overview -**hiTraceMeter** provides APIs for system performance tracing. You can call the APIs provided by **hiTraceMeter** in key codes to track service processes and check the system performance. +HiTraceMeter provides APIs for system performance tracing. You can call the HiTraceMeter APIs in key codes to track service processes and check the system performance. ## Basic Concepts -**hiTraceMeter Tag**: tag specifying the category of the data to trace. It is also known as **HiTraceMeter Category**. Generally, one subsystem maps to a tag. The tag is passed in by the **Tag** parameter in performance tracing APIs. When you use the hiTraceMeter CLI tool to collect tracing data, only the data specified by the **Tag** parameter is collected. +**HiTraceMeter Tag**: Tag used for tracing data categorization. It is also known as **HiTraceMeter Category**. Generally, one subsystem maps to a tag. When you use the [HiTrace](hitrace.md) CLI tool to collect tracing data, only the data specified by the **Tag** parameter is collected. The HiTraceMeter tag for applications is **HITRACE_TAG_APP**, which corresponds to **app** in the tag list displayed by running the **[hitrace](hitrace.md) -l** command. ## Working Principles -1. The application calls hiTraceMeter APIs to trace and output the tracing data to the kernel's ftrace buffer through the kernel's sysfs file interface. - -2. The hiTraceMeter CLI tool reads the tracing data in the ftrace buffer and saves the trace data as a text file on the device. +1. The application calls HiTraceMeter APIs to trace and input the tracing data to the kernel's ftrace buffer through the kernel's sysfs file interface. +2. The [HiTrace](hitrace.md) CLI tool reads the trace data in the kernel ftrace buffer and outputs the trace data to the file on the device. ## Available APIs -The performance tracing APIs are provided by the **hiTraceMeter** module. For details, see [Hitrace](../reference/apis-performance-analysis-kit/js-apis-hitracemeter.md). +The performance tracing APIs are provided by the **HiTraceMeter** module. For details, see [Hitrace](../reference/apis-performance-analysis-kit/js-apis-hitracemeter.md). + +| API | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| startSyncTrace(level: HiTraceOutputLevel, name: string, customArgs?: string): void | Starts a synchronous time slice trace with the trace output level specified. | +| finishSyncTrace(level: HiTraceOutputLevel): void | Stops a synchronous time slice trace with the trace output level specified. The value of **level** must be the same as that of **startSyncTrace**.| +| startAsyncTrace(level: HiTraceOutputLevel, name: string, taskId: number, customCategory: string, customArgs?: string): void | Starts an asynchronous time slice trace with the trace output level specified. If multiple tracing tasks with the same name need to be performed at the same time, different task IDs must be specified through **taskId**. If the tracing tasks with the same name are not performed at the same time, the same task ID can be used.| +| finishAsyncTrace(level: HiTraceOutputLevel, name: string, taskId: number): void | Stops an asynchronous time slice trace with the trace output level specified. Stops a tracing task. The values of **name** and **taskId** must be the same as those in **startAsyncTrace**.| +| traceByValue(level: HiTraceOutputLevel, name: string, count: number): void | Traces an integer with the trace output level specified. **name** and **count** are used to identify the name and value of an integer variable to be traced.| +| isTraceEnabled(): boolean | Checks whether application trace capture is enabled. If not, HiTraceMeter performance tracing is invalid.| + +HiTraceMeter logging APIs are classified into three types by functionality/behavior: API for synchronous time slice tracing, API for asynchronous time slice tracing, and API for integer tracing. Both synchronous and asynchronous time slice tracing APIs are synchronous APIs. You can use HiTraceMeter APIs with [HiTraceChain](./hitracechain-guidelines-arkts.md) to perform tracing and analysis across devices, processes, and threads. -| API| Description| -| -------- | -------- | -| hiTraceMeter.startTrace(name: string, taskId: number) | Starts an asynchronous time slice trace task. If multiple tracing tasks with the same name need to be performed at the same time, different task IDs must be specified through **taskId**. If the tracing tasks with the same name are not performed at the same time, the same task ID can be used.| -| hiTraceMeter.finishTrace(name: string, taskId: number) | Stops an asynchronous time slice trace task. The values of **name** and **taskId** must be the same as those of **hiTraceMeter.startTrace**. | -| hiTraceMeter.traceByValue(name: string, value: number) | Traces the value changes of a numeric variable, which is an integer.| +- The synchronous time slice tracing APIs are used in the scenario where tasks are executed in sequence. +- The asynchronous time slice tracing APIs are used in the scenario where tasks are executed asynchronously. The start and end of an asynchronous trace task are not in sequence. Therefore, the **name** and **taskId** parameters are used to identify the start and end of an asynchronous trace task. +- The integer tracing API is used to trace integer variables. -HiTraceMeter logging APIs are classified into three types by functionality/behavior: API for synchronous time slice tracing, API for asynchronous time slice tracing, and API for integer tracing. APIs for synchronous and asynchronous time slice tracing are synchronous and are used in the same thread. Cross-thread logging and analysis are not supported. +**Parameters** -- The API for synchronous time slice tracing is used for sequential logging, which is not supported in ArkTS/JS. -- The API for asynchronous time slice tracing is used to start logging before an operation is called and end longing after the operation is complete. Since the start and end of asynchronous tracing do not occur in sequence, a unique task ID is used to identify the start and end of asynchronous tracing. The task ID is passed as a parameter of the API for asynchronous tracing. -- The integer tracing API is used to trace numeric variables. +| Name | Type | Mandatory| Description | +| -------------- | ------ | ---- | ------------------------------------------------------------ | +| level | enum | Yes | Trace output level. Trace data whose levels are lower than the system threshold will not be output.
The log version threshold is **INFO**, and the nolog version threshold is **COMMERCIAL**.| +| name | string | Yes | Name of the task or integer variable to trace. The value contains a maximum of 320 characters. If the value length exceeds this limit, excess content will be truncated.| +| taskId | number | Yes | Task ID. If multiple tasks with the same **name** are executed at the same time, you must set different **taskId** when calling **startAsyncTrace**.| +| count | number | Yes | Value of an integer variable. | +| customCategory | string | Yes | Custom category name, which is used to collect asynchronous trace data of the same type. The value contains a maximum of 64 characters. If the value length exceeds this limit, excess content will be truncated.
If the category is not required, pass in an empty string.| +| customArgs | string | No | Custom key-value pair. If there are multiple key-value pairs, separate them with commas (,), for example, **key1=value1,key2=value2**.
A maximum of 512 characters are output. If the **name** and **customCategory** parameters occupy too many characters, the value of **customArgs** may be truncated.
If this parameter is not required, do not pass in it or pass in an empty string.| ## How to Develop -In this example, distributed call chain tracing begins when the application startup execution page is loaded and stops when the service usage is completed. +In this example, distributed call chain tracing begins when the application startup execution page is loaded and stops when the service usage is completed. In the following example, the **startAsyncTrace**, **finishAsyncTrace**, and **traceByValue** APIs of HiTraceMeter are used in ArkTS. -1. In DevEco Studio, create an ArkTS application project. In the **Project** window, choose **entry** > **src** > **main** > **ets** > **pages** > **index**, and double-click **index.ets**. Add the code to the file to implement performance tracing upon page loading. The sample code of tracing task **myTraceTest** is as follows: +1. In DevEco Studio, create an ArkTS application project. In the **Project** window, choose **entry** > **src** > **main** > **ets** > **pages** > **index**, and double-click **index.ets**. Add the code to the file to implement performance tracing upon page loading. The sample code of tracing task **myTestAsyncTrace** is as follows: ```ts import hiTraceMeter from '@ohos.hiTraceMeter'; @@ -52,29 +65,29 @@ In this example, distributed call chain tracing begins when the application star .fontWeight(FontWeight.Bold) .onClick(() => { this.message = 'Hello Hitrace'; - + const COMMERCIAL = hiTraceMeter.HiTraceOutputLevel.COMMERCIAL; + let traceCount = 0; // Start the first tracing task. - hiTraceMeter.startTrace("myTraceTest", 1001); + hiTraceMeter.startAsyncTrace(COMMERCIAL, "myTestAsyncTrace", 1001, "categoryTest", "key=value"); // Start counting the task. traceCount++; - hiTraceMeter.traceByValue("myTestCount", traceCount); + hiTraceMeter.traceByValue(COMMERCIAL, "myTestCountTrace", traceCount); // Keep the service process running. console.log(`myTraceTest running, taskid: 1001`); - + // Start the second tracing task with the same name while the first task is still running. The tasks are running concurrently and therefore their taskId must be different. - hiTraceMeter.startTrace("myTraceTest", 1002); + hiTraceMeter.startAsyncTrace(COMMERCIAL, "myTestAsyncTrace", 1002, "categoryTest", "key=value"); // Start counting the task. traceCount++; - hiTraceMeter.traceByValue("myTestCount", traceCount); + hiTraceMeter.traceByValue(COMMERCIAL, "myTestCountTrace", traceCount); // Keep the service process running. console.log(`myTraceTest running, taskid: 1002`); // End the tracing task whose task ID is 1001. - hiTraceMeter.finishTrace("myTraceTest", 1001); + hiTraceMeter.finishAsyncTrace(COMMERCIAL, "myTestAsyncTrace", 1001); // End the tracing task whose task ID is 1002. - hiTraceMeter.finishTrace("myTraceTest", 1002); - + hiTraceMeter.finishAsyncTrace(COMMERCIAL, "myTestAsyncTrace", 1002); }) } .width('100%') @@ -83,30 +96,27 @@ In this example, distributed call chain tracing begins when the application star } } ``` +2. Click the **Run** button in DevEco Studio to run the project. Then, run the [HiTrace](hitrace.md) command to obtain the tracing task logs. -2. Click the **Run** button in DevEco Studio to run the project. Then, run the [hitrace](hitrace.md) command to obtain the tracing task logs. - - Run the following command in DevEco Studio Terminal: + Run the following command in DevEco Studio Terminal to enable trace capture: ```shell PS D:\xxx\xxx> hdc shell $ hitrace --trace_begin app ``` - - After the **trace** command is executed, call the HiTraceMeter APIs in your service logic on the device. Then, run the following commands in sequence: + Start the application, execute the service call logic (including HiTraceMeter APIs), and run the following commands in sequence: ```shell - $ hitrace --trace_dump | grep tracing_mark_write + $ hitrace --trace_dump | grep myTest $ hitrace --trace_finish ``` - The following is an example of the captured trace data: ```text - <...>-3310 (-------) [005] .... 351382.921936: tracing_mark_write: S|3310|H:myTraceTest 1001 - <...>-3310 (-------) [005] .... 351382.922233: tracing_mark_write: C|3310|H:myTestCount 1 - <...>-3310 (-------) [005] .... 351382.922138: tracing_mark_write: S|3310|H:myTraceTest 1002 - <...>-3310 (-------) [005] .... 351382.922233: tracing_mark_write: C|3310|H:myTestCount 2 - <...>-3310 (-------) [005] .... 351382.922165: tracing_mark_write: F|3310|H:myTestCount 1001 - <...>-3310 (-------) [005] .... 351382.922175: tracing_mark_write: F|3310|H:myTestCount 1002 + <...>-23649 (-------) [007] .... 2078.630872: tracing_mark_write: S|23649|H:myTestAsyncTrace|1001|M62|categoryTest|key=value + <...>-23649 (-------) [007] .... 2078.630887: tracing_mark_write: C|23649|H:myTestCountTrace|1|M62 + <...>-23649 (-------) [007] .... 2078.630989: tracing_mark_write: S|23649|H:myTestAsyncTrace|1002|M62|categoryTest|key=value + <...>-23649 (-------) [007] .... 2078.630996: tracing_mark_write: C|23649|H:myTestCountTrace|2|M62 + <...>-23649 (-------) [007] .... 2078.631027: tracing_mark_write: F|23649|H:myTestAsyncTrace|1001|M62 + <...>-23649 (-------) [007] .... 2078.631033: tracing_mark_write: F|23649|H:myTestAsyncTrace|1002|M62 ``` diff --git a/en/application-dev/dfx/hitracemeter-guidelines-ndk.md b/en/application-dev/dfx/hitracemeter-guidelines-ndk.md index 62326d9c1192279e8a8924dd781de73dc86d2101..8a11373ff47220d96f638b6969bd4ba8ece4bb10 100644 --- a/en/application-dev/dfx/hitracemeter-guidelines-ndk.md +++ b/en/application-dev/dfx/hitracemeter-guidelines-ndk.md @@ -1,87 +1,116 @@ # Using HiTraceMeter (C/C++) -**HiTrace** provides APIs to implement call chain tracing throughout a service process. You can use these APIs to quickly obtain the run log specific to the call chain of a service process and locate faults in inter-device, inter-process, or inter-thread communications. +## Overview -## Available APIs - -The performance tracing APIs are provided by the **HiTraceMeter** module. For details, see [Hitrace](../reference/apis-performance-analysis-kit/_hitrace.md). - -| API| Description| -| -------- | -------- | -| void OH_HiTrace_StartTrace(const char* name) | Starts a synchronous time slice trace.| -| void OH_HiTrace_FinishTrace() | Ends a synchronous time slice trace.| -| void OH_HiTrace_StartAsyncTrace(const char* name, int32_t taskId) | Starts an asynchronous time slice trace.| -| void OH_HiTrace_FinishAsyncTrace(const char* name, int32_t taskId) | Ends an asynchronous time slice trace.| -| void OH_HiTrace_CountTrace(const char* name, int64_t count) | Performs an integer trace.| +HiTraceMeter provides APIs for system performance tracing. You can call the HiTraceMeter APIs in key codes to track service processes and check the system performance. -**Parameter Description** - -| Name| Type| Mandatory| Description | -| ------ | ------ | ---- | ------------------------------------------------------------ | -| name | string | Yes | Name of the variable.| -| taskId | number | Yes | ID used to indicate the association of APIs in a trace. If multiple traces with the same name need to be performed at the same time, different task IDs must be specified in **startTrace**.| -| count | number | Yes | Value of the variable. | - -## How to Develop +## Basic Concepts -1. Add **libhitrace_ndk.z.so** to **CMakeLists.txt**. +**HiTraceMeter Tag**: Tag used for tracing data categorization. It is also known as **HiTraceMeter Category**. Generally, one subsystem maps to a tag. When you use the [HiTrace](hitrace.md) CLI tool to collect tracing data, only the data specified by the **Tag** parameter is collected. The HiTraceMeter tag for applications is **HITRACE_TAG_APP**, which corresponds to **app** in the tag list displayed by running the **[hitrace](hitrace.md) -l** command. - ``` - target_link_libraries(entry PUBLIC libhitrace_ndk.z.so) - ``` +## Implementation Principles -2. Include the **trace.h** header file in the source file. +1. The application calls HiTraceMeter APIs to trace and input the trace data to the kernel's ftrace buffer through the kernel's sysfs file interface. +2. The [HiTrace](hitrace.md) CLI tool reads the trace data in the kernel ftrace buffer and outputs the trace data as a text file on the device. - ```c++ - #include "hitrace/trace.h" - ``` +## Available APIs -3. Trace performance data. The following uses an asynchronous trace as an example. (The sample code is a part of the default **hello.cpp** file. You only need to add related APIs at the required positions. For details about the APIs, see "Available APIs".) +The performance tracing APIs are provided by the **HiTraceMeter** module. For details, see [Hitrace](../reference/apis-performance-analysis-kit/_hitrace.md). - ```c++ - #include "napi/native_api.h" - #include "hitrace/trace.h" - static napi_value Add(napi_env env, napi_callback_info info) - { - // Start an asynchronous time slice trace. - OH_HiTrace_StartAsyncTrace("hitraceTest", 123); - // End the asynchronous time slice trace (The start and end points are for reference only. Add them to the code lines where you want to start and end the trace.) - OH_HiTrace_FinishAsyncTrace("hitraceTest", 123); - size_t requireArgc = 2; - size_t argc = 2; - napi_value args[2] = {nullptr}; +| API | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| void OH_HiTrace_StartTraceEx(HiTrace_Output_Level level, const char* name, const char* customArgs) | Starts a synchronous time slice trace with the trace output level specified. | +| void OH_HiTrace_FinishTraceEx(HiTrace_Output_Level level) | Stops a synchronous time slice trace with the trace output level specified. The value of **level** must be the same as that of **OH_HiTrace_StartTraceEx**.| +| void OH_HiTrace_StartAsyncTraceEx(HiTrace_Output_Level level, const char* name, int32_t taskId, const char* customCategory, const char* customArgs) | Starts an asynchronous time slice trace with the trace output level specified. If multiple tracing tasks with the same name need to be performed at the same time, different task IDs must be specified through **taskId**. If the tracing tasks with the same name are not performed at the same time, the same task ID can be used.| +| void OH_HiTrace_FinishAsyncTraceEx(HiTrace_Output_Level level, const char* name, int32_t taskId) | Stops an asynchronous time slice trace with the trace output level specified. Stops a tracing task. The values of **name** and **taskId** must be the same as those in **OH_HiTrace_StartAsyncTraceEx**.| +| void OH_HiTrace_CountTraceEx(HiTrace_Output_Level level, const char* name, int64_t count) | Traces an integer with the trace output level specified. Traces the value changes of an integer variable.| +| bool OH_HiTrace_IsTraceEnabled(void) | Checks whether application trace capture is enabled. If not, HiTraceMeter performance tracing is invalid.| - napi_get_cb_info(env, info, &argc, args , nullptr, nullptr); +HiTraceMeter logging APIs are classified into three types by functionality/behavior: API for synchronous time slice tracing, API for asynchronous time slice tracing, and API for integer tracing. Both synchronous and asynchronous time slice tracing APIs are synchronous APIs. You can use HiTraceMeter APIs with [HiTraceChain](./hitracechain-guidelines-ndk.md) to perform tracing and analysis across devices, processes, and threads. - napi_valuetype valuetype0; - napi_typeof(env, args[0], &valuetype0); +- The synchronous time slice tracing APIs are used in the scenario where tasks are executed in sequence. +- The asynchronous time slice tracing APIs are used in the scenario where tasks are executed asynchronously. The start and end of an asynchronous trace task are not in sequence. Therefore, the **name** and **taskId** parameters are used to identify the start and end of an asynchronous trace task. +- The integer tracing API is used to trace integer variables. - napi_valuetype valuetype1; - napi_typeof(env, args[1], &valuetype1); +**Parameter Description** - double value0; - napi_get_value_double(env, args[0], &value0); +| Name | Type | Description | +| -------------- | ----------- | ------------------------------------------------------------ | +| level | enum | Trace output level. Trace data whose levels are lower than the system threshold will not be output.
The log version threshold is **HITRACE_LEVEL_INFO**, and the nolog version threshold is **HITRACE_LEVEL_COMMERCIAL**.| +| name | const char* | Name of the task or integer variable to trace. The value contains a maximum of 320 characters. If the value length exceeds this limit, excess content will be truncated.| +| taskId | int32_t | Task ID. If multiple tasks with the same **name** are executed at the same time, you must set different **taskId** when calling **OH_HiTrace_StartAsyncTraceEx**.| +| count | int64_t | Value of an integer variable. | +| customCategory | const char* | Custom category name, which is used to collect asynchronous trace data of the same type. The value contains a maximum of 64 characters. If the value length exceeds this limit, excess content will be truncated.
If the category is not required, pass in an empty string.| +| customArgs | const char* | Custom key-value pair. If there are multiple key-value pairs, separate them with commas (,), for example, **key1=value1,key2=value2**.
A maximum of 512 characters are output. If the **name** and **customCategory** parameters occupy too many characters, the value of **customArgs** may be truncated.
If this parameter is not required, pass in an empty string.| - double value1; - napi_get_value_double(env, args[1], &value1); +## How to Develop - napi_value sum; - napi_create_double(env, value0 + value1, &sum); +In the following example, the **OH_HiTrace_StartAsyncTraceEx** and **OH_HiTrace_FinishAsyncTraceEx** APIs are used in an NDK C/C++ application. - return sum; +1. Add **libhitrace_ndk.z.so** to **CMakeLists.txt**. - } - ``` + ``` + target_link_libraries(entry PUBLIC libhitrace_ndk.z.so) + ``` -4. Install the compiled HAP in the device. In the **cmd** window, run **hdc shell** to connect to the device, and run **hitrace --trace_begin app** to start trace. - - ```shell - capturing trace... - ``` +2. Include the **trace.h** header file in the source file. -5. Click the newly installed HAP several times on the device, and then run **hitrace --trace_dump | grep hitraceTest** in the **shell** window to view the trace result. - - ```shell - <...>-2477 (-------) [001] .... 396.427165: tracing_mark_write: S|2477|H:hitraceTest 123 - <...>-2477 (-------) [001] .... 396.427196: tracing_mark_write: F|2477|H:hitraceTest 123 - ``` + ```c++ + #include "hitrace/trace.h" + ``` + +3. Trace performance data. The following uses an asynchronous trace as an example. (The sample code is a part of the default **hello.cpp** file. You only need to add related APIs at the required positions.) + + ```c++ + #include "napi/native_api.h" + #include "hitrace/trace.h" + static napi_value Add(napi_env env, napi_callback_info info) + { + // Start an asynchronous time slice trace. + OH_HiTrace_StartAsyncTraceEx(HITRACE_LEVEL_COMMERCIAL, "hitraceTest", 123, "categoryTest", "key=value"); + // End the asynchronous time slice trace (The start and end points are for reference only. Add them to the code lines where you want to start and end the trace.) + OH_HiTrace_FinishAsyncTraceEx(HITRACE_LEVEL_COMMERCIAL, "hitraceTest", 123); + size_t requireArgc = 2; + size_t argc = 2; + napi_value args[2] = {nullptr}; + + napi_get_cb_info(env, info, &argc, args , nullptr, nullptr); + + napi_valuetype valuetype0; + napi_typeof(env, args[0], &valuetype0); + + napi_valuetype valuetype1; + napi_typeof(env, args[1], &valuetype1); + + double value0; + napi_get_value_double(env, args[0], &value0); + + double value1; + napi_get_value_double(env, args[1], &value1); + + napi_value sum; + napi_create_double(env, value0 + value1, &sum); + + return sum; + } + ``` + +4. Install the compiled HAP in the device. In the **cmd** window, run **hdc shell** to connect to the device, and run the following command to start tracing. + + ```shell + $ hitrace --trace_begin app + ``` + +5. Start the application, execute the service call logic (including HiTraceMeter APIs), and run the following commands to view trace data. + + ```shell + $ hitrace --trace_dump | grep hitraceTest + $ hitrace --trace_finish + ``` + + The following is an example of the captured trace data: + + ```text + <...>-26889 (-------) [001] .... 3100.023070: tracing_mark_write: S|26889|H:hitraceTest|123|M62|categoryTest|key=value + <...>-26889 (-------) [001] .... 3100.023080: tracing_mark_write: F|26889|H:hitraceTest|123|M62 + ``` diff --git a/en/application-dev/displaymanager/displayManager-overview.md b/en/application-dev/displaymanager/displayManager-overview.md index 219acd806831e44e6108e491763fc00543d89ba3..2e88af5b76d3c5ef42a2d2530ecd79fc7313bb49 100644 --- a/en/application-dev/displaymanager/displayManager-overview.md +++ b/en/application-dev/displaymanager/displayManager-overview.md @@ -12,5 +12,5 @@ For details about how to obtain display properties and listen for status changes ## Constraints -- The Display and Screen APIs must be used in the system that supports the SystemCapability.Window.SessionManager capability. For details, see [SystemCapability](../reference/syscap.md). +- The Display and Screen APIs must be used in the system that supports the SystemCapability.Window.SessionManager capability. For details, see [SystemCapability](../reference/syscap.md). - In multi-display implementation, the Screen API is available only for system applications only, and certain APIs require the ohos.permission.CAPTURE_SCREEN permission. diff --git a/en/application-dev/distributedservice/Readme-EN.md b/en/application-dev/distributedservice/Readme-EN.md index eadddbaabf4180b6f0e1b46c85c8365d69094ab6..e9c7f1ae83431fb67d5f5699ed59432d89028c7b 100644 --- a/en/application-dev/distributedservice/Readme-EN.md +++ b/en/application-dev/distributedservice/Readme-EN.md @@ -1,4 +1,11 @@ -# Distributed Service Kit (Distributed Management Service) +# Distributed Service Kit - [Introduction to Distributed Service Kit](distributedservice-kit-intro.md) - [Distributed Device Management Development](devicemanager-guidelines.md) +- Distributed Ability Connection Management + - [UIAbility Connection Development](abilityconnectmanager-guidelines.md) + + - [UIAbility and Extension Connection Development](distributedextension-guidelines.md) + +- Distributed Hardware Connection Management + - [Distributed Camera Development](camera-distributed.md) \ No newline at end of file diff --git a/en/application-dev/distributedservice/abilityconnectmanager-guidelines.md b/en/application-dev/distributedservice/abilityconnectmanager-guidelines.md index ceb5936e3fed3cf386beb269504a2eae111a85d5..4082b32d8193fb42e7d648a9bb320388c2505e85 100644 --- a/en/application-dev/distributedservice/abilityconnectmanager-guidelines.md +++ b/en/application-dev/distributedservice/abilityconnectmanager-guidelines.md @@ -1,38 +1,47 @@ -# Cross-Device Connection Management +# UIAbility Connection Development ## Introduction -Cross-device connection management allows for mutual capability assistance between devices that form a Super Device through a distributed OS, providing users with a more efficient, immersive experience compared to that of a single device. For example, a camera application of the watch can start a camera function of the mobile phone to implement real-time image preview and remote photographing. +Cross-device connection management allows for mutual capability assistance between devices that form a Super Device through a distributed OS, providing users with a more efficient, immersive experience compared to that of a single device. For example, a camera application of the watch can start a camera function of the mobile phone to implement real-time image preview and remote photographing. ### Available Capabilities - Cross-device application startup: uses the application on the local device to start the same application on another device and perform collaborative operations. -- Data interaction: implements cross-device transmission of data, including text messages, byte streams, images, and transport streams. (Only text interaction is supported for third-party applications.) +- Data interaction: implements cross-device transmission of data.Such data includes text messages, byte streams, images, and transport streams (text interaction supported only for third-party applications). ### Typical Use Cases -The transport stream feature allows users to start the peer camera from the local camera to access capabilities such as camera preview, text-based interaction, photo reception, and remote camera shutter. +The transport stream feature allows users to start the peer camera from the local camera to access capabilities such as text-based interaction, camera preview, photo reception, and remote camera shutter. ### Basic Concepts Before you get started, familiarize yourself with the following concepts: -- **DMS** +- **Distributed Management Service (DMS)** - Distributed Management Service (DMS) is a framework that provides distributed component management capabilities. + A framework that provides distributed component management capabilities. +- **UIAbility** + + A component that implements tasks specific to application UIs, such as lifecycle management, user interaction, and UI rendering. + +- **Extension** + + A component that extends application functions or implements cross-device collaboration. It allows applications to run some tasks in the background or migrates some functions to other devices for execution, implementing distributed capabilities. + + - **Byte stream** - Byte streams are data of the [ArrayBuffer](../arkts-utils/arraybuffer-object.md) type. They can be used to store binary data, for example, image or audio data. + Data of the [ArrayBuffer](../arkts-utils/arraybuffer-object.md) type, which can be used to store binary data, for example, image or audio data. - **Transport stream** - Transport streams are media streams that can be used to transmit images and video streams. - + Media streams that can be used to transmit images and video streams. + ### Implementation Principles Cross-device connection management is built on a distributed component management framework. It implements JS object encapsulation on the distributed component management framework and establishes sessions between applications through this framework to perform cross-device collaboration. The data-based interaction capabilities are provided by the system. @@ -47,9 +56,9 @@ Cross-device connection management is built on a distributed component managemen - You need to log in with the same HUAWEI ID on different devices. - Cross-device collaboration is supported only for UIAbility applications with the same bundle name on different devices. - + - The byte stream, image, and transport stream capabilities are supported only for system applications. - + - After the service collaboration is complete, the collaboration status must be ended in a timely manner. If an application does not apply for a continuous task, the collaboration lifecycle will be ended when the screen is locked or the application is switched to the background for more than 5 seconds. - The distributed component management framework does not censor the transmitted content during the collaboration process. If privacy data is involved, it is recommended that the application employs measures such as data encryption and pop-up notification to enhance information security. @@ -65,7 +74,7 @@ You have logged in to devices A and B with the same HUAWEI ID and the two device ### Setting Up the Environment 1. Download and install DevEco Studio on the PC. For details, see [Downloading Software](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/ide-software-download-V5) and [Installing DevEco Studio](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/ide-software-install-V5). The DevEco Studio version must be 4.1 or later. -2. Update the public-SDK to API 16 or later. For details, see [Switching to Full SDK](../faqs/full-sdk-switch-guide.md). +2. Update the public-SDK to API 18 or later. For details about how to update the SDK, see [OpenHarmony SDK Upgrade Assistant]( ../tools/openharmony_sdk_upgrade_assistant.md). 3. Connect device A and device B to the PC using USB cables. 4. Enable Bluetooth on device A and device B to implement networking. @@ -100,18 +109,18 @@ The following table describes the APIs for cross-device connection management. F | connect(sessionId: number): Promise<ConnectResult>; | Connects to the ability on the source side.| | acceptConnect(sessionId: number, token: string): Promise<void>; | Connects to the ability on the sink side.| | disconnect(sessionId: number): void; | Disconnects the ability connection.| -| on(type: 'connect' \|  'disconnect' \|  'receiveMessage' \|  'receiveData' \|  'receiveImage', sessionId: number, callback: Callback<EventCallbackInfo>): void | Enables listening for the **connect**, **disconnect**, **receiveMessage**, **receiveData**, and **receiveImage** events.| -| off(type: 'connect' \|  'disconnect' \|  'receiveMessage' \|  'receiveData' \|  'receiveImage', 'connect', sessionId: number, callback?: Callback<EventCallbackInfo>): void | Disables listening for the **connect**, **disconnect**, **receiveMessage**, **receiveData**, and **receiveImage** events.| +| on(type: 'connect' \|  'disconnect' \|  'receiveMessage' \|  'receiveData' \|  'receiveImage', sessionId: number, callback: Callback<EventCallbackInfo>): void | Enable listening for the **connect**, **disconnect**, **receiveMessage**, **receiveData**, and **receiveImage **events.| +| off(type: 'connect' \|  'disconnect' \|  'receiveMessage' \|  'receiveData' \|  'receiveImage', 'connect', sessionId: number, callback?: Callback<EventCallbackInfo>): void | Cancels listening for the **connect**, **disconnect**, **receiveMessage**, **receiveData**, and **receiveImage **events.| | sendMessage(sessionId: number, msg: string): Promise<void>; | Sends a text message.| -| sendData(sessionId: number, data: ArrayBuffer): Promise<void>; | Sends byte streams (supported only for system applications).| -| sendImage(sessionId: number, image: image.PixelMap): Promise<void>; | Sends an image (supported only for system applications).| -| createStream(sessionId: number, param: StreamParam): Promise<number>; | Creates transport streams (supported only for system applications).| -| destroyStream(sessionId: number): void; | Destroys transport streams (supported only for system applications).| +| sendData(sessionId: number, data: ArrayBuffer): Promise<void>; | Sends byte streams (supported only for system applications).| +| sendImage(sessionId: number, image: image.PixelMap): Promise<void>; | Sends an image (supported only for system applications).| +| createStream(sessionId: number, param: StreamParam): Promise<number>; | Creates transport streams (supported only for system applications).| +| destroyStream(sessionId: number): void; | Destroys transport streams (supported only for system applications).| ### Development Procedure -The application on device A starts and connects to the application on device B through the cross-device application management module. After the connection is successful, the applications on device A and device B register a callback listener for corresponding events through the **on** interface. The application on device A or device B calls **sendMessage**, **sendData**, **sendImage**, or **createStream** to send text messages, byte streams, or transport streams. The peer end performs subsequent service coordination based on the received callback. +The application on device A starts and connects to the application on device B through the cross-device application management module. After the connection is successful, the applications on device A and device B register a callback listener for corresponding events through the **on** interface. The application on device A or device B calls **sendMessage**, **sendData**, **sendImage**, or **createStream** to send text messages, byte streams, or transport streams. The peer end performs subsequent service coordination based on the received callback. #### Importing the AbilityConnectionManager Module File @@ -125,9 +134,9 @@ The application on device A starts and connects to the application on device B t The application on device A needs to discover device B and use its **netWorkId** as the input parameter of the collaboration API. You can call APIs of the distributed device management module to discover and select the peer device. For details, see [Distributed Device Management Development](devicemanager-guidelines.md). -#### Create a session between applications and set up a connection between them. +#### Initiating a Session Between Applications -During the session and connection establishment, the applications on device A and device B perform different operations. In the subsequent development procedure, the application on device A serves as the connection initiator, while the application on device B serves as the connection receiver. +During session establishment, the applications on device A and device B perform different operations. In the subsequent development procedure, the application on device A serves as the connection initiator, while the application on device B serves as the connection receiver. ##### Device A @@ -270,7 +279,7 @@ After the application on device A calls **connect()**, the application on device #### Enabling Event Listening After the application creates a session and obtains the session ID, you can call **on()** to listen for the corresponding events and notify the listener through a callback. - + ```ts import { abilityConnectionManager } from '@kit.DistributedServiceKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; @@ -290,7 +299,7 @@ After the application creates a session and obtains the session ID, you can call abilityConnectionManager.on("receiveImage", this.sessionId,(callbackInfo) => { hilog.info(0x0000, 'testTag', 'session receiveImage, sessionId is', callbackInfo.sessionId); }); - ``` + ``` #### Sending Data @@ -307,7 +316,7 @@ After the applications are successfully connected, you can call **sendMessage()* hilog.error(0x0000, 'testTag', "connect failed"); }) ``` - + ##### Sending Byte Streams After the applications are successfully connected, you can call **sendData()** on device A or device B to send byte streams to the peer application. (This function is supported only for system applications.) @@ -388,7 +397,7 @@ After the applications are successfully connected, you can call **createStream() abilityConnectionManager.startStream(streamId); }) ``` - + #### Ending Collaboration After the service collaboration is complete, the collaboration status must be ended in a timely manner. If service collaboration is required in a near future, you can call **disconnect()** to disconnect the connection between applications while retaining the session ID. This allows you to reuse the same session ID for establishing a connection next time. If service coordination is not required, you can directly call **destroyAbilityConnectionSession()** to destroy the session. In this case, the connection is automatically disconnected. @@ -415,12 +424,13 @@ After application development is complete, you can install the application on de 1. Tap the **Connect** button of the application on device A. The application on device B is started. 2. Tap the **sendMessage** button of the application on device A. The application on device B triggers the callback of the **on()** API to receive the text strings. + 3. Tap the **sendData** button of the application on device A. The application on device B triggers the callback of the **on()** API to receive the byte streams. 4. Tap the **sendImage** button of the application on device A. The application on device B triggers the callback of the **on()** API to receive the images. 5. Tap the **createStream** button of the application on device A. The application on device B triggers the callback of the **on()** API to receive the transport streams. + 6. Tap the **Disconnect** button of the application on device A or device B. The connection between the two devices is disconnected. The callback of the **connect()** API is triggered to report a disconnection event to the applications on both devices. - ## FAQs ### What should I do if the application on device A fails to start the application on device B? diff --git a/en/application-dev/distributedservice/camera-distributed.md b/en/application-dev/distributedservice/camera-distributed.md new file mode 100644 index 0000000000000000000000000000000000000000..dc782c12484b48cabdc2b8ac9c0b54b38c49cc5b --- /dev/null +++ b/en/application-dev/distributedservice/camera-distributed.md @@ -0,0 +1,445 @@ +# Distributed Camera Development + + +## Overview + + OpenHarmony distributed camera implements collaboration across devices by breaking hardware boundaries. For example, after devices A and B running OpenHarmony are networked, the application on device A can call the camera resources of device B in real time to obtain images (preview stream, photo stream, or video stream) from device B. In addition, in-depth controls such as resolution adjustment and settings synchronization are supported on device A. Distributed camera achieves the following breakthroughs: + - Collaborative creation with multiple users + - Remote collaboration with experts + - Immersive security system + - Distributed audio and video interaction + + +### Basic Concepts + + Before started, you are advised to read the following topics to have a basic understanding of related functions: + - [UIAbility Connection Development](abilityconnectmanager-guidelines.md) + - [Camera Device Management (ArkTS)](../media/camera/camera-device-management.md) + - [Camera Development Preparations](../media/camera/camera-preparation.md) + - [Camera Session Management (ArkTS)](../media/camera/camera-session-management.md) + - [Photo Capture (ArkTS)](../media/camera/camera-shooting.md) + - [Video Recording (ArkTS)](../media/camera/camera-recording.md) + + +## Preparing the Environment + +### Environment Requirements + + Successful networking between device A and device B. + + +### Environment Setup + + 1. Install [DevEco Studio](https://developer.huawei.com/consumer/cn/download/deveco-studio) 5.0 or later. + 2. Update the public-SDK to API version 16 or later. For details, see [OpenHarmony SDK Upgrade Assistant](../tools/openharmony_sdk_upgrade_assistant.md). + 3. Connect device A and device B to the PC using USB cables. + 4. Connect device A and device B to the same Wi-Fi, identify each other, and start networking. For details, see [UIAbility Connection Development](abilityconnectmanager-guidelines.md#initiating-a-session-between-applications). + + +### Environment Verification + + Run the following shell command on the PC: + + ```shell + hdc shell + hidumper -s 4700 -a "buscenter -l remote_device_info" + ``` + + If the networking is successful, the number of networking devices is displayed, for example, **remote device num = 1**. + + +## How to Develop + + OpenHarmony pools cameras on multiple devices to provide users with the capability of using cameras across devices. + +### Development Process + + The figure below shows the recommended development process. + + ![Camera Distrubuted processing](figures/camera-distributed-process.png) + + +### Development Procedure + +#### Importing the Camera and Multimedia Modules + + ```ts + import { camera } from '@kit.CameraKit'; + import { media } from '@kit.MediaKit'; + ``` + +#### Granting the Access Permission to the Application + + The application should apply for required permissions, which include but are not limited to the following: + - For accessing the location of an image or a video: ohos.permission.MEDIA_LOCATION + - For reading files: ohos.permission.READ_MEDIA + - For writing files: ohos.permission.WRITE_MEDIA + - For using camera: ohos.permission.CAMERA + - For multi-device collaboration: ohos.permission.DISTRIBUTED_DATASYNC + + For example, you can call **requestPermissionsFromUser()** to request the corresponding permissions for the UIAbility. + ```ts + //EntryAbility.ets + export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + Logger.info('Sample_VideoRecorder', 'Ability onCreate,requestPermissionsFromUser'); + let permissionNames: Array = ['ohos.permission.MEDIA_LOCATION', 'ohos.permission.READ_MEDIA', + 'ohos.permission.WRITE_MEDIA', 'ohos.permission.CAMERA', 'ohos.permission.MICROPHONE', 'ohos.permission.DISTRIBUTED_DATASYNC']; + abilityAccessCtrl.createAtManager().requestPermissionsFromUser(this.context, permissionNames).then((data)=> { + console.log("testTag", data); + }) + .catch((err : BusinessError) => { + console.log("testTag", err.message); + }); + } + ``` + + +#### Initiating the Preview Stream and Photo Stream on the Distributed Camera + +##### 1. Obtaining the Camera Information of a Remote Device + + After the application networking is successful, you can use **getCameraManager()** to obtain the camera manager instance and **getSupportedCameras()** to obtain the supported camera device object. + + ```ts + private cameras?: Array; + private cameraManager?: camera.CameraManager; + private cameraOutputCapability?: camera.CameraOutputCapability; + private cameraIndex: number = 0; + private curVideoProfiles?: Array; + + function initCamera(): void { + console.info('init remote camera called'); + if (this.cameraManager) { + console.info('cameraManager already exits'); + return; + } + console.info('[camera] case to get cameraManager'); + this.cameraManager = camera.getCameraManager(globalThis.abilityContext); + if (this.cameraManager) { + console.info('[camera] case getCameraManager success'); + } else { + console.info('[camera] case getCameraManager failed'); + return; + } + this.cameras = this.cameraManager.getSupportedCameras(); + if (this.cameras) { + console.info('[camera] case getCameras success, size ', this.cameras.length); + for (let i = 0; i < this.cameras.length; i++) { + let came: camera.CameraDevice = this.cameras[i]; + console.info('[came] camera json:', JSON.stringify(came)); + if (came.connectionType == camera.ConnectionType.CAMERA_CONNECTION_REMOTE) { + this.cameraIndex = i; + this.cameraOutputCapability = this.cameraManager.getSupportedOutputCapability(came); + this.curVideoProfiles = this.cameraOutputCapability.videoProfiles; + console.info('init remote camera done'); // The remote camera is successfully initialized. + break; + } + } + } else { + console.info('[camera] case getCameras failed'); + } + } + ``` + +##### 2. Creating a CameraInput Instance + + After obtaining the **CameraManager** instance and the supported camera device object, call **createCameraInput()** to create a **CameraInput** instance. + + ```ts + // create camera input + async createCameraInput(): Promise { + console.log('createCameraInput called'); + if (this.cameras && this.cameras.length > 0) { + let came: camera.CameraDevice = this.cameras[this.cameraIndex]; + console.log('[came]createCameraInput camera json:', JSON.stringify(came)); + this.cameraInput = this.cameraManager?.createCameraInput(came); + if (this.cameraInput) { + console.log('[camera] case createCameraInput success'); + await this.cameraInput.open().then(() => { + console.log('[camera] case cameraInput.open() success'); + }).catch((err: Error) => { + console.log('[camera] cameraInput.open then.error:', json.stringify(err)); + }); + } else { + console.log('[camera] case createCameraInput failed'); + return; + } + } + } + ``` + +##### 3. Obtaining the PreviewOutput Object + + Use **createPreviewOutput()** to create a **PreviewOutput** object. + + ```ts + private previewOutput?: camera.PreviewOutput; + private avConfig: media.AVRecorderConfig = { + videoSourceType: media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, + profile: this.avProfile, + url: 'fd://', + } + + // create camera preview + async createPreviewOutput(): Promise { + console.log('createPreviewOutput called'); + if (this.cameraOutputCapability && this.cameraManager) { + this.previewProfiles = this.cameraOutputCapability.previewProfiles; + console.log('[camera] this.previewProfiles json ', json.stringify(this.previewProfiles)); + if (this.previewProfiles[0].format === camera.CameraFormat.CAMERA_FORMAT_YUV_420_SP) { + console.log('[camera] case format is VIDEO_SOURCE_TYPE_SURFACE_YUV'); + this.avConfig.videoSourceType = media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV; + } else { + console.log('[camera] case format is VIDEO_SOURCE_TYPE_SURFACE_ES'); + this.avConfig.videoSourceType = media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_ES; + } + this.previewOutput = this.cameraManager.createPreviewOutput(this.previewProfiles[0], this.surfaceId); + if (!this.previewOutput) { + console.log('create previewOutput failed!'); + } + console.log('createPreviewOutput done'); + } + } + ``` + + +##### 4. Obtaining the PhotoOutput Object + + Use **createPhotoOutput()** to create a **PhotoOutput** object and **createImageReceiver()** to create an **ImageReceiver** instance. + + ```ts + import fileio from '@ohos.fileio'; + + private photoReceiver?: image.ImageReceiver; + private photoOutput?: camera.PhotoOutput; + private mSaveCameraAsset: SaveCameraAsset = new SaveCameraAsset('Sample_VideoRecorder'); + + async getImageFileFd(): Promise { + console.info'getImageFileFd called'); + this.mFileAssetId = await this.mSaveCameraAsset.createImageFd(); + this.fdPath = 'fd://' + this.mFileAssetId.toString(); + this.avConfig.url = this.fdPath; + console.info('ImageFileFd is: ' + this.fdPath); + console.info('getImageFileFd done'); + } + + // close file fd + async closeFd(): Promise { + console.info('case closeFd called'); + if (this.mSaveCameraAsset) { + await this.mSaveCameraAsset.closeVideoFile(); + this.mFileAssetId = undefined; + this.fdPath = undefined; + console.info('case closeFd done'); + } + } + + async createPhotoOutput() { + const photoProfile: camera.Profile = { + format: camera.CameraFormat.CAMERA_FORMAT_JPEG, + size: { + "width": 1280, + "height": 720 + } + } + if (!this.cameraManager) { + console.log('createPhotoOutput cameraManager is null') + } + if (!this.photoReceiver) { + this.photoReceiver = image.createImageReceiver(photoProfile.size.width, photoProfile.size.height, photoProfile.format, 8) + this.photoReceiver.on("imageArrival",()=>{ + this.photoReceiver?.readNextImage((err,image)=>{ + if (err || image === undefined) { + console.log('photoReceiver imageArrival on error') + return + } + image.getComponent(4, async (err, img) => { + if (err || img === undefined) { + console.log('image getComponent on error') + return + } + await this.getImageFileFd() + fileio.write(this.mFileAssetId, img.byteBuffer) + await this.closeFd() + await image.release() + console.log('photoReceiver image.getComponent save success') + }) + }) + }) + await this.photoReceiver.getReceivingSurfaceId().then((surfaceId: string) => { + this.photoOutput = this.cameraManager?.createPhotoOutput(photoProfile, surfaceId) + if (!this.photoOutput) { + console.log('cameraManager.createPhotoOutput on error') + } + console.log('cameraManager.createPhotoOutput success') + this.photoOutput?.on("captureStart", (err, captureId) => { + console.log('photoOutput.on captureStart') + }) + }).catch((err: Error) => { + console.error('photoReceiver.getReceivingSurfaceId on error:' + err) + }) + } + } + ``` + +##### 5. Creating a CaptureSession Instance + + Use **createCaptureSession()** to create a **CaptureSession** instance. You can call **beginConfig()** to configure a session, call **addInput()** and **addOutput()** to add **CameraInput()** and **CameraOutput()** to the session, call **commitConfig()** to submit the configuration information, and use a promise to return the result. + + ```ts + private captureSession?: camera.CaptureSession; + + function failureCallback(error: BusinessError): Promise { + console.log('case failureCallback called,errMessage is ', json.stringify(error)); + } + + function catchCallback(error: BusinessError): Promise { + console.log('case catchCallback called,errMessage is ', json.stringify(error)); + } + + // create camera capture session + async createCaptureSession(): Promise { + console.log('createCaptureSession called'); + if (this.cameraManager) { + this.captureSession = this.cameraManager.createCaptureSession(); + if (!this.captureSession) { + console.log('createCaptureSession failed!'); + return + } + try { + this.captureSession.beginConfig(); + this.captureSession.addInput(this.cameraInput); + } catch (e) { + console.log('case addInput error:' + json.stringify(e)); + } + try { + this.captureSession.addOutput(this.previewOutput); + } catch (e) { + console.log('case addOutput error:' + json.stringify(e)); + } + await this.captureSession.commitConfig().then(() => { + console.log('captureSession commitConfig success'); + }, this.failureCallback).catch(this.catchCallback); + } + } + ``` + +##### 6. Starting the Session + + Use **start()** of the **CaptureSession** instance to start the session and use a promise to return the result. + + ```ts + // start captureSession + async startCaptureSession(): Promise { + console.log('startCaptureSession called'); + if (!this.captureSession) { + console.log('CaptureSession does not exists!'); + return + } + await this.captureSession.start().then(() => { + console.log('case start captureSession success'); + }, this.failureCallback).catch(this.catchCallback); + } + ``` + +#### Releasing Distributed Camera Resources + + After the service collaboration is complete, the collaboration status needs to be ended in a timely manner to release distributed camera resources. + + ```ts + // Release the camera. + async releaseCameraInput(): Promise { + console.log('releaseCameraInput called'); + if (this.cameraInput) { + this.cameraInput = undefined; + } + console.log('releaseCameraInput done'); + } + + // Release the preview. + async releasePreviewOutput(): Promise { + console.log('releasePreviewOutput called'); + if (this.previewOutput) { + await this.previewOutput.release().then(() => { + console.log('[camera] case main previewOutput release called'); + }, this.failureCallback).catch(this.catchCallback); + this.previewOutput = undefined; + } + console.log('releasePreviewOutput done'); + } + + // Release the video output. + async releaseVideoOutput(): Promise { + console.log('releaseVideoOutput called'); + if (this.videoOutput) { + await this.videoOutput.release().then(() => { + console.log('[camera] case main videoOutput release called'); + }, this.failureCallback).catch(this.catchCallback); + this.videoOutput = undefined; + } + console.log('releaseVideoOutput done'); + } + + // Stop the capture session. + async stopCaptureSession(): Promise { + console.log('stopCaptureSession called'); + if (this.captureSession) { + await this.captureSession.stop().then(() => { + console.log('[camera] case main captureSession stop success'); + }, this.failureCallback).catch(this.catchCallback); + } + console.log('stopCaptureSession done'); + } + + // Release the capture session. + async releaseCaptureSession(): Promise { + console.log('releaseCaptureSession called'); + if (this.captureSession) { + await this.captureSession.release().then(() => { + console.log('[camera] case main captureSession release success'); + }, this.failureCallback).catch(this.catchCallback); + this.captureSession = undefined; + } + console.log('releaseCaptureSession done'); + } + + // Release the camera resource. + async releaseCamera(): Promise { + console.log('releaseCamera called'); + await this.stopCaptureSession(); + await this.releaseCameraInput(); + await this.releasePreviewOutput(); + await this.releaseVideoOutput(); + await this.releaseCaptureSession(); + console.log('releaseCamera done'); + } + ``` + +### Debugging and Verification + + After application development is complete, you can install the application on device A and device B. The test procedure is as follows: + + 1. Device A starts the distributed camera on device B and initiates a preview. Device A can receive the preview stream. + 2. Device A starts the distributed camera on device B and takes a photo. Device A can receive the photo. + +## FAQs + + +### What should I do if the application on device A cannot start the camera on device B? + +**Possible Causes** + + Devices are not networked or are disconnected after networking. + +**Solution** + + Enable USB debugging on device A and device B, and use a USB cable to connect the devices to the PC. Run the following shell command on the PC: + + ```shell + hdc shell + hidumper -s 4700 -a "buscenter -l remote_device_info" + ``` + If **remote device num = 0** is displayed in the command output, the networking fails. In this case, disable and then enable Wi-Fi, and connect devices to the same Wi-Fi again. If the networking is successful, run the shell command again and the number of networking devices is displayed, for example, **remote device num = 1**. + + \ No newline at end of file diff --git a/en/application-dev/distributedservice/distributedextension-guidelines.md b/en/application-dev/distributedservice/distributedextension-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..fe6e05544c8b75ffeed8fb2e8bf4e68180d15103 --- /dev/null +++ b/en/application-dev/distributedservice/distributedextension-guidelines.md @@ -0,0 +1,188 @@ +# UIAbility and Extension Connection Development + +## Introduction + +The distributed service allows a device to extend its capabilities by cooperating with other devices in various complex scenarios. + +As it is inconvenient for users to use a single account on different devices, the cross-device collaboration capability is provided, enabling a message synchronization mechanism for collaboration between applications on mobile phones and other devices such as watches. + +### Available Capabilities + +Data interaction: implements cross-device transmission of data, including text messages, byte streams, images, and transport streams. (Only text interaction is supported for third-party applications.) + +### Typical Use Cases + +During cross-device collaboration, when device A is running in the background and device B is running in the foreground, Distributed Management Service (DMS) allows the system to activate **DistributedExtension** to implement synchronous data transmission across devices. For example, when an application runs in the background on the mobile phone and in the foreground on the watch, DMS starts **DistributedExtension** to synchronize uplink messages on the watch to the application on the mobile phone. + +### Basic Concepts + +Before you get started, familiarize yourself with the following concepts: + +* **Distributed Management Service (DMS)** + + A framework that provides distributed component management capabilities. +* **UIAbility** + + A component that implements tasks specific to application UIs, such as lifecycle management, user interaction, and UI rendering. +* **Extension** + + A component that extends application functions or implements cross-device collaboration. It allows applications to run some tasks in the background or migrates some functions to other devices for execution, implementing distributed capabilities. +* **Byte stream** + + Data of the [ArrayBuffer](https://gitee.com/openharmony/docs/blob/master/en/application-dev/arkts-utils/arraybuffer-object.md) type, which can be used to store binary data, for example, image or audio data. +* **Transport stream** + + Media streams that can be used to transmit images, audios, text information, and bytes. + +## Implementation Principles + +The application on device A integrates **DistributedExtension**. When DSoftBus on device A receives a message from the application, **DistributedExterntion** starts the application background service on device A to send the application message from device B to the application service. + +![DistributedExtension](figures/distributedextension.png) + +## Constraints + +* You need to log in with the same HUAWEI ID on different devices. +* Cross-device collaboration is supported only for UIAbility applications with the same bundle name on different devices. + +## Setting Up the Environment + +### Environment Requirements + +You have logged in to devices A and B with the same HUAWEI ID and the two devices are successfully networked through Bluetooth. + +### Environment Setup + +1. Install [DevEco Studio](https://gitee.com/link?target=https%3A%2F%2Fdeveloper.huawei.com%2Fconsumer%2Fcn%2Fdownload%2Fdeveco-studio) 4.1 or later on the PC. +2. Update the public-SDK to API 18 or later. For details about how to update the SDK, see [OpenHarmony SDK Upgrade Assistant](../tools/openharmony_sdk_upgrade_assistant.md). +3. Enable Bluetooth on devices A and B to implement networking. + +### Verifying the Environment + +Connect devices A and B to the PC and run the shell command on the PC: + +```shell +hdc shell +hidumper -s 4700 -a "buscenter -l remote_device_info" +``` + +If the networking is successful, the number of networking devices is displayed, for example, **remote device num = 1**. + +## How to Develop + +Cross-device connection management enables real-time processing of application background messages through the distributed OS, providing users with more efficient experience. + +### Available APIs + +For details about how to use the **DistributedExtensionAbility** APIs, see [DistributedExtensionAbility API Reference](../reference/apis-distributedservice-kit/js-apis-distributedExtensionAbility.md). + +| API | Description | +| -------------------------------------------------------------------- | -------------------------- | +| onCreate(want: Want): void; | Creates a distributed collaboration task. | +| onDestroy(): void; | Destroys a distributed collaboration task. | +| onCollaborate(wantParam: Record): AbilityConstant.CollaborateResult; | Called when distributed collaboration is requested.| + +### Development Procedure + +1. Register the `Extension` component in the configuration file. + + In the application configuration file `module.json5`, add the `"extensionAbilities"` field, set `"type"` to `"distributed"`, and add an entry whose `"name"` is `"ohos.extension.DistributedExtension"` to [metadata](../reference/apis-ability-kit/js-apis-bundleManager-metadata.md). + + Example: + + ```json + "extensionAbilities": [ + { + "name": "EntrydistributedAbility", + "srcEntry": "./ets/entrybackupability/EntryDistributedAbility.ets", + "type": "distributed", + "exported": false, + "metadata": [ + { + "name": "ohos.extension.DistributedExtension", + } + ], + "srcEntry": "./ets/common/MDSExtension.ts", + } + ] + ``` +2. Import the required modules. + + ```ts + import { AbilityConstant } from '@kit.AbilityKit'; + import { connection } from '@kit.NetworkKit'; + import { AsyncCallback,BusinessError } from '@kit.BasicServicesKit'; + import { abilityAccessCtrl, bundleManager, Permissions } from '@kit.AbilityKit' + import {DistributedExtensionAbility} from '@kit.DistributedServiceKit'; + ``` +3. Customize the `MDSExtension.ets` file. Specifically, inherit the `DistributedExtensionAbility` class and rewrite the `onCreate`, `onDestroy`, and `onCollaborate` methods to create and destroy **DistributedExtension** and implement connection callback. + + The following is an empty `MDSExtension.ets` file. You can observe its lifecycle based on the corresponding **Logger**. + + ```ts + import DistributedExtensionAbility from '@ohos.application.DistributedExtensionAbility'; + import Logger from '../common/Logger' + import abilityConnectionManager from '@ohos.distributedsched.abilityConnectionManager'; + import { AbilityConstant } from '@kit.AbilityKit'; + import { connection } from '@kit.NetworkKit'; + import { AsyncCallback,BusinessError } from '@kit.BasicServicesKit'; + import { abilityAccessCtrl, bundleManager, Permissions } from '@kit.AbilityKit' + + + const TAG = `FileDistributedExtensionAbility`; + + export default class DistributedExtension extends DistributedExtensionAbility { + onCreate (want) { + Logger.info(TAG, `DistributedExterntion Create ok`); + Logger.info(TAG, `DistributedExterntion on Create want : ${JSON.stringify(want)}`); + Logger.info(TAG, `DistributedExterntion on Create end`); + } + + onCollaborate (wantParam: Record) { + Logger.info(TAG, `DistributedExterntionon onCollabRequest Accept to the result of Ability collaborate`); + let sessionId = -1; + const collabrationType = wantParam["CollaborationKeys.COLLABORATE_TYPE"] as abilityConnectionManager.CollabrationType; + if (collabrationType == undefined) { + return sessionId; + } + + Logger.info(TAG, `onCollab, peerInfo: ${JSON.stringify(collabrationType)}`); + return AbilityConstant.CollaborateResult.ACCEPT; + } + + onDestroy () { + Logger.info(TAG, `DistributedExterntion onDestroy ok`); + } + } + ``` + +## FAQs + +### What should I do if device B does not receive the response message from device A? + +**Possible Cause** + +Devices are not networking. As a result, the connection between device A and device B times out. + +**Solution** + +Enable USB debugging on device A and device B, and use a USB cable to connect the devices to the PC. Run the following shell command on the PC: + +``` +hdc shell +hidumper -s 4700 -a "buscenter -l remote_device_info" +``` + +If **remote device num = 0** is displayed in the command output, the networking has failed. Ensure that you log in to devices using the same HUAWEI ID and connect them through Bluetooth. If the networking is successful, the number of networking devices is displayed, for example, **remote device num = 1**. + +### What should I do if ongoing collaboration services are interrupted because no operation is performed on the application for a long time? + +**Possible Cause** + +During service collaboration, DMS keeps listening for the collaboration lifecycle. After the operation lasts for 10 seconds, the collaboration is ended. + +**Solution** + +Resend the message to restart the collaboration. + + \ No newline at end of file diff --git a/en/application-dev/distributedservice/figures/camera-distributed-process.png b/en/application-dev/distributedservice/figures/camera-distributed-process.png new file mode 100644 index 0000000000000000000000000000000000000000..cccd836e5704fb8187b787d01fef7fae45ee1afd Binary files /dev/null and b/en/application-dev/distributedservice/figures/camera-distributed-process.png differ diff --git a/en/application-dev/distributedservice/figures/distributedextension.png b/en/application-dev/distributedservice/figures/distributedextension.png new file mode 100644 index 0000000000000000000000000000000000000000..246e24dbde0eec842dfefb5033065cc3011254e3 Binary files /dev/null and b/en/application-dev/distributedservice/figures/distributedextension.png differ diff --git a/en/application-dev/faqs/faqs-arkts-utils.md b/en/application-dev/faqs/faqs-arkts-utils.md index fbbf978ea78a1d3bfe2c4ccb0d01831783061fe4..cf351a2123eeb4ba3eacc4fb4a5cdcd3952d6304 100644 --- a/en/application-dev/faqs/faqs-arkts-utils.md +++ b/en/application-dev/faqs/faqs-arkts-utils.md @@ -52,8 +52,10 @@ In addition, ArkTS provides TaskPool concurrent APIs, which are similar to the t To address the problem that a large number of threads are required, you are advised to: -- Convert multi-thread tasks into concurrent tasks and distribute them through the task pool. -- Execute I/O tasks in the calling thread (which can be the **TaskPool** thread), rather than starting new threads for them. +- Convert multithreading tasks into concurrent tasks. When it comes to I/O tasks, use TaskPool to handle them. + +- Execute I/O tasks in the calling thread (which can be the TaskPool thread), rather than starting new threads for them. + - Use worker threads (no more than 8) for resident CPU intensive tasks (which is of a small number). **References** @@ -423,7 +425,7 @@ Multiple threads cannot perform operations on the same memory object simultaneou ## What is the memory sharing principle of a sendable class object of ArkTS? What are the restrictions? How do I use it? (API version 11) -The sendable class is an extension of the actor model. The memory of a sendable class object is shared among threads. However, lock-free must be used for a single thread. To prevent multiple threads from simultaneously accessing a sendable class object, use the synchronization mechanism to ensure thread safe. +The Sendable class is an extension of the actor model. The memory of a sendable class object is shared among threads. However, lock-free must be used for a single thread. To prevent multiple threads from simultaneously accessing a sendable class object, use the synchronization mechanism to ensure thread safe. A sendable object must meet the following specifications: 1. The member property is of the sendable or basic type (string, number, or boolean, but not container class, which will be supported later). @@ -504,7 +506,7 @@ Currently, the use of **synchronized** is not supported. In the future, the Asyn ## Will the main thread be blocked if await is used in the main thread of ArkTS? (API version 10) -**Description** +**Question** If the following code is executed in the main thread, will the main thread be blocked? diff --git a/en/application-dev/ffrt/Readme-EN.md b/en/application-dev/ffrt/Readme-EN.md index 905f1596ff19dd2e05e08084f1eda9bba8d7ae3e..6f7a3dd55c5498f406c136abbe49d8223c28d113 100644 --- a/en/application-dev/ffrt/Readme-EN.md +++ b/en/application-dev/ffrt/Readme-EN.md @@ -1,4 +1,14 @@ # FFRT - [Introduction to Function Flow Runtime Kit](ffrt-overview.md) +- [Function Flow Runtime Paradigms](ffrt-concurrency-paradigm.md) +- Function Flow Runtime Development Samples (C) + - [Serial Queue (C)](ffrt-concurrency-serial-queue-c.md) + - [Concurrent Queue (C)](ffrt-concurrency-concurrent-queue-c.md) + - [Task Graph (C)](ffrt-concurrency-graph-c.md) +- Function Flow Runtime Development Samples (C++) + - [Serial Queue (C++)](ffrt-concurrency-serial-queue-cpp.md) + - [Concurrent Queue (C++)](ffrt-concurrency-concurrent-queue-cpp.md) + - [Task Graph (C++)](ffrt-concurrency-graph-cpp.md) - [Function Flow Runtime Development](ffrt-development-guideline.md) +- [Function Flow Runtime C APIs](ffrt-api-guideline-c.md) diff --git a/en/application-dev/ffrt/ffrt-api-guideline-c.md b/en/application-dev/ffrt/ffrt-api-guideline-c.md new file mode 100644 index 0000000000000000000000000000000000000000..c8ef1d5f9dff9689d1190a07c78572826ae682af --- /dev/null +++ b/en/application-dev/ffrt/ffrt-api-guideline-c.md @@ -0,0 +1,2362 @@ +# Function Flow Runtime C APIs + +## Task Management + +### ffrt_deps_t + +#### Declaration + +```c +typedef enum { + ffrt_dependence_data, + ffrt_dependence_task, +} ffrt_dependence_type_t; + +typedef struct { + ffrt_dependence_type_t type; + const void* ptr; +} ffrt_dependence_t; + +typedef struct { + uint32_t len; + const ffrt_dependence_t* items; +} ffrt_deps_t; +``` + +#### Parameters + +- `len`: number of data dependencies. +- `items`: data dependency array. The data length is equal to `len`. +- `ptr`: data address. +- `type`: data type. It is different from `task_handle`. + +#### Description + +The function of `ffrt_dependence_t` is the same as that of `dependence` in C++, and the function of `ffrt_deps_t` is the same as that of `std::vector` in C++. + +#### Example + +```c +// Create a data dependency. +int x = 0; +ffrt_dependence_t dependence[1]; +dependence[0].type = ffrt_dependence_data; +dependence[0].ptr = &x; +ffrt_deps_t deps; +deps.len = 1; +deps.items = dependence; + +// Create a task dependency. +ffrt_task_handle_t task = ffrt_submit_h_base(user_function_header, NULL, NULL, &attr); +ffrt_dependence_t dependence[1]; +dependence[0].type = ffrt_dependence_task; +dependence[0].ptr = task; +ffrt_deps_t deps; +deps.len = 1; +deps.items = dependence; +``` + +### ffrt_task_attr_t + +#### Declaration + +```c +typedef struct { + uint32_t storage[(ffrt_task_attr_storage_size + sizeof(uint32_t) - 1) / sizeof(uint32_t)]; +} ffrt_task_attr_t; +``` + +#### Description + +Describes the task attribute, which can be configured using `ffrt_task_attr_t` when submitting a common task or queue task. + +#### Methods + +##### ffrt_task_attr_init + +```c +FFRT_C_API int ffrt_task_attr_init(ffrt_task_attr_t* attr); +``` + +Parameters + +- `attr`: pointer to the `ffrt_task_attr_t` object. + +Return Values + +- The value **0** indicates success, and the value **-1** indicates failure. + +Description + +- Initializes an `ffrt_task_attr_t` object. + +##### ffrt_task_attr_destroy + +```c +FFRT_C_API void ffrt_task_attr_destroy(ffrt_task_attr_t* attr); +``` + +Parameters + +- `attr`: pointer to the `ffrt_task_attr_t` object. + +Description + +- Destroys an `ffrt_task_attr_t` object. + +##### ffrt_task_attr_set_name + +```c +FFRT_C_API void ffrt_task_attr_set_name(ffrt_task_attr_t* attr, const char* name); +``` + +Parameters + +- `attr`: pointer to the `ffrt_task_attr_t` object. +- `name`: task name. + +Description + +- Sets the task name, which is valid for printing maintenance and test information. + +##### ffrt_task_attr_get_name + +```c +FFRT_C_API const char* ffrt_task_attr_get_name(const ffrt_task_attr_t* attr); +``` + +Parameters + +- `attr`: pointer to the `ffrt_task_attr_t` object. + +Return Values + +- Task name. + +Description + +- Obtains the task name. + +##### ffrt_task_attr_set_qos + +```c +FFRT_C_API void ffrt_task_attr_set_qos(ffrt_task_attr_t* attr, ffrt_qos_t qos); +``` + +Parameters + +- `attr`: pointer to the `ffrt_task_attr_t` object. +- `qos`: QoS. + +Description + +- Sets the task QoS, which determines the system resource supply during task execution. If QoS is not set, the queue QoS is inherited by default. The default QoS of a common task is `ffrt_qos_default`. + +##### ffrt_task_attr_get_qos + +```c +FFRT_C_API ffrt_qos_t ffrt_task_attr_get_qos(const ffrt_task_attr_t* attr); +``` + +Parameters + +- `attr`: pointer to the `ffrt_task_attr_t` object. + +Return Values + +- QoS. + +Description + +- Obtains the configured QoS. + +##### ffrt_task_attr_set_delay + +```c +FFRT_C_API void ffrt_task_attr_set_delay(ffrt_task_attr_t* attr, uint64_t delay_us); +``` + +Parameters + +- `attr`: pointer to the `ffrt_task_attr_t` object. +- `delay_us`: scheduling delay. The unit is μs. + +Description + +- Sets the scheduling delay of a task. The task is scheduled and executed after the delay interval. If delay is not set, the value is **0** by default. + +##### ffrt_task_attr_get_delay + +```c +FFRT_C_API uint64_t ffrt_task_attr_get_delay(const ffrt_task_attr_t* attr); +``` + +Parameters + +- `attr`: pointer to the `ffrt_task_attr_t` object. + +Return Values + +- Scheduling delay. + +Description + +- Obtains the configured scheduling delay. + +##### ffrt_task_attr_set_queue_priority + +```c +FFRT_C_API void ffrt_task_attr_set_queue_priority(ffrt_task_attr_t* attr, ffrt_queue_priority_t priority); +``` + +Parameters + +- `attr`: pointer to the `ffrt_task_attr_t` object. +- `priority`: task priority. + +Description + +- Sets the task priority. Currently, only concurrent queue tasks support the priority function. Tasks in the same concurrent queue are scheduled based on their priorities. If the priority is not set, `ffrt_queue_priority_low` is used by default. + +##### ffrt_task_attr_get_queue_priority + +```c +FFRT_C_API ffrt_queue_priority_t ffrt_task_attr_get_queue_priority(const ffrt_task_attr_t* attr); +``` + +Parameters + +- `attr`: pointer to the `ffrt_task_attr_t` object. + +Return Values + +- Task priority. + +Description + +- Obtains the configured priority. + +##### ffrt_task_attr_set_stack_size + +```c +FFRT_C_API void ffrt_task_attr_set_stack_size(ffrt_task_attr_t* attr, uint64_t size); +``` + +Parameters + +- `attr`: pointer to the `ffrt_task_attr_t` object. +- `size`: size of the coroutine stack, in bytes. + +Description + +- Sets the size of the coroutine stack, which affects the maximum space used by the call stack during task execution. If this parameter is not set, the default size of the coroutine stack is 1 MB. + +##### ffrt_task_attr_get_stack_size + +```c +FFRT_C_API uint64_t ffrt_task_attr_get_stack_size(const ffrt_task_attr_t* attr); +``` + +Parameters + +- `attr`: pointer to the `ffrt_task_attr_t` object. + +Return Values + +- Size of the coroutine stack. + +Description + +- Obtains the size of the coroutine stack. + +#### Example + +```c +// Submit a common task. The task name is sample_task, the QoS is background, the scheduling delay is 1 ms, and the coroutine stack size is 2 MB. +ffrt_task_attr_t attr; +ffrt_task_attr_init(&attr); +ffrt_task_attr_set_name(&attr, "sample_task"); +ffrt_task_attr_set_qos(&attr, ffrt_qos_background); +ffrt_task_attr_set_delay(&attr, 1000); +ffrt_task_attr_set_stack_size(&attr, 2 * 1024 * 1024); +ffrt_submit_base(user_function_header, NULL, NULL, &attr); +ffrt_task_attr_destroy(&attr); +``` + +### ffrt_alloc_auto_managed_function_storage_base + +#### Declaration + +```c +typedef enum { + ffrt_function_kind_general, + ffrt_function_kind_queue, +} ffrt_function_kind_t; + +typedef void(*ffrt_function_t)(void*); +typedef struct { + ffrt_function_t exec; + ffrt_function_t destroy; + uint64_t reserve[2]; +} ffrt_function_header_t; + +FFRT_C_API void *ffrt_alloc_auto_managed_function_storage_base(ffrt_function_kind_t kind); +``` + +#### Parameters + +- `kind`: `ffrt_function_kind_general` for submitting a common task; `ffrt_function_kind_queue` for submitting a queue task. +- `exec`: function pointer invoked during task execution. +- `destroy`: function pointer invoked after a task is complete. It can be used to destroy resources. +- `reserve`: internal reserved space. It cannot be used by users. + +#### Return Values + +- Pointer to the executor of the user task. + +#### Description + +Allocates memory space. The header of the memory space is in the `ffrt_function_header_t` structure. The return pointer can be converted into the `ffrt_function_header_t*` pointer. A 64-byte space is reserved after the header for customizing the space for storing input parameters or return values. + +#### Example + +- Example 1: Generate a task executor without parameters and return values. + + ```c + #include + #include "ffrt/task.h" + + void foo(void* data) + { + printf("foo\n"); + } + + void after_foo(void* data) + { + printf("after_foo\n"); + } + + int main() + { + ffrt_function_header_t* func = (ffrt_function_header_t*)ffrt_alloc_auto_managed_function_storage_base(ffrt_function_kind_general); + + func->exec = foo; + func->destroy = after_foo; + + ffrt_submit_base(func, NULL, NULL, NULL); + ffrt_wait(); + + return 0; + } + ``` + +- Example 2: Generate a task executor with parameters and return values. + + ```c + #include + #include "ffrt/task.h" + + int foo(int x, int y) + { + printf("foo: x = %d, y = %d\n", x, y); + return x + y; + } + + void after_foo(void* data) + { + printf("after_foo\n"); + } + + // Custom task executor, which can carry parameters and return values. + typedef struct { + ffrt_function_header_t header; // The header space is ffrt_function_header_t. + int arg1; // Argument 1 + int arg2; // Argument 2 + int ret; // Return value + } user_defined_function; + + // Wrap foo into the exec function type of void(*)(void*). + void exec_func_wrapper(void* header) + { + user_defined_function* func = (user_defined_function*)header; + func->ret = foo(func->arg1, func->arg2); // Expand the foo function, pass arguments, and obtain the return value. + } + + int main() + { + user_defined_function* func = (user_defined_function*)ffrt_alloc_auto_managed_function_storage_base(ffrt_function_kind_general); + + func->header.exec = exec_func_wrapper; + func->header.destroy = after_foo; + func->arg1 = 1; + func->arg2 = 2; + + ffrt_submit_base((ffrt_function_header_t*)func, NULL, NULL, NULL); + ffrt_wait(); + + printf("ret = %d\n", func->ret); + return 0; + } + ``` + +### ffrt_submit_base + +#### Declaration + +```c +FFRT_C_API void ffrt_submit_base(ffrt_function_header_t* f, const ffrt_deps_t* in_deps, const ffrt_deps_t* out_deps, const ffrt_task_attr_t* attr); +``` + +#### Parameters + +- `f`: task executor of a user. The value can be of the native `ffrt_function_header_t` type or a custom extension type based on `ffrt_function_header_t`. +- `in_deps`: input data dependency of a task. It is usually expressed as the actual data address. `ffrt_task_handle_t` can also be used as a special input dependency. +- `out_deps`: output data dependency of a task. It is usually expressed as the actual data address. `ffrt_task_handle_t` is not supported. +- `attr`: task attribute. + +#### Description + +Submits a common task that supports attribute settings. After the input dependency is removed, the task can be scheduled and executed. After the task is executed, the output dependency is removed. + +#### Example + +- Example 1: Submit a task with attributes. + + ```c + #include + #include "ffrt/task.h" + + void foo(void* data) + { + printf("foo\n"); + } + + void after_foo(void* data) + { + printf("after_foo\n"); + } + + int main() + { + // Submit a task. + ffrt_function_header_t* func = (ffrt_function_header_t*)ffrt_alloc_auto_managed_function_storage_base(ffrt_function_kind_general); + func->exec = foo; + func->destroy = after_foo; + ffrt_submit_base(func, NULL, NULL, NULL); + + // Submit a task with attributes. + ffrt_task_attr_t attr; + ffrt_task_attr_init(&attr); + ffrt_task_attr_set_name(&attr, "sample_task"); + ffrt_task_attr_set_qos(&attr, ffrt_qos_background); + ffrt_submit_base(func, NULL, NULL, &attr); + + return 0; + } + ``` + +- Example 2: Submit a task with data dependency. + + ```c + // Submit two tasks with data dependency. The Read-After-Write dependency exists between tasks. + #include + #include + #include "ffrt/task.h" + + void cos_func(float* x, float* y) + { + *y = cos(*x); + } + + void tan_func(float* y, float* z) + { + *z = tan(*y); + } + + typedef struct { + ffrt_function_header_t header; + float* arg1; // Argument 1 + float* arg2; // Argument 2 + } user_defined_function; + + void cos_func_wrapper(void* header) + { + user_defined_function* func = (user_defined_function*)header; + cos_func(func->arg1, func->arg2); + } + + void tan_func_wrapper(void* header) + { + user_defined_function* func = (user_defined_function*)header; + tan_func(func->arg1, func->arg2); + } + + void destroy(void* header) {} + + int main() + { + float x = 0.5f, y, z; + + user_defined_function* func1 = (user_defined_function*)ffrt_alloc_auto_managed_function_storage_base(ffrt_function_kind_general); + func1->header.exec = cos_func_wrapper; + func1->header.destroy = destroy; + func1->arg1 = &x; + func1->arg2 = &y; + + user_defined_function* func2 = (user_defined_function*)ffrt_alloc_auto_managed_function_storage_base(ffrt_function_kind_general); + func2->header.exec = tan_func_wrapper; + func2->header.destroy = destroy; + func2->arg1 = &y; + func2->arg2 = &z; + + ffrt_dependence_t dependence_x[1]; + dependence_x[0].type = ffrt_dependence_data; + dependence_x[0].ptr = &x; + ffrt_deps_t deps_x; + deps_x.len = 1; + deps_x.items = dependence_x; + ffrt_dependence_t dependence_y[1]; + dependence_y[0].type = ffrt_dependence_data; + dependence_y[0].ptr = &y; + ffrt_deps_t deps_y; + deps_y.len = 1; + deps_y.items = dependence_y; + ffrt_dependence_t dependence_z[1]; + dependence_z[0].type = ffrt_dependence_data; + dependence_z[0].ptr = &z; + ffrt_deps_t deps_z; + deps_z.len = 1; + deps_z.items = dependence_z; + + ffrt_submit_base((ffrt_function_header_t*)func1, &deps_x, &deps_y, NULL); + ffrt_submit_base((ffrt_function_header_t*)func2, &deps_y, &deps_z, NULL); + + ffrt_wait(); + printf("x = %f, y = %f, z = %f\n", x, y, z); + return 0; + } + ``` + +### ffrt_submit_h_base + +#### Declaration + +```c +typedef void* ffrt_task_handle_t; + +FFRT_C_API ffrt_task_handle_t ffrt_submit_h_base(ffrt_function_header_t* f, const ffrt_deps_t* in_deps, const ffrt_deps_t* out_deps, const ffrt_task_attr_t* attr); +``` + +#### Parameters + +- `f`: task executor of a user. The value can be of the native `ffrt_function_header_t` type or a custom extension type based on `ffrt_function_header_t`. +- `in_deps`: input data dependency of a task. It is usually expressed as the actual data address. `ffrt_task_handle_t` can also be used as a special input dependency. +- `out_deps`: output data dependency of a task. It is usually expressed as the actual data address. `ffrt_task_handle_t` is not supported. +- `attr`: task attribute. + +#### Return Values + +- `ffrt_task_handle_t` task handle. + +#### Description + +Compared with the `ffrt_submit_base` API, the return value of the task handle is added. + +#### Example + +```c +// Submit a task and obtain the task handle. +ffrt_function_header_t* func = (ffrt_function_header_t*)ffrt_alloc_auto_managed_function_storage_base(ffrt_function_kind_general); +func->exec = foo; +func->destroy = after_foo; +ffrt_task_handle_t t = ffrt_submit_h_base(func, NULL, NULL, NULL); +// Note that ffrt_task_handle_t of the C API needs to be explicitly destroyed by calling ffrt_task_handle_destroy. +ffrt_task_handle_destroy(t); +``` + +### ffrt_task_handle_inc_ref + +#### Declaration + +```c +FFRT_C_API uint32_t ffrt_task_handle_inc_ref(ffrt_task_handle_t handle); +``` + +#### Parameters + +- `handle`: task handle. + +#### Return Values + +- Reference count of a task. + +#### Description + +Increases the reference count of the task through the task handle by one each time the task handle is invoked. It is used to control the task lifecycle. When the reference count is not 0, the corresponding task resources are not released. Note that `ffrt_task_handle_t` returned by `ffrt_submit_h_base` has a reference count by default. By default, you can subtract a reference count when using `ffrt_task_handle_destroy` to destroy `ffrt_task_handle_t`. + +### ffrt_task_handle_dec_ref + +#### Declaration + +```c +FFRT_C_API uint32_t ffrt_task_handle_dec_ref(ffrt_task_handle_t handle); +``` + +#### Parameters + +- `handle`: task handle. + +#### Return Values + +- Reference count of a task. + +#### Description + +Subtracts the reference count of the task through the task handle by one each time the task handle is invoked. + +### ffrt_task_handle_destroy + +#### Declaration + +```c +FFRT_C_API void ffrt_task_handle_destroy(ffrt_task_handle_t handle); +``` + +#### Parameters + +- `handle`: task handle. + +#### Description + +Destroys a task handle and subtracts a task reference count by default. + +### ffrt_wait + +#### Declaration + +```c +FFRT_C_API void ffrt_wait(void); +``` + +#### Description + +Waits until all tasks of the same level submitted earlier are complete. + +#### Example + +```c +// Wait until three tasks are complete. +ffrt_submit_base(func1, NULL, NULL, NULL); +ffrt_submit_base(func2, NULL, NULL, NULL); +ffrt_submit_base(func3, NULL, NULL, NULL); +ffrt_wait(); +``` + +### ffrt_wait_deps + +#### Declaration + +```c +FFRT_C_API void ffrt_wait_deps(const ffrt_deps_t* deps); +``` + +#### Parameters + +- `deps`: data dependency to be synchronized. + +#### Description + +Waits until the data dependency is removed. + +#### Example + +```c +// Build the data dependency of x. +int x = 0; +ffrt_dependence_t dependence[1]; +dependence[0].type = ffrt_dependence_data; +dependence[0].ptr = &x; +ffrt_deps_t deps; +deps.len = 1; +deps.items = dependence; + +// Submit a write task. +ffrt_submit_base(func, NULL, &deps, NULL); + +// Wait until the data dependency of the write task is removed. +ffrt_wait_deps(&deps); +``` + +### ffrt_this_task_update_qos + +#### Declaration + +```c +FFRT_C_API int ffrt_this_task_update_qos(ffrt_qos_t qos); +``` + +#### Parameters + +- `qos`: QoS. + +#### Return Values + +- The value **0** indicates success, and the value **1** indicates failure. + +#### Description + +Updates the task QoS dynamically during task execution. Note that this API is used in the function closure of a task to update the QoS of the task that is being executed. If this API is invoked, the task is suspended and then resumed. + +#### Example + +```c +// Dynamically update the QoS during the execution of a qos_background task. +ffrt::submit([]() { + // ... + int ret = ffrt_this_task_update_qos(ffrt_qos_user_initiated); + // ... +}, ffrt::task_attr().qos(ffrt::qos_background)); +``` + +### ffrt_this_task_get_qos + +#### Declaration + +```c +FFRT_C_API ffrt_qos_t ffrt_this_task_get_qos(void); +``` + +#### Return Values + +- QoS. + +#### Description + +Obtains the QoS of the task that is being executed. + +#### Example + +```c +// Dynamically obtain the QoS during the execution of a task. +ffrt::submit([]() { + // ... + // The obtained QoS is ffrt_qos_background. + ffrt_qos_t qos = ffrt_this_task_get_qos(); + // ... +}, ffrt::task_attr().qos(ffrt::qos_background)); +``` + +### ffrt_this_task_get_id + +#### Declaration + +```c +FFRT_C_API uint64_t ffrt_this_task_get_id(void); +``` + +#### Return Values + +- Task ID. + +#### Description + +Obtains the ID of the task that is being executed. + +#### Example + +```c +// Dynamically obtain the task ID during task execution. +ffrt::submit([]() { + // ... + // Obtain the unique task ID. + uint64_t task_id = ffrt_this_task_get_id(); + // ... +}, ffrt::task_attr().qos(ffrt::qos_background)); +``` + +## Task Queue + +### ffrt_queue_attr_t + +#### Declaration + +```c +typedef struct { + uint32_t storage[(ffrt_queue_attr_storage_size + sizeof(uint32_t) - 1) / sizeof(uint32_t)]; +} ffrt_queue_attr_t; +``` + +#### Description + +Configures queue attributes, such as the QoS, timeout, callback function, and maximum concurrency. + +#### Methods + +##### ffrt_queue_attr_init + +```c +int ffrt_queue_attr_init(ffrt_queue_attr_t* attr) +``` + +Parameters + +- `attr`: pointer to the queue attribute. + +Return Values + +- The value **0** indicates success while other values indicate failure. + +Description + +- Initializes a queue attribute object. + +##### ffrt_queue_attr_destroy + +```c +void ffrt_queue_attr_destroy(ffrt_queue_attr_t* attr) +``` + +Parameters + +- `attr`: pointer to the queue attribute. + +Description + +- Destroys a queue attribute object. + +##### ffrt_queue_attr_set_qos + +```c +void ffrt_queue_attr_set_qos(ffrt_queue_attr_t* attr, ffrt_qos_t qos) +``` + +Parameters + +- `attr`: pointer to the queue attribute. +- `qos`: QoS. + +Description + +- Sets the queue QoS. + +##### ffrt_queue_attr_get_qos + +```c +ffrt_qos_t ffrt_queue_attr_get_qos(const ffrt_queue_attr_t* attr) +``` + +Parameters + +- `attr`: pointer to the queue attribute. + +Return Values + +- Current QoS. + +Description + +- Obtains the QoS set in the current attribute. + +##### ffrt_queue_attr_set_timeout + +```c +void ffrt_queue_attr_set_timeout(ffrt_queue_attr_t* attr, uint64_t timeout_us) +``` + +Parameters + +- `attr`: pointer to the queue attribute. +- `timeout_us`: timeout (μs). + +Description + +- Sets the queue timeout (unit: μs). + +##### ffrt_queue_attr_get_timeout + +```c +uint64_t ffrt_queue_attr_get_timeout(const ffrt_queue_attr_t* attr) +``` + +Parameters + +- `attr`: pointer to the queue attribute. + +Return Values + +- Current timeout threshold (μs). + +Description + +- Obtains the timeout set in the current attribute. + +##### ffrt_queue_attr_set_callback + +```c +void ffrt_queue_attr_set_callback(ffrt_queue_attr_t* attr, ffrt_function_header_t* f) +``` + +Parameters + +- `attr`: pointer to the queue attribute. +- `f`: pointer to the task executor, which describes how to execute and destroy the CPU task. + +Description + +- Sets the callback function to be executed after a queue task times out. + +##### ffrt_queue_attr_get_callback + +```c +ffrt_function_header_t* ffrt_queue_attr_get_callback(const ffrt_queue_attr_t* attr) +``` + +Parameters + +- `attr`: pointer to the queue attribute. + +Return Values + +- Pointer to the task executor, which describes how to execute and destroy the CPU task. + +Description + +- Obtains the timeout callback function set in the current attribute. + +##### ffrt_queue_attr_set_max_concurrency + +```c +void ffrt_queue_attr_set_max_concurrency(ffrt_queue_attr_t* attr, const int max_concurrency) +``` + +Parameters + +- `attr`: pointer to the queue attribute. +- `max_concurrency`: maximum concurrency. + +Description + +- Sets the maximum queue concurrency. (Only concurrent queues are supported.) + +##### ffrt_queue_attr_get_max_concurrency + +```c +int ffrt_queue_attr_get_max_concurrency(const ffrt_queue_attr_t* attr) +``` + +Parameters + +- `attr`: pointer to the queue attribute. + +Return Values + +- Maximum concurrency. + +Description + +- Obtains the maximum concurrency set in the current attribute. (Only concurrent queues are supported). + +#### Example + +```cpp +#include +#include "ffrt/queue.h" +#include "ffrt/cpp/task.h" + +int main() +{ + ffrt_queue_attr_t queue_attr; + // (Mandatory) Initialize the queue attribute. + ffrt_queue_attr_init(&queue_attr); + + ffrt_queue_attr_set_qos(&queue_attr, static_cast(ffrt_qos_utility)); + + ffrt_queue_attr_set_timeout(&queue_attr, 10000); + + int x = 0; + std::function&& basicFunc = [&x]() { x += 1; }; + ffrt_function_header_t* func = ffrt_queue_attr_get_callback(&queue_attr); + + ffrt_queue_attr_set_callback(&queue_attr, ffrt::create_function_wrapper(basicFunc, ffrt_function_kind_queue)); + // Destroy the queue attribute. This is mandatory. + ffrt_queue_attr_destroy(&queue_attr); + return 0; +} +``` + +### ffrt_queue_t + +#### Declaration + +```c +typedef void* ffrt_queue_t; +``` + +#### Description + +Pointer to queues. It provides a series of C APIs for submitting, canceling, and waiting queue tasks and querying the number of queuing tasks. + +#### Methods + +##### ffrt_queue_create + +```c +ffrt_queue_t ffrt_queue_create(ffrt_queue_type_t type, const char* name, const ffrt_queue_attr_t* attr) +``` + +Parameters + +- `type`: queue type, for example, `ffrt_queue_serial` or `ffrt_queue_concurrent`. +- `name`: queue name. +- `attr`: pointer to the queue attribute. + +Return Values + +- `ffrt_queue_t`: If the function is called successfully, a non-null queue handle is returned. Otherwise, a null pointer is returned. + +Description + +- Creates a queue with a specified type and name. + +##### ffrt_queue_destroy + +```c +void ffrt_queue_destroy(ffrt_queue_t queue) +``` + +Parameters + +- `queue`: queue handle. + +Description + +- Destroys a queue. + +##### ffrt_queue_submit + +```c +void ffrt_queue_submit(ffrt_queue_t queue, ffrt_function_header_t* f, const ffrt_task_attr_t* attr) +``` + +Parameters + +- `queue`: queue handle. +- `f`: pointer to the task executor, which describes how to execute and destroy the CPU task. +- `attr`: task attribute. + +Description + +- Submits a task to a queue. + +##### ffrt_queue_submit_h + +```c +ffrt_task_handle_t ffrt_queue_submit_h(ffrt_queue_t queue, ffrt_function_header_t* f, const ffrt_task_attr_t* attr) +``` + +Parameters + +- `queue`: queue handle. +- `f`: pointer to the task executor, which describes how to execute and destroy the CPU task. +- `attr`: task attribute. + +Return Values + +- `ffrt_task_handle_t`: If the function is called successfully, a non-null task handle is returned. Otherwise, a null pointer is returned. + +Description + +- Submits a task to a queue and returns a task handle. + +##### ffrt_queue_wait + +```c +void ffrt_queue_wait(ffrt_task_handle_t handle) +``` + +Parameters + +- `ffrt_task_handle_t`: task handle. + +Description + +- Waits for a queue task to complete. + +##### ffrt_queue_cancel + +```c +int ffrt_queue_cancel(ffrt_task_handle_t handle) +``` + +Parameters + +- `ffrt_task_handle_t`: task handle. + +Return Values + +- The value **0** indicates success while other values indicate failure. + +Description + +- Cancels a queue task. + +##### ffrt_get_main_queue + +```c +ffrt_queue_t ffrt_get_main_queue(); +``` + +Return Values + +- Main thread queue. + +Description + +- Obtains the main thread queue for the FFRT thread to communicate with the main thread. + +##### ffrt_get_current_queue + +```c +ffrt_queue_t ffrt_get_current_queue(); +``` + +Return Values + +- ArkTS Worker thread queue. + +Description + +- This API has been deprecated since API version 18. You are not advised to use it. +- Obtains the ArkTS Worker thread queue for the FFRT thread to communicate with the ArkTS Worker thread. + +#### Example + +```cpp +#include "ffrt/queue.h" +#include "ffrt/cpp/task.h" + +int main() +{ + ffrt_queue_attr_t queue_attr; + // 1. Initialize the queue attribute. This is mandatory. + (void)ffrt_queue_attr_init(&queue_attr); + + // 2. Create a serial queue and return queue_handle. + ffrt_queue_t queue_handle = ffrt_queue_create(ffrt_queue_serial, "test_queue", &queue_attr); + + int result = 0; + std::function&& basicFunc = [&result]() { result += 1; }; + + // 3. Submit a serial task. + ffrt_queue_submit(queue_handle, ffrt::create_function_wrapper(basicFunc, ffrt_function_kind_queue), nullptr); + + // 4. Submit the serial task and return the task handle. + ffrt_task_handle_t t1 = ffrt_queue_submit_h(queue_handle, ffrt::create_function_wrapper(basicFunc, ffrt_function_kind_queue), nullptr); + // 5. Wait until the specified task is complete. + ffrt_queue_wait(t1); + + ffrt_task_handle_t t2 = ffrt_queue_submit_h(queue_handle, ffrt::create_function_wrapper(basicFunc, ffrt_function_kind_queue), nullptr); + // 6. Cancel the task with handle t2. + ffrt_queue_cancel(t2); + + // 7. Destroy the handles t1 and t2 submitted to the serial queue task. This is mandatory. + ffrt_task_handle_destroy(t1); + ffrt_task_handle_destroy(t2); + // 8. Destroy the queue attribute. This is mandatory. + ffrt_queue_attr_destroy(&queue_attr); + // 9. Destroy the queue handle. This is mandatory. + ffrt_queue_destroy(queue_handle); + return 0; +} +``` + +## Synchronization Primitive + +### ffrt_mutexattr_t + +#### Declaration + +```c +typedef enum { + ffrt_error = -1, + ffrt_success = 0, + ffrt_error_nomem = ENOMEM, + ffrt_error_timedout = ETIMEDOUT, + ffrt_error_busy = EBUSY, + ffrt_error_inval = EINVAL +} ffrt_error_t; + +typedef enum { + ffrt_mutex_normal = 0, + ffrt_mutex_recursive = 2, + ffrt_mutex_default = ffrt_mutex_normal +} ffrt_mutex_type; + +struct ffrt_mutexattr_t; + +int ffrt_mutexattr_init(ffrt_mutexattr_t* attr); +int ffrt_mutexattr_settype(ffrt_mutexattr_t* attr, int type); +int ffrt_mutexattr_gettype(ffrt_mutexattr_t* attr, int* type); +int ffrt_mutexattr_destroy(ffrt_mutexattr_t* attr); +``` + +#### Description + +- Provides performance implementation similar to pthread mutex. + +#### Methods + +##### ffrt_mutexattr_init + +```c +FFRT_C_API int ffrt_mutexattr_init(ffrt_mutexattr_t* attr); +``` + +Parameters + +- `attr`: FFRT mutex attribute. + +Return Values + +- `ffrt_success` is returned if `attr` is not empty. Otherwise, `ffrt_error_inval` is returned. + +Description + +- Initializes `mutexattr`. + +##### ffrt_mutexattr_destroy + +```c +FFRT_C_API int ffrt_mutexattr_destroy(ffrt_mutexattr_t* attr); +``` + +Parameters + +- `attr`: FFRT mutex attribute. + +Return Values + +- `ffrt_success` is returned if `attr` is not empty. Otherwise, `ffrt_error_inval` is returned. + +Description + +- Destroys `mutexattr`. + +##### ffrt_mutexattr_settype + +```c +FFRT_C_API int ffrt_mutexattr_settype(ffrt_mutexattr_t* attr, int type); +``` + +Parameters + +- `attr`: FFRT mutex attribute. +- `type`: FFRT mutex type. Currently, only `ffrt_mutex_normal` and `ffrt_mutex_recursive` are supported. + +Return Values + +- `ffrt_success` is returned if `attr` is not empty and `type` is valid. Otherwise, `ffrt_error_inval` is returned. + +Description + +- Sets the FFRT mutex attribute. + +##### ffrt_mutexattr_gettype + +```c +FFRT_C_API int ffrt_mutexattr_gettype(ffrt_mutexattr_t* attr, int* type); +``` + +Parameters + +- `attr`: FFRT mutex attribute. +- `type`: pointer to the FFRT mutex type. + +Return Values + +- `ffrt_success` is returned if neither `attr` nor `type` is empty. Otherwise, `ffrt_error_inval` is returned. + +Description + +- Obtains the FFRT mutex attribute. + +#### Example + +```c +ffrt_mutexattr_t attr; +// Initialize the mutex attribute. +ffrt_mutexattr_init(&attr); +// Set a mutex. +ffrt_mutexattr_settype(&attr, ffrt_mutex_normal); +// Set a recursive lock. +ffrt_mutexattr_settype(&attr, ffrt_mutex_recursive); +// Obtain the mutex type. +int type = ffrt_mutex_default; +ffrt_mutexattr_gettype(&attr, &type); +// Destroy the mutex attribute. +ffrt_mutexattr_destroy(&attr); +``` + +### ffrt_mutex_t + +- Implements `pthread_mutex_t`, but does not supports initialization of `PTHREAD_MUTEX_INITIALIZER`. + +#### Declaration + +```c +struct ffrt_mutex_t; +struct ffrt_mutexattr_t; + +int ffrt_mutex_init(ffrt_mutex_t* mutex, const ffrt_mutexattr_t* attr); +int ffrt_mutex_lock(ffrt_mutex_t* mutex); +int ffrt_mutex_unlock(ffrt_mutex_t* mutex); +int ffrt_mutex_trylock(ffrt_mutex_t* mutex); +int ffrt_mutex_destroy(ffrt_mutex_t* mutex); +``` + +#### Description + +- This API can be called inside or outside an FFRT task. +- The traditional function `pthread_mutex_t` may cause unexpected kernel mode trap when it fails to lock a mutex. **ffrt_mutex_t** solves this problem and therefore provides better performance if used properly. +- `ffrt_mutexattr_t` in the C API needs to be created and destroyed by calling `ffrt_mutexattr_init` and `ffrt_mutexattr_destroy`. Otherwise, undefined behavior may occur. +- `ffrt_mutex_t` in the C API needs to be explicitly created and destroyed by calling `ffrt_mutex_init` and `ffrt_mutex_destroy`. Otherwise, undefined behavior may occur. +- You need to set the `ffrt_mutex_t` object in the C code to null or destroy the object. For the same `ffrt_mutex_t` object, `ffrt_mutex_destroy` can be called only once. Otherwise, undefined behavior may occur. +- The same `ffrt_mutexattr_t` in the C API can call `ffrt_mutexattr_init` and `ffrt_mutexattr_destroy` only once. Repeated calling may cause undefined behavior. +- You need to explicitly call `ffrt_mutex_destroy` after `ffrt_mutex_init` and before `ffrt_mutexattr_destroy`. +- If `ffrt_mutex_t` is accessed after `ffrt_mutex_destroy`, undefined behavior may occur. + +#### Methods + +##### ffrt_mutex_init + +```c +FFRT_C_API int ffrt_mutex_init(ffrt_mutex_t* mutex, const ffrt_mutexattr_t* attr); +``` + +Parameters + +- `mutex`: pointer to the operated mutex. +- `attr`: FFRT mutex attribute. Its valid value can be a null pointer, `ffrt_mutex_normal`, or `ffrt_mutex_recursive`. + +Return Values + +- `ffrt_success` is returned if `mutex` is not empty and `attr` is within the valid value range. Otherwise, `ffrt_error_inval` is returned. + +Description + +- Initializes the FFRT mutex. + +##### ffrt_mutex_destroy + +```c +FFRT_C_API int ffrt_mutex_destroy(ffrt_mutex_t* mutex); +``` + +Parameters + +- `mutex`: pointer to the operated mutex. + +Return Values + +- `ffrt_success` is returned if `mutex` is not empty. Otherwise, `ffrt_error_inval` is returned. + +Description + +- Destroys a specified mutex or recursive lock. + +##### ffrt_mutex_lock + +```c +FFRT_C_API int ffrt_mutex_lock(ffrt_mutex_t* mutex); +``` + +Parameters + +- `mutex`: pointer to the operated mutex. + +Return Values + +- `ffrt_success` is returned if `mutex` is not empty. Otherwise, `ffrt_error_inval` is returned. + +Description + +- Locks a specified mutex or recursive lock. This method blocks the current task until the mutex is successfully obtained. + +##### ffrt_mutex_unlock + +```c +FFRT_C_API int ffrt_mutex_unlock(ffrt_mutex_t* mutex); +``` + +Parameters + +- `mutex`: pointer to the operated mutex. + +Return Values + +- `ffrt_success` is returned if `mutex` is not empty. Otherwise, `ffrt_error_inval` is returned. + +Description + +- Unlocks a specified mutex or recursive lock. + +##### ffrt_mutex_trylock + +```c +FFRT_C_API int ffrt_mutex_trylock(ffrt_mutex_t* mutex); +``` + +Parameters + +- `mutex`: pointer to the operated mutex. + +Return Values + +- **ffrt_error_inval** is returned if `mutex` is empty. `ffrt_success` is returned if `mutex` is not empty and the mutex is successfully held. `ffrt_error_busy` is returned if `mutex` is not empty and the mutex fails to be held. + +Description + +- Locks a specified mutex or recursive lock. + +#### Example + +```cpp +#include "ffrt/mutex.h" +#include "ffrt/cpp/task.h" + +int main() +{ + ffrt_mutexattr_t attr; + ffrt_mutex_t lock; + int sum = 0; + int type = ffrt_mutex_default; + ffrt_mutexattr_init(&attr); + ffrt_mutexattr_settype(&attr, ffrt_mutex_recursive); + ffrt_mutexattr_gettype(&attr, &type); + ffrt_mutex_init(&lock, &attr); + ffrt::submit([&]() { + ffrt_mutex_lock(&lock); + ffrt_mutex_trylock(&lock); + sum++; + ffrt_mutex_lock(&lock); + ffrt_mutex_trylock(&lock); + sum++; + ffrt_mutex_unlock(&lock); + ffrt_mutex_unlock(&lock); + ffrt_mutex_unlock(&lock); + ffrt_mutex_unlock(&lock); + }, {}, {}); + + ffrt::wait(); + + ffrt_mutexattr_destroy(&attr); + ffrt_mutex_destroy(&lock); + return 0; +} +``` + +### ffrt_rwlock_t + +- Implements `pthread_rwlock_t`. + +#### Declaration + +```c +struct ffrt_rwlock_t; +struct ffrt_rwlockattr_t; + +int ffrt_rwlock_init(ffrt_rwlock_t* rwlock, const ffrt_rwlockattr_t* attr); +int ffrt_rwlock_wrlock(ffrt_rwlock_t* rwlock); +int ffrt_rwlock_rdlock(ffrt_rwlock_t* rwlock); +int ffrt_rwlock_trywrlock(ffrt_rwlock_t* rwlock); +int ffrt_rwlock_tryrdlock(ffrt_rwlock_t* rwlock); +int ffrt_rwlock_unlock(ffrt_rwlock_t* rwlock); +int ffrt_rwlock_destroy(ffrt_rwlock_t* rwlock); +``` + +#### Description + +- This API can be called inside or outside an FFRT task. +- This API can avoid the issue that `pthread_rwlock_t` sleeps without releasing threads. The performance is better when the API is properly used. +- `ffrt_rwlock_t` in the C API needs to be explicitly created and destroyed by calling `ffrt_rwlock_init` and `ffrt_rwlock_destroy`. Otherwise, undefined behavior may occur. +- When `ffrt_rwlockattr_t` is called, the input parameter of `ffrt_rwlockattr_t` must be a null pointer. +- You need to set the `ffrt_rwlock_t` object in the C code to null or destroy the object. For the same `ffrt_rwlock_t` object, `ffrt_rwlock_destroy` can be called only once. Otherwise, undefined behavior may occur. +- If `ffrt_rwlock_t` is accessed after `ffrt_rwlock_destroy` is called, undefined behavior may occur. + +#### Methods + +##### ffrt_rwlock_init + +```c +FFRT_C_API int ffrt_rwlock_init(ffrt_rwlock_t* rwlock, const ffrt_rwlockattr_t* attr); +``` + +Parameters + +- `rwlock`: pointer to the operated RW lock. +- `attr`: pointer to the RW lock attribute. + +Return Values + +- `ffrt_success` is returned if neither `rwlock` nor `attr` is empty. Otherwise, `ffrt_error_inval` is returned or the current task is blocked. + +Description + +- Initializes the RW lock. + +##### ffrt_rwlock_wrlock + +```c +FFRT_C_API int ffrt_rwlock_wrlock(ffrt_rwlock_t* rwlock); +``` + +Parameters + +- `rwlock`: pointer to the operated RW lock. + +Return Values + +- `ffrt_success` is returned if `rwlock` is not empty. Otherwise, `ffrt_error_inval` is returned. + +Description + +- Adds a write lock to the specified RW lock. + +##### ffrt_rwlock_rdlock + +```c +FFRT_C_API int ffrt_rwlock_rdlock(ffrt_rwlock_t* rwlock); +``` + +Parameters + +- `rwlock`: pointer to the operated RW lock. + +Return Values + +- `ffrt_success` is returned if `rwlock` is not empty. Otherwise, **ffrt_error_inval** is returned. + +Description + +- Adds a read lock to the specified RW lock. + +##### ffrt_rwlock_trywrlock + +```c +FFRT_C_API int ffrt_rwlock_trywrlock(ffrt_rwlock_t* rwlock); +``` + +Parameters + +- `rwlock`: pointer to the operated RW lock. + +Return Values + +- `ffrt_success` is returned if `rwlock` is not empty and no other thread holds the RW lock. Otherwise, `ffrt_error_inval` is returned. + +Description + +- Adds a write lock to the specified RW lock. + +##### ffrt_rwlock_tryrdlock + +```c +FFRT_C_API int ffrt_rwlock_tryrdlock(ffrt_rwlock_t* rwlock); +``` + +Parameters + +- `rwlock`: pointer to the operated RW lock. + +Return Values + +- `ffrt_success` is returned if `rwlock` is not empty and no other thread holds the write lock. Otherwise, `ffrt_error_inval` is returned. + +Description + +- Adds a read lock to the specified RW lock. + +##### ffrt_rwlock_unlock + +```c +FFRT_C_API int ffrt_rwlock_unlock(ffrt_rwlock_t* rwlock); +``` + +Parameters + +- `rwlock`: pointer to the operated RW lock. + +Return Values + +- `ffrt_success` is returned if `rwlock` is not empty. Otherwise, `ffrt_error_inval` is returned. + +Description + +- Unlocks the specified RW lock. + +##### ffrt_rwlock_destroy + +```c +FFRT_C_API int ffrt_rwlock_destroy(ffrt_rwlock_t* rwlock); +``` + +Parameters + +- `rwlock`: pointer to the operated RW lock. + +Return Values + +- `ffrt_success` is returned if `rwlock` is not empty. Otherwise, `ffrt_error_inval` is returned. + +Description + +- Destroys a specified RW lock. + +#### Example + +```cpp +#include "ffrt/shared_mutex.h" +#include "ffrt/sleep.h" +#include "ffrt/cpp/task.h" + +int main() +{ + ffrt_rwlock_t rwlock; + int x = 0; + ffrt_rwlock_init(&rwlock, nullptr); + ffrt::submit([&]() { + ffrt_rwlock_wrlock(&rwlock); + ffrt_usleep(10); + x++; + ffrt_rwlock_unlock(&rwlock); + },{},{}); + + ffrt::submit([&]() { + ffrt_usleep(2); + ffrt_rwlock_rdlock(&rwlock); + ffrt_rwlock_unlock(&rwlock); + },{},{}); + + ffrt::submit([&]() { + ffrt_usleep(2); + if(ffrt_rwlock_trywrlock(&rwlock)){ + x++; + ffrt_rwlock_unlock(&rwlock); + } + },{},{}); + + ffrt::submit([&]() { + ffrt_usleep(2); + if(ffrt_rwlock_tryrdlock(&rwlock)){ + ffrt_rwlock_unlock(&rwlock); + } + },{},{}); + + ffrt::wait(); + + ffrt_rwlock_destroy(&rwlock); + return 0; +} +``` + +### ffrt_cond_t + +- Implements the pthread semaphore function, but does not supports initialization of `PTHREAD_COND_INITIALIZER`. + +#### Declaration + +```c +typedef enum { + ffrt_error = -1, + ffrt_success = 0, + ffrt_error_nomem = ENOMEM, + ffrt_error_timedout = ETIMEDOUT, + ffrt_error_busy = EBUSY, + ffrt_error_inval = EINVAL +} ffrt_error_t; + +typedef struct { + uint32_t storage[(ffrt_cond_storage_size + sizeof(uint32_t) - 1) / sizeof(uint32_t)]; +} ffrt_cond_t; + +int ffrt_cond_init(ffrt_cond_t* cond, const ffrt_condattr_t* attr); +int ffrt_cond_signal(ffrt_cond_t* cond); +int ffrt_cond_broadcast(ffrt_cond_t* cond); +int ffrt_cond_wait(ffrt_cond_t*cond, ffrt_mutex_t* mutex); +int ffrt_cond_timedwait(ffrt_cond_t* cond, ffrt_mutex_t* mutex, const struct timespec* time_point); +int ffrt_cond_destroy(ffrt_cond_t* cond); +``` + +#### Description + +- This API can be called inside or outside an FFRT task. +- The traditional function `pthread_cond_t` may cause unexpected kernel mode trap when the conditions are not met. **ffrt_cond_t** solves this problem and therefore provides better performance if being used properly. +- Note that `ffrt_cond_t` in the C API needs to be explicitly created and destroyed by calling `ffrt_cond_init` and `ffrt_cond_destroy`. However, in the C++ API, the dependency construction and destruction are automatically completed. +- You need to set the `ffrt_cond_t` object in the C code to null or destroy the object. For the same `ffrt_cond_t` object, `ffrt_cond_destroy` can be called only once. Otherwise, undefined behavior may occur. +- If `ffrt_cond_t` is accessed after `ffrt_cond_destroy` is called, undefined behavior may occur. + +#### Methods + +##### ffrt_cond_init + +```c +FFRT_C_API int ffrt_cond_init(ffrt_cond_t* cond, const ffrt_condattr_t* attr); +``` + +Parameters + +- `cond`: pointer to the target semaphore. +- `attr`: pointer to the attribute. A null pointer indicates that the default attribute is used. + +Return Values + +- `ffrt_success` is returned if `cond` is not empty. Otherwise, `ffrt_error_inval` is returned. + +Description + +- Initializes the FFRT condition variable. + +##### ffrt_cond_destroy + +```c +FFRT_C_API int ffrt_cond_destroy(ffrt_cond_t* cond); +``` + +Parameters + +- `cond`: pointer to the target semaphore. + +Return Values + +- `ffrt_success` is returned if `cond` is not empty. Otherwise, `ffrt_error_inval` is returned. + +Description + +- Destroys an FFRT condition variable. + +##### ffrt_cond_signal + +```c +FFRT_C_API int ffrt_cond_signal(ffrt_cond_t* cond); +``` + +Parameters + +- `cond`: pointer to the target semaphore. + +Return Values + +- `ffrt_success` is returned if `cond` is not empty. Otherwise, `ffrt_error_inval` is returned. + +Description + +- Unblocks at least one of the threads that are blocked on a condition variable. + +##### ffrt_cond_broadcast + +```c +FFRT_C_API int ffrt_cond_broadcast(ffrt_cond_t* cond); +``` + +Parameters + +- `cond`: pointer to the target semaphore. + +Return Values + +- `ffrt_success` is returned if `cond` is not empty. Otherwise, `ffrt_error_inval` is returned. + +Description + +- Unblocks all threads currently blocked on a condition variable. + +##### ffrt_cond_wait + +```c +FFRT_C_API int ffrt_cond_wait(ffrt_cond_t* cond, ffrt_mutex_t* mutex); +``` + +Parameters + +- `cond`: pointer to the target semaphore. +- `mutex`: pointer to the target mutex. + +Return Values + +- `ffrt_success` is returned if neither `cond` nor `mutex` is empty. Otherwise, `ffrt_error_inval` is returned. + +Description + +- Blocks a task on a condition variable. When using this method, a task releases the input mutex and enters the waiting state. The task obtains the mutex again and continues to execute until another task notifies the condition variable. +- This method is usually used together with `ffrt_mutex_lock` or `ffrt_mutex_trylock` to ensure that the mutex is held before entering the wait state. + +##### ffrt_cond_timedwait + +```c +FFRT_C_API int ffrt_cond_timedwait(ffrt_cond_t* cond, ffrt_mutex_t* mutex, const struct timespec* time_point); +``` + +Parameters + +- `cond`: pointer to the target semaphore. +- `mutex`: pointer to the target mutex. +- `time_point`: pointer to the maximum duration during which the thread is blocked. + +Return Values + +- `ffrt_success` is returned if `cond`, `mutex`, and `time_point` are not empty. Otherwise, `ffrt_error_inval` is returned. + +Description + +- Blocks a task on a condition variable until the specified timeout is reached. +- Unlike `ffrt_cond_wait`, the `ffrt_cond_timedwait` method allows a task to wait for a period of time on a condition variable. If no notification is received within the specified period of time, the task is woken up and the function returns. + +#### Example + +```cpp +#include +#include "ffrt/condition_variable.h" +#include "ffrt/mutex.h" +#include "ffrt/sleep.h" +#include "ffrt/cpp/task.h" + +struct timespec timeoutms_to_tm(int timeout_ms) { + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + ts.tv_sec += timeout_ms / 1000; + ts.tv_nsec += (timeout_ms % 1000) * 1000000; + if (ts.tv_nsec >= 1000000000) { + ts.tv_sec += 1; + ts.tv_nsec -= 1000000000; + } + return ts; +} + +int main() +{ + int a = 0; + ffrt_cond_t cond; + ffrt_mutex_t lock_; + ffrt_cond_init(&cond, nullptr); + ffrt_mutex_init(&lock_, nullptr); + + for (int i = 0; i < 3; i++) { + ffrt::submit([&]() { + int timeout = 2000; + struct timespec tm = timeoutms_to_tm(timeout); + ffrt_mutex_lock(&lock_); + auto start = std::chrono::high_resolution_clock::now(); + ffrt_cond_timedwait(&cond, &lock_, &tm); + auto end = std::chrono::high_resolution_clock::now(); + a = 123; + ffrt_mutex_unlock(&lock_); + std::chrono::duration elapsed = end - start; + double t = elapsed.count(); + std::cout << "ffrt_cond_timedwait " << t << " ms" << std::endl; + }, {}, {}); + } + + ffrt::submit([&]() { + ffrt_usleep(1000 * 1000); + ffrt_mutex_lock(&lock_); + a = 5; + ffrt_cond_broadcast(&cond); + ffrt_mutex_unlock(&lock_); + }, {}, {}); + ffrt::wait(); + ffrt_cond_destroy(&cond); + ffrt_mutex_destroy(&lock_); + return 0; +} +``` + +## Blocking Primitive + +### ffrt_usleep + +#### Declaration + +```c +FFRT_C_API int ffrt_usleep(uint64_t usec); +``` + +#### Parameters + +- `usec`: sleep duration, in μs. + +#### Description + +- Provides performance implementation similar to C11 sleep and Linux usleep. +- This API can be called only inside an FFRT task. If it is called outside an FFRT task, undefined behavior may occur. +- The sleep precision of this API is μs. +- The traditional function `sleep` may cause unexpected kernel mode trap. **ffrt_usleep** solves this problem and therefore provides better performance if used properly. + +#### Example + +```cpp +#include "ffrt/sleep.h" +#include "ffrt/cpp/task.h" + +int main() +{ + ffrt::submit([=]() { ffrt_usleep(10); }, {}, {}); + ffrt::wait(); + return 0; +} +``` + +## Cooperative Primitive + +### ffrt_yield + +#### Declaration + +```c +FFRT_C_API void ffrt_yield(); +``` + +#### Description + +- Yields CPU execution resources for other executable tasks. If there is no other executable task, `yield` is invalid. +- This API can be called only inside an FFRT task. If it is called outside an FFRT task, undefined behavior may occur. +- The exact behavior of this API depends on the implementation, especially the mechanism and system state of the FFRT scheduler in use. + +#### Example + +```cpp +#include +#include "ffrt/sleep.h" +#include "ffrt/cpp/task.h" + +int main() +{ + int count = 12; + for (int i = 0; i < count; i++) { + ffrt::submit([&]() { + ffrt_usleep(100); + std::cout << "test" << std::endl; + ffrt_yield(); + }, {}, {}); + } + ffrt::wait(); + return 0; +} +``` + +## Timer + +### ffrt_timer_t + +#### Declaration + +```c +typedef int ffrt_timer_t; +typedef void (*ffrt_timer_cb)(void* data); +``` + +#### Description + +Provides timer-related functions. + +#### Methods + +##### ffrt_timer_start + +Declaration + +```c +FFRT_C_API ffrt_timer_t ffrt_timer_start(ffrt_qos_t qos, uint64_t timeout, void* data, ffrt_timer_cb cb, bool repeat); +``` + +Parameters + +- `qos`: QoS. +- `timeout`: timer timeout, in ms. +- `cb`: callback function after expiration. +- `data`: input parameter of the callback function. +- `repeat`: whether the timer is triggered repeatedly. + +Return Values + +- `ffrt_timer_t`, which indicates the timer handle. + +Description + +- Starts a timer. If the timer expires and is not stopped, the callback function is executed. If `repeat` is set to `repeat`, the timer is set again after it expires. + +##### ffrt_timer_stop + +Declaration + +```c +FFRT_C_API int ffrt_timer_stop(ffrt_qos_t qos, ffrt_timer_t handle); +``` + +Parameters + +- `qos`: QoS. +- `handle`: timer handle. + +Return Values + +- The value **0** indicates success, and the value **-1** indicates failure. + +Description + +- Stops a timer. It is used with `ffrt_timer_start`. + +#### Example + +- Example 1: Use a one-shot timer. + + ```c + #include + #include + #include "ffrt/timer.h" + + static void test_fun(void *data) + { + *(int *)data += 1; + } + + void (*cb)(void *) = test_fun; + + int main() + { + static int x = 0; + void *data = &x; + uint64_t timeout = 200; + // Start a timer and execute the callback function after 200 ms. + int handle = ffrt_timer_start(ffrt_qos_default, timeout, data, cb, false); + usleep(300000); + // The timer has been executed and cannot be stopped. + ffrt_timer_stop(ffrt_qos_default, handle); + printf("data: %d\n", x); // Set the value of x to 1. + return 0; + } + ``` + +- Example 2: Use a repeating timer. + + ```c + #include + #include + #include "ffrt/timer.h" + + static void test_fun(void *data) + { + *(int *)data += 1; + } + + void (*cb)(void *) = test_fun; + + int main() + { + static int x = 0; + void *data = &x; + uint64_t timeout = 200; + // Start a repeating timer and execute the callback function every 200 ms. + int handle = ffrt_timer_start(ffrt_qos_default, timeout, data, cb, true); + usleep(500000); + // Stops the repeating timer. + ffrt_timer_stop(ffrt_qos_default, handle); + printf("data: %d\n", x); // Set the value of x to 2. + return 0; + } + ``` + +## Loop + +### ffrt_loop_t + +#### Declaration + +```c +typedef void* ffrt_loop_t; +``` + +#### Description + +Provides loop-related functions. + +#### Methods + +##### ffrt_loop_create + +Declaration + +```c +FFRT_C_API ffrt_loop_t ffrt_loop_create(ffrt_queue_t queue); +``` + +Parameters + +- `queue`: a concurrent queue that needs to be bound with a loop. + +Return Values + +- `ffrt_loop_t` object. + +Description + +- Creates a loop and bind a concurrent queue for storing tasks. You can submit a task to the queue so that the task can be executed in the loop. + +##### ffrt_loop_destroy + +Declaration + +```c +FFRT_C_API int ffrt_loop_destroy(ffrt_loop_t loop); +``` + +Parameters + +- `loop`: loop object. + +Return Values + +- The value **0** indicates success, and the value **-1** indicates failure. + +Description + +- Destroys a loop and unbinds it from the queue. + +##### ffrt_loop_run + +Declaration + +```c +FFRT_C_API int ffrt_loop_run(ffrt_loop_t loop); +``` + +Parameters + +- `loop`: loop object. + +Return Values + +- The value **0** indicates success, and the value **-1** indicates failure. + +Description + +- Runs a loop. The thread that invokes this method executes the loop at the same time, executes queue tasks, and listens for the poller and timer. + +##### ffrt_loop_stop + +Declaration + +```c +FFRT_C_API void ffrt_loop_stop(ffrt_loop_t loop); +``` + +Parameters + +- `loop`: loop object. + +Description + +- Stops a loop. This method is invoked to enable the thread that executes the loop to exit the loop. + +##### ffrt_loop_epoll_ctl + +Declaration + +```c +int ffrt_loop_epoll_ctl(ffrt_loop_t loop, int op, int fd, uint32_t events, void *data, ffrt_poller_cb cb) +``` + +Parameters + +- `loop`: loop object. +- `op`: FD operator. For details, see the operation type of **epoll_ctl**. +- `fd`: event descriptor. +- `events`: event. For details, see the event type of **epoll_ctl**. +- `data`: input parameter of the callback function. +- `cb`: callback function. + +Return Values + +- The value **0** indicates success, and the value **-1** indicates failure. + +Description + +- Manages FD listening on the loop. Event listening and callback are processed on the loop thread. + +##### ffrt_loop_timer_start + +Declaration + +```c +FFRT_C_API ffrt_timer_t ffrt_loop_timer_start(ffrt_loop_t loop, uint64_t timeout, void* data, ffrt_timer_cb cb, bool repeat); +``` + +Parameters + +- `loop`: loop object. +- `timeout`: timer timeout, in ms. +- `cb`: callback function after expiration. +- `data`: input parameter of the callback function. +- `repeat`: whether the timer is triggered repeatedly. + +Return Values + +- `ffrt_timer_t`, which indicates the timer handle. + +Description + +- Starts a timer on the loop. The usage is the same as that of `ffrt_timer_start`. The only difference is that the listening and callback execution of the timer are processed on the loop thread. + +##### ffrt_loop_timer_stop + +Declaration + +```c +FFRT_C_API int ffrt_loop_timer_stop(ffrt_loop_t loop, ffrt_timer_t handle); +``` + +Parameters + +- `loop`: loop object. +- `handle`: timer handle. + +Return Values + +- The value **0** indicates success, and the value **-1** indicates failure. + +Description + +- Stops a timer. The usage is the same as that of `ffrt_timer_stop`. + +#### Example + +- Example 1: loop and concurrent queue. + + ```c + #include + #include + #include "ffrt/loop.h" + + void* ThreadFunc(void* p) + { + int ret = ffrt_loop_run(p); + if (ret == 0) { + printf("loop normal operation."); + } + return NULL; + } + + int main() + { + // Create a concurrent queue. + ffrt_queue_attr_t queue_attr; + (void)ffrt_queue_attr_init(&queue_attr); + ffrt_queue_t queue_handle = ffrt_queue_create(ffrt_queue_concurrent, "test_queue", &queue_attr); + + // Create a loop. + ffrt_loop_t loop = ffrt_loop_create(queue_handle); + + // Create a separate thread to perform the loop. + pthread_t thread; + pthread_create(&thread, 0, ThreadFunc, loop); + + // Stop and destroy the loop. + ffrt_loop_stop(loop); + ffrt_loop_destroy(loop); + + // Destroy the concurrent queue. + ffrt_queue_attr_destroy(&queue_attr); + ffrt_queue_destroy(queue_handle); + return 0; + } + ``` + +- Example 2: loop, concurrent queue, and timer. + + ```cpp + #include + #include + #include + #include + #include + #include + #include "ffrt/loop.h" + #include "ffrt/cpp/task.h" + + void* ThreadFunc(void* p) + { + ffrt_loop_run(p); + return nullptr; + } + + static void test_fun(void* data) + { + *(int*)data += 1; + } + + static void (*cb)(void*) = test_fun; + + void testCallBack(void *data, unsigned int events) {} + + struct TestData { + int fd; + uint64_t expected; + }; + + int main() + { + // Create a concurrent queue. + ffrt_queue_attr_t queue_attr; + (void)ffrt_queue_attr_init(&queue_attr); + ffrt_queue_t queue_handle = ffrt_queue_create(ffrt_queue_concurrent, "test_queue", &queue_attr); + + // Create a loop. + auto loop = ffrt_loop_create(queue_handle); + int result1 = 0; + + // Submit a task to the loop queue. + std::function &&basicFunc1 = [&result1]() { result1 += 10; }; + ffrt_task_handle_t task = ffrt_queue_submit_h(queue_handle, ffrt::create_function_wrapper(basicFunc1, ffrt_function_kind_queue), nullptr); + + // Create a separate thread to perform the loop. + pthread_t thread; + pthread_create(&thread, 0, ThreadFunc, loop); + + static int x = 0; + int* xf = &x; + void* data = xf; + uint64_t timeout1 = 20; + uint64_t timeout2 = 10; + uint64_t expected = 0xabacadae; + + int testFd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); + struct TestData testData {.fd = testFd, .expected = expected}; + + // Register a timer with the loop. + ffrt_timer_t timeHandle = ffrt_loop_timer_start(loop, timeout1, data, cb, false); + + // Register an FD listener with the loop. + int ret = ffrt_loop_epoll_ctl(loop, EPOLL_CTL_ADD, testFd, EPOLLIN, (void*)(&testData), testCallBack); + if (ret == 0) { + printf("ffrt_loop_epoll_ctl executed successfully.\n"); + } + ssize_t n = write(testFd, &expected, sizeof(uint64_t)); + usleep(25000); + // Delete the FD listener. + ffrt_loop_epoll_ctl(loop, EPOLL_CTL_DEL, testFd, 0, nullptr, nullptr); + + // Stop the loop. + ffrt_loop_stop(loop); + pthread_join(thread, nullptr); + + // Delete the timer. + ffrt_loop_timer_stop(loop, timeHandle); + + // Destroy the loop. + ret = ffrt_loop_destroy(loop); + + // Destroy the concurrent queue. + ffrt_queue_attr_destroy(&queue_attr); + ffrt_queue_destroy(queue_handle); + return 0; + } + ``` diff --git a/en/application-dev/ffrt/ffrt-concurrency-concurrent-queue-c.md b/en/application-dev/ffrt/ffrt-concurrency-concurrent-queue-c.md new file mode 100644 index 0000000000000000000000000000000000000000..ef5f387bffe42b77012c58804476746964a1d7fe --- /dev/null +++ b/en/application-dev/ffrt/ffrt-concurrency-concurrent-queue-c.md @@ -0,0 +1,172 @@ +# Function Flow Runtime Concurrent Queue (C) + +## Overview + +The FFRT concurrent queue provides the capability of setting the priority and queue concurrency. Tasks in the queue can be executed on multiple threads at the same time, achieving better effect. + +- **Queue concurrency**: You can set the maximum concurrency of a queue to control the number of tasks that can be executed at the same time. This avoids system resource impact caused by excessive concurrent tasks, ensuring system stability and performance. +- **Task priority**: You can set a priority for each task. Different tasks are scheduled and executed strictly based on the priority. Tasks with the same priority are executed in sequence. Tasks with higher priorities are executed prior to those with lower priorities to ensure that key tasks can be processed in a timely manner. + +## Example: Bank Service System + +For example, each customer (common customer or VIP customer) submits a service request to the bank service system. The service request of the VIP customer can be processed first. +The bank system has two windows for handling service requests submitted by customers. You can use the FFRT paradigm to perform the following modeling: + +- **Queuing logic**: concurrent queue. +- **Service window**: concurrency of the concurrent queue, which also equals the number of FFRT Worker threads. +- **Customer level**: priority of concurrent queue tasks. + +The implementation code is as follows: + +```c +#include +#include +#include "ffrt/queue.h" +#include "ffrt/task.h" + +ffrt_queue_t create_bank_system(const char *name, int concurrency) +{ + ffrt_queue_attr_t queue_attr; + (void)ffrt_queue_attr_init(&queue_attr); + ffrt_queue_attr_set_max_concurrency(&queue_attr, concurrency); + + // Create a concurrent queue. + ffrt_queue_t queue = ffrt_queue_create(ffrt_queue_concurrent, name, &queue_attr); + + // Destroy the queue attributes after the queue is created. + ffrt_queue_attr_destroy(&queue_attr); + if (!queue) { + printf("create queue failed\n"); + return NULL; + } + + printf("create bank system successfully\n"); + return queue; +} + +void destroy_bank_system(ffrt_queue_t queue_handle) +{ + ffrt_queue_destroy(queue_handle); + printf("destroy bank system successfully\n"); +} + +void bank_business(void *arg) +{ + usleep(100 * 1000); + const char *data = (const char *)arg; + printf("saving or withdraw for %s\n", data); +} + +// Encapsulate the operation of submitting a task to a queue into a function. +ffrt_task_handle_t commit_request(ffrt_queue_t bank, void (*func)(void *), const char *name, + ffrt_queue_priority_t level, int delay) +{ + ffrt_task_attr_t task_attr; + (void)ffrt_task_attr_init(&task_attr); + ffrt_task_attr_set_name(&task_attr, name); + ffrt_task_attr_set_queue_priority(&task_attr, level); + ffrt_task_attr_set_delay(&task_attr, delay); + + return ffrt_queue_submit_h(bank, ffrt_create_function_wrapper(func, NULL, name), &task_attr); +} + +// Encapsulate the operation of canceling a task in a queue into a function. +int cancel_request(ffrt_task_handle_t request) +{ + return ffrt_queue_cancel(request); +} + +// Encapsulate the operation of waiting for a task in a queue into a function. +void wait_for_request(ffrt_task_handle_t task) +{ + ffrt_queue_wait(task); +} + +int main() +{ + ffrt_queue_t bank = create_bank_system("Bank", 2); + if (!bank) { + printf("create bank system failed\n"); + return -1; + } + commit_request(bank, bank_business, "customer1", ffrt_queue_priority_low, 0); + commit_request(bank, bank_business, "customer2", ffrt_queue_priority_low, 0); + commit_request(bank, bank_business, "customer3", ffrt_queue_priority_low, 0); + commit_request(bank, bank_business, "customer4", ffrt_queue_priority_low, 0); + + // VIP customers have the priority to enjoy services. + commit_request(bank, bank_business, "VIP", ffrt_queue_priority_high, 0); + + ffrt_task_handle_t task = commit_request(bank, bank_business, "customer5", ffrt_queue_priority_low, 0); + ffrt_task_handle_t task_last = commit_request(bank, bank_business, "customer6", ffrt_queue_priority_low, 0); + + // Cancel the service for customer 5. + cancel_request(task); + + // Wait until all customer services are complete. + wait_for_request(task_last); + destroy_bank_system(bank); + + return 0; +} +``` + +C-style FFRT construction requires additional encapsulation using common code and is irrelevant to specific service scenarios. + +```c +typedef struct { + ffrt_function_header_t header; + ffrt_function_t func; + ffrt_function_t after_func; + void* arg; +} c_function_t; + +static inline void ffrt_exec_function_wrapper(void* t) +{ + c_function_t* f = (c_function_t *)t; + if (f->func) { + f->func(f->arg); + } +} + +static inline void ffrt_destroy_function_wrapper(void* t) +{ + c_function_t* f = (c_function_t *)t; + if (f->after_func) { + f->after_func(f->arg); + } +} + +#define FFRT_STATIC_ASSERT(cond, msg) int x(int static_assertion_##msg[(cond) ? 1 : -1]) +static inline ffrt_function_header_t *ffrt_create_function_wrapper(const ffrt_function_t func, + const ffrt_function_t after_func, void *arg) +{ + FFRT_STATIC_ASSERT(sizeof(c_function_t) <= ffrt_auto_managed_function_storage_size, + size_of_function_must_be_less_than_ffrt_auto_managed_function_storage_size); + + c_function_t* f = (c_function_t *)ffrt_alloc_auto_managed_function_storage_base(ffrt_function_kind_queue); + f->header.exec = ffrt_exec_function_wrapper; + f->header.destroy = ffrt_destroy_function_wrapper; + f->func = func; + f->after_func = after_func; + f->arg = arg; + return (ffrt_function_header_t *)f; +} +``` + +## Available APIs + +The main FFRT APIs involved in the preceding example are as follows: + +| Name | Description | +| -------------------------------------------------------------------------------------------------- | ---------------------- | +| [ffrt_queue_create](ffrt-api-guideline-c.md#ffrt_queue_create) | Creates a queue. | +| [ffrt_queue_destroy](ffrt-api-guideline-c.md#ffrt_queue_destroy) | Destroys a queue. | +| [ffrt_task_attr_set_queue_priority](ffrt-api-guideline-c.md#ffrt_task_attr_set_queue_priority) | Sets the priority of a task in a queue. | +| [ffrt_queue_attr_set_max_concurrency](ffrt-api-guideline-c.md#ffrt_queue_attr_set_max_concurrency) | Sets the concurrency of the concurrent queue.| + +## Constraints + +1. `ffrt_queue_attr_t` must be initialized by calling `ffrt_queue_attr_init` before the attribute is set or obtained. If `ffrt_queue_attr_t` is no longer used, `ffrt_queue_attr_destroy` needs to be explicitly called to release resources. +2. `ffrt_queue_t` must explicitly call `ffrt_queue_destroy` to release resources before the process exits. +3. It is recommended that the maximum concurrency of a concurrent queue be within a proper range. If the value is too large, it is meaningless to exceed the number of Worker threads. If the value is too small, the system resource utilization may be low. diff --git a/en/application-dev/ffrt/ffrt-concurrency-concurrent-queue-cpp.md b/en/application-dev/ffrt/ffrt-concurrency-concurrent-queue-cpp.md new file mode 100644 index 0000000000000000000000000000000000000000..e29af56f5e573a0d77fff41d08bcf98e14f2495f --- /dev/null +++ b/en/application-dev/ffrt/ffrt-concurrency-concurrent-queue-cpp.md @@ -0,0 +1,116 @@ +# Function Flow Runtime Concurrent Queue (C++) + +## Overview + +The FFRT concurrent queue provides the capability of setting the priority and queue concurrency. Tasks in the queue can be executed on multiple threads at the same time, achieving better effect. + +- **Queue concurrency**: You can set the maximum concurrency of a queue to control the number of tasks that can be executed at the same time. This avoids system resource impact caused by excessive concurrent tasks, ensuring system stability and performance. +- **Task priority**: You can set a priority for each task. Different tasks are scheduled and executed strictly based on the priority. Tasks with the same priority are executed in sequence. Tasks with higher priorities are executed prior to those with lower priorities to ensure that key tasks can be processed in a timely manner. + +## Example: Bank Service System + +For example, each customer (common customer or VIP customer) submits a service request to the bank service system. The service request of the VIP customer can be processed first. +The bank system has two windows for handling service requests submitted by customers. You can use the FFRT paradigm to perform the following modeling: + +- **Queuing logic**: concurrent queue. +- **Service window**: concurrency of the concurrent queue, which also equals the number of FFRT Worker threads. +- **Customer level**: priority of concurrent queue tasks. + +The implementation code is as follows: + +```cpp +#include +#include +#include "ffrt/cpp/queue.h" +#include "ffrt/cpp/task.h" + +class BankQueueSystem { +private: + std::unique_ptr queue_; + +public: + BankQueueSystem(const char *name, int concurrency) + { + queue_ = std::make_unique( + ffrt::queue_concurrent, name, ffrt::queue_attr().max_concurrency(concurrency)); + std::cout << "bank system has been initialized" << std::endl; + } + + ~BankQueueSystem() + { + queue_ = nullptr; + std::cout << "bank system has been destroyed" << std::endl; + } + + // Start to queue, that is, submit queue tasks. + ffrt::task_handle Enter(const std::function& func, const char *name, ffrt_queue_priority_t level, int delay) + { + return queue_->submit_h(func, ffrt::task_attr().name(name).priority(level).delay(delay)); + } + + // Exit the queue, that is, cancel queue tasks. + int Exit(const ffrt::task_handle &t) + { + return queue_->cancel(t); + } + + // Wait for tasks in the queue. + void Wait(const ffrt::task_handle& handle) + { + queue_->wait(handle); + } +}; + +void BankBusiness() +{ + usleep(100 * 1000); + std::cout << "saving or withdraw ordinary customer" << std::endl; +} + +void BankBusinessVIP() +{ + usleep(100 * 1000); + std::cout << "saving or withdraw VIP" << std::endl; +} + +int main() +{ + BankQueueSystem bankQueue("Bank", 2); + + bankQueue.Enter(BankBusiness, "customer1", ffrt_queue_priority_low, 0); + bankQueue.Enter(BankBusiness, "customer2", ffrt_queue_priority_low, 0); + bankQueue.Enter(BankBusiness, "customer3", ffrt_queue_priority_low, 0); + bankQueue.Enter(BankBusiness, "customer4", ffrt_queue_priority_low, 0); + + // VIP customers have the priority to enjoy services. + bankQueue.Enter(BankBusinessVIP, "vip", ffrt_queue_priority_high, 0); + + ffrt::task_handle handle = bankQueue.Enter(BankBusiness, "customer5", ffrt_queue_priority_low, 0); + ffrt::task_handle handleLast = bankQueue.Enter(BankBusiness, "customer6", ffrt_queue_priority_low, 0); + + // Cancel the service for customer 5. + bankQueue.Exit(handle); + + // Wait until all customer services are complete. + bankQueue.Wait(handleLast); + return 0; +} +``` + +## Available APIs + +The main FFRT APIs involved in the preceding example are as follows: + +| Name | Description | +| ----------------------------------------------------------------------------------------------------------------------------- | ------------ | +| class [task_attr](https://gitee.com/openharmony/resourceschedule_ffrt/blob/master/docs/ffrt-api-guideline-cpp.md#task_attr) | Task attribute class.| +| class [queue_attr](https://gitee.com/openharmony/resourceschedule_ffrt/blob/master/docs/ffrt-api-guideline-cpp.md#queue_attr) | Queue attribute class.| +| class [queue](https://gitee.com/openharmony/resourceschedule_ffrt/blob/master/docs/ffrt-api-guideline-cpp.md#queue) | Queue class. | + +> **NOTE** +> +> For details about how to use FFRT C++ APIs, see [Using FFRT C++ APIs](ffrt-development-guideline.md#using-ffrt-c-api-1). + +## Constraints + +1. It is recommended that the maximum concurrency of a concurrent queue be within a proper range. If the value is too large, it is meaningless to exceed the number of Worker threads. If the value is too small, the system resource utilization may be low. diff --git a/en/application-dev/ffrt/ffrt-concurrency-graph-c.md b/en/application-dev/ffrt/ffrt-concurrency-graph-c.md new file mode 100644 index 0000000000000000000000000000000000000000..8a15d88ac56eaecbbd83c611539d75de9aa1b552 --- /dev/null +++ b/en/application-dev/ffrt/ffrt-concurrency-graph-c.md @@ -0,0 +1,293 @@ +# Function Flow Runtime Task Graph (C) + +## Overview + +The FFRT task graph supports task dependency and data dependency. Each node in the task graph indicates a task, and each edge indicates the dependency between tasks. Task dependency is classified into input dependency (`in_deps`) and output dependency (`out_deps`). + +You can use either of the following ways to build a task graph: + +- Use the task dependency to build a task graph. The task `handle` is used to indicate a task object. +- Use the data dependency to build a task graph. The data object is abstracted as a data signature, and each data signature uniquely indicates a data object. + +### Task dependency + +> **NOTE** +> +> When a task handle appears in `in_deps`, the corresponding task is the previous task. When a task handle appears in `out_deps`, the corresponding task is the subsequent task. + +Task dependency applies to scenarios where tasks have specific sequence or logical process requirements. For example: + +- Tasks with sequence. For example, a data preprocessing task is executed before a model training task. +- Logic process control. For example, in a typical commodity transaction process, orders are placed, followed by production and then logistics transportation. +- Multi-level chain: For example, during video processing, you can perform tasks such as transcoding, generating thumbnails, adding watermarks, and releasing the final video. + +### Data Dependency + +> **NOTE** +> +> When the signature of a data object appears in `in_deps` of a task, the task is referred to as a consumer task that executes without modifying the original input data object. +> When the signature of a data object appears in `out_deps` of a task, the task is referred to as a producer task that updates the output data object's content to create a new version. + +Data dependency applies to scenarios where tasks are triggered by data production and consumption relationships. + +A data object may have multiple versions. Each version corresponds to one producer task and zero, one, or more consumer tasks. A sequence of the data object versions and the version-specific producer task and consumer tasks are defined according to the delivery sequence of the producer task and consumer tasks. + +When all producer tasks and consumer tasks of the data object of all the available versions are executed, the data dependency is removed. In this case, the task enters the ready state and can be scheduled for execution. + +FFRT can dynamically build producer/consumer-based data dependencies between tasks at runtime and perform scheduling based on the task data dependency status, including: + +- Producer-Consumer dependency + + A dependency formed between the producer task of a data object of a specific version and a consumer task of the data object of the same version. It is also referred to as a read-after-write dependency. + +- Consumer-Producer dependency + + A dependency formed between a consumer task of a data object of a specific version and the producer task of the data object of the next version. It is also referred to as a write-after-read dependency. + +- Producer-Producer dependency + + A dependency formed between the producer task of a data object of a specific version and a producer task of the data object of the next version. It is also referred to as a write-after-write dependency. + +For example, the relationship between a group of tasks and data A is expressed as follows: + +```cpp +task1(OUT A); +task2(IN A); +task3(IN A); +task4(OUT A); +task5(OUT A); +``` + +![image](figures/ffrt_figure3.png) + +For ease of description, circles are used to represent tasks and squares are used to represent data. + +The following conclusions can be drawn: + +- task1 and task2/task3 form a producer-consumer dependency. This means that task2/task3 can read data A only after task1 writes data A. +- task2/task3 and task4 form a consumer-producer dependency. This means that task4 can write data A only after task2/task3 reads data A. +- task 4 and task 5 form a producer-producer dependency. This means that task 5 can write data A only after task 4 writes data A. + +## Example: Streaming Video Processing + +A user uploads a video to the platform. The processing steps include: parsing, transcoding, generating a thumbnail, adding a watermark, and releasing the video. Transcoding and thumbnail generation can occur simultaneously. The following figure shows the task process. + +![image](figures/ffrt_figure1.png) + +The FFRT provides task graph that can describe the task dependency and parallelize the preceding video processing process. The code is as follows: + +```c +#include +#include "ffrt/task.h" + +static inline void ffrt_submit_c(ffrt_function_t func, const ffrt_function_t after_func, + void* arg, const ffrt_deps_t* in_deps, const ffrt_deps_t* out_deps, const ffrt_task_attr_t* attr) +{ + ffrt_submit_base(ffrt_create_function_wrapper(func, after_func, arg), in_deps, out_deps, attr); +} + +static inline ffrt_task_handle_t ffrt_submit_h_c(ffrt_function_t func, const ffrt_function_t after_func, + void* arg, const ffrt_deps_t* in_deps, const ffrt_deps_t* out_deps, const ffrt_task_attr_t* attr) +{ + return ffrt_submit_h_base(ffrt_create_function_wrapper(func, after_func, arg), in_deps, out_deps, attr); +} + +void func_TaskA(void* arg) +{ + printf("Parse\n"); +} + +void func_TaskB(void* arg) +{ + printf("Transcode\n"); +} + +void func_TaskC(void* arg) +{ + printf("Generate a thumbnail\n"); +} + +void func_TaskD(void* arg) +{ + printf("Add watermark\n"); +} + +void func_TaskE(void* arg) +{ + printf("Release\n"); +} + +int main() +{ + // Submit task A. + ffrt_task_handle_t hTaskA = ffrt_submit_h_c(func_TaskA, NULL, NULL, NULL, NULL, NULL); + + // Submit tasks B and C. + ffrt_dependence_t taskA_deps[] = {{ffrt_dependence_task, hTaskA}}; + ffrt_deps_t dTaskA = {1, taskA_deps}; + ffrt_task_handle_t hTaskB = ffrt_submit_h_c(func_TaskB, NULL, NULL, &dTaskA, NULL, NULL); + ffrt_task_handle_t hTaskC = ffrt_submit_h_c(func_TaskC, NULL, NULL, &dTaskA, NULL, NULL); + + // Submit task D. + ffrt_dependence_t taskBC_deps[] = {{ffrt_dependence_task, hTaskB}, {ffrt_dependence_task, hTaskC}}; + ffrt_deps_t dTaskBC = {2, taskBC_deps}; + ffrt_task_handle_t hTaskD = ffrt_submit_h_c(func_TaskD, NULL, NULL, &dTaskBC, NULL, NULL); + + // Submit task E. + ffrt_dependence_t taskD_deps[] = {{ffrt_dependence_task, hTaskD}}; + ffrt_deps_t dTaskD = {1, taskD_deps}; + ffrt_submit_c(func_TaskE, NULL, NULL, &dTaskD, NULL, NULL); + + // Wait until all tasks are complete. + ffrt_wait(); + return 0; +} +``` + +C-style FFRT construction requires additional encapsulation using common code and is irrelevant to specific service scenarios. + +```c +typedef struct { + ffrt_function_header_t header; + ffrt_function_t func; + ffrt_function_t after_func; + void* arg; +} c_function_t; + +static inline void ffrt_exec_function_wrapper(void* t) +{ + c_function_t* f = (c_function_t *)t; + if (f->func) { + f->func(f->arg); + } +} + +static inline void ffrt_destroy_function_wrapper(void* t) +{ + c_function_t* f = (c_function_t *)t; + if (f->after_func) { + f->after_func(f->arg); + } +} + +#define FFRT_STATIC_ASSERT(cond, msg) int x(int static_assertion_##msg[(cond) ? 1 : -1]) +static inline ffrt_function_header_t *ffrt_create_function_wrapper(const ffrt_function_t func, + const ffrt_function_t after_func, void *arg) +{ + FFRT_STATIC_ASSERT(sizeof(c_function_t) <= ffrt_auto_managed_function_storage_size, + size_of_function_must_be_less_than_ffrt_auto_managed_function_storage_size); + + c_function_t* f = (c_function_t *)ffrt_alloc_auto_managed_function_storage_base(ffrt_function_kind_general); + f->header.exec = ffrt_exec_function_wrapper; + f->header.destroy = ffrt_destroy_function_wrapper; + f->func = func; + f->after_func = after_func; + f->arg = arg; + return (ffrt_function_header_t *)f; +} +``` + +The expected output may be as follows: + +```plain +Video parsing +Video transcoding +Thumbnails generation +Watermark adding +Video release +``` + +## Example: Fibonacci Sequence + +Each number in the Fibonacci sequence is the sum of the first two numbers. The process of calculating the Fibonacci number can well express the task dependency through the data object. The code for calculating the Fibonacci number using the FFRT framework is as follows: + +```c +#include +#include "ffrt/task.h" + +typedef struct { + int x; + int* y; +} fib_ffrt_s; + +static inline void ffrt_submit_c(ffrt_function_t func, const ffrt_function_t after_func, + void* arg, const ffrt_deps_t* in_deps, const ffrt_deps_t* out_deps, const ffrt_task_attr_t* attr) +{ + ffrt_submit_base(ffrt_create_function_wrapper(func, after_func, arg), in_deps, out_deps, attr); +} + +void fib_ffrt(void* arg) +{ + fib_ffrt_s* p = (fib_ffrt_s*)arg; + int x = p->x; + int* y = p->y; + + if (x <= 1) { + *y = x; + } else { + int y1, y2; + fib_ffrt_s s1 = {x - 1, &y1}; + fib_ffrt_s s2 = {x - 2, &y2}; + + // Build data dependencies. + ffrt_dependence_t dx_deps[] = {{ffrt_dependence_data, &x}}; + ffrt_deps_t dx = {1, dx_deps}; + ffrt_dependence_t dy1_deps[] = {{ffrt_dependence_data, &y1}}; + ffrt_deps_t dy1 = {1, dy1_deps}; + ffrt_dependence_t dy2_deps[] = {{ffrt_dependence_data, &y2}}; + ffrt_deps_t dy2 = {1, dy2_deps}; + ffrt_dependence_t dy12_deps[] = {{ffrt_dependence_data, &y1}, {ffrt_dependence_data, &y2}}; + ffrt_deps_t dy12 = {2, dy12_deps}; + + // Submit tasks separately. + ffrt_submit_c(fib_ffrt, NULL, &s1, &dx, &dy1, NULL); + ffrt_submit_c(fib_ffrt, NULL, &s2, &dx, &dy2, NULL); + + // Wait until the task is complete. + ffrt_wait_deps(&dy12); + *y = y1 + y2; + } +} + +int main() +{ + int r; + fib_ffrt_s s = {5, &r}; + ffrt_dependence_t dr_deps[] = {{ffrt_dependence_data, &r}}; + ffrt_deps_t dr = {1, dr_deps}; + ffrt_submit_c(fib_ffrt, NULL, &s, NULL, &dr, NULL); + + // Wait until the task is complete. + ffrt_wait_deps(&dr); + printf("Fibonacci(5) is %d\n", r); + return 0; +} +``` + +Expected output: + +```plain +Fibonacci(5) is 5 +``` + +In the example, `fibonacci(x-1)` and `fibonacci(x-2)` are submitted to FFRT as two tasks. After the two tasks are complete, the results are accumulated. Although a single task is split into two subtasks, the subtasks can be further split. Therefore, the concurrency of the entire computational graph is very high. + +Each task forms a call tree in the FFRT. + +![image](figures/ffrt_figure2.png) + +## Available APIs + +The main FFRT APIs involved in the preceding example are as follows: + +| Name | Description | +| ---------------------------------------------------------------- | -------------------------------------- | +| [ffrt_submit_base](ffrt-api-guideline-c.md#ffrt_submit_base) | Submits a task. | +| [ffrt_submit_h_base](ffrt-api-guideline-c.md#ffrt_submit_h_base) | Submits a task, and obtains the task handle. | +| [ffrt_wait_deps](ffrt-api-guideline-c.md#ffrt_wait_deps) | Waits until the dependent tasks are complete.| + +## Constraints + +- For `ffrt_submit_base`, the total number of input dependencies and output dependencies of each task cannot exceed 8. +- For `ffrt_submit_h_base`, the total number of input dependencies and output dependencies of each task cannot exceed 7. +- When a parameter is used as both an input dependency and an output dependency, it is counted as one dependency. For example, if the input dependency is `{&x}` and the output dependency is also `{&x}`, then the number of dependencies is 1. diff --git a/en/application-dev/ffrt/ffrt-concurrency-graph-cpp.md b/en/application-dev/ffrt/ffrt-concurrency-graph-cpp.md new file mode 100644 index 0000000000000000000000000000000000000000..cf316c5949fe22355bb6541e83552a3637ca4586 --- /dev/null +++ b/en/application-dev/ffrt/ffrt-concurrency-graph-cpp.md @@ -0,0 +1,171 @@ +# Function Flow Runtime Task Graph (C++) + +## Overview + +The FFRT task graph supports task dependency and data dependency. Each node in the task graph indicates a task, and each edge indicates the dependency between tasks. Task dependency is classified into input dependency (`in_deps`) and output dependency (`out_deps`). + +You can use either of the following ways to build a task graph: + +- Use the task dependency to build a task graph. The task `handle` is used to indicate a task object. +- Use the data dependency to build a task graph. The data object is abstracted as a data signature, and each data signature uniquely indicates a data object. + +### Task dependency + +> **NOTE** +> +> When a task handle appears in `in_deps`, the corresponding task is the previous task. When a task handle appears in `out_deps`, the corresponding task is the subsequent task. + +Task dependency applies to scenarios where tasks have specific sequence or logical process requirements. For example: + +- Tasks with sequence. For example, a data preprocessing task is executed before a model training task. +- Logic process control. For example, in a typical commodity transaction process, orders are placed, followed by production and then logistics transportation. +- Multi-level chain: For example, during video processing, you can perform tasks such as transcoding, generating thumbnails, adding watermarks, and releasing the final video. + +### Data Dependency + +> **NOTE** +> +> When the signature of a data object appears in `in_deps` of a task, the task is referred to as a consumer task that executes without modifying the original input data object. +> When the signature of a data object appears in `out_deps` of a task, the task is referred to as a producer task that updates the output data object's content to create a new version. + +Data dependency applies to scenarios where tasks are triggered by data production and consumption relationships. + +A data object may have multiple versions. Each version corresponds to one producer task and zero, one, or more consumer tasks. A sequence of the data object versions and the version-specific producer task and consumer tasks are defined according to the delivery sequence of the producer task and consumer tasks. + +When all producer tasks and consumer tasks of the data object of all the available versions are executed, the data dependency is removed. In this case, the task enters the ready state and can be scheduled for execution. + +FFRT can dynamically build producer/consumer-based data dependencies between tasks at runtime and perform scheduling based on the task data dependency status, including: + +- Producer-Consumer dependency + + A dependency formed between the producer task of a data object of a specific version and a consumer task of the data object of the same version. It is also referred to as a read-after-write dependency. + +- Consumer-Producer dependency + + A dependency formed between a consumer task of a data object of a specific version and the producer task of the data object of the next version. It is also referred to as a write-after-read dependency. + +- Producer-Producer dependency + + A dependency formed between the producer task of a data object of a specific version and a producer task of the data object of the next version. It is also referred to as a write-after-write dependency. + +For example, the relationship between a group of tasks and data A is expressed as follows: + +```cpp +task1(OUT A); +task2(IN A); +task3(IN A); +task4(OUT A); +task5(OUT A); +``` + +![image](figures/ffrt_figure3.png) + +For ease of description, circles are used to represent tasks and squares are used to represent data. + +The following conclusions can be drawn: + +- task1 and task2/task3 form a producer-consumer dependency. This means that task2/task3 can read data A only after task1 writes data A. +- task2/task3 and task4 form a consumer-producer dependency. This means that task4 can write data A only after task2/task3 reads data A. +- task 4 and task 5 form a producer-producer dependency. This means that task 5 can write data A only after task 4 writes data A. + +## Example: Streaming Video Processing + +A user uploads a video to the platform. The processing steps include: parsing, transcoding, generating a thumbnail, adding watermark, and releasing the video. Transcoding and thumbnail generation can occur simultaneously. The following figure shows the task process. + +![image](figures/ffrt_figure1.png) + +The FFRT provides task graph that can describe the task dependency and parallelize the preceding video processing process. The code is as follows: + +```cpp +#include +#include "ffrt/cpp/task.h" + +int main() +{ + // Submit a task. + auto handle_A = ffrt::submit_h([] () { std::cout << "Parse" << std::endl; }); + auto handle_B = ffrt::submit_h([] () { std::cout << "Transcode" << std::endl; }, {handle_A}); + auto handle_C = ffrt::submit_h([] () { std::cout << "Generate a thumbnail" << std::endl; }, {handle_A}); + auto handle_D = ffrt::submit_h([] () { std::cout << "Add watermark" << std::endl; }, {handle_B, handle_C}); + ffrt::submit([] () { std::cout << "Release" << std::endl; }, {handle_D}); + + // Wait until all tasks are complete. + ffrt::wait(); + return 0; +} +``` + +The expected output may be as follows: + +```plain +Video parsing +Video transcoding +Thumbnails generation +Watermark adding +Video release +``` + +## Example: Fibonacci Sequence + +Each number in the Fibonacci sequence is the sum of the first two numbers. The process of calculating the Fibonacci number can well express the task dependency through the data object. The code for calculating the Fibonacci number using the FFRT framework is as follows: + +```cpp +#include +#include "ffrt/cpp/task.h" + +void Fib(int x, int& y) +{ + if (x <= 1) { + y = x; + } else { + int y1, y2; + + // Submit the task and build data dependencies. + ffrt::submit([&]() { Fib(x - 1, y1); }, {&x}, {&y1}); + ffrt::submit([&]() { Fib(x - 2, y2); }, {&x}, {&y2}); + + // Wait until the task is complete. + ffrt::wait({&y1, &y2}); + y = y1 + y2; + } +} + +int main() +{ + int y; + Fib(5, y); + std::cout << "Fibonacci(5) is " << y << std::endl; +} +``` + +Expected output: + +```plain +Fibonacci(5) is 5 +``` + +In the example, `fibonacci(x-1)` and `fibonacci(x-2)` are submitted to FFRT as two tasks. After the two tasks are complete, the results are accumulated. Although a single task is split into two subtasks, the subtasks can be further split. Therefore, the concurrency of the entire computational graph is very high. + +Each task forms a call tree in the FFRT. + +![image](figures/ffrt_figure2.png) + +## Available APIs + +The main FFRT APIs involved in the preceding example are as follows: + +| Name | Description | +| ------------------------------------------------------------------------------------------------------------------- | -------------------------------- | +| [submit](https://gitee.com/openharmony/resourceschedule_ffrt/blob/master/docs/ffrt-api-guideline-cpp.md#submit) | Submits a task. | +| [submit_h](https://gitee.com/openharmony/resourceschedule_ffrt/blob/master/docs/ffrt-api-guideline-cpp.md#submit_h) | Submits a task, and obtains the task handle.| +| [wait](https://gitee.com/openharmony/resourceschedule_ffrt/blob/master/docs/ffrt-api-guideline-cpp.md#wait) | Waits until all tasks in the context are complete. | + +> **NOTE** +> +> For details about how to use FFRT C++ APIs, see [Using FFRT C++ APIs](ffrt-development-guideline.md#using-ffrt-c-api-1). + +## Constraints + +- For `submit`, the total number of input dependencies and output dependencies of each task cannot exceed 8. +- For `submit_h`, the total number of input dependencies and output dependencies of each task cannot exceed 7. +- When a parameter is used as both an input dependency and an output dependency, it is counted as one dependency. For example, if the input dependency is `{&x}` and the output dependency is also `{&x}`, then the number of dependencies is 1. diff --git a/en/application-dev/ffrt/ffrt-concurrency-paradigm.md b/en/application-dev/ffrt/ffrt-concurrency-paradigm.md new file mode 100644 index 0000000000000000000000000000000000000000..9b2f3c498207ac49cb096f832c129065a6791f3e --- /dev/null +++ b/en/application-dev/ffrt/ffrt-concurrency-paradigm.md @@ -0,0 +1,43 @@ +# Function Flow Runtime Paradigms + +To cope with fixed task execution sequence, flexible priority-based scheduling, and complex task dependencies in actual services, Function Flow Runtime (FFRT) supports three paradigms: serial queue, concurrent queue, and task graph. + +## Serial Queue + +The serial queue is often used for: + +1. **Sequential execution**: The serial queue ensures that tasks are executed one by one in sequence, avoiding data inconsistency and errors caused by out-of-order execution. +2. **Data security**: The serial queue prevents multiple threads from competing for shared resources concurrently, ensuring data consistency and security. +3. **Task scheduling**: The serial queue can schedule the execution sequence of complex tasks. For example, it ensures that a task begins after the previous one completes when tasks with multiple dependencies are performed. +4. **Simplified development**: The serial queue is more simple and clear compared with manual mutex management and synchronization. You only need to add tasks to the queue for automatic system scheduling and execution, simplifying development and debugging. +5. **Resource management**: The serial queue can limit the number of concurrent tasks and avoid resource competition and overload, optimizing system resource usage. + +![image](figures/ffrt_figure4.png) + +For details about the development sample, see [Serial Queue (C)](ffrt-concurrency-serial-queue-c.md) or [Serial Queue (C++)](ffrt-concurrency-serial-queue-cpp.md). + +## Concurrent Queue + +The concurrent queue is often used for: + +1. **Concurrency improvement**: The concurrent queue allows concurrent execution of multiple tasks, fully utilizing the computing capability of the multi-core processor and significantly improving the concurrency and overall performance of the system. +2. **Efficient resource utilization**: The concurrent queue can allocate tasks to available CPU cores to optimize resource usage and reduce task waiting time and resource competition. +3. **Flexible task scheduling**: The concurrent queue can schedule tasks based on priorities and QoS to ensure that key tasks can be executed in a timely manner and improve the system response speed. +4. **Resource impact prevention**: The concurrent queue can set the maximum concurrency to avoid system resource impact caused by excessive concurrent tasks, ensuring system stability and performance. + +![image](figures/ffrt_figure5.png) + +For details about the development sample, see [Concurrent Queue (C)](ffrt-concurrency-concurrent-queue-c.md) or [Concurrent Queue (C++)](ffrt-concurrency-concurrent-queue-cpp.md). + +## Task Graph + +The task graph is often used for: + +1. **Complex task dependency**: In actual applications, tasks have complex dependencies among each other. The task graph represents task dependencies by using directed graphs to clearly manage and schedule tasks. +2. **Dynamic task scheduling**: The task graph can dynamically adjust task scheduling and dependencies and execution sequence according to the running conditions. +3. **Concurrent task execution**: The task graph allows multiple independent tasks to be executed concurrently, making full use of system computing resources and improving concurrency and execution efficiency. +4. **Structured concurrency**: The clear task lifecycles and dependencies in the task graph ensure that the creation and completion of concurrent tasks are explicit in the code structure, reducing the complexity and errors of concurrent programming. + +![image](figures/ffrt_figure6.png) + +For details about the development sample, see [Task Graph (C)](ffrt-concurrency-graph-c.md) or [Task Graph (C++)](ffrt-concurrency-graph-cpp.md). diff --git a/en/application-dev/ffrt/ffrt-concurrency-serial-queue-c.md b/en/application-dev/ffrt/ffrt-concurrency-serial-queue-c.md new file mode 100644 index 0000000000000000000000000000000000000000..a6d549bed2d9c17af4d849aa94b8b0b23b0d6e17 --- /dev/null +++ b/en/application-dev/ffrt/ffrt-concurrency-serial-queue-c.md @@ -0,0 +1,196 @@ +# Function Flow Runtime Serial Queue (C) + +## Overview + +The FFRT serial queue is implemented based on the coroutine scheduling model. It provides efficient message queue functions and supports multiple service scenarios, such as asynchronous communication, mobile data peak clipping, lock-free status and resource management, and architecture decoupling. The following functions are supported: + +- **Queue creation and destruction**: The queue name and priority can be specified during creation. Each queue is equivalent to an independent thread. Tasks in the queue are executed asynchronously compared with user threads. +- **Task delay**: The `delay` can be set when a task is submitted. The unit is `μs`. The delayed task will be scheduled and executed after `uptime` (submission time + delay time). +- **Serial scheduling**: Tasks in the same queue are sorted in ascending order of `uptime` and executed in serial mode. Ensure that the next task starts to be executed only after the previous task in the queue is complete. +- **Task canceling**: You can cancel a task that is not dequeued based on the task handle. The task cannot be canceled if it has been started or completed. +- **Task waiting**: You can wait for a task to complete based on the task handle. When a specified task is complete, all tasks whose `uptime` is earlier than the specified task in the queue have been executed. +- **Task priority**: You can set the priority of a single task when submitting the task. Priorities take effect only after a task is dequeued relative to other system loads, and do not affect the serial task order in the same queue. If the task priority is not set, the priority of the queue is inherited by default. + +## Example: Asynchronous Log System + +The following is an example of implementing an asynchronous log system. The main thread submits the log task to the queue, and the background thread obtains the task from the queue and writes the task to the file. It ensures the log sequence and prevents the main thread from being blocked by the file write operation. + +With FFRT APIs, you only need to focus on service logic implementation and do not need to pay attention to asynchronous thread management, thread security, and scheduling efficiency. + +The example simplifies the logic for handling exceptions and ensuring thread security. The code is as follows: + +```c +#include +#include +#include +#include +#include "ffrt/queue.h" +#include "ffrt/task.h" + +typedef struct { + FILE *logFile; // Pointer to a log file. + ffrt_queue_t queue; // Task queue. +} logger_t; + +// Global logger variable. +logger_t* g_logger = NULL; + +// Initialize the log system. +logger_t *logger_create(const char *filename) +{ + logger_t *logger = (logger_t *)malloc(sizeof(logger_t)); + if (!logger) { + perror("Failed to allocate memory for logger_t"); + return NULL; + } + + // Open the log file. + logger->logFile = fopen(filename, "a"); + if (!logger->logFile) { + perror("Failed to open log file"); + free(logger); + return NULL; + } + printf("Log file opened: %s\n", filename); + + // Create a task queue. + logger->queue = ffrt_queue_create(ffrt_queue_serial, "logger_queue_c", NULL); + if (!logger->queue) { + perror("Failed to create queue"); + fclose(logger->logFile); + free(logger); + return NULL; + } + + return logger; +} + +// Destroy the log system. +void logger_destroy(logger_t *logger) +{ + if (logger) { + // Destroy the queue. + if (logger->queue) { + ffrt_queue_destroy(logger->queue); + } + + // Close the log file. + if (logger->logFile) { + fclose(logger->logFile); + printf("Log file closed\n"); + } + + free(logger); + } +} + +// Log task. +void write_task(void *arg) +{ + char *message = (char *)arg; + if (g_logger && g_logger->logFile) { + fprintf(g_logger->logFile, "%s\n", message); + fflush(g_logger->logFile); + } + + free(message); +} + +// Add a log task. +void logger_log(logger_t *logger, const char *message) +{ + if (!logger || !logger->queue) { + return; + } + + // Copy the message string. + char *messageCopy = strdup(message); + if (!messageCopy) { + perror("Failed to allocate memory for message"); + return; + } + + ffrt_queue_submit(logger->queue, ffrt_create_function_wrapper(write_task, NULL, messageCopy), NULL); +} + +int main() +{ + // Initialize the global logger. + g_logger = logger_create("log_c.txt"); + if (!g_logger) { + return -1; + } + + // Use the global logger to add a log task. + logger_log(g_logger, "Log message 1"); + logger_log(g_logger, "Log message 2"); + logger_log(g_logger, "Log message 3"); + + // Simulate the main thread to continue executing other tasks. + sleep(1); + + // Destroy the global logger. + logger_destroy(g_logger); + g_logger = NULL; + return 0; +} +``` + +C-style FFRT construction requires additional encapsulation using common code and is irrelevant to specific service scenarios. + +```c +typedef struct { + ffrt_function_header_t header; + ffrt_function_t func; + ffrt_function_t after_func; + void* arg; +} c_function_t; + +static inline void ffrt_exec_function_wrapper(void* t) +{ + c_function_t* f = (c_function_t *)t; + if (f->func) { + f->func(f->arg); + } +} + +static inline void ffrt_destroy_function_wrapper(void* t) +{ + c_function_t* f = (c_function_t *)t; + if (f->after_func) { + f->after_func(f->arg); + } +} + +#define FFRT_STATIC_ASSERT(cond, msg) int x(int static_assertion_##msg[(cond) ? 1 : -1]) +static inline ffrt_function_header_t *ffrt_create_function_wrapper(const ffrt_function_t func, + const ffrt_function_t after_func, void *arg) +{ + FFRT_STATIC_ASSERT(sizeof(c_function_t) <= ffrt_auto_managed_function_storage_size, + size_of_function_must_be_less_than_ffrt_auto_managed_function_storage_size); + + c_function_t* f = (c_function_t *)ffrt_alloc_auto_managed_function_storage_base(ffrt_function_kind_queue); + f->header.exec = ffrt_exec_function_wrapper; + f->header.destroy = ffrt_destroy_function_wrapper; + f->func = func; + f->after_func = after_func; + f->arg = arg; + return (ffrt_function_header_t *)f; +} +``` + +## Available APIs + +The main FFRT APIs involved in the preceding example are as follows: + +| Name | Description | +| ---------------------------------------------------------------- | ------------------------------ | +| [ffrt_queue_create](ffrt-api-guideline-c.md#ffrt_queue_create) | Creates a queue. | +| [ffrt_queue_destroy](ffrt-api-guideline-c.md#ffrt_queue_destroy) | Destroys a queue. | +| [ffrt_queue_submit](ffrt-api-guideline-c.md#ffrt_queue_submit) | Submits a task to a queue.| + +## Constraints + +- **Avoid submitting ultra-long tasks.** The FFRT has a built-in process-level queue task timeout detection mechanism. When the execution time of a serial task exceeds the preset threshold (30 seconds by default), the system prints and reports exception logs and triggers the preset process timeout callback function (if configured). +- **Use synchronization primitives correctly.** Do not use `std::mutex`, `std::condition_variable`, or `std::recursive_mutex` in the task closure submitted to FFRT. As synchronization primitives in the standard library will occupy the FFRT Worker thread for a long time, you should use the synchronization primitives provided by FFRT: `ffrt::mutex`, `ffrt::condition_variable`, or `ffrt::recursive_mutex`. The usage is the same as that of the standard library. +- **Manage queues in global variables.** If serial queues are managed in global variables and destroyed with service processes, pay attention to lifecycle decoupling in the test program. When the test is complete, the serial queue needs to be explicitly released. Other resources can be released with global variables. The reason is that global variables are destructed after the main function ends, and the release of serial queues depends on other resources in the FFRT framework, and the resources may have been destroyed. diff --git a/en/application-dev/ffrt/ffrt-concurrency-serial-queue-cpp.md b/en/application-dev/ffrt/ffrt-concurrency-serial-queue-cpp.md new file mode 100644 index 0000000000000000000000000000000000000000..99a66f177de9cdf54ba569e0bf489db761e30b52 --- /dev/null +++ b/en/application-dev/ffrt/ffrt-concurrency-serial-queue-cpp.md @@ -0,0 +1,99 @@ +# Function Flow Runtime Serial Queue (C++) + +## Overview + +The FFRT serial queue is implemented based on the coroutine scheduling model. It provides efficient message queue functions and supports multiple service scenarios, such as asynchronous communication, mobile data peak clipping, lock-free status and resource management, and architecture decoupling. The following functions are supported: + +- **Queue creation and destruction**: The queue name and priority can be specified during creation. Each queue is equivalent to an independent thread. Tasks in the queue are executed asynchronously compared with user threads. +- **Task delay**: The `delay` can be set when a task is submitted. The unit is `μs`. The delayed task will be scheduled and executed after `uptime` (submission time + delay time). +- **Serial scheduling**: Tasks in the same queue are sorted in ascending order of `uptime` and executed in serial mode. Ensure that the next task starts to be executed only after the previous task in the queue is complete. +- **Task canceling**: You can cancel a task that is not dequeued based on the task handle. The task cannot be canceled if it has been started or completed. +- **Task waiting**: You can wait for a task to complete based on the task handle. When a specified task is complete, all tasks whose `uptime` is earlier than the specified task in the queue have been executed. +- **Task priority**: You can set the priority of a single task when submitting the task. Priorities take effect only after a task is dequeued relative to other system loads, and do not affect the serial task order in the same queue. If the task priority is not set, the priority of the queue is inherited by default. + +## Example: Asynchronous Log System + +The following is an example of implementing an asynchronous log system. The main thread submits the log task to the queue, and the background thread obtains the task from the queue and writes the task to the file. It ensures the log sequence and prevents the main thread from being blocked by the file write operation. + +With FFRT APIs, you only need to focus on service logic implementation and do not need to pay attention to asynchronous thread management, thread security, and scheduling efficiency. + +The example simplifies the logic for handling exceptions and ensuring thread security. The code is as follows: + +```cpp +#include +#include +#include +#include +#include "ffrt/cpp/queue.h" + +class Logger { +public: + Logger(const std::string& filename) + { + // Create a queue. + queue_ = std::make_unique("loggerQueue"); + + // Open a file in append mode. + logFile_.open(filename, std::ios::app); + if (!logFile_.is_open()) { + throw std::runtime_error("Failed to open log file: " + filename); + } + std::cout << "Log file opened: " << filename << std::endl; + } + + ~Logger() { + // Destroy the queue. + queue_ = nullptr; + + if (logFile_.is_open()) { + logFile_.close(); + std::cout << "Log file closed" << std::endl; + } + } + + // Add a log task. + void log(const std::string& message) { + queue_->submit([this, message] { + logFile_ << message << std::endl; + }); + } + +private: + std::ofstream logFile_; + std::unique_ptr queue_; +}; + +int main() +{ + Logger logger("log.txt"); + + // The main thread adds the log task. + logger.log("Log message 1"); + logger.log("Log message 2"); + logger.log("Log message 3"); + + // Simulate the main thread to continue executing other tasks. + std::this_thread::sleep_for(std::chrono::seconds(1)); + + return 0; +} +``` + +## Available APIs + +The main FFRT APIs involved in the preceding example are as follows: + +| Name | Description | +| --------------------------------------------------------------------------------------------------------------------- | -------------- | +| class [queue](https://gitee.com/openharmony/resourceschedule_ffrt/blob/master/docs/ffrt-api-guideline-cpp.md#queue) | Queue class. | +| [sleep_for](https://gitee.com/openharmony/resourceschedule_ffrt/blob/master/docs/ffrt-api-guideline-cpp.md#sleep_for) | Delays a task for some time.| + +> **NOTE** +> +> For details about how to use FFRT C++ APIs, see [Using FFRT C++ APIs](ffrt-development-guideline.md#using-ffrt-c-api-1). + +## Constraints + +- **Avoid submitting ultra-long tasks.** The FFRT has a built-in process-level queue task timeout detection mechanism. When the execution time of a serial task exceeds the preset threshold (30 seconds by default), the system prints and reports exception logs and triggers the preset process timeout callback function (if configured). +- **Use synchronization primitives correctly.** Do not use `std::mutex`, `std::condition_variable`, or `std::recursive_mutex` in the task closure submitted to FFRT. As synchronization primitives in the standard library will occupy the FFRT Worker thread for a long time, you should use the synchronization primitives provided by FFRT: `ffrt::mutex`, `ffrt::condition_variable`, or `ffrt::recursive_mutex`. The usage is the same as that of the standard library. +- **Manage queues in global variables.** If serial queues are managed in global variables and destroyed with service processes, pay attention to lifecycle decoupling in the test program. When the test is complete, the serial queue needs to be explicitly released. Other resources can be released with global variables. The reason is that global variables are destructed after the main function ends, and the release of serial queues depends on other resources in the FFRT framework, and the resources may have been destroyed. diff --git a/en/application-dev/ffrt/ffrt-development-guideline.md b/en/application-dev/ffrt/ffrt-development-guideline.md index 602f6492c3016433f6e31d3b9f85817817541f8e..f93297a801ac76fccadaa472426a908b6d2a7c47 100644 --- a/en/application-dev/ffrt/ffrt-development-guideline.md +++ b/en/application-dev/ffrt/ffrt-development-guideline.md @@ -1,2387 +1,258 @@ # Function Flow Runtime Development -## When to Use - -Function Flow is a task-based and data-driven concurrent programming model that allows you to develop an application by creating tasks and describing their dependencies. Function Flow Runtime (FFRT) is a software runtime library that works with the Function Flow programming model. It is used to schedule and execute tasks of an application developed on the Function Flow programming model. Specifically, FFRT automatically and concurrently schedules and executes tasks of the application based on the task dependency status and available resources, so that you can focus on feature development. - -This topic walks you through how to implement parallel programming based on the Function Flow programming model and FFRT. - -## Available APIs - -| API | Description | -| ------------------------------------------------------------ | ------------------------------------------------------------ | -| ffrt_condattr_init (ffrt_condattr_t* attr) | Initializes a condition variable attribute.| -| ffrt_condattr_destroy(ffrt_condattr_t* attr) | Destroys a condition variable attribute.| -| ffrt_condattr_setclock(ffrt_condattr_t* attr, ffrt_clockid_t clock) | Sets the clock of a condition variable attribute.| -| ffrt_condattr_getclock(const ffrt_condattr_t* attr, ffrt_clockid_t* clock) | Obtains the clock of a condition variable attribute. | -| ffrt_cond_init(ffrt_cond_t* cond, const ffrt_condattr_t* attr) | Initializes a condition variable. | -| ffrt_cond_signal(ffrt_cond_t* cond) | Unblocks at least one of the threads that are blocked on a condition variable.| -| ffrt_cond_broadcast(ffrt_cond_t* cond) | Unblocks all threads currently blocked on a condition variable.| -| ffrt_cond_wait(ffrt_cond_t* cond, ffrt_mutex_t* mutex) | Blocks the calling thread on a condition variable.| -| ffrt_cond_timedwait(ffrt_cond_t* cond, ffrt_mutex_t* mutex, const struct timespec* time_point) | Blocks the calling thread on a condition variable for a given duration.| -| ffrt_cond_destroy(ffrt_cond_t* cond) | Destroys a condition variable.| -| ffrt_mutex_init(ffrt_mutex_t* mutex, const ffrt_mutexattr_t* attr) | Initializes a mutex.| -| ffrt_mutex_lock(ffrt_mutex_t* mutex) | Locks a mutex.| -| ffrt_mutex_unlock(ffrt_mutex_t* mutex) | Unlocks a mutex.| -| ffrt_mutex_trylock(ffrt_mutex_t* mutex) | Attempts to lock a mutex.| -| ffrt_mutex_destroy(ffrt_mutex_t* mutex) | Destroys a mutex.| -| ffrt_queue_attr_init(ffrt_queue_attr_t* attr) | Initializes a queue attribute.| -| ffrt_queue_attr_destroy(ffrt_queue_attr_t* attr) | Destroys a queue attribute.| -| ffrt_queue_attr_set_qos(ffrt_queue_attr_t* attr, ffrt_qos_t qos) | Sets the queue QoS.| -| ffrt_queue_attr_get_qos(const ffrt_queue_attr_t* attr) | Obtains the queue QoS.| -| ffrt_queue_create(ffrt_queue_type_t type, const char* name, const ffrt_queue_attr_t* attr) | Creates a queue.| -| ffrt_queue_destroy(ffrt_queue_t queue) | Destroys a queue.| -| ffrt_queue_submit(ffrt_queue_t queue, ffrt_function_header_t* f, const ffrt_task_attr_t* attr) | Submits a task to a queue.| -| ffrt_queue_submit_h(ffrt_queue_t queue, ffrt_function_header_t* f, const ffrt_task_attr_t* attr) | Submits a task to a queue, and obtains the task handle.| -| ffrt_queue_wait(ffrt_task_handle_t handle) | Waits until a task in the queue is complete.| -| ffrt_queue_cancel(ffrt_task_handle_t handle) | Cancels a task in the queue.| -| ffrt_queue_attr_set_max_concurrency(ffrt_queue_attr_t* attr, const int max_concurrency) | Sets the maximum concurrency for a queue, which must be a concurrent queue.| -| ffrt_queue_attr_get_max_concurrency(ffrt_queue_attr_t* attr) | Obtains the maximum concurrency of a queue, which must be a concurrent queue.| -| ffrt_get_main_queue() | Obtains the main thread queue.| -| ffrt_get_current_queue() | Obtains the ArkTS Worker thread queue.| -| ffrt_usleep(uint64_t usec) | Suspends the calling thread for a given duration.| -| ffrt_yield(void) | Passes control to other tasks so that they can be executed.| -| ffrt_task_attr_init(ffrt_task_attr_t* attr) | Initializes a task attribute.| -| ffrt_task_attr_set_name(ffrt_task_attr_t* attr, const char* name) | Sets a task name.| -| ffrt_task_attr_get_name(const ffrt_task_attr_t* attr) | Obtains a task name.| -| ffrt_task_attr_destroy(ffrt_task_attr_t* attr) | Destroys a task attribute.| -| ffrt_task_attr_set_qos(ffrt_task_attr_t* attr, ffrt_qos_t qos) | Sets the task QoS.| -| ffrt_task_attr_get_qos(const ffrt_task_attr_t* attr) | Obtains the task QoS.| -| ffrt_task_attr_set_delay(ffrt_task_attr_t* attr, uint64_t delay_us) | Sets the task delay time.| -| ffrt_task_attr_get_delay(const ffrt_task_attr_t* attr) | Obtains the task delay time.| -| ffrt_task_attr_set_queue_priority(ffrt_task_attr_t* attr, ffrt_queue_priority_t priority) | Sets the task priority in the queue.| -| ffrt_task_attr_get_queue_priority(const ffrt_task_attr_t* attr) | Obtains the task priority in the queue.| -| ffrt_this_task_get_qos() | Obtains the QoS of this task.| -| ffrt_this_task_update_qos(ffrt_qos_t qos) | Updates the QoS of this task.| -| ffrt_this_task_get_id(void) | Obtains the ID of this task.| -| ffrt_alloc_auto_managed_function_storage_base(ffrt_function_kind_t kind) | Applies for memory for the function execution structure.| -| ffrt_submit_base(ffrt_function_header_t* f, const ffrt_deps_t* in_deps, const ffrt_deps_t* out_deps, const ffrt_task_attr_t* attr) | Submits a task.| -| ffrt_submit_h_base(ffrt_function_header_t* f, const ffrt_deps_t* in_deps, const ffrt_deps_t* out_deps, const ffrt_task_attr_t* attr) | Submits a task, and obtains the task handle.| -| ffrt_task_handle_destroy(ffrt_task_handle_t handle) | Destroys a task handle.| -| ffrt_skip(ffrt_task_handle_t handle) | Skips a task.| -| ffrt_wait_deps(const ffrt_deps_t* deps) | Waits until the dependent tasks are complete.| -| ffrt_loop_create(ffrt_queue_t queue) | Creates a loop.| -| ffrt_loop_destroy(ffrt_loop_t loop) | Destroys a loop.| -| ffrt_loop_run(ffrt_loop_t loop) | Runs a loop.| -| ffrt_loop_stop(ffrt_loop_t loop) | Stops a loop.| -| ffrt_loop_epoll_ctl(ffrt_loop_t loop, int op, int fd, uint32_t events, void* data, ffrt_poller_cb cb) | Manages listening events on a loop.| -| ffrt_loop_timer_start(ffrt_loop_t loop, uint64_t timeout, void* data, ffrt_timer_cb cb, bool repeat) | Starts the timer on a loop.| -| ffrt_loop_timer_stop(ffrt_loop_t loop, ffrt_timer_t handle) | Stops the timer on a loop.| -| ffrt_timer_start(ffrt_qos_t qos, uint64_t timeout, void* data, ffrt_timer_cb cb, bool repeat) | Starts the timer.| -| ffrt_timer_stop(ffrt_qos_t qos, ffrt_timer_t handle); | Stops the timer.| - -## API Introduction - - -### Task Management APIs - -#### ffrt_submit_base - -Exports an FFRT dynamic library. You can encapsulate this API into the C API **ffrt_submit** for binary compatibility. - -##### Declaration - -```{.c} -const int ffrt_auto_managed_function_storage_size = 64 + sizeof(ffrt_function_header_t); -typedef enum { - ffrt_function_kind_general, - ffrt_function_kind_queue -} ffrt_function_kind_t; - -void* ffrt_alloc_auto_managed_function_storage_base(ffrt_function_kind_t kind); - -typedef void(*ffrt_function_t)(void*); -typedef struct { - ffrt_function_t exec; - ffrt_function_t destroy; - uint64_t reserve[2]; -} ffrt_function_header_t; - -void ffrt_submit_base(ffrt_function_header_t* func, const ffrt_deps_t* in_deps, const ffrt_deps_t* out_deps, const ffrt_task_attr_t* attr); -``` - -##### Parameters - -`kind` - -Subtype of **function**. It is used to optimize the internal data structure. The default value is **ffrt_function_kind_general**. - -`func` - -Pointer to the CPU function. The struct executed by the pointer describes two function pointers, namely, **exec** and **destroy**, according to the **ffrt_function_header_t** definition. FFRT executes and destroys the task by using the two function pointers. - -`in_deps` - -* Optional. -* Input dependencies of the task. FFRT establishes the dependency by using the virtual address of the data as the data signature. - -`out_deps` - -* Optional. - -* Output dependencies of the task. - - **NOTE** - - The dependency is essentially a value. FFRT cannot determine whether the value is reasonable. It always treats the input value reasonable. However, you are not advised to use inappropriate values such as **NULL**, **1**, or **2** to establish dependencies because doing this will establish unnecessary dependencies and affect concurrency. Instead, use the actual memory address. - -`attr` - -* Optional. -* Task attribute, such as QoS. For details, see [ffrt_task_attr_t](#ffrt_task_attr_t). - -##### Return value - -N/A - -##### Description -* You are advised to encapsulate **ffrt_submit_base** first. For details, see **Example** below. -* As an underlying capability, **ffrt_submit_base** must meet the following requirements: - * The **func** pointer can be allocated by calling **ffrt_alloc_auto_managed_function_storage_base**, and the two function pointers in the struct must be in the specified sequence (**exec** prior to **destroy**). - * The memory allocated by calling **ffrt_alloc_auto_managed_function_storage_base** is of the size specified by **ffrt_auto_managed_function_storage_size**. Its lifecycle is managed by FFRT. When the task is complete, FFRT automatically releases the memory. -* The following two function pointers are defined in **ffrt_function_header_t**: - * **exec**: describes how the task is executed. It is called by FFRT to execute the task. - * **destroy**: describes how a task is destroyed. It is called by FFRT to destroy the task. - -##### Example - - -```{.c} -template -struct function { - template - function(ffrt_function_header_t h, CT&& c) : header(h), closure(std::forward(c)) {} - ffrt_function_header_t header; - T closure; -}; - -template -void exec_function_wrapper(void* t) -{ - auto f = (function>*)t; - f->closure(); -} - -template -void destroy_function_wrapper(void* t) -{ - auto f = (function>*)t; - f->closure = nullptr; -} - -template -inline ffrt_function_header_t* create_function_wrapper(T&& func) -{ - using function_type = function>; - static_assert(sizeof(function_type) <= ffrt_auto_managed_function_storage_size, - "size of function must be less than ffrt_auto_managed_function_storage_size"); - - auto p = ffrt_alloc_auto_managed_function_storage_base(ffrt_function_kind_general); - auto f = new (p) function_type( - {exec_function_wrapper, destroy_function_wrapper}, - std::forward(func)); - return (ffrt_function_header_t*)f; -} - -static inline void submit(std::function&& func) -{ - return ffrt_submit_base(create_function_wrapper(std::move(func)), NULL, NULL, NULL); -} -``` - -#### ffrt_wait - -- Used together with **ffrt_submit_base**. -- Waits by suspending the current execution context, until the specified data is produced or all subtasks of the current task are complete. - -##### Declaration - -```{.c} -void ffrt_wait_deps(ffrt_deps_t* deps); -void ffrt_wait(); -``` - -##### Parameters - -`deps` - -Virtual addresses of the data to be produced. These addresses may be used as **out_deps** in **submit()** of some tasks. For details about how to generate the dependency, see **ffrt_deps_t**. Note that a null pointer indicates no dependency. - -##### Return value - -N/A - -##### Description -* **ffrt_wait_deps(deps)** is used to suspend code execution before the data specified by **deps** is produced. -* **ffrt_wait()** is used to suspend code execution before all subtasks (excluding grandchild tasks and lower-level subtasks) submitted by the current context are complete. -* This API can be called inside or outside an FFRT task. -* **ffrt_wait_deps(deps)** or **ffrt_wait()** called outside an FFRT task can be sensed by the OS, and therefore it is more expensive than that called inside an FFRT task. As such, you are advised to use **ffrt_wait()** inside an FFRT task whenever possible. - -##### Example - -**Recursive Fibonacci** - -The Fibonacci Sequence implemented in serial mode is as follows: - -```{.c} -#include - -void fib(int x, int* y) { - if (x <= 1) { - *y = x; - } else { - int y1, y2; - fib(x - 1, &y1); - fib(x - 2, &y2); - *y = y1 + y2; - } -} -int main(int narg, char** argv) -{ - int r; - fib(10, &r); - printf("fibonacci 10: %d\n", r); - return 0; -} -``` - -Use FFRT to implement the Fibonacci Sequence in parallel mode: (For Fibonacci, the computing workload of a single task is small and parallel acceleration is not required. However, this pattern requires high flexibility of the parallel programming model.) - -```{.c} -#include -#include "ffrt.h" // All header files related to FFRT are included. - -typedef struct { - int x; - int* y; -} fib_ffrt_s; - -typedef struct { - ffrt_function_header_t header; - ffrt_function_t func; - ffrt_function_t after_func; - void* arg; -} c_function; - -static void ffrt_exec_function_wrapper(void* t) -{ - c_function* f = (c_function*)t; - if (f->func) { - f->func(f->arg); - } -} - -static void ffrt_destroy_function_wrapper(void* t) -{ - c_function* f = (c_function*)t; - if (f->after_func) { - f->after_func(f->arg); - } -} - -#define FFRT_STATIC_ASSERT(cond, msg) int x(int static_assertion_##msg[(cond) ? 1 : -1]) -static inline ffrt_function_header_t* ffrt_create_function_wrapper(const ffrt_function_t func, - const ffrt_function_t after_func, void* arg) -{ - FFRT_STATIC_ASSERT(sizeof(c_function) <= ffrt_auto_managed_function_storage_size, - size_of_function_must_be_less_than_ffrt_auto_managed_function_storage_size); - c_function* f = (c_function*)ffrt_alloc_auto_managed_function_storage_base(ffrt_function_kind_general); - f->header.exec = ffrt_exec_function_wrapper; - f->header.destroy = ffrt_destroy_function_wrapper; - f->func = func; - f->after_func = after_func; - f->arg = arg; - return (ffrt_function_header_t*)f; -} - -static inline void ffrt_submit_c(ffrt_function_t func, const ffrt_function_t after_func, - void* arg, const ffrt_deps_t* in_deps, const ffrt_deps_t* out_deps, const ffrt_task_attr_t* attr) -{ - ffrt_submit_base(ffrt_create_function_wrapper(func, after_func, arg), in_deps, out_deps, attr); -} - -void fib_ffrt(void* arg) -{ - fib_ffrt_s* p = (fib_ffrt_s*)arg; - int x = p->x; - int* y = p->y; - - if (x <= 1) { - *y = x; - } else { - int y1, y2; - fib_ffrt_s s1 = {x - 1, &y1}; - fib_ffrt_s s2 = {x - 2, &y2}; - const std::vector dx_deps = {{ffrt_dependence_data, &x}}; - ffrt_deps_t dx{static_cast(dx_deps.size()), dx_deps.data()}; - const std::vector dy1_deps = {{ffrt_dependence_data, &y1}}; - ffrt_deps_t dy1{static_cast(dy1_deps.size()), dy1_deps.data()}; - const std::vector dy2_deps = {{ffrt_dependence_data, &y2}}; - ffrt_deps_t dy2{static_cast(dy2_deps.size()), dy2_deps.data()}; - const std::vector dy12_deps = {{ffrt_dependence_data, &y1}, {ffrt_dependence_data, &y2}}; - ffrt_deps_t dy12{static_cast(dy12_deps.size()), dy12_deps.data()}; - ffrt_submit_c(fib_ffrt, NULL, &s1, &dx, &dy1, NULL); - ffrt_submit_c(fib_ffrt, NULL, &s2, &dx, &dy2, NULL); - ffrt_wait_deps(&dy12); - *y = y1 + y2; - } -} - -int main(int narg, char** argv) -{ - int r; - fib_ffrt_s s = {10, &r}; - const std::vector dr_deps = {{ffrt_dependence_data, &r}}; - ffrt_deps_t dr{static_cast(dr_deps.size()), dr_deps.data()}; - ffrt_submit_c(fib_ffrt, NULL, &s, NULL, &dr, NULL); - ffrt_wait_deps(&dr); - printf("fibonacci 10: %d\n", r); - return 0; -} -``` - -**NOTE** - -(1) fibonacci (x-1) and fibonacci (x-2) are submitted to FFRT as two tasks. After the two tasks are complete, the results are accumulated. - -(2) A single task can be split into only two subtasks, but the subtasks can be further split. Therefore, the entire computing graph delivers a high DOP, and a call tree is formed between tasks in FFRT. - - - -> **NOTE** -> -> The preceding implementation requires you to explicitly manage the data lifecycle and encapsulate input parameters, making the code complex. - -#### ffrt_deps_t - -Abstraction of dependency arrays in C code, logically equivalent to **std::vector** in C++ code. - -##### Declaration - -```{.c} -typedef enum { - ffrt_dependence_data, - ffrt_dependence_task, -} ffrt_dependence_type_t; - -typedef struct { - ffrt_dependence_type_t type; - const void* ptr; -} ffrt_dependence_t; - -typedef struct { - uint32_t len; - const ffrt_dependence_t* items; -} ffrt_deps_t; -``` - -##### Parameters - -`len` - -Number of dependent signatures. The value must be greater than or equal to 0. - -`item` - -Pointer to the start address of each signature. - -`type` - -Dependency type, which can be data dependency or task dependency. - -`ptr` - -Actual address of the dependent signature content. - -##### Return value - -N/A - -##### Description - -**item** is the start address pointer of each signature. The pointer can point to the heap space or stack space, but the allocated space must be greater than or equal to len * sizeof(ffrt_dependence_t). - -##### Example - -Create a data dependency or task dependency. - -```{.c} -// Create ffrt_deps_t on which the data depends. -int x = 0; -const std::vector in_deps = {{ffrt_dependence_data, &x}}; -ffrt_deps_t in{static_cast(in_deps.size()), in_deps.data()}; - -// Submit a task, and obtain a task handle. -ffrt_task_handle_t task = ffrt_submit_h_base( - ffrt_create_function_wrapper(OnePlusForTest, NULL, &a), NULL, NULL, &attr); -// Create ffrt_deps_t on which the task depends. -const std::vector wait_deps = {{ffrt_dependence_task, task}}; -ffrt_deps_t wait{static_cast(wait_deps.size()), wait_deps.data()}; -``` - -#### ffrt_task_attr_t - -Auxiliary class for defining task attributes. It is used together with **ffrt_submit_base**. - -##### Declaration - -```{.c} -typedef enum { - ffrt_qos_inherent = -1, - ffrt_qos_background, - ffrt_qos_utility, - ffrt_qos_default, - ffrt_qos_user_initiated, -} ffrt_qos_default_t; - -typedef int ffrt_qos_t; - -typedef struct { - uint32_t storage[(ffrt_task_attr_storage_size + sizeof(uint32_t) - 1) / sizeof(uint32_t)]; -} ffrt_task_attr_t; -typedef void* ffrt_task_handle_t; - -int ffrt_task_attr_init(ffrt_task_attr_t* attr); -void ffrt_task_attr_destroy(ffrt_task_attr_t* attr); -void ffrt_task_attr_set_qos(ffrt_task_attr_t* attr, ffrt_qos_t qos); -ffrt_qos_t ffrt_task_attr_get_qos(const ffrt_task_attr_t* attr); -void ffrt_task_attr_set_name(ffrt_task_attr_t* attr, const char* name); -const char* ffrt_task_attr_get_name(const ffrt_task_attr_t* attr); -void ffrt_task_attr_set_delay(ffrt_task_attr_t* attr, uint64_t delay_us); -uint64_t ffrt_task_attr_get_delay(const ffrt_task_attr_t* attr); -``` - -##### Parameters - -`attr` - -Handle of the target task attribute. - -`qos` - -* QoS. -* **ffrt_qos_inherent** is a QoS type, indicating that the QoS of the task to be submitted by **ffrt_submit** inherits the QoS of the current task. - -`delay_us` - -Delay for executing the task, in μs. - -##### Return value - -N/A - -##### Description -* The content passed by **attr** is fetched and stored when **ffrt_submit** is being executed. You can destroy the content on receiving the return value of **ffrt_submit**. -* Conventions: - * If **task_attr** is not used for QoS setting during task submission, the QoS of the task is **ffrt_qos_default**. - * If **task_attr** is set to **ffrt_qos_inherent** during task submission, the QoS of the task to be submitted is the same as that of the current task. If a task with the **ffrt_qos_inherent** attribute is submitted outside an FFRT task, its QoS is **ffrt_qos_default**. - * In other cases, the QoS value passed in is used. -* You need to set the **ffrt_task_attr_t** object to null or destroy the object. For the same **ffrt_task_attr_t** object, **ffrt_task_attr_destroy** can be called only once. Otherwise, undefined behavior may occur. -* If **task_attr** is accessed after **ffrt_task_attr_destroy** is called, undefined behavior may occur. - -##### Example - -Submit a task with the QoS set to **ffrt_qos_background**: - -```{.c} -#include -#include "ffrt.h" - -void my_print(void* arg) -{ - printf("hello ffrt\n"); -} - -typedef struct { - ffrt_function_header_t header; - ffrt_function_t func; - ffrt_function_t after_func; - void* arg; -} c_function; - -static void ffrt_exec_function_wrapper(void* t) -{ - c_function* f = (c_function*)t; - if (f->func) { - f->func(f->arg); - } -} - -static void ffrt_destroy_function_wrapper(void* t) -{ - c_function* f = (c_function*)t; - if (f->after_func) { - f->after_func(f->arg); - } -} - -#define FFRT_STATIC_ASSERT(cond, msg) int x(int static_assertion_##msg[(cond) ? 1 : -1]) -static inline ffrt_function_header_t* ffrt_create_function_wrapper(const ffrt_function_t func, - const ffrt_function_t after_func, void* arg) -{ - FFRT_STATIC_ASSERT(sizeof(c_function) <= ffrt_auto_managed_function_storage_size, - size_of_function_must_be_less_than_ffrt_auto_managed_function_storage_size); - c_function* f = (c_function*)ffrt_alloc_auto_managed_function_storage_base(ffrt_function_kind_general); - f->header.exec = ffrt_exec_function_wrapper; - f->header.destroy = ffrt_destroy_function_wrapper; - f->func = func; - f->after_func = after_func; - f->arg = arg; - return (ffrt_function_header_t*)f; -} - -static inline void ffrt_submit_c(ffrt_function_t func, const ffrt_function_t after_func, - void* arg, const ffrt_deps_t* in_deps, const ffrt_deps_t* out_deps, const ffrt_task_attr_t* attr) -{ - ffrt_submit_base(ffrt_create_function_wrapper(func, after_func, arg), in_deps, out_deps, attr); -} - -int main(int narg, char** argv) -{ - ffrt_task_attr_t attr; - ffrt_task_attr_init(&attr); - ffrt_task_attr_set_qos(&attr, ffrt_qos_background); - ffrt_task_attr_set_delay(&attr, 10000); - ffrt_submit_c(my_print, NULL, NULL, NULL, NULL, &attr); - ffrt_task_attr_destroy(&attr); - ffrt_wait(); - return 0; -} -``` - - - - -#### ffrt_submit_h_base - -Submits a task to the scheduler. Different from **ffrt_submit_base**, **ffrt_submit_h_base** returns a task handle. The handle can be used to establish the dependency between tasks or implement synchronization in the **wait** statements. - -##### Declaration - -```{.c} -typedef void* ffrt_task_handle_t; - -ffrt_task_handle_t ffrt_submit_h_base(ffrt_function_t func, void* arg, const ffrt_deps_t* in_deps, const ffrt_deps_t* out_deps, const ffrt_task_attr_t* attr); -void ffrt_task_handle_destroy(ffrt_task_handle_t handle); -``` - -##### Parameters - -`func` - -Pointer to the CPU function. The struct executed by the pointer describes two function pointers, namely, **exec** and **destroy**, according to the **ffrt_function_header_t** definition. FFRT executes and destroys the task by using the two function pointers. - -`in_deps` - -* Optional. -* Input dependencies of the task. FFRT establishes the dependency by using the virtual address of the data as the data signature. - -`out_deps` - -* Optional. - -* Output dependencies of the task. - - **NOTE** - - The dependency is essentially a value. FFRT cannot determine whether the value is reasonable. It always treats the input value reasonable. However, you are not advised to use inappropriate values such as **NULL**, **1**, or **2** to establish dependencies. Instead, use the actual memory address because inappropriate values will establish unnecessary dependencies and affect concurrency. - -`attr` - -* Optional. -* Task attribute, such as QoS. For details, see [ffrt_task_attr_t](#ffrt_task_attr_t). - -##### Return value - -Take handle. The handle can be used to establish the dependency between tasks or implement synchronization in the wait statements. - -##### Description - -* **ffrt_task_handle_t** in the C code must be explicitly destroyed by calling **ffrt_task_handle_destroy**. -* You need to set the **ffrt_task_handle_t** object in the C code to null or destroy the object. For the same **ffrt_task_handle_t** object, **ffrt_task_handle_destroy** can be called only once. Otherwise, undefined behavior may occur. -* If **ffrt_task_handle_t** is accessed after **ffrt_task_handle_destroy** is called, undefined behavior may occur. - -##### Example - -```{.c} -#include -#include "ffrt.h" - -void func0(void* arg) -{ - printf("hello "); -} - -void func1(void* arg) -{ - (*(int*)arg)++; -} - -void func2(void* arg) -{ - printf("world, x = %d\n", *(int*)arg); -} - -void func3(void* arg) -{ - printf("handle wait"); - (*(int*)arg)++; -} - -typedef struct { - ffrt_function_header_t header; - ffrt_function_t func; - ffrt_function_t after_func; - void* arg; -} c_function; - -static void ffrt_exec_function_wrapper(void* t) -{ - c_function* f = (c_function*)t; - if (f->func) { - f->func(f->arg); - } -} - -static void ffrt_destroy_function_wrapper(void* t) -{ - c_function* f = (c_function*)t; - if (f->after_func) { - f->after_func(f->arg); - } -} - -#define FFRT_STATIC_ASSERT(cond, msg) int x(int static_assertion_##msg[(cond) ? 1 : -1]) -static inline ffrt_function_header_t* ffrt_create_function_wrapper(const ffrt_function_t func, - const ffrt_function_t after_func, void* arg) -{ - FFRT_STATIC_ASSERT(sizeof(c_function) <= ffrt_auto_managed_function_storage_size, - size_of_function_must_be_less_than_ffrt_auto_managed_function_storage_size); - c_function* f = (c_function*)ffrt_alloc_auto_managed_function_storage_base(ffrt_function_kind_general); - f->header.exec = ffrt_exec_function_wrapper; - f->header.destroy = ffrt_destroy_function_wrapper; - f->func = func; - f->after_func = after_func; - f->arg = arg; - return (ffrt_function_header_t*)f; -} - -static inline ffrt_task_handle_t ffrt_submit_h_c(ffrt_function_t func, const ffrt_function_t after_func, - void* arg, const ffrt_deps_t* in_deps, const ffrt_deps_t* out_deps, const ffrt_task_attr_t* attr) -{ - return ffrt_submit_h_base(ffrt_create_function_wrapper(func, after_func, arg), in_deps, out_deps, attr); -} - -static inline void ffrt_submit_c(ffrt_function_t func, const ffrt_function_t after_func, - void* arg, const ffrt_deps_t* in_deps, const ffrt_deps_t* out_deps, const ffrt_task_attr_t* attr) -{ - ffrt_submit_base(ffrt_create_function_wrapper(func, after_func, arg), in_deps, out_deps, attr); -} - - -int main(int narg, char** argv) -{ - // Handle the work with submit. - ffrt_task_handle_t h = ffrt_submit_h_c(func0, NULL, NULL, NULL, NULL, NULL); // not need some data in this task - int x = 1; - const std::vector in_deps = {{ffrt_dependence_data, &x}}; - ffrt_deps_t d2{static_cast(in_deps.size()), in_deps.data()}; - - const std::vector out_deps = {{ffrt_dependence_data, &x}}; - ffrt_deps_t d1{static_cast(out_deps.size()), out_deps.data()}; - - ffrt_submit_c(func1, NULL, &x, NULL, &d1, NULL); - ffrt_submit_c(func2, NULL, &x, &d2, NULL, NULL); // this task depend x and h - ffrt_task_handle_destroy(h); - - // Handle the work with wait. - ffrt_task_handle_t h2 = ffrt_submit_h_c(func3, NULL, &x, NULL, NULL, NULL); - - const std::vector wait_deps = {{ffrt_dependence_task, h2}}; - ffrt_deps_t d3{static_cast(wait_deps.size()), wait_deps.data()}; - ffrt_wait_deps(&d3); - ffrt_task_handle_destroy(h2); - printf("x = %d", x); - ffrt_wait(); - return 0; -} -``` - -Expected output - -``` -hello -handle wait -x = 2 -world, x = 3 -``` - - - -#### ffrt_this_task_get_id - -Obtains the ID of this task. This API is used for maintenance and testing. (The task ID is unique, but the task name may be duplicate.) - -##### Declaration - -```{.c} -uint64_t ffrt_this_task_get_id(); -``` - -##### Parameters - -N/A - -##### Return value - -ID of the task being executed. - -##### Description - -* If this API is called inside a task, the ID of this task is returned. If this API is called outside a task, **0** is returned. -* You can determine whether the function runs on an FFRT or a non-FFRT worker thread based on the return value. -* The task ID starts from 1 and is incremented by 1 each time a task is submitted. The task ID contains 64 bits. Even if one million tasks are submitted per second, it takes 292471.2 years to finish one loop. - -##### Example - -N/A - -#### ffrt_this_task_update_qos - -Updates the QoS of the task being executed. - -##### Declaration - -```{.c} -int ffrt_this_task_update_qos(ffrt_qos_t qos); -``` - -##### Parameters - -`qos` - -New QoS. - -##### Return value - -Returns **0** if the operation is successful; returns a non-zero value otherwise. - -##### Description - -* The QoS update takes effect immediately. -* If the new QoS is different from the current QoS, the task is blocked and then resumed based on the new QoS. -* If the new QoS is the same as the current QoS, the API returns **0** immediately without any processing. -* If this API is called not inside a task, a non-zero value is returned. You can ignore the value or perform other operations. - -##### Example - -N/A - -#### ffrt_this_task_get_qos - -Obtains the QoS of the task being executed. - -##### Declaration - -```{.c} -ffrt_qos_t ffrt_this_task_get_qos(); -``` - -##### Parameters - -NA - -##### Return value - -QoS. - -##### Description - -N/A - -##### Example - -```{.c} -#include "ffrt.h" - -int main(int narg, char** argv) -{ - static int x = 0; - int* xf = &x; - void* data = xf; - uint64_t timeout1 = 20; - - ffrt::submit([=]() { - ffrt_qos_t taskQos = ffrt_this_task_get_qos(); - ffrt_timer_cb cb; - ffrt_timer_start(taskQos, timeout1, data, cb, false); - ffrt_usleep(200); - }, {}, {}); - ffrt::wait(); - return 0; -} - -``` - -### Serial Queue - -Based on the FFRT coroutine scheduling model, the serial queue implements a message queue. Serial tasks are executed in FFRT Worker threads. You do not need to maintain a dedicated thread, making the scheduling overhead lightweight. - -#### ffrt_queue_attr_t - -##### Declaration -```{.c} -typedef struct { - uint32_t storage[(ffrt_queue_attr_storage_size + sizeof(uint32_t) - 1) / sizeof(uint32_t)]; -} ffrt_queue_attr_t; - -int ffrt_queue_attr_init(ffrt_queue_attr_t* attr); -void ffrt_queue_attr_destroy(ffrt_queue_attr_t* attr); -``` - -##### Parameters - -`attr` -Pointer to the uninitialized **ffrt_queue_attr_t** object. - -##### Return value -Returns **0** if the API is called successfully; returns **-1** otherwise. - -##### Description -* An **ffrt_queue_attr_t** object must be created prior to an **ffrt_queue_t** object. -* You need to set the **ffrt_queue_attr_t** object to null or destroy the object. For the same **ffrt_queue_attr_t** object, **ffrt_queue_attr_destroy** can be called only once. Otherwise, undefined behavior may occur. -* If **ffrt_queue_attr_t** is accessed after **ffrt_queue_attr_destroy** is called, undefined behavior may occur. - -##### Example -See the example provided in **ffrt_queue_t**. - -#### ffrt_queue_t - -##### Declaration -```{.c} -typedef enum { ffrt_queue_serial, ffrt_queue_concurrent, ffrt_queue_max } ffrt_queue_type_t; -typedef void* ffrt_queue_t; - -ffrt_queue_t ffrt_queue_create(ffrt_queue_type_t type, const char* name, const ffrt_queue_attr_t* attr) -void ffrt_queue_destroy(ffrt_queue_t queue) -``` - -##### Parameters - -`type` - -Queue type. - -`name` - -Pointer to the queue name. - -`attr` - -Pointer to the queue attribute. For details, see **ffrt_queue_attr_t**. - -##### Return value -Returns the queue created if the API is called successfully; returns a null pointer otherwise. - -##### Description -* Tasks submitted to the queue are executed in sequence. If a task is blocked, the execution sequence of the task cannot be ensured. -* You need to set the **ffrt_queue_t** object to null or destroy the object. For the same **ffrt_queue_t** object, **ffrt_queue_destroy** can be called only once. Otherwise, undefined behavior may occur. -* If **ffrt_queue_t** is accessed after **ffrt_queue_destroy** is called, undefined behavior may occur. - -##### Example -``` -#include -#include "ffrt.h" - -using namespace std; - -template -struct Function { - ffrt_function_header_t header; - T closure; -}; - -template -void ExecFunctionWrapper(void* t) -{ - auto f = reinterpret_cast>*>(t); - f->closure(); -} - -template -void DestroyFunctionWrapper(void* t) -{ - auto f = reinterpret_cast>*>(t); - f = nullptr; -} - -template -static inline ffrt_function_header_t* create_function_wrapper(T&& func, - ffrt_function_kind_t kind = ffrt_function_kind_general) -{ - using function_type = Function>; - auto p = ffrt_alloc_auto_managed_function_storage_base(kind); - auto f = new (p)function_type; - f->header.exec = ExecFunctionWrapper; - f->header.destroy = DestroyFunctionWrapper; - f->closure = std::forward(func); - return reinterpret_cast(f); -} - -int main(int narg, char** argv) -{ - ffrt_queue_attr_t queue_attr; - (void)ffrt_queue_attr_init(&queue_attr); - ffrt_queue_t queue_handle = ffrt_queue_create(ffrt_queue_serial, "test_queue", &queue_attr); - std::function&& queueFunc = [] () {printf("Task done.\n");}; - ffrt_function_header_t* queueFunc_t = create_function_wrapper((queueFunc), ffrt_function_kind_queue); - ffrt_queue_submit(queue_handle, queueFunc_t, nullptr); - - ffrt_queue_attr_destroy(&queue_attr); - ffrt_queue_destroy(queue_handle); -} -``` - -#### ffrt_get_main_queue - -Obtains the main thread queue. - -##### Declaration -```{.c} -ffrt_queue_t ffrt_get_main_queue(); -``` - -##### Parameters - -NA - -##### Return value - -Main thread queue. - -##### Description - -The main thread queue is obtained for the FFRT thread to communicate with the main thread. - -##### Example -```{.c} -This test case must be executed on HarmonyOS. -#include "ffrt.h" - -inline void OnePlusForTest(void* data) -{ - *(int*)data += 1; -} - -int main(int narg, char** argv) -{ - ffrt::queue *serialQueue = new ffrt::queue("ffrt_normal_queue", {}); - ffrt_queue_t mainQueue = ffrt_get_main_queue(); - ffrt_task_attr_t attr; - ffrt_task_attr_init(&attr); - ffrt_task_attr_set_qos(&attr, ffrt_qos_user_initiated); - int result = 0; - std::function&& basicFunc = [&result]() { - OnePlusForTest(static_cast(&result)); - OnePlusForTest(static_cast(&result)); - ffrt_usleep(3000); - }; - - ffrt::task_handle handle = serialQueue->submit_h( - [&] { - result = result + 1; - ffrt_queue_submit(mainQueue, ffrt::create_function_wrapper(basicFunc, ffrt_function_kind_queue), - &attr); - }, - ffrt::task_attr().qos(3).name("ffrt main_queue.")); - - serialQueue->wait(handle); - return 0; -} -``` - -#### ffrt_get_current_queue - -Obtains the ArkTS Worker thread queue. - -##### Declaration -```{.c} -ffrt_queue_t ffrt_get_current_queue(); -``` - -##### Parameters - -NA - -##### Return value - -ArkTS Worker thread queue. - -##### Description - -The ArkTS Worker thread queue is obtained for the FFRT thread to communicate with the ArkTS Worker thread. - -##### Example -```{.c} -// This test case must be executed on HarmonyOS. -#include "ffrt.h" - -inline void OnePlusForTest(void* data) -{ - *(int*)data += 1; -} - -int main(int narg, char** argv) -{ - ffrt::queue *serialQueue = new ffrt::queue("ffrt_normal_queue", {}); - ffrt_queue_t currentQueue = ffrt_get_current_queue(); - ffrt_task_attr_t attr; - ffrt_task_attr_init(&attr); - ffrt_task_attr_set_qos(&attr, ffrt_qos_user_initiated); - int result = 0; - std::function&& basicFunc = [&result]() { - OnePlusForTest(static_cast(&result)); - OnePlusForTest(static_cast(&result)); - ffrt_usleep(3000); - }; - - ffrt::task_handle handle = serialQueue->submit_h( - [&] { - result = result + 1; - ffrt_queue_submit(currentQueue, ffrt::create_function_wrapper(basicFunc, ffrt_function_kind_queue), - &attr); - }, - ffrt::task_attr().qos(3).name("ffrt current_queue.")); - - serialQueue->wait(handle); - return 0; -} -``` - - -### Concurrent Queue - -FFRT supports concurrent queues and allows you to set the concurrency and task priority of a concurrent queue. - -#### ffrt_queue_attr_set_max_concurrency - -Sets the maximum concurrency for a queue, which must be a concurrent queue. - -##### Declaration -```{.c} -void ffrt_queue_attr_set_max_concurrency(ffrt_queue_attr_t* attr, const int max_concurrency); -``` - -##### Parameters - -`attr` - -Pointer to the queue attribute. For details, see **ffrt_queue_attr_t**. - -`max_concurrency` - -Maximum concurrency. If the parameter is set to a value less than or equal to 0, the concurrency 1 is used. - -##### Return value - -NA - -##### Description - -If the concurrency is set to a large value, for example, 100, the actual concurrency may fail to reach the set value due to hardware capability limitations. - -##### Example -```{.c} -#include "ffrt.h" - -int main(int narg, char** argv) -{ - ffrt_queue_attr_t queue_attr; - (void)ffrt_queue_attr_init(&queue_attr); - uint64_t concurrency = 4; - ffrt_queue_attr_set_max_concurrency(&queue_attr, concurrency); - concurrency = ffrt_queue_attr_get_max_concurrency(&queue_attr); - ffrt_queue_attr_destroy(&queue_attr); - printf("concurrency=%lu\n", concurrency); - return 0; -} -``` - -Expected output - -``` -concurrency=4 -``` - -#### ffrt_queue_attr_get_max_concurrency - -Obtains the maximum concurrency of a queue, which must be a concurrent queue. - -##### Declaration -```{.c} -int ffrt_queue_attr_get_max_concurrency(const ffrt_queue_attr_t* attr); -``` - -##### Parameters - -`attr` - -Pointer to the queue attribute. For details, see **ffrt_queue_attr_t**. - -##### Return value - -Maximum concurrency. - -##### Description -N/A - -##### Example -```{.c} -#include "ffrt.h" - -int main(int narg, char** argv) -{ - ffrt_queue_attr_t queue_attr; - (void)ffrt_queue_attr_init(&queue_attr); - uint64_t concurrency = 4; - ffrt_queue_attr_set_max_concurrency(&queue_attr, concurrency); - concurrency = ffrt_queue_attr_get_max_concurrency(&queue_attr); - ffrt_queue_attr_destroy(&queue_attr); - printf("concurrency=%lu\n", concurrency); - return 0; -} -``` - -Expected output - -``` -concurrency=4 -``` - -#### ffrt_task_attr_set_queue_priority -
-Sets the task priority in the queue. - -##### Declaration -```{.c} -/* Task priority */ -typedef enum { -ffrt_queue_priority_immediate = 0, -ffrt_queue_priority_high, -ffrt_queue_priority_low, -ffrt_queue_priority_idle, -} ffrt_queue_priority_t; - -void ffrt_task_attr_set_queue_priority(ffrt_task_attr_t* attr, ffrt_queue_priority_t priority); -``` - -##### Parameters - -`attr` - -Pointer to the task attribute. For details, see **ffrt_task_attr_t**. - -`priority` - -Task priority. Four priorities are supported. For details, see **ffrt_queue_priority_t**. - -##### Return value - -NA - -##### Description -N/A - -##### Example -```{.c} -#include "ffrt.h" - -int main(int narg, char** argv) -{ - ffrt_task_attr_t task_attr; - (void)ffrt_task_attr_init(&task_attr); - ffrt_queue_priority_t priority = ffrt_queue_priority_idle; - ffrt_task_attr_set_queue_priority(&task_attr, priority); - priority = ffrt_task_attr_get_queue_priority(&task_attr); - ffrt_task_attr_destroy(&task_attr); - printf("priority=%d\n", priority); - return 0; -} -``` - -Expected output - -``` -priority=3 -``` - -#### ffrt_task_attr_get_queue_priority - -Obtains the task priority in a queue. - -##### Declaration -```{.c} -ffrt_queue_priority_t ffrt_task_attr_get_queue_priority(const ffrt_task_attr_t* attr); -``` - -##### Parameters - -`attr` - -Pointer to the queue attribute. For details, see **ffrt_queue_attr_t**. - -##### Return value - -Task priority. - -##### Description -N/A - -##### Example -```{.c} -#include "ffrt.h" - -int main(int narg, char** argv) -{ - ffrt_task_attr_t task_attr; - (void)ffrt_task_attr_init(&task_attr); - ffrt_queue_priority_t priority = ffrt_queue_priority_idle; - ffrt_task_attr_set_queue_priority(&task_attr, priority); - priority = ffrt_task_attr_get_queue_priority(&task_attr); - ffrt_task_attr_destroy(&task_attr); - printf("priority=%d\n", priority); - return 0; -} -``` - -Expected output - -``` -priority=3 -``` - -### Synchronization Primitive - -#### ffrt_mutex_t - -Provides performance implementation similar to pthread mutex. - -##### Declaration - -```{.c} -typedef enum { - ffrt_error = -1, - ffrt_success = 0, - ffrt_error_nomem = ENOMEM, - ffrt_error_timedout = ETIMEDOUT, - ffrt_error_busy = EBUSY, - ffrt_error_inval = EINVAL -} ffrt_error_t; - -struct ffrt_mutex_t; - -int ffrt_mutex_init(ffrt_mutex_t* mutex, const ffrt_mutexattr_t* attr); -int ffrt_mutex_lock(ffrt_mutex_t* mutex); -int ffrt_mutex_unlock(ffrt_mutex_t* mutex); -int ffrt_mutex_trylock(ffrt_mutex_t* mutex); -int ffrt_mutex_destroy(ffrt_mutex_t* mutex); -``` - -##### Parameters - -`attr` - -Attribute of the mutex. Set it to a null pointer. This is because FFRT supports only mutex of the basic type currently. - -`mutex` - -Pointer to the target mutex. - -##### Return value - -Returns **ffrt_success** if the API is called successfully; returns an error code otherwise. - -##### Description -* This API can be called only inside an FFRT task. If it is called outside an FFRT task, undefined behavior may occur. -* The traditional function **pthread_mutex_t** may cause unexpected kernel mode trap when it fails to lock a mutex. **ffrt_mutex_t** solves this problem and therefore provides better performance if used properly. -* Currently, recursion and timing are not supported. -* **ffrt_mutex_t** in the C code must be explicitly created and destroyed by calling **ffrt_mutex_init** and **ffrt_mutex_destroy**, respectively. -* You need to set the **ffrt_mutex_t** object in the C code to null or destroy the object. For the same **ffrt_mutex_t** object, **ffrt_mutex_destroy** can be called only once. Otherwise, undefined behavior may occur. -* If **ffrt_mutex_t** is accessed after **ffrt_mutex_destroy** is called, undefined behavior may occur. - -##### Example - -```{.c} -#include -#include "ffrt.h" - -typedef struct { - int* sum; - ffrt_mutex_t* mtx; -} tuple; - -void func(void* arg) -{ - tuple* t = (tuple*)arg; - - int ret = ffrt_mutex_lock(t->mtx); - if (ret != ffrt_success) { - printf("error\n"); - } - (*t->sum)++; - ret = ffrt_mutex_unlock(t->mtx); - if (ret != ffrt_success) { - printf("error\n"); - } -} - -typedef struct { - ffrt_function_header_t header; - ffrt_function_t func; - ffrt_function_t after_func; - void* arg; -} c_function; - -static void ffrt_exec_function_wrapper(void* t) -{ - c_function* f = (c_function*)t; - if (f->func) { - f->func(f->arg); - } -} - -static void ffrt_destroy_function_wrapper(void* t) -{ - c_function* f = (c_function*)t; - if (f->after_func) { - f->after_func(f->arg); - } -} - -#define FFRT_STATIC_ASSERT(cond, msg) int x(int static_assertion_##msg[(cond) ? 1 : -1]) -static inline ffrt_function_header_t* ffrt_create_function_wrapper(const ffrt_function_t func, - const ffrt_function_t after_func, void* arg) -{ - FFRT_STATIC_ASSERT(sizeof(c_function) <= ffrt_auto_managed_function_storage_size, - size_of_function_must_be_less_than_ffrt_auto_managed_function_storage_size); - c_function* f = (c_function*)ffrt_alloc_auto_managed_function_storage_base(ffrt_function_kind_general); - f->header.exec = ffrt_exec_function_wrapper; - f->header.destroy = ffrt_destroy_function_wrapper; - f->func = func; - f->after_func = after_func; - f->arg = arg; - return (ffrt_function_header_t*)f; -} - -static inline void ffrt_submit_c(ffrt_function_t func, const ffrt_function_t after_func, - void* arg, const ffrt_deps_t* in_deps, const ffrt_deps_t* out_deps, const ffrt_task_attr_t* attr) -{ - ffrt_submit_base(ffrt_create_function_wrapper(func, after_func, arg), in_deps, out_deps, attr); -} - -void ffrt_mutex_task(void *) -{ - int sum = 0; - ffrt_mutex_t mtx; - tuple t = {&sum, &mtx}; - int ret = ffrt_mutex_init(&mtx, NULL); - if (ret != ffrt_success) { - printf("error\n"); - } - for (int i = 0; i < 10; i++) { - ffrt_submit_c(func, NULL, &t, NULL, NULL, NULL); - } - ffrt_mutex_destroy(&mtx); - ffrt_wait(); - printf("sum = %d\n", sum); -} - -int main(int narg, char** argv) -{ - int r; - ffrt_submit_c(ffrt_mutex_task, NULL, NULL, NULL, NULL, NULL); - ffrt_wait(); - return 0; -} -``` - -Expected output - -``` -sum=10 -``` - -This example is for reference only and is not encouraged in practice. - - -#### ffrt_cond_t - -Provides performance implementation similar to pthread semaphore. - -##### Declaration - -```{.c} -typedef enum { - ffrt_error = -1, - ffrt_success = 0, - ffrt_error_nomem = ENOMEM, - ffrt_error_timedout = ETIMEDOUT, - ffrt_error_busy = EBUSY, - ffrt_error_inval = EINVAL -} ffrt_error_t; - -struct ffrt_cond_t; - -int ffrt_cond_init(ffrt_cond_t* cond, const ffrt_condattr_t* attr); -int ffrt_cond_signal(ffrt_cond_t* cond); -int ffrt_cond_broadcast(ffrt_cond_t* cond); -int ffrt_cond_wait(ffrt_cond_t*cond, ffrt_mutex_t* mutex); -int ffrt_cond_timedwait(ffrt_cond_t* cond, ffrt_mutex_t* mutex, const struct timespec* time_point); -int ffrt_cond_destroy(ffrt_cond_t* cond); -``` - -##### Parameters - -`cond` - -Pointer to the target semaphore. - -`attr` - -Pointer to the attribute. A null pointer indicates that the default attribute is used. - -`mutex` - -Pointer to the target mutex. - -`time_point` - -Pointer to the maximum duration during which the thread is blocked. - - -##### Return value - -Returns **ffrt_success** if the API is successfully called; returns **ffrt_error_timedout** if the maximum duration is reached before the mutex is locked. - -##### Description -* This API can be called only inside an FFRT task. If it is called outside an FFRT task, undefined behavior may occur. -* The traditional function **pthread_cond_t** may cause unexpected kernel mode trap when the conditions are not met. **ffrt_cond_t** solves this problem and therefore provides better performance if being used properly. -* **ffrt_cond_t** in the C code must be explicitly created and destroyed by calling **ffrt_cond_init** and **ffrt_cond_destroy**, respectively. -* You need to set the **ffrt_cond_t** object in the C code to null or destroy the object. For the same **ffrt_cond_t** object, **ffrt_cond_destroy** can be called only once. Otherwise, undefined behavior may occur. -* If **ffrt_cond_t** is accessed after **ffrt_cond_destroy** is called, undefined behavior may occur. - -##### Example - -```{.c} -#include -#include "ffrt.h" - -typedef struct { - ffrt_cond_t* cond; - int* a; - ffrt_mutex_t* lock_; -} tuple; - -void func1(void* arg) -{ - tuple* t = (tuple*)arg; - int ret = ffrt_mutex_lock(t->lock_); - if (ret != ffrt_success) { - printf("error\n"); - } - while (*t->a != 1) { - ret = ffrt_cond_wait(t->cond, t->lock_); - if (ret != ffrt_success) { - printf("error\n"); - } - } - ret = ffrt_mutex_unlock(t->lock_); - if (ret != ffrt_success) { - printf("error\n"); - } - printf("a = %d\n", *(t->a)); -} - -void func2(void* arg) -{ - tuple* t = (tuple*)arg; - int ret = ffrt_mutex_lock(t->lock_); - if (ret != ffrt_success) { - printf("error\n"); - } - *(t->a) = 1; - ret = ffrt_cond_signal(t->cond); - if (ret != ffrt_success) { - printf("error\n"); - } - ret = ffrt_mutex_unlock(t->lock_); - if (ret != ffrt_success) { - printf("error\n"); - } -} - -typedef struct { - ffrt_function_header_t header; - ffrt_function_t func; - ffrt_function_t after_func; - void* arg; -} c_function; - -static void ffrt_exec_function_wrapper(void* t) -{ - c_function* f = (c_function*)t; - if (f->func) { - f->func(f->arg); - } -} - -static void ffrt_destroy_function_wrapper(void* t) -{ - c_function* f = (c_function*)t; - if (f->after_func) { - f->after_func(f->arg); - } -} - -#define FFRT_STATIC_ASSERT(cond, msg) int x(int static_assertion_##msg[(cond) ? 1 : -1]) -static inline ffrt_function_header_t* ffrt_create_function_wrapper(const ffrt_function_t func, - const ffrt_function_t after_func, void* arg) -{ - FFRT_STATIC_ASSERT(sizeof(c_function) <= ffrt_auto_managed_function_storage_size, - size_of_function_must_be_less_than_ffrt_auto_managed_function_storage_size); - c_function* f = (c_function*)ffrt_alloc_auto_managed_function_storage_base(ffrt_function_kind_general); - f->header.exec = ffrt_exec_function_wrapper; - f->header.destroy = ffrt_destroy_function_wrapper; - f->func = func; - f->after_func = after_func; - f->arg = arg; - return (ffrt_function_header_t*)f; -} - -static inline void ffrt_submit_c(ffrt_function_t func, const ffrt_function_t after_func, - void* arg, const ffrt_deps_t* in_deps, const ffrt_deps_t* out_deps, const ffrt_task_attr_t* attr) -{ - ffrt_submit_base(ffrt_create_function_wrapper(func, after_func, arg), in_deps, out_deps, attr); -} - -void ffrt_cv_task(void *) -{ - ffrt_cond_t cond; - int ret = ffrt_cond_init(&cond, NULL); - if (ret != ffrt_success) { - printf("error\n"); - } - int a = 0; - ffrt_mutex_t lock_; - tuple t = {&cond, &a, &lock_}; - ret = ffrt_mutex_init(&lock_, NULL); - if (ret != ffrt_success) { - printf("error\n"); - } - ffrt_submit_c(func1, NULL, &t, NULL, NULL, NULL); - ffrt_submit_c(func2, NULL, &t, NULL, NULL, NULL); - ffrt_wait(); - ffrt_cond_destroy(&cond); - ffrt_mutex_destroy(&lock_); -} - -int main(int narg, char** argv) -{ - ffrt_submit_c(ffrt_cv_task, NULL, NULL, NULL, NULL, NULL); - ffrt_wait(); - return 0; -} -``` - -Expected output - -``` -a=1 -``` - -This example is for reference only and is not encouraged in practice. - -#### ffrt_usleep - -Provides performance implementation similar to C11 sleep and Linux usleep. - -##### Declaration - -```{.c} -int ffrt_usleep(uint64_t usec); -``` - -##### Parameters - -`usec` - -Duration that the calling thread is suspended, in μs. - -##### Return value - -N/A - -##### Description -* This API can be called only inside an FFRT task. If it is called outside an FFRT task, undefined behavior may occur. -* The traditional function **sleep** may cause unexpected kernel mode trap. **ffrt_usleep** solves this problem and therefore provides better performance if used properly. - -##### Example - -```{.c} -#include -#include -#include "ffrt.h" - -void func(void* arg) -{ - time_t current_time = time(NULL); - printf("Time: %s", ctime(¤t_time)); - ffrt_usleep(2000000); // Suspend for 2 seconds - current_time = time(NULL); - printf("Time: %s", ctime(¤t_time)); -} - -typedef struct { - ffrt_function_header_t header; - ffrt_function_t func; - ffrt_function_t after_func; - void* arg; -} c_function; - -static void ffrt_exec_function_wrapper(void* t) -{ - c_function* f = (c_function*)t; - if (f->func) { - f->func(f->arg); - } -} - -static void ffrt_destroy_function_wrapper(void* t) -{ - c_function* f = (c_function*)t; - if (f->after_func) { - f->after_func(f->arg); - } -} - -#define FFRT_STATIC_ASSERT(cond, msg) int x(int static_assertion_##msg[(cond) ? 1 : -1]) -static inline ffrt_function_header_t* ffrt_create_function_wrapper(const ffrt_function_t func, - const ffrt_function_t after_func, void* arg) -{ - FFRT_STATIC_ASSERT(sizeof(c_function) <= ffrt_auto_managed_function_storage_size, - size_of_function_must_be_less_than_ffrt_auto_managed_function_storage_size); - c_function* f = (c_function*)ffrt_alloc_auto_managed_function_storage_base(ffrt_function_kind_general); - f->header.exec = ffrt_exec_function_wrapper; - f->header.destroy = ffrt_destroy_function_wrapper; - f->func = func; - f->after_func = after_func; - f->arg = arg; - return (ffrt_function_header_t*)f; -} - -static inline void ffrt_submit_c(ffrt_function_t func, const ffrt_function_t after_func, - void* arg, const ffrt_deps_t* in_deps, const ffrt_deps_t* out_deps, const ffrt_task_attr_t* attr) -{ - ffrt_submit_base(ffrt_create_function_wrapper(func, after_func, arg), in_deps, out_deps, attr); -} - -int main(int narg, char** argv) -{ - ffrt_submit_c(func, NULL, NULL, NULL, NULL, NULL); - ffrt_wait(); - return 0; -} -``` - -An output case is as follows: - -``` -Time: Tue Aug 13 15:45:30 2024 -Time: Tue Aug 13 15:45:32 2024 -``` - -#### ffrt_yield - -Passes control to other tasks so that they can be executed. If there is no other task that can be executed, this API is invalid. - -##### Declaration - -```{.c} -void ffrt_yield(); -``` - -##### Parameters - -N/A - -##### Return value - -N/A - -##### Description -* This API can be called only inside an FFRT task. If it is called outside an FFRT task, undefined behavior may occur. -* The exact behavior of this API depends on the implementation, especially the mechanism and system state of the FFRT scheduler in use. - -##### Example - -N/A - -### ffrt timer - -FFRT supports the capability of starting and stopping the timer. - -#### ffrt_timer_start - -Starts a timer. - -##### Declaration -```{.c} -typedef int ffrt_timer_t; -typedef void (*ffrt_timer_cb)(void* data); - -ffrt_timer_t ffrt_timer_start(ffrt_qos_t qos, uint64_t timeout, void* data, ffrt_timer_cb cb, bool repeat); -``` - -##### Parameters - -`qos` - -QoS. - -`timeout` - -Timeout of the timer. - -`data` - -Pointer to the input parameter in the callback function invoked upon a timeout. - -`cb` - -Callback function invoked upon a timeout. - -`repeat` - -Whether to repeat the timer. - -##### Return value - -Handle to the timer. - -##### Description -N/A - -##### Example -```{.c} -#include -#include -#include "ffrt.h" - -static void testfun(void *data) -{ - *(int *)data += 1; -} - -void (*cb)(void *) = testfun; - -int main(int narg, char** argv) -{ - static int x = 0; - int *xf = &x; - void *data = xf; - uint64_t timeout = 200; - int handle = ffrt_timer_start(ffrt_qos_default, timeout, data, cb, false); - usleep(300000); - ffrt_timer_stop(ffrt_qos_default, handle); - printf("data: %d\n", x); - return 0; -} -``` - -Expected output - -``` -data: 1 -``` - -#### ffrt_timer_stop - -Stops the timer. - -##### Declaration -```{.c} -int ffrt_timer_stop(ffrt_qos_t qos, ffrt_timer_t handle); -``` - -##### Parameters - -`qos` - -QoS. - -`handle` - -Handle to the timer. - -##### Return value - -**0** if the call is successful; **-1** if the call fails. - -##### Description -N/A - -##### Example -```{.c} -#include -#include -#include "ffrt.h" - -static void testfun(void *data) -{ - *(int *)data += 1; -} - -void (*cb)(void *) = testfun; - -int main(int narg, char** argv) -{ - static int x = 0; - int *xf = &x; - void *data = xf; - uint64_t timeout = 200; - int handle = ffrt_timer_start(ffrt_qos_default, timeout, data, cb, false); - usleep(300000); - ffrt_timer_stop(ffrt_qos_default, handle); - printf("data: %d\n", x); - return 0; -} -``` - -Expected output - -``` -data: 1 -``` - -### ffrt looper - -FFRT provides the looper mechanism. The looper supports task submission, event listening, and timer. The looper runs in the user thread. +## Overview -#### ffrt_loop_create +Function Flow Runtime (FFRT) is a task-based and data-driven concurrent programming model that allows you to develop an application by creating tasks and describing their dependencies. +Specifically, FFRT automatically and concurrently schedules and executes tasks of the application based on the task dependency status and available resources, so that you can focus on feature development. -Creates a loop. +This document provides guidance for you to implement concurrent programming based on the FFRT programming model. -##### Declaration -```{.c} -typedef void* ffrt_loop_t; +## Maintenance and Test -ffrt_loop_t ffrt_loop_create(ffrt_queue_t queue); -``` - -##### Parameters - -`queue` - -Queue, which must be a concurrent queue. - -##### Return value - -Loop object. - -##### Description -N/A - -##### Example -```{.c} -#include -#include -#include -#include "c/loop.h" - -int main(int narg, char** argv) -{ - ffrt_queue_attr_t queue_attr; - (void)ffrt_queue_attr_init(&queue_attr); - ffrt_queue_t queue_handle = ffrt_queue_create(ffrt_queue_concurrent, "test_queue", &queue_attr); - - auto loop = ffrt_loop_create(queue_handle); - - if (loop != NULL) { - printf("loop is not null.\n"); - } - - int ret = ffrt_loop_destroy(loop); - - ffrt_queue_attr_destroy(&queue_attr); - ffrt_queue_destroy(queue_handle); - return 0; -} -``` - -Expected output - -``` -loop is not null. -``` - -#### ffrt_loop_destroy - -Destroys a loop. - -##### Declaration -```{.c} -int ffrt_loop_destroy(ffrt_loop_t loop); -``` - -##### Parameters - -`loop` - -Loop object. - -##### Return value +### Timeout Monitoring -**0** if the call is successful; **-1** if the call fails. +FFRT provides a queue-level and task-level timeout maintenance and test mechanism to monitor the end-to-end time for scheduling queues and tasks that carry important responsibilities in user services. -##### Description -N/A - -##### Example -```{.c} -#include -#include -#include -#include "c/loop.h" - -int main(int narg, char** argv) -{ - ffrt_queue_attr_t queue_attr; - (void)ffrt_queue_attr_init(&queue_attr); - ffrt_queue_t queue_handle = ffrt_queue_create(ffrt_queue_concurrent, "test_queue", &queue_attr); - - auto loop = ffrt_loop_create(queue_handle); - - int ret = ffrt_loop_destroy(loop); - - if (ret == 0) { - printf("loop normal destruction."); - } - - ffrt_queue_attr_destroy(&queue_attr); - ffrt_queue_destroy(queue_handle); - return 0; -} -``` - -Expected output - -``` -loop normal destruction. -``` - -#### ffrt_loop_run - -Runs a loop. - -##### Declaration -```{.c} -int ffrt_loop_run(ffrt_loop_t loop); -``` - -##### Parameters - -`loop` - -Loop object. +- When a task in the queue times out, the FFRT prints alarm logs and notifies the service through the callback. +- When a task times out, the FFRT prints alarm logs and calls the process-level callback function. -##### Return value - -**0** if the call is successful; **-1** if the call fails. - -##### Description -N/A - -##### Example -```{.c} -#include -#include -#include -#include "c/loop.h" - -void* ThreadFunc(void* p) -{ - int ret = ffrt_loop_run(p); - if (ret == 0) { - printf("loop normal operation."); - } - return nullptr; -} -int main(int narg, char** argv) -{ - ffrt_queue_attr_t queue_attr; - (void)ffrt_queue_attr_init(&queue_attr); - ffrt_queue_t queue_handle = ffrt_queue_create(ffrt_queue_concurrent, "test_queue", &queue_attr); +> **NOTE** +> +> The callback function executed when a task times out must be unique in the process and should be configured in the FFRT by the service party before the task is submitted. The callback function cannot be configured during task submission or task timeout detection. - auto loop = ffrt_loop_create(queue_handle); - pthread_t thread; - pthread_create(&thread, 0, ThreadFunc, loop); +The APIs are as follows: - ffrt_loop_stop(loop); - int ret = ffrt_loop_destroy(loop); +| C++ API | C API | Description | +| ----------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | ---------------------- | +| [queue_attr::timeout](https://gitee.com/openharmony/resourceschedule_ffrt/blob/master/docs/ffrt-api-guideline-cpp.md#set-queue-timeout) | [ffrt_queue_attr_set_timeout](ffrt-api-guideline-c.md#ffrt_queue_attr_set_timeout) | Sets the queue timeout. | +| [queue_attr::callback](https://gitee.com/openharmony/resourceschedule_ffrt/blob/master/docs/ffrt-api-guideline-cpp.md#set-queue-callback) | [ffrt_queue_attr_set_callback](ffrt-api-guideline-c.md#ffrt_queue_attr_set_callback) | Sets the queue timeout callback.| - ffrt_queue_attr_destroy(&queue_attr); - ffrt_queue_destroy(queue_handle); - return 0; -} -``` +### Long-Time Task Monitoring -Expected output +#### Mechanism -``` -loop normal operation. -``` +- When the task execution reaches one second, stack printing is triggered. The stack printing interval is then changed to one minute. After 10 prints, the interval is changed to 10 minutes. After another 10 prints, the interval is changed to and fixed at 30 minutes. +- The `GetBacktraceStringByTid` API of DFX is called for stack printing. This API sends stack capture signals to the blocked thread to trigger interrupts and capture the call stack return. -#### ffrt_loop_stop +#### Example -Stops a loop. +Search for the keyword **RecordSymbolAndBacktrace** in the corresponding process log. The following is an example of the corresponding log: -##### Declaration -```{.c} -void ffrt_loop_stop(ffrt_loop_t loop); +```txt +W C01719/ffrt: 60500:RecordSymbolAndBacktrace:159 Tid[16579] function occupies worker for more than [1]s. +W C01719/ffrt: 60501:RecordSymbolAndBacktrace:164 Backtrace: +W C01719/ffrt: #00 pc 00000000000075f0 /system/lib64/module/file/libhash.z.so +W C01719/ffrt: #01 pc 0000000000008758 /system/lib64/module/file/libhash.z.so +W C01719/ffrt: #02 pc 0000000000012b98 /system/lib64/module/file/libhash.z.so +W C01719/ffrt: #03 pc 000000000002aaa0 /system/lib64/platformsdk/libfilemgmt_libn.z.so +W C01719/ffrt: #04 pc 0000000000054b2c /system/lib64/platformsdk/libace_napi.z.so +W C01719/ffrt: #05 pc 00000000000133a8 /system/lib64/platformsdk/libuv.so +W C01719/ffrt: #06 pc 00000000000461a0 /system/lib64/chipset-sdk/libffrt.so +W C01719/ffrt: #07 pc 0000000000046d44 /system/lib64/chipset-sdk/libffrt.so +W C01719/ffrt: #08 pc 0000000000046a6c /system/lib64/chipset-sdk/libffrt.so +W C01719/ffrt: #09 pc 00000000000467b0 /system/lib64/chipset-sdk/libffrt.so ``` -##### Parameters - -`loop` - -Loop object. - -##### Return value +The log prints the task stack, Worker thread ID, and execution time of the long-time task. Find the corresponding component based on the stack to determine the blocking cause. -N/A. +#### Precautions -##### Description N/A -##### Example -```{.c} -#include -#include -#include -#include "c/loop.h" - -void* ThreadFunc(void* p) -{ - int ret = ffrt_loop_run(p); - return nullptr; -} -int main(int narg, char** argv) -{ - ffrt_queue_attr_t queue_attr; - (void)ffrt_queue_attr_init(&queue_attr); - ffrt_queue_t queue_handle = ffrt_queue_create(ffrt_queue_concurrent, "test_queue", &queue_attr); - - auto loop = ffrt_loop_create(queue_handle); - pthread_t thread; - pthread_create(&thread, 0, ThreadFunc, loop); - - ffrt_loop_stop(loop); - int ret = ffrt_loop_destroy(loop); - - ffrt_queue_attr_destroy(&queue_attr); - ffrt_queue_destroy(queue_handle); - return 0; -} -``` - -Expected output - -``` -**0** if the loop object is stopped normally. -``` - -#### ffrt_loop_epoll_ctl - -Manages listening events on a loop. - -##### Declaration -```{.c} -int ffrt_loop_epoll_ctl(ffrt_loop_t loop, int op, int fd, uint32_t events, void *data, ffrt_poller_cb cb); -``` - -##### Parameters - -`loop` - -Loop object. - -`op` - -Operation to be performed, such as **EPOLL_CTL_ADD** and **EPOLL_CLT_DEL**. - -`fd` - -File descriptor. - -`events` +### Running Information Dump -Events linked to the file descriptor. +#### Mechanism -`data` +FFRT provides an external interface API `ffrt_dump` to dump the internal information about the running of the FFRT subsystem, including: -Pointer to the input parameter in the callback function invoked upon event changes. +1. FFRT statistics: number of submitted tasks, number of running tasks, number of coroutine switching times, and number of completed tasks; +2. Worker thread information: number of Worker threads in each QoS, Worker ID, ID of the running task, task name, and task type. +3. Common task information: common tasks that are not released in the current process, dump task name and ID, and call stack information of each task. +4. Queue task information: queue tasks that are not released in the current process, dump task name and ID, and call stack information of each task. -`cb` +When the current process is frozen, the DFX module proactively calls the `ffrt_dump` API to dump the FFRT information to the freeze file and store the file in the `/data/log/faultlog/faultlogger/` directory. You can directly use the task call stack information in the file to locate the frame freezing of the corresponding task. -Callback function invoked upon event changes. +#### Example -##### Return value +```txt +ready task ptr: qos 0 readptr 79 writeptr 79 +ready task ptr: qos 1 readptr 360 writeptr 360 +ready task ptr: qos 2 readptr 19 writeptr 19 +ready task ptr: qos 3 readptr 0 writeptr 0 +ready task ptr: qos 4 readptr 0 writeptr 0 +ready task ptr: qos 5 readptr 65 writeptr 65 +ready task ptr: qos 6 readptr 0 writeptr 0 +ready task ptr: qos 7 readptr 0 writeptr 0 +submit queue: readptr 24 writeptr 24 +intr wake: status 255 +proc status: taskCnt 23 vercnt 0sigCnt0 + |-> worker count + qos 0: worker num:1 tid:31676 + qos 2: worker num:3 tid:51349, 28769, 28565 + qos 5: worker num:1 tid:30605 + |-> worker status + qos 0: worker tid 31676 is running nothing + qos 2: worker tid 51349 is running nothing + qos 2: worker tid 28769 is running, task id 24591 name sq_CesSrvMain_12_PublishCommonEventDetailed_24591 fromTid 43928 createTime 2024-11-27 02:52:27.325248 executeTime 2024-11-27 02:52:27.326150 + qos 2: worker tid 28565 is running, task id 24611 name sq_dfx_freeze_task_queue_16_NotifyAppFaultTask_24611 fromTid 43833 createTime 2024-11-27 02:52:38.114787 executeTime 2024-11-27 02:52:38.115424 + qos 5: worker tid 30605 is running, task id 24595 name sq_AbilityManagerService_19_SubmitTaskInner_24595 fromTid 43610 createTime 2024-11-27 02:52:27.844237 executeTime 2024-11-27 02:52:27.844573 + |-> ready queue status + |-> blocked by task dependence + <1/1>stack: task id 3,qos 2,name AgingTask fromTid 43417 createTime 2024-11-27 01:21:39.641673 executeTime 2024-11-27 01:21:39.642290 +#00 pc 0000000000065c5c /system/lib64/ndk/libffrt.so(CoYield()+560)(22be57f01a789a03813d26a19c3a4042) +#01 pc 00000000000a3268 /system/lib64/ndk/libffrt.so(ffrt::this_task::SleepUntilImpl(std::__h::chrono::time_point>> const&)+356)(22be57f01a789a03813d26a19c3a4042) +#02 pc 00000000000a39b4 /system/lib64/ndk/libffrt.so(ffrt_usleep+60)(22be57f01a789a03813d26a19c3a4042) +#03 pc 0000000000420de0 /system/lib64/libbms.z.so(2eb52bd03af1b9a31e14ffe60bfc39da) +#04 pc 00000000000a6a2c /system/lib64/ndk/libffrt.so(ffrt::CPUEUTask::Execute()+300)(22be57f01a789a03813d26a19c3a4042) +#05 pc 0000000000066d18 /system/lib64/ndk/libffrt.so(22be57f01a789a03813d26a19c3a4042) +``` + +#### Precautions + +The DFX module has requirements on the processing time during freeze, which has a low probability that the information collected by `ffrt_dump` is incomplete and the freeze processing time expires. In this case, the information flushed to the disk is missing. + +### Blackbox Logs + +#### Mechanism + +When a process crashes, the FFRT module receives signals (`SIGABRT`, `SIGBUS`, `SIGFPE`, `SIGILL`, `SIGSTKFLT`, `SIGSTOP`, `SIGSYS`, and `SIGTRAP`) and saves important running information to the faultlog, including the running task, running information and call stack information of the current Worker thread, common task information, and queue task information. You can use the information to locate the crashes. + +#### Example -**0** if the call is successful; **-1** if the call fails. +```txt +C01719/CameraDaemon/ffrt: 9986:operator():254 <<<=== ffrt black box(BBOX) start ===>>> +C01719/CameraDaemon/ffrt: 9987:SaveCurrent:63 <<<=== current status ===>>> +C01719/CameraDaemon/ffrt: 9988:SaveCurrent:68 signal SIGABRT triggered: source tid 5962, task id 17, qos 2, name SvrWatchdog +C01719/CameraDaemon/ffrt: 9989:SaveWorkerStatus:94 <<<=== worker status ===>>> +C01719/CameraDaemon/ffrt: 9990:SaveWorkerStatus:100 qos 0: worker tid 6410 is running nothing +C01719/CameraDaemon/ffrt: 9991:SaveWorkerStatus:100 qos 2: worker tid 5968 is running nothing +C01719/CameraDaemon/ffrt: 9992:SaveWorkerStatus:100 qos 2: worker tid 5964 is running nothing +C01719/CameraDaemon/ffrt: 9993:SaveWorkerStatus:100 qos 2: worker tid 5963 is running nothing +C01719/CameraDaemon/ffrt: 9994:SaveWorkerStatus:105 qos 2: worker tid 5962 is running task id 17 name SvrWatchdog +C01719/CameraDaemon/ffrt: 9995:SaveWorkerStatus:100 qos 2: worker tid 5967 is running nothing +C01719/CameraDaemon/ffrt: 9996:SaveWorkerStatus:100 qos 2: worker tid 5965 is running nothing +C01719/CameraDaemon/ffrt: 9997:SaveWorkerStatus:100 qos 2: worker tid 5961 is running nothing +C01719/CameraDaemon/ffrt: 9998:SaveWorkerStatus:100 qos 2: worker tid 1146 is running nothing +C01719/CameraDaemon/ffrt: 9999:SaveWorkerStatus:100 qos 2: worker tid 1145 is running nothing +C01719/CameraDaemon/ffrt: 10000:SaveWorkerStatus:100 qos 2: worker tid 5966 is running nothing +``` + +#### Precautions -##### Description N/A -##### Example -```{.c} -#include -#include -#include -#include -#include -#include -#include "c/loop.h" -#include "ffrt.h" - -void* ThreadFunc(void* p) -{ - int ret = ffrt_loop_run(p); - return nullptr; -} - -static void testfun(void* data) -{ - *(int*)data += 1; -} - -static void (*cb)(void*) = testfun; - -void testCallBack(void *data, unsigned int events) {} - -struct TestData { - int fd; - uint64_t expected; -}; - -int main(int narg, char** argv) -{ - ffrt_queue_attr_t queue_attr; - (void)ffrt_queue_attr_init(&queue_attr); - ffrt_queue_t queue_handle = ffrt_queue_create(ffrt_queue_concurrent, "test_queue", &queue_attr); - - auto loop = ffrt_loop_create(queue_handle); - int result1 = 0; - std::function &&basicFunc1 = [&result1]() {result1 += 10;}; - ffrt_task_handle_t task1 = ffrt_queue_submit_h(queue_handle, ffrt::create_function_wrapper(basicFunc1, ffrt_function_kind_queue), nullptr); - - pthread_t thread; - pthread_create(&thread, 0, ThreadFunc, loop); - - static int x = 0; - int* xf = &x; - void* data = xf; - uint64_t timeout1 = 20; - uint64_t timeout2 = 10; - uint64_t expected = 0xabacadae; - - int testFd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); - struct TestData testData {.fd = testFd, .expected = expected}; - ffrt_timer_t timeHandle = ffrt_loop_timer_start(loop, timeout1, data, cb, false); - - int ret = ffrt_loop_epoll_ctl(loop, EPOLL_CTL_ADD, testFd, EPOLLIN, (void*)(&testData), testCallBack); - if (ret == 0) { - printf("ffrt_loop_epoll_ctl executed successfully.\n"); - } - ssize_t n = write(testFd, &expected, sizeof(uint64_t)); - usleep(25000); - ffrt_loop_epoll_ctl(loop, EPOLL_CTL_DEL, testFd, 0, nullptr, nullptr); - - ffrt_loop_stop(loop); - pthread_join(thread, nullptr); - ffrt_loop_timer_stop(loop, timeHandle); - ret = ffrt_loop_destroy(loop); - - ffrt_queue_attr_destroy(&queue_attr); - ffrt_queue_destroy(queue_handle); - return 0; -} -``` - -Expected output - -``` -ffrt_loop_epoll_ctl if the operation is successful. -``` - -#### ffrt_loop_timer_start - -Starts the timer on a loop. +### Tracing -##### Declaration -```{.c} -ffrt_timer_t ffrt_loop_timer_start(ffrt_loop_t loop, uint64_t timeout, void* data, ffrt_timer_cb cb, bool repeat); -``` - -##### Parameters - -`loop` - -Loop object. - -`timeout` - -Timeout of the timer. - -`data` - -Pointer to the input parameter in the callback function invoked upon event changes. - -`cb` - -Callback function invoked upon event changes. - -`repeat` - -* Whether to repeat the timer. - -##### Return value - -Handle to the timer. - -##### Description -N/A +#### Mechanism -##### Example -For details, see the **ffrt_loop_epoll_ctl** interface example. +During FFRT task scheduling and execution, the system traces the task status in the FFRT framework in real time. You can use the trace graphical tool to analyze whether the task behavior meets the expectation. -#### ffrt_loop_timer_stop +#### Example -Stops the timer. +1. Starting trace capture -##### Declaration -```{.c} -int ffrt_loop_timer_stop(ffrt_loop_t loop, ffrt_timer_t handle) -``` - -##### Parameters + ```shell + hdc shell "hitrace -t 10 -b 20480 -o /data/local/tmp/in_systrace.ftrace sched freq idle ffrt" + # -t: specifies the trace collection duration, during which all trace records are flushed to the disk. + # -b: specifies the size of the trace record cache. If the buffer is insufficient, some records may be overwritten and not flushed to disks. + # -o: specifies the path for storing trace files. + ``` -`loop` +2. Using a graphical tool -Loop object. + Obtain the trace file from the device and use a graphical tool, for example, [Perfetto](https://perfetto.dev/), to analyze the file. -`handle` +#### Precautions -Handle to the timer. +You can also add traces to your service code to locate the fault. Note that in the high-frequency call process, adding traces will cause system overhead and affect service performance. -##### Return value +### Debug Logs -**0** if the call is successful; **-1** if the call fails. +#### Mechanism -##### Description -N/A +- By default, debug logs are disabled for the FFRT, but can be enabled by using commands to obtain more maintenance and test information for fault locating in the development. +- Enable the FFRT debug log function: -##### Example -For details, see the **ffrt_loop_epoll_ctl** interface example. + ```shell + hdc shell hilog -b DEBUG -D 0xD001719 + ``` -## Long-Time Task Monitoring +- Restore the default FFRT INFO log level. -### Mechanism -* When the task execution reaches one second, stack printing is triggered. The stack printing interval is then changed to one minute. After 10 prints, the interval is changed to 10 minutes. After another 10 prints, the interval is changed to and fixed at 30 minutes. -* The **GetBacktraceStringByTid** interface of the DFX is called for the stack printing. This interface sends stack capture signals to the blocked thread to trigger interrupts and capture the call stack return. + ```shell + hdc shell hilog -b INFO -D 0xD001719 + ``` -### Example -Search for the keyword **RecordSymbolAndBacktrace** in the corresponding process log. The following is an example of the corresponding log: +#### Example +```txt +4190 5631 D C01719/neboard:EngineServiceAbility:1/ffrt: 275337:Detach:147 qos 3 thread not joinable +3257 6075 D C01719/com.ohos.sceneboard/ffrt: 513070:SetDefaultThreadAttr:148 qos apply tid[6075] level[3] ``` -W C01719/ffrt: 60500:RecordSymbolAndBacktrace:159 Tid[16579] function occupies worker for more than [1]s. -W C01719/ffrt: 60501:RecordSymbolAndBacktrace:164 Backtrace: -W C01719/ffrt: #00 pc 00000000000075f0 /system/lib64/module/file/libhash.z.so -W C01719/ffrt: #01 pc 0000000000008758 /system/lib64/module/file/libhash.z.so -W C01719/ffrt: #02 pc 0000000000012b98 /system/lib64/module/file/libhash.z.so -W C01719/ffrt: #03 pc 000000000002aaa0 /system/lib64/platformsdk/libfilemgmt_libn.z.so -W C01719/ffrt: #04 pc 0000000000054b2c /system/lib64/platformsdk/libace_napi.z.so -W C01719/ffrt: #05 pc 00000000000133a8 /system/lib64/platformsdk/libuv.so -W C01719/ffrt: #06 pc 00000000000461a0 /system/lib64/chipset-sdk/libffrt.so -W C01719/ffrt: #07 pc 0000000000046d44 /system/lib64/chipset-sdk/libffrt.so -W C01719/ffrt: #08 pc 0000000000046a6c /system/lib64/chipset-sdk/libffrt.so -W C01719/ffrt: #09 pc 00000000000467b0 /system/lib64/chipset-sdk/libffrt.so -``` -The log prints the task stack, Worker thread ID, and execution time of the long-time task. Find the corresponding component based on the stack to determine the blocking cause. +#### Precautions -### Precautions -During long-time task monitoring, an interrupt signal is sent. If your code contains **sleep** or a blocked thread that will be woken up by the interrupt, you should receive the return value of the blocked thread and call the code again. -The following is an example: -``` -unsigned int leftTime = sleep(10); -while (leftTime != 0) { - leftTime = sleep(leftTime); -} -``` +The FFRT is the system base and supports the running of a large number of upper-layer services and frameworks. If the debug log function is enabled globally, the number of logs will exceed the threshold, which affects the log output of other modules. ## How to Develop The following describes how to use the native APIs provided by FFRT to create parallel tasks and serial queue tasks and destroy corresponding resources. -**Adding Dynamic Link Libraries** +1. Add a dynamic link library to the `CMakeLists.txt` project. -Add the following libraries to **CMakeLists.txt**. -```txt -libffrt.z.so -``` + ```txt + libffrt.z.so + ``` -**Including Header Files** -```c++ -#include "ffrt/task.h" -#include "ffrt/type_def.h" -#include "ffrt/condition_variable.h" -#include "ffrt/mutex.h" -#include "ffrt/queue.h" -#include "ffrt/sleep.h" -``` +2. Include the following header files in the project. + + ```cpp + #include "ffrt/task.h" + #include "ffrt/type_def.h" + #include "ffrt/condition_variable.h" + #include "ffrt/loop.h" + #include "ffrt/mutex.h" + #include "ffrt/queue.h" + #include "ffrt/sleep.h" + #include "ffrt/timer.h" + ``` + +3. Encapsulate the function to be executed. -1. **Encapsulate the function to be executed.** - ```c++ + ```cpp // Method 1: Use the template. C++ is supported. template - struct Function { + struct function { ffrt_function_header_t header; T closure; }; template - void ExecFunctionWrapper(void* t) + void exec_function_wrapper(void* t) { - auto f = reinterpret_cast>*>(t); + auto f = reinterpret_cast>*>(t); f->closure(); } template - void DestroyFunctionWrapper(void* t) + void destroy_function_wrapper(void* t) { - auto f = reinterpret_cast>*>(t); + auto f = reinterpret_cast>*>(t); f->closure = nullptr; } template - static inline ffrt_function_header_t* create_function_wrapper(T&& func, + inline ffrt_function_header_t* create_function_wrapper(T&& func, ffrt_function_kind_t kind = ffrt_function_kind_general) { - using function_type = Function>; + using function_type = function>; + static_assert(sizeof(function_type) <= ffrt_auto_managed_function_storage_size, + "size of function must be less than ffrt_auto_managed_function_storage_size"); + auto p = ffrt_alloc_auto_managed_function_storage_base(kind); auto f = new (p)function_type; - f->header.exec = ExecFunctionWrapper; - f->header.destroy = DestroyFunctionWrapper; + f->header.exec = exec_function_wrapper; + f->header.destroy = destroy_function_wrapper; f->closure = std::forward(func); return reinterpret_cast(f); } @@ -2392,37 +263,38 @@ libffrt.z.so ffrt_function_t func; ffrt_function_t after_func; void* arg; - } CFunction; + } c_function_t; - static void FfrtExecFunctionWrapper(void* t) + static inline void ffrt_exec_function_wrapper(void* t) { - CFunction* f = static_cast(t); - if (f->func) { - f->func(f->arg); - } + c_function_t* f = (c_function_t *)t; + if (f->func) { + f->func(f->arg); + } } - static void FfrtDestroyFunctionWrapper(void* t) + static inline void ffrt_destroy_function_wrapper(void* t) { - CFunction* f = static_cast(t); + c_function_t* f = (c_function_t *)t; if (f->after_func) { f->after_func(f->arg); } } #define FFRT_STATIC_ASSERT(cond, msg) int x(int static_assertion_##msg[(cond) ? 1 : -1]) - static inline ffrt_function_header_t* ffrt_create_function_wrapper(const ffrt_function_t func, - const ffrt_function_t after_func, void* arg, ffrt_function_kind_t kind_t = ffrt_function_kind_general) + static inline ffrt_function_header_t *ffrt_create_function_wrapper(const ffrt_function_t func, + const ffrt_function_t after_func, void *arg) { - FFRT_STATIC_ASSERT(sizeof(CFunction) <= ffrt_auto_managed_function_storage_size, + FFRT_STATIC_ASSERT(sizeof(c_function_t) <= ffrt_auto_managed_function_storage_size, size_of_function_must_be_less_than_ffrt_auto_managed_function_storage_size); - CFunction* f = static_cast(ffrt_alloc_auto_managed_function_storage_base(kind_t)); - f->header.exec = FfrtExecFunctionWrapper; - f->header.destroy = FfrtDestroyFunctionWrapper; + + c_function_t* f = (c_function_t *)ffrt_alloc_auto_managed_function_storage_base(ffrt_function_kind_general); + f->header.exec = ffrt_exec_function_wrapper; + f->header.destroy = ffrt_destroy_function_wrapper; f->func = func; f->after_func = after_func; f->arg = arg; - return reinterpret_cast(f); + return (ffrt_function_header_t *)f; } // Example: function to be submitted for execution. @@ -2431,11 +303,10 @@ libffrt.z.so (*static_cast(arg)) += 1; } ``` - -2. **Set the task attributes.** - Set the task attributes, including the QoS and task name, before submitting the task. - ```c++ +4. Set task attributes, including the QoS level and task name. + + ```cpp // ******Initialize the attributes of the parallel task****** ffrt_task_attr_t attr; ffrt_task_attr_init(&attr); @@ -2444,7 +315,7 @@ libffrt.z.so // Create the attributes of the serial queue. ffrt_queue_attr_t queue_attr; - // Create the handle of the serial queue. + // Create the handle to the serial queue. ffrt_queue_t queue_handle; // Initialize the queue attribute. @@ -2463,8 +334,9 @@ libffrt.z.so queue_handle = ffrt_queue_create(ffrt_queue_serial, "test_queue", &queue_attr); ``` -3. **Submit the task.** - ```c++ +5. Submit the task. + + ```cpp int a = 0; // ******Parallel task****** // Submit the parallel task without obtaining a handle. @@ -2489,8 +361,9 @@ libffrt.z.so ffrt_queue_wait(handle); ``` -4. **Destroy the resources after the task is submitted.** - ```c++ +6. Destroy the resources after the task is submitted. + + ```cpp // ******Destroy the parallel task****** ffrt_task_attr_destroy(&attr); ffrt_task_handle_destroy(task); @@ -2504,93 +377,229 @@ libffrt.z.so ## Suggestions -### Suggestion 1: Functional programming - -Basic idea: Use functional programming for the calculation process. +### Suggestion 1: Functional Programming -* Use pure functions and encapsulate them to express each step of the process. -* There is no global data access. -* There is no internal state reserved. -* Use **ffrt_submit_base()** to submit a function in asynchronous mode for execution. -* Use **in_deps** and **out_deps** of **ffrt_submit_base()** to specify the data objects to be accessed by the function and the access mode. -* Use **inDeps** and **outDeps** to specify the dependency between tasks to ensure the correctness of program execution. +- Use pure functions and encapsulate them to express each step of the process. +- There is no global data access. +- There is no internal state reserved. +- Use `ffrt_submit_base()` to submit a function in asynchronous mode for execution. +- Use `in_deps` and `out_deps` of `ffrt_submit_base()` to specify the data objects to be accessed by the function and the access mode. +- Programmers use the `in_deps` and `out_deps` parameters to express task dependencies to ensure the correctness of program execution. -> **NOTE** -> > Using pure functions helps you maximize the parallelism and avoid data races and lock abuse. +> +> In practice, you may not use pure functions in certain scenarios, with the following prerequisites: +> +> - `in_deps` and `out_deps` can ensure the correctness of program execution. +> - The lock mechanism provided by FFRT is used to protect access to global variables. -In practice, you may not use pure functions in certain scenarios, with the following prerequisites: +### Suggestion 2: Using FFRT APIs -* **in_deps** and **out_deps** can ensure the correctness of program execution. -* The lock mechanism provided by FFRT is used to protect access to global variables. +- Do not use the APIs of the system thread library to create threads in FFRT tasks. Instead, use `submit` to submit tasks. +- Use the lock, condition variable, sleep, and I/O APIs provided by FFRT to replace the APIs of the system thread library. + - Using the APIs of the system thread library may block worker threads and result in extra performance overhead. +### Suggestion 3: Deadline Mechanism -### Suggestion 2: Use FFRT APIs +- Use FFRT APIs in processing flows that feature periodic/repeated execution. +- Use FFRT APIs in processing flows with clear time constraints and is performance critical. +- Use FFRT APIs in relatively large-granularity processing flows, such as the frame processing flow with the 16.6 ms time constraint. -* Do not use the APIs of the system thread library to create threads in FFRT tasks. Instead, use **ffrt_submit_base** or **ffrt_submit_h_base** to submit tasks. -* Use the lock, condition variable, sleep, and I/O APIs provided by FFRT to replace the APIs of the system thread library. -* Using the APIs of the system thread library may block worker threads and result in extra performance overhead. +### Suggestion 4: Migration from the Thread Model -### Suggestion 3: Deadline mechanism +- Create a thread instead of creating an FFRT task. + - A thread is logically similar to a task without `in_deps`. +- Identify the dependency between threads and express the dependencies in `in_deps` and `out_deps` of the task. +- Decompose an intra-thread computing process into asynchronous tasks for invoking. +- Use the task dependency and lock mechanism to avoid data races of concurrent tasks. -* Use FFRT APIs in processing flows that feature periodic/repeated execution. -* Use FFRT APIs in processing flows with clear time constraints and is performance critical. -* Use FFRT APIs in relatively large-granularity processing flows, such as the frame processing flow with the 16.6 ms time constraint. +### Suggestion 5: C++ APIs Recommended -### Suggestion 4: Migration from the thread model +- The FFRT C++ APIs are implemented based on the C APIs. Before using the APIs, you can manually add the C++ header file. -* Create a thread instead of creating an FFRT task. -* A thread is logically similar to a task without **in_deps**. -* Identify the dependency between threads and express the dependencies in **in_deps** or **out_deps** of the task. -* Decompose an intra-thread computing process into asynchronous tasks for invoking. -* Use the task dependency and lock mechanism to avoid data races of concurrent tasks. +## Constraints -### Suggestion 5: C++ APIs recommended +### Thread Local Variables -* The FFRT C++ APIs are implemented based on the C APIs. Before using the APIs, you can manually add the C++ header file. -* For details about how to download C++ APIs, see [FFRT C++ APIs](https://gitee.com/openharmony/resourceschedule_ffrt/tree/master/interfaces/kits). +Risks exist when thread local variables are used in FFRT tasks. The details are as follows: -## Constraints +- Thread local variables include the variables defined by `thread_local` provided by C/C++ and the variables created by using `thread_local`. +- FFRT supports task scheduling. The thread to which a task is scheduled is random. Therefore, there are risks to use thread local variables, which is consistent with all other frameworks that support concurrent task scheduling. +- By default, an FFRT task runs in coroutine mode. During task execution, the coroutine may exit. When the task is resumed, the thread that executes the task may change. + +### Thread Binding + +- FFRT supports task scheduling. The thread to which a task is scheduled is random. Thread-bound behaviors, such as thread_idx, thread priority, and thread affinity, cannot be used in tasks. + +### Synchronization Primitives in the Standard Library + +A deadlock may occur when the mutex of the standard library is used in the FFRT task. You need to use the mutex provided by the FFRT. The details are as follows: + +- When `lock()` is successfully executed, the mutex records the execution stack of the caller as the owner of the lock. If the caller is the current execution stack, a success message is returned to support nested lock obtaining in the same execution stack. In implementation of the standard library, the "execution stack" is represented by a thread identifier. +- When the mutex of the standard library is used in the FFRT task, if the task (coroutine) exits between the outer and inner lock and the task is resumed on the FFRT Worker thread that is different from the thread that calls `lock()` for the first time, the calling thread is not the owner and `lock()` fails to be called, the FFRT Worker thread is suspended, and `unlock()` is not executed. As a result, a deadlock occurs. + +### Support for the Process `fork()` Scenario + +- Create a child process in a process that does not use FFRT. FFRT can be used in the child process. +- Create a child process using `fork()` in a process that uses FFRT. FFRT cannot be used in the child process. +- Create a child process using `fork()` and `exec()` in a process that uses FFRT. FFRT can be used in the child process. + +### Dynamic FFRT Deployment + +- Static library deployment may cause multi-instance problems. For example, when multiple .so files loaded by the same process use FFRT in static library mode, FFRT is instantiated into multiple copies, and their behavior is unknown. + +### Limited Number of Input and Output Dependencies + +- For `ffrt_submit_base`, the total number of input dependencies and output dependencies of each task cannot exceed 8. +- For `ffrt_submit_h_base`, the total number of input dependencies and output dependencies of each task cannot exceed 7. +- When a parameter is used as both an input dependency and an output dependency, it is counted as one dependency. For example, if the input dependency is `{&x}` and the output dependency is also `{&x}`, then the number of dependencies is 1. + +### Restrictions on Process or Thread Exit + +- When a process exits, the shared resources in the process, such as the thread pool in the FFRT, have been released. **submit()** should not be called. +- When a thread exits, the thread local resources in the FFRT have been released. **submit()** should not be called for the thread that is exiting. + +## Common Anti-Patterns + +### After an FFRT object is initialized in the C code, you are responsible for setting the object to null or destroying the object. + +- To ensure high performance, the C APIs of FFRT do not use a flag to indicate the object destruction status. You need to release resources properly. Repeatedly destroying an object will cause undefined behavior. +- Noncompliant example 1: Repeated calling of destroy() may cause unpredictable data damage. + + ```cpp + #include + #include "ffrt/cpp/task.h" + + void abnormal_case_1() + { + ffrt_task_handle_t h = ffrt_submit_h_base( + ffrt::create_function_wrapper(std::function([](){ printf("Test task running...\n"); })), + NULL, NULL, NULL); + // ... + ffrt_task_handle_destroy(h); + ffrt_task_handle_destroy(h); // Repeated release + } + ``` + +- Noncompliant example 2: No calling of destroy() may cause memory leak. + + ```cpp + #include + #include "ffrt/cpp/task.h" + + void abnormal_case_2() + { + ffrt_task_handle_t h = ffrt_submit_h_base( + ffrt::create_function_wrapper(std::function([](){ printf("Test task running...\n"); })), + NULL, NULL, NULL); + // ... + // Memory leak + } + ``` + +- Recommended example: Call **destroy()** only once. You can leave it empty if necessary. + + ```cpp + #include + #include "ffrt/cpp/task.h" + + void normal_case() + { + ffrt_task_handle_t h = ffrt_submit_h_base( + ffrt::create_function_wrapper(std::function([](){ printf("Test task running...\n"); })), + NULL, NULL, NULL); + // ... + ffrt_task_handle_destroy(h); + h = nullptr; // Set the task handle variable to null if necessary. + } + ``` + +### Incorrect Variable Lifecycle + +- When submitting an FFRT task, pay attention to the misuse of objects or resources during their lifecycle. These misuses may cause program breakdown, data damage, or difficult debugging. +- Noncompliant example 1: Ended variable lifecycle causes a UAF problem. + + ```cpp + #include + #include "ffrt/cpp/task.h" + + void abnormal_case_3() + { + int x = 0; + ffrt::submit([&] { + usleep(1000); // Simulate the service processing logic. + x++; // The variable lifecycle may have ended, and a UAF problem may occur when the variable is accessed. + }); + } + ``` + +- Noncompliant example 2: Ended mutex lifecycle causes function exceptions. + + ```cpp + #include + #include "ffrt/cpp/mutex.h" + #include "ffrt/cpp/task.h" + + void abnormal_case_4() + { + ffrt::mutex lock; + ffrt::submit([&] { + lock.lock(); // When performing operations on the FFRT lock, ensure that the lifecycle of the FFRT lock is valid. + usleep(1000); // Simulate the service processing logic. + lock.unlock(); // When performing operations on the FFRT lock, ensure that the lifecycle of the FFRT lock is valid. + }); + } + ``` +## Using FFRT in DevEco IDE -After an FFRT object is initialized in the C code, you are responsible for setting the object to null or destroying the object. +### Using FFRT C API -To ensure high performance, the C APIs of FFRT do not use a flag to indicate the object destruction status. You need to release resources properly. Repeatedly destroying an object will cause undefined behavior. +Native Development Kit (NDK) is a toolset provided by HarmonyOS SDK. It offers native APIs that allow you to implement key application functions using C or C++ code. -Noncompliant example 1: Repeated calling of **destroy()** may cause unpredictable data damage. +The FFRT C APIs have been integrated into the NDK. You can directly use the corresponding API in DevEco IDE. -```{.c} -#include "ffrt.h" -void abnormal_case_1() -{ - ffrt_task_handle_t h = ffrt_submit_h_base([](){printf("Test task running...\n");}, NULL, NULL, NULL, NULL, NULL); - ... - ffrt_task_handle_destroy(h); - ffrt_task_handle_destroy(h); // double free -} +```cpp +#include "ffrt/type_def.h" +#include "ffrt/task.h" +#include "ffrt/queue.h" +#include "ffrt/condition_variable.h" +#include "ffrt/mutex.h" +#include "ffrt/shared_mutex.h" +#include "ffrt/sleep.h" +#include "ffrt/loop.h" +#include "ffrt/timer.h" +``` + +### Using FFRT C++ API + +The FFRT deployment depends on the FFRT dynamic library `libffrt.so` and a group of header files. The dynamic library exports only C APIs, and C++ APIs call C APIs. In addition, C++ elements in APIs are compiled into the dynamic library based on the header files, ensuring ABI compatibility. + +![image](figures/ffrt_figure7.png) + +To use FFRT C++ APIs, you need to use the FFRT third-party library [@ppd/ffrt](https://ohpm.openharmony.cn/#/en/detail/@ppd%2Fffrt), which is a C++ API library officially maintained by FFRT. + +Run the following command in the module directory to install the third-party library: + +```shell +ohpm install @ppd/ffrt ``` -Noncompliant example 2: A memory leak occurs if **destroy()** is not called. +You can also configure the dependencies in the `oh-package.json5` file so that the third-party library can be automatically downloaded and installed through DevEco Studio. + +Add dependencies to the `CMakeLists.txt` file: -```{.c} -#include "ffrt.h" -void abnormal_case_2() -{ - ffrt_task_handle_t h = ffrt_submit_h_base([](){printf("Test task running...\n");}, NULL, NULL, NULL, NULL, NULL); - ... - // Memory leak -} +```txt +target_link_libraries( PUBLIC libffrt.z.so ffrt::ffrtapi) ``` -Recommended example: Call **destroy()** only once; set the object to null if necessary. - -```{.c} -#include "ffrt.h" -void normal_case() -{ - ffrt_task_handle_t h = ffrt_submit_h_base([](){printf("Test task running...\n");}, NULL, NULL, NULL, NULL, NULL); - ... - ffrt_task_handle_destroy(h); - h = nullptr; // if necessary -} +Use the FFRT C++ API in the code. + +```cpp +#include "ffrt/cpp/task.h" +#include "ffrt/cpp/queue.h" +#include "ffrt/cpp/condition_variable.h" +#include "ffrt/cpp/mutex.h" +#include "ffrt/cpp/shared_mutex.h" +#include "ffrt/cpp/sleep.h" ``` diff --git a/en/application-dev/ffrt/ffrt-overview.md b/en/application-dev/ffrt/ffrt-overview.md index a00e8124c0c3207fe1c58126158ba789318fc9cc..6a2cadb49acf55ccb0e8779ad3a1627f9232c0e6 100644 --- a/en/application-dev/ffrt/ffrt-overview.md +++ b/en/application-dev/ffrt/ffrt-overview.md @@ -2,163 +2,64 @@ ## Introduction -Function Flow Runtime Kit provides a concurrent programming framework that allows you to develop an application by creating tasks and describing their dependencies. It supports data dependency management, task executor, and system event processing. It adopts coroutine-based task execution to support more concurrent tasks and improve the thread usage with fewer system threads. It leverages the computing resources of the multi-core platform to ensure intensive resource management. It solves the problem of thread resource abuse and provides the ultimate user experience. +Function Flow Runtime (FFRT) is a concurrent programming framework designed to simplify concurrent programming and task scheduling. You only need to pay attention to tasks and their dependencies in task scheduling without processing underlying threads and computing resources. In addition, FFRT leverages coroutine-based task execution to enhance task parallelism, improve thread utilization, and fully utilizes the computing resources of the multi-core platform to ensure centralized management and optimized scheduling of all system resources. ## Basic Concepts -Function Flow is a task-based and data-driven concurrent programming model that allows you to develop an application by creating tasks and describing their dependencies. Function Flow Runtime (FFRT) is a software runtime library that works with the Function Flow programming model. It is used to schedule and execute tasks of an application developed on the Function Flow programming model. Specifically, FFRT automatically and concurrently schedules and executes tasks of the application based on the task dependency status and available resources, so that you can focus on feature development. +The following describes the basic concepts in FFRT development: -### Programming Models +- **Task**: a combination of programming clues and runtime execution objects. It usually includes a group of instruction sequences and their operation data context. +- **Task dependency**: dependency among tasks. It determines whether a task can be executed only after other tasks are complete, and allows you to define the execution sequence of complex tasks. +- **Quality of Service (QoS)**: quality of service of a task. It is used to indicate task priority and resource allocation. +- **Primitive**: a basic operation or construction used to implement synchronization and mutual exclusion. For example, a mutex or a condition variable. +- **Worker**: a worker thread that executes a task. Each worker can execute multiple tasks. Generally, the scheduler is responsible for managing and allocating tasks. +- **Scheduling**: a process that determines when and which worker executes a task. The scheduler schedules tasks based on factors such as task dependencies and QoS levels. -| Item | Thread Programming Model | FFRT Programming Model | -| -------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| Degree of Parallelism (DOP) mining mode| Programmers create multiple threads and assign tasks to them for parallel execution to achieve the optimal runtime performance.| Programmers, with the help of compilers or programming language features, decompose the application into tasks and describe their data dependencies during static programming. The scheduler allocates tasks to worker threads for execution.| -| Owner for creating threads| Programmers are responsible for creating threads. The maximum number of threads that can be created is not under control.| The scheduler is responsible for creating and managing worker threads. Programmers cannot directly create threads.| -| Load balancing | Programmers map tasks to threads during static programming. Improper mapping or uncertain task execution time will cause a load imbalance among threads.| A ready task is automatically scheduled to an idle thread for execution, reducing the load imbalance among threads.| -| Scheduling overhead | Thread scheduling is implemented by a kernel-mode scheduler, resulting in high scheduling overhead. | Thread scheduling is implemented by a user-mode coroutine scheduler, requiring less scheduling overhead. In addition, FFRT can further reduce the scheduling overhead through hardware-based scheduling offload.| -| Dependency expression | A thread is in the executable state once it is created, and it is executed parallelly with other threads, causing frequent thread switching.| FFRT determines whether a task can be executed based on the input and output dependencies explicitly expressed during task creation. If the input dependencies do not meet the requirements, the task is not scheduled.| +### Programming Models -### Function Flow +| | Thread Programming Model | Task Programming Model | +| -------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | +| Degree of Parallelism (DOP) mining mode| Programmers create multiple threads and assign tasks to them for parallel execution to achieve the optimal runtime performance. | Programmers, with the help of compilers or programming language features, decompose the application into tasks and describe their data dependencies during static programming. The scheduler allocates tasks to worker threads for execution. | +| Owner for creating threads| Programmers are responsible for creating threads. The maximum number of threads that can be created is not under control. | The scheduler is responsible for creating and managing worker threads. Programmers cannot directly create threads. | +| Load balancing | Programmers map tasks to threads during static programming. Improper mapping or uncertain task execution time will cause a load imbalance among threads.| A ready task is automatically scheduled to an idle thread for execution, reducing the load imbalance among threads. | +| Scheduling overhead | Thread scheduling is implemented by a kernel-mode scheduler, resulting in high scheduling overhead. | Thread scheduling is implemented by a user-mode coroutine scheduler, requiring less scheduling overhead. In addition, FFRT can further reduce the scheduling overhead through hardware-based scheduling offload.| +| Dependency expression | A thread is in the executable state once it is created, and it is executed parallelly with other threads, causing frequent thread switching. | FFRT determines whether a task can be executed based on the input and output dependencies explicitly expressed during task creation. If the input dependencies do not meet the requirements, the task is not scheduled. | -The Function Flow programming model allows you to develop an application by creating tasks and describing their dependencies. Its most outstanding features are task-based and data-driven. +### FFRT Programming Model -#### Task-based +The FFRT programming model allows you to develop applications by describing tasks and their dependencies. Its main features include `Task-Based`, `Queue-Enabled`, and `Graph-Driven`. -Task-based means that you can use tasks to express an application and schedule the tasks at runtime. +#### Task-Based -A task is defined as a developer-oriented programming clue and a runtime-oriented execution object. It usually contains a set of sequential instructions and a data context environment to run the instructions. +The `Task-Based` feature means that you can use tasks to express an application and schedule the tasks at runtime. -Tasks in the Function Flow programming model have the following features: +The tasks in the FFRT programming model have the following features: -- The dependency between tasks can be specified in data-driven form. +- Task dependencies can be directly specified, or expressed using data objects. - Tasks can be nested. That is, when a task is being executed, a new task can be generated and delivered to that task to form a parent-child relationship. - Simultaneous operations, such as wait, lock, and condition variables, are supported. > **NOTE** > -> The task granularity determines the number of concurrent tasks and therefore affects the application execution performance. A small granularity increases the scheduling overhead, whereas a large granularity decreases the DOP. The minimum task granularity allowed in the Function Flow programming model is 100 μs. - -#### Data-driven - -Data-driven means that the dependency between tasks is expressed through data dependencies. - -Data objects associated with a task are read and written during task execution. In the Function Flow programming model, a data object is abstracted as a data signature. They are in one-to-one mapping. - -Data dependencies, consisting of **in_deps** and **out_deps**, are abstracted as a list of data signatures mapping to the data objects manipulated by the task. When the signature of a data object appears in **in_deps** of a task, the task is a consumer task of the data object. The execution of a consumer task does not change the content of the input data object. When the signature of a data object appears in **out_deps** of a task, the task is a producer task of the data object. The execution of a producer task changes the content of the output data object and generates a new version of the data object. - -A data object may have multiple versions. Each version corresponds to one producer task and zero, one, or more consumer tasks. A sequence of the data object versions and the version-specific producer task and consumer tasks are defined according to the delivery sequence of the producer task and consumer tasks. - -When all producer tasks and consumer tasks of the data object of all the available versions are executed, the data dependency is removed. In this case, the task enters the ready state and can be scheduled for execution. - -With the data-driven dependency expression, FFRT can dynamically build different types of data dependencies between tasks and schedule the tasks based on the data dependency status at runtime. The following data dependency types are available: - -- Producer-Consumer dependency - - A dependency formed between the producer task of a data object of a specific version and a consumer task of the data object of the same version. It is also referred to as a read-after-write dependency. - -- Consumer-Producer dependency - - A dependency formed between a consumer task of a data object of a specific version and the producer task of the data object of the next version. It is also referred to as a write-after-read dependency. - -- Producer-Producer dependency - - A dependency formed between the producer task of a data object of a specific version and a producer task of the data object of the next version. It is also referred to as a write-after-write dependency. - -Assume that the relationship between some tasks and data A is as follows: - -```cpp -task1(OUT A); -task2(IN A); -task3(IN A); -task4(OUT A); -task5(OUT A); -``` - -![image](figures/ffrtfigure3.png) - -> **NOTE** -> -> For ease of description, circles are used to represent tasks and squares are used to represent data. - -The following conclusions can be drawn: - -- task1 and task2/task3 form a producer-consumer dependency. This means that task2/task3 can read data A only after task1 writes data A. -- task2/task3 and task4 form a consumer-producer dependency. This means that task4 can write data A only after task2/task3 reads data A. -- task 4 and task 5 form a producer-producer dependency. This means that task 5 can write data A only after task 4 writes data A. - -## Constraints - -### The **thread_local** variable is not supported. - -The behavior of creating the **thread_local** variable in a task or transferring it between tasks is uncertain. The reason is that FFRT does not have the concept of thread. It only has the concept of task. - -In C++ semantics, the **thread_local** variable can be compiled, but it is uncertain the thread on which the task that uses the variable is executed. - -For non-worker threads in FFRT processes, the behavior of the **thread_local** variable is not affected by FFRT. - -Similar problems occur for thread-bound features such as thread_idx, pthread_specific, recursive lock, thread priority, thread affinity, and recursive lock. - -Do not use these features. If these features are required, use **task local** of FFRT instead. - -### Do not use FFRT in forked subprocesses. - -### Deploy FFRT in dynamic library mode. - -Static library deployment may cause multi-instance problems. For example, when multiple .so files loaded by the same process use FFRT in static library mode, FFRT is instantiated into multiple copies, and their behavior is unknown. - -### After an FFRT object is initialized in the C code, you are responsible for setting the object to null or destroying the object. - -To ensure high performance, the C APIs of FFRT do not use a flag to indicate the object destruction status. You need to release resources properly. Repeatedly destroying an object will cause undefined behavior. - -Noncompliant example 1: Repeated calling of **destroy()** may cause unpredictable data damage. - -```{.cpp} -#include "ffrt.h" -void abnormal_case_1() -{ - ffrt_task_handle_t h = ffrt_submit_h([](){printf("Test task running...\n");}, NULL, NULL, NULL, NULL, NULL); - ... - ffrt_task_handle_destroy(h); - ffrt_task_handle_destroy(h); // double free -} -``` - -Noncompliant example 2: A memory leak occurs if **destroy()** is not called. - -```{.cpp} -#include "ffrt.h" -void abnormal_case_2() -{ - ffrt_task_handle_t h = ffrt_submit_h([](){printf("Test task running...\n");}, NULL, NULL, NULL, NULL, NULL); - ... - // Memory leak -} -``` +> The task granularity determines the number of concurrent tasks and therefore affects the application execution performance. A small granularity increases the scheduling overhead, whereas a large granularity decreases the DOP. The minimum task granularity allowed in the FFRT programming model is 100 μs. -Recommended example: Call **destroy()** only once; set the object to null if necessary. +#### Queue-Enabled -```{.cpp} -#include "ffrt.h" -void normal_case() -{ - ffrt_task_handle_t h = ffrt_submit_h([](){printf("Test task running...\n");}, NULL, NULL, NULL, NULL, NULL); - ... - ffrt_task_handle_destroy(h); - h = nullptr; // if necessary -} -``` +The `Queue-Enabled` feature means that you can use task queues to restrict task execution sequence and concurrency at runtime. Task queues include serial queues and concurrent queues, which are used in different scenarios. -### The number of input and output dependencies is limited. +- The serial queue ensures that tasks are executed in sequence according to the submission sequence. It is applicable to the task flow that maintains a specific execution sequence. +- The concurrent queue allows multiple tasks to be executed at the same time, improving concurrency performance. It is applicable to parallel computing and efficient use of multi-core processors. +- The concurrent queue can also restrict the overall concurrency of a task unit to ensure that system resources are properly allocated and avoid performance bottlenecks or system instability caused by excessive concurrency. -For **submit()**, the total number of input dependencies and output dependencies of each task cannot exceed 8. +The `Queue-Enabled` feature provides you with flexible task scheduling modes. You can select a proper task execution policy based on your requirements to optimize the performance of your applications. -For **submit_h()**, the total number of input dependencies and output dependencies of each task cannot exceed 7. +#### Graph-Driven -When a parameter is used as both an input dependency and an output dependency, it is counted as one dependency. For example, if the input dependency is {&x} and the output dependency is also {&x}, then the number of dependencies is 1. +The `Graph-Driven` feature means that you can use dependency graphs to manage task dependencies and implement efficient scheduling of complex task flows. -### It is recommended that FFRT mutex be used in FFRT task context. -FFRT provides performance implementation similar to **std::mutex**. FFRT mutex can be called only inside an FFRT task. If it is called outside an FFRT task, undefined behavior may occur. +The FFRT programming model supports two methods to build task dependency graphs: -**std::mutex** may cause unexpected kernel mode trap when it fails to lock a mutex. FFRT mutex solves this problem and therefore provides better performance if used properly. +- **Task dependency**: Task dependencies are directly described. +- **Data flow**: Task dependencies are described based on the relationship between data producers and consumers. -FFRT supports a maximum of eight worker threads. When eight tasks use **std::mutex** at the same time, deadlock occurs on all threads during coroutine switchover. Therefore, exercise caution when using **std::mutex**. +You can select a proper method described above based on service characteristics to simplify service models and development. diff --git a/en/application-dev/ffrt/figures/ffrt_figure1.png b/en/application-dev/ffrt/figures/ffrt_figure1.png new file mode 100644 index 0000000000000000000000000000000000000000..f8dba9cbf44ee134542338ea534caf2bf5a7497a Binary files /dev/null and b/en/application-dev/ffrt/figures/ffrt_figure1.png differ diff --git a/zh-cn/application-dev/ffrt/figures/ffrtfigure2.png b/en/application-dev/ffrt/figures/ffrt_figure2.png similarity index 100% rename from zh-cn/application-dev/ffrt/figures/ffrtfigure2.png rename to en/application-dev/ffrt/figures/ffrt_figure2.png diff --git a/zh-cn/application-dev/ffrt/figures/ffrtfigure3.png b/en/application-dev/ffrt/figures/ffrt_figure3.png similarity index 100% rename from zh-cn/application-dev/ffrt/figures/ffrtfigure3.png rename to en/application-dev/ffrt/figures/ffrt_figure3.png diff --git a/en/application-dev/ffrt/figures/ffrt_figure4.png b/en/application-dev/ffrt/figures/ffrt_figure4.png new file mode 100644 index 0000000000000000000000000000000000000000..a869663d46ce0bf70ba2e1a825a8ecd0a38480d7 Binary files /dev/null and b/en/application-dev/ffrt/figures/ffrt_figure4.png differ diff --git a/en/application-dev/ffrt/figures/ffrt_figure5.png b/en/application-dev/ffrt/figures/ffrt_figure5.png new file mode 100644 index 0000000000000000000000000000000000000000..a1798ffe313dc07c0890b1e2c77999f90b286fe9 Binary files /dev/null and b/en/application-dev/ffrt/figures/ffrt_figure5.png differ diff --git a/en/application-dev/ffrt/figures/ffrt_figure6.png b/en/application-dev/ffrt/figures/ffrt_figure6.png new file mode 100644 index 0000000000000000000000000000000000000000..dc5fe24037c4ee2d12711baa67dbd5402f23d5c5 Binary files /dev/null and b/en/application-dev/ffrt/figures/ffrt_figure6.png differ diff --git a/en/application-dev/ffrt/figures/ffrt_figure7.png b/en/application-dev/ffrt/figures/ffrt_figure7.png new file mode 100644 index 0000000000000000000000000000000000000000..30c087b96cc0251ab7d43dc3989f78dd09a8e7d5 Binary files /dev/null and b/en/application-dev/ffrt/figures/ffrt_figure7.png differ diff --git a/en/application-dev/file-management/Readme-EN.md b/en/application-dev/file-management/Readme-EN.md index 941f093a0dc3761f6b468b794084649e26f8fe80..af25fa02db376b715f14679f9190abb64e3b03bd 100644 --- a/en/application-dev/file-management/Readme-EN.md +++ b/en/application-dev/file-management/Readme-EN.md @@ -1,10 +1,10 @@ -# Core File Kit (Basic File Services) +# Core File Kit - [Introduction to Core File Kit](core-file-kit-intro.md) -- Application Files +- Application Files - [Application File Overview](app-file-overview.md) - [Application Sandbox](app-sandbox-directory.md) - - Application File Access and Management + - Application File Access and Management - [Accessing Application Files (ArkTS)](app-file-access.md) - [Accessing Application Files (C/C++)](native-fileio-guidelines.md) - [Obtaining Application and File System Space Statistics](app-fs-space-statistics.md) @@ -12,28 +12,28 @@ - [Pushing Files to an Application Sandbox Directory](send-file-to-app-sandbox.md) - [Sharing an Application File](share-app-file.md) - - Application Data Backup and Restore + - Application Data Backup and Restore - [Application Data Backup and Restore Overview](app-file-backup-overview.md) - [Accessing Backup and Restore](app-file-backup-extension.md) - [Triggering Backup and Restore (for System Applications Only)](app-file-backup.md) -- User Files +- User Files - [User File Overview](user-file-overview.md) - [User File URI](user-file-uri-intro.md) - [FileUri Development (C/C++)](native-fileuri-guidelines.md) - [Obtaining the User Directory Environment (C/C++)](native-environment-guidelines.md) - - Selecting and Saving User Files + - Selecting and Saving User Files - [Selecting User Files](select-user-file.md) - [Saving User Files](save-user-file.md) - [Persisting Temporary Permissions (ArkTS)](file-persistPermission.md) - [Persisting Temporary Permissions (C/C++)](native-fileshare-guidelines.md) - [Obtaining and Accessing a User Directory](request-dir-permission.md) - - [Developing a File Manager Application (for System Applications Only)](dev-user-file-manager.md) + - [Developing a FileManager Application (for System Applications Only)](dev-user-file-manager.md) - [Managing External Storage Devices (for System Applications Only)](manage-external-storage.md) -- Distributed File System +- Distributed File System - [Distributed File System Overview](distributed-fs-overview.md) - [Setting the Security Level of a Distributed File](set-security-label.md) - [Accessing Files Across Devices](file-access-across-devices.md) diff --git a/en/application-dev/file-management/app-file-access.md b/en/application-dev/file-management/app-file-access.md index d9a42f97f3243a6d4a1a1fa75ff15fa43a6d6622..992cb15584691c76dd989de82da86ab09dcca804 100644 --- a/en/application-dev/file-management/app-file-access.md +++ b/en/application-dev/file-management/app-file-access.md @@ -57,18 +57,21 @@ let context = getContext(this) as common.UIAbilityContext; let filesDir = context.filesDir; function createFile(): void { - // Create a file and open it. + // Create and open a file if the file does not exist. Open it if the file exists. let file = fs.openSync(filesDir + '/test.txt', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); // Write data to the file. let writeLen = fs.writeSync(file.fd, "Try to write str."); console.info("The length of str is: " + writeLen); - // Read data from the file. + // Create an ArrayBuffer object whose size is 1024 bytes to store the data read from the file. let arrayBuffer = new ArrayBuffer(1024); + // Set the offset and length to be read. let readOptions: ReadOptions = { offset: 0, length: arrayBuffer.byteLength }; + // Read the file content to the ArrayBuffer object and return the number of bytes read. let readLen = fs.readSync(file.fd, arrayBuffer, readOptions); + // Convert the ArrayBuffer object into a Buffer object and output it as a string. let buf = buffer.from(arrayBuffer, 0, readLen); console.info("the content of file: " + buf.toString()); // Close the file. @@ -123,7 +126,7 @@ function readWriteFile(): void { ### Reading and Writing Files in a Stream -The following example demonstrates how to read and write file data using a stream. +The following sample code shows how to use the **stream()** API to read the **test.txt** file content and write the content to the **destFile.txt** file. ```ts // pages/xxx.ets @@ -135,10 +138,11 @@ let context = getContext(this) as common.UIAbilityContext; let filesDir = context.filesDir; async function readWriteFileWithStream(): Promise { - // Open the file streams. + // Create and open an input file stream. let inputStream = fs.createStreamSync(filesDir + '/test.txt', 'r+'); + // Create and open an output file stream. let outputStream = fs.createStreamSync(filesDir + '/destFile.txt', "w+"); - // Read data from the source file and write the data to the destination file using a stream. + let bufSize = 4096; let readSize = 0; let buf = new ArrayBuffer(bufSize); @@ -146,6 +150,7 @@ async function readWriteFileWithStream(): Promise { offset: readSize, length: bufSize }; + // Read data from the source file and write the data to the destination file using a stream. let readLen = await inputStream.read(buf, readOptions); readSize += readLen; while (readLen > 0) { @@ -163,13 +168,11 @@ async function readWriteFileWithStream(): Promise { > **NOTE** > -> - Close the stream once it is not required. -> - Comply with the programming specifications for **Stream** APIs in asynchronous mode and avoid mixed use of the APIs in synchronous mode and asynchronous mode. -> - The **Stream** APIs do not support concurrent read and write operations. +> Close the stream once it is not required.
Comply with the programming specifications for **Stream** APIs in asynchronous mode and avoid mixed use of the APIs in synchronous mode and asynchronous mode.
The **Stream** APIs do not support concurrent read and write operations. ### Listing Files -The following example demonstrates how to obtain files that meet the specified conditions. +The following example demonstrates how to list files that meet the specified conditions. ```ts import { fileIo as fs, Filter, ListFileOptions } from '@kit.CoreFileKit'; @@ -216,7 +219,7 @@ function copyFileWithReadable(): void { const rs = fs.createReadStream(`${filesDir}/read.txt`); // Create a writable stream. const ws = fs.createWriteStream(`${filesDir}/write.txt`); - // Copy files in paused mode. + // Copy files in paused mode. Pause file operation and copy the original file data to another location, to ensure data integrity and consistency. rs.on('readable', () => { const data = rs.read(); if (!data) { @@ -231,7 +234,7 @@ function copyFileWithData(): void { const rs = fs.createReadStream(`${filesDir}/read.txt`); // Create a writable stream. const ws = fs.createWriteStream(`${filesDir}/write.txt`); - // Copy files in flowing mode. + // Copy files in stream mode. Read and write file data while accessing the original data, to ensure data timeliness. rs.on('data', (emitData) => { const data = emitData?.data; if (!data) { @@ -240,10 +243,11 @@ function copyFileWithData(): void { ws.write(data as Uint8Array); }); } - ``` -The following example demonstrates how to use a file hash stream. +### Using File Hash Streams + +A hash stream is a data transmission and storage technology that can convert data of any length into a hash value of a fixed length to verify data integrity and consistency. The following code shows how to use the file hash processing API [ohos.file.hash](../reference/apis-core-file-kit/js-apis-file-hash.md) to process file hash streams. ```ts // pages/xxx.ets diff --git a/en/application-dev/file-management/app-file-backup-extension.md b/en/application-dev/file-management/app-file-backup-extension.md index 267385cc9f11dcacd45ffeabe3681817e8d8ad15..247d260cc4b5384689edb5f87dc75b07b6b60673 100644 --- a/en/application-dev/file-management/app-file-backup-extension.md +++ b/en/application-dev/file-management/app-file-backup-extension.md @@ -11,14 +11,15 @@ For details about how to use the APIs, see [BackupExtensionAbility](../reference ## Constraints - The path of the file or directory to be backed up or restored cannot exceed 4095 bytes. Otherwise, undefined behavior may occur. -- If a directory needs to be backed up, the application process must have the permission to read the directory and all its subdirectories (**r** in DAC). Otherwise, the backup fails. -- If a file needs to be backed up, the application process must have the permission to retrieve all the ancestor directories of the file (**x** in DAC). Otherwise, the backup fails. +- If a directory needs to be backed up, the application process must have the permission to read the directory and all its subdirectories (`r` in DAC). Otherwise, the backup fails. +- If a file needs to be backed up, the application process must have the permission to retrieve all the ancestor directories of the file (`x` in DAC). Otherwise, the backup fails. +- The path of the file or directory to be backed up or restored does not support relative paths (**../**) and soft links. ## How to Develop -1. Add **extensionAbilities** to the application's **module.json5** file. +1. Add `extensionAbilities` to the application's `module.json5` file. - In **module.json5**, add the **extensionAbilities** field, set **type** to **backup**, and add a record with **name** set to **ohos.extension.backup** under **["metadata"](../reference/apis-ability-kit/js-apis-bundleManager-metadata.md)**. + In `module.json5`, add the `extensionAbilities` field, set `type` to `backup`, and add a record with `name` set to `ohos.extension. backup` under **["metadata"](../reference/apis-ability-kit/js-apis-bundleManager-metadata.md)**. Example: @@ -37,7 +38,8 @@ For details about how to use the APIs, see [BackupExtensionAbility](../reference "resource": "$profile:backup_config" } ], - // In the BackupExtension.ets file, define BackupExtensionAbility in extensionAbilities and override onBackup or onBackupEx and onRestore or onRestoreEx methods. The onBackupEx and onRestoreEx methods are recommended. + // In the BackupExtension.ets file, define BackupExtensionAbility in extensionAbilities and override onBackup or onBackupEx + // and onRestore or onRestoreEx methods. The onBackupEx and onRestoreEx methods are recommended. // Empty implementation can be used if there is no special requirement. In this case, the backup and restore service backs up or restores data based on the unified backup and restore rules. "srcEntry": "./ets/BackupExtension/BackupExtension.ets", } @@ -69,7 +71,7 @@ For details about how to use the APIs, see [BackupExtensionAbility](../reference Empty implementation can be used if there is no special requirement. In this case, the backup and restore service backs up or restores data based on the unified backup and restore rules. - The following example shows an empty implementation of the **BackupExtension.ets** file. + The following example shows an empty implementation of the `BackupExtension.ets` file. ```ts //onBackup && onRestore @@ -130,10 +132,10 @@ For details about how to use the APIs, see [BackupExtensionAbility](../reference | Field | Type | Mandatory| Description | | -------------------- | ---------- | ---- | ------------------------------------------------------------ | | allowToBackupRestore | Boolean | Yes | Whether to enable backup and restore. The default value is **false**. | -| includes | String array| No | Files and directories to be backed up in the application sandbox directory.
The pattern string that does not start with a slash (/) indicates a relative path.
If **includes** is not configured, the backup and restore framework uses the **includes** default (as listed in the code snippet below).| -| excludes | String array| No | Items in **includes** that do not need to be backed up. The value is in the same format as **includes**.
If **excludes** is not configured, the backup and restore framework uses an empty array by default.| +| includes | String array| No | Files and directories to be backed up in the application sandbox directory.
The pattern string that does not start with a slash (/) indicates a relative path.
When configuring `includes`, ensure that the configured path range is included in the supported paths listed in the following code snippet.
If `includes` is not configured, the backup and restore framework uses the **includes** default (as listed in the code snippet below).| +| excludes | String array| No | Items in `includes` that do not need to be backed up. The value is in the same format as `includes`.
When configuring `excludes`, ensure that it is within the subset of `includes`.
If `excludes` is not configured, the backup and restore framework uses an empty array by default.| | fullBackupOnly | Boolean | No | Whether to use the default restore directory of the application. The default value is **false**. If the value is **true**, data will be cached in a temporary directory obtained by [backupDir](../reference/apis-core-file-kit/js-apis-file-backupextensioncontext.md) in the data restore process. If it is **false** or not specified, the restored data is decompressed in **/**.| -| restoreDeps | String | No | **(Not recommended)** Dependencies for the application to restore.
The default value is "".
You need to configure the names of the dependent applications. Currently, only one dependency is supported. The configured dependency takes effect only in the context of one restore task. If no dependent application is detected, the dependency description will be ignored and the restore task continues. The application restore will fail if the dependent application is not restored or fails to be restored.| +| restoreDeps | String | No | **(Not recommended)** Dependencies for the application to restore. The default value is "". You need to configure the names of the dependent applications. Currently, only one dependency is supported. The configured dependency takes effect only in the context of one restore task. If no dependent application is detected, the dependency description will be ignored and the restore task continues. The application restore will fail if the dependent application is not restored or fails to be restored.| | extraInfo | JSON string | No | Additional information to be passed. | > **NOTE** @@ -143,11 +145,12 @@ For details about how to use the APIs, see [BackupExtensionAbility](../reference > - If **fullBackupOnly** is set to **false**, the restored data will be decompressed in the root directory **/**, and the file with the same name in the directory will be overwritten. > - If **fullBackupOnly** is set to **true**, the restored data will be decompressed in a temporary directory. You need to implement the data restoration logic in **OnRestore** or **OnRestoreEx**. > -> You can determine the data restore mode to use based on service requirements. Assume that the temporary directory is **/data/storage/el2/base/.backup/restore/** and the data backup directory of the application is **data/storage/el2/base/files/A/**. +> You can determine the data restore mode to use based on service requirements. > -> If **fullBackupOnly** is **false**, the restored data will be decompressed to the **/data/storage/el2/base/files/A/** directory. If **fullBackupOnly** is **true**, data will be decompressed to the **/data/storage/el2/base/.backup/restore/data/storage/el2/base/files/A/** directory. +> Example: +> Assume that the application backup path is **data/storage/el2/base/files/A/**. If **fullBackupOnly** is **false**, the restored data will be decompressed to the **/data/storage/el2/base/files/A/** directory. If **fullBackupOnly** is **true**, data will be decompressed to the temporary directory **[backupDir](../reference/apis-core-file-kit/js-apis-file-backupextensioncontext.md)/restore/data/storage/el2/base/files/A/**. -**includes** defaults: +The following lists the paths supported by **includes**: ```json { @@ -155,14 +158,25 @@ For details about how to use the APIs, see [BackupExtensionAbility](../reference "data/storage/el1/database/", "data/storage/el1/base/files/", "data/storage/el1/base/preferences/", - "data/storage/el1/base/haps//files/", - "data/storage/el1/base/haps//preferences/", + "data/storage/el1/base/haps/*/files/", + "data/storage/el1/base/haps/*/preferences/", "data/storage/el2/database/", "data/storage/el2/base/files/", "data/storage/el2/base/preferences/", - "data/storage/el2/base/haps//files/", - "data/storage/el2/base/haps//preferences/", - "data/storage/el2/distributedfiles/" + "data/storage/el2/base/haps/*/files/", + "data/storage/el2/base/haps/*/preferences/", + "data/storage/el2/distributedfiles/", + "data/storage/el5/database/", + "data/storage/el5/base/files/", + "data/storage/el5/base/preferences/", + "data/storage/el5/base/haps/*/files/", + "data/storage/el5/base/haps/*/preferences/" ] } ``` + +## + + + +- diff --git a/en/application-dev/file-management/app-file-backup.md b/en/application-dev/file-management/app-file-backup.md index edd4dbe027c94e32146e2ffdbea3ad60e8de4ee5..88e016ba9fd541fd793f75b64e9a54692f993e24 100644 --- a/en/application-dev/file-management/app-file-backup.md +++ b/en/application-dev/file-management/app-file-backup.md @@ -66,7 +66,7 @@ async function getLocalCapabilities(): Promise { | spaceOccupied | Number | Yes | Space occupied by the application data.| | versionCode | Number | Yes | Application version number. | | versionName | String | Yes | Application version name. | -| deviceType | String | Yes | Type of the device. | +| deviceType | String | Yes | Device type. | | systemFullName | String | Yes | Device version. | ```json diff --git a/en/application-dev/file-management/app-fs-space-statistics.md b/en/application-dev/file-management/app-fs-space-statistics.md index 30bcd684c50adf0284d5b9cabc98bf2f793f81f8..c22c9306ad5a50813464fe5c58832997b9cc5a06 100644 --- a/en/application-dev/file-management/app-fs-space-statistics.md +++ b/en/application-dev/file-management/app-fs-space-statistics.md @@ -4,28 +4,32 @@ This topic describes how to obtain statistics on the space occupied by your appl ## Available APIs -For details about the APIs, see [ohos.file.statvfs](../reference/apis-core-file-kit/js-apis-file-statvfs.md) and [ohos.file.storageStatistics](../reference/apis-core-file-kit/js-apis-file-storage-statistics.md). +For details about APIs, see [ohos.file.statvfs](../reference/apis-core-file-kit/js-apis-file-statvfs.md) and [ohos.file.storageStatistics](../reference/apis-core-file-kit/js-apis-file-storage-statistics.md). **Table 1** APIs for application and file system space statistics | Module| API| Description| | -------- | -------- | -------- | -| \@ohos.file.storageStatistics | getCurrentBundleStats | Obtains the storage space of the current application, in bytes.| -| \@ohos.file.statvfs | getFreeSize | Obtains the free space of a file system, in bytes.| -| \@ohos.file.statvfs | getTotalSize | Obtains the total space of a file system, in bytes.| +| \@ohos.file.storageStatistics | getCurrentBundleStats | Obtains the storage space of the current application, in bytes.| +| \@ohos.file.storageStatistics | getFreeSize | Obtains the total space of the built-in storage, in bytes. This API returns the result asynchronously.| +| \@ohos.file.storageStatistics | getFreeSizeSync | Obtains the total space of the built-in storage, in bytes. This API returns the result synchronously.| +| \@ohos.file.storageStatistics | getTotalSize | Obtains the available space of the built-in storage, in bytes. This API returns the result asynchronously.| +| \@ohos.file.storageStatistics | getTotalSizeSync | Obtains the available space of the built-in storage, in bytes. This API returns the result synchronously.| +| \@ohos.file.statvfs | getFreeSize | Obtains the free space of a file system, in bytes.| +| \@ohos.file.statvfs | getTotalSize | Obtains the total space of a file system, in bytes.| **Table 2** Attributes for application space statistics | BundleStats Attribute| Description| Directory for Statistics| | -------- | -------- | -------- | -| appSize | Size of the application installation files, in bytes.| /data/storage/el1/bundle| -| cacheSize | Size of the application cache files, in bytes.| /data/storage/el1/base/cache
/data/storage/el1/base/haps/entry/cache
/data/storage/el2/base/cache
/data/storage/el2/base/haps/entry/cache| -| dataSize | Size of other files of the application, in bytes.| The files include local files, distributed files, and database files of the application.
- Local file directories (parent directories of the **cache** directories):
**/data/storage/el1/base**
**/data/storage/el2/base**
- Distributed file directory:
**/data/storage/el2/distributedfiles**
- Database directories:
**/data/storage/el1/database**
**/data/storage/el2/database**| +| appSize | Size of the application installation files, in bytes.| Application installation file directory:
**/data/storage/el1/bundle**| +| cacheSize | Size of the application cache files, in bytes.| Application cache file directories:
**/data/storage/el1/base/cache**
**/data/storage/el1/base/haps/entry/cache**
**/data/storage/el2/base/cache**
**/data/storage/el2/base/haps/entry/cache**| +| dataSize | Size of other files of the application, in bytes.| The files include local files, distributed files, and database files of the application.
- Local file directories (parent directories of the **cache** directories):
**/data/storage/el1/base**
**/data/storage/el2/base**
- Distributed application directory:
/data/storage/el2/distributedfiles
- Database directories:
**/data/storage/el1/database**
**/data/storage/el2/database**| ## Development Example - Obtain the free space of **/data** of the file system. - + ```ts import { statfs } from '@kit.CoreFileKit'; import { BusinessError } from '@kit.BasicServicesKit'; @@ -43,7 +47,7 @@ For details about the APIs, see [ohos.file.statvfs](../reference/apis-core-file- ``` - Obtain the space occupied by the current application. - + ```ts import { storageStatistics } from '@kit.CoreFileKit'; import { BusinessError } from '@kit.BasicServicesKit'; @@ -56,3 +60,59 @@ For details about the APIs, see [ohos.file.statvfs](../reference/apis-core-file- } }); ``` + +- Obtain the total space of the built-in storage asynchronously. + + ```ts + import { storageStatistics } from '@kit.CoreFileKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + storageStatistics.getTotalSize().then((number: number) => { + console.info("getTotalSize successfully:" + JSON.stringify(number)); + }).catch((err: BusinessError) => { + console.error("getTotalSize failed with error:"+ JSON.stringify(err)); + }); + ``` + +- Obtain the total space of the built-in storage synchronously. + + ```ts + import { storageStatistics } from '@kit.CoreFileKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + try { + let number = storageStatistics.getTotalSizeSync(); + console.info("getTotalSizeSync successfully:" + JSON.stringify(number)); + } catch (err) { + let error: BusinessError = err as BusinessError; + console.error("getTotalSizeSync failed with error:" + JSON.stringify(error)); + } + ``` + +- Obtain the available space of the built-in storage asynchronously. + + ```ts + import { storageStatistics } from '@kit.CoreFileKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + storageStatistics.getFreeSize().then((number: number) => { + console.info("getFreeSize successfully:" + JSON.stringify(number)); + }).catch((err: BusinessError) => { + console.error("getFreeSize failed with error:" + JSON.stringify(err)); + }); + ``` + +- Obtain the available space of the built-in storage synchronously. + + ```ts + import { storageStatistics } from '@kit.CoreFileKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + try { + let number = storageStatistics.getFreeSizeSync(); + console.info("getFreeSizeSync successfully:" + JSON.stringify(number)); + } catch (err) { + let error: BusinessError = err as BusinessError; + console.error("getFreeSizeSync failed with error:" + JSON.stringify(error)); + } + ``` diff --git a/en/application-dev/file-management/app-sandbox-directory.md b/en/application-dev/file-management/app-sandbox-directory.md index dc72475a8643231f2e40e7eab203aad594ff750f..102724f91981ecdde7f2f7f3b3212d46c509b365 100644 --- a/en/application-dev/file-management/app-sandbox-directory.md +++ b/en/application-dev/file-management/app-sandbox-directory.md @@ -11,7 +11,6 @@ The application sandbox is an isolation mechanism used to prevent malicious data The following figure illustrates the file access mechanism in the application sandbox. **Figure 1** File access mechanism in the application sandbox - ![Application sandbox file access relationship](figures/application-sandbox-file-access-relationship.png) ## Application Sandbox Directory and Application Sandbox Path @@ -27,7 +26,6 @@ With the application sandbox mechanism, an application is not aware of the exist - The application sandbox paths and physical paths are not in one-to-one mappings. The application sandbox paths are always shorter than physical paths. Some physical paths do not have the corresponding application sandbox paths. **Figure 2** Different directory views to processes and applications - ![Application sandbox path](figures/application-sandbox-path.png) ## Application File Directory and Application File Path @@ -39,7 +37,6 @@ The system file directory visible to an application is preset by OpenHarmony. The following figure shows the application file directory structure. The path of a file or a folder in the application file directory is called the application file path. The application file paths have different attributes. **Figure 3** Application file directory structure - ![Application file directory structure](figures/application-file-directory-structure.png) > **NOTE** @@ -51,16 +48,39 @@ The following figure shows the application file directory structure. The path of 2. Level 2 directory **storage/**: directory for persistent files of the application. -3. Level 3 directories **el1/** and **el2/**: directories for files of different encryption levels. - - **el1**: device-level encrypted directory for the data that can be accessed once the device starts. - - **el2**: user-level encrypted directory. If the device does not have a lock screen password, data in this directory can be directly accessed when the device is powered on. If the device has a lock screen password, data in this directory can be accessed only after at least one successful authentication (PIN, fingerprint, facial authentication, or the like).
- Unless otherwise required, application data is placed in the **el2** directory for security purposes. The data that needs to be accessed before the screen is unlocked (such as the clock, alarm, and wallpaper data) is placed in the **el1** directory. For details about the operations on **el1/** and **el2/**, see [Obtaining and Modifying el Directories](../application-models/application-context-stage.md#obtaining-and-modifying-encryption-levels). +3. There are files of different encryption levels in **el1/** and **el5/**. + + EL1 (Encryption Level 1): + - All files are protected on the device. After the device is powered on, users can access the files protected by EL1 without identity authentication. This mode is not recommended unless otherwise specified. + - The ciphertext stolen from the storage device cannot be decrypted offline. + + EL2 (Encryption Level 2): + - On the basis of EL1, files are protected after the first user authentication. After the device is powered on, users can access the files protected by EL2 only after the first authentication. Those files are always accessible as long as the device is online. This mode is recommended by default. + - Files cannot be read by attackers if the phone is lost after power-off. + + EL3 (Encryption Level 3): + - Files can be created but cannot be read when the screen is locked, which is different from EL4. This mode is not required unless otherwise specified. + + EL4 (Encryption Level 4): + - On the basis of EL2, files are protected when the device screen is locked. In this case, data protected by EL4 cannot be accessed. This mode is not required unless otherwise specified. + - Files cannot be read by attackers if the device is stolen with screen locked. + + EL5 (Encryption Level 5): + - On the basis of EL2, files are protected when the device screen is locked. In this case, data protected by EL5 cannot be accessed, but files can be created, read, and written. This mode is not required unless otherwise specified. + - EL5 directories are not generated by default unless the permissions for access to the EL5 database are configured. For details, see [Using an EL5 Database](../database/encrypted_estore_guidelines.md). + + > **NOTE** + > + > Unless otherwise required, application data is placed in the **el2** directory for security purposes. The data that needs to be accessed before the first user authentication (such as the clock, alarm, and wallpaper data) is placed in the **el1** directory. + > + > You can listen for the [COMMON_EVENT_USER_UNLOCKED](../reference/apis-basic-services-kit/common_event/commonEventManager-definitions.md#common_event_user_unlocked) event to detect that the first user authentication is complete. + > + > For details about the operations on **el1/** and **el2/**, see [Obtaining and Modifying el Directories](../application-models/application-context-stage.md#obtaining-and-modifying-encryption-levels). -4. Level 4 and level 5 directories: directories for the application global information and OpenHarmony Ability Packages (HAPs). An application in the development state has one or more HAPs. For details, see [Application Package Structure in Stage Model](../quick-start/application-package-structure-stage.md). - The application global data is stored in the **distributedfiles** directory and **files**, **cache**, **preferences**, and **temp** in **base**. You can use **ApplicationContext** to obtain the application file paths of these directories. +4. Level 4 and level 5 directories: + The application's global data is stored in the **distributedfiles** directory and **files**, **cache**, **preferences**, and **temp** in **base**. You can use **ApplicationContext** to obtain the application file paths of these directories. - You can use **UIAbilityContext**, **AbilityStageContext**, and **ExtensionContext** to obtain application file paths related to a HAP. When a HAP is uninstalled, the files in the **haps/** directory are automatically deleted, without affecting the files in application-level directories. - For details about how to obtain the context and application file paths, see [Context (Stage Model)](../application-models/application-context-stage.md). + Files of an OpenHarmony Ability Package (HAP) are stored in the **haps/** directory. You can use **UIAbilityContext**, **AbilityStageContext**, and **ExtensionContext** to obtain application file paths related to a HAP. When a HAP is uninstalled, the files in the **haps/** directory are automatically deleted, without affecting the files in application-level directories. An application in the development state has one or more HAPs. For details, see [Application Package Structure in Stage Model](../quick-start/application-package-structure-stage.md). The following table describes the application file paths and their lifecycle. @@ -70,10 +90,10 @@ The following figure shows the application file directory structure. The path of | -------- | -------- | -------- | -------- | | bundle | bundleCodeDir | Installation file directory| Directory for saving the HAPs after an application is installed.
This directory is cleared when the application is uninstalled.
Do not access resource files using concatenated paths. Use [@ohos.resourceManager](../reference/apis-localization-kit/js-apis-resource-manager.md) instead.
You can store the application's code resource data, including the HAPs of the application, reusable library files, and plug-ins, in this directory. The code in this directory can be dynamically loaded.| | base | NA | Directory for the device's files| Directory for saving the application's persistent data on the device. Subdirectories include **files/**, **cache/**, **temp/**, and **haps/**.
This directory is cleared when the application is uninstalled.| - | database | databaseDir | Database directory| Directory in **el2** for saving the files operated by the distributed database service.
This directory is cleared when the application is uninstalled.
This directory can be used to store the application's private database data, such as database files, in distributed scenarios only.| + | database | databaseDir | Database directory| Directory in **el2** for saving the files operated by the distributed database service.
This directory is cleared when the application is uninstalled.
This directory can be used to store the application's private database data, such as database files, in distributed scenarios only.| | distributedfiles | distributedFilesDir | Distributed file directory| Directory in **el2** for saving the application files that can be directly accessed across devices.
This directory is cleared when the application is uninstalled.
You can place the application's data used for distributed scenarios, including file sharing, file backup, and file processing across devices, in this directory. The data stored in this directory enables an application to run smoothly on multiple devices that form a Super Device.| | files | filesDir | Application file directory| Directory for saving the application's persistent files on the device.
This directory is cleared when the application is uninstalled.
You can place the application's private data, including persistent files, images, media files, and log files, in this directory. The data is stored in this directory to ensure privacy, security, and permanent validity.| - | cache | cacheDir | Application cache file directory| Directory for caching the downloaded files of the application or saving the cache files regenerated on the device.
This directory is automatically cleared when the size of the **cache** directory reaches the quota or the system storage space reaches a certain threshold. End users can also clear this directory by using a system space management application.
The application needs to check whether a file still exists and determine whether to cache a file again.
You can place the cached data of the application, including offline data, cached images, database backup, and temporary files, in this directory. Data stored in this directory may be automatically deleted by the system. Therefore, do not store important data in this directory.| + | cache | cacheDir | Application cache file directory| Directory for caching the downloaded files of the application or saving the cache files regenerated on the device.
This directory is automatically cleared when the size of the **cache** directory reaches the quota or the system storage space reaches a certain threshold. End users can also clear this directory by using a system space management application. The application needs to check whether a file still exists and determine whether to cache the file again. This directory is cleared when the application is uninstalled.
You can place the cached data of the application, including offline data, cached images, database backup, and temporary files, in this directory. Data stored in this directory may be automatically deleted by the system. Therefore, do not store important data in this directory.| | preferences | preferencesDir | Preferences file directory| Directory for saving common application configuration and user preferences managed by ArkData APIs on the device.
This directory is cleared when the application is uninstalled. For details about how to make preferences data persistent, see [Persisting Preferences Data](../database/data-persistence-by-preferences.md).
You can place application preferences data, including preference files and configuration files, in this directory. This directory applies to storing only a small amount of data.| | temp | tempDir | Temporary file directory| Directory for saving the files generated and required during the application's runtime on the device.
This directory is cleared when the application exits.
You can place temporarily generated data of the application, including cached database data and images, temporary log files, downloaded application installation packages, in this directory. The data stored in this directory can be deleted immediately after being used.| @@ -81,7 +101,7 @@ The following figure shows the application file directory structure. The path of The read and write operations performed on an application sandbox directory are eventually performed on the files in the physical directory after address conversion. The following table lists their mappings. -In the physical paths, <USERID> has a fixed value of **100**, and <EXTENSIONPATH> is moduleName-extensionName. For details about the application running in an independent Extension sandbox, see [ExtensionAbility Component](../application-models/extensionability-overview.md). +In the physical paths, <USERID> indicates the ID of the current user, which starts from 100, and <EXTENSIONPATH> is moduleName-extensionName. For details about the application running in an independent Extension sandbox, see [ExtensionAbility Component](../application-models/extensionability-overview.md). | Application Sandbox Path| Physical Path| | -------- | -------- | @@ -90,4 +110,4 @@ In the physical paths, <USERID> has a fixed value of **100**, and <EXTE | /data/storage/el2/base | Application directory of encryption level 2.
- Application running in a non-independent sandbox: **/data/app/el2/<USERID>/base/<PACKAGENAME>**
- Extension application running in an independent sandbox: **/data/app/el2/<USERID>/base/+extension-<EXTENSIONPATH>+<PACKAGENAME>**| | /data/storage/el1/database | Database directory of the application under **el1/**.
- Application running in a non-independent sandbox: **/data/app/el1/<USERID>/database/<PACKAGENAME>**
- Extension application running in an independent sandbox: **/data/app/el1/<USERID>/database/+extension-<EXTENSIONPATH>+<PACKAGENAME>**| | /data/storage/el2/database | Database directory of the application under **el2/**.
- Application running in a non-independent sandbox: **/data/app/el2/<USERID>/database/<PACKAGENAME>**
- Extension application running in an independent sandbox: **/data/app/el2/<USERID>/database/+extension-<EXTENSIONPATH>+<PACKAGENAME>**| -| /data/storage/el2/distributedfiles | **/mnt/hmdfs/<USERID>/account/merge_view/data/<PACKAGENAME>** | +| /data/storage/el2/distributedfiles | **/mnt/hmdfs/<USERID>/account/merge_view/data/<PACKAGENAME>**| Distributed data directory with an account under **el2/**.| diff --git a/en/application-dev/file-management/core-file-kit-intro.md b/en/application-dev/file-management/core-file-kit-intro.md index 972c46ab17b2c1631ad96f78a52e6485f4345982..6f73f02c8129a7faed2e0f05c8cb7eaf5aecdcfc 100644 --- a/en/application-dev/file-management/core-file-kit-intro.md +++ b/en/application-dev/file-management/core-file-kit-intro.md @@ -66,8 +66,7 @@ The application file access framework is implemented through [ohos.file.fs](../r You can use the user file access framework to access and manage user files. This framework leverages the ExtensionAbility of OpenHarmony to provide a set of methods and interfaces for accessing user files. -**Figure 2** User file access framework - +**Figure 2** User file access framework ![User file access framework](figures/user-file-access-framework.png) - The file access client (a system application or third-party application) can access user files, for example, select a photo or save multiple documents, by starting the **FilePicker** application. diff --git a/en/application-dev/file-management/dev-user-file-manager.md b/en/application-dev/file-management/dev-user-file-manager.md index a8172bca3de5b7868f119179c5c1d16b9658f6b4..91d2f82ab03c6d35628057fb3402a9bb37cdce95 100644 --- a/en/application-dev/file-management/dev-user-file-manager.md +++ b/en/application-dev/file-management/dev-user-file-manager.md @@ -3,15 +3,16 @@ OpenHarmony is prebuilt with the **FileManager** application. You can also develop your own file manager application as required. ## How to Develop -For details about the APIs used to develop a file manager, see [User File Access and Management](../reference/apis-core-file-kit/js-apis-fileAccess-sys.md). +For details about the APIs for developing the user file manager, see [User File Access and Management](../reference/apis-core-file-kit/js-apis-fileAccess-sys.md). -1. Apply for permissions required.
Apply for the ohos.permission.FILE_ACCESS_MANAGER and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED permissions. For details, see [Requesting Permissions for System_basic Applications](../security/AccessToken/determine-application-mode.md#requesting-permissions-for-system_basic-applications). - -> **NOTE** +1. Apply for permissions required.
+ Request the ohos.permission.FILE_ACCESS_MANAGER and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED permissions. For details, see [Requesting Permissions for System_basic Applications](../security/AccessToken/determine-application-mode.md#requesting-permissions-for-system_basic-applications). + + > **NOTE** > - > - The ohos.permission.FILE_ACCESS_MANAGER permission allows your application to use the user file access framework APIs. + > The ohos.permission.FILE_ACCESS_MANAGER permission allows your application to call the user file access framework APIs. > - > - The ohos.permission.GET_BUNDLE_INFO_PRIVILEGED permission allows your application to obtain information about file management server applications supported by the system. + > The ohos.permission.GET_BUNDLE_INFO_PRIVILEGED permission allows your application to obtain information about file management server applications supported by the system. 2. Import dependent modules. @@ -72,10 +73,10 @@ For details about the APIs used to develop a file manager, see [User File Access } ``` -4. View directories.
- In the user file access framework, **FileInfo** indicates basic information about a file or folder. You can use **listfile()** to obtain a **FileIterator** object that traverses all files (folders) of the next level or use **scanfile()** to obtain a **FileIterator** object that meets the specified conditions. +4. View directories. + In the user file access framework, **FileInfo** indicates basic information about a file or folder. You can use **listfile()** to obtain a **FileIterator** object that traverses all files (folder) of the next level or use **scanfile()** to obtain a **FileIterator** object that meets the specified conditions. - Currently, **listfile()** and **scanfile()** can be called by the **RootInfo** object to traverse the next-level files or filter the entire directory tree. In addition, **listfile()** and **scanfile()** can be called by the **FileInfo** object to traverse the next-level files or filter the specified directories. + Currently, **listfile()** and **scanfile()** can be called by the **RootInfo** object to traverse the next-level files or filter the entire directory tree. In addition, **listfile()** and **scanfile()** can be called by the **FileInfo** object to traverse the next-level files or filter the specified directories. ```ts import { BusinessError } from '@kit.BasicServicesKit'; @@ -89,7 +90,7 @@ For details about the APIs used to develop a file manager, see [User File Access let isDone: boolean = false; let filter: Filter = {suffix : [".txt", ".jpg", ".xlsx"]}; // Set the filter. try { - let fileIterator = rootInfo.listFile(); // Traverse the root directory of rootinfos[0] and return a FileIterator object. + let fileIterator = rootInfo.listFile(); // Traverse the root directory of rootinfos[0] and return an iterator object. // let fileIterator = rootInfo.scanFile(filter); // Filter device rootinfos[0] files that meet the specified conditions and return a FileIterator object. if (!fileIterator) { console.error("listFile interface returns an undefined object"); @@ -112,7 +113,7 @@ For details about the APIs used to develop a file manager, see [User File Access let isDone02: boolean = false; let filter02: Filter = {suffix : [".txt", ".jpg", ".xlsx"]}; // Set the filter. try { - let fileIterator = fileInfoDir.listFile(); // Traverse files in the specified directory and return a FileIterator object. + let fileIterator = fileInfoDir.listFile(); // Traverse files in the specified directory and return an iterator object. // let fileIterator = rootInfo.scanFile(filter02); // Filter the files in the specified directory and return a FileIterator object. if (!fileIterator) { console.error("listFile interface returns an undefined object"); @@ -130,7 +131,7 @@ For details about the APIs used to develop a file manager, see [User File Access } ``` -5. Perform operations on files or folders.
+5. Perform operations on files or directories. You can integrate APIs of the user file access framework to implement user behaviors, such as deleting, renaming, creating, and moving a file or folder. The following example shows how to create a file. For details about other APIs, see [User File Access and Management](../reference/apis-core-file-kit/js-apis-fileAccess-sys.md). ```ts @@ -150,7 +151,7 @@ For details about the APIs used to develop a file manager, see [User File Access if (!fileUri) { console.error("createFile return undefined object"); } - console.info("createFile success, fileUri: " + JSON.stringify(fileUri)); + console.info("createFile sucess, fileUri: " + JSON.stringify(fileUri)); } catch (err) { let error: BusinessError = err as BusinessError; console.error("createFile failed, errCode:" + error.code + ", errMessage:" + error.message); @@ -165,64 +166,86 @@ For details about the APIs, see [User File Access and Management](../reference/a You can use **notify()** to observe not only the changes of directories, but also the device online/offline status. -1. Apply for permissions required.
+1. Request permissions required.
- Apply for the ohos.permission.FILE_ACCESS_MANAGER and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED permissions. For details, see [Declaring Permissions](../security/AccessToken/declare-permissions.md). + Request the ohos.permission.FILE_ACCESS_MANAGER and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED permissions. For details, see [Declaring Permissions](../security/AccessToken/declare-permissions.md). > **NOTE** > - > - The ohos.permission.FILE_ACCESS_MANAGER permission allows your application to call the user file access framework APIs. - >- The ohos.permission.GET_BUNDLE_INFO_PRIVILEGED permission allows your application to obtain information about file management server applications supported by the system. - + > The ohos.permission.FILE_ACCESS_MANAGER permission allows your application to call the user file access framework APIs. + > + > The ohos.permission.GET_BUNDLE_INFO_PRIVILEGED permission allows your application to obtain information about file management server applications supported by the system. + 2. Import dependent modules. ```ts import { fileAccess } from '@kit.CoreFileKit'; import { fileExtensionInfo } from '@kit.CoreFileKit'; ``` - - The **fileAccess** module provides APIs for basic file operations, and the **fileExtensionInfo** module provides key structs for application development. - -3. Define an observer callback. + + The **fileAccess** module provides APIs for basic file operations, and the **fileExtensionInfo** module provides key structs for application development. + +3. Define the observer callback. ```ts const callbackDir1 = (NotifyMessageDir: fileAccess.NotifyMessage) => { if (NotifyMessageDir != undefined) { - console.log('NotifyType: ' + NotifyMessageDir.type + 'NotifyUri:' + NotifyMessageDir.uri[0]); + console.log('NotifyType: ' + NotifyMessageDir.type + 'NotifyUri:' + NotifyMessageDir.uris[0]); } else { console.error("NotifyMessageDir is undefined"); } } ``` -4. Subscribe to the device online/offline status. - - Pass in the constant [DEVICES_URI](../reference/apis-core-file-kit/js-apis-fileAccess-sys.md#constant) to the **registerObserver** method to listen for the device online/offline status. - - ```ts - import { BusinessError } from '@kit.BasicServicesKit'; - async function UnregisterObserver03() { - try { - // Listen for the device online/offline status. - fileAccessHelper.registerObserver(fileAccess.DEVICES_URI, true, callbackDir1); - } catch (err) { - let error: BusinessError = err as BusinessError; - console.error("unregisterObserver failed, errCode:" + error.code + ", errMessage:" + error.message); - } - } - ``` - -5. Unsubscribe from the device online/offline status. - - Pass in the constant [DEVICES_URI](../reference/apis-core-file-kit/js-apis-fileAccess-sys.md#constant) to the **unregisterObserver** method to unsubscribe from the device online/offline status. - - ```ts - import { BusinessError } from '@kit.BasicServicesKit'; - try { - // Unsubscribe from the device online/offline status. - fileAccessHelper.unregisterObserver(fileAccess.DEVICES_URI, callbackDir1); - } catch (err) { - let error: BusinessError = err as BusinessError; - console.error("unregisterObserver failed, errCode:" + error.code + ", errMessage:" + error.message); - } - ``` \ No newline at end of file +4. Observe devices. + + To listen for the device online/offline status, pass in [DEVICES_URI](../reference/apis-core-file-kit/js-apis-fileAccess-sys.md#constant) to **registerObserver**. To cancel the listening for the device online/offline status, pass in **DEVICES_URI** to **unregisterObserver()**. + + ```ts + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; + + // Define the observer callback. + const callbackDir1 = (NotifyMessageDir: fileAccess.NotifyMessage) => { + if (NotifyMessageDir != undefined) { + console.log('NotifyType: ' + NotifyMessageDir.type + 'NotifyUri:' + NotifyMessageDir.uris[0]); + } else { + console.error("NotifyMessageDir is undefined"); + } + } + + let context = getContext(this) as common.UIAbilityContext; + // Create a helper object for connecting to all file management servers in the system. + let fileAccessHelperAllServer: fileAccess.FileAccessHelper; + function createFileAccessHelper(): void { + try { // this.context is the context passed from EntryAbility. + fileAccessHelperAllServer = fileAccess.createFileAccessHelper(context); + if (!fileAccessHelperAllServer) { + console.error("createFileAccessHelper interface returns an undefined object"); + } + } catch (err) { + let error: BusinessError = err as BusinessError; + console.error("createFileAccessHelper failed, errCode:" + error.code + ", errMessage:" + error.message); + } + } + // Pass in DEVICES_URI to registerObserver() to listen for the device online/offline status. + async function UnregisterObserver03() { + try { + // Listen for the device online/offline status. + fileAccessHelperAllServer.registerObserver(fileAccess.DEVICES_URI, true, callbackDir1); + } catch (err) { + let error: BusinessError = err as BusinessError; + console.error("unregisterObserver failed, errCode:" + error.code + ", errMessage:" + error.message); + } + } + // Pass in DEVICES_URI to unregisterObserver () to cancel the device status listening. + async function UnregisterObserver04() { + try { + // Unsubscribe from the device online/offline status. + fileAccessHelperAllServer.unregisterObserver(fileAccess.DEVICES_URI, callbackDir1); + } catch (err) { + let error: BusinessError = err as BusinessError; + console.error("unregisterObserver failed, errCode:" + error.code + ", errMessage:" + error.message); + } + } + ``` diff --git a/en/application-dev/file-management/file-access-across-devices.md b/en/application-dev/file-management/file-access-across-devices.md index ae47aefb373a9e69c6f1a9fd0408136fc4cb6f1c..a8bbef61dc540b80ce837dd0576fbfd5110c154d 100644 --- a/en/application-dev/file-management/file-access-across-devices.md +++ b/en/application-dev/file-management/file-access-across-devices.md @@ -5,7 +5,7 @@ The distributed file system provides applications the capability for accessing f ## How to Develop 1. Connect the devices to form a Super Device.
- Perform unified account authentication for the devices. The devices are not necessarily in the same LAN. + Log in to the same account on two devices and ensure that Bluetooth and Wi-Fi are enabled. Bluetooth does not require a physical connection, and Wi-Fi does not need to be connected to the same LAN. 2. Implement cross-device access to the files of your application.
Place the files in the **distributedfiles/** directory of the application sandbox directory to implement access from difference devices. @@ -114,3 +114,5 @@ The distributed file system provides applications the capability for accessing f console.error(`Failed to disconnectDfs Code: ${err.code}, message: ${err.message}`) }) ``` + + \ No newline at end of file diff --git a/en/application-dev/file-management/file-management-overview.md b/en/application-dev/file-management/file-management-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..4344c69323005452572399c4e17de37069d6d270 --- /dev/null +++ b/en/application-dev/file-management/file-management-overview.md @@ -0,0 +1,31 @@ +# File Management Overview + +The data in an operating system (OS) can be classified into the following types based on the data structure: + +- Structured data: data that can be defined in a unified data model and is generally stored in a database. In OpenHarmony application development, the management of structured data is implemented by the [data management module](../database/data-mgmt-overview.md). + +- Unstructured data: data that does not conform to any predefined data structure or model and cannot be easily presented in two-dimensional database tables. Unstructured data includes files in a variety of formats, such as documents, images, videos, and audio clips. In OpenHarmony application development, the management of unstructured data is implemented by the file management module, which will be elaborated in this document. + +In the file management module, the files can be classified into the following types based on the file owner: + +- [Application files](app-file-overview.md): files of an application, including the installation files, resource files, and cache files of the application. + +- [User files](user-file-overview.md): files of a user who has logged in to the device. User files include the user's images, videos, audio clips, and documents. + +- System files: files irrelevant to applications and users. System files include public libraries, device files, and system resource files. The system files do not need to be managed by developers and are not described in this document. + +The file systems can be classified into the following types based on the file storage location (data source location): + +- Local file system: allows access to the files stored on a device and its external storage devices (such as USB flash drives and removable hard drives). The local file system is the most basic file system and is not described in this document. + +- [Distributed file system](distributed-fs-overview.md): allows access to files across devices, which include not only the local device and its external storage devices, but also the devices connected over a computer network. + +**Figure 1** Files in an OS + +![File classification model](figures/file-classification-model.png) + +## + + + +- diff --git a/en/application-dev/file-management/file-persistPermission.md b/en/application-dev/file-management/file-persistPermission.md index 60efc79f48d12ef598860c95f2c3bc767c18a3d0..57eae34b0f01af79830600636e68b37578d7dc20 100644 --- a/en/application-dev/file-management/file-persistPermission.md +++ b/en/application-dev/file-management/file-persistPermission.md @@ -6,24 +6,23 @@ If an application accesses a file by using Picker, the permission for accessing ## Persisting a Temporary Permission Granted by Picker -### Persisting a Temporary Permission You can use Picker to select a file or folder, and persist the temporary permission granted by Picker by using the API provided by [ohos.fileshare](../reference/apis-core-file-kit/js-apis-fileShare.md). -When an application needs to temporarily access data in a user directory, for example, a communication application needs to send a user file or image, it calls [select()](../reference/apis-core-file-kit/js-apis-file-picker.md#select-3) of Picker to select the file or image to be sent. In this case, the application obtains the temporary permission for accessing the file or image. To access the file or image after the application or device is restarted, the application still needs to call a Picker API. +1. When an application needs to temporarily access data in a user directory, for example, a communication application needs to send a user file or image, it calls [select()](../reference/apis-core-file-kit/js-apis-file-picker.md#select-3) of Picker to select the file or image to be sent. In this case, the application obtains the temporary permission for accessing the file or image. After the application or device is restarted, the application still needs to call a Picker API to access the file or image. -Sometimes, an application needs to access a file or folder multiple times. For example, after editing a user file, a file editor application needs to select and open the file directly from the history records. To address this need, you can use Picker to select the file, and use [ohos.fileshare.persistPermission](../reference/apis-core-file-kit/js-apis-fileShare.md#filesharepersistpermission11) to persist the temporary permission granted by Picker. +2. Sometimes, an application needs to access a file or folder multiple times. For example, after editing a user file, a file editor application needs to select and open the file directly from the history records. In this case, you can use Picker to select the file, and use [ohos.fileshare.persistPermission](../reference/apis-core-file-kit/js-apis-fileShare.md#filesharepersistpermission11) to persist the temporary permission granted by Picker. -Before persisting a temporary permission, ensure that: -- The device must have the SystemCapability.FileManagement.File.Environment.FolderObtain system capability. You can use **canIUse()** to check whether the device has the required system capability. +Before persisting a temporary permission, ensure that:
The device must have the system capability SystemCapability.FileManagement.AppFileService.FolderAuthorization. You can use **canIUse()** to check whether the device has the required system capability. ```ts -if (!canIUse('SystemCapability.FileManagement.File.Environment.FolderObtain')) { +if (!canIUse('SystemCapability.FileManagement.AppFileService.FolderAuthorization')) { console.error('this api is not supported on this device'); return; } ``` -- The application must have the ohos.permission.FILE_ACCESS_PERSIST permission. For details about how to request the permission, see [Workflow for Requesting Permissions](../security/AccessToken/determine-application-mode.md). +**Required Permissions**
+ohos.permission.FILE_ACCESS_PERSIST. For details about how to request the permission, see [Workflow for Requesting Permissions](../security/AccessToken/determine-application-mode.md). **Example** @@ -60,6 +59,7 @@ async function persistPermissionExample() { } } ``` + **NOTE** > - You are advised to save the URI of the file with persistent permission for the related application locally to facilitate the subsequent activation. > - The permission persistence data is also stored in the system database. After the application or device is restarted, the persistent permission can be used only after being activated. For details, see [Activating a Persistent Permission](#activating-a-persistent-permission-for-accessing-a-file-or-folder). @@ -68,7 +68,6 @@ async function persistPermissionExample() { For details about how to persist a temporary permission using C/C++ APIs, see [OH_FileShare_PersistPermission](native-fileshare-guidelines.md). -### Revoking a Temporary Permission You can use [ohos.fileshare.revokePermission](../reference/apis-core-file-kit/js-apis-fileShare.md#filesharerevokepermission11) to revoke the persistent permission from a file, and update the data stored in the application to delete the file URI from the recently accessed data. **Required Permissions** @@ -108,14 +107,13 @@ async function revokePermissionExample() { } } ``` + **NOTE** > - The URI in the example comes from the permission persistence data stored for the application. > - You are advised to activate the persistent permissions based on service requirements. Do not activate all persistent permissions. > - The APIs used for persisting permissions are available only for 2-in-1 devices. You can use **canIUse()** to check whether the device has the required system capability. The caller must also have the required permissions. - - -For details about how to revoke temporary permission using C/C++ APIs, see [OH_FileShare_RevokePermission](native-fileshare-guidelines.md). +For details about how to revoke a persistent permission using C/C++ APIs, see [OH_FileShare_RevokePermission](native-fileshare-guidelines.md). ## Activating a Persistent Permission for Accessing a File or Folder @@ -167,4 +165,4 @@ async function activatePermissionExample() { > - If the activation fails because the permission has not been persisted, persist the permission first. > - The APIs used for persisting permissions are available only for 2-in-1 devices. You can use **canIUse()** to check whether the device has the required system capability. The caller must also have the required permissions. -For details about how to activate a persistent permission using C/C++ APIs, see [OH_FileShare_ActivatePermission](native-fileshare-guidelines.md). \ No newline at end of file +For details about how to activate a persistent permission using C/C++ APIs, see [OH_FileShare_ActivatePermission](native-fileshare-guidelines.md). diff --git a/en/application-dev/file-management/manage-external-storage.md b/en/application-dev/file-management/manage-external-storage.md index 2874385d25b09d6fd5bc947f751c4b9973e7effa..61c9489b43dfc282ae06cbc3741f3c0f8c2121a1 100644 --- a/en/application-dev/file-management/manage-external-storage.md +++ b/en/application-dev/file-management/manage-external-storage.md @@ -15,7 +15,8 @@ External storage devices are managed by the StorageManager and StorageDaemon ser - If the check fails, the volume state changes to **UNMOUNTED**. - For a volume in the **MOUNTED** state: - - If the user chooses **Eject device**, the volume state changes to **EJECTING** and COMMON_EVENT_VOLUME_EJECT is broadcast. After StorageDaemon unmounts the volume, the volume state changes to **UNMOUNTED** and COMMON_EVENT_VOLUME_UNMOUNTED is broadcast.
For a volume in the **UNMOUNTED** state, removing the device will delete the volume information and broadcast COMMON_EVENT_VOLUME_REMOVED. + - If the user chooses **Eject device**, the volume state changes to **EJECTING** and COMMON_EVENT_VOLUME_EJECT is broadcast. After StorageDaemon unmounts the volume, the volume state changes to **UNMOUNTED** and COMMON_EVENT_VOLUME_UNMOUNTED is broadcast. +
For a volume in the **UNMOUNTED** state, removing the device will delete the volume information and broadcast COMMON_EVENT_VOLUME_REMOVED. - If the user removes the device, the volume state changes to **EJECTING** and then to **UNMOUNTED**, and the broadcasts of the corresponding states are sent. After the device is removed, the volume information is deleted and the COMMON_EVENT_VOLUME_BAD_REMOVAL broadcast is sent. ## Available APIs @@ -26,23 +27,23 @@ The following table describes the broadcast related parameters. **Table 1** Broadcast parameters -| Broadcast| Parameter| +| Broadcast| Parameter| | -------- | -------- | -| usual.event.data.VOLUME_REMOVED | **id**: ID of the volume.
**diskId**: ID of the disk to which the volume belongs.| -| usual.event.data.VOLUME_UNMOUNTED | **id**: ID of the volume.
**diskId**: ID of the disk to which the volume belongs.
**volumeState**: state of the volume.| -| usual.event.data.VOLUME_MOUNTED | **id**: ID of the volume.
**diskId**: ID of the disk to which the volume belongs.
**volumeState**: state of the volume.
**fsUuid**: universally unique identifier (UUID) of the volume.
**path**: path where the volume is mounted.| -| usual.event.data.VOLUME_BAD_REMOVAL | **id**: ID of the volume.
**diskId**: ID of the disk to which the volume belongs.| -| usual.event.data.VOLUME_EJECT | **id**: ID of the volume.
**diskId**: ID of the disk to which the volume belongs.
**volumeState**: state of the volume.| +| usual.event.data.VOLUME_REMOVED | **id**: ID of the volume.
**diskId**: ID of the disk to which the volume belongs.| +| usual.event.data.VOLUME_UNMOUNTED | **id**: ID of the volume.
**diskId**: ID of the disk to which the volume belongs.
**volumeState**: state of the volume.| +| usual.event.data.VOLUME_MOUNTED | **id**: ID of the volume.
**diskId**: ID of the disk to which the volume belongs.
**volumeState**: state of the volume.
**fsUuid**: universally unique identifier (UUID) of the volume.
**path**: path where the volume is mounted.| +| usual.event.data.VOLUME_BAD_REMOVAL | **id**: ID of the volume.
**diskId**: ID of the disk to which the volume belongs.| +| usual.event.data.VOLUME_EJECT | **id**: ID of the volume.
**diskId**: ID of the disk to which the volume belongs.
**volumeState**: state of the volume.| ## How to Develop You can subscribe to broadcast events to observe the insertion and removal of external storage devices, and query or manage volumes based on the volume information obtained from the broadcast. -1. Apply for permissions.
- Apply for the ohos.permission.STORAGE_MANAGER permission if your application needs to subscribe to volume broadcast events. For details, see [Requesting Permissions for system_basic Applications](../security/AccessToken/determine-application-mode.md#requesting-permissions-for-system_basic-applications). +1. Apply for permissions.
+ Apply for the ohos.permission.STORAGE_MANAGER permission if your application needs to subscribe to volume broadcast events. For details, see [Requesting Permissions for system_basic Applications](../security/AccessToken/determine-application-mode.md#requesting-permissions-for-system_basic-applications). -2. Subscribe to broadcast events.
- You can subscribe to the following events: +2. Subscribe to broadcast events.
+ You can subscribe to the following events: - "usual.event.data.VOLUME_REMOVED": The device is removed. - "usual.event.data.VOLUME_UNMOUNTED": The volume is unmounted. diff --git a/en/application-dev/file-management/native-environment-guidelines.md b/en/application-dev/file-management/native-environment-guidelines.md index 0ad8fc1b4fa141bc60d2d9a08d033c17f44960f0..8dca0d14c4d87ae2790a91450b9ef9fb4ed1f1a9 100644 --- a/en/application-dev/file-management/native-environment-guidelines.md +++ b/en/application-dev/file-management/native-environment-guidelines.md @@ -2,7 +2,7 @@ ## When to Use -Before accessing or operating a user file, a third-party application needs to obtain the user directory. The **Environment** module provides the APIs for obtaining the user directories. +You can use [Environment](../reference/apis-core-file-kit/_environment.md) to allow a third-party application to access files in a user directory. ## Constraints @@ -15,9 +15,9 @@ For details about the APIs, see [Environment](../reference/apis-core-file-kit/_e | API| Description| | -------- | -------- | -| FileManagement_ErrCode OH_Environment_GetUserDownloadDir (char **result)| Obtains the sandbox path of the **Download** directory. This API is available only for 2-in-1 devices.| -| FileManagement_ErrCode OH_Environment_GetUserDesktopDir (char **result) | Obtains the sandbox path of the **Desktop** directory. This API is available only for 2-in-1 devices.| -| FileManagement_ErrCode OH_Environment_GetUserDocumentDir (char **result) | Obtains the sandbox path of the **Documents** directory. This API is available only for 2-in-1 devices.| +| FileManagement_ErrCode OH_Environment_GetUserDownloadDir (char **result)| Obtains the sandbox path of the **Download** directory. This function supports only 2-in-1 devices.| +| FileManagement_ErrCode OH_Environment_GetUserDesktopDir (char **result) | Obtains the sandbox path of the **Desktop** directory. This function supports only 2-in-1 devices.| +| FileManagement_ErrCode OH_Environment_GetUserDocumentDir (char **result) | Obtains the sandbox path of the **Documents** directory. This function supports only 2-in-1 devices.| ## How to Develop @@ -66,7 +66,7 @@ target_link_libraries(sample PUBLIC libohenvironment.so) } ``` -3. Call **OH_Environment_GetUserDocumentDir** to obtain the sandbox path of the user **Documents** directory. The memory allocated must be released using **free()**.
Example: +3. Call **OH_Environment_GetUserDocumentDir** to obtain the sandbox path of the user **Document** directory. The memory allocated must be released using **free()**.
Example: ```c void GetUserDocumentDirPathExample() { diff --git a/en/application-dev/file-management/native-fileio-guidelines.md b/en/application-dev/file-management/native-fileio-guidelines.md index 50436b9148fcd0de223d0acad7f98eae9fc52792..7ea53de82b87e3b86170422f343c8c1476bf90fc 100644 --- a/en/application-dev/file-management/native-fileio-guidelines.md +++ b/en/application-dev/file-management/native-fileio-guidelines.md @@ -2,7 +2,7 @@ ## When to Use -The **FileIO** module provides APIs for basic file operations. +The **FileIO** module provides some APIs for basic file operations. For details about other APIs, see [libc](../reference/native-lib/musl.md) and [libc++](../reference/native-lib/cpp.md). ## Basic Concepts @@ -10,7 +10,7 @@ URI: uniquely identifies a file. ## Constraints -- Before performing file operations, ensure that the URI or path passed in is correct and valid. +Before performing file operations, ensure that the URI or path passed in is correct and valid. ## Available APIs @@ -20,7 +20,7 @@ For details about the APIs, see [FileIO](../reference/apis-core-file-kit/_file_i | -------- | -------- | | FileManagement_ErrCode OH_FileIO_GetFileLocation(char *uri, int uriLength, FileIO_FileLocation *location)| Obtains the location of a file.| | enum FileIO_FileLocation FileIO_FileLocation| Enumerates the file locations.| -| enum enum FileManagement_ErrCode FileManagement_ErrCode| Enumerates the error codes used in the **FileIO** module.| +| enum FileManagement_ErrCode FileManagement_ErrCode| Enumerates the error codes used in the **FileIO** module.| ## How to Develop @@ -56,4 +56,4 @@ Call **OH_FileIO_GetFileLocation** to obtain the location of a file.
Example printf("GetFileLocation failed, error code is %d", ret); } } -``` + ``` diff --git a/en/application-dev/file-management/native-fileshare-guidelines.md b/en/application-dev/file-management/native-fileshare-guidelines.md index ff17dc1ffdddaafb876d3c97754f0329454850be..e71b3a7883b39012862719db43b141daf034ccbc 100644 --- a/en/application-dev/file-management/native-fileshare-guidelines.md +++ b/en/application-dev/file-management/native-fileshare-guidelines.md @@ -2,7 +2,7 @@ ## When to Use -If an application accesses a file by using a Picker, the permission for accessing the file will be automatically revoked after the application exits or the device restarts. To retain the permission for accessing the file, you need to [persistent the authorization](file-persistPermission.md#when-to-use). You can use the **FileShare** module to persist permissions on files or folders based on their URI, activate or deactivate persistent permissions on files or folders, and check the persistent permissions. +If an application accesses a file by using Picker, the permission for accessing the file will be automatically invalidated after the application exits or the device restarts. To retain the permission for accessing the file, you need to [persist the permission](file-persistPermission.md#when-to-use). You can use the **FileShare** module to persist permissions on files or folders based on their URI, activate or deactivate persistent permissions on files or folders, and check the persistent permissions. ## Available APIs @@ -21,11 +21,11 @@ For details about the APIs, see [FileShare](../reference/apis-core-file-kit/file - Before using the **FileShare** APIs, check that your device has SystemCapability.FileManagement.AppFileService.FolderAuthorization. -- To call **FileShare** APIs, the application must have the ohos.permission.FILE_ACCESS_PERSIST permission. For details about how to request the permission, see [Workflow for Requesting Permissions](../security/AccessToken/determine-application-mode.md). +- To call **FileShare** APIs, the application must have the ohos.permission.FILE_ACCESS_PERSIST permission. For details about how to request the permission, see [Workflow for Using Permissions](../security/AccessToken/determine-application-mode.md). ## How to Develop -The following example describes how to use the **FileShare** APIs. +The following example describes how to use the `FileShare` APIs. **Adding the Dynamic Link Library** diff --git a/en/application-dev/file-management/native-fileuri-guidelines.md b/en/application-dev/file-management/native-fileuri-guidelines.md index 12ae03776feb75a08112013889740e5004ed65f7..93fc6e42f3fd586c244f38b50df6716c782b21ff 100644 --- a/en/application-dev/file-management/native-fileuri-guidelines.md +++ b/en/application-dev/file-management/native-fileuri-guidelines.md @@ -2,7 +2,7 @@ ## When to Use -You can use the APIs provided by the **fileUri** module to perform basic URI operations. +FileUri provides APIs for basic file URI operations, such as converting URIs to sandbox paths, converting sandbox paths to URIs, and obtaining URIs of directories where the specified URIs are located, facilitating URI access in file sharing services. ## Basic Concepts @@ -10,7 +10,7 @@ You can use the APIs provided by the **fileUri** module to perform basic URI ope ## Constraints -- The parameters passed in must be correct and valid before a URI is converted or verified. +- When converting a URI to a path, you are advised to use the system capability to obtain the URI source, for example, the URI returned by the picker, clipboard, dragging, and path-to-URI APIs provided by the system. If the URI combined by applications or users is converted, the converted path may fail to be accessed. - To ensure data accuracy, only one object can be processed during the conversion or verification of a URI. @@ -18,13 +18,13 @@ You can use the APIs provided by the **fileUri** module to perform basic URI ope For details about the APIs, see [File URI](../reference/apis-core-file-kit/fileuri.md). -| API| Description | -| -------- |--------------------------------------------| -| FileManagement_ErrCode OH_FileUri_GetUriFromPath(const char *path, unsigned int length, char **result)| Obtains the URI from a path. | -| FileManagement_ErrCode OH_FileUri_GetPathFromUri(const char *uri, unsigned int length, char **result) | Obtains the sandbox path from a URI. | -| FileManagement_ErrCode OH_FileUri_GetFullDirectoryUri(const char *uri, unsigned int length, char **result) | Obtains the URI of the directory, in which a URI is located.| -| bool OH_FileUri_IsValidUri(const char *uri, unsigned int length) | Checks whether a URI is valid. | -| FileManagement_ErrCode OH_FileUri_GetFileName(const char *uri, unsigned int length, char **result) | Obtains the file name based on the given URI. | +| API| Description| +| -------- |-------| +| FileManagement_ErrCode OH_FileUri_GetUriFromPath(const char *path, unsigned int length, char **result)| Generates the application URI based on the input path. When a path is converted to a URI, Chinese characters and non-digit characters in the path are compiled into the corresponding ASCII code and combined into the URI.| +| FileManagement_ErrCode OH_FileUri_GetPathFromUri(const char *uri, unsigned int length, char **result) | Converts the URI to the corresponding sandbox path.
1. During URI-to-path conversion, the ASCII code in the URI is decoded and then concatenated to the original position. The URI generated by a non-system API may contain characters beyond the ASCII code parsing range. As a result, the string cannot be concatenated.
2. The conversion is performed based on the string replacement rule specified by the system (the rule may change with the system evolution). During the conversion, the path is not verified, so that the conversion result may not be accessible.| +| FileManagement_ErrCode OH_FileUri_GetFullDirectoryUri(const char *uri, unsigned int length, char **result) | Obtains the URI of the path.
If the URI points to a file, the URI of the path is returned. If the URI points to a directory, the original string is returned without processing.
If the file specified by the URI does not exist or the attribute fails to be obtained, an empty string is returned.| +| bool OH_FileUri_IsValidUri(const char *uri, unsigned int length) | Checks whether the format of the input URI is correct. The system only checks whether the URI meets the format specifications defined by the system. The validity of the URI is not verified.| +| FileManagement_ErrCode OH_FileUri_GetFileName(const char *uri, unsigned int length, char **result) | Obtains the file name based on the given URI. (The ASCII code in the file name will be decoded and then concatenated to the original position.)| ## How to Develop @@ -53,7 +53,7 @@ target_link_libraries(sample PUBLIC libohfileuri.so) char *uriResult = NULL; FileManagement_ErrCode ret = OH_FileUri_GetUriFromPath(path, length ,&uriResult); if (ret == 0 && uriResult !=NULL) { - printf("pathUri= %s", uriResult); // The URI obtained by application a is file://com.example.demo/data/storage/el2/base/files/test.txt. + printf("pathUri=%s", uriResult); // The URI obtained by application a is file://com.example.demo/data/storage/el2/base/files/test.txt. } if (uriResult != NULL) { free(uriResult); @@ -72,7 +72,7 @@ target_link_libraries(sample PUBLIC libohfileuri.so) char *pathResult = NULL; FileManagement_ErrCode ret = OH_FileUri_GetPathFromUri(uri, length, &pathResult); if (ret == 0 && pathResult != NULL) { - printf ("pathResult= %s", pathResult); // PathResult is /data/storage/el2/base/files/test.txt. + printf("pathResult=%s", pathResult); // PathResult is /data/storage/el2/base/files/test.txt. } if (pathResult != NULL) { free(pathResult); @@ -91,7 +91,7 @@ target_link_libraries(sample PUBLIC libohfileuri.so) char *uriResult = NULL; FileManagement_ErrCode ret = OH_FileUri_GetFullDirectoryUri(uri, length, &uriResult); if (ret == 0 && uriResult != NULL) { - printf("pathUri= %s",uriResult);// The URI obtained is file://com.example.demo/data/storage/el2/base/files/. + printf("pathUri=%s",uriResult);// The URI obtained is file://com.example.demo/data/storage/el2/base/files/. } if (uriResult != NULL) { free(uriResult); @@ -123,7 +123,7 @@ target_link_libraries(sample PUBLIC libohfileuri.so) char *uriResult = NULL; FileManagement_ErrCode ret = OH_FileUri_GetFileName(uri, length, &uriResult); if (ret == 0 && uriResult != NULL) { - printf ("pathUri=%s,"uriResult);// Obtain the file name test.txt from the URI. + printf("pathUri=%s",uriResult);// Obtain the file name test.txt from the URI. } if (uriResult != NULL) { free(uriResult); diff --git a/en/application-dev/file-management/request-dir-permission.md b/en/application-dev/file-management/request-dir-permission.md index 09feb2c718d3cb5c3d3071c9526031ff5e12e1e4..65b8c6b9d1eec24814f2f8873b4c053b9483798f 100644 --- a/en/application-dev/file-management/request-dir-permission.md +++ b/en/application-dev/file-management/request-dir-permission.md @@ -141,7 +141,7 @@ target_link_libraries(sample PUBLIC libohenvironment.so libhilog_ndk.z.so) #include ``` -- Call **OH_Environment_GetUserDownloadDir** to obtain the sandbox path of the user **Download** folder. The memory allocated by **malloc()** must be released using **free()**.
Example: +1. Call **OH_Environment_GetUserDownloadDir** to obtain the sandbox path of the user **Download** folder. The memory allocated by **malloc()** must be released using **free()**.
Example: ```c++ void GetUserDownloadDirExample() @@ -157,7 +157,7 @@ target_link_libraries(sample PUBLIC libohenvironment.so libhilog_ndk.z.so) } ``` -- Call **OH_Environment_GetUserDownloadDir** to obtain the sandbox path of the **Download** folder and view the files in it.
Example: +2. Call **OH_Environment_GetUserDownloadDir** to obtain the sandbox path of the **Download** folder and view the files in it.
Example: ```c++ void ScanUserDownloadDirPathExample() @@ -187,7 +187,7 @@ target_link_libraries(sample PUBLIC libohenvironment.so libhilog_ndk.z.so) } ``` -- Call **OH_Environment_GetUserDownloadDir** to obtain the sandbox path of the user **Download** folder and save **temp.txt** to this folder.
Example: +3. Call **OH_Environment_GetUserDownloadDir** to obtain the sandbox path of the user **Download** folder and save **temp.txt** to this folder.
Example: ```c++ void WriteUserDownloadDirPathExample() diff --git a/en/application-dev/file-management/save-user-file.md b/en/application-dev/file-management/save-user-file.md index 920c4b5eda26e9bf56c870ee664c0bceb5f6f75c..e6381c63c279c737639ec4b9fd8362f3066054ee 100644 --- a/en/application-dev/file-management/save-user-file.md +++ b/en/application-dev/file-management/save-user-file.md @@ -1,17 +1,21 @@ # Saving User Files -When a user needs to download a file from the Internet or save a file to another directory, use **FilePicker** to save the file. The permission on the file URI granted by Picker, however, is temporary. If required, you can persist the permission on the URI. For details, see [Persisting a Temporary Permission Granted by Picker](file-persistPermission.md#persisting-a-temporary-permission-granted-by-picker). +When a user needs to download a file from the Internet or save a file to another directory, use **FilePicker** to save the file. Pay attention to the following key points: -The operations for saving images, audio or video clips, and documents are similar. Call **save()** of the corresponding Picker instance and pass in **saveOptions**. No permission is required if your application uses **FilePicker** to access files. +**Permission Description** -Currently, all the **save()** behaviors of **FilePicker** can be perceived by users. Specifically, **FilePicker** is started to save the files to a directory managed by **FileManager**. The files are isolated from the assets managed by **Gallery** and cannot be viewed in **Gallery**. +- The read and write permissions on the file URI granted by Picker is temporary by default, and will be automatically invalidated once the application exits. +- You can persist the permissions on the URI. For details, see [Persisting a Temporary Permission Granted by Picker](file-persistPermission.md#persisting-a-temporary-permission-granted-by-picker). (This operation is available only for 2-in-1 devices.) +- No permission is required if your application uses Picker to save audio clips, images, videos, and document files. -To enable the saved image or video to be viewed in **Gallery**, [create the media asset using a security component](../media/medialibrary/photoAccessHelper-savebutton.md). +**System Isolation Description** +- The files saved by the Picker are stored in the specified directory. They are isolated from the assets managed by **Gallery** and cannot be viewed in **Gallery**. +- To save images and videos to **Gallery**, [use a security component](../media/medialibrary/photoAccessHelper-savebutton.md). ## Saving Images or Videos -[PhotoViewPicker](../reference/apis-core-file-kit/js-apis-file-picker.md#photoviewpicker) will not be maintained in later versions. You are advised to [use a security component to create a media asset](../media/medialibrary/photoAccessHelper-savebutton.md). +[PhotoViewPicker](../reference/apis-core-file-kit/js-apis-file-picker.md#photoviewpickerdeprecated) will not be maintained in later versions. You are advised to use [Media Library Kit](../media/medialibrary/photoAccessHelper-savebutton.md) to save media assets. If the security component cannot be called to save images and videos in your development, use [PhotoAccessHelper.showAssetsCreationDialog](../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#showassetscreationdialog12) to save images and videos. @@ -26,14 +30,14 @@ If the security component cannot be called to save images and videos in your dev import { common } from '@kit.AbilityKit'; ``` -2. Create a **documentSaveOptions** instance. +2. Configure the save options. ```ts // Create a documentSaveOptions instance. const documentSaveOptions = new picker.DocumentSaveOptions(); - // (Optional) Name of the document to save. + // (Optional) Name of the file to save. The default value is empty. documentSaveOptions.newFileNames = ["DocumentViewPicker01.txt"]; - // (Optional) Type of the document to save. The value is in ['Description|File name extensions'] format. To save all documents, use 'All files (*.*)|.*'. If there are multiple file name extensions, the first one is used by default. + // (Optional) Type of the document to save. The value is in ['Description|File name extensions'] format. To save all files, use 'All files (*.*)|.*'. If there are multiple file name extensions (a maximum of 100 extensions can be filtered), the first one is used by default. If this parameter is not specified, no extension is filtered by default. documentSaveOptions.fileSuffixChoices = ['Document|.txt', '.pdf']; ``` @@ -43,9 +47,7 @@ If the security component cannot be called to save images and videos in your dev let uris: Array = []; // Ensure that getContext(this) returns UIAbilityContext. let context = getContext(this) as common.Context; - // Create a DocumentViewPicker instance. const documentViewPicker = new picker.DocumentViewPicker(context); - // After the user selects the target folder and saves the documents, the URIs of the saved documents are returned. documentViewPicker.save(documentSaveOptions).then((documentSaveResult: Array) => { uris = documentSaveResult; console.info('documentViewPicker.save to file succeed and uris are:' + uris); @@ -54,16 +56,18 @@ If the security component cannot be called to save images and videos in your dev }) ``` -> **NOTE** -> -> - Avoid directly using a URI in the Picker callback to open the document. Instead, define a global variable to save the URI. -> - The permission for the URIs returned by [save()](../reference/apis-core-file-kit/js-apis-file-picker.md#save) of Picker is a temporary read/write permission. The temporary permission will be invalidated once the application exits. -> - You can persist the temporary permission for a URI, which is available only for 2-in-1 devices. For details, see [Persisting a Temporary Permission Granted by Picker](file-persistPermission.md#persisting-a-temporary-permission-granted-by-picker). -> - You can also directly save the documents to the **Download** folder. For details, see [Saving Files to the Download Directory](#saving-files-to-the-download-directory). + > **NOTE** + > + > 1. URI storage:
+ > - Avoid directly using a URI in the Picker callback.
+ > - Define a global variable to save the URI for future use.
+ > + > 2. Quick saving:
+ > - Directly access the download directory in [DOWNLOAD mode](#saving-files-to-the-download-directory).
4. After the application UI is returned from FilePicker, call [fs.openSync](../reference/apis-core-file-kit/js-apis-file-fs.md#fsopensync) to open a document based on the URI. The file descriptor (FD) is returned after the document is opened. - ```ts + ```ts const uri = ''; // Note that the permission specified by the mode parameter of fs.openSync() is fs.OpenMode.READ_WRITE. let file = fs.openSync(uri, fs.OpenMode.READ_WRITE); @@ -89,22 +93,21 @@ If the security component cannot be called to save images and videos in your dev import { common } from '@kit.AbilityKit'; ``` -2. Create an **audioSaveOptions** instance. +2. Configure the save options. ```ts - // Create an audioSaveOptions instance. const audioSaveOptions = new picker.AudioSaveOptions(); - // Set the name of the audio clip to save. This parameter is optional. + // (Optional) Name of the document to save. audioSaveOptions.newFileNames = ['AudioViewPicker01.mp3']; ``` -3. Create an [AudioViewPicker](../reference/apis-core-file-kit/js-apis-file-picker.md#audioviewpicker) instance and use [save()](../reference/apis-core-file-kit/js-apis-file-picker.md#save-5) to start the FilePicker page to save the audio clip. +3. Create an [AudioViewPicker](../reference/apis-core-file-kit/js-apis-file-picker.md#audioviewpicker) instance and call [save()](../reference/apis-core-file-kit/js-apis-file-picker.md#save-5) to start the FilePicker page to save the audio clip. + ```ts let uri: string = ''; // Ensure that getContext(this) returns UIAbilityContext. let context = getContext(this) as common.Context; const audioViewPicker = new picker.AudioViewPicker(context); - // After the user selects the target folder and saves the audio clips, the URIs of the saved audio clips are returned. audioViewPicker.save(audioSaveOptions).then((audioSelectResult: Array) => { uri = audioSelectResult[0]; console.info('audioViewPicker.save to file succeed and uri is:' + uri); @@ -112,12 +115,15 @@ If the security component cannot be called to save images and videos in your dev console.error(`Invoke audioViewPicker.save failed, code is ${err.code}, message is ${err.message}`); }) ``` -> **NOTE** -> -> - Avoid directly using a URI in the Picker callback to open the audio clip. Instead, define a global variable to save the URI. -> - The permission for the URIs returned by [save()](../reference/apis-core-file-kit/js-apis-file-picker.md#save-3) of Picker is a temporary read/write permission. The temporary permission will be invalidated once the application exits. -> - You can persist the temporary permission for a URI, which is available only for 2-in-1 devices. For details, see [Persisting a Temporary Permission Granted by Picker](file-persistPermission.md#persisting-a-temporary-permission-granted-by-picker). -> - You can also directly save audio clips to the **Download** folder. For details, see [Saving Files to the Download Directory](#saving-files-to-the-download-directory). + + > **NOTE** + > + > 1. URI storage:
+ > - Avoid directly using a URI in the Picker callback.
+ > - Define a global variable to save the URI for future use.
+ > + > 2. Quick saving:
+ > - Directly access the download directory in [DOWNLOAD mode](#saving-files-to-the-download-directory).
4. After the application UI is returned from FilePicker, call [fs.openSync](../reference/apis-core-file-kit/js-apis-file-fs.md#fsopensync) to open an audio clip based on the URI. The FD is returned after the audio clip is opened. @@ -127,7 +133,7 @@ If the security component cannot be called to save images and videos in your dev console.info('file fd: ' + file.fd); ``` -5. Call [fs.writeSync](../reference/apis-core-file-kit/js-apis-file-fs.md#writesync) to modify the audio clip based on the FD, and use **fs.closeSync()** to close the FD. +5. Call [fs.writeSync](../reference/apis-core-file-kit/js-apis-file-fs.md#writesync) to modify the document based on the FD, and call **fs.closeSync()** to close the FD. ```ts let writeLen = fs.writeSync(file.fd, 'hello, world'); @@ -135,29 +141,34 @@ If the security component cannot be called to save images and videos in your dev fs.closeSync(file); ``` + ## Saving Files to the Download Directory -When using **save()**, you can set **pickerMode** to **DOWNLOAD**, which will trigger user authorization. After the user allows the operation, a folder with the current HAP bundle name will be created in the **Download** directory of the user, and the folder URI will be returned by **save()**. As a result, user files can be directly stored in the folder with this URI. +**Characteristics** + +- The directory is automatically created in `Download/bundle name/`. +- Files can be directly saved without file selection. +- You can create files under the returned URI that has persistent permissions. + 1. Import modules. ```ts - import { picker } from '@kit.CoreFileKit'; + import { fileUri, picker } from '@kit.CoreFileKit'; import { fileIo as fs } from '@kit.CoreFileKit'; import { BusinessError } from '@kit.BasicServicesKit'; import { common } from '@kit.AbilityKit'; ``` -2. Create a **documentSaveOptions** instance. +2. Configure the download mode. ```ts - // Create a documentSaveOptions instance. const documentSaveOptions = new picker.DocumentSaveOptions(); // Set pickerMode to DOWNLOAD, which takes precedence over the settings in documentSaveOptions. documentSaveOptions.pickerMode = picker.DocumentPickerMode.DOWNLOAD; ``` -3. Create a **DocumentViewPicker** instance, and call [save()](../reference/apis-core-file-kit/js-apis-file-picker.md#save-1) to start the FilePicker modal page to save the audio clip. After the user allows the operation, a folder of the corresponding application is created in the **Download** directory and the URI of the folder is returned. - +3. Save the file to the **Download** directory. + ```ts let uri: string = ''; // Ensure that getContext(this) returns UIAbilityContext. @@ -168,6 +179,10 @@ When using **save()**, you can set **pickerMode** to **DOWNLOAD**, which will tr documentViewPicker.save(documentSaveOptions ).then((documentSaveResult: Array) => { uri = documentSaveResult[0]; console.info('documentViewPicker.save succeed and uri is:' + uri); + const testFilePath = new fileUri.FileUri(uri + '/test.txt').path; + const file = fs.openSync(testFilePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); + fs.writeSync(file.fd, 'Hello World!'); + fs.closeSync(file.fd); }).catch((err: BusinessError) => { console.error(`Invoke documentViewPicker.save failed, code is ${err.code}, message is ${err.message}`); }) diff --git a/en/application-dev/file-management/select-user-file.md b/en/application-dev/file-management/select-user-file.md index 9ec203c549fde6823767795b5ef56781b19cdd7d..a32ecc868f49db9182a251c3c1b6c1c5aa58b058 100644 --- a/en/application-dev/file-management/select-user-file.md +++ b/en/application-dev/file-management/select-user-file.md @@ -4,7 +4,7 @@ You can use [FilePicker](../reference/apis-core-file-kit/js-apis-file-picker.md) **FilePicker** provides the following types of Pickers by file type: -- [PhotoViewPicker](../reference/apis-core-file-kit/js-apis-file-picker.md#photoviewpicker): used to select and save images and videos. However, the APIs of this Picker will not be maintained in later versions. You are advised to use [PhotoViewPicker of PhotoAccessHelper](../media/medialibrary/photoAccessHelper-photoviewpicker.md) to select images, and use [security components to create media assets](../media/medialibrary/photoAccessHelper-savebutton.md). +- [PhotoViewPicker](../reference/apis-core-file-kit/js-apis-file-picker.md#photoviewpickerdeprecated): used to select and save images and videos. However, the APIs of this Picker will not be maintained in later versions. You are advised to use [PhotoViewPicker of PhotoAccessHelper](../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#photoviewpicker) to select images and the [security component to save them](../media/medialibrary/photoAccessHelper-savebutton.md). - [DocumentViewPicker](../reference/apis-core-file-kit/js-apis-file-picker.md#documentviewpicker): used to select and save documents. The **DocumentViewPicker** API triggers the **FilePicker** application. Documents are not distinguished by file name extensions. For example, the images and files downloaded from a browser are documents. @@ -12,7 +12,7 @@ You can use [FilePicker](../reference/apis-core-file-kit/js-apis-file-picker.md) ## Selecting Images or Videos -[PhotoViewPicker](../reference/apis-core-file-kit/js-apis-file-picker.md#photoviewpicker) will not be maintained in later versions. You are advised to use [PhotoViewPicker of PhotoAccessHelper](../media/medialibrary/photoAccessHelper-photoviewpicker.md) to select images. +[PhotoViewPicker](../reference/apis-core-file-kit/js-apis-file-picker.md#photoviewpickerdeprecated) will not be maintained in later versions. You are advised to use [PhotoViewPicker of PhotoAccessHelper](../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#photoviewpicker) to select images. ## Selecting Documents @@ -29,14 +29,22 @@ You can use [FilePicker](../reference/apis-core-file-kit/js-apis-file-picker.md) ```ts const documentSelectOptions = new picker.DocumentSelectOptions(); - // (Optional) Set the maximum number of documents that can be selected. + // Set the maximum number of documents that can be selected. This parameter is optional. documentSelectOptions.maxSelectNumber = 5; - // (Optional) Specify the path of the files or folder to select. + // Specify the path of the files or folder to select. This parameter is optional. documentSelectOptions.defaultFilePathUri = "file://docs/storage/Users/currentUser/test"; - // (Optional) Set the file name extension types ['File name extension description|File name extension type'] that can be selected. Use a comma to separate multiple file name extensions, which cannot exceed 100. To select all files, use 'All files(*.*)|.*'. + // (Optional. If this parameter is not transferred, all files are displayed by default.) Set the file name extension types ['File name extension description|File name extension type'] that can be selected. (Optional) Use a comma to separate multiple file name extensions, which cannot exceed 100. The wildcard ['All files (*.*)|.*'] can be used on 2-in-1 devices to display all files. Currently, mobile phones do not support this configuration. documentSelectOptions.fileSuffixFilters = ['Image(.png, .jpg)|.png, .jpg', 'Document|.txt', 'Video|.mp4', '.pdf']; - // Whether to grant the permission for the specified files or folder. The value true means to grant the permission, the value false means the opposite. If this parameter is true, defaultFilePathUri is mandatory and the file management authorization page is displayed. If this parameter is false, a common file management page is displayed. This parameter is optional. - documentSelectOptions.authMode = true; + // Whether to grant the permission for the specified files or folder. The value true means to grant the permission, the value false (default) means the opposite. If this parameter is true, defaultFilePathUri is mandatory and the file management authorization page is displayed. If this parameter is false, a common file management page is displayed. This parameter is optional and only 2-in-1 devices are supported. + documentSelectOptions.authMode = false; + // Whether to enable the batch authorization mode. The value true means to enable the batch authorization mode, and the value false (default) means the opposite. When multAuthMode is set to true, only the multiUriArray parameter takes effect. Only mobile phones are supported. + documentSelectOptions.multiAuthMode = false; + // Whether to pass the URIs for batch authorization. (Only files are supported and folders are not supported.) This parameter does not take effect when multAuthMode is set to false. Only mobile phones are supported. + documentSelectOptions.multiUriArray = ["file://docs/storage/Users/currentUser/test", "file://docs/storage/Users/currentUser/2test"]; + // Whether to enable the aggregation view mode to launch the file management application. The value DEFAULT means that this parameter does not take effect and the aggregation view mode is disabled. Values other than DEFAULT means that other parameters do not take effect. Only mobile phones are supported. + documentSelectOptions.mergeMode = picker.MergeTypeMode.DEFAULT; + // Whether to support encryption (only files are supported). The default value is false. If this parameter is set to true, files can be encrypted on the picker page. + documentSelectOptions.isEncryptionSupported = false; ``` 3. Create a [DocumentViewPicker](../reference/apis-core-file-kit/js-apis-file-picker.md#documentviewpicker) instance, and call [select()](../reference/apis-core-file-kit/js-apis-file-picker.md#select-3) to start the FilePicker application page for the user to select documents. @@ -105,7 +113,7 @@ You can use [FilePicker](../reference/apis-core-file-kit/js-apis-file-picker.md) const audioSelectOptions = new picker.AudioSelectOptions(); ``` -3. Create an [AudioViewPicker](../reference/apis-core-file-kit/js-apis-file-picker.md#audioviewpicker) instance, and call [select()](../reference/apis-core-file-kit/js-apis-file-picker.md#select-6) to start the FilePicker application page for the user to select audio clips. +3. Create an [AudioViewPicker](../reference/apis-core-file-kit/js-apis-file-picker.md#audioviewpicker) instance, and call [select()](../reference/apis-core-file-kit/js-apis-file-picker.md#select-5) to start the FilePicker application page for the user to select audio clips. ```ts let uris: string = ''; diff --git a/en/application-dev/file-management/set-security-label.md b/en/application-dev/file-management/set-security-label.md index c458c3d2db07d28adc2103e264da3afbc0f37c3d..ec04df50f3276efbce2ea41ec416e212a2e44ff6 100644 --- a/en/application-dev/file-management/set-security-label.md +++ b/en/application-dev/file-management/set-security-label.md @@ -4,7 +4,7 @@ The security capabilities vary with devices. For example, small embedded devices ## Available APIs -For details about the APIs, see [ohos.file.securityLabel](../reference/apis-core-file-kit/js-apis-file-securityLabel.md). +For details about APIs, see [ohos.file.securityLabel](../reference/apis-core-file-kit/js-apis-file-securityLabel.md). **Table 1** Security level APIs @@ -35,7 +35,7 @@ let context = getContext(this) as common.UIAbilityContext; // Obtain UIAbilityCo let pathDir = context.filesDir; let filePath = pathDir + '/test.txt'; -// Open the file. +// Open a file. let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); // Set the data level of the file to S0. securityLabel.setSecurityLabel(filePath, 's0').then(() => { diff --git a/en/application-dev/file-management/share-app-file.md b/en/application-dev/file-management/share-app-file.md index 535c9414690e73406b7236b0bdf6137c72e5413d..4d82197e72f92a5bcd196eccb0ab824a272e15ce 100644 --- a/en/application-dev/file-management/share-app-file.md +++ b/en/application-dev/file-management/share-app-file.md @@ -1,25 +1,24 @@ # Sharing an Application File -An application can share a file with another application based on the file descriptor (FD) or uniform resource identifier (URI) of the file. +An application can share a file with another application based on the uniform resource identifier (URI) of the file. -- URI-based file sharing: You can use [wantConstant.Flags](../reference/apis-ability-kit/js-apis-app-ability-wantConstant.md#flags) to specify the read or read/write permission on the file for the target application (application with which the file is shared). The target application can call [fs.open](../reference/apis-core-file-kit/js-apis-file-fs.md#fsopen) to open the file based on the URI and perform read and write operations. Currently, only temporary authorization is supported. The permission on the shared file is revoked once the target application exits. +## Using startAbility to Start a File Application -- FD-based sharing: You can use **open()** of the ohos.file.fs module to specify the read or read/write permission on the file for the target application. After obtaining the FD from Want, the target application can call [ohos.file.fs](../reference/apis-core-file-kit/js-apis-file-fs.md) APIs to read and write the file. -After the FD of a shared file is closed, the target application can no longer open the shared file. Therefore, FD-based file sharing is not recommended. This topic describes how to [share an application file](#sharing-an-application-file) and [use a shared file](#using-a-shared-file) based on the file URI. +[startAbility](../application-models/file-processing-apps-startup.md)-based file sharing: You can use [wantConstant.Flags](../reference/apis-ability-kit/js-apis-app-ability-wantConstant.md#flags) to specify the read or read/write permission on the file for the target application (application with which the file is shared). The target application can call [fs.open](../reference/apis-core-file-kit/js-apis-file-fs.md#fsopen) to open the file based on the URI and perform read and write operations. ## Shareable Application Directories -| Application Sandbox Path | Physical Path | Description              | -| ---------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| /data/storage/el1/base | /data/app/el1/\/base/\ | Encrypted database directory under **/el1**. | -| /data/storage/el2/base | /data/app/el2/\/base/\ | Encrypted database directory under **/el2**. | -| /data/storage/el2/distributedfiles | /mnt/hmdfs/\/account/device_view/\/data/\ | Distributed data directory with an account under **/el2**. | +| Application Sandbox Path | Description             | +| ------- | ---- | +| /data/storage/el1/base | Encrypted database directory under **/el1**.| +| /data/storage/el2/base | Encrypted database directory under **/el2**.| +| /data/storage/el2/distributedfiles | Distributed data directory with an account under **el2/**.| ## File URI Specifications The file URIs are in the following format: - **file**://<bundleName>/<path> + file://<bundleName>/<path> - **file**: indicates a file URI. @@ -27,134 +26,8 @@ The file URIs are in the following format: - *path*: specifies the application sandbox path of the file. -## Sharing an Application File +## -Before sharing an application file, you need to [obtain the application file path](../application-models/application-context-stage.md#obtaining-application-file-paths). + -1. Obtain the application sandbox path of the file and convert it into the file URI. - - ```ts - import { UIAbility } from '@kit.AbilityKit'; - import { fileUri } from '@kit.CoreFileKit'; - import { window } from '@kit.ArkUI'; - - export default class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage: window.WindowStage) { - // Obtain the application sandbox path of the file. - let pathInSandbox = this.context.filesDir + "/test1.txt"; - // Convert the application sandbox path into a URI. - let uri = fileUri.getUriFromPath(pathInSandbox); - // The obtained URI is file://com.example.demo/data/storage/el2/base/files/test1.txt. - } - } - ``` - -2. Set the target application and grant permissions on the file.
- Use [startAbility](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to start the target application. You need to pass in the obtained URI in **uri** of the **want** parameter, set the type of the file to share, set **action** to **ohos.want.action.sendData**, and set the granted permission on the file in **flags**. For details, see [Want](../reference/apis-ability-kit/js-apis-app-ability-want.md#properties). - - > **NOTE** - > - > The write permission granted includes the read permission. - - ```ts - import { fileUri } from '@kit.CoreFileKit'; - import { window } from '@kit.ArkUI'; - import { wantConstant } from '@kit.AbilityKit'; - import { UIAbility } from '@kit.AbilityKit'; - import { Want } from '@kit.AbilityKit'; - import { BusinessError } from '@kit.BasicServicesKit'; - - export default class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage: window.WindowStage) { - // Obtain the application sandbox path of the file. - let filePath = this.context.filesDir + '/test1.txt'; - // Convert the application sandbox path into a URI. - let uri = fileUri.getUriFromPath(filePath); - let want: Want = { - // Grant the read and write permissions on the shared file to the target application. - flags: wantConstant.Flags.FLAG_AUTH_WRITE_URI_PERMISSION | wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, - // Set the implicit startup rule for the target application. - action: 'ohos.want.action.sendData', - uri: uri, - type: 'text/plain' - } - this.context.startAbility(want) - .then(() => { - console.info('Invoke getCurrentBundleStats succeeded.'); - }) - .catch((err: BusinessError) => { - console.error(`Invoke startAbility failed, code is ${err.code}, message is ${err.message}`); - }); - } - // ... - } - ``` -**Figure 1** Example - - ![share-app-file](figures/share-app-file.png) - -## Using a Shared File - -In the [**module.json5** file](../quick-start/module-configuration-file.md) of the target application, set **actions** to **ohos.want.action.sendData** to allow the application to receive files shared by others and set **uris** to the type of the URI to receive. In the following example, the target application receives only .txt files with **scheme** of **file**. - -```json -{ - "module": { - ... - "abilities": [ - { - ... - "skills": [ - { - ... - "actions": [ - "ohos.want.action.sendData" - ], - "uris": [ - { - "scheme": "file", - "type": "text/plain" - } - ] - } - ] - } - ] - } -} -``` - -After the UIAbility starts, the target application obtains want information via [onCreate()](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityoncreate) or [onNewWant](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#uiabilityonnewwant). - -After obtaining the URI of the shared file from **want**, the target application can call **fs.open** to open the file and then read and write the file. - -```ts -// xxx.ets -import { fileIo as fs } from '@kit.CoreFileKit'; -import { Want } from '@kit.AbilityKit'; -import { BusinessError } from '@kit.BasicServicesKit'; - -function getShareFile() { - try { - let want: Want = {}; // Change the value to the want information passed by the application that shares the file. - - // Obtain the uri field from the want information. - let uri = want.uri; - if (uri == null || uri == undefined) { - console.info('uri is invalid'); - return; - } - try { - // Perform operations on the URI of the shared file as required. For example, open the URI to obtain the file object in read/write mode. - let file = fs.openSync(uri, fs.OpenMode.READ_WRITE); - console.info('open file successfully!'); - } catch (err) { - let error: BusinessError = err as BusinessError; - console.error(`Invoke openSync failed, code is ${error.code}, message is ${error.message}`); - } - } catch (error) { - let err: BusinessError = error as BusinessError; - console.error(`Invoke openSync failed, code is ${err.code}, message is ${err.message}`); - } -} -``` +- diff --git a/en/application-dev/file-management/user-file-uri-intro.md b/en/application-dev/file-management/user-file-uri-intro.md index c8e055ab2f267b8f7480872abbea7a65f9ee9a9c..4a61fb9e8231c3baa6a401068348e9515a5c170d 100644 --- a/en/application-dev/file-management/user-file-uri-intro.md +++ b/en/application-dev/file-management/user-file-uri-intro.md @@ -7,7 +7,7 @@ As a unique identifier of a user file, the uniform resource identifier (URI) is The URIs in the system can be classified into the following types: - Document URI: URI of a file selected or saved by the file manager started by picker, or obtained via the **fileAccess** module. For details, see [Obtaining a Document URI](#obtaining-a-document-uri). -- Media file URI: URI of an image or video selected from **Gallery** by picker ; URI of an image or video obtained via the **photoAccessHelper** module; URI of an image, video, or audio file obtained via the **userFileManager** module. For details, see [Obtaining a Media File URI](#obtaining-a-media-file-uri). +- Media file URI: URI of an image or video selected from **Gallery** by picker; URI of an image or video obtained via the **photoAccessHelper** module; URI of an image, video, or audio file obtained via the **userFileManager** module. For details, see [Obtaining a Media File URI](#obtaining-a-media-file-uri). ![user-file-uri-intro](figures/user-file-uri-intro.png) @@ -25,22 +25,21 @@ The following table describes the fields in a document URI. | ------------- | ------------------- | | 'file://docs/storage/Users/currentUser/' | Indicates the root directory of the file manager.| | '\/' | Indicates the relative path of the file, for example, **Download/** and **Documents/**.| -| 'test.txt' | Indicates the name of the file stored in the user file system. The supported file types vary, depending on the file manager used. Common file types include TXT, JPG, MP4, and MP3. | +| 'test.txt' | Indicates the name of the file stored in the user file system. The supported file types vary, depending on the file manager used. Common file types include TXT, JPG, MP4, and MP3.| ### Obtaining a Document URI -- Call **select()** or **save()** of [DocumentViewPicker](../reference/apis-core-file-kit/js-apis-file-picker.md#documentviewpicker) to select or save a document. -- Call **select()** or **save()** of [AudioViewPicker](../reference/apis-core-file-kit/js-apis-file-picker.md#audioviewpicker) to select or save an audio file. -- Call [@ohos.file.fileAccess](../reference/apis-core-file-kit/js-apis-fileAccess-sys.md). The [FileInfo](../reference/apis-core-file-kit/js-apis-fileAccess-sys.md#fileinfo) object contains the URI of the file or directory. Note that the APIs of [@ohos.file.fileAccess](../reference/apis-core-file-kit/js-apis-fileAccess-sys.md) can be called only by system applications. +1. Call **select()** or **save()** of [DocumentViewPicker](../reference/apis-core-file-kit/js-apis-file-picker.md#documentviewpicker) to select or save a document. -You can obtain the document URIs of the files and folders in the following directories: +2. Call **select()** or **save()** of [AudioViewPicker](../reference/apis-core-file-kit/js-apis-file-picker.md#audioviewpicker) to select or save an audio file. -- External storage directory -- **Docs** directory -- **Download** directory -- **Desktop** directory -- **Documents** directory -- **Share** directory of the shared disk +3. Call [@ohos.file.fileAccess](../reference/apis-core-file-kit/js-apis-fileAccess-sys.md). The [FileInfo](../reference/apis-core-file-kit/js-apis-fileAccess-sys.md#fileinfo) object contains the URI of the file or directory. Note that the APIs of [@ohos.file.fileAccess](../reference/apis-core-file-kit/js-apis-fileAccess-sys.md) can be called only by system applications. You can obtain the document URIs of the files and folders in the following directories: + - External storage directory + - **Docs** directory + - **Download** directory + - **Desktop** directory + - **Documents** directory + - **Share** directory of the shared disk ### Using a Document URI @@ -108,17 +107,17 @@ async function example() { The URI format varies depending on the media file type. -- Image URI format: +Image URI format: - 'file://media/Photo/\/IMG_datetime_0001/displayName.jpg' +- 'file://media/Photo/\/IMG_datetime_0001/displayName.jpg' -- Video URI format: +Video URI format: - 'file://media/Photo/\/VID_datetime_0001/displayName.mp4' +- 'file://media/Photo/\/VID_datetime_0001/displayName.mp4' -- Audio file URI format: +Audio file URI format: - 'file://media/Audio/\/AUD_datetime_0001/displayName.mp3' +- 'file://media/Audio/\/AUD_datetime_0001/displayName.mp3' The following table describes the fields in a media file URI. @@ -137,12 +136,12 @@ The following table describes the fields in a media file URI. ### Obtaining a Media File URI -- Call [PhotoAccessHelper.PhotoViewPicker](../media/medialibrary/photoAccessHelper-photoviewpicker.md) to select media files. The URIs of the selected files are returned. +1. Call [PhotoViewPicker of PhotoAccessHelper](../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#photoviewpicker) to select media files. The URIs of the selected files are returned. -- Call [getAssets](../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#getassets) or [createAsset](../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#createasset) of [photoAccessHelper](../reference/apis-media-library-kit/js-apis-photoAccessHelper.md). +2. Call [getAssets](../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#getassets) or [createAsset](../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#createasset) of [photoAccessHelper](../reference/apis-media-library-kit/js-apis-photoAccessHelper.md). -- Call [getPhotoAssets](../reference/apis-core-file-kit/js-apis-userFileManager-sys.md#getphotoassets), [getAudioAssets](../reference/apis-core-file-kit/js-apis-userFileManager-sys.md#getaudioassets), [createAudioAsset](../reference/apis-core-file-kit/js-apis-userFileManager-sys.md#createaudioasset10), or [createPhotoAsset](../reference/apis-core-file-kit/js-apis-userFileManager-sys.md#createphotoasset) of [userFileManager](../reference/apis-core-file-kit/js-apis-userFileManager-sys.md). - +3. Call [getPhotoAssets](../reference/apis-core-file-kit/js-apis-userFileManager-sys.md#getphotoassets), [getAudioAssets](../reference/apis-core-file-kit/js-apis-userFileManager-sys.md#getaudioassets), [createAudioAsset](../reference/apis-core-file-kit/js-apis-userFileManager-sys.md#createaudioasset10), or [createPhotoAsset](../reference/apis-core-file-kit/js-apis-userFileManager-sys.md#createphotoasset) of [userFileManager](../reference/apis-core-file-kit/js-apis-userFileManager-sys.md). + ### Using a Media File URI @@ -151,7 +150,7 @@ Applications of the normal APL can call [photoAccessHelper](../reference/apis-me Applications of the system_basic or system_core APL can call **photoAccessHelper** and [userFileManager](../reference/apis-core-file-kit/js-apis-userFileManager-sys.md) APIs to process media files based on their URI. For details about how to use the APIs, see the API reference document. -If you do not want to request the permission for a normal application, call [PhotoAccessHelper.PhotoViewPicker](../media/medialibrary/photoAccessHelper-photoviewpicker.md) to obtain the file URI and call [photoAccessHelper.getAssets](../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#getassets) to obtain the **PhotoAsset** object based on the URI. The **PhotoAsset** object can be used to call [getThumbnail](../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#getthumbnail) to obtain the thumbnail and call [get](../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#get) to read certain information in [PhotoKeys](../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#photokeys). +If you do not want to request the permission for a normal application, call [PhotoViewPicker of PhotoAccessHelper](../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#photoviewpicker) to obtain the file URI and call [photoAccessHelper.getAssets](../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#getassets) to obtain the **PhotoAsset** object based on the URI. The **PhotoAsset** object can be used to call [getThumbnail](../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#getthumbnail) to obtain the thumbnail and call [get](../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#get) to read certain information in [PhotoKeys](../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#photokeys). The following information can be obtained from **PhotoKeys** through temporary authorization: @@ -161,12 +160,12 @@ The following information can be obtained from **PhotoKeys** through temporary a | PHOTO_TYPE | 'media_type' | Type of the media file. | | DISPLAY_NAME | 'display_name' | File name displayed. | | SIZE | 'size' | Size of the file. | -| DATE_ADDED | 'date_added' | Date when the file was added. The value is the number of seconds elapsed since the Epoch time. | -| DATE_MODIFIED | 'date_modified' | Date when the file content (not the file name) was last modified. The value is the number of seconds elapsed since the Epoch time.| +| DATE_ADDED | 'date_added' | Unix timestamp when the file was added, in seconds. | +| DATE_MODIFIED | 'date_modified' | Unix timestamp when the file content (not the file name) was last modified, in seconds. | | DURATION | 'duration' | Duration, in ms. | | WIDTH | 'width' | Image width, in pixels. | | HEIGHT | 'height' | Image height, in pixels. | -| DATE_TAKEN | 'date_taken' | Date when the photo was taken. The value is the number of seconds elapsed since the Epoch time. | +| DATE_TAKEN | 'date_taken' | Unix timestamp when the photo was taken, in seconds. | | ORIENTATION | 'orientation' | Orientation of the image file. | | TITLE | 'title' | Title in the file. | diff --git a/en/application-dev/form/Readme-EN.md b/en/application-dev/form/Readme-EN.md index 0c69bdbdf51c9c1c84091566e94bb7438722d785..2710099a1ede67cd730a092036755223dfbd1f1d 100644 --- a/en/application-dev/form/Readme-EN.md +++ b/en/application-dev/form/Readme-EN.md @@ -1,33 +1,37 @@ -# Form Kit +# Form Kit - [Introduction to Form Kit](formkit-overview.md) -- Service Widget Development in Stage Model - - Developing an ArkTS Widget +- Service Widget Development in Stage Model + - Developing an ArkTS Widget - [ArkTS Widget Working Principles](arkts-ui-widget-working-principles.md) - [ArkTS Widget Related Modules](arkts-ui-widget-modules.md) - - ArkTS Widget Development + - ArkTS Widget Development - [Creating an ArkTS Widget](arkts-ui-widget-creation.md) - [Configuring Widget Configuration Files](arkts-ui-widget-configuration.md) - [Widget Lifecycle Management](arkts-ui-widget-lifecycle.md) - - Widget Page Development + - Widget Page Development - [Widget Page Capability Overview](arkts-ui-widget-page-overview.md) - [Using Animations in the Widget](arkts-ui-widget-page-animation.md) - [Applying Custom Drawing in the Widget](arkts-ui-widget-page-custom-drawing.md) - - Widget Event Development + - Widget Event Development - [Widget Event Capability Overview](arkts-ui-widget-event-overview.md) - [Launching the UIAbility of the Widget Provider Through the router Event](arkts-ui-widget-event-router.md) - [Launching the UIAbility of the Widget Provider in the Background Through the call Event](arkts-ui-widget-event-call.md) - [Updating Widget Content Through the message Event](arkts-ui-widget-event-formextensionability.md) - [Updating Widget Content Through the router or call Event](arkts-ui-widget-event-uiability.md) - - Widget Data Interaction + - Widget Data Interaction - [Updating Widget Content](arkts-ui-widget-interaction-overview.md) - [Interval-based Widget Updates](arkts-ui-widget-update-by-time.md) - [Time-specific Widget Updates](arkts-ui-widget-update-by-time-point.md) - [Updating Widget Content Through a Proxy](arkts-ui-widget-update-by-proxy.md) - [Conditional Widget Updates](arkts-ui-widget-update-by-conditions.md) + - [Updating Widget Content by Widget Host (for System Applications Only)](arkts-ui-widget-content-update.md) - [Updating Local and Online Images in the Widget](arkts-ui-widget-image-update.md) - [Updating Widget Content by State](arkts-ui-widget-update-by-status.md) + - Editing the ArkTS Widget Page + - [Overview of ArkTs Widget Page Editing Interaction](arkts-ui-widget-event-formeditextensionability-overview.md) + - [Editing and Updating the Widget Content](arkts-ui-widget-event-formeditextensionability.md) - [Widget Host Development (for System Applications Only)](widget-host-development-guide.md) diff --git a/en/application-dev/form/arkts-ui-widget-configuration.md b/en/application-dev/form/arkts-ui-widget-configuration.md index 503d3092ccdf6e282137a921d4609605f9132948..e74b5752eb44320f7baaa1dbe503de020d802244 100644 --- a/en/application-dev/form/arkts-ui-widget-configuration.md +++ b/en/application-dev/form/arkts-ui-widget-configuration.md @@ -38,6 +38,7 @@ Widget-related configuration includes **FormExtensionAbility** configuration and | Field| Description| Data Type| Default Value Allowed| | -------- | -------- | -------- | -------- | + | forms | Configuration about all application widgets.
A maximum of 16 widgets can be configured. If more than 16 widgets are configured, the first 16 widgets are retained.| Array| No| | name | Name of the widget. The value is a string with a maximum of 127 bytes.| String| No| | displayName | Display name of the widget. The value can be a string or a resource index to the name in multiple languages. The string must contain 1 to 30 bytes.| String| No| | description | Description of the widget. The value can be a string or a resource index to descriptions in multiple languages. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| diff --git a/en/application-dev/form/arkts-ui-widget-event-formeditextensionability-overview.md b/en/application-dev/form/arkts-ui-widget-event-formeditextensionability-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..aabcbe27a86925a42d0c0ba2da954e3284581da1 --- /dev/null +++ b/en/application-dev/form/arkts-ui-widget-event-formeditextensionability-overview.md @@ -0,0 +1,20 @@ +# Overview of ArkTs Widget Page Editing Interaction + +The home screen provides a unified widget editing page. The widget provider uses the [startSecondPage](../reference/apis-form-kit/js-apis-inner-application-formEditExtensionContext.md#startsecondpage) method provided by FormEditExtensionContext of the [FormEditExtensionAbility](../reference/apis-form-kit/js-apis-app-form-formEditExtensionAbility.md) component to transfer the level-2 editing page information to the home screen. After the home screen opens the level-2 editing page, the page content can be edited. + + +The following figure shows the widget editing process. + +Figure 1 Widget editing process + +![FormEditExtensionAbility](./figures/Widget-FormEditExtensionAbility.PNG) + +1. When a user taps a widget to edit it, the widget provider inherits [FormEditExtensionAbility](../reference/apis-form-kit/js-apis-app-form-formEditExtensionAbility.md) to implement the widget editing function. + +2. After the user identifies that the widget provider inherits [FormEditExtensionAbility](../reference/apis-form-kit/js-apis-app-form-formEditExtensionAbility.md), the level-1 editing page of the widget provider is displayed. + +3. The widget provider invokes the [startSecondPage](../reference/apis-form-kit/js-apis-inner-application-formEditExtensionContext.md#startsecondpage) method of [FormEditExtensionContext](../reference/apis-form-kit/js-apis-inner-application-formEditExtensionContext.md) in the callback method [onSessionCreate](../reference/apis-form-kit/js-apis-app-form-formEditExtensionAbility.md#onsessioncreate) of [FormEditExtensionAbility](../reference/apis-form-kit/js-apis-app-form-formEditExtensionAbility.md) to transfer the level-2 page information of the widget provider to be started to the widget management service. + +4. The widget management service transfers the received level-2 page information of the widget provider to the user. + +5. Then the user opens the level-2 page to edit the page content. diff --git a/en/application-dev/form/arkts-ui-widget-event-formeditextensionability.md b/en/application-dev/form/arkts-ui-widget-event-formeditextensionability.md new file mode 100644 index 0000000000000000000000000000000000000000..8d558cfc63f2eb77a035171d8d0d68f47fbcb931 --- /dev/null +++ b/en/application-dev/form/arkts-ui-widget-event-formeditextensionability.md @@ -0,0 +1,183 @@ +# Editing and Updating the Widget Content + +The home screen provides a unified widget editing page. The widget provider uses [FormEditExtensionAbility](../reference/apis-form-kit/js-apis-app-form-formEditExtensionAbility.md) provided by the widget framework to develop the widget editing function. + +## How to Develop +1. In the entry module of the project, create a code file named EntryFormEditAbility. In the EntryFormEditAbility file, implement the [startSecondPage](../reference/apis-form-kit/js-apis-inner-application-formEditExtensionContext.md#startsecondpage) method. In the [onSessionCreate](../reference/apis-form-kit/js-apis-app-form-formEditExtensionAbility.md#onsessioncreate) callback method, load the level-1 widget editing page and transfer the implementation of the **startSecondPage** method to the level-1 widget editing page. + +```ts +// src/main/ets/entryformeditability/EntryFormEditAbility.ets + +import { FormEditExtensionAbility } from '@kit.FormKit'; +import { Want,UIExtensionContentSession } from '@kit.AbilityKit'; +import { ExtensionEvent } from '../pages/model/ExtensionEvent'; + +const TAG: string = 'FormEditDemo[EntryFormEditAbility] -->'; +export default class EntryFormEditAbility extends FormEditExtensionAbility { + onCreate() { + console.log(`${TAG} onCreate`); + } + onForeground(): void { + console.log(`${TAG} EntryFormEditAbility onForeground.....`); + } + onBackground(): void { + console.log(`${TAG} EntryFormEditAbility onBackground......`); + } + onDestroy(): void { + console.log(`${TAG} EntryFormEditAbility onDestroy......`); + } + onSessionCreate(want: Want, session: UIExtensionContentSession) { + console.log(`${TAG} onSessionCreate start..... want: ${JSON.stringify(want)}`); + let storage: LocalStorage = new LocalStorage(); + let extensionEvent: ExtensionEvent = new ExtensionEvent(); + extensionEvent.setStartSecondPage(() => this.startSecondPage()); + storage.setOrCreate('extensionEvent', extensionEvent); + try { + session.loadContent('pages/Extension', storage); + session.setWindowBackgroundColor('#00000000'); + } catch (e) { + console.log(`${TAG} EntryFormEditAbility loadContent err, want: ${JSON.stringify(e)}`); + } + } + onSessionDestroy(session: UIExtensionContentSession) { + console.log(`${TAG} onSessionDestroy`); + } + private startSecondPage(): void { + const bundleName: string = this.context.extensionAbilityInfo.bundleName; + const secPageAbilityName: string = 'FormEditSecPageAbility'; + console.log(`${TAG} startSecondPage. bundleName: ${bundleName}, secPageAbilityName: ${secPageAbilityName}.`); + try { + this.context.startSecondPage({ + bundleName: bundleName, + parameters: { + "secPageAbilityName": secPageAbilityName + } + }); + } catch (err) { + console.log(`${TAG} startSecondPage failed: ${err}`); + } + } +}; +``` + +2. Add an extension file to display the level-1 editing page of the widget. + +```ts +// src/main/ets/pages/Extension.ets + +import { UIExtensionContentSession } from '@kit.AbilityKit'; +import { ExtensionEvent } from './model/ExtensionEvent'; + +let storage = LocalStorage.getShared(); +const TAG: string = 'FormEditDemo[Extension] -->'; +@Entry(storage) +@Component +struct Extension { + @State message: string = 'UIExtension Provider'; + private session: UIExtensionContentSession | undefined = storage.get('session'); + private extensionEvent: ExtensionEvent | undefined = storage.get('extensionEvent'); + onPageShow() { + console.log(`${TAG} onPageShow. extensionEvent: ${JSON.stringify(this.extensionEvent)}, session: ${JSON.stringify(this.session)}.`); + } + build() { + Row() { + Column() { + Text(this.message) + .fontSize(20) + .fontWeight(FontWeight.Bold) + .textAlign(TextAlign.Center) + Button("Add") + .width('80%') + .type(ButtonType.Capsule) + .margin({ + top: 20 + }) + .onClick(() => { + console.log(`${TAG} Button onClick`); + this.extensionEvent?.startFormEditSecondPage(); + }) + } + } + .justifyContent(FlexAlign.Center) + .width('100%') + } +} +``` + +3. Add the ExtensionEvent file and use the **startFormEditSecondPage** method to invoke the [startSecondPage](../reference/apis-form-kit/js-apis-inner-application-formEditExtensionContext.md#startsecondpage) method. + +```ts +// src/main/ets/widget/pages/model/ExtensionEvent.ets + +const TAG: string = 'FormEditDemo[ExtensionEvent] -->'; +export class ExtensionEvent { + private startSecondPage: () => void = () => { + console.log(`${TAG} startSecondPage is empty!`); + }; + public setStartSecondPage(startSecondPage: () => void) { + console.log(`${TAG} setStartSecondPage`); + this.startSecondPage = startSecondPage; + } + public startFormEditSecondPage(): void { + console.log(`${TAG} startFormEditSecondPage`); + this.startSecondPage(); + } +} + +``` + +4. Add the widget editing configuration to the [module.json5](../quick-start/module-configuration-file.md) configuration file of the application. + +```json +"extensionAbilities": [ + { + "name": "EntryFormEditAbility", + "srcEntry": "./ets/entryformeditability/EntryFormEditAbility.ets", + "type": "formEdit" + } +] +``` + +5. Add the formConfigAbility configuration to the [form_config.json](./arkts-ui-widget-configuration.md) configuration file of the widget. + +```json +{ + "forms": [ + { + "name": "widget", + "displayName": "$string:widget_display_name", + "description": "$string:widget_desc", + "src": "./ets/widget/pages/WidgetCard.ets", + "uiSyntax": "arkts", + "formConfigAbility": "ability://EntryFormEditAbility", + "window": { + "designWidth": 720, + "autoDesignWidth": true + }, + "colorMode": "auto", + "isDynamic": true, + "isDefault": true, + "updateEnabled": false, + "scheduledUpdateTime": "10:30", + "updateDuration": 1, + "defaultDimension": "1*2", + "supportDimensions": [ + "1*2", + "2*2", + "2*4", + "4*4" + ] + } + ] +} +``` +6. Register the Extension page file in the **resource/base/profile/main_pages.json** file in the development view. + +```json +{ + "src": [ + "pages/Index", + "pages/Extension" + ] +} +``` diff --git a/en/application-dev/form/arkts-ui-widget-image-update.md b/en/application-dev/form/arkts-ui-widget-image-update.md index af1672bb1a6d8a72eacaf1242e418c0dad02ff16..b558683513875276503580301f53573d01bc3f48 100644 --- a/en/application-dev/form/arkts-ui-widget-image-update.md +++ b/en/application-dev/form/arkts-ui-widget-image-update.md @@ -108,6 +108,7 @@ Typically, a widget includes local images or online images downloaded from the n } catch (err) { hilog.error(DOMAIN_NUMBER, TAG, "write data to file failed with error message: " + err.message + ", error code: " + err.code); } finally { + // Before executing fileIo.closeSync, ensure that formProvider.updateForm has been executed. fileIo.closeSync(imgFile); }; } catch (e) { diff --git a/en/application-dev/form/arkts-ui-widget-lifecycle.md b/en/application-dev/form/arkts-ui-widget-lifecycle.md index 13ecc446a649a14dee399ddbae93e57dd61886d2..27d47792b54d4cb185c7e9e29c42bfb29cbc2fc4 100644 --- a/en/application-dev/form/arkts-ui-widget-lifecycle.md +++ b/en/application-dev/form/arkts-ui-widget-lifecycle.md @@ -12,7 +12,6 @@ When creating an ArkTS widget, you need to implement the [FormExtensionAbility]( ``` 2. In **EntryFormAbility.ets**, implement the [FormExtensionAbility](../reference/apis-form-kit/js-apis-app-form-formExtensionAbility.md) lifecycle API, including **onAddForm**, in which [want](../reference/apis-ability-kit/js-apis-app-ability-want.md) can be used to obtain the widget information through [FormParam](../reference/apis-form-kit/js-apis-app-form-formInfo.md#formparam). - ```ts const TAG: string = 'EntryFormAbility'; const DOMAIN_NUMBER: number = 0xFF00; @@ -37,6 +36,7 @@ When creating an ArkTS widget, you need to implement the [FormExtensionAbility]( // 1. Temporary widgets and normal widgets are defined from the viewpoint of the widget host. // 2. Temporary widgets have a brief existence, appearing following particular events or user interactions and vanishing automatically upon task completion. // 3. Normal widgets maintain a lasting presence, continuing to exist unless explicitly removed or altered by the user. Function widgets developed in normal cases are normal widgets. + // 4. Currently, temporary widgets are not used on mobile phones. hilog.info(DOMAIN_NUMBER, TAG, '[EntryFormAbility] onCastToNormalForm'); } @@ -84,7 +84,6 @@ When creating an ArkTS widget, you need to implement the [FormExtensionAbility]( } ``` - > **NOTE** > > The FormExtensionAbility cannot reside in the background. It persists for 10 seconds after the lifecycle callback is completed and exits if no new lifecycle callback is invoked during this time frame. This means that continuous tasks cannot be processed in the widget lifecycle callbacks. For the service logic that may take more than 10 seconds to complete, it is recommended that you [start the application](arkts-ui-widget-event-uiability.md) for processing. After the processing is complete, use [updateForm](../reference/apis-form-kit/js-apis-app-form-formProvider.md#updateform) to notify the widget of the update. diff --git a/en/application-dev/form/arkts-ui-widget-modules.md b/en/application-dev/form/arkts-ui-widget-modules.md index 6984435d07be24ef239b65b847e42aa34082ae3c..ffa9347b242867400e4ec338d87171382b5e40d7 100644 --- a/en/application-dev/form/arkts-ui-widget-modules.md +++ b/en/application-dev/form/arkts-ui-widget-modules.md @@ -1,7 +1,7 @@ # ArkTS Widget Related Modules -**Figure 1** ArkTS widget related modules +**Figure 1** ArkTS widget related modules ![WidgetModules](figures/WidgetModules.png) @@ -15,9 +15,9 @@ - [formBindingData](../reference/apis-form-kit/js-apis-app-form-formBindingData.md): provides APIs for widget data binding. You can use the APIs to create a **FormBindingData** object and obtain related information. -- [Page layout (WidgetCard.ets)](arkts-ui-widget-page-overview.md): provides APIs for the declarative UI paradigm. +- [Page layout (WidgetCard.ets)](arkts-ui-widget-page-overview.md): provides the widget UI development capability based on ArkUI. + - [General capabilities of ArkTS widgets](arkts-ui-widget-page-overview.md#page-capabilities-supported-by-arkts-widgets): provides components, attributes, and APIs that can be used in ArkTS widgets. - [Capabilities exclusive to ArkTS widgets](arkts-ui-widget-event-overview.md): include the **postCardAction** API used for interaction between the widget internal and the provider application and can be called only in the widget. - - [ArkTS widget capability list](arkts-ui-widget-page-overview.md#page-capabilities-supported-by-arkts-widgets): contain the APIs, components, events, attributes, and lifecycle callbacks that can be used in ArkTS widgets. - [Widget configuration](arkts-ui-widget-configuration.md): includes FormExtensionAbility configuration and widget configuration. - Configure the FormExtensionAbility information under **extensionAbilities** in the [module.json5 file](../quick-start/module-configuration-file.md). diff --git a/en/application-dev/form/arkts-ui-widget-page-overview.md b/en/application-dev/form/arkts-ui-widget-page-overview.md index 853e1fcf5860ac65bb40a9c264daacaa2690ce34..38f73f9484dd2293cba8e238e6ade955c4a07bcf 100644 --- a/en/application-dev/form/arkts-ui-widget-page-overview.md +++ b/en/application-dev/form/arkts-ui-widget-page-overview.md @@ -1,19 +1,17 @@ # Widget Page Capability Overview -You can leverage the ArkUI declarative paradigm to develop ArkTS widget pages. The following widget pages are automatically generated by a DevEco Studio template. You can adjust the pages based on the real-world service scenarios. +ArkTS widgets are developed using the general [ArkTS language](../quick-start/arkts-get-started.md). You can use the [declarative paradigm](../ui/arkts-ui-development-overview.md) to develop ArkTS widget pages. +The following widget pages are automatically generated by a DevEco Studio template. You can adjust the pages based on the real-world service scenarios. ![WidgetPreviewPage](figures/WidgetPreviewPage.png) -ArkTS widgets have full capabilities of JS widgets, with added animation and custom drawing capabilities plus partial support for components, events, animations, data management, and state management capabilities of the [declarative paradigm](../ui/arkts-ui-development-overview.md). - - ## Page Capabilities Supported by ArkTS Widgets -For details about the capabilities supported by ArkTS widgets, see [Learning ArkTS](../quick-start/arkts-get-started.md) and [ArkTS-based Declarative Development Paradigm](../ui/arkts-ui-development-overview.md). +ArkTS widgets have all capabilities of JS widgets, and support animations, custom drawing, and support capabilities auch as components, events, animations, data management, and status management of [declarative paradigm](../ui/arkts-ui-development-overview.md). -Only the components and APIs marked with "supported in ArkTS widgets" can be used for ArkTS widgets. Pay special attention to the differences from applications. +For APIs that can be used in ArkTS widgets, the tag **Widget capability** is added. Since API version x, these APIs can be used in ArkTS widgets. Pay attention to the capability differences in the widget scenario. -For example, the following description indicates that the @Component decorator can be used in ArkTS widgets. +For example, the following description indicates that CircleShape can be used in ArkTS widgets. ![WidgetSupportApi](figures/WidgetSupportApi.png) diff --git a/en/application-dev/form/arkts-ui-widget-working-principles.md b/en/application-dev/form/arkts-ui-widget-working-principles.md index f7c2fb3483d106580eb41e099a30d1597a469227..e9b58a889eb7d5522cf8ba6da2f4e48eae9d99c0 100644 --- a/en/application-dev/form/arkts-ui-widget-working-principles.md +++ b/en/application-dev/form/arkts-ui-widget-working-principles.md @@ -4,7 +4,6 @@ ## Implementation Principles **Figure 1** ArkTS widget implementation principles - ![WidgetPrinciple](figures/WidgetPrinciple.png) - Widget host: an application that displays the widget content and controls the widget location. Only the system application can function as a widget host. @@ -16,8 +15,7 @@ - Widget rendering service: a service that manages widget rendering instances. Widget rendering instances are bound to the [FormComponent](../reference/apis-arkui/arkui-ts/ts-basic-components-formcomponent-sys.md) on the widget host on a one-to-one basis. The widget rendering service runs the widget page code **widgets.abc** for rendering, and sends the rendered data to the corresponding [FormComponent](../reference/apis-arkui/arkui-ts/ts-basic-components-formcomponent-sys.md) on the widget host. **Figure 2** Working principles of the ArkTS widget rendering service - - ![WidgetRender](figures/WidgetRender.png) +![WidgetRender](figures/WidgetRender.png) Compared with dynamic widgets, static widgets have the same overall running framework and rendering process. The main difference is that after the widget rendering service renders the widget content, the widget host uses the last frame of rendered data as a static image, and the widget rendering instance releases all running resources of the widget to save memory. As such, frequent updating of static widgets causes continuous creation and destruction of resources, resulting in increased power consumption.
Unlike JS widgets, ArkTS widgets support logic code execution. The widget page code **widgets.abc** is executed by the widget rendering service, which is managed by the Widget Manager. Each widget component of a widget host corresponds to a rendering instance in the widget rendering service. Rendering instances of a widget provider run in the same ArkTS virtual machine operating environment, and rendering instances of different widget providers run in different ArkTS virtual machine operating environments. In this way, the resources and state data are isolated between widgets of different widget providers. During development, pay attention to the use of the **globalThis** object. Use one **globalThis** object for widgets from the same widget provider, and different **globalThis** objects for widgets from different widget providers. @@ -32,7 +30,6 @@ As a quick entry to applications, ArkTS widgets outperform JS widgets in the fol ArkTS widgets share the same declarative UI development framework as application pages. This means that the page layouts can be directly reused in widgets, improving development experience and efficiency. **Figure 3** Comparison of widget project structures - ![WidgetProject](figures/WidgetProject.png) - More widget features @@ -46,7 +43,7 @@ Compared with JS widgets, ArkTS widgets provide more capabilities, but they are - When importing modules, you can import only the modules marked with "supported in ArkTS widgets." -- Shared packages cannot be imported. +- [HAR](../quick-start/har-package.md) can be imported, but [HSP](../quick-start/in-app-hsp.md) cannot. - The native programming language cannot be used for development. @@ -63,3 +60,10 @@ In addition, ArkTS widgets do not support the following features: - Hot reload - **setTimeOut** + +## Samples + +The following samples are provided to help you better understand how to develop an ArkTS widget: + + +- [Communication Between JS and C++ for Stage Model Widgets (ArkTS, API version 10)] (https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/Widget/FormGame) diff --git a/en/application-dev/form/figures/Widget-FormEditExtensionAbility.PNG b/en/application-dev/form/figures/Widget-FormEditExtensionAbility.PNG new file mode 100644 index 0000000000000000000000000000000000000000..49e05613e2da005d74c9e97add3d19282ff2f032 Binary files /dev/null and b/en/application-dev/form/figures/Widget-FormEditExtensionAbility.PNG differ diff --git a/en/application-dev/form/figures/WidgetCreateProject.png b/en/application-dev/form/figures/WidgetCreateProject.png index 2372e68a25c116ace77374eba86a8ea7a0680988..53f4e2839f1cb31bcd06ac2c3000fcd36504c498 100644 Binary files a/en/application-dev/form/figures/WidgetCreateProject.png and b/en/application-dev/form/figures/WidgetCreateProject.png differ diff --git a/en/application-dev/form/figures/WidgetProjectCreate1.png b/en/application-dev/form/figures/WidgetProjectCreate1.png index 0c6dab77c8f8a68117d6a70f683bfff0548eda30..f22d39e5662034847b2412ef135dc8f8126077ef 100644 Binary files a/en/application-dev/form/figures/WidgetProjectCreate1.png and b/en/application-dev/form/figures/WidgetProjectCreate1.png differ diff --git a/en/application-dev/form/figures/WidgetProjectCreate2.png b/en/application-dev/form/figures/WidgetProjectCreate2.png index 7bf742e04e2f30febb05f2d8638193dc10532863..755a881da30fe236fe7d270bcb325b8330da692c 100644 Binary files a/en/application-dev/form/figures/WidgetProjectCreate2.png and b/en/application-dev/form/figures/WidgetProjectCreate2.png differ diff --git a/en/application-dev/form/figures/WidgetProjectCreate3.png b/en/application-dev/form/figures/WidgetProjectCreate3.png index 98429567ad24b1a83c67118173bf6cb504bea25d..05fe48522421fce3d1f0b11ad8ef1ab373385cb0 100644 Binary files a/en/application-dev/form/figures/WidgetProjectCreate3.png and b/en/application-dev/form/figures/WidgetProjectCreate3.png differ diff --git a/en/application-dev/form/figures/WidgetProjectView.png b/en/application-dev/form/figures/WidgetProjectView.png index a1c8b42becc089b6b69f58c362569faeaf84f06f..8bb959986e40a25cb450ee7422feb4f8335067dc 100644 Binary files a/en/application-dev/form/figures/WidgetProjectView.png and b/en/application-dev/form/figures/WidgetProjectView.png differ diff --git a/en/application-dev/inputmethod/Readme-EN.md b/en/application-dev/inputmethod/Readme-EN.md index 4d2ad250802ed9512043a6a29404989fd02fc933..046240e57e3ca557031b8b636efc554f855d45b1 100644 --- a/en/application-dev/inputmethod/Readme-EN.md +++ b/en/application-dev/inputmethod/Readme-EN.md @@ -1,8 +1,9 @@ -# IME Kit (Input Method Development Service) +# IME Kit - [Introduction to IME Kit](ime-kit-intro.md) - [Implementing an Input Method Application](inputmethod-application-guide.md) - [Using the Input Method in a Custom Edit Box](use-inputmethod-in-custom-edit-box.md) - [Switching Between Input Methods](switch-inputmehod-guide.md) - [Setting Input Method Subtypes](input-method-subtype-guide.md) -- [Custom Edit Box Development Guide (C/C++)](use-inputmethod-in-custom-edit-box-ndk.md) +- [Using the Input Method in a Custom Edit Box (C/C++)](use-inputmethod-in-custom-edit-box-ndk.md) +- [Immersive Mode of the Input Method Application](inputmethod-immersive-mode-guide.md) diff --git a/en/application-dev/inputmethod/figures/immersive-mode-of-the-input-method.PNG b/en/application-dev/inputmethod/figures/immersive-mode-of-the-input-method.PNG new file mode 100644 index 0000000000000000000000000000000000000000..407832a88a880aec69776e255e30cd419a31bf22 Binary files /dev/null and b/en/application-dev/inputmethod/figures/immersive-mode-of-the-input-method.PNG differ diff --git a/en/application-dev/inputmethod/inputmethod-immersive-mode-guide.md b/en/application-dev/inputmethod/inputmethod-immersive-mode-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..a9ca7b36b2991163b88c9f92cbb5cb8c5ad8d7f7 --- /dev/null +++ b/en/application-dev/inputmethod/inputmethod-immersive-mode-guide.md @@ -0,0 +1,42 @@ +# Immersive Mode of the Input Method Application + + +## When to Use + +To implement consistent immersive experience, a communication mechanism between foreground applications and input method applications is provided. You can set the immersive input mode based on the immersive mode of the foreground application. + +## Working Principles +![Immersive mode of the input method](./figures/immersive-mode-of-the-input-method.png) +- The foreground application sets the desired immersive mode based on the application scenario. +- The desired immersive mode of the foreground application is then passed to the input method application through the input method framework. +- The input method application determines the final immersive mode for the input method framework based on the immersive mode of the foreground application. + +## Access Guide +1. The foreground application [sets the immersive mode for the text box](../reference/apis-arkui/arkui-ts/ts-basic-components-textarea.md#keyboardappearance15). The sample code is as follows: + ```ts + TextArea({text: "hello world"}) + .keyboardAppearance(KeyboardAppearance.IMMERSIVE) + ``` + +2. The input method application [subscribes to the text box attribute change event](../reference/apis-ime-kit/js-apis-inputmethodengine.md#oneditorattributechanged10) and detects the immersive mode desired by the foreground application through the **immersiveMode** field in the **EditorAttribute** callback. The sample code is as follows: + + ```ts + import { inputMethodEngine } from '@kit.IMEKit'; + + inputMethodEngine.getKeyboardDelegate().on("editorAttributeChanged", (attr : inputMethodEngine.EditorAttribute) => { + console.log("recv editorAttributeChanged, immersiveMode: " + attr.immersiveMode); + }) + ``` + +3. The input method application [sets the immersive mode](../reference/apis-ime-kit/js-apis-inputmethodengine.md#setimmersivemode15). + - The **IMMERSIVE** mode is determined by the input method application. + - The input method application cannot set the **IMMERSIVE** mode to the input method framework. + - If the input method application receives **IMMERSIVE** from the foreground application, it is recommended that the input method application set the final immersive mode to **LIGHT_IMMERSIVE** or **DARK_IMMERSIVE** based on the current system color mode. + + + The following sample code shows how to set the immersive mode: + ```ts + panel.setImmersiveMode(inputMethodEngine.ImmersiveMode.LIGHT_IMMERSIVE); + ``` + + \ No newline at end of file diff --git a/en/application-dev/inputmethod/use-inputmethod-in-custom-edit-box-ndk.md b/en/application-dev/inputmethod/use-inputmethod-in-custom-edit-box-ndk.md index 45da7c0970768805353c1bdd8d0b1c2b8a44354e..190db40e5ca69140254ade3238d3a143ebf0d995 100644 --- a/en/application-dev/inputmethod/use-inputmethod-in-custom-edit-box-ndk.md +++ b/en/application-dev/inputmethod/use-inputmethod-in-custom-edit-box-ndk.md @@ -1,9 +1,9 @@ -# Custom Edit Box Development Guide (C/C++) +# Using the Input Method in a Custom Edit Box (C/C++) ## When to Use -IME Kit allows you to use self-drawing components to develop the custom edit box to interact with input method applications, including displaying and hiding input methods and receiving text editing notifications from input method applications. This document describes how to use C/C++ to develop this function. +IME Kit allows you to use input method in the custom edit box to interact with input method applications, including displaying and hiding input methods and receiving text editing notifications from input method applications. This document describes how to use C/C++ to develop this function. ## APIs diff --git a/en/application-dev/internationalization/Readme-EN.md b/en/application-dev/internationalization/Readme-EN.md index b91f6b5e8b221c7b6d34d07874b43e1decd6f3f0..51b86c8e8018cf5c8729a62af1bdd91a042db43f 100644 --- a/en/application-dev/internationalization/Readme-EN.md +++ b/en/application-dev/internationalization/Readme-EN.md @@ -1,10 +1,10 @@ -# Localization Kit +# Localization Kit - [Introduction to Localization Kit](i18n-l10n.md) -- Application Internalization +- Application Internationalization - [UI Design for Internationalization](i18n-ui-design.md) - [Locale and Cultural Habit Division](i18n-locale-culture.md) - - Language and User Preference Setting + - Language and User Preference Setting - [System Language and Region Setting](i18n-system-language-region.md) - [Preferred Language Setting](i18n-preferred-language.md) @@ -14,25 +14,25 @@ - [Number and Unit of Measurement Formatting](i18n-numbers-weights-measures.md) - [Phone Number Formatting](i18n-phone-numbers.md) - [Calendar Setting](i18n-calendar.md) - - Time Zone and DST Setting + - Time Zone and DST Setting - [Timezone Setting](i18n-time-zone.md) - [DST Transition](i18n-dst-transition.md) - - Multilingual Sorting + - Multilingual Sorting - [Overview of Multilingual Sorting](i18n-sorting-overview.md) - [Sorting by Local Habits](i18n-sorting-local.md) - [Sorting by Indexes](i18n-sorting-index.md) - [Character Processing](i18n-character-processing.md) - - Name Localization + - Name Localization - [Language and Locale Name Localization](i18n-language-region-display.md) - [Time Zone Name Localization](i18n-time-zone-display.md) -- Application Localization +- Application Localization - [Multilingual Resource Provisioning](l10n-multilingual-resources.md) - - Application Translation + - Application Translation - [Hard Coding and Concatenation Prevention](l10n-hard-coding-concatenate.md) - [Scene and Context Clarification for Translation](l10n-translation-scene.md) - [Singular/Plural Form Selection](l10n-singular-plural.md) -- Localization Testing - - Pseudo-Localization Testing +- Localization Testing + - Pseudo-Localization Testing - [Overview of Pseudo-Localization Testing](pseudo-i18n-testing-overview.md) - [Pseudo-Localization Testing for Translation](pseudo-i18n-testing-translation.md) - [Pseudo-Localization Testing for UI Mirroring](pseudo-i18n-testing-mirror.md) diff --git a/en/application-dev/internationalization/i18n-calendar.md b/en/application-dev/internationalization/i18n-calendar.md index 6f27349feb32df83a798680841d0478d6c51a78a..6ce217fbed9db5b4131a0297ee9270f2011e04ed 100644 --- a/en/application-dev/internationalization/i18n-calendar.md +++ b/en/application-dev/internationalization/i18n-calendar.md @@ -2,76 +2,73 @@ ## Use Cases -Users in different locales use different calendars. To be specific, the Gregorian calendar is used in most locales, whereas calendars such as the lunar, Islamic, and Hebrew calendars are used in some other locales. What's more, the date and time on the calendar also vary according to the time zone and DST. Therefore, the system should allow users to choose calendars that comply with their local habits. This is made real with the complete set of internationalization (i18n) APIs provided by the [Calendar](../reference/apis-localization-kit/js-apis-i18n.md#calendar8) class. Besides setting the calendar type, date (year, month, and day), time zone, start date of a week, minimum number of days in the first week of a year, user can even determine whether a day is a weekend on the calendar and calculate the day difference between two dates. During application development, you can choose functions that suit your needs in a flexible manner. +Users in different locales use different calendars. To be specific, the Gregorian calendar is used in most locales, whereas calendars such as the lunar, Islamic, and Hebrew calendars are used in some other locales. What's more, the date and time on the calendar also vary according to the time zone and DST. Therefore, the system should allow users to choose calendars that comply with their local habits. This is made real with the complete set of APIs provided by the [Calendar](../reference/apis-localization-kit/js-apis-i18n.md#calendar8) class. Besides setting the calendar type, date (year, month, and day), time zone, start date of a week, minimum number of days in the first week of a year, users can even determine whether a day is a weekend on the calendar and calculate the day difference between two dates. During application development, you can choose functions that suit your needs in a flexible manner. ## How to Develop The following illustrates how to view the lunar calendar date corresponding to the Gregorian calendar date as an example to help you understand the usage of [Calendar](../reference/apis-localization-kit/js-apis-i18n.md#calendar8) APIs. 1. Import the **i18n** module. - - ```ts - import { i18n } from '@kit.LocalizationKit'; - ``` + ```ts + import { i18n } from '@kit.LocalizationKit'; + ``` 2. Configure the Gregorian calendar. + ```ts + let calendar: i18n.Calendar = i18n.getCalendar('zh-Hans', 'gregory'); + // Set the date and time of the Calendar object to 2022.06.13 08:00:00. + calendar.setTime(new Date(2022, 5, 13, 8, 0, 0)); + calendar.setTime(10540800000); - ```ts - let calendar : i18n.Calendar = i18n.getCalendar("zh-Hans", "gregory"); - // Set the date and time of the Calendar object to 2022.06.13 08:00:00. - calendar.setTime(new Date(2022, 5, 13, 8, 0, 0)); - calendar.setTime(10540800000); - - // Set the date and time of the Calendar object to 2022.06.13 08:00:00. - calendar.set(2022, 5, 13, 8, 0, 0); + // Set the date and time of the Calendar object to 2022.06.13 08:00:00. + calendar.set(2022, 5, 13, 8, 0, 0); - // Set the time zone for the Calendar object. - calendar.setTimeZone("Asia/Shanghai"); + // Set the time zone for the Calendar object. + calendar.setTimeZone('Asia/Shanghai'); - // Obtain the time zone for the Calendar object. - let timezone: string = calendar.getTimeZone(); // Asia/Shanghai + // Obtain the time zone for the Calendar object. + let timezone: string = calendar.getTimeZone(); // timezone = 'Asia/Shanghai' - // Obtain the start day of a week for the Calendar object. - let firstDayOfWeek : number = calendar.getFirstDayOfWeek(); // 1 + // Obtain the start day of a week for the Calendar object. + let firstDayOfWeek: number = calendar.getFirstDayOfWeek(); // firstDayOfWeek = 1 - // Set the start day of a week for the Calendar object. - calendar.setFirstDayOfWeek(1); + // Set the start day of a week for the Calendar object. + calendar.setFirstDayOfWeek(1); - // Obtain the minimum number of days in the first week of a year for the Calendar object. - let minimalDaysInFirstWeek : number = calendar.getMinimalDaysInFirstWeek(); // 1 + // Obtain the minimum number of days in the first week of a year for the Calendar object. + let minimalDaysInFirstWeek: number = calendar.getMinimalDaysInFirstWeek(); // minimalDaysInFirstWeek = 1 - // Set the minimum number of days in the first week of a year for the Calendar object. - calendar.setMinimalDaysInFirstWeek(3); + // Set the minimum number of days in the first week of a year for the Calendar object. + calendar.setMinimalDaysInFirstWeek(3); - // Obtain the value of the specified field in the Calendar object. - let value: number = calendar.get("year"); // 2022 + // Obtain the value of the specified field in the Calendar object. + let year: number = calendar.get('year'); // year = 2022 - // Obtain the localized name of the Calendar object. - let calendarName: string = calendar.getDisplayName("zh-Hans"); // Gregorian calendar + // Obtain the localized name of the Calendar object. + let calendarName: string = calendar.getDisplayName('zh-Hans'); // calendarName = 'Gregorian calendar' - // Check whether a given date is a weekend for the Calendar object. - let isWeekend : boolean= calendar.isWeekend(new Date(2023, 9, 15)); // true + // Check whether a given date is a weekend for the Calendar object. + let isWeekend: boolean = calendar.isWeekend(new Date(2023, 9, 15)); // isWeekend = true - // Perform addition and subtraction operations on the specified field of the Calendar object. - calendar.set(2023, 10, 15); - calendar.add("date", 2); - calendar.get("date"); // 17 + // Perform addition and subtraction operations on the specified field of the Calendar object. + calendar.set(2023, 10, 15); + calendar.add('date', 2); + let day: number = calendar.get('date'); // day = 17 - // Check the number of days between the Calendar object and the specified date. - calendar.compareDays(new Date(2023, 10, 15)); // -3 - ``` + // Check the number of days between the Calendar object and the specified date. + let daysDifference: number = calendar.compareDays(new Date(2023, 10, 15)); // daysDifference = -3 + ``` 3. Obtain the lunar calendar date corresponding to the Gregorian calendar date. - - ```ts - let calendar : i18n.Calendar = i18n.getCalendar("zh-Hans", "chinese"); - // Pass the Gregorian calendar information to the Calendar object, with the date and time being 2023.07.25 08:00:00. - calendar.setTime(new Date(2023, 6, 25, 8, 0, 0)); - // Obtain the year, month, and day of the lunar calendar. - calendar.get("year"); // Year expressed in a heavenly stem and earthly branch, which is 40 in this example. The value ranges from 1 to 60. - calendar.get("month"); // The value 5 indicates June. - calendar.get ("date"); // Day, which is 8 in this example. - ``` + ```ts + let calendar: i18n.Calendar = i18n.getCalendar('zh-Hans', 'chinese'); + // Pass the Gregorian calendar information to the Calendar object, with the date and time being 2023.07.25 08:00:00. + calendar.setTime(new Date(2023, 6, 25, 8, 0, 0)); + // Obtain the year, month, and day of the lunar calendar. + let year: number = calendar.get('year'); // year = 40 indicates the age of the trunk branch. The value ranges from 1 to 60. + let month: number = calendar.get('month'); // month = 5 indicates June. + let day: number = calendar.get('date'); // day = 8 indicates the eighth day. + ``` **Table 1** Supported calendar types diff --git a/en/application-dev/internationalization/i18n-character-processing.md b/en/application-dev/internationalization/i18n-character-processing.md index 632178c292f8f87a11f531c29ec364140ce2004b..21f8aae09f0dbd042c6cab315a8b5378a8943c94 100644 --- a/en/application-dev/internationalization/i18n-character-processing.md +++ b/en/application-dev/internationalization/i18n-character-processing.md @@ -11,7 +11,7 @@ Character rules vary greatly in different languages, and it is usually difficult Character attributes are used to determine the character type, for example, digit, letter, or space, and check whether a character is of the right-to-left (RTL) language or whether a character is an ideographic character (for example, Chinese, Japanese, or Korean). -These functions are implemented by APIs of the **Unicode** class. For example, you can use [isDigit](../reference/apis-localization-kit/js-apis-i18n.md#isdigit9) to check whether a character is a digit. The development procedure is as follows: +You can implement these functions by using APIs of the Unicode class. For example, you can use [isDigit](../reference/apis-localization-kit/js-apis-i18n.md#isdigit9) to check whether a character is a digit. The development procedure is as follows: 1. Import the **i18n** module. @@ -25,10 +25,10 @@ These functions are implemented by APIs of the **Unicode** class. For example, y let isDigit: boolean = i18n.Unicode.isDigit(char: string); ``` -3. Obtain the character type. The following code snippet uses the common type as an example. For details, see the **getType** API reference. +3. Obtain the character type. The following code snippet uses the common type as an example. ```ts - let type = i18n.Unicode.getType(char: string); + let unicodeType: string = i18n.Unicode.getType(char: string); ``` **Development Example** @@ -37,25 +37,25 @@ These functions are implemented by APIs of the **Unicode** class. For example, y import { i18n } from '@kit.LocalizationKit'; // Check whether the input character is a digit. -let isDigit = i18n.Unicode.isDigit('1'); // isDigit: true +let isDigit: boolean = i18n.Unicode.isDigit('1'); // isDigit = true // Check whether a character is of the RTL language. -let isRTL = i18n.Unicode.isRTL('a'); // isRTL: false +let isRTL: boolean = i18n.Unicode.isRTL('a'); // isRTL = false // Check whether a character is an ideographic character. -let isIdeograph = i18n.Unicode.isIdeograph('Hua'); // isIdeograph: true +let isIdeograph: boolean = i18n.Unicode.isIdeograph ('华'); // isIdeograph = true // Obtain the character type. -let type = i18n.Unicode.getType('a'); // type: U_LOWERCASE_LETTER +let unicodeType: string = i18n.Unicode.getType('a'); // unicodeType = 'U_LOWERCASE_LETTER' ``` ### Transliteration -Transliteration means to use content with similar pronunciation in the local language to replace the original content. This function is implemented through the [transform](../reference/apis-localization-kit/js-apis-i18n.md#transform9) API of the **Transliterator** class. The development procedure is as follows: +Transliteration means to use content with similar pronunciation in the local language to replace the original content. You can implement this function by using the [transform](../reference/apis-localization-kit/js-apis-i18n.md#transform9) API of the **Transliterator** class. The development procedure is as follows: > **NOTE** -> This module supports the transliteration from Chinese characters to pinyin. However, it does not guaranteed that polyphonic characters are effectively processed based on the context. +> This module supports the transliteration from Chinese characters to pinyin. However, it does not guaranteed that polyphonic characters are correctly processed. 1. Import the **i18n** module. ```ts @@ -64,13 +64,13 @@ Transliteration means to use content with similar pronunciation in the local lan 2. Create a **Transliterator** object to obtain the transliteration list. ```ts - let transliterator: i18n.Transliterator = i18n.Transliterator.getInstance(id: string); // Pass in a valid ID to create a Transliterator object. - let ids: string[] = i18n.Transliterator.getAvailableIDs(); // Obtain the list of IDs supported by the Transliterator object. + let ids: string[] = i18n.Transliterator.getAvailableIDs(); // Obtain the list of IDs supported by the Transliterator object. + let transliterator: i18n.Transliterator = i18n.Transliterator.getInstance(id: string); // Pass in a valid ID to create a Transliterator object. ``` 3. Transliterate text. ```ts - let res: string = transliterator.transform(text: string); // Transliterate the text content. + let translatedText: string = transliterator.transform(text: string); // Transliterate the text content. ``` @@ -80,37 +80,34 @@ Transliteration means to use content with similar pronunciation in the local lan import { i18n } from '@kit.LocalizationKit'; // Transliterate the text into the Latn format. -let transliterator = i18n.Transliterator.getInstance('Any-Latn'); -let wordArray = ["中国", "德国", "美国", "法国"] -for (let i = 0; i < wordArray.length; i++) { - let res = transliterator.transform(wordArray[i]); // res: zhōng guó, dé guó, měi guó, fǎ guó -} +let transliterator: i18n.Transliterator = i18n.Transliterator.getInstance('Any-Latn'); +let text: string = '中国' +let translatedText: string = transliterator.transform(text); // translatedText = 'zhōng guó' // Chinese transliteration and tone removal -let transliter = i18n.Transliterator.getInstance('Any-Latn;Latin-Ascii'); -let result = transliter.transform('中国'); // result: zhong guo +let toneLessTransliterator: i18n.Transliterator = i18n.Transliterator.getInstance('Any-Latn;Latin-Ascii'); +translatedText = toneLessTransliterator.transform ('中国'); // translatedText ='zhong guo' // Chinese surname pronunciation -let nameTransliter = i18n.Transliterator.getInstance('Han-Latin/Names'); -let result1 = nameTransliter.transform('单老师'); // result1: shàn lǎo shī -let result2 = nameTransliter.transform('长孙无忌'); // result2: zhǎng sūn wú jì - +let nameTransliterator: i18n.Transliterator = i18n.Transliterator.getInstance('Han-Latin/Names'); +translatedText = nameTransliterator.transform('单老师'); // translatedText = 'shàn lǎo shī' +translatedText = nameTransliterator.transform('长孙无忌'); // translatedText = 'zhǎng sūn wú jì' // Obtain the list of IDs supported by the Transliterator object. -let ids = i18n.Transliterator.getAvailableIDs(); // ids: ['ASCII-Latin', 'Accents-Any', ...] +let ids: string[] = i18n.Transliterator.getAvailableIDs(); // ids = ['ASCII-Latin', 'Accents-Any', ...] ``` -### Character Normalization +### Text Normalization -Character normalization means to the standardize characters according to the specified paradigm. This function is implemented through the [normalize](../reference/apis-localization-kit/js-apis-i18n.md#normalize10) API of the **Normalizer** class. The development procedure is as follows: +Text normalization means to the normalize text according to the specified paradigm. You can implement this function by using the [normalize](../reference/apis-localization-kit/js-apis-i18n.md#normalize10) API of the **Normalizer** class. The development procedure is as follows: 1. Import the **i18n** module. ```ts import { i18n } from '@kit.LocalizationKit'; ``` -2. Create a **Normalizer** object. Pass in the text normalization paradigm to create a **Normalizer** object. The text normalization paradigm can be NFC, NFD, NFKC, or NFKD. For details, see [Unicode Normalization Forms](https://www.unicode.org/reports/tr15/#Norm_Forms). +2. Pass in the text normalization paradigm to create a **Normalizer** object. The text normalization paradigm can be NFC, NFD, NFKC, or NFKD. For details, see [Unicode Normalization Forms](https://www.unicode.org/reports/tr15/#Norm_Forms). ```ts let normalizer: i18n.Normalizer = i18n.Normalizer.getInstance(mode: NormalizerMode); ``` @@ -125,23 +122,22 @@ Character normalization means to the standardize characters according to the spe // Import the i18n module. import { i18n } from '@kit.LocalizationKit'; -// Normalize characters in the NFC form. -let normalizer = i18n.Normalizer.getInstance(i18n.NormalizerMode.NFC); -let normalizedText = normalizer.normalize('\u1E9B\u0323'); // normalizedText: \u1E9B\u0323 +// Normalize text according to the NFC paradigm. +let normalizer: i18n.Normalizer = i18n.Normalizer.getInstance(i18n.NormalizerMode.NFC); +let normalizedText: string = normalizer.normalize('\u1E9B\u0323'); // normalizedText = 'ẛ̣' ``` ### Line Wrapping -Line wrapping means to obtain the text break position based on the specified text boundary and wrap the line. It is implemented by using the APIs of the [BreakIterator](../reference/apis-localization-kit/js-apis-i18n.md#breakiterator8) class. The development procedure is as follows: +Line wrapping means to obtain the text break position based on the specified text boundary and wrap the line. You can implement this function by using APIs of the [BreakIterator](../reference/apis-localization-kit/js-apis-i18n.md#breakiterator8) class. The development procedure is as follows: 1. Import the **i18n** module. ```ts import { i18n } from '@kit.LocalizationKit'; ``` -2. Create a **BreakIterator** object. - Pass a valid locale to create a **BreakIterator** object. This object wraps lines based on the rules specified by the locale. +2. Create a **BreakIterator** object. Pass a valid locale to create a **BreakIterator** object. This object wraps lines based on the rules specified by the locale. ```ts let iterator: i18n.BreakIterator = i18n.getLineInstance(locale: string); @@ -157,8 +153,8 @@ Line wrapping means to obtain the text break position based on the specified tex ```ts let currentPos: number = iterator.current(); // Obtain the position of BreakIterator in the text. let firstPos: number = iterator.first(); // Set the position of BreakIterator as the first break point and return the position of the break point. The first break point is always at the beginning of the text, that is firstPos = 0. - let nextPos: number = iterator.next(number); // Move BreakIterator by the specified number of break points. If the number is a positive number, the iterator is moved backward. If the number is a negative number, the iterator is moved forward. The default value is 1. nextPos indicates the position after moving. If BreakIterator is moved out of the text length range, -1 is returned. - let isBoundary: boolean = iterator.isBoundary(number); // Check whether the position indicated by the specified number is a break point. + let nextPos: number = iterator.next(index?: number); // Move BreakIterator by the specified number of break points. If the number is a positive number, the iterator is moved backward. If the number is a negative number, the iterator is moved forward. The default value is 1. nextPos indicates the position after moving. If BreakIterator is moved out of the text length range, -1 is returned. + let isBoundary: boolean = iterator.isBoundary(offset: number); // Check whether the position indicated by the specified number is a break point. ``` @@ -168,45 +164,37 @@ Line wrapping means to obtain the text break position based on the specified tex import { i18n } from '@kit.LocalizationKit'; // Create a BreakIterator object. -let iterator = i18n.getLineInstance('en-GB'); +let iterator: i18n.BreakIterator = i18n.getLineInstance('en-GB'); // Set the text to be processed. iterator.setLineBreakText('Apple is my favorite fruit.'); // Move BreakIterator to the beginning of the text. -let firstPos = iterator.first(); // firstPos: 0 +let firstPos: number = iterator.first(); // firstPos = 0 // Move BreakIterator by several break points. -let nextPos = iterator.next(2); // nextPos: 9 +let nextPos: number = iterator.next(2); // nextPos = 9 // Check whether a position is a break point. -let isBoundary = iterator.isBoundary(9); // isBoundary: true +let isBoundary: boolean = iterator.isBoundary(9); // isBoundary = true // Obtain the text processed by BreakIterator. -let breakText = iterator.getLineBreakText(); // breakText: Apple is my favorite fruit. +let breakText: string = iterator.getLineBreakText(); // breakText = 'Apple is my favorite fruit.' ``` ### Performs file path mirroring. -File path mirroring means to localize the input file paths. This function is implemented through the [getUnicodeWrappedFilePath](../reference/apis-localization-kit/js-apis-i18n.md#getunicodewrappedfilepath16) API of the **I18NUtil** class. The development procedure is as follows: +File path mirroring is a process of localizing the input file path directions. It is performed when **mirrorPath** is passed. You can implement this function by using the [getUnicodeWrappedFilePath](../reference/apis-localization-kit/js-apis-i18n.md#getunicodewrappedfilepath18) API of the **I18NUtil** class. The development procedure is as follows: -1. Import the **i18n** and **intl** modules. -```ts - import { BusinessError } from '@kit.BasicServicesKit'; +1. Import the **i18n** module. + ```ts import { i18n, intl } from '@kit.LocalizationKit'; -``` + ``` -2. Call the file path mirroring API. -```ts - try { - let path: string = "/data/out/tmp"; // Define a path. - let delimiter: string = "/"; // Define the path delimiter. - let locale: intl.Locale = new intl.Locale ("ar"); // Define the locale object. - let mirrorPath : string = i18n.I18NUtil.getUnicodeWrappedFilePath(path, delimiter, locale); // Call the API. - } catch (error) { - console.error(`call I18NUtil.getUnicodeWrappedFilePath failed, error code: ${error.code}, message: ${error.message}.`); - } -``` +2. Perform file path mirroring. + ```ts + let mirrorPath: string = i18n.I18NUtil.getUnicodeWrappedFilePath(path: string, delimiter?: string, locale?: intl.Locale); + ``` **Development Example** @@ -216,18 +204,21 @@ import { BusinessError } from '@kit.BasicServicesKit'; import { i18n, intl } from '@kit.LocalizationKit'; try { - // Perform file path mirroring if mirrorPath is passed. - let path : string = "/data/out/tmp"; - let delimiter : string = "/"; - let locale : intl.Locale = new intl.Locale("ar"); - let mirrorPath : string = i18n.I18NUtil.getUnicodeWrappedFilePath(path, delimiter, locale); // mirrorPath: tmp/out/data/ - - // Skip file path mirroring if unMirrorPath is passed. - let localeZh : intl.Locale = new intl.Locale("zh"); - let unMirrorPath : string = i18n.I18NUtil.getUnicodeWrappedFilePath(path, delimiter, localeZh); // unMirrorPath: /data/out/tmp + // Perform file path mirroring if mirrorPath is passed. + let path: string = 'data/out/tmp'; + let delimiter: string = '/'; + let locale: intl.Locale = new intl.Locale('ar'); + // mirrorPath = 'tmp/out/data/' + let mirrorPath: string = i18n.I18NUtil.getUnicodeWrappedFilePath(path, delimiter, locale); + + // Skip file path mirroring if unMirrorPath is passed. + let localeZh: intl.Locale = new intl.Locale('zh'); + // unMirrorPath = '/data/out/tmp' + let unMirrorPath: string = i18n.I18NUtil.getUnicodeWrappedFilePath(path, delimiter, localeZh); } catch (error) { - console.error(`call I18NUtil.getUnicodeWrappedFilePath failed, error code: ${error.code}, message: ${error.message}.`); + console.error(`call I18NUtil.getUnicodeWrappedFilePath failed, error code: ${error.code}, message: ${error.message}.`); } ``` + \ No newline at end of file diff --git a/en/application-dev/internationalization/i18n-dst-transition.md b/en/application-dev/internationalization/i18n-dst-transition.md index ef88c83f8d8e23bd5b72d055f166eede25f9773b..493048fbf17537349648a8a3caf137a33d6aba50 100644 --- a/en/application-dev/internationalization/i18n-dst-transition.md +++ b/en/application-dev/internationalization/i18n-dst-transition.md @@ -8,7 +8,7 @@ DST is a local time system that sees manual adjustment to the time with the aim ## How It Works -When the local time reaches the DST transition point, DST transition is automatically implemented based on the DST transition rules configured in the system. If an application uses a common TS API, for example, **Date()**, to obtain and display the time, it also displays the DST time when the DST transition time is reached. +When the local time reaches the DST transition point, DST transition is automatically implemented based on the DST transition rules configured in the system. If an application uses a standard TS API, for example, `Date()`, to obtain and display the time, it also displays the DST time when the DST transition time is reached. The DST transition rules are as follows: @@ -19,23 +19,23 @@ The DST transition rules are as follows: ```ts import { i18n } from '@kit.LocalizationKit'; - let calendar = i18n.getCalendar("zh-Hans"); - calendar.setTimeZone("Europe/London"); - calendar.set(2021, 2, 27, 16, 0, 0); //The day before daylight saving time start - let time1 = calendar.getTimeInMillis(); - calendar.set(2021, 2, 28, 16, 0, 0); //The day daylight saving time start - let time2 = calendar.getTimeInMillis(); - let hours = (time2 - time1)/(3600*1000) //The hours between the same wall clock time before and after DST. Should be 23 + let calendar: i18n.Calendar = i18n.getCalendar('zh-Hans'); + calendar.setTimeZone('Europe/London'); + calendar.set (2021, 2, 27, 16, 0, 0); // Time before the DST starts + let startTime: number = calendar.getTimeInMillis(); + calendar.set (2021, 2, 28, 16, 0, 0); // Time in the DST period + let finishTime: number = calendar.getTimeInMillis(); + let hours: number = (finishTime - startTime) / (3600 * 1000); // hours = 23 ``` 2. Store and display time data. Store and display time data according to the local DST timing rules. The time gap and repetition caused by DST transition need to be processed. - When DST starts, one hour is missing, for example, 1:59:59→3:00:00. When DST ends, one hour is repeated, for example, 3:59:59→3:00:00. + The transition into DST will cause a one-hour gap, for example, shifting from 1:59:59 to 3:00:00. The transition out of DST will cause a one-hour overlap, for example, rollback from 3:59:59 to 3:00:00. It is recommended that the DST flag be added to the local time when DST is active. - ![DST flag](figures/dst-transition.png) + ![DST flag](figures/dst-flag.png) 3. Store and transmit time data. You are advised to use the standard time (UTC or GMT) of time zone 0 for time data storage and transmission. This helps prevent data loss or errors caused by DST transition. diff --git a/en/application-dev/internationalization/i18n-l10n.md b/en/application-dev/internationalization/i18n-l10n.md index cded31513b6ed43003631900da68e33aea3b751d..47bed70a0ef968ba0dad54593b60301021b8b421 100644 --- a/en/application-dev/internationalization/i18n-l10n.md +++ b/en/application-dev/internationalization/i18n-l10n.md @@ -1,4 +1,4 @@ -# Introduction to Localization Kit +# Overview of Internationalization and Localization Users in different locales have different cultural backgrounds and speak different languages. Therefore, if your application is to be released for use in different locales, you must consider the language and cultural differences in different locales. Internationalization and localization can have your application UI displayed in line with local user habits. The improved user experience, in turn, will help your application to extend its reach to potential markets. @@ -7,7 +7,9 @@ Users in different locales have different cultural backgrounds and speak differe Internationalization (known as i18n) is a set of multilingual and multicultural capabilities, including locale-specific features as well as time zone and DST features. Where, locale-specific features provide access to setting the date and time, numbers and units of measurement, phone numbers, calendars, and languages of different locales, while the time zone and DST features provide access to obtaining the time zone and DST transition. Internationalization usually happens in the application design and development phase. It employs a universal design without specifying a dedicated language. -To help applications adapt to different markets, internationalization provides some general guidelines for application development. For example, DO NOT assume user cultures and habits. Specifically, do not assume commas as number group separators in all locales and hard code commas as the number group separators in the application code. Another example is to separate UI elements (such as images and character strings) from the code logic as application resources. To launch an application in certain locales, you just need to have the corresponding resources translated into the target language. This helps avoid code modification, eliminating the need for application redesign and development. +To help applications adapt to different markets, internationalization provides some general guidelines for application development, for example: +- DO NOT assume user cultures and habits. Specifically, do not assume commas as number group separators in all locales and hard code commas as the number group separators in the application code. +- Separate UI elements (such as images and character strings) from the code logic as application resources. To release an application in certain locales, you just need to have the corresponding resources translated into the target language. This helps avoid code modification, eliminating the need for application redesign and development. Localization (known as l10n) happens in the application customization phase. It is a process of translating and localizing application resources to meet users' language and cultural requirements in dedicated locales. It fulfills the needs for multilingual resource configuration, including resource translation, taboo check, and localization testing. diff --git a/en/application-dev/internationalization/i18n-language-region-display.md b/en/application-dev/internationalization/i18n-language-region-display.md index 6dfb870fb09cd52ef59578a487452ec058bbb84f..fbfd30fa34f0dec5c7556a2a764b159f2c393253 100644 --- a/en/application-dev/internationalization/i18n-language-region-display.md +++ b/en/application-dev/internationalization/i18n-language-region-display.md @@ -3,7 +3,7 @@ ## Use Cases -Language and locale name localization means to localize language and locale names on the UI based on local language habits. For example, in an English environment, Simplified Chinese is represented by 简体中文. +Language and locale name localization means to localize language and locale names on the UI based on local language habits. For example, Simplified Chinese and English are used in an English environment while 简体中文 and 英文 are used in a Chinese environment. ## How to Develop @@ -16,18 +16,18 @@ For details about the APIs, see [getDisplayCountry](../reference/apis-localizati ``` 2. Localize language names. - When providing language names for a user, for example, when a user switches the system language, the system displays the localized language names. The following uses provides an example of displaying German in a way similar to Chinese. + In scenarios where language names are provided for users, for example, switching of the system language, the system displays the localized language names to users. The following provides an example of displaying German in a way similar to Chinese. ```ts - let displayLanguage = i18n.System.getDisplayLanguage("de", "zh-Hans-CN"); // German + let displayLanguage: string = i18n.System.getDisplayLanguage('de', 'zh-Hans-CN'); // displayLanguage = 'German' // language: two-letter language code, for example, zh, de, or fr. // locale: localization identifier, for example, en-GB, en-US, or zh-Hans-CN. // sentenceCase: whether the first letter of the language name needs to be capitalized. The default value is true. ``` 3. Localize country/region names. - When providing country/region names for a user, for example, when a user switches the country/region, the system displays the localized country/region names. + In scenarios where country/region names are provided for users, for example, switching of the system locale, the system displays the localized country/region names to users. The following uses Saudi Arabia as an example. ```ts - let displayCountry = i18n.System.getDisplayCountry("SA", "en-GB"); // Saudi Arabia + let displayCountry: string = i18n.System.getDisplayCountry('SA', 'en-GB'); // displayCountry = 'Saudi Arabia' // country: two-letter country/region code, for example, CN, DE, or SA. // locale: localization identifier, for example, en-GB, en-US, or zh-Hans-CN. // sentenceCase: whether the first letter of the country/region name needs to be capitalized. The default value is true. diff --git a/en/application-dev/internationalization/i18n-locale-culture.md b/en/application-dev/internationalization/i18n-locale-culture.md index 5471b76c2c1d621e0ba08eba6e70bbda19220aa4..3055652a9c30639be879785c0ac69c7b317c01ff 100644 --- a/en/application-dev/internationalization/i18n-locale-culture.md +++ b/en/application-dev/internationalization/i18n-locale-culture.md @@ -49,44 +49,43 @@ A locale consists of four parts: language, script, country/region, and extended ## How to Develop -The following uses date and time formatting as an example. For details about APIs, see [getPluralStringValueSync](../reference/apis-localization-kit/js-apis-resource-manager.md#getpluralstringvaluesync10). +The following uses date and time formatting as an example. For details about APIs, see [DateTimeFormat](../reference/apis-localization-kit/js-apis-intl.md#datetimeformat). 1. Import the **intl** module. ```ts import { intl } from '@kit.LocalizationKit'; ``` -2. Create a **Locale** object. Three methods are provided: +2. Create a **Locale** object using any of the following methods: - According to the format provided in [How It Works](#how-it-works), pass in the locale string to the **Locale** constructor to create a **Locale** object. - Configure locale features in **LocaleOptions**, and then use the locale string and **LocaleOptions** to create a **Locale** object. The attributes configured in **LocaleOptions** automatically overwrite the corresponding attributes in the locale string. - Use the default **Locale** constructor to create a **Locale** object. This object will be used to represent the current system locale. ```ts - let date = new Date(2023, 9, 15); - - // Method 1: Create a Locale object using the locale string. - let zhLocale = new intl.Locale("zh-Hans-CN-u-nu-latn"); - + let zhLocale: intl.Locale = new intl.Locale('zh-Hans-CN-u-nu-latn'); + // Method 2: Create a Locale object using the locale string and LocaleOptions. - let enLocale = new intl.Locale("en", {numberingSystem: "latn"}); - + let enLocale: intl.Locale = new intl.Locale('en', { numberingSystem: 'latn' }); + // Method 3: Create a Locale object using the default Locale constructor. - let systemLocale = new intl.Locale(); + let systemLocale: intl.Locale = new intl.Locale(); ``` 3. Format the date and time. Pass the **Locale** object to the **DateTimeFormat** constructor to create a **DateTimeFormat** class to implement date and time formatting for the locale. Similarly, three methods are provided. ```ts + let date: Date = new Date(2023, 9, 15); + // Method 1 - let zhDateTimeFmt = new intl.DateTimeFormat(zhLocale.toString()); - let result = zhDateTimeFmt.format(date); // result = "2023/10/15" - + let zhDateTimeFmt: intl.DateTimeFormat = new intl.DateTimeFormat(zhLocale.toString()); + let formattedResult: string = zhDateTimeFmt.format(date); // formattedResult = '2023/10/15' + // Method 2 - let enDateTimeFmt = new intl.DateTimeFormat(enLocale.toString()); - result = enDateTimeFmt.format(date); // result = "10/15/23" - + let enDateTimeFmt: intl.DateTimeFormat = new intl.DateTimeFormat(enLocale.toString()); + formattedResult = enDateTimeFmt.format(date); // formattedResult = '10/15/23' + // Method 3 - let systemDateTimeFmt = new intl.DateTimeFormat(systemLocale.toString()); - result = systemDateTimeFmt.format(date); // result = "2023/10/15" (The display effect depends on the current system environment.) + let systemDateTimeFmt: intl.DateTimeFormat = new intl.DateTimeFormat(systemLocale.toString()); + formattedResult = systemDateTimeFmt.format(date); // formattedResult = "2023/10/15" (The display effect is subject to the system environment.) ``` diff --git a/en/application-dev/internationalization/i18n-numbers-weights-measures.md b/en/application-dev/internationalization/i18n-numbers-weights-measures.md index 486ccf65c17957121c54bbde959eac6db01f48cc..507dbfeee059f59b367f218e7f5d83f6f897155a 100644 --- a/en/application-dev/internationalization/i18n-numbers-weights-measures.md +++ b/en/application-dev/internationalization/i18n-numbers-weights-measures.md @@ -2,7 +2,7 @@ ## Use Cases -In different countries and cultures, numbers, currencies, and units of measurement are expressed in different ways, including what symbols are used as decimal separators, how many digits are displayed after separators, and what currencies and units of measurement are used. Suppose you want to display the number 1000 on the application UI to indicate the price of a product. If the fixed format **1,000** is used, it may be considered as **1** in some European countries where a comma is used as a decimal point. Formatting is therefore needed to ensure that numbers, currencies, and units of measurement are displayed on the application UI in line with local user habits. +In different countries and cultures, numbers, currencies, and units of measurement are expressed in different ways, including what symbols are used as decimal separators, how many digits are displayed after separators, and what currencies and units of measurement are used. Suppose you want to display the number 1000 on the application UI to indicate the price of a product. If the fixed format **1,000** is used, it may be considered as 1 in some European countries where a comma is used as a decimal point. Formatting is therefore needed to format numbers, currencies, and units of measurement so that they are displayed on the application UI in line with local user habits. ## How to Develop @@ -35,7 +35,7 @@ Number formatting is implemented through the [format](../reference/apis-localiza **Number Formatting Options** -You can use [NumberOptions](../reference/apis-localization-kit/js-apis-intl.md#numberoptions) to configure number formatting options, including minimum number of integer digits, minimum and maximum numbers of fraction digits, minimum and maximum numbers of significant digits, use of grouping for display, number notation, compact display, rounding mode, rounding priority, rounding increment, number display format, and numbering system. Supported number display formats include decimal, percent, currency, and unit. +You can use [NumberOptions](../reference/apis-localization-kit/js-apis-intl.md#numberoptions) to configure number formatting options, including minimum number of integer digits, minimum and maximum numbers of fraction digits, minimum and maximum numbers of significant digits, use of grouping for display, number notation, compact display, rounding mode, rounding priority, rounding increment, number display format, and numeral system. Supported number display formats include decimal, percent, currency, and unit. The following uses **123000.123** as an example to show the parameter values and corresponding display effects. @@ -105,49 +105,57 @@ The following uses **123000.123** as an example to show the parameter values and import { intl } from '@kit.LocalizationKit'; // Display numbers in scientific notation. -let numberFormat1 = new intl.NumberFormat('zh-CN', {notation: 'scientific', maximumSignificantDigits: 3}); -let formattedNumber1 = numberFormat1.format(123400); // formattedNumber1: 1.23E5 +let scientificFormat: intl.NumberFormat = new intl.NumberFormat('zh-CN', + { + notation: 'scientific', + maximumSignificantDigits: 3 + }); +let formattedNumber: string = scientificFormat.format(123400); // formattedNumber = '1.23E5' // Display numbers in the compact format. -let numberFormat2 = new intl.NumberFormat('zh-CN', {notation: 'compact', compactDisplay: 'short'}); -let formattedNumber2 = numberFormat2.format(123400); // formattedNumber2: 120 thousand +let compactFormat: intl.NumberFormat = new intl.NumberFormat('zh-CN', + { + notation: 'compact', + compactDisplay: 'short' + }); +formattedNumber = compactFormat.format(123400); // formattedNumber = '12万)' // Display the signs in numbers. -let numberFormat3 = new intl.NumberFormat('zh-CN', {signDisplay: 'always'}); -let formattedNumber3 = numberFormat3.format(123400); // formattedNumber3: +123,400 +let signFormat: intl.NumberFormat = new intl.NumberFormat('zh-CN', { signDisplay: 'always' }); +formattedNumber = signFormat.format(123400); // formattedNumber = '+123,400' // Display numbers in the percentage format. -let numberFormat4 = new intl.NumberFormat('zh-CN', {style: 'percent'}); -let formattedNumber4 = numberFormat4.format(0.25); // formattedNumber4: 25% +let percentFormat: intl.NumberFormat = new intl.NumberFormat('zh-CN', { style: 'percent' }); +formattedNumber = percentFormat.format(0.25); // formattedNumber = '25%' // Rounding mode -let numberFormat5 : intl.NumberFormat = new intl.NumberFormat('en', - { - roundingMode: 'trunc', - maximumSignificantDigits: 2 - }); -console.log(numberFormat5.format(2.28)); // 2.2 -console.log(numberFormat5.format(-2.25)); // -2.2 +let truncFormat: intl.NumberFormat = new intl.NumberFormat('en', + { + roundingMode: 'trunc', + maximumSignificantDigits: 2 + }); +formattedNumber = truncFormat.format(2.28); // formattedNumber = '2.2' +formattedNumber = truncFormat.format(-2.25); // formattedNumber = '-2.2' // Rounding priority -let options : intl.NumberOptions = { - roundingPriority: 'lessPrecision', - maximumFractionDigits: 3, - maximumSignificantDigits: 2 +let lessPrecisionOptions: intl.NumberOptions = { + roundingPriority: 'lessPrecision', + maximumFractionDigits: 3, + maximumSignificantDigits: 2 }; -let numberFormat6 : intl.NumberFormat = new intl.NumberFormat('en', options); -console.log(numberFormat6.format(1.23456)); // 1.2 +let lessPrecisionFormat: intl.NumberFormat = new intl.NumberFormat('en', lessPrecisionOptions); +formattedNumber = lessPrecisionFormat.format(1.23456); // formattedNumber = '1.2' // Rounding increment -let numOptions : intl.NumberOptions = { - style: "currency", - currency: "USD", - roundingIncrement: 5, - maximumFractionDigits: 2, - roundingMode: "halfCeil" +let halfCeilNumOptions: intl.NumberOptions = { + style: 'currency', + currency: 'USD', + roundingIncrement: 5, + maximumFractionDigits: 2, + roundingMode: 'halfCeil' }; -let numberFormat7 : intl.NumberFormat = new intl.NumberFormat('en-US', numOptions); -console.log(numberFormat7.format(11.21)); // $11.20 +let halfCeilFormat: intl.NumberFormat = new intl.NumberFormat('en-US', halfCeilNumOptions); +formattedNumber = halfCeilFormat.format(11.21); // formattedNumber = '$11.20' ``` ### Number Range Formatting @@ -179,20 +187,20 @@ Number range formatting is implemented through the [formatRange](../reference/ap import { intl } from '@kit.LocalizationKit'; // Number range formatting -let options : intl.NumberOptions = { - style: "currency", - currency: "EUR", - maximumFractionDigits: 0 +let options: intl.NumberOptions = { + style: 'currency', + currency: 'EUR', + maximumFractionDigits: 0 }; -let numberRangeFormat : intl.NumberFormat = new intl.NumberFormat('es-ES', options); -console.log(numberRangeFormat.formatRange(2, 8)); // 2-8 € -console.log(numberRangeFormat.formatRange(2.9, 3.1)); // ~3 € +let numberRangeFormat: intl.NumberFormat = new intl.NumberFormat('es-ES', options); +let formattedRange: string = numberRangeFormat.formatRange(2, 8); // formattedRange = '2-8 €' +formattedRange = numberRangeFormat.formatRange(2.9, 3.1); // formattedRange = '~3 €' ``` ### Currency and Unit Formatting -Currency and unit formatting is based on number formatting. When creating a **NumberFormat** object for currency and unit formatting, set the number formatting style to currency and unit, respectively. Similarly, this can be done through [NumberOptions](../reference/apis-localization-kit/js-apis-intl.md#numberoptions). The following tables show the parameter values and corresponding display effects. +Currency and unit formatting is based on number formatting. When creating a **NumberFormat** object for currency and unit formatting, set the number formatting style to **currency** and **unit**, respectively. Similarly, this can be done through [NumberOptions](../reference/apis-localization-kit/js-apis-intl.md#numberoptions). The following tables show the parameter values and corresponding display effects. **Currency Formatting Options** @@ -216,7 +224,7 @@ Assume that the currency unit is USD and the value is **-12300**. **Unit Formatting Options** -Assume that the unit name is hectare and the value is **-12300**. +Assume that the unit name is **hectare** and the value is **-12300**. **Table 11** Unit display (unitDisplay) @@ -230,7 +238,7 @@ Assume that the unit name is hectare and the value is **-12300**. | Value| Display Effect| | -------- | -------- | -| Left unspecified| -12,300 ha | +| Unspecified| -12,300 ha | | default | -47.491 sq mi | | area-land-agricult | -30,393.962 ac | @@ -241,20 +249,30 @@ Assume that the unit name is hectare and the value is **-12300**. import { intl } from '@kit.LocalizationKit'; // Format the currency. -let numberFormat5 = new intl.NumberFormat('zh-CN', {style: 'currency', currency: 'USD'}); -let formattedNumber5 = numberFormat5.format(123400); // formattedNumber5: US$123,400.00 +let currencyFormat: intl.NumberFormat = new intl.NumberFormat('zh-CN', { style: 'currency', currency: 'USD' }); +let formattedNumber: string = currencyFormat.format(123400); // formattedNumber = 'US$123,400.00' // Display the currency using its name. -let numberFormat6 = new intl.NumberFormat('zh-CN', {style: 'currency', currency: 'USD', currencyDisplay: 'name'}); -US$ let formattedNumber6 = numberFormat6.format(123400); // formattedNumber6: US$123,400.00 +let currencyNameFormat: intl.NumberFormat = new intl.NumberFormat('zh-CN', + { + style: 'currency', + currency: 'USD', + currencyDisplay: 'name' + }); +formattedNumber = currencyNameFormat.format(123400); // formattedNumber = '123,400.00美元' // Format units of measurement. -let numberFormat7 = new intl.NumberFormat('en-GB', {style: 'unit', unit: 'hectare'}); -let formattedNumber7 = numberFormat7.format(123400); // formattedNumber7: 123,400 ha +let unitFormat: intl.NumberFormat = new intl.NumberFormat('en-GB', { style: 'unit', unit: 'hectare' }); +formattedNumber = unitFormat.format(123400); // formattedNumber = '123,400 ha' // Format the units of measurement in the specified scenario, for example, area-land-agricult. -let numberFormat8 = new intl.NumberFormat('en-GB', {style: 'unit', unit: 'hectare', unitUsage: 'area-land-agricult'}); -let formattedNumber8 = numberFormat8.format(123400); // formattedNumber8: 304,928.041 ac +let unitUsageFormat: intl.NumberFormat = new intl.NumberFormat('en-GB', + { + style: 'unit', + unit: 'hectare', + unitUsage: 'area-land-agricult' + }); +formattedNumber = unitUsageFormat.format(123400); // formattedNumber = '304,928.041 ac' ``` @@ -262,12 +280,12 @@ let formattedNumber8 = numberFormat8.format(123400); // formattedNumber8: 304,92 Units of measurement conversion and formatting are implemented by the [unitConvert](../reference/apis-localization-kit/js-apis-i18n.md#unitconvert9) API of the [I18NUtil](../reference/apis-localization-kit/js-apis-i18n.md#i18nutil9) class. The development procedure is as follows: -1. Import the **i18n** module. +1. Import the **intl** module. ```ts import { i18n } from '@kit.LocalizationKit'; ``` -2. Convert the unit of measurement. +2. Change the unit of measurement. Convert the unit of measurement from **fromUnit** to **toUnit**, and format the unit based on the specified locale and formatting style. The display effect varies according to the style. For details, see Table 13. ```ts @@ -297,8 +315,9 @@ let fromUnit: i18n.UnitInfo = {unit: 'cup', measureSystem: 'US'}; let toUnit: i18n.UnitInfo = {unit: 'liter', measureSystem: 'SI'}; // Convert the unit based on the locale en-US. -let convertedUnit1 = i18n.I18NUtil.unitConvert(fromUnit, toUnit, 1000, 'en-US'); // convertedUnit1: 236.588 L +let convertedUnit: string = i18n.I18NUtil.unitConvert(fromUnit, toUnit, 1000, 'en-US'); // convertedUnit = '236.588 L' // Display the complete unit. -let convertedUnit2 = i18n.I18NUtil.unitConvert(fromUnit, toUnit, 1000, 'en-US', 'long'); // convertedUnit2: 236.588 liters +convertedUnit = i18n.I18NUtil.unitConvert(fromUnit, toUnit, 1000, 'en-US', 'long'); // convertedUnit = '236.588 liters' ``` + \ No newline at end of file diff --git a/en/application-dev/internationalization/i18n-phone-numbers.md b/en/application-dev/internationalization/i18n-phone-numbers.md index 1f60e46c3feb404dae6f65cfad28a7748b600921..0c04c6fa01901c495d6757aa6e2cdfd8a814b0b2 100644 --- a/en/application-dev/internationalization/i18n-phone-numbers.md +++ b/en/application-dev/internationalization/i18n-phone-numbers.md @@ -56,28 +56,25 @@ The following uses the phone number **158\*\*\*\*2312** and the country code **C import { i18n } from '@kit.LocalizationKit'; // Format the phone number. -let phoneNumberFormat1 = new i18n.PhoneNumberFormat('CN'); -let formattedPhoneNumber1 = phoneNumberFormat1.format('158****2312'); // formattedPhoneNumber1: 158 **** 2312 +let phoneNumberFormat: i18n.PhoneNumberFormat = new i18n.PhoneNumberFormat('CN'); +let formattedPhoneNumber: string = phoneNumberFormat.format('158****2312'); // formattedPhoneNumber = '158 **** 2312' // Set the format type of the phone number to RFC3966. -let phoneNumberFormat2 = new i18n.PhoneNumberFormat('CN', {type: 'RFC3966'}); -let formattedPhoneNumber2 = phoneNumberFormat2.format('158****2312'); // formattedPhoneNumber2: tel:+86-158-****-2312 +let RFC3966Format: i18n.PhoneNumberFormat = new i18n.PhoneNumberFormat('CN', { type: 'RFC3966' }); +formattedPhoneNumber = RFC3966Format.format('158****2312'); // formattedPhoneNumber = 'tel:+86-158-****-2312' // Check whether the phone number is valid. -let phoneNumberFormat3 = new i18n.PhoneNumberFormat('CN'); -let isValid = phoneNumberFormat3.isValidNumber('158****2312'); // isValid: true +let isValid: boolean = phoneNumberFormat.isValidNumber('158****2312'); // isValid = true // Display the home area of the phone number in the specified language. -let phoneNumberFormat4 = new i18n.PhoneNumberFormat("CN"); -let locationName4 = phoneNumberFormat4.getLocationName('158****2312', 'en-GB') // locationName4: XiAn, Shanxi +let locationName: string = phoneNumberFormat.getLocationName('158****2312', 'en-GB'); // locationName = 'XiAn, Shanxi' // Format the phone number being dialed. -let phoneNumberFmt = new i18n.PhoneNumberFormat('CN', {type: 'TYPING'}); -let phoneNumber : string = "0755453"; -let formatResult : string = ""; +let typingFormat: i18n.PhoneNumberFormat = new i18n.PhoneNumberFormat('CN', { type: 'TYPING' }); +let phoneNumber: string = '0755453'; +let formatResult: string = ''; // Format the dialed number as follows: formatResult = '0755 453' for (let i = 0; i < phoneNumber.length; i++) { formatResult += phoneNumber.charAt(i); - formatResult = phoneNumberFmt.format(formatResult); + formatResult = typingFormat.format(formatResult); } -console.log(formatResult); // formatResult: 0755 453 ``` diff --git a/en/application-dev/internationalization/i18n-preferred-language.md b/en/application-dev/internationalization/i18n-preferred-language.md index 124878a3683fe9797a139e228abb8597aba318f8..fc3cc87c0104f6ba001af9c7eeecbeee372ac458 100644 --- a/en/application-dev/internationalization/i18n-preferred-language.md +++ b/en/application-dev/internationalization/i18n-preferred-language.md @@ -2,14 +2,12 @@ ## Use Cases -In most cases, multi-language users may set the system language to one language (for example, Chinese) and the language of a specific application to another language (for example, English). When application resources are loaded on the UI, it is expected that the resources be displayed in the language set for the application. To address this issue, you can set a preferred language in locale settings so that resources are loaded in the preferred language when the application is launched. Currently, only one preferred language can be set for an application. +Multi-language users usually set the system language to one language (for example, Chinese) and the language of a specific application to another language (for example, English). When application resources are loaded on the UI, it is expected that the resources be displayed in the language set for the application. To address this issue, you can set a preferred language in locale settings so that resources are loaded in the preferred language when the application is launched. Currently, only one preferred language can be set for an application. ## How to Develop For details about how to use related APIs, see [getAppPreferredLanguage](../reference/apis-localization-kit/js-apis-i18n.md#getapppreferredlanguage9). -The following uses date and time formatting as an example to illustrate how the preferred language works. - 1. Import the **i18n** and **intl** modules. ```ts import { i18n } from '@kit.LocalizationKit'; @@ -18,25 +16,25 @@ The following uses date and time formatting as an example to illustrate how the 2. Obtain the preferred language of the application. ```ts - let appPreferredLanguage: string = i18n.System.getAppPreferredLanguage(); // Obtain the preferred language of the application. + let appPreferredLanguage: string = i18n.System.getAppPreferredLanguage(); // Obtain the preferred language of the application. ``` -3. Set the preferred language of the application. After the preferred language of the application is set to the target language, the application UI is switched to the target language. The setting affects only the application, but not the system language settings. +3. Set the preferred language of the application. After the preferred language of the application is set to the target language, the application UI is switched to the target language. The setting is subject only to the application. It does not affect the system language settings. ```ts - try { - i18n.System.setAppPreferredLanguage("zh-Hans"); // Set the preferred language of the application to zh-Hans. - } catch(error) { - let err: BusinessError = error as BusinessError; - console.error(`call System.setAppPreferredLanguage failed, error code: ${err.code}, message: ${err.message}.`); - } + try { + i18n.System.setAppPreferredLanguage('zh-Hans'); // Set the preferred language of the application to zh-Hans. + } catch (error) { + let err: BusinessError = error as BusinessError; + console.error(`call System.setAppPreferredLanguage failed, error code: ${err.code}, message: ${err.message}.`); + } ``` 4. Clear the preferred language of the application. If the preferred language is set to **default**, the application's language will be the same as the system language, and the setting will take effect upon application restarting. ```ts - try { - i18n.System.setAppPreferredLanguage ("default"); // Clear the preferred language of the application. - } catch(error) { - let err: BusinessError = error as BusinessError; - console.error(`call System.setAppPreferredLanguage failed, error code: ${err.code}, message: ${err.message}.`); - } + try { + i18n.System.setAppPreferredLanguage ('default'); // Clear the preferred language of the application. + } catch(error) { + let err: BusinessError = error as BusinessError; + console.error(`call System.setAppPreferredLanguage failed, error code: ${err.code}, message: ${err.message}.`); + } ``` diff --git a/en/application-dev/internationalization/i18n-sorting-index.md b/en/application-dev/internationalization/i18n-sorting-index.md index c681bc5b1c4f668080e966302a00b28c8e3e032f..90bac009276185face94e16d26cfac20e4aaf89b 100644 --- a/en/application-dev/internationalization/i18n-sorting-index.md +++ b/en/application-dev/internationalization/i18n-sorting-index.md @@ -15,12 +15,17 @@ For details about how to use related APIs, see [IndexUtil](../reference/apis-loc 2. Create an **IndexUtil** object. ```ts - let indexUtil = i18n.getInstance(locale?:string); // The default value of locale is the current system locale. + let indexUtil: i18n.IndexUtil = i18n.getInstance(locale?: string); // The default value of locale is the current system locale. ``` 3. Obtain the index list. ```ts - let indexList = indexUtil.getIndexList(); + let indexList: Array = indexUtil.getIndexList(); + ``` + +4. Obtain the index. + ```ts + let index: string = indexUtil.getIndex(text: string); ``` **Development Example** @@ -28,11 +33,16 @@ For details about how to use related APIs, see [IndexUtil](../reference/apis-loc ```ts // Import the i18n module. import { i18n } from '@kit.LocalizationKit'; + // Create indexes in a single language. -let indexUtil = i18n.getInstance("zh-CN"); -let indexList = indexUtil.getIndexList(); // ["...", "A", "B", "C", "D", "E" ... "X", "Y", "Z", "..."] +let indexUtil: i18n.IndexUtil = i18n.getInstance('zh-CN'); +let indexList: Array = indexUtil.getIndexList(); // indexList = ['...', 'A', 'B', 'C', ... 'X', 'Y', 'Z', '...'] + // Create indexes in multiple languages. -indexUtil.addLocale("ru-RU"); -indexList = indexUtil.getIndexList(); // …,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,…,А,Б,В,Г,Д,Е,Ж,З,И,Й,К,Л,М,Н,О,П,Р,С,Т,У,Ф,Х,Ц,Ч,Ш,Щ,Ы,Э,Ю,Я,... -indexUtil.getIndex ("Hello"); // Index H +indexUtil.addLocale('ru-RU'); +// indexList = ['...', 'A', 'B', 'C', ... 'X', 'Y', 'Z', '...', 'А', 'Б', 'В', ... 'Э', 'Ю', 'Я', '...'] +indexList = indexUtil.getIndexList(); + +// Obtain the index of the string. +let index: string = indexUtil.getIndex('Nihao'); // index = 'N' ``` diff --git a/en/application-dev/internationalization/i18n-sorting-local.md b/en/application-dev/internationalization/i18n-sorting-local.md index c35d9d8684ebbb50006c2483f6fddb37859c4bf6..5542924b3032b9b57be68d8a53facb862cf366c2 100644 --- a/en/application-dev/internationalization/i18n-sorting-local.md +++ b/en/application-dev/internationalization/i18n-sorting-local.md @@ -6,7 +6,7 @@ The sorting function allows list content, for example, the language list in **Se ## How to Develop -The sorting function is implemented by the [compare](../reference/apis-localization-kit/js-apis-intl.md#compare8) API of the [Collator](../reference/apis-localization-kit/js-apis-intl.md#collator8) class. The development procedure is as follows: +You can implement the sorting function by using the [compare](../reference/apis-localization-kit/js-apis-intl.md#compare8) API of the [Collator](../reference/apis-localization-kit/js-apis-intl.md#collator8) class. The development procedure is as follows: 1. Import the **intl** module. ```ts @@ -16,12 +16,12 @@ The sorting function is implemented by the [compare](../reference/apis-localizat 2. Create a **Collator** object. You can use **CollatorOptions** to set different sorting formats. For details, see Table 1. ```ts - let collator = new intl.Collator(locale: string | Array, options?: CollatorOptions); + let collator: intl.Collator = new intl.Collator(locale: string | Array, options?: CollatorOptions); ``` 3. Compare two strings. ```ts - let compareResult = collator.compare(first: string, second: string); + let compareResult: number = collator.compare(first: string, second: string); // If compareResult is a negative number, the first parameter is placed before the second parameter. // If compareResult is 0, the first and second parameters are not sorted in sequence. // If compareResult is a positive number, the first parameter is placed after the second parameter. @@ -37,17 +37,17 @@ The sorting function is implemented by the [compare](../reference/apis-localizat | | best fit | Exact matching.| | | usage | sort | Sorting.| | | | search | Search for matched strings.| | -| sensitivity | base | Compare different letters.| Example: a ≠ b, a = á, a = A| -| | accent | Compare different letters or accents.| Example: a ≠ b, a ≠ á, a = A| -| | case | Compare the capitalization of different letters or the same letter.| Example: a ≠ b, a = á, a = A| -| | variant | Compare different letters or accents, and other distinctive signs or capitalization.| Example: a ≠ b, a ≠ á, a ≠ A| -| ignorePunctuation | true | Ignore punctuation.| a,b = ab | -| | false | Not ignore punctuation.| a,b < ab | -| numeric | true | Sort by number.| 1 < 2 < 10 < 11 | -| | false | Not sort by number.| 1 < 10 < 11 < 2 | -| caseFirst | upper | Place uppercase letters in the front.| ab,aB, AB,Ab => AB < Ab < aB < ab | -| | lower | Place lowercase letters in the front.| ab,aB, AB,Ab => ab < aB < Ab < AB | -| | false | Not distinguish first letter capitalization.| ab,aB, AB,Ab => ab < aB < Ab < AB | +| sensitivity | base | Compare different letters.| 'a' ≠ 'b', 'a' = 'á', 'a' = 'A' | +| | accent | Compare different letters or accents.| 'a' ≠ 'b', 'a' ≠ 'á', 'a' = 'A' | +| | case | Compare the capitalization of different letters or the same letter.| 'a' ≠ 'b', 'a' = 'á', 'a' ≠ 'A' | +| | variant | Compare different letters or accents, and other distinctive signs or capitalization.| 'a' ≠ 'b', 'a' ≠ 'á', 'a' ≠ 'A' | +| ignorePunctuation | true | Ignore punctuation.| 'a,b' = 'ab' | +| | false | Not ignore punctuation.| 'a,b' < 'ab' | +| numeric | true | Sort by number.| '1' < '2' < '10' < '11' | +| | false | Not sort by number.| '1' < '10' < '11' < '2' | +| caseFirst | upper | Place uppercase letters in the front.| 'AB' < 'Ab' < 'aB' < 'ab' | +| | lower | Place lowercase letters in the front.| 'ab' < 'aB' < 'Ab' < 'AB' | +| | false | Not distinguish first letter capitalization.| 'ab' < 'aB' < 'Ab' < 'AB' | | collation | big5han | Pinyin sorting for Latin letters.| | | | compat | Compatibility sorting, only for Arabic.| | | | dict | Dictionary-style sorting, only for Singhalese.| | @@ -73,48 +73,44 @@ import { intl } from '@kit.LocalizationKit'; // Create a Collator object. let options: intl.CollatorOptions = { - localeMatcher: "lookup", - usage: "sort", - sensitivity: "case" // Case sensitive + localeMatcher: 'lookup', + usage: 'sort', + sensitivity: 'case' // Case sensitive }; -let collator = new intl.Collator("zh-CN", options); +let collator: intl.Collator = new intl.Collator('zh-CN', options); // Case-sensitive sorting -let array = ["app", "App", "Apple", "ANIMAL", "animal", "apple", "APPLE"]; -array.sort((a, b) => { - return collator.compare(a, b); +let array: Array = ['app', 'App', 'Apple', 'ANIMAL', 'animal', 'apple', 'APPLE']; +array.sort((a, b) => { // After sorting: array = ['animal', 'ANIMAL', 'app', 'App', 'apple', 'Apple', 'APPLE'] + return collator.compare(a, b); }) -console.log("result: ", array); // animal ANIMAL app App apple Apple APPLE // Pinyin sorting for Chinese -array = ["Pingguo", "Li", "Xiangjiao", "Shiliu", "Ganzhe", "Putao", "Juzi"]; -array.sort((a, b) => { - return collator.compare(a, b); +array = ['Pingguo', 'Li', 'Xiangjiao', 'Shiliu', 'Ganzhe', 'Putao', 'Juzi']; +array.sort((a, b) => { // After sorting: array = ['Ganzhe', 'Juzi', 'Li', 'Pingguo', 'Putao', 'Shiliu', 'Xiangjiao'] + return collator.compare(a, b); }) -console.log("result: ", array); // Ganzhe, Juzi, Li, Pingguo, Putao, Shiliu, Xiangjiao // Stroke sorting options = { - localeMatcher: "lookup", - usage: "sort", - collation: "stroke" + localeMatcher: 'lookup', + usage: 'sort', + collation: 'stroke' }; -collator = new intl.Collator("zh-CN", options); -array = ["苹果", "梨", "香蕉", "石榴", "甘蔗", "葡萄", "橘子"]; -array.sort((a, b) => { - return collator.compare(a, b); +let strokeCollator: intl.Collator = new intl.Collator('zh-CN', options); +array = ['Pingguo', 'Li', 'Xiangjiao', 'Shiliu', 'Ganzhe', 'Putao', 'Juzi']; +array.sort((a, b) => { // After sorting: array = ['Ganzhe', 'Shiliu', 'Pingguo', 'Xiangjiao', 'Li', 'Putao', 'Juzi'] + return strokeCollator.compare(a, b); }) -console.log("result: ", array); // 甘蔗,石榴,苹果,香蕉,梨,葡萄,橘子 // Search for the matched string. options = { - usage: "search", - sensitivity: "base" + usage: 'search', + sensitivity: 'base' }; -collator = new intl.Collator("tr", options); -let sourceArray = ['Türkiye', 'TüRkiye', 'salt', 'bright']; -let s = 'türkiye'; -let matches = sourceArray.filter(item => collator.compare(item, s) === 0); -console.log(matches.toString()); // Türkiye,TüRkiye +let searchCollator: intl.Collator = new intl.Collator('tr', options); +array = ['Türkiye', 'TüRkiye', 'salt', 'bright']; +let target: string = 'türkiye'; +// matches = ['Türkiye', 'TüRkiye'] +let matches: string[] = array.filter(item => searchCollator.compare(item, target) === 0); ``` - \ No newline at end of file diff --git a/en/application-dev/internationalization/i18n-sorting-overview.md b/en/application-dev/internationalization/i18n-sorting-overview.md index 361d85cbb4c23766bb65e79e85a5741cdb9dda4d..f4133abb08756513432964af0041c10e6a7425b8 100644 --- a/en/application-dev/internationalization/i18n-sorting-overview.md +++ b/en/application-dev/internationalization/i18n-sorting-overview.md @@ -1,5 +1,5 @@ # Overview of Multilingual Sorting -The sorting rules for characters may vary according to languages and cultures. The sorting function allows your application to apply different rules to sort content for users in different countries or regions and using different languages. Besides, it helps your application to output sorting results with semantic features, instead of sorting results simply based on alphabetic codes, to facilitate query and search. The function is common in many scenarios, for example, the language list, country/region list, and contact list. +The sorting rules for characters may vary according to languages and cultures. The sorting function allows your application to apply different sorting rules for users in different countries or regions and using different languages. Besides, it enables your application to output sorting results with semantic features, instead to facilitate query and search. The function is applicable in use cases such as language list, country/region list, and contact list. Currently, sorting can be implemented by [local habits](i18n-sorting-local.md) or [indexes](i18n-sorting-index.md). diff --git a/en/application-dev/internationalization/i18n-system-language-region.md b/en/application-dev/internationalization/i18n-system-language-region.md index ca19b028d1bbea8397f1a24700f53d9745c5154a..50be12f68dcd8bd18589144d277f4fd63bcfe28d 100644 --- a/en/application-dev/internationalization/i18n-system-language-region.md +++ b/en/application-dev/internationalization/i18n-system-language-region.md @@ -21,37 +21,37 @@ For details about how to use related APIs, see [System](../reference/apis-locali 2. Obtain the system language, region, and locale. ```ts // Obtain the system language. - let systemLanguage = i18n.System.getSystemLanguage(); // systemLanguage indicates the current system language. + let systemLanguage: string = i18n.System.getSystemLanguage(); // systemLanguage indicates the current system language. // Obtain the system region. - let systemRegion = i18n.System.getSystemRegion(); // systemRegion indicates the current system region. + let systemRegion: string = i18n.System.getSystemRegion(); // systemRegion indicates the current system region. // Obtain the system locale. - let systemLocale = i18n.System.getSystemLocale(); // systemLocale is the current system locale. + let systemLocale: string = i18n.System.getSystemLocale(); // systemLocale is the current system locale. ``` 3. Set the system language, region, and locale. ```ts - // Set the current system language to zh. + // Set the current system language to zh-Hans. try { - i18n.System.setSystemLanguage('zh'); - } catch(error) { + i18n.System.setSystemLanguage('zh-Hans'); + } catch (error) { let err: BusinessError = error as BusinessError; console.error(`call System.setSystemLanguage failed, error code: ${err.code}, message: ${err.message}.`); } - + // Set the current system region to CN. try { - i18n.System.setSystemRegion('CN'); - } catch(error) { + i18n.System.setSystemRegion('CN'); + } catch (error) { let err: BusinessError = error as BusinessError; console.error(`call System.setSystemRegion failed, error code: ${err.code}, message: ${err.message}.`); } - + // Set the current system locale to zh-Hans-CN. try { - i18n.System.setSystemLocale('zh-Hans-CN'); - } catch(error) { + i18n.System.setSystemLocale('zh-Hans-CN'); + } catch (error) { let err: BusinessError = error as BusinessError; console.error(`call System.setSystemLocale failed, error code: ${err.code}, message: ${err.message}.`); } diff --git a/en/application-dev/internationalization/i18n-time-date.md b/en/application-dev/internationalization/i18n-time-date.md index ededc700e125eee41256a0fb68e2a9a9fc0d7444..857edb2cdc07b60d4be1a5f5507d6d7c0ffe949b 100644 --- a/en/application-dev/internationalization/i18n-time-date.md +++ b/en/application-dev/internationalization/i18n-time-date.md @@ -8,7 +8,7 @@ Time and date formatting includes date and time formatting, relative time format ## Constraints -1. The date format and time format must be set at the same time. If the date format, but not the time format, is set, only the date format is displayed. If the time format, but not the date format, is set, only the time format is displayed. +1. The date format and time format must be set at the same time. If the time format, but not the date format, is set, only the time is displayed; if the date format, but not the time format, is set, only the date is displayed. 2. If the date or time format is specified, setting of the year, month, day, hour, minute, second, and weekday formats is not supported. If the date or time format is not set, the year, month, day, hour, minute, second, and weekday formats can be set independently. @@ -25,7 +25,7 @@ Date and time formatting is implemented by the [format](../reference/apis-locali 2. Create a **DateTimeFormat** object. Pass in a locale or locale list. If a locale list is passed, the first valid locale is used. If you do not pass in any locale, the current system locale will be used. - You can use **DateTimeOptions** to set different date and time formats. For details, see Table 1 to Table 6. + You can use **DateTimeOptions** to set different date and time formats. For details, see Table 1 to Table 10. ```ts let dateFormat: intl.DateTimeFormat = new intl.DateTimeFormat(locale: string | Array, options?: DateTimeOptions); @@ -36,7 +36,7 @@ Date and time formatting is implemented by the [format](../reference/apis-locali ```ts // Format the date and time. let formattedDate: string = dateFormat.format(date: Date); - + // Format the time segment. let formattedDateRange: string = dateFormat.formatRange(startDate: Date, endDate: Date); ``` @@ -48,92 +48,166 @@ Date and time formatting is implemented by the [format](../reference/apis-locali **Date and Time Formatting Options** -The following uses the time **2021-09-17 13:04:00** and locale **zh-CN** as an example to show the values of [DateTimeOptions](../reference/apis-localization-kit/js-apis-intl.md#datetimeoptions) and corresponding display effects. +The following uses 13:04:00 and 00:25:00 on September 17, 2021 and locales **zh-CN** and **en** as examples to illustrate the values and display results of [DateTimeOptions](../reference/apis-localization-kit/js-apis-intl.md#datetimeoptions). **Table 1** Date display format (dateStyle) -| Value| Display Effect| -| -------- | -------- | -| full | Friday, September 17, 2021| -| long | September 17, 2021| -| short | 2021/9/17 | -| medium | September 17, 2021| +| Value | Description | 2021-09-17 13:04:00 for Locale zh-CN| 2021-09-17 13:04:00 for Locale en| +| ------ | --------------------------------------- | ------------------------------------------ | ---------------------------------------- | +| full | Complete date display, including the year, month, day, and week.| 2021年9月17日星期五 | Friday, September 17, 2021 | +| long | Long date display, including the year, month, and day. | 2021年9月17日 | September 17, 2021 | +| short | Short date display, including the year, month, and day. | 2021/9/17 | 9/17/21 | +| medium | Medium date display, including the year, month, and day. | 2021年9月17日 | Sep 17, 2021 | **Table 2** Time display format (timeStyle) -| Value| Display Effect| -| -------- | -------- | -| full | 13:04:00 China Standard Time| -| long | GMT+8 13:4:00 | -| short | 13:04 | -| medium | 13:04:00 | +| Value | Description| 2021-09-17 13:04:00 for Locale zh-CN| 2021-09-17 13:04:00 for Locale en| +| ------ | ------------- | -------- | -------- | +| full | Complete time display, including the time zone and time accurate to seconds.| 中国标准时间 13:04:00 | 13:04:00 China Standard Time | +| long | Long time display, including the time zone expressed in the format of GMT + time zone offset and time accurate to seconds.| GMT+8 13:04:00 | 13:04:00 GMT+8 | +| short | Short time display, including hour and minute.| 13:04 | 13:04 | +| medium | Medium time display, including hour, minute, and second.| 13:04:00 | 13:04:00 | **Table 3** Year display format (year) -| Value| Display Effect| -| -------- | -------- | -| numeric | 2021 | -| 2-digit | 21 | +| Value| Description| 2021-09-17 13:04:00 for Locale zh-CN| 2021-09-17 13:04:00 for Locale en| +| -------- | --------- | -------- | -------- | +| numeric | Complete year| 2021年| 2021 | +| 2-digit | 2-digit year display| 21年| 21 | **Table 4** Weekday display format (weekday) -| Value| Display Effect| -| -------- | -------- | -| long | Friday| -| short | Fri.| -| narrow | 5| +| Value| Description| 2021-09-17 13:04:00 for Locale zh-CN| 2021-09-17 13:04:00 for Locale en| +| -------- | ------- | -------- | -------- | +| long | Long weekday display| 星期五| Friday | +| short | Short weekday display.| 周五| Fri | +| narrow | Narrow weekday display.| 五| F | + +**Table 5** Hour cycle format (hourCycle) + +| Value| Description | 2021-09-17 13:04:00 for Locale zh-CN| 2021-09-17 00:25:00 for Locale zh-CN| +| --- | --------------- | -------------------------------------------- | ------------------------------------------- | +| h11 | Use of 0-11 to indicate the hour| 下午1:04 | 上午0:25 | +| h12 | Use of 1-12 to indicate the hour| 下午1:04 | 上午12:25 | +| h23 | Use of 0-23 to indicate the hour| 13:04 | 00:25 | +| h24 | Use of 1-24 to indicate the hour| 13:04 | 24:25 | + +> **NOTE** +> +> The preceding table shows the display effect for different values of **hourCycle** when **dateStyle** or **timeStyle** is not set. + + +**Table 6** Hour cycle format (hourCycle) + +| Value| Description | 2021-09-17 13:04:00 for Locale zh-CN| 2021-09-17 00:25:00 for Locale zh-CN| +| --- | --------------- | -------------------------------------------- | ------------------------------------------- | +| h11 | Use of 1-24 to indicate the hour| 下午13:04 | 上午24:25 | +| h12 | Use of 1-12 to indicate the hour| 下午1:04 | 上午12:25 | +| h23 | Use of 0-11 to indicate the hour| 1:04 | 0:25 | +| h24 | Use of 0-23 to indicate the hour| 13:04 | 0:25 | + +> **NOTE** +> +> The preceding table shows the display effect for different values of **hourCycle** when **dateStyle** or **timeStyle** is set. + +**Table 7** Month format (month) + +| Value| Description| 2021-09-17 13:04:00 for Locale zh-CN| 2021-09-17 13:04:00 for Locale en| +| -------- | --------- | -------- | -------- | +| numeric | Display of the month as a number| 9月| 9 | +| 2-digit | Display of the month in two digits| 09月| 09 | +| long | Long month display| 九月| September | +| short | Short month display| 9| Sep | +| narrow | Narrow month display| 9 | S | + +**Table 8** Localized representation of time zone names (timeZoneName) + +| Value | Description | 2021-09-17 13:04:00 for Locale zh-CN| 2021-09-17 13:04:00 for Locale en| +| ----- | ------------------ | -------------------------------------------- | ---------------------------------------- | +| long | Long time zone name| 中国标准时间 | China Standard Time | +| short | Short time zone name| GMT+8 | GMT+8 | + +**Table 9** Era display format (era) +| Value| Description| 2021-09-17 13:04:00 for Locale zh-CN| 2021-09-17 13:04:00 for Locale en| +| -------- | ------ | -------- | -------- | +| long | Long epoch display| 公元| Anno Domini | +| short | Short epoch display| 公元| AD | +| narrow | Narrow epoch display| 公元| A | -**Table 5** Hour cycle (hourCycle) +**Table 10** Time period format (dayPeriod) -| Value| Display Effect| -| -------- | -------- | -| h11 | 13:04| -| h12 | 1:04| -| h23 | 1:04 | -| h24 | 13:04 | +| Value| Description| 2021-09-17 13:04:00 for Locale zh-CN| 2021-09-17 13:04:00 for Locale en| +| -------- | ------ | -------- | -------- | +| long | Long time period display| 下午| in the afternoon | +| short | Short time period display| 下午| in the afternoon | +| narrow | Narrow time period display| 下午| in the afternoon | **Development Example** ```ts // Import the intl module. import { intl } from '@kit.LocalizationKit'; -let date = new Date(2021, 8, 17, 13, 4, 0); // The date and time is 2021.09.17 13:04:00. -let startDate = new Date(2021, 8, 17, 13, 4, 0); -let endDate = new Date(2021, 8, 18, 13, 4, 0); +let date: Date = new Date(2021, 8, 17, 13, 4, 0); // The date and time is 2021.09.17 13:04:00. +let startDate: Date = new Date(2021, 8, 17, 13, 4, 0); +let endDate: Date = new Date(2021, 8, 18, 13, 4, 0); // Display complete time information. -let dateFormat1 = new intl.DateTimeFormat('zh-CN', {dateStyle: 'full', timeStyle: 'full'}); -let formattedDate1 = dateFormat1.format(date); // formattedDate1: Friday, September 17, 2021 at 13:04:00 China Standard Time +let fullFormat: intl.DateTimeFormat = new intl.DateTimeFormat('zh-CN', { dateStyle: 'full', timeStyle: 'full' }); +let formattedDate: string = fullFormat.format(date); // formattedDate = 'Friday, September 17, 2021 China Standard Time 13:04:00' // Display short time information in limited space. -let dateFormat2 = new intl.DateTimeFormat('zh-CN', {dateStyle: 'short', timeStyle: 'short'}); -let formattedDate2 = dateFormat2.format(date); // formattedDate2: 2021/9/17 13:04 +let shortFormat: intl.DateTimeFormat = new intl.DateTimeFormat('zh-CN', { dateStyle: 'short', timeStyle: 'short' }); +formattedDate = shortFormat.format(date); // formattedDate = '2021/9/17 13:04' // Customize the display effect of year, month, day, hour, minute, and second. -let dateFormat3 = new intl.DateTimeFormat('zh-CN', {year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit'}); -let formattedDate3 = dateFormat3.format(date); // formattedDate3: 2021/09/17 13:04:00 +let customFormat: intl.DateTimeFormat = new intl.DateTimeFormat('zh-CN', + { + year: 'numeric', + month: '2-digit', + day: '2-digit', + hour: '2-digit', + minute: '2-digit', + second: '2-digit' + }); +formattedDate = customFormat.format(date); // formattedDate = '2021/09/17 13:04:00' // Display only part of the time. -let dateFormat4 = new intl.DateTimeFormat('zh-CN', {month: 'long', day: 'numeric', weekday: 'long' }); -let formattedDate4 = dateFormat4.format(date); // formattedDate4: Friday, September 17 +let partialFormat: intl.DateTimeFormat = new intl.DateTimeFormat('zh-CN', + { + month: 'long', + day: 'numeric', + weekday: 'long' + }); +formattedDate = partialFormat.format(date); // formattedDate = 'Friday, September 17' // Customize the date and time format. -let dateFormat5 = new intl.DateTimeFormat('zh-CN', {dateStyle: 'short', timeStyle: 'short', hourCycle: 'h11'}); -let formattedDate5 = dateFormat5.format(date); // formattedDate5: 2021/9/17 1:04 PM +let hourCycleFormat: intl.DateTimeFormat = new intl.DateTimeFormat('zh-CN', + { + dateStyle: 'short', + timeStyle: 'short', + hourCycle: 'h11' + }); +formattedDate = hourCycleFormat.format(date); // formattedDate = '2021/9/17 1:04 PM' // Customize the date and time format for users accustomed to other numeral systems. -let dateFormat6 = new intl.DateTimeFormat('zh-CN', {dateStyle: 'short', timeStyle: 'short', numberingSystem: 'arab'}); -let formattedDate6 = dateFormat6.format(date); // formattedDate6: ٢٠٢١/٩/١٧ ١٣:٠٤ +let numberingSystemFormat: intl.DateTimeFormat = new intl.DateTimeFormat('zh-CN', + { + dateStyle: 'short', + timeStyle: 'short', + numberingSystem: 'arab' + }); +formattedDate = numberingSystemFormat.format(date); // formattedDate = '٢٠٢١/٩/١٧ ١٣:٠٤' // Format a time segment. -let dataFormat7 = new intl.DateTimeFormat('en-GB'); -let formattedDateRange = dataFormat7.formatRange(startDate, endDate); // formattedDateRange: 17/09/2021 - 18/09/2021 +let dateRangeFormat: intl.DateTimeFormat = new intl.DateTimeFormat('en-GB'); +let formattedDateRange: string = + dateRangeFormat.formatRange(startDate, endDate); // formattedDateRange = '17/09/2021 - 18/09/2021' // Obtain formatting options. -let dataFormat8 = new intl.DateTimeFormat('en-GB', {dateStyle: 'full'}); -let options = dataFormat8.resolvedOptions(); -let dateStyle = options.dateStyle; // dateStyle: full +let dateFormat: intl.DateTimeFormat = new intl.DateTimeFormat('en-GB', { dateStyle: 'full' }); +let options: intl.DateTimeOptions = dateFormat.resolvedOptions(); +let dateStyle: string | undefined = options.dateStyle; // dateStyle = 'full' ``` ### Relative Time Formatting @@ -170,20 +244,20 @@ Relative time formatting is implemented by the [format](../reference/apis-locali The following uses the relative time **one day ago** and locales **fr-FR** and **en-GB** as an example to show different values of [RelativeTimeFormatInputOptions](../reference/apis-localization-kit/js-apis-intl.md#relativetimeformatinputoptions8) and corresponding display effects. -**Table 6** Output message format (numeric) +**Table 11** Numeric representation (numeric) -| Value| Display Effect (fr-FR)| Display Effect (en-GB)| -| -------- | -------- | -------- | -| always | il y a 1 jour | 1 day ago | -| auto | hier | yesterday | +| Value | Description | Display Effect (fr-FR)| Display Effect (en-GB)| +| ------ | -------------------------------------------- | -------------- | --------------- | +| always | Use of a number to indicate the relative time | il y a 1 jour | 1 day ago | +| auto | Use of a phrase or value based on the locale to indicate the relative time| hier | yesterday | -Table 7 Internationalization message length (style) +**Table 12** Relative time style (style) -| Value| Display Effect (fr-FR)| Display Effect (en-GB)| -| -------- | -------- | -------- | -| long | il y a 1 jour | 1 day ago | -| short | il y a 1 j | 1 day ago | -| narrow | -1 j | 1 day ago | +| Value | Description | Display Effect (fr-FR)| Display Effect (en-GB)| +| ------ | -------------------- | -------------- | -------------- | +| long | Long relative time display | il y a 1 jour | 1 day ago | +| short | Short relative time display | il y a 1 j | 1 day ago | +| narrow | Narrow relative time display| -1 j | 1 day ago | **Development Example** @@ -192,26 +266,27 @@ Table 7 Internationalization message length (style) import { intl } from '@kit.LocalizationKit'; // Display the relative time. -let relativeTimeFormat1 = new intl.RelativeTimeFormat('en-GB'); -let formattedRelativeTime1 = relativeTimeFormat1.format(-1, 'day'); // formattedRelativeTime1: 1 day ago +let relativeTimeFormat: intl.RelativeTimeFormat = new intl.RelativeTimeFormat('en-GB'); +let formattedRelativeTime: string = relativeTimeFormat.format(-1, 'day'); // formattedRelativeTime = '1 day ago' // Display the relative time in a conversational style. -let relativeTimeFormat2 = new intl.RelativeTimeFormat('en-GB', {numeric: "auto"}); -let formattedRelativeTime2 = relativeTimeFormat2.format(-1, 'day'); // formattedRelativeTime2: yesterday +let numericAutoFormat: intl.RelativeTimeFormat = new intl.RelativeTimeFormat('en-GB', { numeric: 'auto' }); +formattedRelativeTime = numericAutoFormat.format(-1, 'day'); // formattedRelativeTime = 'yesterday' // Use the narrow style for certain languages. -let relativeTimeFormat3 = new intl.RelativeTimeFormat('fr-FR'); // The default style is long. -let formattedRelativeTime3 = relativeTimeFormat3.format(-1, 'day'); // formattedRelativeTime3: il y a 1 jour -let relativeTimeFormat4 = new intl.RelativeTimeFormat('fr-FR', {style: 'narrow'}); -let formattedRelativeTime4 = relativeTimeFormat4.format(-1, 'day'); // formattedRelativeTime4: -1 j +let longFormat: intl.RelativeTimeFormat = new intl.RelativeTimeFormat('fr-FR'); // The default style is long. +formattedRelativeTime = longFormat.format(-1, 'day'); // formattedRelativeTime = 'il y a 1 jour' +let narrowFormat: intl.RelativeTimeFormat = new intl.RelativeTimeFormat('fr-FR', { style: 'narrow' }); +formattedRelativeTime = narrowFormat.format(-1, 'day'); // formattedRelativeTime = '-1 j' // Display the custom relative time for the specified locale. -let relativeTimeFormat5 = new intl.RelativeTimeFormat('en-GB', {style: 'long'}); -// parts: [{type: 'literal', value: 'in'}, {type: 'integer', value: 1, unit: 'day'}, {type: 'literal', value: 'day'}] -let parts = relativeTimeFormat5.formatToParts(1, 'day'); +let partFormat: intl.RelativeTimeFormat = new intl.RelativeTimeFormat('en-GB', { style: 'long' }); +// parts = [{type: 'literal', value: 'in'}, {type: 'integer', value: 1, unit: 'day'}, {type: 'literal', value: 'day'}] +let parts: object[] = partFormat.formatToParts(1, 'day'); // Obtain the formatting options of RelativeTimeFormat. -let relativeTimeFormat6 = new intl.RelativeTimeFormat('en-GB', {numeric: 'auto'}); -let options = relativeTimeFormat6.resolvedOptions(); -let numeric = options.numeric; // numeric: auto +let resolvedFormat: intl.RelativeTimeFormat = new intl.RelativeTimeFormat('en-GB', { numeric: 'auto' }); +let options: intl.RelativeTimeFormatResolvedOptions = resolvedFormat.resolvedOptions(); +let numeric: string = options.numeric; // numeric = 'auto' ``` + \ No newline at end of file diff --git a/en/application-dev/internationalization/i18n-time-zone-display.md b/en/application-dev/internationalization/i18n-time-zone-display.md index 17ec9d6490e50005624349e78fbe325809b39e69..1e8ed5f89f1d11e4521302fbc2125c0ca97d64e7 100644 --- a/en/application-dev/internationalization/i18n-time-zone-display.md +++ b/en/application-dev/internationalization/i18n-time-zone-display.md @@ -2,7 +2,7 @@ ## Use Cases -In a multi-language environment, time zones may be addressed by users in different regions in different ways. Therefore, your application needs to localize time zone names to adapt to local user habits. +In a multi-language environment, time zones may be addressed by users in different regions in different ways. To this end, your application needs to localize time zone names to adapt to local user habits. ## How to Develop @@ -15,6 +15,6 @@ For details about how to use related APIs, see [getDisplayName](../reference/api 2. Localize the time zone name, for example, **America/Sao_Paulo**. ```ts - let timezone = i18n.getTimeZone("America/Sao_Paulo"); - let timeZoneName = timezone.getDisplayName("zh-Hans", true); // Brasilia Standard Time + let timezone: i18n.TimeZone = i18n.getTimeZone('America/Sao_Paulo'); + let timeZoneName: string = timezone.getDisplayName ('zh-Hans', true); // timeZoneName ='Brasília Standard Time' ``` diff --git a/en/application-dev/internationalization/i18n-time-zone.md b/en/application-dev/internationalization/i18n-time-zone.md index 05f07ffc3278dcc085db765b04ba6acb3981f54e..ed515e97ac72ff4fbc8171c0c8bf62d173c53d0d 100644 --- a/en/application-dev/internationalization/i18n-time-zone.md +++ b/en/application-dev/internationalization/i18n-time-zone.md @@ -16,57 +16,57 @@ The local time of different countries and regions varies according to their long 2. Create a **TimeZone** object and implement functions such as calculating the offset between a fixed time zone and the actual time zone and obtaining and traversing the time zone list. ```ts // Obtain the time zone of Brazil. - let timezone = i18n.getTimeZone("America/Sao_Paulo"); // Pass in a specific time zone to create a TimeZone object. - let timezoneId = timezone.getID();// America/Sao_Paulo - + let timezone: i18n.TimeZone = i18n.getTimeZone('America/Sao_Paulo'); // Pass in a specific time zone to create a TimeZone object. + let timezoneId: string = timezone.getID(); // timezoneId = 'America/Sao_Paulo' + // Obtain the TimeZone object corresponding to the city ID. - let aucklandTimezone = i18n.TimeZone.getTimezoneFromCity("Auckland"); - let aucklandTzId = aucklandTimezone.getID(); // Pacific/Auckland - + let aucklandTimezone: i18n.TimeZone = i18n.TimeZone.getTimezoneFromCity('Auckland'); + timezoneId = aucklandTimezone.getID(); // timezoneId = 'Pacific/Auckland' + // Localized time zone name - let timeZoneName = timezone.getDisplayName("zh-Hans", true); // Brasilia Standard Time - + let timeZoneName: string = timezone.getDisplayName ('zh-Hans', true); // timeZoneName ='Brasília Standard Time' + // Localized city name - let cityDisplayName = i18n.TimeZone.getCityDisplayName("Auckland", "zh-Hans") // Auckland (New Zealand) - + let cityDisplayName: string = i18n.TimeZone.getCityDisplayName('Auckland', 'zh-Hans'); // cityDisplayName = 'Auckland (New Zealand)' + // Fixed offset of the time zone - let rawOffset = timezone.getRawOffset(); // -10800000 - + let rawOffset: number = timezone.getRawOffset(); // rawOffset = -10800000 + // Actual offset of the time zone (fixed offset + DST) - let offset = timezone.getOffset(1234567890);// -10800000 - + let offset: number = timezone.getOffset(1234567890); // offset = -10800000 + // List of time zone IDs supported by the system - let ids = i18n.TimeZone.getAvailableIDs(); // ["America/Adak", "Asia/Hovd", "America/Sao_Paulo", "Asia/Jerusalem", "Europe/London",...] - + let availableIDs: Array = i18n.TimeZone.getAvailableIDs(); // availableIDs = ['America/Adak', 'Asia/Hovd', ...] + // List of time zone city IDs supported by the system - let cityIdArray = i18n.TimeZone.getAvailableZoneCityIDs(); // ["Auckland", "Magadan", "Lord Howe Island",...] + let cityIDs: Array = i18n.TimeZone.getAvailableZoneCityIDs(); // cityIDs = ['Auckland', 'Magadan', ...] + // Traverse the list of time zone city IDs. let timezoneList: Array = []; // Time zone list displayed to the user + class Item { - cityDisplayName : string = ""; - timezoneId : string = ""; - offset : string = ""; - cityId : string = "" + cityDisplayName: string = ""; + timezoneId: string = ""; + offset: string = ""; + cityId: string = "" } - for (let i =0 ; i < cityIdArray.length ; i++) { - let cityId = cityIdArray[i]; - let timezone = i18n.TimeZone.getTimezoneFromCity(cityId); // TimeZone object corresponding to the city ID - let cityDisplayName = i18n.TimeZone.getCityDisplayName(cityId, "zh-CN"); // Localized city name - let timestamp = (new Date()).getTime() - let item : Item = { - cityDisplayName : cityDisplayName, - timezoneId : timezone.getID(), - offset : 'GMT'+ (timezone.getOffset(timestamp) / 3600*1000), - cityId : cityId - } - timezoneList.push(item); - } - - // TimeZone object array corresponding to the specified geographical coordinates - let timezoneArray = i18n.TimeZone.getTimezonesByLocation(-43.1, -22.5) - for (let i =0;i < timezoneArray.length; i++) { - let tzId = timezoneArray[i].getID(); // America/Sao_Paulo + + for (let i = 0; i < cityIDs.length; i++) { + let cityId: string = cityIDs[i]; + let timezone: i18n.TimeZone = i18n.TimeZone.getTimezoneFromCity(cityId); // TimeZone object corresponding to the city ID + let cityDisplayName: string = i18n.TimeZone.getCityDisplayName(cityId, 'zh-CN'); // Localized city name + let timestamp: number = (new Date()).getTime(); + let item: Item = { + cityDisplayName: cityDisplayName, + timezoneId: timezone.getID(), + offset: 'GMT' + (timezone.getOffset(timestamp) / 3600 * 1000), + cityId: cityId + }; + timezoneList.push(item); } + + // TimeZone object array corresponding to the specified geographical coordinates + let timezoneArray: Array = i18n.TimeZone.getTimezonesByLocation(-43.1, -22.5); ``` ### Dual-Clock Application @@ -78,26 +78,26 @@ The local time of different countries and regions varies according to their long 2. Add a time zone to the preferred time zone list of the application. ```ts - let timezone1 = i18n.getTimeZone("America/Sao_Paulo"); - let timezone2 = i18n.getTimeZone(); - let appPreferredTimeZoneList: Array = [] // Application preferred time zone list - appPreferredTimeZoneList.push(timezone1); - appPreferredTimeZoneList.push(timezone2); + let pauloTimezone: i18n.TimeZone = i18n.getTimeZone('America/Sao_Paulo'); + let defaultTimezone: i18n.TimeZone = i18n.getTimeZone(); + let appPreferredTimeZoneList: Array = []; // Application preferred time zone list + appPreferredTimeZoneList.push(pauloTimezone); + appPreferredTimeZoneList.push(defaultTimezone); ``` 3. Traverse the preferred time zone list of the application to obtain the time of each time zone. ```ts - let locale = i18n.System.getSystemLocale(); - for (let i = 0 ; i < appPreferredTimeZoneList.length ; i++) { - let timezone = appPreferredTimeZoneList[i].getID(); - let calendar = i18n.getCalendar(locale); - calendar.setTimeZone(timezone); // Set the time zone of the Calendar object. - // Obtain the year, month, day, hour, minute, and second. - let year = calendar.get("year"); - let month = calendar.get("month"); - let day = calendar.get("date"); - let hour = calendar.get("hour"); - let minute = calendar.get("minute"); - let second = calendar.get("second"); + let locale: string = i18n.System.getSystemLocale(); + for (let i = 0; i < appPreferredTimeZoneList.length; i++) { + let timezone: string = appPreferredTimeZoneList[i].getID(); + let calendar: i18n.Calendar = i18n.getCalendar(locale); + calendar.setTimeZone(timezone); // Set the time zone of the Calendar object. + // Obtain the year, month, day, hour, minute, and second. + let year: number = calendar.get('year'); + let month: number = calendar.get('month'); + let day: number = calendar.get('date'); + let hour: number = calendar.get('hour'); + let minute: number = calendar.get('minute'); + let second: number = calendar.get('second'); } ``` diff --git a/en/application-dev/internationalization/i18n-ui-design.md b/en/application-dev/internationalization/i18n-ui-design.md index 465093a91d2f2cd67b16d3ab9cbdfe7d804debea..8aadb387eaacd0256992d3409944c2d7815c5ceb 100644 --- a/en/application-dev/internationalization/i18n-ui-design.md +++ b/en/application-dev/internationalization/i18n-ui-design.md @@ -4,7 +4,7 @@ A set of effective internationalization guidelines for UI design can not only es ## Space Reservation and Flexible Layout -The length of translations languages varies greatly according to languages. Translation may increase the length of UI texts. To ensure that UI strings are not truncated after being translated into other languages, the best practice is to use flexible dynamic layout. That is, UI controls are dynamically adjusted based on the text length. If flexible layout is not applicable during actual development, reserve sufficient text space. The following table takes English as an example to provide the reference space to be reserved for translation. +The length of translations can vary significantly across languages, which may cause UI text length to increase after translation. To ensure that UI strings are not truncated after being translated into other languages, the best practice is to use flexible dynamic layout. That is, UI controls are dynamically adjusted based on the text length. If flexible layout is not applicable, reserve sufficient text space during development. The following table takes English as an example to provide the reference space to be reserved for translation. **Table 1** Reserved space on the UI for translation @@ -23,7 +23,7 @@ Different text alignment modes and reading sequences may be used for different l - UI layout mirroring. The UI should allow the content of an RTL language to be displayed in the original layout, meeting the bidirectional reading experience. For example, ABC is read ABC for an LTR language and CBA for an RTL language. -- UI element mirroring. UI controls and icons with directionality are required to comply with mirroring rules, as shown in Figure 3, Figure 4, and Figure 5. Some icons, for example, the clock face, do not need to be mirrored because they are not directional or related to real objects. +- UI element mirroring. UI controls and icons with directionality are required to comply with mirroring rules, as shown in Figure 3, Figure 4, and Figure 5. Some icons, for example, the clock face, do not need to be mirrored because they are not directional or related to real objects. - Touch and operation. The touch or operation on each UI element should comply with the reading sequence of the language in use. For example, if there are multiple tabs, swiping left means to move backward for an LTR language and swiping right means to move backward for an RTL language. @@ -31,20 +31,20 @@ Different text alignment modes and reading sequences may be used for different l **Figure 1** Example general layout (English) -![image_0000001784343297](figures/image_0000001784343297.png) +![zh-cn_image_0000001784343297](figures/zh-cn_image_0000001784343297.png) **Figure 2** Example mirroring layout (Arabic) -![image_0000001784263053](figures/image_0000001784263053.png) +![zh-cn_image_0000001784263053](figures/zh-cn_image_0000001784263053.png) **Figure 3** General icon resources -![image_0000001737423164](figures/image_0000001737423164.png) +![zh-cn_image_0000001737423164](figures/zh-cn_image_0000001737423164.png) **Figure 4** Icon resources for RTL languages -![image_0000001737264020](figures/image_0000001737264020.png) +![zh-cn_image_0000001737264020](figures/zh-cn_image_0000001737264020.png) **Figure 5** Mirroring controls for RTL languages -![image_0000001784343305](figures/image_0000001784343305.png) +![zh-cn_image_0000001784343305](figures/zh-cn_image_0000001784343305.png) diff --git a/en/application-dev/internationalization/i18n-user-preferences.md b/en/application-dev/internationalization/i18n-user-preferences.md index ef3a894c8edfe1768665afc14090c7654e961363..15c1454c6c10949e85dffe6d70c1d670b423225d 100644 --- a/en/application-dev/internationalization/i18n-user-preferences.md +++ b/en/application-dev/internationalization/i18n-user-preferences.md @@ -23,28 +23,28 @@ For details about how to use the APIs, see [setUsingLocalDigit](../reference/api 3. Enable display of local digits on the application page. ```ts - try { + try { i18n.System.setUsingLocalDigit(true); // Enable the local digit switch. - } catch(error) { + } catch (error) { let err: BusinessError = error as BusinessError; console.error(`call System.setUsingLocalDigit failed, error code: ${err.code}, message: ${err.message}.`); } - let date = new Date(2023, 9, 25); // The date is 2023.10.25. - let appPreferredLanguage = "ar"; - let dateTimeFmt = new intl.DateTimeFormat(appPreferredLanguage); - let result = dateTimeFmt.format(date); // result = "٢٠٢٣/١٠/٢٥" (local Arabic digits) + let date: Date = new Date(2023, 9, 25); // The date is 2023-10-25. + let appPreferredLanguage: string = 'ar'; + let dateTimeFmt: intl.DateTimeFormat = new intl.DateTimeFormat(appPreferredLanguage); + let formattedTime: string = dateTimeFmt.format(date); // formattedTime = '٢٠٢٣/١٠/٢٥' (represented by localized numbers in Arabic) ``` 4. Set the 24-hour clock format. ```ts - try { + try { i18n.System.set24HourClock(true); // true means to enable the 24-hour clock, and false means to enable the 12-hour clock. - } catch(error) { + } catch (error) { let err: BusinessError = error as BusinessError; console.error(`call System.set24HourClock failed, error code: ${err.code}, message: ${err.message}.`); } - let date = new Date(2023, 9, 25, 16, 48, 0); // The date and time is 2023.10.25 16:48:00. - let appPreferredLanguage = "zh"; - let dateTimeFmt = new intl.DateTimeFormat(appPreferredLanguage, { timeStyle: "medium" }); - let result = dateTimeFmt.format(date); // result = "16:48:00" + let date: Date = new Date(2023, 9, 25, 16, 48, 0); // The date and time is 2023-10-25 16:48:00. + let appPreferredLanguage: string = 'zh'; + let dateTimeFmt: intl.DateTimeFormat = new intl.DateTimeFormat(appPreferredLanguage, { timeStyle: 'medium' }); + let formattedTime: string = dateTimeFmt.format(date); // formattedTime = '16:48:00' ``` diff --git a/en/application-dev/internationalization/l10n-hard-coding-concatenate.md b/en/application-dev/internationalization/l10n-hard-coding-concatenate.md index a5aca9b4805c0666ca6f0a35e7a022d200787c4e..6d2b20b64f7c7bf381b5802f3c5f4b44fbdc5160 100644 --- a/en/application-dev/internationalization/l10n-hard-coding-concatenate.md +++ b/en/application-dev/internationalization/l10n-hard-coding-concatenate.md @@ -12,12 +12,12 @@ Different from obtaining data from external systems or generating data during op 1. Avoid using hard coding. Extract the strings to be translated into resource files, separate them from the code, and use dedicated APIs for loading. For details, see [Multilingual Resource Provisioning](./l10n-multilingual-resources.md). -2. Do not directly concatenate strings. If variables (for example, **Video** and **Browser** in **Open HUAWEI Video** and **Open HUAWEI Browser**) are present, use placeholders as the substitute of variables to make the syntax complete. +2. Do not directly concatenate strings. If variables (for example, **Video** and **Browser** in **Open Video** and **Open Browser**) are present, use placeholders as the substitute of variables to make the syntax complete. Example of a resource placeholder: ```ts { "name": "string1", - "value": "Open the %s app." + "value": "Open %s" } ``` diff --git a/en/application-dev/internationalization/l10n-multilingual-resources.md b/en/application-dev/internationalization/l10n-multilingual-resources.md index 305e9f839597b638503925f1c5781d35a05e89ff..69310918c2d45a5fe480627d61a841475555125f 100644 --- a/en/application-dev/internationalization/l10n-multilingual-resources.md +++ b/en/application-dev/internationalization/l10n-multilingual-resources.md @@ -3,7 +3,7 @@ ## Use Cases -When an application is to be launched in multiple regions, the application needs to be localized according to local language and culture requirements. This allows the application to load and display content in such a way that meets the usage habits of local users. The contents loaded on the UI include text, images, audios, and videos. Such contents are called resources. To ensure that the application properly loads the content specific to different countries, locales, and languages, you need to create multiple resource directories to store these resources. When a user runs an application, the system automatically selects and loads the resources that best match the device based on the locale. To better implement application localization, it is recommended that the localized content be separated from the core functions as much as possible and be stored in a resource directory. +When an application is to be launched in multiple countries or regions, the application needs to be localized according to local language and culture requirements. This allows the application to load and display content in such a way that meets the usage habits of local users. The contents loaded on the UI include text, images, audios, and videos. Such contents are called resources. To ensure that the application properly loads the content specific to different countries, locales, and languages, you need to create multiple resource directories to store these resources. When a user runs an application, the system automatically selects and loads the resources that best match the device based on the locale. To better implement application localization, it is recommended that the localized content be separated from the core functions as much as possible and be stored in a resource directory. The following introduces how to configure resource files and resource matching rules. You only need to focus on resource configuration. After resource files are configured, your application can then access resources based on service requirements. For details, see [Resource Categories and Access](../quick-start/resource-categories-and-access.md#resource-access). @@ -16,11 +16,11 @@ The following introduces how to configure resource files and resource matching r 2. Create resource directories. - Resource directories include a default directory (**base** directory) and one or more qualifier directories. The default directory is generated when a project is created. It can be used to store content such as strings, colors, animations, and layouts. Qualifier directories can be customized based on languages and scripts. They are used to store resources such as strings, images, and audios specific to the target locale. An example of a customized qualifier directory is **resources/en_GB-vertical-car-mdpi**. + Resource directories include a default directory (`base` directory) and one or more qualifier directories. The default directory is generated when a project is created. It can be used to store content such as strings, colors, animations, and layouts. Qualifier directories can be customized based on languages and scripts. They are used to store resources such as strings, images, and audios specific to the target locale. An example of a customized qualifier directory is `resources/en_GB-vertical-car-mdpi`. -3. Create resource group directories. Create the corresponding resource group directory according to the resource type. For example, to store media resources, create the **media** directory. The directory structure is **resources/en_GB-vertical-car-mdpi/media**. +3. Create resource group directories. Create the corresponding resource group directory according to the resource type. For example, to store media resources, create the `media` directory. The directory structure is `resources/en_GB-vertical-car-mdpi/media`. -4. Create resource files. Place resources such as strings, images, and audios in the corresponding **.json** resource files. +4. Create resource files. Place resources such as strings, images, and audios in the corresponding `.json` resource files. > **NOTE** > diff --git a/en/application-dev/internationalization/l10n-singular-plural.md b/en/application-dev/internationalization/l10n-singular-plural.md index 3473328daba3bfa80c168b164ee02fc4fe4acd5c..d9e0d2cb38cb864c88033a4b820e131acf6d80df 100644 --- a/en/application-dev/internationalization/l10n-singular-plural.md +++ b/en/application-dev/internationalization/l10n-singular-plural.md @@ -16,7 +16,7 @@ Singular and plural numbers are usually distinguished by the following categorie - other: other cases -For example, in Arabic, the rules are as follows: +For example, in Arabic, the plural rules are as follows: - zero : 0 @@ -32,16 +32,4 @@ For example, in Arabic, the rules are as follows: ## How to Develop -For details about how to use the APIs, see [getPluralStringValueSync](../reference/apis-localization-kit/js-apis-resource-manager.md#getpluralstringvaluesync10). - -```ts -import { BusinessError } from '@ohos.base'; - -try { - this.context.resourceManager.getPluralStringByNameSync("test", 1);} -catch (error) { - let code = (error as BusinessError).code; - let message = (error as BusinessError).message; - console.error(`getPluralStringByNameSync failed, error code: ${code}, message: ${message}.`); -} -``` +For details about how to use the APIs, see [getIntPluralStringValueSync](../reference/apis-localization-kit/js-apis-resource-manager.md#getintpluralstringvaluesync18). diff --git a/en/application-dev/internationalization/l10n-translation-scene.md b/en/application-dev/internationalization/l10n-translation-scene.md index 0276c9eb569d7edc5600e14566b0bddd80697a22..713c3914959619231d18c1433df6b3d7bbfb5d0a 100644 --- a/en/application-dev/internationalization/l10n-translation-scene.md +++ b/en/application-dev/internationalization/l10n-translation-scene.md @@ -1,8 +1,6 @@ # Scene and Context Clarification for Translation -The translation results of the same content may vary greatly in different scenes and contexts. When providing UI strings for translation, clarifying the scene and context can help to avoid translation errors. +The translation results of the same content may vary greatly in different scenes and contexts. When providing UI strings for translation, clarifying the scene and context can help to avoid translation errors. Translation scene information is usually provided in two ways: -Translation scene information is usually provided in two ways: - -- Use string resource files for commenting or annotation, including the context, part-of-speech, keyword meaning, maximum text length allowed by a control, and meaning and value range of a variable. -- Provide screenshots. +1. Comments and annotations, which are made using string resource files, including the the context, part-of-speech, key word meaning, maximum text length supported by a control, variable meaning, and value range. +2. Screenshots, which are provided to show the actual UI layout and content. diff --git a/en/application-dev/internationalization/pseudo-i18n-testing-mirror.md b/en/application-dev/internationalization/pseudo-i18n-testing-mirror.md index 003b5263bed8576e52aa6eb6bfc94ffc62ee2a6b..d4a5fa8799cf6dd9e7f2e47b7821f73005fc5af1 100644 --- a/en/application-dev/internationalization/pseudo-i18n-testing-mirror.md +++ b/en/application-dev/internationalization/pseudo-i18n-testing-mirror.md @@ -1,6 +1,6 @@ # Pseudo-Localization Testing for UI Mirroring -## Application scenario +## Application Scenario The pseudo-localization testing for UI mirroring aims to check whether the text reading direction is correct. In some languages, the text is not read from left to right. For example, in Arabic, text is read from right to left. @@ -18,6 +18,6 @@ The pseudo-localization testing for UI mirroring aims to check whether the text ## **Test Item** -1. Check whether the UI layout, text direction, and UI control logic comply with the reading habit of the target locale. For details, see [UI Mirroring](i18n-ui-design.md#ui-mirroring). +1. Check whether the UI layout, text direction, and control logic comply with the reading habit of the target locale. For details, see [UI Mirroring](i18n-ui-design.md#ui-mirroring). 2. Check whether related functions are normal. diff --git a/en/application-dev/internationalization/pseudo-i18n-testing-overview.md b/en/application-dev/internationalization/pseudo-i18n-testing-overview.md index 6457f6cdad316037441115d9cc7ed86cfc789fd4..6147246a9d67c7b8b5ab0e3e7e8ac7af5c2748fc 100644 --- a/en/application-dev/internationalization/pseudo-i18n-testing-overview.md +++ b/en/application-dev/internationalization/pseudo-i18n-testing-overview.md @@ -1,7 +1,7 @@ # Overview of Pseudo-Localization Testing -Pseudo-localization is also called pseudo-translation. It simulates the localization process to help find potential localization problems and avoid function defects. It is commonly used in software testing to test whether the software complies with localization and internationalization specifications. Pseudo-localization does not translate the text of the software into a foreign language. Instead, it replaces the text with localized text according to certain rules to simulate the localization process. +Pseudo-localization is also called pseudo-translation. It simulates the localization process to help find potential problems and avoid function defects. It is commonly used in software testing to test whether the software complies with localization and internationalization specifications. Pseudo-localization does not translate the text of the software into a foreign language. Instead, it replaces the text with localized text according to certain rules to simulate the localization process. For newly developed software or software with great UI changes, the delivery period may be delayed if UI testing is performed after the translation is complete. Besides, software UI is apt to change at the early stage of development and therefore translation of UI text is generally not feasible during this period. If translation is done when the product becomes mature, the translation and testing process may delay the product release. This is no longer a challenge with pseudo-localization testing, which helps to uncover potential problems before you actually begin to localize your product. diff --git a/en/application-dev/internationalization/pseudo-i18n-testing-translation.md b/en/application-dev/internationalization/pseudo-i18n-testing-translation.md index 675c82fd1f3e97e7ed50c8324a29c2dfe4be8bd8..075f31dce9d801e1ee9e19f7ba70f375d6b1f1b9 100644 --- a/en/application-dev/internationalization/pseudo-i18n-testing-translation.md +++ b/en/application-dev/internationalization/pseudo-i18n-testing-translation.md @@ -7,7 +7,7 @@ Pseudo-localization testing is used to identify problems that may cause abnormal **Text truncation or abnormal UI layout**: For software components such as menus, text areas, keys, and check boxes, the text length is usually adjusted to adapt to the source language (usually English) during UI design, and then the text alignment, position, and line spacing are adjusted on this basis. However, the text length often increases after translation, leading to abnormal UI layout or text truncation in an inappropriate position. For example, Russian or Norwegian words are usually longer than English words. If the reserved space on the UI is small, the text that exceeds the scope is truncated, and consequently the translated text cannot be displayed completely. -**Abnormal text or symbol display**: This is usually due to a lack of fonts or typesetting capabilities of the system, which arises from the misunderstanding that users would not enter special characters or characters in a specific language during software usage. For example, if a user enters Uyghur text on a Chinese UI, the text may not be properly displayed. +**Abnormal text or symbol display**: This is usually due to a lack of fonts or typesetting capabilities of the system. This issue typically stems from an assumption during development that users would not input special characters or text in specific languages. For example, if a user enters Uyghur text on a Chinese UI, the text may not be properly displayed. ## Test Process @@ -15,8 +15,8 @@ Pseudo-localization testing is used to identify problems that may cause abnormal 1. Switch to the target locale for pseudo-localization testing, for example, **en-XA**. You can switch the locale through the code (system permission required): ```ts - import I18n from '@ohos.i18n' - I18n.System.setSystemLanguage('en-XA') + import { i18n } from '@kit.LocalizationKit'; + i18n.System.setSystemLanguage('en-XA') ``` 2. Traverse the applications to be tested. @@ -24,12 +24,12 @@ Pseudo-localization testing is used to identify problems that may cause abnormal ## **Test Item** -![image_0000001737423156](figures/image_0000001737423156.png) +![zh-cn_image_0000001737423156](figures/zh-cn_image_0000001737423156.png) 1. Check the UI for text truncation or distortion, or abnormal layout. Text truncation can be observed by checking whether the text ends with **]** (a right square bracket). If the text does not end with **]**, it is not completely displayed. 2. Check for hard coding problems. Hard coding of UI text can be observed by checking whether the text is processed in pseudo-translation format. -3. Check for string concatenation. String concatenation can be observed by checking whether strings in the pseudo-translation format appear in the same control in a consecutive manner, for example, **[string 1][string 2]**. +3. Check for string concatenation problems. String concatenation can be observed by checking whether strings in the pseudo-translation format appear in the same control in a consecutive manner, for example, **[string 1][string 2]**. -4. Check whether the multilingual text is displayed properly. If the text is not properly displayed, for example, squares or blanks are present or the text is incomplete or partially truncated, the display is abnormal. +4. Check for multilingual text display problems. If the text is not properly displayed, for example, squares or blanks are present or the text is incomplete or partially truncated, the display is abnormal. diff --git a/en/application-dev/ipc/Readme-EN.md b/en/application-dev/ipc/Readme-EN.md index 5f245a55a60dd2265009232e9c7599e66b6baf67..fba1586bb5edd86844465ed12f8c5fccafa304ff 100644 --- a/en/application-dev/ipc/Readme-EN.md +++ b/en/application-dev/ipc/Readme-EN.md @@ -1,4 +1,4 @@ -# IPC Kit (Inter-Process Communication Service) +# IPC Kit - [Introduction to IPC Kit](ipc-rpc-overview.md) - [IPC and RPC Development](ipc-rpc-development-guideline.md) diff --git a/en/application-dev/ipc/ipc-rpc-development-guideline.md b/en/application-dev/ipc/ipc-rpc-development-guideline.md index 98191468242b4f83b3eea8dbd3b41b87c5bd617c..7a904616752244f9d7ba2c7ac3669b2cff1aefad 100644 --- a/en/application-dev/ipc/ipc-rpc-development-guideline.md +++ b/en/application-dev/ipc/ipc-rpc-development-guideline.md @@ -192,13 +192,11 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat // If the FA model is used, import featureAbility from @kit.AbilityKit. // import { featureAbility } from '@kit.AbilityKit'; import { rpc } from '@kit.IPCKit'; - ``` - -2. Connect to the desired ability. + ``` - Construct the **want** variable, and specify the bundle name and component name of the application where the ability is located. If cross-device communication is involved, also specify the network ID of the target device, which can be obtained through **distributedDeviceManager**. +2. Bind the desired ability. - Then, construct the **connect** variable, and specify the callback to be invoked when the binding is successful, the binding fails, or the ability is disconnected. If you use the FA model, call the API provided by **featureAbility** to bind an ability. If you use the stage model, obtain a service instance through **Context**, and then call the API provided by **featureAbility** to bind an ability. + Construct the **want** variable, and specify the bundle name and component name of the application where the ability is located. If cross-device communication is involved, also specify the network ID of the target device, which can be obtained through **distributedDeviceManager**.
Then, construct the **connect** variable, and specify the callback to be invoked when the binding is successful, the binding fails, or the ability is disconnected. If you use the FA model, call the API provided by **featureAbility** to bind an ability. If you use the stage model, obtain a service instance through **Context**, and then call the API provided by **featureAbility** to bind an ability. ```ts // If the FA model is used, import featureAbility from @kit.AbilityKit. @@ -208,11 +206,11 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat import { hilog } from '@kit.PerformanceAnalysisKit'; import { distributedDeviceManager } from '@kit.DistributedServiceKit'; import { BusinessError } from '@kit.BasicServicesKit'; - + let dmInstance: distributedDeviceManager.DeviceManager | undefined; let proxy: rpc.IRemoteObject | undefined; let connectId: number; - + // Bind an ability on a single device. let want: Want = { // Enter the bundle name and ability name. @@ -233,11 +231,11 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat }; // Use this method to connect to the ability in the FA model. // connectId = featureAbility.connectAbility(want, connect); - + let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext; // UIAbilityContext // Save the connection ID, which will be used when the ability is disconnected. connectId = context.connectServiceExtensionAbility(want,connect); - + // Bind an ability across devices. try{ dmInstance = distributedDeviceManager.createDeviceManager("ohos.rpc.test"); @@ -245,7 +243,7 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat let err: BusinessError = error as BusinessError; hilog.error(0x0000, 'testTag', 'createDeviceManager errCode:' + err.code + ', errMessage:' + err.message); } - + // Use distributedDeviceManager to obtain the network ID of the target device. if (dmInstance != undefined) { let deviceList = dmInstance.getAvailableDeviceListSync(); @@ -259,13 +257,13 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat // Save the connection ID, which will be used when the ability is disconnected. // Use this method to connect to the ability in the FA model. // connectId = featureAbility.connectAbility(want, connect); - + // The first parameter specifies the bundle name of the application, and the second parameter specifies the callback used to return the network ID obtained by using distributedDeviceManager. connectId = context.connectServiceExtensionAbility(want,connect); } ``` -3. Process service requests sent from the client. +3. Process requests sent from the client. Call **onConnect()** to return a proxy object inherited from [rpc.RemoteObject](../reference/apis-ipc-kit/js-apis-rpc.md#remoteobject) after the ability is successfully connected. Implement [onRemoteMessageRequest](../reference/apis-ipc-kit/js-apis-rpc.md#onremotemessagerequest9) for the proxy object to process requests sent from the client. @@ -362,7 +360,7 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat let proxy: rpc.IRemoteObject | undefined; let connectId: number; - // Connect to an ability on a single device. + // Bind an ability on a single device. let want: Want = { // Enter the bundle name and ability name. bundleName: "ohos.rpc.test.server", @@ -386,3 +384,8 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat this.context.disconnectServiceExtensionAbility(connectId); ``` +## + + + +- diff --git a/en/application-dev/media/audio/Readme-EN.md b/en/application-dev/media/audio/Readme-EN.md index ea98552b303544d47c6a2adf423c4a8a92e06fd2..af6cc4ff513b27c8574d02ddaceff5047bd95e97 100644 --- a/en/application-dev/media/audio/Readme-EN.md +++ b/en/application-dev/media/audio/Readme-EN.md @@ -3,10 +3,10 @@ - [Introduction to Audio Kit](audio-kit-intro.md) - [Selecting an Appropriate Audio Stream Type](using-right-streamusage-and-sourcetype.md) - [Introduction to Audio Focus and Audio Session](audio-playback-concurrency.md) -- Audio Focus Management +- Audio Focus Management - [Using AudioSession to Manage Audio Focus (ArkTS)](audio-session-management.md) - [Using AudioSession to Manage Audio Focus (C/C++)](using-ohaudio-for-session.md) -- Audio Playback +- Audio Playback - [Audio Playback Overview](audio-playback-overview.md) - [Using AudioRenderer for Audio Playback](using-audiorenderer-for-playback.md) - [Responding to Audio Output Device Changes](audio-output-device-change.md) @@ -17,6 +17,7 @@ - [Using AudioHaptic for Audio-Haptic Playback](using-audiohaptic-for-playback.md) - [Volume Management](volume-management.md) - [Audio Effect Management](audio-effect-management.md) + - [Spatial Audio Management](public-audio-spatialization-management.md) - [Spatial Audio Management (for System Applications Only)](audio-spatialization-management.md) @@ -25,17 +26,17 @@ - [Distributed Audio Playback (for System Applications Only)](distributed-audio-playback.md) -- Audio Recording +- Audio Recording - [Audio Recording Overview](audio-recording-overview.md) - [Using AudioCapturer for Audio Recording](using-audiocapturer-for-recording.md) - [Using OHAudio for Audio Recording (C/C++)](using-ohaudio-for-recording.md) - [Microphone Management](mic-management.md) - [Audio Recording Stream Management](audio-recording-stream-management.md) - [Managing Global Audio Input Devices](audio-input-device-management.md) -- Audio Call +- Audio Call - [Audio Call Overview](audio-call-overview.md) - [Developing Audio Call](audio-call-development.md) -- Not Recommended +- Not Recommended - [Switching from OpenSL ES to OHAudio (C/C++)](replace-opensles-by-ohaudio.md) - [Using OpenSL ES for Audio Playback (C/C++)](using-opensl-es-for-playback.md) - [Using OpenSL ES for Audio Recording (C/C++)](using-opensl-es-for-recording.md) diff --git a/en/application-dev/media/audio/audio-call-development.md b/en/application-dev/media/audio/audio-call-development.md index b420b602972fb4c64b74015d65c0753cda3d0fe6..ffd8e9eedb23f2b86ae2ede0a92859b6d9a6ecad 100644 --- a/en/application-dev/media/audio/audio-call-development.md +++ b/en/application-dev/media/audio/audio-call-development.md @@ -241,7 +241,7 @@ async function start() { // Stop recording. async function stop() { if (audioCapturer !== undefined) { - // The AudioCapturer can be stopped only when it is in STATE_RUNNING or STATE_PAUSED state. + // The AudioCapturer can be stopped only when it is in the STATE_RUNNING or STATE_PAUSED state. if (audioCapturer.state.valueOf() !== audio.AudioState.STATE_RUNNING && audioCapturer.state.valueOf() !== audio.AudioState.STATE_PAUSED) { console.info('Capturer is not running or paused'); return; diff --git a/en/application-dev/media/audio/audio-effect-management.md b/en/application-dev/media/audio/audio-effect-management.md index cfcb31bed8db72d91c4b911939d23dfd93a6a97f..1e7168444c0a9b7d55565b48cdfc9fca55920988 100644 --- a/en/application-dev/media/audio/audio-effect-management.md +++ b/en/application-dev/media/audio/audio-effect-management.md @@ -22,15 +22,15 @@ Before the management, you must call [createAudioRenderer(options: AudioRenderer import { BusinessError } from '@kit.BasicServicesKit'; let audioStreamInfo: audio.AudioStreamInfo = { - samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, - channels: audio.AudioChannel.CHANNEL_2, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, - encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, // Sampling rate. + channels: audio.AudioChannel.CHANNEL_2, // Channel. + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, // Sampling format. + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW // Encoding format. }; let audioRendererInfo: audio.AudioRendererInfo = { - usage: audio.StreamUsage.STREAM_USAGE_MUSIC, - rendererFlags: 0 + usage: audio.StreamUsage.STREAM_USAGE_MUSIC, // Audio stream usage type: music. Set this parameter based on the service scenario. + rendererFlags: 0 // AudioRenderer flag. }; let audioRendererOptions: audio.AudioRendererOptions = { diff --git a/en/application-dev/media/audio/audio-input-device-management.md b/en/application-dev/media/audio/audio-input-device-management.md index ab2b499a4dbf369ee0d9f7b9db8381c75866cd0c..3682d117265a3d346d6edebffd1f8c17b6ef79a2 100644 --- a/en/application-dev/media/audio/audio-input-device-management.md +++ b/en/application-dev/media/audio/audio-input-device-management.md @@ -9,8 +9,8 @@ Before using **AudioRoutingManager** to manage audio devices, import the audio m ```ts import { audio } from '@kit.AudioKit'; // Import the audio module. -let audioManager = audio.getAudioManager(); // Create an AudioManager instance. -let audioRoutingManager = audioManager.getRoutingManager(); // Call an API of AudioManager to create an AudioRoutingManager instance. +let audioManager = audio.getAudioManager(); // Create an AudioManager instance. +let audioRoutingManager = audioManager.getRoutingManager(); // Call an API of AudioManager to create an AudioRoutingManager instance. ``` ## Supported Audio Input Device Types @@ -45,10 +45,10 @@ import { audio } from '@kit.AudioKit'; // Listen for connection state changes of audio devices. audioRoutingManager.on('deviceChange', audio.DeviceFlag.INPUT_DEVICES_FLAG, (deviceChanged: audio.DeviceChangeAction) => { - console.info('device change type: ' + deviceChanged.type); // Device connection state change. The value 0 means that the device is connected and 1 means that the device is disconnected. + console.info('device change type: ' + deviceChanged.type); // Device connection state change. The value 0 means that the device is connected and 1 means that the device is disconnected. console.info('device descriptor size : ' + deviceChanged.deviceDescriptors.length); - console.info('device change descriptor: ' + deviceChanged.deviceDescriptors[0].deviceRole); // Device role. - console.info('device change descriptor: ' + deviceChanged.deviceDescriptors[0].deviceType); // Device type. + console.info('device change descriptor: ' + deviceChanged.deviceDescriptors[0].deviceRole); // Device role. + console.info('device change descriptor: ' + deviceChanged.deviceDescriptors[0].deviceType); // Device type. }); // Cancel the listener for the connection state changes of audio devices. diff --git a/en/application-dev/media/audio/audio-kit-intro.md b/en/application-dev/media/audio/audio-kit-intro.md index c2173beb888bf4e110c01b18b4d0a5dbe2efed46..8aff7c81fa22f1a206889722e8e6a10a093c5f2f 100644 --- a/en/application-dev/media/audio/audio-kit-intro.md +++ b/en/application-dev/media/audio/audio-kit-intro.md @@ -7,21 +7,21 @@ Audio Kit provides scenario-specific audio playback and recording APIs to help y - Low-latency playback Unified low-latency and non-low-latency audio playback APIs are provided to achieve the lowest audio output latency on various hardware devices. For example, low-latency APIs can be used to implement fast and smooth audio playback in scenarios such as gaming, prompt/alarm tones, and Karaoke. - + - Low-power playback In long-duration audio playback scenarios such as music playing and audiobook listening, a differentiated audio buffer processing mechanism is used for the screen-off scene. This helps audio playback consume less power by reducing the CPU wake-up frequency. - + - Audio effect mode Applications can enable or disable the system audio effects as required to deliver the optimal audio effect output. The system provides scenario-specific audio effects, for example, audio effects for music playing, audiobook listening, and movie watching. If your application requires custom audio effects, you can disable the system audio effects. - + - Spatial audio Spatial audio APIs are provided. Applications can play audio sources in different formats (stereo, multi-channel, and AudioVivid), and users can get a sense of space and direction while wearing TWS earbuds for listening. - + - Audio-haptic Provides AudioHaptic APIs to implement low-delay synchronous control of audio and haptic streams. When the audio-haptic effect is enabled, users can get rhythmic auditory and haptic feedback while typing or having incoming calls. diff --git a/en/application-dev/media/audio/audio-output-device-change.md b/en/application-dev/media/audio/audio-output-device-change.md index ac7524ac5e33445b89e69f1909104ad67112571a..83d7acf431bef5be2e590abe1b0e0792ad1e0dbb 100644 --- a/en/application-dev/media/audio/audio-output-device-change.md +++ b/en/application-dev/media/audio/audio-output-device-change.md @@ -44,7 +44,6 @@ The system sends [AudioStreamDeviceChangeReason](../../reference/apis-audio-kit/ ## Example ```ts - import router from '@ohos.router'; import { audio } from '@kit.AudioKit'; import { BusinessError } from '@kit.BasicServicesKit'; @@ -56,7 +55,7 @@ The system sends [AudioStreamDeviceChangeReason](../../reference/apis-audio-kit/ encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW // Encoding format. }; let audioRendererInfo: audio.AudioRendererInfo = { - usage: audio.StreamUsage.STREAM_USAGE_MUSIC, // Audio stream usage type. + usage: audio.StreamUsage.STREAM_USAGE_MUSIC, // Audio stream usage type: music. Set this parameter based on the service scenario. rendererFlags: 0 // AudioRenderer flag. }; let audioRendererOptions: audio.AudioRendererOptions = { diff --git a/en/application-dev/media/audio/audio-output-device-management.md b/en/application-dev/media/audio/audio-output-device-management.md index b2372c7200061c32179bcfa7395acf495bd8b50a..d6261c04fedc6c54d37f3052c60c9efe9b708b8d 100644 --- a/en/application-dev/media/audio/audio-output-device-management.md +++ b/en/application-dev/media/audio/audio-output-device-management.md @@ -9,9 +9,9 @@ Before using **AudioRoutingManager** to manage audio devices, import the audio m ```ts import { audio } from '@kit.AudioKit'; // Import the audio module. -let audioManager = audio.getAudioManager(); // Create an AudioManager instance. +let audioManager = audio.getAudioManager(); // Create an AudioManager instance. -let audioRoutingManager = audioManager.getRoutingManager(); // Call an API of AudioManager to create an AudioRoutingManager instance. +let audioRoutingManager = audioManager.getRoutingManager(); // Call an API of AudioManager to create an AudioRoutingManager instance. ``` ## Supported Audio Output Device Types @@ -44,6 +44,10 @@ audioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data: Set a listener to listen for changes of the device connection state. When a device is connected or disconnected, a callback is triggered. +> **NOTE** +> +> The listener captures all changes in device connections. It is not recommended that the changes be used as a basis for handling automatic pausing in applications. If an application needs to manage services related to automatic pause, it should consider the [reasons behind changes in the audio stream output device](audio-output-device-change.md). + ```ts import { audio } from '@kit.AudioKit'; @@ -110,8 +114,8 @@ import { audio } from '@kit.AudioKit'; import { BusinessError } from '@kit.BasicServicesKit'; let rendererInfo: audio.AudioRendererInfo = { - usage : audio.StreamUsage.STREAM_USAGE_MUSIC, - rendererFlags : 0 + usage: audio.StreamUsage.STREAM_USAGE_MUSIC, // Audio stream usage type: music. Set this parameter based on the service scenario. + rendererFlags: 0 // AudioRenderer flag. }; async function getPreferOutputDeviceForRendererInfo() { @@ -129,8 +133,8 @@ async function getPreferOutputDeviceForRendererInfo() { import { audio } from '@kit.AudioKit'; let rendererInfo: audio.AudioRendererInfo = { - usage : audio.StreamUsage.STREAM_USAGE_MUSIC, - rendererFlags : 0 + usage: audio.StreamUsage.STREAM_USAGE_MUSIC, // Audio stream usage type: music. Set this parameter based on the service scenario. + rendererFlags: 0 // AudioRenderer flag. }; // Listen for changes of the output device with the highest priority. diff --git a/en/application-dev/media/audio/audio-recording-stream-management.md b/en/application-dev/media/audio/audio-recording-stream-management.md index 7c05605368b429529175c451d23b0b8e3c1341cc..da37c038584dce0391879c03b1d287b4358fdb68 100644 --- a/en/application-dev/media/audio/audio-recording-stream-management.md +++ b/en/application-dev/media/audio/audio-recording-stream-management.md @@ -41,12 +41,11 @@ During application development, first use **getStreamManager()** to create an ** For details about the APIs, see [AudioStreamManager](../../reference/apis-audio-kit/js-apis-audio.md#audiostreammanager9). - ## How to Develop 1. Create an **AudioStreamManager** instance. - Before using **AudioStreamManager** APIs, you must use **getStreamManager()** to create an **AudioStreamManager** instance. + Before using **AudioStreamManager** APIs, you must use **getStreamManager()** to create an **AudioStreamManager** instance. ```ts import { audio } from '@kit.AudioKit'; @@ -89,7 +88,8 @@ For details about the APIs, see [AudioStreamManager](../../reference/apis-audio- 4. (Optional) Call **getCurrentAudioCapturerInfoArray()** to obtain information about the current audio recording stream. - This API can be used to obtain the unique ID of the audio recording stream, UID of the audio recording client, audio status, and other information about the AudioCapturer. + This API can be used to obtain the unique ID of the audio recording stream, UID of the audio recording client, audio status, and other information about the AudioCapturer. + > **NOTE** > > Before listening for state changes of all audio streams, the application must [declare the ohos.permission.USE_BLUETOOTH permission](../../security/AccessToken/declare-permissions.md), for the device name and device address (Bluetooth related attributes) to be displayed correctly. diff --git a/en/application-dev/media/audio/distributed-audio-playback.md b/en/application-dev/media/audio/distributed-audio-playback.md index 9f8b3d146f75b8a8b41018bf4d1a3090562bc8b6..cc9e502d91298f3b8a944f6723a24635a5ef6979 100644 --- a/en/application-dev/media/audio/distributed-audio-playback.md +++ b/en/application-dev/media/audio/distributed-audio-playback.md @@ -81,8 +81,8 @@ let audioRoutingManager = audioManager.getRoutingManager(); let outputAudioRendererFilter: audio.AudioRendererFilter = { uid: 20010041, rendererInfo: { - usage: audio.StreamUsage.STREAM_USAGE_MUSIC, - rendererFlags: 0 + usage: audio.StreamUsage.STREAM_USAGE_MUSIC, // Audio stream usage type: music. Set this parameter based on the service scenario. + rendererFlags: 0 // AudioRenderer flag. } as audio.AudioRendererInfo, rendererId: 0 }; diff --git a/en/application-dev/media/audio/public-audio-spatialization-management.md b/en/application-dev/media/audio/public-audio-spatialization-management.md new file mode 100644 index 0000000000000000000000000000000000000000..9c7a77901c50efe802d072208259b307c69d16a2 --- /dev/null +++ b/en/application-dev/media/audio/public-audio-spatialization-management.md @@ -0,0 +1,67 @@ +# Spatial Audio Management + +Spatial audio management primarily involves querying the support for spatial audio rendering, querying its enabled or disabled status, and listening for its status changes. + +## How to Use + +Before using any APIs of **AudioSpatializationManager**, you must call [getSpatializationManager](../../reference/apis-audio-kit/js-apis-audio.md#getspatializationmanager18) to obtain an **AudioSpatializationManager** instance. + + ```ts + import { audio } from '@kit.AudioKit'; + + let audioManager = audio.getAudioManager(); + let audioSpatializationManager = audioManager.getSpatializationManager(); + ``` + +## Checking Whether a Device Supports Spatial Audio Rendering + +Use the **spatializationSupported** property in [AudioDeviceDescriptor](../../reference/apis-audio-kit/js-apis-audio.md#audiodevicedescriptor) to check whether a specified device supports spatial audio rendering. You need to use other audio APIs to obtain **AudioDeviceDescriptor** of a connected device or the current audio device. + + ```ts + import { audio } from '@kit.AudioKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + const deviceDescriptors: audio.AudioDeviceDescriptors = audioRoutingManager.getDevicesSync(audio.DeviceFlag.OUTPUT_DEVICES_FLAG); + for (let i = 0; i < deviceDescriptors.length; i++) { + console.info('deviceDescriptor deviceRole: ${deviceDescriptors[i].deviceRole}'); + console.info('deviceDescriptor deviceType: ${deviceDescriptors[i].deviceType}'); + console.info('deviceDescriptor name: ${deviceDescriptors[i].name}'); + console.info('deviceDescriptor spatializationSupported: ${deviceDescriptors[i].spatializationSupported}'); + } + ``` + +## Checking the Status of Spatial Audio Rendering of the Current Device + +Call [isSpatializationEnabledForCurrentDevice](../../reference/apis-audio-kit/js-apis-audio.md#isspatializationenabledforcurrentdevice18) to check whether spatial audio rendering is enabled for the current device. +- If **true** is returned, spatial audio rendering is enabled for the current device. If **false** is returned, it is disabled. +- Spatial audio rendering takes effect only when the current device support spatial audio rendering. + + ```ts + import { audio } from '@kit.AudioKit'; + + let isSpatializationEnabledForCurrentDevice: boolean = audioSpatializationManager.isSpatializationEnabledForCurrentDevice(); + console.info(`AudioSpatializationManager isSpatializationEnabledForCurrentDevice: ${isSpatializationEnabledForCurrentDevice}`); + ``` + +**Listening for Spatial Audio Rendering Status Changes of the Current Device** + +Call [on('spatializationEnabledChangeForCurrentDevice')](../../reference/apis-audio-kit/js-apis-audio.md#onspatializationenabledchangeforcurrentdevice18) to subscribe to the spatial audio rendering status change event of the current device. + +If **true** is returned, spatial audio rendering is enabled. If **false** is returned, it is disabled. + +```ts +import { audio } from '@kit.AudioKit'; + +audioSpatializationManager.on('spatializationEnabledChangeForCurrentDevice', (isSpatializationEnabledForCurrentDevice: boolean) => { + console.info(`isSpatializationEnabledForCurrentDevice: ${isSpatializationEnabledForCurrentDevice}`); +}); +``` + +**Canceling Listening for Spatial Audio Rendering Status Changes of the Current Device** + +Call [off('spatializationEnabledChangeForCurrentDevice')](../../reference/apis-audio-kit/js-apis-audio.md#offspatializationenabledchangeforcurrentdevice18) to unsubscribe from the spatial audio rendering status change event of the current device. + + ```ts + import { audio } from '@kit.AudioKit'; + audioSpatializationManager.off('spatializationEnabledChangeForCurrentDevice'); + ``` diff --git a/en/application-dev/media/audio/replace-opensles-by-ohaudio.md b/en/application-dev/media/audio/replace-opensles-by-ohaudio.md index 54a0e546c560aabdf117916fb3cc4612408d8ec6..f883071333ff8d2bd0dcc6c5333b6ccada7ea603 100644 --- a/en/application-dev/media/audio/replace-opensles-by-ohaudio.md +++ b/en/application-dev/media/audio/replace-opensles-by-ohaudio.md @@ -33,7 +33,7 @@ OpenSL ES: Obtain an **Engine** object through the global interface, and construct an audio playback object based on the **Engine** object and the input and output parameters. -```c++ +```cpp // Generate an Engine object. SLEngineItf engine; // ... @@ -64,7 +64,7 @@ OHAudio: Use the builder mode to generate an audio playback object based on custom parameters. -```c++ +```cpp // Create a builder. OH_AudioStreamBuilder *builder; OH_AudioStreamBuilder_Create(&builder, AUDIOSTREAM_TYPE_RENDERER); @@ -89,7 +89,7 @@ OpenSL ES: Obtain the state switching interface based on the audio playback object and use the interface to switch the state. There are three states: **SL_PLAYSTATE_STOPPED**, **SL_PLAYSTATE_PAUSED**, and **SL_PLAYSTATE_PLAYING**. -```c++ +```cpp // Obtain the playback operation interface based on the audio playback object. SLPlayItf playItf = nullptr; (*playerObject)->GetInterface(playerObject, SL_IID_PLAY, &playItf); @@ -103,7 +103,7 @@ OHAudio: There are independent state switching interfaces. The state is switched based on the state machine. There are six states, which are mainly switched between **AUDIOSTREAM_STATE_PREPARED**, **AUDIOSTREAM_STATE_RUNNING**, **AUDIOSTREAM_STATE_STOPPED**, **AUDIOSTREAM_STATE_PAUSED**, and **AUDIOSTREAM_STATE_RELEASED**. -```c++ +```cpp // Switch the state. OH_AudioRenderer_Start(audioRenderer); OH_AudioRenderer_Pause(audioRenderer); @@ -116,7 +116,7 @@ OpenSL ES: Based on the extended **OHBufferQueue** APIs, you can register a custom callback function to write audio data to be played to the system buffer. -```c++ +```cpp static void MyBufferQueueCallback(SLOHBufferQueueItf bufferQueueItf, void *pContext, SLuint32 size) { SLuint8 *buffer = nullptr; @@ -141,7 +141,7 @@ OHAudio: The callback mode is used. When the audio playback object is constructed, a data input callback is registered to implement custom data filling. During playback, a data request callback is automatically triggered at a proper time based on the system scheduling and delay configuration. -```c++ +```cpp static int32_t MyOnWriteData( OH_AudioRenderer *renderer, void *userData, @@ -166,7 +166,7 @@ OpenSL ES: Call **SLObjectItf** to release object resources. -```c++ +```cpp // Release the playback object resources. (*playerObject)->Destroy(playerObject); ``` @@ -175,7 +175,7 @@ OHAudio: Call the release interface of the module to release object resources. -```c++ +```cpp // Release the builder resources. OH_AudioStreamBuilder_Destroy(builder); diff --git a/en/application-dev/media/audio/using-audiocapturer-for-recording.md b/en/application-dev/media/audio/using-audiocapturer-for-recording.md index c6677c5644436a2639aa010e4213e79feebc990b..aba79d9514282e7ad5fb6d8e9bbcc00453be6098 100644 --- a/en/application-dev/media/audio/using-audiocapturer-for-recording.md +++ b/en/application-dev/media/audio/using-audiocapturer-for-recording.md @@ -33,8 +33,8 @@ You can call **on('stateChange')** to listen for state changes of the AudioCaptu }; let audioCapturerInfo: audio.AudioCapturerInfo = { - source: audio.SourceType.SOURCE_TYPE_MIC, - capturerFlags: 0 + source: audio.SourceType.SOURCE_TYPE_MIC, // Audio source type: microphone. Set this parameter based on the service scenario. + capturerFlags: 0 // Flag indicating an AudioCapturer. }; let audioCapturerOptions: audio.AudioCapturerOptions = { @@ -146,7 +146,7 @@ let audioStreamInfo: audio.AudioStreamInfo = { encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW // Encoding format. }; let audioCapturerInfo: audio.AudioCapturerInfo = { - source: audio.SourceType.SOURCE_TYPE_MIC, // Audio source type. + source: audio.SourceType.SOURCE_TYPE_MIC, // Audio source type: microphone. Set this parameter based on the service scenario. capturerFlags: 0 // Flag indicating an AudioCapturer. }; let audioCapturerOptions: audio.AudioCapturerOptions = { diff --git a/en/application-dev/media/audio/using-audiorenderer-for-playback.md b/en/application-dev/media/audio/using-audiorenderer-for-playback.md index c1194e41cf92814ddc7e7c387a0cf2ac6127f90d..faaf8102aa88600458cef835d61539a8afc30aa1 100644 --- a/en/application-dev/media/audio/using-audiorenderer-for-playback.md +++ b/en/application-dev/media/audio/using-audiorenderer-for-playback.md @@ -41,8 +41,8 @@ During application development, you are advised to use [on('stateChange')](../.. }; let audioRendererInfo: audio.AudioRendererInfo = { - usage: audio.StreamUsage.STREAM_USAGE_MUSIC, - rendererFlags: 0 + usage: audio.StreamUsage.STREAM_USAGE_MUSIC, // Audio stream usage type: music. Set this parameter based on the service scenario. + rendererFlags: 0 // AudioRenderer flag. }; let audioRendererOptions: audio.AudioRendererOptions = { @@ -227,7 +227,7 @@ let audioStreamInfo: audio.AudioStreamInfo = { encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW // Encoding format. }; let audioRendererInfo: audio.AudioRendererInfo = { - usage: audio.StreamUsage.STREAM_USAGE_MUSIC, // Audio stream usage type. + usage: audio.StreamUsage.STREAM_USAGE_MUSIC, // Audio stream usage type: music. Set this parameter based on the service scenario. rendererFlags: 0 // AudioRenderer flag. }; let audioRendererOptions: audio.AudioRendererOptions = { diff --git a/en/application-dev/media/audio/using-ohaudio-for-playback.md b/en/application-dev/media/audio/using-ohaudio-for-playback.md index d5e35fc1cfe1c22fdeaa82826dcd78cf36acc5a1..9d138e99f1e94254b9474b494b2f497c78cfc452 100644 --- a/en/application-dev/media/audio/using-ohaudio-for-playback.md +++ b/en/application-dev/media/audio/using-ohaudio-for-playback.md @@ -36,14 +36,14 @@ To use APIs for audio playback, import <[native_audiostreambuilder.h](../../refe The following code snippet shows how to use [OH_AudioStreamBuilder_Create](../../reference/apis-audio-kit/_o_h_audio.md#oh_audiostreambuilder_create) to create a builder: -``` +```cpp OH_AudioStreamBuilder* builder; OH_AudioStreamBuilder_Create(&builder, streamType); ``` After the audio service is complete, call [OH_AudioStreamBuilder_Destroy](../../reference/apis-audio-kit/_o_h_audio.md#oh_audiostreambuilder_destroy) to destroy the builder. -``` +```cpp OH_AudioStreamBuilder_Destroy(builder); ``` @@ -55,7 +55,7 @@ The following walks you through how to implement simple playback: 1. Create an audio stream builder. - ```c++ + ```cpp OH_AudioStreamBuilder* builder; OH_AudioStreamBuilder_Create(&builder, AUDIOSTREAM_TYPE_RENDERER); ``` @@ -64,7 +64,7 @@ The following walks you through how to implement simple playback: After creating the builder for audio playback, set the parameters required. - ```c++ + ```cpp // Set the audio sampling rate. OH_AudioStreamBuilder_SetSamplingRate(builder, 48000); // Set the number of audio channels. @@ -97,7 +97,7 @@ The following walks you through how to implement simple playback: - Since API version 12, you can call [OH_AudioStreamBuilder_SetFrameSizeInCallback](../../reference/apis-audio-kit/_o_h_audio.md#oh_audiostreambuilder_setframesizeincallback) to set **audioDataSize**. - ```c++ + ```cpp // Customize a data writing function. static OH_AudioData_Callback_Result NewAudioRendererOnWriteData( OH_AudioRenderer* renderer, @@ -166,7 +166,7 @@ The following walks you through how to implement simple playback: > > - Once the callback function finishes its execution, the audio service queues the data in the buffer for playback. Therefore, do not change the buffered data outside the callback. Regarding the last frame, if there is insufficient data to completely fill the buffer, you must concatenate the available data with padding to ensure that the buffer is full. This prevents any residual dirty data in the buffer from adversely affecting the playback effect. - ```c++ + ```cpp // Customize a data writing function. int32_t MyOnWriteData( OH_AudioRenderer* renderer, @@ -223,7 +223,7 @@ The following walks you through how to implement simple playback: - Initialize each callback in [OH_AudioRenderer_Callbacks](../../reference/apis-audio-kit/_o_h_audio.md#oh_audiorenderer_callbacks) by a custom callback method or a null pointer. - ```c++ + ```cpp // Customize a data writing function. int32_t MyOnWriteData( OH_AudioRenderer* renderer, @@ -258,7 +258,7 @@ The following walks you through how to implement simple playback: - Initialize and clear the struct before using it. - ```c++ + ```cpp // Customize a data writing function. int32_t MyOnWriteData( OH_AudioRenderer* renderer, @@ -291,7 +291,7 @@ The following walks you through how to implement simple playback: 4. Create an audio renderer instance. - ```c++ + ```cpp OH_AudioRenderer* audioRenderer; OH_AudioStreamBuilder_GenerateRenderer(builder, &audioRenderer); ``` @@ -305,20 +305,32 @@ The following walks you through how to implement simple playback: | OH_AudioStream_Result OH_AudioRenderer_Start(OH_AudioRenderer* renderer) | Starts the audio renderer. | | OH_AudioStream_Result OH_AudioRenderer_Pause(OH_AudioRenderer* renderer) | Pauses the audio renderer. | | OH_AudioStream_Result OH_AudioRenderer_Stop(OH_AudioRenderer* renderer) | Stops the audio renderer. | - | OH_AudioStream_Result OH_AudioRenderer_Flush(OH_AudioRenderer* renderer) | Flushes written audio data.| + | OH_AudioStream_Result OH_AudioRenderer_Flush(OH_AudioRenderer* renderer) | Flushes obtained audio data.| | OH_AudioStream_Result OH_AudioRenderer_Release(OH_AudioRenderer* renderer) | Releases the audio renderer instance.| 6. Destroy the audio stream builder. When the builder is no longer used, release related resources. - ```c++ + ```cpp OH_AudioStreamBuilder_Destroy(builder); ``` +## Setting the Volume for an Audio Stream + +You can use [OH_AudioRenderer_SetVolume](../../reference/apis-audio-kit/_o_h_audio.md#oh_audiorenderer_setvolume) to set the volume for the current audio stream. + +```cpp +// Volume to set. The value range is [0.0, 1.0]. +float volume = 0.5f; + +// Set the volume for the audio stream. +OH_AudioStream_Result OH_AudioRenderer_SetVolume(audioRenderer, volume); +``` + ## Setting the Low Latency Mode -If the device supports the low-latency channel, you can use the low-latency mode to create a player for a higher-quality audio experience. +If the device supports the low-latency channel and the sampling rate is set to 48000, you can use the low-latency mode to create a player for a higher-quality audio experience. The development process is similar to that in the common playback scenario. The only difference is that you need to set the low delay mode by calling [OH_AudioStreamBuilder_SetLatencyMode()](../../reference/apis-audio-kit/_o_h_audio.md#oh_audiostreambuilder_setlatencymode) when creating an audio stream builder. @@ -328,7 +340,7 @@ The development process is similar to that in the common playback scenario. The The code snippet is as follows: -```C +```cpp OH_AudioStreamBuilder_SetLatencyMode(builder, AUDIOSTREAM_LATENCY_MODE_FAST); ``` @@ -346,7 +358,7 @@ For audio in HOA format, to obtain the correct rendering and playback effect, yo The code snippet is as follows: -```C +```cpp OH_AudioStreamBuilder_SetChannelLayout(builder, CH_LAYOUT_STEREO); ``` @@ -358,9 +370,8 @@ The development process is similar to that in the common playback scenario. The When an audio file in AudioVivid format is played, the frame size is fixed. Therefore, do not call [OH_AudioStreamBuilder_SetFrameSizeInCallback()](../../reference/apis-audio-kit/_o_h_audio.md#oh_audiostreambuilder_setframesizeincallback) to set the frame size in the callback. In addition, when setting the number of audio channels and the audio channel layout, use the sum of the number of sound beds written into the audio source and the number of objects. -The code snippet is as follows: -```C +```cpp // Customize a callback function for simultaneously writing PCM data and metadata. int32_t MyOnWriteDataWithMetadata( OH_AudioRenderer* renderer, diff --git a/en/application-dev/media/audio/using-ohaudio-for-recording.md b/en/application-dev/media/audio/using-ohaudio-for-recording.md index eb1ae6d94800d84bc1da39c333fc002a3866a655..191fd93fb811ee0eea1fc4e3365f9df389c4add5 100644 --- a/en/application-dev/media/audio/using-ohaudio-for-recording.md +++ b/en/application-dev/media/audio/using-ohaudio-for-recording.md @@ -33,14 +33,14 @@ To use APIs for audio recording, import <[native_audiostreambuilder.h](../../ref The following code snippet shows how to use [OH_AudioStreamBuilder_Create](../../reference/apis-audio-kit/_o_h_audio.md#oh_audiostreambuilder_create) to create a builder: -``` +```cpp OH_AudioStreamBuilder* builder; OH_AudioStreamBuilder_Create(&builder, streamType); ``` After the audio service is complete, call [OH_AudioStreamBuilder_Destroy](../../reference/apis-audio-kit/_o_h_audio.md#oh_audiostreambuilder_destroy) to destroy the builder. -``` +```cpp OH_AudioStreamBuilder_Destroy(builder); ``` @@ -50,10 +50,9 @@ Read [OHAudio](../../reference/apis-audio-kit/_o_h_audio.md) for the API referen The following walks you through how to implement simple recording: - 1. Create an audio stream builder. - ```c++ + ```cpp OH_AudioStreamBuilder* builder; OH_AudioStreamBuilder_Create(&builder, AUDIOSTREAM_TYPE_CAPTURER); ``` @@ -62,7 +61,7 @@ The following walks you through how to implement simple recording: After creating the builder for audio recording, set the parameters required. - ```c++ + ```cpp // Set the audio sampling rate. OH_AudioStreamBuilder_SetSamplingRate(builder, 48000); // Set the number of audio channels. @@ -81,7 +80,7 @@ The following walks you through how to implement simple recording: For details about concurrent processing of multiple audio streams, see [Processing Audio Interruption Events](audio-playback-concurrency.md). The procedure is similar, and the only difference is the API programming language in use. - ```c++ + ```cpp // Customize a data reading function. int32_t MyOnReadData( OH_AudioCapturer* capturer, @@ -137,7 +136,7 @@ The following walks you through how to implement simple recording: - Initialize each callback in [OH_AudioCapturer_Callbacks](../../reference/apis-audio-kit/_o_h_audio.md#oh_audiocapturer_callbacks) by a custom callback method or a null pointer. - ```c++ + ```cpp // Customize a data reading function. int32_t MyOnReadData( OH_AudioCapturer* capturer, @@ -171,7 +170,7 @@ The following walks you through how to implement simple recording: - Initialize and clear the struct before using it. - ```c++ + ```cpp // Customize a data reading function. int32_t MyOnReadData( OH_AudioCapturer* capturer, @@ -204,7 +203,7 @@ The following walks you through how to implement simple recording: 4. Create an audio capturer instance. - ```c++ + ```cpp OH_AudioCapturer* audioCapturer; OH_AudioStreamBuilder_GenerateCapturer(builder, &audioCapturer); ``` @@ -215,7 +214,7 @@ The following walks you through how to implement simple recording: | API | Description | | ------------------------------------------------------------ | ------------ | - | OH_AudioStream_Result OH_AudioCapturer_Start(OH_AudioCapturer* capturer) | Starts the audio capturer. | + | OH_AudioStream_Result OH_AudioCapturer_Start(OH_AudioCapturer* capturer) | Starts the audio capturer. | | OH_AudioStream_Result OH_AudioCapturer_Pause(OH_AudioCapturer* capturer) | Pauses the audio capturer. | | OH_AudioStream_Result OH_AudioCapturer_Stop(OH_AudioCapturer* capturer) | Stops the audio capturer. | | OH_AudioStream_Result OH_AudioCapturer_Flush(OH_AudioCapturer* capturer) | Flushes obtained audio data.| @@ -225,7 +224,7 @@ The following walks you through how to implement simple recording: When the builder is no longer used, release related resources. - ```c++ + ```cpp OH_AudioStreamBuilder_Destroy(builder); ``` @@ -241,7 +240,7 @@ The development process is similar to that in the common recording scenario. The Code snippet: -```C +```cpp OH_AudioStream_LatencyMode latencyMode = AUDIOSTREAM_LATENCY_MODE_FAST; OH_AudioStreamBuilder_SetLatencyMode(builder, latencyMode); ``` diff --git a/en/application-dev/media/audio/using-opensl-es-for-playback.md b/en/application-dev/media/audio/using-opensl-es-for-playback.md index f3fd30801b8e53d026f1198e649eb76a0a1b0702..4546c72a48f5bbacf2341293b1615c4407096cdf 100644 --- a/en/application-dev/media/audio/using-opensl-es-for-playback.md +++ b/en/application-dev/media/audio/using-opensl-es-for-playback.md @@ -22,12 +22,12 @@ The following lists the OpenSL ES APIs that have been implemented on OpenHarmony - **SLInterfaceID implemented on OpenHarmony** - | SLInterfaceID | Description | + | SLInterfaceID | Description| | -------- | -------- | - | SL_IID_ENGINE | Universal engine, which provides the interface for creating player objects. | - | SL_IID_PLAY | Provides the player status interface. | - | SL_IID_VOLUME | Provides interfaces for adjusting and reading the volume of audio playback streams. | - | SL_IID_OH_BUFFERQUEUE | Provides the callback registration interface for audio playback stream data. | + | SL_IID_ENGINE | Universal engine, which provides the interface for creating player objects.| + | SL_IID_PLAY | Provides the player status interface.| + | SL_IID_VOLUME | Provides interfaces for adjusting and reading the volume of audio playback streams.| + | SL_IID_OH_BUFFERQUEUE | Provides the callback registration interface for audio playback stream data.| - **Engine APIs implemented on OpenHarmony** - SLresult (\*CreateAudioPlayer) (SLEngineItf self, SLObjectItf \* pPlayer, SLDataSource \*pAudioSrc, SLDataSink \*pAudioSnk, SLuint32 numInterfaces, const SLInterfaceID \* pInterfaceIds, const SLboolean \* pInterfaceRequired) @@ -53,13 +53,13 @@ The following lists the OpenSL ES APIs that have been implemented on OpenHarmony The APIs listed below can be used only after is introduced. - | API | Description | + | API| Description| | -------- | -------- | - | SLresult (\*Enqueue) (SLOHBufferQueueItf self, const void \*buffer, SLuint32 size) | Adds a buffer to the corresponding queue.
For an audio playback operation, this API adds the buffer with audio data to the **filledBufferQ_** queue. For an audio recording operation, this API adds the idle buffer after recording data storage to the **freeBufferQ_** queue.
The **self** parameter indicates the **BufferQueue** object that calls this API.
The **buffer** parameter indicates the pointer to the buffer with audio data or the pointer to the idle buffer after the recording data is stored.
The **size** parameter indicates the size of the buffer. | - | SLresult (\*Clear) (SLOHBufferQueueItf self) | Releases a **BufferQueue** object.
The **self** parameter indicates the **BufferQueue** object that calls this API. | - | SLresult (\*GetState) (SLOHBufferQueueItf self, SLOHBufferQueueState \*state) | Obtains the state of a **BufferQueue** object.
The **self** parameter indicates the **BufferQueue** object that calls this API.
The **state** parameter indicates the pointer to the state of the **BufferQueue** object. | - | SLresult (\*RegisterCallback) (SLOHBufferQueueItf self, SlOHBufferQueueCallback callback, void\* pContext) | Registers a callback.
The **self** parameter indicates the **BufferQueue** object that calls this API.
The **callback** parameter indicates the callback to be registered for the audio playback or recording operation.
The **pContext** parameter indicates the pointer to the audio file to be played for an audio playback operation or the pointer to the audio file to be recorded for an audio recording operation. | - | SLresult (\*GetBuffer) (SLOHBufferQueueItf self, SLuint8\*\* buffer, SLuint32\* size) | Obtains a buffer.
For an audio playback operation, this API obtains an idle buffer from the **freeBufferQ_** queue. For an audio recording operation, this API obtains the buffer that carries recording data from the **filledBufferQ_** queue.
The **self** parameter indicates the **BufferQueue** object that calls this API.
The **buffer** parameter indicates the double pointer to the idle buffer or the buffer carrying recording data.
The **size** parameter indicates the size of the buffer. | + | SLresult (\*Enqueue) (SLOHBufferQueueItf self, const void \*buffer, SLuint32 size) | Adds a buffer to the corresponding queue.
For an audio playback operation, this API adds the buffer with audio data to the **filledBufferQ_** queue. For an audio recording operation, this API adds the idle buffer after recording data storage to the **freeBufferQ_** queue.
The **self** parameter indicates the **BufferQueue** object that calls this API.
The **buffer** parameter indicates the pointer to the buffer with audio data or the pointer to the idle buffer after the recording data is stored.
The **size** parameter indicates the size of the buffer.| + | SLresult (\*Clear) (SLOHBufferQueueItf self) | Releases a **BufferQueue** object.
The **self** parameter indicates the **BufferQueue** object that calls this API.| + | SLresult (\*GetState) (SLOHBufferQueueItf self, SLOHBufferQueueState \*state) | Obtains the state of a **BufferQueue** object.
The **self** parameter indicates the **BufferQueue** object that calls this API.
The **state** parameter indicates the pointer to the state of the **BufferQueue** object.| + | SLresult (\*RegisterCallback) (SLOHBufferQueueItf self, SlOHBufferQueueCallback callback, void\* pContext) | Registers a callback.
The **self** parameter indicates the **BufferQueue** object that calls this API.
The **callback** parameter indicates the callback to be registered for the audio playback or recording operation.
The **pContext** parameter indicates the pointer to the audio file to be played for an audio playback operation or the pointer to the audio file to be recorded for an audio recording operation.| + | SLresult (\*GetBuffer) (SLOHBufferQueueItf self, SLuint8\*\* buffer, SLuint32\* size) | Obtains a buffer.
For an audio playback operation, this API obtains an idle buffer from the **freeBufferQ_** queue. For an audio recording operation, this API obtains the buffer that carries recording data from the **filledBufferQ_** queue.
The **self** parameter indicates the **BufferQueue** object that calls this API.
The **buffer** parameter indicates the double pointer to the idle buffer or the buffer carrying recording data.
The **size** parameter indicates the size of the buffer.| ## Sample Code @@ -73,7 +73,7 @@ Refer to the sample code below to play an audio file. 1. Add the header files. - ```c++ + ```cpp #include "SLES/OpenSLES.h" #include "SLES/OpenSLES_OpenHarmony.h" #include "SLES/OpenSLES_Platform.h" @@ -81,7 +81,7 @@ Refer to the sample code below to play an audio file. 2. Use the **slCreateEngine** API to obtain an **engine** instance. - ```c++ + ```cpp SLObjectItf engineObject = nullptr; slCreateEngine(&engineObject, 0, nullptr, 0, nullptr, nullptr); (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE); @@ -89,14 +89,14 @@ Refer to the sample code below to play an audio file. 3. Obtain the **engineEngine** instance of the **SL_IID_ENGINE** API. - ```c++ + ```cpp SLEngineItf engineEngine = nullptr; (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineEngine); ``` 4. Configure the player and create an **AudioPlayer** instance. - ```c++ + ```cpp SLDataLocator_BufferQueue slBufferQueue = { SL_DATALOCATOR_BUFFERQUEUE, 1 @@ -129,14 +129,14 @@ Refer to the sample code below to play an audio file. 5. Obtain the **bufferQueueItf** instance of the **SL_IID_OH_BUFFERQUEUE** API. - ```c++ + ```cpp SLOHBufferQueueItf bufferQueueItf; (*pcmPlayerObject)->GetInterface(pcmPlayerObject, SL_IID_OH_BUFFERQUEUE, &bufferQueueItf); ``` 6. Open an audio file and register the **BufferQueueCallback** function. - ```c++ + ```cpp static void BufferQueueCallback (SLOHBufferQueueItf bufferQueueItf, void *pContext, SLuint32 size) { SLuint8 *buffer = nullptr; @@ -151,7 +151,7 @@ Refer to the sample code below to play an audio file. 7. Obtain the **playItf** instance of the **SL_PLAYSTATE_PLAYING** API and start playing. - ```c++ + ```cpp SLPlayItf playItf = nullptr; (*pcmPlayerObject)->GetInterface(pcmPlayerObject, SL_IID_PLAY, &playItf); (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_PLAYING); @@ -159,7 +159,7 @@ Refer to the sample code below to play an audio file. 8. Stop playing. - ```c++ + ```cpp (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_STOPPED); (*pcmPlayerObject)->Destroy(pcmPlayerObject); (*engineObject)->Destroy(engineObject); diff --git a/en/application-dev/media/audio/using-opensl-es-for-recording.md b/en/application-dev/media/audio/using-opensl-es-for-recording.md index b7702815fcc802ee778a9b28e127d2b3edd14aa6..b3eb82c2af653be28169b3e58d70a0ec8d548929 100644 --- a/en/application-dev/media/audio/using-opensl-es-for-recording.md +++ b/en/application-dev/media/audio/using-opensl-es-for-recording.md @@ -46,13 +46,13 @@ The following lists the OpenSL ES APIs that have been implemented on OpenHarmony The APIs listed below can be used only after <OpenSLES_OpenHarmony.h> is introduced. - | API| Description| + | API| Description| | -------- | -------- | - | SLresult (\*Enqueue) (SLOHBufferQueueItf self, const void \*buffer, SLuint32 size) | Adds a buffer to the corresponding queue.
For an audio playback operation, this API adds the buffer with audio data to the **filledBufferQ_** queue. For an audio recording operation, this API adds the idle buffer after recording data storage to the **freeBufferQ_** queue.
The **self** parameter indicates the **BufferQueue** object that calls this API.
The **buffer** parameter indicates the pointer to the buffer with audio data or the pointer to the idle buffer after the recording data is stored.
The **size** parameter indicates the size of the buffer.| - | SLresult (\*Clear) (SLOHBufferQueueItf self) | Releases a **BufferQueue** object.
The **self** parameter indicates the **BufferQueue** object that calls this API.| - | SLresult (\*GetState) (SLOHBufferQueueItf self, SLOHBufferQueueState \*state) | Obtains the state of a **BufferQueue** object.
The **self** parameter indicates the **BufferQueue** object that calls this API.
The **state** parameter indicates the pointer to the state of the **BufferQueue** object.| - | SLresult (\*RegisterCallback) (SLOHBufferQueueItf self, SlOHBufferQueueCallback callback, void\* pContext) | Registers a callback.
The **self** parameter indicates the **BufferQueue** object that calls this API.
The **callback** parameter indicates the callback to be registered for the audio playback or recording operation.
The **pContext** parameter indicates the pointer to the audio file to be played for an audio playback operation or the pointer to the audio file to be recorded for an audio recording operation.| - | SLresult (\*GetBuffer) (SLOHBufferQueueItf self, SLuint8\*\* buffer, SLuint32\* size) | Obtains a buffer.
For an audio playback operation, this API obtains an idle buffer from the **freeBufferQ_** queue. For an audio recording operation, this API obtains the buffer that carries recording data from the **filledBufferQ_** queue.
The **self** parameter indicates the **BufferQueue** object that calls this API.
The **buffer** parameter indicates the double pointer to the idle buffer or the buffer carrying recording data.
The **size** parameter indicates the size of the buffer.| + | SLresult (\*Enqueue) (SLOHBufferQueueItf self, const void \*buffer, SLuint32 size) | Adds a buffer to the corresponding queue.
For an audio playback operation, this API adds the buffer with audio data to the **filledBufferQ_** queue. For an audio recording operation, this API adds the idle buffer after recording data storage to the **freeBufferQ_** queue.
The **self** parameter indicates the **BufferQueue** object that calls this API.
The **buffer** parameter indicates the pointer to the buffer with audio data or the pointer to the idle buffer after the recording data is stored.
The **size** parameter indicates the size of the buffer.| + | SLresult (\*Clear) (SLOHBufferQueueItf self) | Releases a **BufferQueue** object.
The **self** parameter indicates the **BufferQueue** object that calls this API.| + | SLresult (\*GetState) (SLOHBufferQueueItf self, SLOHBufferQueueState \*state) | Obtains the state of a **BufferQueue** object.
The **self** parameter indicates the **BufferQueue** object that calls this API.
The **state** parameter indicates the pointer to the state of the **BufferQueue** object.| + | SLresult (\*RegisterCallback) (SLOHBufferQueueItf self, SlOHBufferQueueCallback callback, void\* pContext) | Registers a callback.
The **self** parameter indicates the **BufferQueue** object that calls this API.
The **callback** parameter indicates the callback to be registered for the audio playback or recording operation.
The **pContext** parameter indicates the pointer to the audio file to be played for an audio playback operation or the pointer to the audio file to be recorded for an audio recording operation.| + | SLresult (\*GetBuffer) (SLOHBufferQueueItf self, SLuint8\*\* buffer, SLuint32\* size) | Obtains a buffer.
For an audio playback operation, this API obtains an idle buffer from the **freeBufferQ_** queue. For an audio recording operation, this API obtains the buffer that carries recording data from the **filledBufferQ_** queue.
The **self** parameter indicates the **BufferQueue** object that calls this API.
The **buffer** parameter indicates the double pointer to the idle buffer or the buffer carrying recording data.
The **size** parameter indicates the size of the buffer.| ## Sample Code @@ -66,30 +66,30 @@ Refer to the sample code below to record an audio file. 1. Add the header files. - ```c++ + ```cpp #include "SLES/OpenSLES.h" #include "SLES/OpenSLES_OpenHarmony.h" #include "SLES/OpenSLES_Platform.h" ``` 2. Use the **slCreateEngine** API to create and instantiate an **engine** object. - - ```c++ + + ```cpp SLObjectItf engineObject = nullptr; slCreateEngine(&engineObject, 0, nullptr, 0, nullptr, nullptr); (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE); ``` 3. Obtain the **engineEngine** instance of the **SL_IID_ENGINE** API. - - ```c++ + + ```cpp SLEngineItf engineItf = nullptr; (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineItf); ``` 4. Configure the recorder information (including the input source **audiosource** and output source **audiosink**), and create a **pcmCapturerObject** instance. - - ```c++ + + ```cpp SLDataLocator_IODevice io_device = { SL_DATALOCATOR_IODEVICE, SL_IODEVICE_AUDIOINPUT, @@ -123,26 +123,25 @@ Refer to the sample code below to record an audio file. (*engineItf)->CreateAudioRecorder(engineItf, &pcmCapturerObject, &audioSource, &audioSink, 0, nullptr, nullptr); (*pcmCapturerObject)->Realize(pcmCapturerObject, SL_BOOLEAN_FALSE); - ``` 5. Obtain the **recordItf** instance of the **SL_IID_RECORD** API. - - ```c++ + + ```cpp SLRecordItf recordItf; (*pcmCapturerObject)->GetInterface(pcmCapturerObject, SL_IID_RECORD, &recordItf); ``` 6. Obtain the **bufferQueueItf** instance of the **SL_IID_OH_BUFFERQUEUE** API. - - ```c++ + + ```cpp SLOHBufferQueueItf bufferQueueItf; (*pcmCapturerObject)->GetInterface(pcmCapturerObject, SL_IID_OH_BUFFERQUEUE, &bufferQueueItf); ``` 7. Register the **BufferQueueCallback** function. - - ```c++ + + ```cpp static void BufferQueueCallback(SLOHBufferQueueItf bufferQueueItf, void *pContext, SLuint32 size) { // Obtain the user information passed in during the registration from pContext. @@ -159,17 +158,15 @@ Refer to the sample code below to record an audio file. ``` 8. Start audio recording. - - ```c++ + + ```cpp (*recordItf)->SetRecordState(recordItf, SL_RECORDSTATE_RECORDING); ``` 9. Stop audio recording. - - ```c++ + + ```cpp (*recordItf)->SetRecordState(recordItf, SL_RECORDSTATE_STOPPED); (*pcmCapturerObject)->Destroy(pcmCapturerObject); (*engineObject)->Destroy(engineObject); ``` - - \ No newline at end of file diff --git a/en/application-dev/media/audio/using-right-streamusage-and-sourcetype.md b/en/application-dev/media/audio/using-right-streamusage-and-sourcetype.md index 1d8adcc25a67af8eb6110a6d9b7c822ea22db3c7..88bef17884ece2746f910d2ec1790692030b356b 100644 --- a/en/application-dev/media/audio/using-right-streamusage-and-sourcetype.md +++ b/en/application-dev/media/audio/using-right-streamusage-and-sourcetype.md @@ -105,7 +105,6 @@ Common methods for setting the audio playback stream type are as follows: Set the **audioRendererInfo** [property](../../reference/apis-media-kit/js-apis-media.md#properties) of the AVPlayer. **AVPlayer.audioRendererInfo** is of the **audio.AudioRendererInfo** type. You can use **AudioRendererInfo.usage** to specify [StreamUsage](../../reference/apis-audio-kit/js-apis-audio.md#streamusage). > **NOTE** - > > The **audioRendererInfo** property of the AVPlayer can be set only in the initialized state. > > If the application does not set this property, the AVPlayer performs default processing. If the media source contains videos, the default value of **usage** is **STREAM_USAGE_MOVIE**. Otherwise, the default value of **usage** is **STREAM_USAGE_MUSIC**. diff --git a/en/application-dev/media/audio/using-toneplayer-for-playback.md b/en/application-dev/media/audio/using-toneplayer-for-playback.md index a16669efc0a7b49b9a71cbf9a4758899f8baf83d..f57c08d358275450f5ef6354acacc284af5f8139 100644 --- a/en/application-dev/media/audio/using-toneplayer-for-playback.md +++ b/en/application-dev/media/audio/using-toneplayer-for-playback.md @@ -2,41 +2,39 @@ TonePlayer9+ provides APIs for playing and managing Dual Tone Multi Frequency (DTMF) tones, such as dial tones, ringback tones, supervisory tones, and proprietary tones. The main task of the TonePlayer is to generate sine waves of different frequencies by using the built-in algorithm based on the [ToneType](../../reference/apis-audio-kit/js-apis-audio-sys.md#tonetype9) and add the sine waves to create a sound. The sound can then be played by using the [AudioRenderer](../../reference/apis-audio-kit/js-apis-audio.md#audiorenderer8), and the playback task can also be managed by using the [AudioRenderer](../../reference/apis-audio-kit/js-apis-audio.md#audiorenderer8). The full process includes loading the DTMF tone configuration, starting DTMF tone playing, stopping the playback, and releasing the resources associated with the **TonePlayer** object. For details about the APIs, see the [TonePlayer API Reference](../../reference/apis-audio-kit/js-apis-audio-sys.md#toneplayer9). - ## Supported Tone Types The table below lists the supported [ToneType](../../reference/apis-audio-kit/js-apis-audio-sys.md#tonetype9)s. You can call **load()** with **audio.ToneType.*type*** as a parameter to load the tone resource of the specified type. -| Tone Type | Value | Description | +| Tone Type| Value| Description| | -------- | -------- | -------- | -| TONE_TYPE_DIAL_0 | 0 | DTMF tone of key 0. | -| TONE_TYPE_DIAL_1 | 1 | DTMF tone of key 1. | -| TONE_TYPE_DIAL_2 | 2 | DTMF tone of key 2. | -| TONE_TYPE_DIAL_3 | 3 | DTMF tone of key 3. | -| TONE_TYPE_DIAL_4 | 4 | DTMF tone of key 4. | -| TONE_TYPE_DIAL_5 | 5 | DTMF tone of key 5. | -| TONE_TYPE_DIAL_6 | 6 | DTMF tone of key 6. | -| TONE_TYPE_DIAL_7 | 7 | DTMF tone of key 7. | -| TONE_TYPE_DIAL_8 | 8 | DTMF tone of key 8. | -| TONE_TYPE_DIAL_9 | 9 | DTMF tone of key 9. | -| TONE_TYPE_DIAL_S | 10 | DTMF tone of the star key (*). | -| TONE_TYPE_DIAL_P | 11 | DTMF tone of the pound key (#). | -| TONE_TYPE_DIAL_A | 12 | DTMF tone of key A. | -| TONE_TYPE_DIAL_B | 13 | DTMF tone of key B. | -| TONE_TYPE_DIAL_C | 14 | DTMF tone of key C. | -| TONE_TYPE_DIAL_D | 15 | DTMF tone of key D. | -| TONE_TYPE_COMMON_SUPERVISORY_DIAL | 100 | Supervisory tone - dial tone. | -| TONE_TYPE_COMMON_SUPERVISORY_BUSY | 101 | Supervisory tone - busy. | -| TONE_TYPE_COMMON_SUPERVISORY_CONGESTION | 102 | Supervisory tone - congestion. | -| TONE_TYPE_COMMON_SUPERVISORY_RADIO_ACK | 103 | Supervisory tone - radio path acknowledgment. | -| TONE_TYPE_COMMON_SUPERVISORY_RADIO_NOT_AVAILABLE | 104 | Supervisory tone - radio path not available. | -| TONE_TYPE_COMMON_SUPERVISORY_CALL_WAITING | 106 | Supervisory tone - call waiting tone. | -| TONE_TYPE_COMMON_SUPERVISORY_RINGTONE | 107 | Supervisory tone - ringing tone. | -| TONE_TYPE_COMMON_PROPRIETARY_BEEP | 200 | Proprietary tone - beep tone. | -| TONE_TYPE_COMMON_PROPRIETARY_ACK | 201 | Proprietary tone - ACK. | -| TONE_TYPE_COMMON_PROPRIETARY_PROMPT | 203 | Proprietary tone - PROMPT. | -| TONE_TYPE_COMMON_PROPRIETARY_DOUBLE_BEEP | 204 | Proprietary tone - double beep tone. | - +| TONE_TYPE_DIAL_0 | 0 | DTMF tone of key 0.| +| TONE_TYPE_DIAL_1 | 1 | DTMF tone of key 1.| +| TONE_TYPE_DIAL_2 | 2 | DTMF tone of key 2.| +| TONE_TYPE_DIAL_3 | 3 | DTMF tone of key 3.| +| TONE_TYPE_DIAL_4 | 4 | DTMF tone of key 4.| +| TONE_TYPE_DIAL_5 | 5 | DTMF tone of key 5.| +| TONE_TYPE_DIAL_6 | 6 | DTMF tone of key 6.| +| TONE_TYPE_DIAL_7 | 7 | DTMF tone of key 7.| +| TONE_TYPE_DIAL_8 | 8 | DTMF tone of key 8.| +| TONE_TYPE_DIAL_9 | 9 | DTMF tone of key 9.| +| TONE_TYPE_DIAL_S | 10 | DTMF tone of the star key (*).| +| TONE_TYPE_DIAL_P | 11 | DTMF tone of the pound key (#).| +| TONE_TYPE_DIAL_A | 12 | DTMF tone of key A.| +| TONE_TYPE_DIAL_B | 13 | DTMF tone of key B.| +| TONE_TYPE_DIAL_C | 14 | DTMF tone of key C.| +| TONE_TYPE_DIAL_D | 15 | DTMF tone of key D.| +| TONE_TYPE_COMMON_SUPERVISORY_DIAL | 100 | Supervisory tone - dial tone.| +| TONE_TYPE_COMMON_SUPERVISORY_BUSY | 101 | Supervisory tone - busy.| +| TONE_TYPE_COMMON_SUPERVISORY_CONGESTION | 102 | Supervisory tone - congestion.| +| TONE_TYPE_COMMON_SUPERVISORY_RADIO_ACK | 103 | Supervisory tone - radio path acknowledgment.| +| TONE_TYPE_COMMON_SUPERVISORY_RADIO_NOT_AVAILABLE | 104 | Supervisory tone - radio path not available.| +| TONE_TYPE_COMMON_SUPERVISORY_CALL_WAITING | 106 | Supervisory tone - call waiting tone.| +| TONE_TYPE_COMMON_SUPERVISORY_RINGTONE | 107 | Supervisory tone - ringing tone.| +| TONE_TYPE_COMMON_PROPRIETARY_BEEP | 200 | Proprietary tone - beep tone.| +| TONE_TYPE_COMMON_PROPRIETARY_ACK | 201 | Proprietary tone - ACK.| +| TONE_TYPE_COMMON_PROPRIETARY_PROMPT | 203 | Proprietary tone - PROMPT.| +| TONE_TYPE_COMMON_PROPRIETARY_DOUBLE_BEEP | 204 | Proprietary tone - double beep tone.| ## How to Develop @@ -48,9 +46,10 @@ To implement audio playback with the TonePlayer, perform the following steps: import { audio } from '@kit.AudioKit'; let audioRendererInfo: audio.AudioRendererInfo = { - usage : audio.StreamUsage.STREAM_USAGE_DTMF, - rendererFlags : 0 + usage: audio.StreamUsage.STREAM_USAGE_DTMF, // Audio stream usage type: DTMF. Set this parameter based on the service scenario. + rendererFlags: 0 // AudioRenderer flag. }; + async function createTonePlayer() { let tonePlayerPromise = await audio.createTonePlayer(audioRendererInfo); } @@ -60,7 +59,7 @@ To implement audio playback with the TonePlayer, perform the following steps: ```ts async function load() { - await tonePlayerPromise.load(audio.ToneType.TONE_TYPE_DIAL_0); + await tonePlayerPromise.load(audio.ToneType.TONE_TYPE_DIAL_0); } ``` @@ -68,7 +67,7 @@ To implement audio playback with the TonePlayer, perform the following steps: ```ts async function start() { - await tonePlayerPromise.start(); + await tonePlayerPromise.start(); } ``` @@ -76,7 +75,7 @@ To implement audio playback with the TonePlayer, perform the following steps: ```ts async function stop() { - await tonePlayerPromise.stop(); + await tonePlayerPromise.stop(); } ``` @@ -84,20 +83,18 @@ To implement audio playback with the TonePlayer, perform the following steps: ```ts async function release() { - await tonePlayerPromise.release(); + await tonePlayerPromise.release(); } ``` If the APIs are not called in the preceding sequence, the error code **6800301 NAPI_ERR_SYSTEM** is returned. - ## Sample Code Refer to the following code to play the DTMF tone when the dial key on the keyboard is pressed. To prevent the UI thread from being blocked, most **TonePlayer** calls are asynchronous. Each API provides the callback and promise functions. The following examples use the promise functions. For more information, see [TonePlayer](../../reference/apis-audio-kit/js-apis-audio-sys.md#toneplayer9). - ```ts import { audio } from '@kit.AudioKit'; import { BusinessError } from '@kit.BasicServicesKit'; @@ -109,13 +106,13 @@ async function testTonePlayerPromise(type: audio.ToneType) { if (timerPro) clearTimeout(timerPro); let tonePlayerPromise: audio.TonePlayer; let audioRendererInfo: audio.AudioRendererInfo = { - usage : audio.StreamUsage.STREAM_USAGE_DTMF, - rendererFlags : 0 + usage: audio.StreamUsage.STREAM_USAGE_DTMF, // Audio stream usage type: DTMF. Set this parameter based on the service scenario. + rendererFlags: 0 // AudioRenderer flag. }; timerPro = setTimeout(async () => { try { console.info('testTonePlayerPromise: createTonePlayer'); - // Create a DTMF player. + // Create a DTMF player. tonePlayerPromise = await audio.createTonePlayer(audioRendererInfo); console.info('testTonePlayerPromise: createTonePlayer-success'); console.info(`testTonePlayerPromise: load type: ${type}`); @@ -146,5 +143,4 @@ async function testTonePlayerPromise(type: audio.ToneType) { async function testTonePlayer() { testTonePlayerPromise(audio.ToneType.TONE_TYPE_DIAL_0); } - ``` diff --git a/en/application-dev/media/audio/volume-management.md b/en/application-dev/media/audio/volume-management.md index 1a549e7ee834e8df405d6f791e71fcc051627c35..ea77b202c070cfdf5400bf45d39df6e78b03ee1e 100644 --- a/en/application-dev/media/audio/volume-management.md +++ b/en/application-dev/media/audio/volume-management.md @@ -4,7 +4,7 @@ You can use different APIs to manage the system volume and audio stream volume. ## System Volume -**AudioVolumeManager** is provided for system volume management. Before using this API, you must call **getVolumeManager()** to obtain an **AudioVolumeManager** instance. +**AudioVolumeManager** is provided for system volume management. Before using this API, you must call [getVolumeManager()](../../reference/apis-audio-kit/js-apis-audio.md#getvolumemanager9) to obtain an **AudioVolumeManager** instance. Currently, **AudioVolumeManager** can be used to obtain volume information and listen for volume changes. It cannot be used to adjust the system volume. If you want to adjust the system volume, follow the instructions provided in [Adjusting the System Volume Using the Volume Panel](#adjusting-the-system-volume-using-the-volume-panel). @@ -41,6 +41,88 @@ An application cannot directly adjust the system volume. However, it can invoke To achieve this, you can use the ArkTS component **AVVolumePanel** in your application. For details, see the [AVVolumePanel Reference](../../reference/apis-audio-kit/ohos-multimedia-avvolumepanel.md). +## Application Volume + +**AudioVolumeManager** is provided for application volume management. Before using this API, you must call [getVolumeManager()](../../reference/apis-audio-kit/js-apis-audio.md#getvolumemanager9) to obtain an **AudioVolumeManager** instance. + +When [volume mode](../../reference/apis-audio-kit/js-apis-audio.md#audiovolumemode18) is set to **APP_INDIVIDUAL**, you can set and query the application volume by calling the APIs in the following sample. + +### Adjusting the Application Volume + +```ts +import { audio } from '@kit.AudioKit'; + +let audioManager = audio.getAudioManager(); +let audioVolumeManager = audioManager.getVolumeManager(); + +// Set the volume (ranging from 0 to 100) for the application. +audioVolumeManager.setAppVolumePercentage(20).then(() => { + console.info(`set app volume success.`); +}); + +// Query the application volume. +audioVolumeManager.getAppVolumePercentage().then((value: number) => { + console.info(`app volume is ${value}.`); +}); + +// Subscribe to the application volume change event. For the same event, if the callback parameter passed to the off API is the same as that passed to the on API, the off API cancels the subscription registered with the specified callback parameter. +let appVolumeChangeCallback = (volumeEvent: audio.VolumeEvent) => { + console.info(`VolumeType of stream: ${volumeEvent.volumeType} `); + console.info(`Volume level: ${volumeEvent.volume} `); + console.info(`Whether to updateUI: ${volumeEvent.updateUi} `); +}; +audioVolumeManager.on('appVolumeChange', appVolumeChangeCallback); +audioVolumeManager.off('appVolumeChange', appVolumeChangeCallback); + +// Cancel all subscriptions to the event. +audioVolumeManager.off('appVolumeChange'); +``` + + +### Adjusting the Application Volume Based on the UID (for System Applications Only) + +```ts +import { audio } from '@kit.AudioKit'; + +let uid: number = 20010041; // Application ID. +let audioManager = audio.getAudioManager(); +let audioVolumeManager = audioManager.getVolumeManager(); + +// Set the volume (ranging from 0 to 100) for an application. +let volume: number = 20; // Volume to set. +audioVolumeManager.setAppVolumePercentageForUid(uid, volume).then(() => { + console.info(`set app volume success.`); +}); + +// Obtain the volume (ranging from 0 to 100) of an application. +audioVolumeManager.getAppVolumePercentageForUid(uid).then((value: number) => { + console.info(`app volume is ${value}.`); +}); + +// Check whether the application volume is muted. +audioVolumeManager.setAppVolumePercentageForUid(uid, true).then((value: boolean) => { + console.info(`app muted state is ${value}.`); +}); + +// Set the application mute state. +audioVolumeManager.setAppVolumePercentageForUid(uid, true).then(() => { + console.info(`set app mute state success.`); +}); + +// Subscribe to the application volume change event. For the same event, if the callback parameter passed to the off API is the same as that passed to the on API, the off API cancels the subscription registered with the specified callback parameter. +let appVolumeChangeForUidCallback = (volumeEvent: audio.VolumeEvent) => { + console.info(`VolumeType of stream: ${volumeEvent.volumeType} `); + console.info(`Volume level: ${volumeEvent.volume} `); + console.info(`Whether to updateUI: ${volumeEvent.updateUi} `); +}; +audioVolumeManager.on('appVolumeChangeForUid', uid, appVolumeChangeForUidCallback); +audioVolumeManager.off('appVolumeChangeForUid', appVolumeChangeForUidCallback); + +// Cancel all subscriptions to the event. +audioVolumeManager.off('appVolumeChangeForUid'); +``` + + ## Audio Stream Volume The **setVolume()** API in both the **AVPlayer** and **AudioRenderer** classes can be used to set the audio stream volume. The code snippet below uses the API in the [AVPlayer](../../reference/apis-media-kit/js-apis-media.md#mediacreateavplayer9) class: diff --git a/en/application-dev/media/avcodec/Readme-EN.md b/en/application-dev/media/avcodec/Readme-EN.md index d483bc8316bbe63dedc7c4d4f1e556d67c16388c..aa0b901f57d6dc0d546612ad105d6a74e7f09d3e 100644 --- a/en/application-dev/media/avcodec/Readme-EN.md +++ b/en/application-dev/media/avcodec/Readme-EN.md @@ -2,13 +2,16 @@ - [Introduction to AVCodec Kit](avcodec-kit-intro.md) - [AVCodec Supported Formats](avcodec-support-formats.md) -- Audio and Video Codecs +- Audio and Video Codecs - [Obtaining Supported Codecs](obtain-supported-codecs.md) - [Audio Encoding](audio-encoding.md) - [Audio Decoding](audio-decoding.md) - [Video Encoding](video-encoding.md) - [Temporally Scalable Video Encoding](video-encoding-temporal-scalability.md) + - [Video Encoding Configurations for Typical Scenarios](video-encoding-configuration-typical-scenarios.md) - [Video Decoding](video-decoding.md) -- Media Data Muxing and Demuxing + - [Concurrently Creating a Video Decoder and Initializing NativeWindow](parallel-decoding-nativeWindow.md) + - [Video Variable Frame Rate](video-variable-refreshrate.md) +- Media Data Muxing and Demuxing - [Media Data Muxing](audio-video-muxer.md) - [Media Data Demuxing](audio-video-demuxer.md) diff --git a/en/application-dev/media/avcodec/audio-decoding.md b/en/application-dev/media/avcodec/audio-decoding.md index 05a015231b1f1a860c20a9b2a983c20a5c675afd..1b1ba18de0d2b28cb7b8af177c9a3b32af1fbda0 100644 --- a/en/application-dev/media/avcodec/audio-decoding.md +++ b/en/application-dev/media/avcodec/audio-decoding.md @@ -61,7 +61,7 @@ target_link_libraries(sample PUBLIC libnative_media_acodec.so) ```cpp // Namespace of the C++ standard library. using namespace std; - // Create a decoder by name. + // Create a decoder by codec name. OH_AVCapability *capability = OH_AVCodec_GetCapability(OH_AVCODEC_MIMETYPE_AUDIO_MPEG, false); const char *name = OH_AVCapability_GetName(capability); OH_AVCodec *audioDec_ = OH_AudioCodec_CreateByName(name); @@ -97,12 +97,16 @@ target_link_libraries(sample PUBLIC libnative_media_acodec.so) Register the **OH_AVCodecCallback** struct that defines the following callback function pointers: - **OH_AVCodecOnError**, a callback used to report a codec operation error - - **OH_AVCodecOnStreamChanged**, a callback used to report a codec stream change, for example, audio channel change + - **OH_AVCodecOnStreamChanged**, a callback used to report stream information changes, including changes in the sampling rate, number of audio channels, and audio sampling format. The decoding formats that can detect these changes include AAC, FLAC, MP3, and VORBIS. (This callback is supported since API version 15.) - **OH_AVCodecOnNeedInputBuffer**, a callback used to report input data required, which means that the decoder is ready for receiving data - **OH_AVCodecOnNewOutputBuffer**, a callback used to report output data generated, which means that decoding is complete You need to process the callback functions to ensure that the decoder runs properly. + > **NOTE** + > + > You are not advised to perform time-consuming operations in the callback. + ```cpp // Implement the OH_AVCodecOnError callback function. static void OnError(OH_AVCodec *codec, int32_t errorCode, void *userData) @@ -115,8 +119,20 @@ target_link_libraries(sample PUBLIC libnative_media_acodec.so) static void OnOutputFormatChanged(OH_AVCodec *codec, OH_AVFormat *format, void *userData) { (void)codec; - (void)format; (void)userData; + // Callback processing after the decoding output parameters are changed. The application performs processing as required. + int32_t sampleRate; + int32_t channelCount; + int32_t sampleFormat; + if (OH_AVFormat_GetIntValue(format, OH_MD_KEY_AUD_SAMPLE_RATE, &sampleRate)) { + // Check whether the sampling rate changes and perform processing as required. + } + if (OH_AVFormat_GetIntValue(format, OH_MD_KEY_AUD_CHANNEL_COUNT, &channelCount)) { + // Check whether the number of audio channels changes and perform processing as required. + } + if (OH_AVFormat_GetIntValue(format, OH_MD_KEY_AUDIO_SAMPLE_FORMAT, &sampleFormat)) { + // Check whether the audio sampling format changes and perform processing as required. + } } // Implement the OH_AVCodecOnNeedInputBuffer callback function. static void OnInputBufferAvailable(OH_AVCodec *codec, uint32_t index, OH_AVBuffer *data, void *userData) @@ -145,28 +161,32 @@ target_link_libraries(sample PUBLIC libnative_media_acodec.so) OH_AVCodecCallback cb_ = {&OnError, &OnOutputFormatChanged, &OnInputBufferAvailable, &OnOutputBufferAvailable}; int32_t ret = OH_AudioCodec_RegisterCallback(audioDec_, cb_, signal_); if (ret != AVCS_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` -4. (Optional) Call **OH_AudioCodec_SetDecryptionConfig** to set the decryption configuration. Call this API after the media key system information is obtained but before **Prepare()** is called. For details about how to obtain such information, see step 4 in [Media Data Demuxing](audio-video-demuxer.md). For details about DRM APIs, see [DRM](../../reference/apis-drm-kit/_drm.md). +4. (Optional) Call **OH_AudioCodec_SetDecryptionConfig** to set the decryption configuration. + + Call this API after the media key system information is obtained but before **Prepare()** is called. For details about how to obtain such information, see step 4 in [Media Data Demuxing](audio-video-demuxer.md). + + For details about DRM APIs, see [DRM](../../reference/apis-drm-kit/_drm.md). Add the header files. ```c++ - #include +#include #include #include #include ``` Link the dynamic library in the CMake script. - + ``` cmake - target_link_libraries(sample PUBLIC libnative_drm.so) +target_link_libraries(sample PUBLIC libnative_drm.so) ``` - + The following is the sample code: - ```c++ +```c++ // Create a media key system based on the media key system information. The following uses com.clearplay.drm as an example. MediaKeySystem *system = nullptr; int32_t ret = OH_MediaKeySystem_Create("com.clearplay.drm", &system); @@ -174,9 +194,9 @@ target_link_libraries(sample PUBLIC libnative_media_acodec.so) printf("create media key system failed"); return; } - + // Create a media key session. - MediaKeySession *session = nullptr; +MediaKeySession *session = nullptr; DRM_ContentProtectionLevel contentProtectionLevel = CONTENT_PROTECTION_LEVEL_SW_CRYPTO; ret = OH_MediaKeySystem_CreateMediaKeySession(system, &contentProtectionLevel, &session); if (ret != DRM_OK) { @@ -193,24 +213,25 @@ target_link_libraries(sample PUBLIC libnative_media_acodec.so) bool secureAudio = false; ret = OH_AudioCodec_SetDecryptionConfig(audioDec_, session, secureAudio); ``` - + 5. Call **OH_AudioCodec_Configure()** to configure the decoder. Key values of configuration options are described as follows: - | | Description | AAC | FLAC| Vorbis | MPEG | G711mu | AMR (AMR-NB and AMR-WB) | APE | - | ---------------------------- | :----------------------------------------------------------: | :--------------------------------: | :--: | :--------------------------------: | :--: | :-----------------: | :-------------------------------: | :-------------------------------: | - | OH_MD_KEY_AUD_SAMPLE_RATE | Sampling rate | Mandatory | Mandatory| Mandatory | Mandatory| Mandatory | Mandatory | Mandatory | - | OH_MD_KEY_AUD_CHANNEL_COUNT | Number of audio channels | Mandatory | Mandatory| Mandatory | Mandatory| Mandatory | Mandatory | Mandatory | - | OH_MD_KEY_MAX_INPUT_SIZE | Maximum input size | Optional | Optional| Optional | Optional| Optional | Optional | Optional | - | OH_MD_KEY_AAC_IS_ADTS | ADTS or not | Optional (Default value: 1 latm) | - | - | - | - | - | - | - | MD_KEY_AUDIO_SAMPLE_FORMAT | Output audio stream format | Optional (SAMPLE_S16LE, SAMPLE_F32LE)| - | Optional (SAMPLE_S16LE, SAMPLE_F32LE)| Optional| Optional (default: SAMPLE_S16LE)| Optional (SAMPLE_S16LE, SAMPLE_F32LE)| Optional | - | MD_KEY_BITRATE | Optional | Optional | Optional| Optional | Optional| Optional | Optional | Optional | - | MD_KEY_IDENTIFICATION_HEADER | ID Header | - | - | Mandatory (Either this parameter or **MD_KEY_CODEC_CONFIG** must be set.) | - | - | - | - | - | MD_KEY_SETUP_HEADER | Setup Header | - | - | Mandatory (Either this parameter or **MD_KEY_CODEC_CONFIG** must be set.) | - | - | - | - | - | MD_KEY_CODEC_CONFIG | MD_KEY_SETUP_HEADERID Header+Common Header+Setup Header stitching| - | | Mandatory (Either this parameter or the combination of **MD_KEY_IDENTIFICATION_HEADER** and **MD_KEY_SETUP_HEADER** must be selected.) | - | - | - | - | + | key | Description | AAC | FLAC| Vorbis | MPEG | G711mu | AMR (AMR-NB and AMR-WB) | APE | + | ---------------------------- | :--------------: | :--------------------------------: | :--: | :--------------------------------: | :--: | :-----------------: | :-------------------------------: | :--: | + | OH_MD_KEY_AUD_SAMPLE_RATE | Sampling rate | Mandatory | Mandatory| Mandatory | Mandatory| Mandatory | Mandatory | Mandatory| + | OH_MD_KEY_AUD_CHANNEL_COUNT | Number of audio channels | Mandatory | Mandatory| Mandatory | Mandatory| Mandatory | Mandatory | Mandatory| + | OH_MD_KEY_MAX_INPUT_SIZE | Maximum input size | Optional | Optional| Optional | Optional| Optional | Optional | Optional| + | OH_MD_KEY_AAC_IS_ADTS | ADTS or not | Optional (defaults to **1**) | - | - | - | - | - | - | + | OH_MD_KEY_AUDIO_SAMPLE_FORMAT | Output audio stream format | Optional (SAMPLE_S16LE, SAMPLE_F32LE)| Optional| Optional (SAMPLE_S16LE, SAMPLE_F32LE)| Optional| Optional (default: SAMPLE_S16LE)| Optional (SAMPLE_S16LE, SAMPLE_F32LE)| Optional| + | OH_MD_KEY_BITRATE | Bit rate | Optional | Optional| Optional | Optional| Optional | Optional | Optional| + | OH_MD_KEY_IDENTIFICATION_HEADER | ID Header | - | - | Mandatory (Either this parameter or **MD_KEY_CODEC_CONFIG** must be set.) | - | - | - | - | + | OH_MD_KEY_SETUP_HEADER | Setup Header | - | - | Mandatory (Either this parameter or **MD_KEY_CODEC_CONFIG** must be set.) | - | - | - | - | + | OH_MD_KEY_CODEC_CONFIG | Codec-specific data| Optional | - | Mandatory (Either this parameter or the combination of **MD_KEY_IDENTIFICATION_HEADER** and **MD_KEY_SETUP_HEADER** must be selected.) | - | - | - | Optional| The sample below lists the value range of each audio decoding type. + | Audio Decoding Type| Sampling Rate (Hz) | Audio Channel Count| | ----------- | ---------------------------------------------------------------------------------------------- | :----: | | AAC | 8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000, 64000, 88200, 96000 | 1–8 | @@ -247,7 +268,7 @@ target_link_libraries(sample PUBLIC libnative_media_acodec.so) // Configure the decoder. ret = OH_AudioCodec_Configure(audioDec_, format); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` @@ -256,7 +277,7 @@ target_link_libraries(sample PUBLIC libnative_media_acodec.so) ```cpp ret = OH_AudioCodec_Prepare(audioDec_); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` @@ -272,13 +293,13 @@ target_link_libraries(sample PUBLIC libnative_media_acodec.so) // Start decoding. ret = OH_AudioCodec_Start(audioDec_); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` 8. (Optional) Call **OH_AVCencInfo_SetAVBuffer()** to set the Common Encryption Scheme (CENC) information. - If the content being played is DRM encrypted and demuxing is performed by the upper-layer application, call **OH_AVCencInfo_SetAVBuffer()** to set the CENC information to the AVBuffer so that the media data can be decrypted in the AVBuffer. + If the content being played is DRM encrypted and [demuxing](audio-video-demuxer.md#media-data-demuxing) is performed by the upper-layer application, call **OH_AVCencInfo_SetAVBuffer()** to set the CENC information to the AVBuffer so that the media data can be decrypted in the AVBuffer. Add the header file. @@ -310,43 +331,45 @@ target_link_libraries(sample PUBLIC libnative_media_acodec.so) // Create a CencInfo instance. OH_AVCencInfo *cencInfo = OH_AVCencInfo_Create(); if (cencInfo == nullptr) { - // Exception handling. + // Handle exceptions. } // Set the decryption algorithm. OH_AVErrCode errNo = OH_AVCencInfo_SetAlgorithm(cencInfo, DRM_ALG_CENC_AES_CTR); if (errNo != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } // Set KeyId and Iv. errNo = OH_AVCencInfo_SetKeyIdAndIv(cencInfo, keyId, keyIdLen, iv, ivLen); if (errNo != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } // Set the sample information. errNo = OH_AVCencInfo_SetSubsampleInfo(cencInfo, encryptedBlockCount, skippedBlockCount, firstEncryptedOffset, subsampleCount, subsamples); if (errNo != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } // Set the mode. KeyId, Iv, and SubSamples have been set. errNo = OH_AVCencInfo_SetMode(cencInfo, DRM_CENC_INFO_KEY_IV_SUBSAMPLES_SET); if (errNo != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } // Set CencInfo to the AVBuffer. errNo = OH_AVCencInfo_SetAVBuffer(cencInfo, buffer); if (errNo != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } // Destroy the CencInfo instance. errNo = OH_AVCencInfo_Destroy(cencInfo); if (errNo != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` 9. Call **OH_AudioCodec_PushInputBuffer()** to write the data to decode. + You should fill in complete input data before calling this API. + To indicate the End of Stream (EOS), pass in the **AVCODEC_BUFFER_FLAGS_EOS** flag. ```c++ @@ -374,11 +397,13 @@ target_link_libraries(sample PUBLIC libnative_media_acodec.so) OH_AVBuffer_SetBufferAttr(buffer, &attr); int32_t ret = OH_AudioCodec_PushInputBuffer(audioDec_, index); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` -10. Call **OH_AudioCodec_FreeOutputBuffer()** to output decoded PCM streams. +10. Call **OH_AudioCodec_FreeOutputBuffer()** to release the decoded data. + + Once you have retrieved the decoded PCM stream, call **OH_AudioCodec_FreeOutputBuffer()** to free up the data. ```c++ @@ -388,39 +413,39 @@ target_link_libraries(sample PUBLIC libnative_media_acodec.so) OH_AVCodecBufferAttr attr = {0}; ret = OH_AVBuffer_GetBufferAttr(data, &attr); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } // Write the decoded data (specified by data) to the output file. pcmOutputFile_.write(reinterpret_cast(OH_AVBuffer_GetAddr(data)), attr.size); ret = OH_AudioCodec_FreeOutputBuffer(audioDec_, index); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } if (attr.flags == AVCODEC_BUFFER_FLAGS_EOS) { - // End + // End. } ``` 11. (Optional) Call **OH_AudioCodec_Flush()** to refresh the decoder. - After **OH_AudioCodec_Flush()** is called, the decoder remains in the running state, but the current queue is cleared and the buffer storing the decoded data is freed. To continue decoding, you must call **OH_AudioCodec_Start()** again. + After **OH_AudioCodec_Flush()** is called, the decoder remains in the running state, but the current queue is cleared and the buffer storing the decoded data is freed. To continue decoding, you must call **OH_AudioCodec_Start()** again. - You need to call **OH_AudioCodec_Start()** in the following cases: + You need to call **OH_AudioCodec_Start()** in the following cases: - * The EOS of the file is reached. - * An error with **OH_AudioCodec_IsValid** set to **true** (indicating that the execution can continue) occurs. + * The EOS of the file is reached. + * An error with **OH_AudioCodec_IsValid** set to **true** (indicating that the execution can continue) occurs. ```c++ // Refresh the decoder. ret = OH_AudioCodec_Flush(audioDec_); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } // Start decoding again. ret = OH_AudioCodec_Start(audioDec_); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` @@ -432,22 +457,24 @@ target_link_libraries(sample PUBLIC libnative_media_acodec.so) // Reset the decoder. ret = OH_AudioCodec_Reset(audioDec_); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } // Reconfigure the decoder. ret = OH_AudioCodec_Configure(audioDec_, format); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` 13. Call **OH_AudioCodec_Stop()** to stop the decoder. + After the codec is stopped, you can call **OH_AudioCodec_Start()** to start it again. If you have passed specific data in the previous **OH_AudioCodec_Start()** for the codec, you must pass it again. + ```c++ // Stop the decoder. ret = OH_AudioCodec_Stop(audioDec_); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` @@ -461,7 +488,7 @@ target_link_libraries(sample PUBLIC libnative_media_acodec.so) // Call OH_AudioCodec_Destroy to destroy the decoder. ret = OH_AudioCodec_Destroy(audioDec_); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } else { audioDec_ = NULL; // The decoder cannot be destroyed repeatedly. } diff --git a/en/application-dev/media/avcodec/audio-encoding.md b/en/application-dev/media/avcodec/audio-encoding.md index b80d3cabc9af12475d8af3f51fbae88f1abd22ed..14b3f9c27e8517977727dec237bedad3f5e44c5f 100644 --- a/en/application-dev/media/avcodec/audio-encoding.md +++ b/en/application-dev/media/avcodec/audio-encoding.md @@ -10,10 +10,10 @@ For details about the supported encoding capabilities, see [AVCodec Supported Fo - Audio recording - Record and pass in PCM data, and encode the data into streams in the desired format. + Record incoming PCM data, encode it into the desired stream format, and then [wrap](audio-video-muxer.md#media-data-muxing) it in the target file format. - Audio editing - Export edited PCM data, and encode the data into streams in the desired format. + When exporting edited PCM data as an audio file, the PCM data must be encoded into the appropriate audio format and then [wrapped](audio-video-muxer.md#media-data-muxing) into a file. > **NOTE** > > AAC encoders adopt the VBR mode by default, which may differ in the configured parameters. @@ -93,17 +93,21 @@ target_link_libraries(sample PUBLIC libnative_media_acodec.so) AEncBufferSignal *signal_; ``` -3. Call **OH_AudioCodec_RegisterCallback()** to register callback functions. +3. Call **OH_AudioCodec_RegisterCallback()** to register callback functions. Register the **OH_AVCodecCallback** struct that defines the following callback function pointers: - **OH_AVCodecOnError**, a callback used to report a codec operation error - - **OH_AVCodecOnStreamChanged**, a callback used to report a codec stream change, for example, audio channel change + - **OH_AVCodecOnStreamChanged**. This callback is not supported by the audio encoder. - **OH_AVCodecOnNeedInputBuffer**, a callback used to report input data required, which means that the encoder is ready for receiving PCM data - **OH_AVCodecOnNewOutputBuffer**, a callback used to report output data generated, which means that encoding is complete You need to process the callback functions to ensure that the encoder runs properly. + > **NOTE** + > + > You are not advised to perform time-consuming operations in the callback. + ```cpp // Implement the OH_AVCodecOnError callback function. static void OnError(OH_AVCodec *codec, int32_t errorCode, void *userData) @@ -146,7 +150,7 @@ target_link_libraries(sample PUBLIC libnative_media_acodec.so) // Set the asynchronous callbacks. int32_t ret = OH_AudioCodec_RegisterCallback(audioEnc_, cb_, signal_); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` @@ -161,7 +165,7 @@ target_link_libraries(sample PUBLIC libnative_media_acodec.so) The sample below lists the value range of each audio encoding type. | Audio Encoding Type| Sampling Rate (Hz) | Audio Channel Count | | ----------- | ------------------------------------------------------------------------------- | :----------------: | - | AAC | 8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000, 64000, 88200, 96000| 1, 2, 3, 4, 5, 6, and 8| + | AAC | 8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000, 64000, 88200, 96000| 1, 2, 3, 4, 5, 6, and 8| | FLAC | 8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000, 64000, 88200, 96000| 1–8 | | MP3 | 8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000 | 1–2 | | G711mu | 8000 | 1 | @@ -183,7 +187,7 @@ target_link_libraries(sample PUBLIC libnative_media_acodec.so) constexpr OH_BitsPerSample SAMPLE_FORMAT = OH_BitsPerSample::SAMPLE_S16LE; // A frame of audio data takes 20 ms. constexpr float TIME_PER_FRAME = 0.02; - // (Optional) Configure the maximum input length and the size of each frame of audio data. + // (Optional) Configure the maximum input length and the size of each audio frame. constexpr uint32_t DEFAULT_MAX_INPUT_SIZE = DEFAULT_SAMPLERATE * TIME_PER_FRAME * DEFAULT_CHANNEL_COUNT * sizeof(short); // aac OH_AVFormat *format = OH_AVFormat_Create(); // Set the format. @@ -196,7 +200,7 @@ target_link_libraries(sample PUBLIC libnative_media_acodec.so) // Configure the encoder. ret = OH_AudioCodec_Configure(audioEnc_, format); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` @@ -230,7 +234,7 @@ target_link_libraries(sample PUBLIC libnative_media_acodec.so) // Configure the encoder. ret = OH_AudioCodec_Configure(audioEnc_, format); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` @@ -241,7 +245,7 @@ target_link_libraries(sample PUBLIC libnative_media_acodec.so) ```cpp ret = OH_AudioCodec_Prepare(audioEnc_); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` @@ -257,11 +261,13 @@ target_link_libraries(sample PUBLIC libnative_media_acodec.so) // Start encoding. ret = OH_AudioCodec_Start(audioEnc_); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` -7. Call **OH_AudioCodec_PushInputBuffer()** to write the data to encode. +7. Call **OH_AudioCodec_PushInputBuffer()** to write the data to encode. You should fill in complete input data before calling this API. + + Set **SAMPLES_PER_FRAME** as follows: For AAC encoding, set **SAMPLES_PER_FRAME** to the number of PCM samples every 20 ms, that is, sampling rate x 0.02. @@ -289,6 +295,7 @@ target_link_libraries(sample PUBLIC libnative_media_acodec.so) // Number of audio channels. For AMR encoding, only mono audio input is supported. constexpr int32_t DEFAULT_CHANNEL_COUNT = 2; // Length of the input data of each frame, that is, number of audio channels x number of samples per frame x number of bytes per sample (SAMPLE_S16LE used as an example). + // If the last frame of data does not meet the required length,you are advised to discard it or add padding. constexpr int32_t INPUT_FRAME_BYTES = DEFAULT_CHANNEL_COUNT * SAMPLES_PER_FRAME * sizeof(short); uint32_t index = signal_->inQueue_.front(); auto buffer = signal_->inBufferQueue_.front(); @@ -305,19 +312,22 @@ target_link_libraries(sample PUBLIC libnative_media_acodec.so) // Send the data to the input queue for encoding. The index is the subscript of the queue. ret = OH_AudioCodec_PushInputBuffer(audioEnc_, index); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` In the preceding example, **attr.flags** indicates the type of the buffer flag. - + To indicate the End of Stream (EOS), pass in the **AVCODEC_BUFFER_FLAGS_EOS** flag. + | Value| Description| | -------- | -------- | | AVCODEC_BUFFER_FLAGS_NONE | Common frame.| | AVCODEC_BUFFER_FLAGS_EOS | The buffer is an end-of-stream frame.| | AVCODEC_BUFFER_FLAGS_CODEC_DATA | The buffer contains codec-specific data.| -8. Call **OH_AudioCodec_FreeOutputBuffer()** to output the encoded stream. +8. Call **OH_AudioCodec_FreeOutputBuffer()** to release the encoded data. + + Once you have retrieved the encoded stream, call **OH_AudioCodec_FreeOutputBuffer()** to free up the data. ```c++ uint32_t index = signal_->outQueue_.front(); @@ -326,17 +336,17 @@ target_link_libraries(sample PUBLIC libnative_media_acodec.so) OH_AVCodecBufferAttr attr = {0}; ret = OH_AVBuffer_GetBufferAttr(avBuffer, &attr); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } // Write the encoded data (specified by data) to the output file. outputFile_->write(reinterpret_cast(OH_AVBuffer_GetAddr(avBuffer)), attr.size); // Release the output buffer. ret = OH_AudioCodec_FreeOutputBuffer(audioEnc_, index); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } if (attr.flags == AVCODEC_BUFFER_FLAGS_EOS) { - // End + // End. } ``` @@ -355,12 +365,12 @@ target_link_libraries(sample PUBLIC libnative_media_acodec.so) // Refresh the encoder. ret = OH_AudioCodec_Flush(audioEnc_); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } // Start encoding again. ret = OH_AudioCodec_Start(audioEnc_); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` @@ -372,22 +382,24 @@ target_link_libraries(sample PUBLIC libnative_media_acodec.so) // Reset the encoder. ret = OH_AudioCodec_Reset(audioEnc_); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } // Reconfigure the encoder. ret = OH_AudioCodec_Configure(audioEnc_, format); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` 11. Call **OH_AudioCodec_Stop()** to stop the encoder. + After the encoder is stopped, you can call **Start** to start it again. If you have passed specific data in the previous **Start** for the encoder, you must pass it again. + ```c++ // Stop the encoder. ret = OH_AudioCodec_Stop(audioEnc_); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` @@ -401,7 +413,7 @@ target_link_libraries(sample PUBLIC libnative_media_acodec.so) // Call OH_AudioCodec_Destroy to destroy the encoder. ret = OH_AudioCodec_Destroy(audioEnc_); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } else { audioEnc_ = NULL; // The encoder cannot be destroyed repeatedly. } diff --git a/en/application-dev/media/avcodec/audio-video-demuxer.md b/en/application-dev/media/avcodec/audio-video-demuxer.md index cbeb843654e172ca85ba10b9e7d86fd814f56470..16fb2b9614315fc564e978f4490c2723581f83a1 100644 --- a/en/application-dev/media/avcodec/audio-video-demuxer.md +++ b/en/application-dev/media/avcodec/audio-video-demuxer.md @@ -41,7 +41,7 @@ target_link_libraries(sample PUBLIC libnative_media_core.so) > **NOTE** > -> The word 'sample' in the preceding code snippet is only an example. Use the actual project directory name. +> The word **sample** in the preceding code snippet is only an example. Use the actual project directory name. > ### How to Develop @@ -58,12 +58,12 @@ target_link_libraries(sample PUBLIC libnative_media_core.so) #include ``` -2. Create a resource object. +2. Create a resource instance. When using **open** to obtain the FD, convert the value of **filepath** to a [sandbox path](../../file-management/app-sandbox-directory.md#mappings-between-application-sandbox-paths-and-physical-paths) to obtain sandbox resources. ```c++ - // Create the FD. You must have the read permission on the file handle when opening the file. (filePath indicates the path of the file to be demuxed. The file must exist.) + // Create the FD. You must have the read permission on the file instance to open the file. (filePath indicates the path of the file to be demuxed. The file must exist.) std::string filePath = "test.mp4"; int fd = open(filePath.c_str(), O_RDONLY); struct stat fileStatus {}; @@ -74,23 +74,23 @@ target_link_libraries(sample PUBLIC libnative_media_core.so) printf("get stat failed"); return; } - // Create a source resource object for the FD resource file. If offset is not the start position of the file or size is not the actual file size, the data obtained may be incomplete. Consequently, the source resource object may fail to create or subsequent demuxing may fail. + // Create a source resource instance for the FD resource file. If offset is not the start position of the file or size is not the actual file size, the data obtained may be incomplete. Consequently, the source resource object may fail to create or subsequent demuxing may fail. OH_AVSource *source = OH_AVSource_CreateWithFD(fd, 0, fileSize); if (source == nullptr) { printf("create source failed"); return; } - // (Optional) Create a source resource object for the URI resource file. + // (Optional) Create a source resource instance for the URI resource file. // OH_AVSource *source = OH_AVSource_CreateWithURI(uri); - // (Optional) Create a source resource object for the custom data source. Before the operation, you must implement AVSourceReadAt. + // (Optional) Create a source resource instance for the custom data source. Before the operation, you must implement AVSourceReadAt. // Add g_filePath when OH_AVSource_CreateWithDataSource is used. // g_filePath = filePath ; // OH_AVDataSource dataSource = {fileSize, AVSourceReadAt}; // OH_AVSource *source = OH_AVSource_CreateWithDataSource(&dataSource); ``` - Implement the **AVSourceReadAt** API before creating the resource object. + Implement the **AVSourceReadAt** API before creating the resource instance. ```c++ // Add the header file. @@ -147,7 +147,7 @@ target_link_libraries(sample PUBLIC libnative_media_core.so) ``` 3. Create a demuxer instance. ```c++ - // Create a demuxer for the resource object. + // Create a demuxer for the resource instance. OH_AVDemuxer *demuxer = OH_AVDemuxer_CreateWithSource(source); if (demuxer == nullptr) { printf("create demuxer failed"); @@ -174,11 +174,33 @@ target_link_libraries(sample PUBLIC libnative_media_core.so) DRM_MediaKeySystemInfo mediaKeySystemInfo; OH_AVDemuxer_GetMediaKeySystemInfo(demuxer, &mediaKeySystemInfo); ``` - After obtaining and parsing DRM information, create [MediaKeySystem](../drm/native-drm-mediakeysystem-management.md) and [MediaKeySession](../drm/native-drm-mediakeysession-management.md) instances of the corresponding DRM scheme to obtain a media key. If required, set the audio decryption configuration by following step 4 in [Audio Decoding](./audio-decoding.md#how-to-develop), and set the video decryption configuration by following step 5 [Surface Output in Video Decoding](./video-decoding.md#surface-mode) or step 4 in [Buffer Output in Video Decoding](./video-decoding.md#buffer mode). + After obtaining and parsing DRM information, create [MediaKeySystem and MediaKeySession](../drm/drm-c-dev-guide.md) instances of the corresponding DRM scheme to obtain a media key. If required, set the audio decryption configuration by following step 4 in [Audio Decoding](audio-decoding.md#how-to-develop), and set the video decryption configuration by following step 5 in [Surface Output in Video Decoding](video-decoding.md#surface-mode) or step 4 in [Buffer Output in Video Decoding](video-decoding.md#buffer-mode). -5. (Optional) Obtain the number of tracks. If you know the track information, skip this step. +5. Obtain file information. ```c++ + // (Optional) Obtain custom file attributes. If custom file attributes are not required, skip this step. + // Obtain custom attributes from the source file. + OH_AVFormat *customMetadataFormat = OH_AVSource_GetCustomMetadataFormat(source); + if (customMetadataFormat == nullptr) { + printf("get custom metadata format failed"); + return; + } + // Precautions: + // 1. customKey must exactly match the key used during muxing (including the complete naming hierarchy). + // The example key is for demonstration only. Replace it with the actual custom string. + // For example, if the key used during muxing is com.openharmony.custom.meta.abc.efg, + // you must use the full key. Using a truncated key like com.openharmony.custom.meta.abc will fail. + // 2. The type of value must match the data type used during muxing. (The example uses a string type. For int or float, use the corresponding interface.) + const char *customKey = "com.openharmony.custom.meta.string"; // Replace it with the actual key used during muxing. + const char *customValue; + if (!OH_AVFormat_GetStringValue(customMetadataFormat, customKey, &customValue)) { + printf("get custom metadata from custom metadata format failed"); + return; + } + OH_AVFormat_Destroy(customMetadataFormat); + + // (Optional) Obtain the number of tracks. If you know the track information, skip this step. // Obtain the number of tracks from the file source information. You can call the API to obtain file-level attributes. For details, see Table 1 in Appendix 1. OH_AVFormat *sourceFormat = OH_AVSource_GetSourceFormat(source); if (sourceFormat == nullptr) { @@ -248,8 +270,9 @@ target_link_libraries(sample PUBLIC libnative_media_core.so) ```c++ // Demuxing is performed from this time. // Note: - // 1. If OH_AVDemuxer_SeekToTime is called for an MPEG TS file, the target position may be a non-key frame. You can then call OH_AVDemuxer_ReadSampleBuffer to check whether the current frame is a key frame based on the obtained OH_AVCodecBufferAttr. If it is a non-key frame, which causes display issues on the application side, cyclically read the frames until you reach the first key frame, where you can perform processing such as decoding. + // 1. If OH_AVDemuxer_SeekToTime is called for an MPEG TS or MPG file, the target position may be a non-key frame. You can then call OH_AVDemuxer_ReadSampleBuffer to check whether the current frame is a key frame based on the obtained OH_AVCodecBufferAttr. If it is a non-key frame, which causes display issues on the application side, cyclically read the frames until you reach the first key frame, where you can perform processing such as decoding. // 2. If OH_AVDemuxer_SeekToTime is called for an OGG file, the file seeks to the start of the time interval (second) where the input parameter millisecond is located, which may cause a certain number of frame errors. + // 3. The seek operation of the demuxer is performed only on streams with consistent decoding behavior. If a stream requires the decoder to reconfigure or re-input parameter data after seeking to decode correctly, it may result in artifacts or decoder freezing. OH_AVDemuxer_SeekToTime(demuxer, 0, OH_AVSeekMode::SEEK_MODE_CLOSEST_SYNC); ``` @@ -284,6 +307,8 @@ target_link_libraries(sample PUBLIC libnative_media_core.so) int32_t ret; while (!audioIsEnd || !videoIsEnd) { // Before calling OH_AVDemuxer_ReadSampleBuffer, call OH_AVDemuxer_SelectTrackByID to select the track from which the demuxer reads data. + // Note: + // For AVI format, since the container standard does not support encapsulating timestamp information, the demuxed frames do not contain PTS information. The caller needs to calculate display timestamps based on the frame rate and the display order of the decoded frames. // Obtain the audio sample. if(!audioIsEnd) { ret = OH_AVDemuxer_ReadSampleBuffer(demuxer, audioTrackIndex, buffer); @@ -313,16 +338,16 @@ target_link_libraries(sample PUBLIC libnative_media_core.so) 10. Destroy the demuxer instance. ```c++ - // Manually set the instance to NULL after OH_AVSource_Destroy is called. Do not call this API repeatedly for the same instance; otherwise, a program error occurs. + // Manually set the instance to a null pointer after OH_AVSource_Destroy is called. Do not call this API repeatedly for the same instance; otherwise, a program error occurs. if (OH_AVSource_Destroy(source) != AV_ERR_OK) { printf("destroy source pointer error"); } - source = NULL; - // Manually set the instance to NULL after OH_AVDemuxer_Destroy is called. Do not call this API repeatedly for the same instance; otherwise, a program error occurs. + source = nullptr; + // Manually set the instance to a null pointer after OH_AVDemuxer_Destroy is called. Do not call this API repeatedly for the same instance; otherwise, a program error occurs. if (OH_AVDemuxer_Destroy(demuxer) != AV_ERR_OK) { printf("destroy demuxer pointer error"); } - demuxer = NULL; + demuxer = nullptr; close(fd); ``` @@ -333,6 +358,8 @@ target_link_libraries(sample PUBLIC libnative_media_core.so) > > Attribute data can be obtained only when the file is parsed normally. If the file information is incorrect or missing, the parsing is abnormal and the corresponding data cannot be obtained. > +> Currently, data in the GBK character set is converted to UTF-8. If other character sets need to be converted to UTF-8, you must handle the conversion. For details, see [icu4c](../../reference/native-lib/icu4c.md). +> > For details about the data type and value range, see [Media Data Key-Value Pairs](../../reference/apis-avcodec-kit/_codec_base.md#media-data-key-value-pairs). **Table 1** Supported file-level attributes @@ -358,7 +385,7 @@ target_link_libraries(sample PUBLIC libnative_media_core.so) > **NOTE** > > Attribute data can be obtained only when the file is parsed normally. If the file information is incorrect or missing, the parsing is abnormal and the corresponding data cannot be obtained. -> +> > For details about the data type and value range, see [Media Data Key-Value Pairs](../../reference/apis-avcodec-kit/_codec_base.md#media-data-key-value-pairs). **Table 2** Supported track-level attributes diff --git a/en/application-dev/media/avcodec/audio-video-muxer.md b/en/application-dev/media/avcodec/audio-video-muxer.md index cb91dde76485dc9e79eb732cdc2475a2c77b6b9b..3e81b0ac5dc8214ec0ab468588460f84090e4d96 100644 --- a/en/application-dev/media/avcodec/audio-video-muxer.md +++ b/en/application-dev/media/avcodec/audio-video-muxer.md @@ -39,6 +39,8 @@ target_link_libraries(sample PUBLIC libnative_media_core.so) The following walks you through how to implement the entire process of audio and video muxing. It uses the MP4 format as an example. +For details about the keys to be configured for different container formats, see [AVCodec Supported Formats](avcodec-support-formats.md#media-data-muxing). + 1. Add the header files. ```c++ @@ -54,7 +56,7 @@ The following walks you through how to implement the entire process of audio and ```c++ // Set the muxing format to MP4. OH_AVOutputFormat format = AV_OUTPUT_FORMAT_MPEG_4; - // Create a File Descriptor (FD) in read/write mode. + // Create an FD in read/write mode. int32_t fd = open("test.mp4", O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR); OH_AVMuxer *muxer = OH_AVMuxer_Create(fd, format); ``` @@ -84,8 +86,8 @@ The following walks you through how to implement the entire process of audio and ```c++ int audioTrackId = -1; uint8_t *buffer = ...; // Encoding configuration data. If there is no configuration data, leave the parameter unspecified. - size_t size =...; // Length of the encoding configuration data. Set this parameter based on project requirements. - OH_AVFormat *formatAudio = OH_AVFormat_Create (); // Call OH_AVFormat_Create to create a format. The following showcases how to mux an AAC-LC audio with the sampling rate of 44100 Hz and two audio channels. + size_t size = ...; // Length of the encoding configuration data. Set this parameter based on project requirements. + OH_AVFormat *formatAudio = OH_AVFormat_Create(); // Call OH_AVFormat_Create to create a format. The following showcases how to mux an AAC-LC audio with the sampling rate of 44100 Hz and two audio channels. OH_AVFormat_SetStringValue(formatAudio, OH_MD_KEY_CODEC_MIME, OH_AVCODEC_MIMETYPE_AUDIO_AAC); // Mandatory. OH_AVFormat_SetIntValue(formatAudio, OH_MD_KEY_AUD_SAMPLE_RATE, 44100); // Mandatory. OH_AVFormat_SetIntValue(formatAudio, OH_MD_KEY_AUD_CHANNEL_COUNT, 2); // Mandatory. @@ -104,7 +106,7 @@ The following walks you through how to implement the entire process of audio and ```c++ int audioTrackId = -1; uint8_t *buffer = ...; // Encoding configuration data. If there is no configuration data, leave the parameter unspecified. - size_t size =...; // Length of the encoding configuration data. Set this parameter based on project requirements. + size_t size = ...; // Length of the encoding configuration data. Set this parameter based on project requirements. OH_AVFormat *formatAudio = OH_AVFormat_CreateAudioFormat(OH_AVCODEC_MIMETYPE_AUDIO_AAC, 44100, 2); OH_AVFormat_SetIntValue(formatAudio, OH_MD_KEY_PROFILE, AAC_PROFILE_LC); // Optional. OH_AVFormat_SetBuffer(formatAudio, OH_MD_KEY_CODEC_CONFIG, buffer, size); // Optional. @@ -123,12 +125,12 @@ The following walks you through how to implement the entire process of audio and ```c++ int videoTrackId = -1; uint8_t *buffer = ...; // Encoding configuration data. If there is no configuration data, leave the parameter unspecified. - size_t size =...; // Length of the encoding configuration data. Set this parameter based on project requirements. + size_t size = ...; // Length of the encoding configuration data. Set this parameter based on project requirements. OH_AVFormat *formatVideo = OH_AVFormat_Create(); OH_AVFormat_SetStringValue(formatVideo, OH_MD_KEY_CODEC_MIME, OH_AVCODEC_MIMETYPE_VIDEO_AVC); // Mandatory. OH_AVFormat_SetIntValue(formatVideo, OH_MD_KEY_WIDTH, 1280); // Mandatory. OH_AVFormat_SetIntValue(formatVideo, OH_MD_KEY_HEIGHT, 720); // Mandatory. - OH_AVFormat_SetBuffer(formatVideo, OH_MD_KEY_CODEC_CONFIG, buffer, size); // Optional + OH_AVFormat_SetBuffer(formatVideo, OH_MD_KEY_CODEC_CONFIG, buffer, size); // Optional. int ret = OH_AVMuxer_AddTrack(muxer, &videoTrackId, formatVideo); if (ret != AV_ERR_OK || videoTrackId < 0) { @@ -142,9 +144,9 @@ The following walks you through how to implement the entire process of audio and ```c++ int videoTrackId = -1; uint8_t *buffer = ...; // Encoding configuration data. If there is no configuration data, leave the parameter unspecified. - size_t size =...; // Length of the encoding configuration data. Set this parameter based on project requirements. + size_t size = ...; // Length of the encoding configuration data. Set this parameter based on project requirements. OH_AVFormat *formatVideo = OH_AVFormat_CreateVideoFormat(OH_AVCODEC_MIMETYPE_VIDEO_AVC, 1280, 720); - OH_AVFormat_SetBuffer(formatVideo, OH_MD_KEY_CODEC_CONFIG, buffer, size); // Optional + OH_AVFormat_SetBuffer(formatVideo, OH_MD_KEY_CODEC_CONFIG, buffer, size); // Optional. int ret = OH_AVMuxer_AddTrack(muxer, &videoTrackId, formatVideo); if (ret != AV_ERR_OK || videoTrackId < 0) { @@ -189,11 +191,13 @@ The following walks you through how to implement the entire process of audio and ```c++ // Call Start() to write the file header. After this API is called, you cannot set media parameters or add tracks. if (OH_AVMuxer_Start(muxer) != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` -9. Call **OH_AVMuxer_WriteSampleBuffer()** to write data. The encapsulated data includes video, audio, and cover data. +9. Call **OH_AVMuxer_WriteSampleBuffer()** to write data. + + The encapsulated data includes video, audio, and cover data. ```c++ // Data can be written only after Start() is called. @@ -214,7 +218,7 @@ The following walks you through how to implement the entire process of audio and int ret = OH_AVMuxer_WriteSampleBuffer(muxer, trackId, sample); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` @@ -223,15 +227,17 @@ The following walks you through how to implement the entire process of audio and ```c++ // Call Stop() to write the file trailer. After this API is called, you cannot write media data. if (OH_AVMuxer_Stop(muxer) != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` -11. Call **OH_AVMuxer_Destroy()** to release the instance. Do not repeatedly destroy the instance. Otherwise, the program may crash. +11. Call **OH_AVMuxer_Destroy()** to release the instance. + + Do not repeatedly destroy the instance. Otherwise, the program may crash. ```c++ if (OH_AVMuxer_Destroy(muxer) != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } muxer = NULL; close(fd); // Close the FD. diff --git a/en/application-dev/media/avcodec/avcodec-kit-intro.md b/en/application-dev/media/avcodec/avcodec-kit-intro.md index 0e6b51e3f1b8926692512037ba2d33b628681a2b..d7781ca5a24f4cf773fc2728d4c0afa4babbf3aa 100644 --- a/en/application-dev/media/avcodec/avcodec-kit-intro.md +++ b/en/application-dev/media/avcodec/avcodec-kit-intro.md @@ -1,5 +1,5 @@ # Introduction to AVCodec Kit -Audio and Video Codec (AVCodec) Kit provides capabilities such as audio and video codec, media file muxing and demuxing, and media data input. +Audio and Video Codec (AVCodec) Kit provides capabilities such as audio/video encoding and decoding, media file muxing and demuxing, and media data input. For performance reasons, AVCodec Kit provides only C APIs. ## Capability Scope diff --git a/en/application-dev/media/avcodec/avcodec-support-formats.md b/en/application-dev/media/avcodec/avcodec-support-formats.md index 8db8df97669857c7f32d4099b8aea7bcc3294de3..5cd9420734a9b8a1bba5377010373d36e7345d72 100644 --- a/en/application-dev/media/avcodec/avcodec-support-formats.md +++ b/en/application-dev/media/avcodec/avcodec-support-formats.md @@ -8,9 +8,9 @@ Currently, the following decoding capabilities are supported: | Video Hardware Decoding Type | Video Software Decoding Type | | --------------------- | ---------------- | -| AVC (H.264) and HEVC (H.265)|AVC (H.264) | +| AVC (H.264) and HEVC (H.265) | MPEG2, MPEG4, and AVC (H.264) | -Video software decoding and hardware decoding are different. When a decoder is created based on the MIME type, only H.264 (OH_AVCODEC_MIMETYPE_VIDEO_AVC) is supported for software decoding, and H.264 (OH_AVCODEC_MIMETYPE_VIDEO_AVC) and H.265 (OH_AVCODEC_MIMETYPE_VIDEO_HEVC) can be used for hardware decoding as long as they are supported by the hardware platform. +Video software decoding and hardware decoding are different. When a decoder is created based on the MIME type, only MPEG2 (OH_AVCODEC_MIMETYPE_VIDEO_MPEG2), MPEG4 (OH_AVCODEC_MIMETYPE_VIDEO_MPEG4_PART2), and H.264 (OH_AVCODEC_MIMETYPE_VIDEO_AVC) are supported for software decoding, and H.264 (OH_AVCODEC_MIMETYPE_VIDEO_AVC) and H.265 (OH_AVCODEC_MIMETYPE_VIDEO_HEVC) can be used for hardware decoding as long as they are supported by the hardware platform. For details about the range of each decoding capability, see [Obtaining Supported Codecs](obtain-supported-codecs.md). @@ -20,9 +20,9 @@ For details about the development guide, see [Video Decoding](video-decoding.md) Currently, the following encoding capabilities are supported: -| Container Format| Video Encoding Type | -| -------- | ---------------------------- | -| mp4 | HEVC (H.265) and AVC (H.264)| +| Video Encoding Type | +| ---------------------------- | +| HEVC (H.265) and AVC (H.264)| Only hardware encoding is supported. When an encoder is created based on the MIME type, H.264 (OH_AVCODEC_MIMETYPE_VIDEO_AVC) and H.265 (OH_AVCODEC_MIMETYPE_VIDEO_HEVC) are supported. @@ -35,17 +35,7 @@ For details about the development guide, see [Video Encoding](video-encoding.md) Currently, the following decoding capabilities are supported: -| Container Format| Audio Decoding Type | -| -------- | :--------------------------- | -| mp4 | AAC, MPEG (MP3), FLAC, Vorbis | -| m4a | AAC | -| flac | Flac | -| ogg | Vorbis | -| aac | AAC | -| mp3 | MPEG (MP3) | -| amr | AMR (AMR-NB and AMR-WB) | -| raw | G711mu | -| ape | APE | +AAC, MPEG (MP3), FLAC, Vorbis, AMR (AMR-NB and AMR-WB), G.711Mu, APE For details about the development guide, see [Audio Decoding](audio-decoding.md). @@ -54,15 +44,7 @@ For details about the development guide, see [Audio Decoding](audio-decoding.md) Currently, the following encoding capabilities are supported: -| Container Format| Audio Encoding Type | -| -------- | :--------------- | -| mp4 | AAC, FLAC | -| m4a | AAC | -| flac | Flac | -| aac | AAC | -| mp3 | MP3 | -| raw | G711mu | - +AAC, FLAC, MP3, G.711Mu For details about the development guide, see [Audio Encoding](audio-encoding.md). @@ -71,21 +53,23 @@ For details about the development guide, see [Audio Encoding](audio-encoding.md) ### Media Data Demuxing -The following demuxing formats are supported: +The following container formats are supported: -| Media Format | Muxing Format | Stream Format | +| Media Format | Container Format | Stream Format | | -------- | :----------------------------| :----------------------------| -| Audio/Video | mp4 |Video stream: AVC (H.264); audio stream: AAC and MPEG (MP3); subtitle stream: WEBVTT| +| Audio/Video | mp4 |Video stream: AVC (H.264) and MPEG4; audio stream: AAC and MPEG (MP3); subtitle stream: WEBVTT| | Audio/Video | fmp4 |Video stream: AVC (H.264); audio stream: AAC and MPEG (MP3)| | Audio/Video | mkv |Video stream: AVC (H.264); audio stream: AAC, MPEG (MP3), and OPUS| -| Audio/Video | mpeg-ts |Video stream: AVC (H.264); audio stream: AAC and MPEG (MP3)| +| Audio/Video | mpeg-ts |Video stream: AVC (H.264), MPEG2, and MPEG4; audio stream: AAC and MPEG (MP3)| | Audio/Video | flv |Video stream: AVC (H.264); audio stream: AAC| +| Audio/Video | mpeg-ps |Video stream: AVC (H.264) and MPEG2; audio stream: MPEG (MP2 and MP3)| +| Audio/Video | avi |Video stream: H.263, AVC (H.264), MPEG2, and MPEG4; audio stream: AAC, MPEG (MP2 and MP3), and PCM| | Audio | m4a |Audio stream: AAC| | Audio | aac |Audio stream: AAC| | Audio | mp3 |Audio stream: MPEG (MP3)| -| Audio | ogg |Audio stream: OGG| +| Audio | ogg |Audio stream: Vorbis| | Audio | flac |Audio stream: FLAC| -| Audio | wav |Audio stream: PCM and PCM-MULAW| +| Audio | wav |Audio stream: PCM and G.711Mu| | Audio | amr |Audio stream: AMR (AMR-NB and AMR-WB)| | Audio | ape |Audio stream: APE| | External subtitle | srt |Subtitle stream: SRT| @@ -100,17 +84,92 @@ For details about the development guide, see [Media Data Demuxing](audio-video-d Currently, the following muxer capabilities are supported: -| Muxing Format| Video Codec Type | Audio Codec Type | Cover Type | +| Container Format| Video Codec Type | Audio Codec Type | Cover Type | | -------- | --------------------- | ---------------- | -------------- | | mp4 | AVC (H.264) | AAC, MPEG (MP3)| jpeg, png, bmp| | m4a | - | AAC | jpeg, png, bmp| | mp3 | - | MPEG (MP3) | - | | amr | - | AMR (AMR-NB and AMR-WB)| - | | wav | - | G711mu(pcm-mulaw) | - | +| aac | - | AAC | - | > **NOTE** > > - When the container format is MP4 and the audio codec type is MPEG (MP3), the sampling rate must be greater than or equal to 16000 Hz. > - When the container format is MP4 or M4A and the audio codec type is AAC, the number of audio channels ranges from 1 to 7. +Key values of configuration options are described as follows: + +mp4 container format + | key | Description | aac | mp3 | H.264 | H.265 | jpg | png | bmp | + | ---------------------------------- | :------------------: | :----: | :----: | :----: | :----: | :----: | :----: | :----: | + | OH_MD_KEY_AUD_SAMPLE_RATE | Sampling rate | Mandatory | Mandatory | - | - | - | - | - | + | OH_MD_KEY_AUD_CHANNEL_COUNT | Number of audio channels | Mandatory | Mandatory | - | - | - | - | - | + | OH_MD_KEY_AUDIO_SAMPLE_FORMAT | Output audio stream format | Optional | Optional | - | - | - | - | - | + | OH_MD_KEY_CHANNEL_LAYOUT | Channel layout | Optional | Optional | - | - | - | - | - | + | OH_MD_KEY_PROFILE | Encoding profile | Optional | - | - | - | - | - | - | + | OH_MD_KEY_BITRATE | Bit rate | Optional | Optional | Optional | Optional | - | - | - | + | OH_MD_KEY_CODEC_CONFIG | Codec-specific data | Optional | - | Optional | Optional | - | - | - | + | OH_MD_KEY_WIDTH | Width | - | - | Mandatory | Mandatory | Mandatory | Mandatory | Mandatory | + | OH_MD_KEY_HEIGHT | Height | - | - | Mandatory | Mandatory | Mandatory | Mandatory | Mandatory | + | OH_MD_KEY_FRAME_RATE | Video stream frame rate | - | - | Optional | Optional | - | - | - | + | OH_MD_KEY_COLOR_PRIMARIES | Video color gamut | - | - | Optional | Optional | - | - | - | + | OH_MD_KEY_TRANSFER_CHARACTERISTICS | Video transfer function | - | - | Optional | Optional | - | - | - | + | OH_MD_KEY_MATRIX_COEFFICIENTS | Video matrix coefficient | - | - | Optional | Optional | - | - | - | + | OH_MD_KEY_RANGE_FLAG | Value range flag | - | - | Optional | Optional | - | - | - | + | OH_MD_KEY_VIDEO_IS_HDR_VIVID | Whether the video track is an HDR Vivid| - | - | - | Optional | - | - | - | + +m4a container format + | key | Description | aac | jpg | png | bmp | + | ---------------------------------- | :------------------: | :----: | :----: | :----: | :----: | + | OH_MD_KEY_AUD_SAMPLE_RATE | Sampling rate | Mandatory | - | - | - | + | OH_MD_KEY_AUD_CHANNEL_COUNT | Number of audio channels | Mandatory | - | - | - | + | OH_MD_KEY_AUDIO_SAMPLE_FORMAT | Output audio stream format | Optional | - | - | - | + | OH_MD_KEY_CHANNEL_LAYOUT | Channel layout | Optional | - | - | - | + | OH_MD_KEY_PROFILE | Encoding profile | Optional | - | - | - | + | OH_MD_KEY_BITRATE | Bit rate | Optional | - | - | - | + | OH_MD_KEY_CODEC_CONFIG | Codec-specific data | Optional | - | - | - | + | OH_MD_KEY_WIDTH | Width | - | Mandatory | Mandatory | Mandatory | + | OH_MD_KEY_HEIGHT | Height | - | Mandatory | Mandatory | Mandatory | + +amr container format + | key | Description | amr_nb | amr_wb | + | ---------------------------------- | :------------------: | :----: | :----: | + | OH_MD_KEY_AUD_SAMPLE_RATE | Sampling rate | Mandatory | Mandatory | + | OH_MD_KEY_AUD_CHANNEL_COUNT | Number of audio channels | Mandatory | Mandatory | + | OH_MD_KEY_AUDIO_SAMPLE_FORMAT | Output audio stream format | Optional | Optional | + | OH_MD_KEY_CHANNEL_LAYOUT | Channel layout | Optional | Optional | + | OH_MD_KEY_BITRATE | Bit rate | Optional | Optional | + +mp3 container format + | key | Description | mp3 | jpg | + | ---------------------------------- | :------------------: | :----: | :----: | + | OH_MD_KEY_AUD_SAMPLE_RATE | Sampling rate | Mandatory | - | + | OH_MD_KEY_AUD_CHANNEL_COUNT | Number of audio channels | Mandatory | - | + | OH_MD_KEY_AUDIO_SAMPLE_FORMAT | Output audio stream format | Optional | - | + | OH_MD_KEY_CHANNEL_LAYOUT | Channel layout | Optional | - | + | OH_MD_KEY_BITRATE | Bit rate | Optional | - | + | OH_MD_KEY_WIDTH | Width | - | Mandatory | + | OH_MD_KEY_HEIGHT | Height | - | Mandatory | + +wav container format + | key | Description | g711mu | + | ---------------------------------- | :------------------: | :----: | + | OH_MD_KEY_AUD_SAMPLE_RATE | Sampling rate | Mandatory | + | OH_MD_KEY_AUD_CHANNEL_COUNT | Number of audio channels | Mandatory | + | OH_MD_KEY_AUDIO_SAMPLE_FORMAT | Output audio stream format | Optional | + | OH_MD_KEY_CHANNEL_LAYOUT | Channel layout | Optional | + | OH_MD_KEY_BITRATE | Bit rate | Mandatory | + +aac container format + | key | Description | aac | + | ---------------------------------- | :------------------: | :----: | + | OH_MD_KEY_AUD_SAMPLE_RATE | Sampling rate | Mandatory | + | OH_MD_KEY_AUD_CHANNEL_COUNT | Number of audio channels | Mandatory | + | OH_MD_KEY_AUDIO_SAMPLE_FORMAT | Output audio stream format | Optional | + | OH_MD_KEY_CHANNEL_LAYOUT | Channel layout | Optional | + | OH_MD_KEY_BITRATE | Bit rate | Optional | + | OH_MD_KEY_PROFILE | Encoding profile | Mandatory | + | OH_MD_KEY_AAC_IS_ADTS | Whether the format is ADTS | Mandatory | + For details about the development guide, see [Media Data Muxing](audio-video-muxer.md). diff --git a/en/application-dev/media/avcodec/figures/video-variable-refreshrate.png b/en/application-dev/media/avcodec/figures/video-variable-refreshrate.png new file mode 100644 index 0000000000000000000000000000000000000000..596fa1d58846514b2840f75b5124d9868736bff6 Binary files /dev/null and b/en/application-dev/media/avcodec/figures/video-variable-refreshrate.png differ diff --git a/en/application-dev/media/avcodec/obtain-supported-codecs.md b/en/application-dev/media/avcodec/obtain-supported-codecs.md index aa2a4b43addd2291825a4161d1d8a8e32e33ff3d..78e6cceebd35f0c6f9906ee18f9ed1d1e163c74b 100644 --- a/en/application-dev/media/avcodec/obtain-supported-codecs.md +++ b/en/application-dev/media/avcodec/obtain-supported-codecs.md @@ -95,10 +95,10 @@ OH_AVCodec *videoEnc = OH_VideoEncoder_CreateByMime(OH_AVCODEC_MIMETYPE_VIDEO_AV OH_AVFormat *format = OH_AVFormat_CreateVideoFormat(OH_AVCODEC_MIMETYPE_VIDEO_AVC, 1920, 1080); double frameRate = isHardward ? 60.0 : 30.0; if (!OH_AVFormat_SetDoubleValue(format, OH_MD_KEY_FRAME_RATE, frameRate)) { - // Exception handling. + // Handle exceptions. } if (OH_VideoEncoder_Configure(videoEnc, format) != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } OH_AVFormat_Destroy(format); ``` @@ -157,18 +157,18 @@ OH_BitrateMode bitrateMode = BITRATE_MODE_CBR; int32_t bitrate = 3000000; OH_AVCapability *capability = OH_AVCodec_GetCapability(OH_AVCODEC_MIMETYPE_VIDEO_AVC, true); if (capability == nullptr) { - // Exception handling. + // Handle exceptions. } // 1. Check whether a bit rate mode is supported. bool isSupported = OH_AVCapability_IsEncoderBitrateModeSupported(capability, bitrateMode); if (!isSupported) { - // Exception handling. + // Handle exceptions. } // 2. Obtain the bit rate range and check whether the bit rate to be configured is within the range. OH_AVRange bitrateRange = {-1, -1}; int32_t ret = OH_AVCapability_GetEncoderBitrateRange(capability, &bitrateRange); if (ret != AV_ERR_OK || bitrateRange.maxVal <= 0) { - // Exception handling. + // Handle exceptions. } if (bitrate > bitrateRange.maxVal || bitrate < bitrateRange.minVal) { // 3. (Optional) Adjust the bit rate parameters to be configured. @@ -178,10 +178,10 @@ OH_AVCodec *videoEnc = OH_VideoEncoder_CreateByMime(OH_AVCODEC_MIMETYPE_VIDEO_AV OH_AVFormat *format = OH_AVFormat_CreateVideoFormat(OH_AVCODEC_MIMETYPE_VIDEO_AVC, 1920, 1080); if (OH_AVFormat_SetIntValue(format, OH_MD_KEY_VIDEO_ENCODE_BITRATE_MODE, bitrateMode) && OH_AVFormat_SetLongValue(format, OH_MD_KEY_BITRATE, static_cast(bitrate)) == false) { - // Exception handling. + // Handle exceptions. } if (OH_VideoEncoder_Configure(videoEnc, format) != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } OH_AVFormat_Destroy(format); ``` @@ -193,18 +193,18 @@ OH_BitrateMode bitrateMode = BITRATE_MODE_CQ; int32_t quality = 0; OH_AVCapability *capability = OH_AVCodec_GetCapability(OH_AVCODEC_MIMETYPE_VIDEO_AVC, true); if (capability == nullptr) { - // Exception handling. + // Handle exceptions. } // 1. Check whether a bit rate mode is supported. bool isSupported = OH_AVCapability_IsEncoderBitrateModeSupported(capability, bitrateMode); if (!isSupported) { - // Exception handling. + // Handle exceptions. } // 2. Obtain the quality range and determine whether the quality parameters to be configured are within the range. OH_AVRange qualityRange = {-1, -1}; int32_t ret = OH_AVCapability_GetEncoderQualityRange(capability, &qualityRange); if (ret != AV_ERR_OK || qualityRange.maxVal < 0) { - // Exception handling. + // Handle exceptions. } if (quality > qualityRange.maxVal || quality < qualityRange.minVal) { // 3. (Optional) Adjust the quality parameters to be configured. @@ -214,10 +214,10 @@ OH_AVCodec *videoEnc = OH_VideoEncoder_CreateByMime(OH_AVCODEC_MIMETYPE_VIDEO_AV OH_AVFormat *format = OH_AVFormat_CreateVideoFormat(OH_AVCODEC_MIMETYPE_VIDEO_AVC, 1920, 1080); if (OH_AVFormat_SetIntValue(format, OH_MD_KEY_VIDEO_ENCODE_BITRATE_MODE, bitrateMode) && OH_AVFormat_SetIntValue(format, OH_MD_KEY_QUALITY, quality) == false) { - // Exception handling. + // Handle exceptions. } if (OH_VideoEncoder_Configure(videoEnc, format) != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } OH_AVFormat_Destroy(format); ``` @@ -233,7 +233,7 @@ The complexity range determines the number of tools used by the codec. It is sup ```c++ OH_AVCapability *capability = OH_AVCodec_GetCapability(OH_AVCODEC_MIMETYPE_AUDIO_AAC, true); if (capability == nullptr) { - // Exception handling. + // Handle exceptions. } // Check the supported encoding complexity range. OH_AVRange complexityRange = {-1, -1}; @@ -258,14 +258,14 @@ int32_t channelCount = 2; int32_t bitrate = 261000; OH_AVCapability *capability = OH_AVCodec_GetCapability(OH_AVCODEC_MIMETYPE_AUDIO_AAC, true); if (capability == nullptr) { - // Exception handling. + // Handle exceptions. } // 1. Check whether the sample rate to be configured is supported. const int32_t *sampleRates = nullptr; -uint32_t sampleRateNum = -1; +uint32_t sampleRateNum = 0; int32_t ret = OH_AVCapability_GetAudioSupportedSampleRates(capability, &sampleRates, &sampleRateNum); -if (ret != AV_ERR_OK || sampleRates == nullptr || sampleRateNum <= 0) { - // Exception handling. +if (ret != AV_ERR_OK || sampleRates == nullptr || sampleRateNum == 0) { + // Handle exceptions. } bool isMatched = false; for (int i = 0; i < sampleRateNum; i++) { @@ -280,7 +280,7 @@ if (!isMatched) { OH_AVRange channelRange = {-1, -1}; ret = OH_AVCapability_GetAudioChannelCountRange(capability, &channelRange); if (ret != AV_ERR_OK || channelRange.maxVal <= 0) { - // Exception handling. + // Handle exceptions. } if (channelCount > channelRange.maxVal || channelCount < channelRange.minVal ) { //4. (Optional) Adjust the number of channels to be configured. @@ -289,7 +289,7 @@ if (channelCount > channelRange.maxVal || channelCount < channelRange.minVal ) { OH_AVRange bitrateRange = {-1, -1}; ret = OH_AVCapability_GetEncoderBitrateRange(capability, &bitrateRange); if (ret != AV_ERR_OK || bitrateRange.maxVal <= 0) { - // Exception handling. + // Handle exceptions. } if (bitrate > bitrateRange.maxVal || bitrate < bitrateRange.minVal ) { //7. (Optional) Adjust the bit rate to be configured. @@ -300,10 +300,10 @@ OH_AVFormat *format = OH_AVFormat_Create(); if (OH_AVFormat_SetIntValue(format, OH_MD_KEY_AUD_SAMPLE_RATE, sampleRate) && OH_AVFormat_SetIntValue(format, OH_MD_KEY_AUD_CHANNEL_COUNT, channelCount) && OH_AVFormat_SetLongValue(format, OH_MD_KEY_BITRATE, static_cast(bitrate)) == false) { - // Exception handling. + // Handle exceptions. } if (OH_AudioEncoder_Configure(audioEnc, format) != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } OH_AVFormat_Destroy(format); ``` @@ -326,14 +326,14 @@ The code snippet below checks whether a profile is supported and obtains the sup OH_AVCProfile profile = AVC_PROFILE_MAIN; OH_AVCapability *capability = OH_AVCodec_GetCapability(OH_AVCODEC_MIMETYPE_VIDEO_AVC, true); if (capability == nullptr) { - // Exception handling. + // Handle exceptions. } // 1. Check whether the profile to be configured is supported. const int32_t *profiles = nullptr; -uint32_t profileNum = -1; +uint32_t profileNum = 0; int32_t ret = OH_AVCapability_GetSupportedProfiles(capability, &profiles, &profileNum); -if (ret != AV_ERR_OK || profiles == nullptr || profileNum <= 0) { - // Exception handling. +if (ret != AV_ERR_OK || profiles == nullptr || profileNum == 0) { + // Handle exceptions. } bool isMatched = false; for (int i = 0; i < profileNum; i++) { @@ -343,10 +343,10 @@ for (int i = 0; i < profileNum; i++) { } // 2. Obtain the codec levels supported by the profile. const int32_t *levels = nullptr; -uint32_t levelNum = -1; +uint32_t levelNum = 0; ret = OH_AVCapability_GetSupportedLevelsForProfile(capability, profile, &levels, &levelNum); -if (ret != AV_ERR_OK || levels == nullptr || levelNum <= 0) { - // Exception handling. +if (ret != AV_ERR_OK || levels == nullptr || levelNum == 0) { + // Handle exceptions. } OH_AVCLevel maxLevel = static_cast(levels[levelNum -1]); // 3. (Optional) Use different service logic based on the maximum level supported. @@ -364,10 +364,10 @@ switch (maxLevel) { OH_AVCodec *videoEnc = OH_VideoEncoder_CreateByMime(OH_AVCODEC_MIMETYPE_VIDEO_AVC); OH_AVFormat *format = OH_AVFormat_CreateVideoFormat(OH_AVCODEC_MIMETYPE_VIDEO_AVC, 1920, 1080); if (!OH_AVFormat_SetIntValue(format, OH_MD_KEY_PROFILE, profile)) { - // Exception handling. + // Handle exceptions. } if (OH_VideoEncoder_Configure(videoEnc, format) != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } OH_AVFormat_Destroy(format); ``` @@ -378,7 +378,7 @@ If you already know the required profile and level combination, use the code sni // 1. Obtain an H.264 encoder capability instance. OH_AVCapability *capability = OH_AVCodec_GetCapability(OH_AVCODEC_MIMETYPE_VIDEO_AVC, true); if (capability == nullptr) { - // Exception handling. + // Handle exceptions. } // 2. Check whether the combination of the profile and level is supported. bool isSupported = OH_AVCapability_AreProfileAndLevelSupported(capability, AVC_PROFILE_MAIN, AVC_LEVEL_51); @@ -428,7 +428,7 @@ OH_AVCapability *capability = OH_AVCodec_GetCapability(OH_AVCODEC_MIMETYPE_VIDEO int32_t widthAlignment = 0; int32_t ret = OH_AVCapability_GetVideoWidthAlignment(capability, &widthAlignment); if (ret != AV_ERR_OK || widthAlignment <= 0) { - // Exception handling. + // Handle exceptions. } else if (width % widthAlignment != 0) { // 2. (Optional) Align the video width. width = (width + widthAlignment - 1) / widthAlignment * widthAlignment; @@ -437,7 +437,7 @@ if (ret != AV_ERR_OK || widthAlignment <= 0) { OH_AVRange widthRange = {-1, -1}; ret = OH_AVCapability_GetVideoWidthRange(capability, &widthRange); if (ret != AV_ERR_OK || widthRange.maxVal <= 0) { - // Exception handling. + // Handle exceptions. } else if (width < widthRange.minVal || width > widthRange.maxVal) { // 4. (Optional) Adjust the video width. width = min(max(width, widthRange.minVal), widthRange.maxVal); @@ -446,7 +446,7 @@ if (ret != AV_ERR_OK || widthRange.maxVal <= 0) { OH_AVRange heightRange = {-1, -1}; ret = OH_AVCapability_GetVideoHeightRangeForWidth(capability, width, &heightRange); if (ret != AV_ERR_OK || heightRange.maxVal <= 0) { - // Exception handling. + // Handle exceptions. } // 6. Select a proper video height from the range. ``` @@ -460,7 +460,7 @@ OH_AVCapability *capability = OH_AVCodec_GetCapability(OH_AVCODEC_MIMETYPE_VIDEO int32_t heightAlignment = 0; int32_t ret = OH_AVCapability_GetVideoHeightAlignment(capability, &heightAlignment); if (ret != AV_ERR_OK || heightAlignment <= 0) { - // Exception handling. + // Handle exceptions. } else if (height % heightAlignment != 0) { // 2. (Optional) Align the video height. height = (height + heightAlignment - 1) / heightAlignment * heightAlignment; @@ -469,7 +469,7 @@ if (ret != AV_ERR_OK || heightAlignment <= 0) { OH_AVRange heightRange = {-1, -1}; ret = OH_AVCapability_GetVideoHeightRange(capability, &heightRange); if (ret != AV_ERR_OK || heightRange.maxVal <= 0) { - // Exception handling. + // Handle exceptions. } else if (height < heightRange.minVal || height > heightRange.maxVal) { // 4. (Optional) Adjust the video height. height = min(max(height, heightRange.minVal), heightRange.maxVal); @@ -478,7 +478,7 @@ if (ret != AV_ERR_OK || heightRange.maxVal <= 0) { OH_AVRange widthRange = {-1, -1}; ret = OH_AVCapability_GetVideoWidthRangeForHeight(capability, height, &widthRange); if (ret != AV_ERR_OK || widthRange.maxVal <= 0) { - // Exception handling. + // Handle exceptions. } // 6. Select a proper video width from the range. ``` @@ -506,7 +506,7 @@ OH_AVCapability *capability = OH_AVCodec_GetCapability(OH_AVCODEC_MIMETYPE_VIDEO OH_AVRange frameRateRange = {-1, -1}; int32_t ret = OH_AVCapability_GetVideoFrameRateRange(capability, &frameRateRange); if (ret != AV_ERR_OK || frameRateRange.maxVal <= 0) { - // Exception handling. + // Handle exceptions. } // 2. Check whether the frame rate is within the range. bool isSupported = frameRate >= frameRateRange.minVal && frameRate <= frameRateRange.maxVal; @@ -526,7 +526,7 @@ if (!isSupported) { OH_AVRange frameRateRange = {-1, -1}; int32_t ret = OH_AVCapability_GetVideoFrameRateRangeForSize(capability, width, height, &frameRateRange); if (ret != AV_ERR_OK || frameRateRange.maxVal <= 0) { - // Exception handling. + // Handle exceptions. } frameRate = min(max(frameRate, frameRateRange.minVal), frameRateRange.maxVal); } @@ -535,10 +535,10 @@ if (!isSupported) { OH_AVCodec *videoEnc = OH_VideoEncoder_CreateByMime(OH_AVCODEC_MIMETYPE_VIDEO_AVC); OH_AVFormat *format = OH_AVFormat_CreateVideoFormat(OH_AVCODEC_MIMETYPE_VIDEO_AVC, width, height); if (!OH_AVFormat_SetIntValue(format, OH_MD_KEY_FRAME_RATE, frameRate)) { - // Exception handling. + // Handle exceptions. } if (OH_VideoEncoder_Configure(videoEnc, format) != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } OH_AVFormat_Destroy(format); ``` @@ -555,14 +555,14 @@ The video pixel format determines the pixel layout of an image that is encoded a constexpr OH_AVPixelFormat DEFAULT_PIXELFORMAT = AV_PIXEL_FORMAT_NV12; OH_AVCapability *capability = OH_AVCodec_GetCapability(OH_AVCODEC_MIMETYPE_VIDEO_AVC, true); if (capability == nullptr) { - // Exception handling. + // Handle exceptions. } // 1. Obtain the video pixel formats supported by the video codec. const int32_t *pixFormats = nullptr; -uint32_t pixFormatNum = -1; +uint32_t pixFormatNum = 0; int32_t ret = OH_AVCapability_GetVideoSupportedPixelFormats(capability, &pixFormats, &pixFormatNum); -if (ret != AV_ERR_OK || pixFormats == nullptr || pixFormatNum <= 0) { - // Exception handling. +if (ret != AV_ERR_OK || pixFormats == nullptr || pixFormatNum == 0) { + // Handle exceptions. } // 2. Check whether the pixel format to be configured is supported. bool isMatched = false; @@ -579,7 +579,6 @@ if (!isMatched) { ### Checking Whether a Codec Feature Is Supported and Obtaining Its Properties A codec feature refers to an optional feature used only in specific encoding and decoding scenarios. For details, see [OH_AVCapabilityFeature](../../reference/apis-avcodec-kit/_a_v_capability.md#oh_avcapabilityfeature-1). - | API | Description | | -------- | ---------------------------- | | OH_AVCapability_IsFeatureSupported | Check whether a codec supports a given feature.| @@ -592,7 +591,7 @@ constexpr int32_t NEEDED_LTR_NUM = 2; OH_AVFormat *format = OH_AVFormat_CreateVideoFormat(OH_AVCODEC_MIMETYPE_VIDEO_AVC, 1920, 1080); OH_AVCapability *capability = OH_AVCodec_GetCapability(OH_AVCODEC_MIMETYPE_VIDEO_AVC, true); if (capability == nullptr) { - // Exception handling. + // Handle exceptions. } // 1. Check whether the long-term reference frame feature is supported. bool isSupported = OH_AVCapability_IsFeatureSupported(capability,VIDEO_ENCODER_LONG_TERM_REFERENCE); @@ -603,13 +602,13 @@ if (isSupported) { bool ret = OH_AVFormat_GetIntValue(properties, OH_FEATURE_PROPERTY_KEY_VIDEO_ENCODER_MAX_LTR_FRAME_COUNT, &maxLTRCount); if (ret && maxLTRCount >= NEEDED_LTR_NUM) { if (!OH_AVFormat_SetIntValue(format, OH_MD_KEY_VIDEO_ENCODER_LTR_FRAME_COUNT, NEEDED_LTR_NUM)) { - // Exception handling. + // Handle exceptions. } } } // 3. Create and configure an encoder. OH_AVCodec *videoEnc = OH_VideoEncoder_CreateByMime(OH_AVCODEC_MIMETYPE_VIDEO_AVC); if (OH_VideoEncoder_Configure(videoEnc, format) != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` diff --git a/en/application-dev/media/avcodec/parallel-decoding-nativeWindow.md b/en/application-dev/media/avcodec/parallel-decoding-nativeWindow.md new file mode 100644 index 0000000000000000000000000000000000000000..9826786ba580c6c668fcf0f2f9bcb68e39b187f6 --- /dev/null +++ b/en/application-dev/media/avcodec/parallel-decoding-nativeWindow.md @@ -0,0 +1,147 @@ +# Concurrently Creating a Video Decoder and Initializing NativeWindow + +## When to Use + +To ensure that a video decoder can be created and run properly in surface mode, you can create an empty surface before the **XComponent** is created or the OpenGL post-processing (NativeImage) is initialized. + + +## How to Develop + +The following describes how to concurrently create a video decoder and initialize NativeWindow. This approach ensures that the video decoder can be set up and executed properly, even before the surface consumer is ready. + +**Linking Dynamic Libraries** + +``` cmake +target_link_libraries(sample PUBLIC libnative_image.so) +target_link_libraries(sample PUBLIC libnative_window.so) +target_link_libraries(sample PUBLIC libnative_buffer.so) +target_link_libraries(sample PUBLIC libnative_media_vdec.so) +``` + +> **NOTE** +> +> The word **sample** in the preceding code snippet is only an example. Use the actual project directory name. +> + +**Including Header Files** + +```c++ +#include +#include +#include +#include +#include +#include +``` + +1. Create an OH_NativeImage instance. + + ```c++ + // Create a NativeImage instance as the surface consumer. + OH_NativeImage* image = OH_ConsumerSurface_Create(); + ``` + +2. Obtain the NativeWindow instance that functions as the producer. + + ```c++ + // Obtain a NativeWindow instance. + OHNativeWindow* nativeImageWindow = OH_NativeImage_AcquireNativeWindow(image); + ``` + +3. Set the width and height of the NativeWindow instance. + + ```c++ + int code = SET_BUFFER_GEOMETRY; + int32_t width = 800; + int32_t height = 600; + int32_t ret = OH_NativeWindow_NativeWindowHandleOpt(nativeImageWindow, code, width, height); + if (ret != AV_ERR_OK) { + // Handle exceptions. + } + ``` + +4. Register a callback function for the NativeImage instance. + + Register the **OH_OnFrameAvailableListener**, which contains the following parameters: + + - **context**: user-defined context information. + - **onFrameAvailable**: callback function triggered when a frame is available. + + ```c++ + // Implement onFrameAvailable. + static void onFrameAvailable() + { + OHNativeWindowBuffer *buffer = nullptr; + int fenceFd; + // Obtain an OHNativeWindowBuffer instance through the OH_NativeImage instance on the consumer side. + OH_NativeImage_AcquireNativeWindowBuffer(image, &buffer, &fenceFd); + // Release the OHNativeWindowBuffer instance through the OH_NativeImage instance. + OH_NativeImage_ReleaseNativeWindowBuffer(image, &buffer, &fenceFd); + } + + static void context() + { + // Customize the context information. + } + + // Set a listener. + OH_OnFrameAvailableListener listener = {&onFrameAvailable, &context}; + // Register the listener to listen for frame availability events. + ret = OH_NativeImage_SetOnFrameAvailableListener(image, listener); + if (ret != AV_ERR_OK) { + // Handle exceptions. + } + ``` + + > **NOTE** + > + > In this example, the callback function just retrieves and releases the buffer. You can customize and expand the callback function based on service requirements. + > + +5. Configure the decoder. + + For details, see step 5 in [Video Decoding in Surface Mode](video-decoding.md#surface-output). + +6. Set the surface. + + Before the actual surface consumer is created, you can use the temporarily created consumer to connect to the decoder. + + In the code snippet below, the following variables are used: + - **videoDec**: pointer to the video decoder instance. For details, see step 2 in [Video Decoding Surface Mode](video-decoding.md#surface-output). + + ```c++ + + ret = OH_VideoDecoder_SetSurface(videoDec, nativeImageWindow); + if (ret != AV_ERR_OK) { + // Handle exceptions. + } + ``` + +7. Start the decoder. + + For details, see step 9 in [Video Decoding Surface Mode](video-decoding.md#surface-output). + + +8. Set the surface. + + After the actual surface consumer is created, call **OH_VideoDecoder_SetSurface** to redirect the decoded output to the new surface. + + You can obtain NativeWindow in either of the following ways: + 1. If the image is directly displayed after being decoded, obtain NativeWindow from the **XComponent**. For details about the operation, see [XComponent](../../reference/apis-arkui/arkui-ts/ts-basic-components-xcomponent.md). + 2. If OpenGL post-processing is performed after decoding, obtain NativeWindow from NativeImage. For details about the operation, see [NativeImage](../../graphics/native-image-guidelines.md). + + ```c++ + + ret = OH_VideoDecoder_SetSurface(videoDec, nativeWindow); + if (ret != AV_ERR_OK) { + // Handle exceptions. + } + ``` + +9. Destroy the OH_NativeImage instance. + + After calling **OH_VideoDecoder_Destroy**, call **OH_NativeImage_Destroy** to destroy the OH_NativeImage instance. + ```c++ + // Destroy the OH_NativeImage instance. + OH_NativeImage_Destroy(&image); + ``` diff --git a/en/application-dev/media/avcodec/video-decoding.md b/en/application-dev/media/avcodec/video-decoding.md index ecf0a8db96df9ae75ccfa38004e437214c47cc60..17b2443d7c002ba3ce3025bf17d8da28622f6689 100644 --- a/en/application-dev/media/avcodec/video-decoding.md +++ b/en/application-dev/media/avcodec/video-decoding.md @@ -16,17 +16,18 @@ Through the VideoDecoder module, your application can implement the following ke | Dynamic surface switching | Call **OH_VideoDecoder_SetSurface** to configure this capability. It is supported only in surface mode. For details, see step 6 in surface mode. | | Low-latency decoding | Call **OH_VideoDecoder_Configure** to configure this capability. For details, see step 5 in surface mode or step 5 in buffer mode. | -## Restrictions +## Constraints -- The buffer mode does not support 10-bit image data. -- After **flush()**, **reset()**, or **stop()** is called, the PPS/SPS must be transferred again in the **start()** call. For details about the example, see step 14 in [Surface Output](#surface-output). +- HDR Vivid decoding is not supported in buffer mode. +- After **flush()**, **reset()**, or **stop()** is called, the PPS/SPS must be transferred again in the **start()** call. For details about the example, see step 13 in [Surface Output](#surface-output). - If **flush()**, **reset()**, **stop()**, or **destroy()** is executed in a non-callback thread, the execution result is returned after all callbacks are executed. - Due to limited hardware decoder resources, you must call **OH_VideoDecoder_Destroy** to destroy every decoder instance when it is no longer needed. - The input streams for video decoding support only the AnnexB format, and the supported AnnexB format supports multiple slices. However, the slices of the same frame must be sent to the decoder at a time. - When **flush()**, **reset()**, or **stop()** is called, do not continue to operate the OH_AVBuffer obtained through the previous callback function. - The DRM decryption capability supports both non-secure and secure video channels in [surface mode](#surface-output), but only non-secure video channels in buffer mode (#buffer-output). - The buffer mode and surface mode use the same APIs. Therefore, the surface mode is described as an example. -- In buffer mode, after obtaining the pointer to an OH_AVBuffer object through the callback function **OH_AVCodecOnNewOutputBuffer**, call **OH_VideoDecoder_FreeOutputBuffer** to notify the system that the buffer has been fully utilized. In this way, the system can write the subsequently decoded data to the corresponding location. If the OH_NativeBuffer object is obtained through **OH_AVBuffer_GetNativeBuffer** and its lifecycle extends beyond that of the OH_AVBuffer pointer object, you mut perform data duplication. In this case, you should manage the lifecycle of the newly generated OH_NativeBuffer object to ensure that the object can be correctly used and released. +- In buffer mode, after obtaining the pointer to an OH_AVBuffer instance through the callback function **OH_AVCodecOnNewOutputBuffer**, call **OH_VideoDecoder_FreeOutputBuffer** to notify the system that the buffer has been fully utilized. In this way, the system can write the subsequently decoded data to the corresponding location. If the OH_NativeBuffer instance is obtained through **OH_AVBuffer_GetNativeBuffer** and its lifecycle extends beyond that of the OH_AVBuffer pointer instance, you mut perform data duplication. In this case, you should manage the lifecycle of the newly generated OH_NativeBuffer object to ensure that the object can be correctly used and released. + ## Surface Output and Buffer Output @@ -65,7 +66,7 @@ The following figure shows the interaction between states. - When the decoder is in the Executing state, you can call **OH_VideoDecoder_Flush** to switch it to the Flushed substate. - After all data to be processed is transferred to the decoder, the [AVCODEC_BUFFER_FLAGS_EOS](../../reference/apis-avcodec-kit/_core.md#oh_avcodecbufferflags-1) flag is added to the last input buffer in the input buffers queue. Once this flag is detected, the decoder transits to the End-of-Stream substate. In this state, the decoder does not accept new inputs, but continues to generate outputs until it reaches the tail frame. -7. When the decoder is no longer needed, you must call **OH_VideoDecoder_Destroy** to destroy the decoder instance. Then the decoder enters the Released state. +7. When the decoder is no longer needed, you must call **OH_VideoDecoder_Destroy** to destroy the decoder instance, which then transitions to the Released state. ## How to Develop @@ -89,7 +90,7 @@ target_link_libraries(sample PUBLIC libnative_media_vdec.so) > **NOTE** > -> The word 'sample' in the preceding code snippet is only an example. Use the actual project directory name. +> The word **sample** in the preceding code snippet is only an example. Use the actual project directory name. > ### Defining the Basic Structure @@ -165,7 +166,7 @@ The sample code provided in this section adheres to the C++17 standard and is fo }; ``` -4. Define global variables. +4. Configure global variables. These global variables are for reference only. They can be encapsulated into an object based on service requirements. @@ -255,17 +256,17 @@ Currently, the VideoDecoder module supports only data rotation in asynchronous m (void)errorCode; (void)userData; } - + // Implement the OH_AVCodecOnStreamChanged callback function. static void OnStreamChanged(OH_AVCodec *codec, OH_AVFormat *format, void *userData) { - // The changed video width, height, and stride can be obtained through format. + // The changed video width and height can be obtained through format. (void)codec; (void)userData; OH_AVFormat_GetIntValue(format, OH_MD_KEY_VIDEO_PIC_WIDTH, &width); OH_AVFormat_GetIntValue(format, OH_MD_KEY_VIDEO_PIC_HEIGHT, &height); } - + // Implement the OH_AVCodecOnNeedInputBuffer callback function. static void OnNeedInputBuffer(OH_AVCodec *codec, uint32_t index, OH_AVBuffer *buffer, void *userData) { @@ -274,7 +275,7 @@ Currently, the VideoDecoder module supports only data rotation in asynchronous m (void)userData; inQueue.Enqueue(std::make_shared(index, buffer)); } - + // Implement the OH_AVCodecOnNewOutputBuffer callback function. static void OnNewOutputBuffer(OH_AVCodec *codec, uint32_t index, OH_AVBuffer *buffer, void *userData) { @@ -286,9 +287,9 @@ Currently, the VideoDecoder module supports only data rotation in asynchronous m // Call OH_VideoDecoder_RegisterCallback() to register the callback functions. OH_AVCodecCallback cb = {&OnError, &OnStreamChanged, &OnNeedInputBuffer, &OnNewOutputBuffer}; // Set the asynchronous callbacks. - int32_t ret = OH_VideoDecoder_RegisterCallback(videoDec, cb, NULL); // NULL: userData is null. + int32_t ret = OH_VideoDecoder_RegisterCallback(videoDec, cb, nullptr); // nullptr: userData is null. if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` @@ -296,7 +297,7 @@ Currently, the VideoDecoder module supports only data rotation in asynchronous m > > In the callback functions, pay attention to multi-thread synchronization for operations on the data queue. > - > During video playback, if the SPS of the video stream contains color information, the decoder will return the information (RangeFlag, ColorPrimary, MatrixCoefficient, and TransferCharacteristic) through **OH_AVFormat parameter** in the **OH_AVCodecOnStreamChanged** callback. + > During video playback, if the SPS of the video stream contains color information, the decoder will return the information (RangeFlag, ColorPrimary, MatrixCoefficient, and TransferCharacteristic) through the **OH_AVFormat** parameter in the **OH_AVCodecOnStreamChanged** callback. > > In surface mode of video decoding, the internal data is processed by using High Efficiency Bandwidth Compression (HEBC) by default, and the values of **widthStride** and **heightStride** cannot be obtained. @@ -334,7 +335,7 @@ Currently, the VideoDecoder module supports only data rotation in asynchronous m DRM_ContentProtectionLevel contentProtectionLevel = CONTENT_PROTECTION_LEVEL_SW_CRYPTO; ret = OH_MediaKeySystem_CreateMediaKeySession(system, &contentProtectionLevel, &session); if (ret != DRM_OK) { - // If the creation fails, check the DRM interface document and logs. + // If the creation fails, refer to the DRM interface document and check logs. printf("create media key session failed."); return; } @@ -366,15 +367,15 @@ Currently, the VideoDecoder module supports only data rotation in asynchronous m OH_AVFormat *format = OH_AVFormat_Create(); // Set the format. - OH_AVFormat_SetIntValue (format, OH_MD_KEY_WIDTH, width); // Mandatory - OH_AVFormat_SetIntValue(format, OH_MD_KEY_HEIGHT, height); // Mandatory + OH_AVFormat_SetIntValue (format, OH_MD_KEY_WIDTH, width); // Mandatory. + OH_AVFormat_SetIntValue(format, OH_MD_KEY_HEIGHT, height); // Mandatory. OH_AVFormat_SetIntValue(format, OH_MD_KEY_PIXEL_FORMAT, pixelFormat); // (Optional) Configure low-latency decoding. OH_AVFormat_SetIntValue(format, OH_MD_KEY_VIDEO_ENABLE_LOW_LATENCY, 1); // Configure the decoder. int32_t ret = OH_VideoDecoder_Configure(videoDec, format); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } OH_AVFormat_Destroy(format); ``` @@ -389,22 +390,21 @@ Currently, the VideoDecoder module supports only data rotation in asynchronous m ```c++ // Set the window parameters. - int32_t ret = OH_VideoDecoder_SetSurface(videoDec, window); // Obtain the window from the XComponent. + int32_t ret = OH_VideoDecoder_SetSurface(videoDec, nativeWindow); // Obtain the native window from the XComponent. if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } + // Configure the matching mode between the video and screen. (Scale the buffer at the original aspect ratio to enable the smaller side of the buffer to match the window, while making the excess part transparent.) + OH_NativeWindow_NativeWindowSetScalingModeV2(nativeWindow, OH_SCALING_MODE_SCALE_CROP_V2); ``` 7. (Optional) Call **OH_VideoDecoder_SetParameter()** to set the surface parameters of the decoder. - For details about the configurable options, see [Video Dedicated Key-Value Paris](../../reference/apis-avcodec-kit/_codec_base.md#media-data-key-value-pairs). ```c++ OH_AVFormat *format = OH_AVFormat_Create(); // Configure the display rotation angle. OH_AVFormat_SetIntValue(format, OH_MD_KEY_ROTATION, 90); - // Configure the matching mode (scaling or cropping) between the video and the screen. - OH_AVFormat_SetIntValue(format, OH_MD_KEY_SCALING_MODE, SCALING_MODE_SCALE_CROP); int32_t ret = OH_VideoDecoder_SetParameter(videoDec, format); OH_AVFormat_Destroy(format); ``` @@ -414,7 +414,7 @@ Currently, the VideoDecoder module supports only data rotation in asynchronous m ```c++ ret = OH_VideoDecoder_Prepare(videoDec); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` @@ -424,7 +424,7 @@ Currently, the VideoDecoder module supports only data rotation in asynchronous m // Start the decoder. int32_t ret = OH_VideoDecoder_Start(videoDec); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` @@ -463,38 +463,38 @@ Currently, the VideoDecoder module supports only data rotation in asynchronous m // Create a CencInfo instance. OH_AVCencInfo *cencInfo = OH_AVCencInfo_Create(); if (cencInfo == nullptr) { - // Exception handling. + // Handle exceptions. } // Set the decryption algorithm. OH_AVErrCode errNo = OH_AVCencInfo_SetAlgorithm(cencInfo, DRM_ALG_CENC_AES_CTR); if (errNo != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } // Set KeyId and Iv. errNo = OH_AVCencInfo_SetKeyIdAndIv(cencInfo, keyId, keyIdLen, iv, ivLen); if (errNo != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } // Set the sample information. errNo = OH_AVCencInfo_SetSubsampleInfo(cencInfo, encryptedBlockCount, skippedBlockCount, firstEncryptedOffset, subsampleCount, subsamples); if (errNo != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } // Set the mode. KeyId, Iv, and SubSamples have been set. errNo = OH_AVCencInfo_SetMode(cencInfo, DRM_CENC_INFO_KEY_IV_SUBSAMPLES_SET); if (errNo != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } // Set CencInfo to the AVBuffer. errNo = OH_AVCencInfo_SetAVBuffer(cencInfo, buffer); if (errNo != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } // Destroy the CencInfo instance. errNo = OH_AVCencInfo_Destroy(cencInfo); if (errNo != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` @@ -504,20 +504,20 @@ Currently, the VideoDecoder module supports only data rotation in asynchronous m - **buffer**: parameter passed by the callback function **OnNeedInputBuffer**. You can obtain the virtual address of the input stream by calling [OH_AVBuffer_GetAddr](../../reference/apis-avcodec-kit/_core.md#oh_avbuffer_getaddr). - **index**: parameter passed by the callback function **OnNeedInputBuffer**, which uniquely corresponds to the buffer. - - **size**, **offset**, **pts**, and **frameData**: size, offset, timestamp, and frame data. For details about how to obtain such information, see [Media Data Demuxing](./audio-video-demuxer.md). + - **size**, **offset**, **pts**, and **frameData**: size, offset, timestamp, and frame data. For details about how to obtain such information, see step 9 in [Media Data Demuxing](./audio-video-demuxer.md). - **flags**: type of the buffer flag. For details, see [OH_AVCodecBufferFlags](../../reference/apis-avcodec-kit/_core.md#oh_avcodecbufferflags). ```c++ std::shared_ptr bufferInfo = inQueue.Dequeue(); std::shared_lock lock(codecMutex); if (bufferInfo == nullptr || !bufferInfo->isValid) { - // Exception handling. + // Handle exceptions. } // Write stream data. uint8_t *addr = OH_AVBuffer_GetAddr(bufferInfo->buffer); int32_t capcacity = OH_AVBuffer_GetCapacity(bufferInfo->buffer); if (size > capcacity) { - // Exception handling. + // Handle exceptions. } memcpy(addr, frameData, size); // Configure the size, offset, and timestamp of the frame data. @@ -529,12 +529,12 @@ Currently, the VideoDecoder module supports only data rotation in asynchronous m // Write the information to the buffer. int32_t ret = OH_AVBuffer_SetBufferAttr(bufferInfo->buffer, &info); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } // Send the data to the input buffer for decoding. index is the index of the buffer. ret = OH_VideoDecoder_PushInputBuffer(videoDec, bufferInfo->index); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` @@ -549,15 +549,15 @@ Currently, the VideoDecoder module supports only data rotation in asynchronous m std::shared_ptr bufferInfo = outQueue.Dequeue(); std::shared_lock lock(codecMutex); if (bufferInfo == nullptr || !bufferInfo->isValid) { - // Exception handling. + // Handle exceptions. } // Obtain the decoded information. OH_AVCodecBufferAttr info; int32_t ret = OH_AVBuffer_GetBufferAttr(bufferInfo->buffer, &info); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } - // The value is determined by the caller. + // You can determine the value. bool isRender; bool isNeedRenderAtTime; if (isRender) { @@ -576,7 +576,7 @@ Currently, the VideoDecoder module supports only data rotation in asynchronous m ret = OH_VideoDecoder_FreeOutputBuffer(videoDec, bufferInfo->index); } if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` @@ -600,26 +600,26 @@ Currently, the VideoDecoder module supports only data rotation in asynchronous m // Refresh the decoder. int32_t ret = OH_VideoDecoder_Flush(videoDec); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } inQueue.Flush(); outQueue.Flush(); // Start decoding again. ret = OH_VideoDecoder_Start(videoDec); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } std::shared_ptr bufferInfo = outQueue.Dequeue(); if (bufferInfo == nullptr || !bufferInfo->isValid) { - // Exception handling. + // Handle exceptions. } // Retransfer PPS/SPS. // Configure the frame PPS/SPS information. uint8_t *addr = OH_AVBuffer_GetAddr(bufferInfo->buffer); int32_t capcacity = OH_AVBuffer_GetCapacity(bufferInfo->buffer); if (xpsSize > capcacity) { - // Exception handling. + // Handle exceptions. } memcpy(addr, xpsData, xpsSize); OH_AVCodecBufferAttr info; @@ -627,12 +627,12 @@ Currently, the VideoDecoder module supports only data rotation in asynchronous m // Write the information to the buffer. ret = OH_AVBuffer_SetBufferAttr(bufferInfo->buffer, &info); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } // Push the frame data to the decoder. index is the index of the corresponding queue. ret = OH_VideoDecoder_PushInputBuffer(videoDec, bufferInfo->index); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` @@ -651,24 +651,24 @@ Currently, the VideoDecoder module supports only data rotation in asynchronous m // Reset the decoder. int32_t ret = OH_VideoDecoder_Reset(videoDec); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } inQueue.Flush(); outQueue.Flush(); // Reconfigure the decoder. ret = OH_VideoDecoder_Configure(videoDec, format); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } // Reconfigure the surface in surface mode. This is not required in buffer mode. - ret = OH_VideoDecoder_SetSurface(videoDec, window); + ret = OH_VideoDecoder_SetSurface(videoDec, nativeWindow); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } // The decoder is ready again. ret = OH_VideoDecoder_Prepare(videoDec); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` @@ -681,7 +681,7 @@ Currently, the VideoDecoder module supports only data rotation in asynchronous m // Stop the decoder. int32_t ret = OH_VideoDecoder_Stop(videoDec); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } inQueue.Flush(); outQueue.Flush(); @@ -693,18 +693,18 @@ Currently, the VideoDecoder module supports only data rotation in asynchronous m > > This API cannot be called in the callback function. > - > After the call, you must set the decoder to NULL to prevent program errors caused by wild pointers. + > After the call, you must set a null pointer to the decoder to prevent program errors caused by wild pointers. ```c++ std::unique_lock lock(codecMutex); // Call OH_VideoDecoder_Destroy to destroy the decoder. int32_t ret = AV_ERR_OK; - if (videoDec != NULL) { + if (videoDec != nullptr) { ret = OH_VideoDecoder_Destroy(videoDec); - videoDec = NULL; + videoDec = nullptr; } if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } inQueue.Flush(); outQueue.Flush(); @@ -828,9 +828,9 @@ Currently, the VideoDecoder module supports only data rotation in asynchronous m // Call OH_VideoDecoder_RegisterCallback() to register the callback functions. OH_AVCodecCallback cb = {&OnError, &OnStreamChanged, &OnNeedInputBuffer, &OnNewOutputBuffer}; // Set the asynchronous callbacks. - int32_t ret = OH_VideoDecoder_RegisterCallback(videoDec, cb, NULL); // NULL: userData is null. + int32_t ret = OH_VideoDecoder_RegisterCallback(videoDec, cb, nullptr); // nullptr: userData is null. if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` @@ -849,6 +849,7 @@ Currently, the VideoDecoder module supports only data rotation in asynchronous m #include #include ``` + Link the dynamic library in the CMake script. ``` cmake @@ -872,7 +873,7 @@ Currently, the VideoDecoder module supports only data rotation in asynchronous m DRM_ContentProtectionLevel contentProtectionLevel = CONTENT_PROTECTION_LEVEL_SW_CRYPTO; ret = OH_MediaKeySystem_CreateMediaKeySession(system, &contentProtectionLevel, &session); if (ret != DRM_OK) { - // If the creation fails, check the DRM interface document and logs. + // If the creation fails, refer to the DRM interface document and check logs. printf("create media key session failed."); return; } @@ -893,13 +894,13 @@ Currently, the VideoDecoder module supports only data rotation in asynchronous m ```c++ OH_AVFormat *format = OH_AVFormat_Create(); // Set the format. - OH_AVFormat_SetIntValue (format, OH_MD_KEY_WIDTH, width); // Mandatory - OH_AVFormat_SetIntValue(format, OH_MD_KEY_HEIGHT, height); // Mandatory + OH_AVFormat_SetIntValue (format, OH_MD_KEY_WIDTH, width); // Mandatory. + OH_AVFormat_SetIntValue(format, OH_MD_KEY_HEIGHT, height); // Mandatory. OH_AVFormat_SetIntValue(format, OH_MD_KEY_PIXEL_FORMAT, pixelFormat); // Configure the decoder. int32_t ret = OH_VideoDecoder_Configure(videoDec, format); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } OH_AVFormat_Destroy(format); ``` @@ -909,7 +910,7 @@ Currently, the VideoDecoder module supports only data rotation in asynchronous m ```c++ int32_t ret = OH_VideoDecoder_Prepare(videoDec); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` @@ -921,7 +922,7 @@ Currently, the VideoDecoder module supports only data rotation in asynchronous m // Start the decoder. int32_t ret = OH_VideoDecoder_Start(videoDec); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` @@ -948,38 +949,38 @@ Currently, the VideoDecoder module supports only data rotation in asynchronous m // Create a CencInfo instance. OH_AVCencInfo *cencInfo = OH_AVCencInfo_Create(); if (cencInfo == nullptr) { - // Exception handling. + // Handle exceptions. } // Set the decryption algorithm. OH_AVErrCode errNo = OH_AVCencInfo_SetAlgorithm(cencInfo, DRM_ALG_CENC_AES_CTR); if (errNo != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } // Set KeyId and Iv. errNo = OH_AVCencInfo_SetKeyIdAndIv(cencInfo, keyId, keyIdLen, iv, ivLen); if (errNo != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } // Set the sample information. errNo = OH_AVCencInfo_SetSubsampleInfo(cencInfo, encryptedBlockCount, skippedBlockCount, firstEncryptedOffset, subsampleCount, subsamples); if (errNo != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } // Set the mode. KeyId, Iv, and SubSamples have been set. errNo = OH_AVCencInfo_SetMode(cencInfo, DRM_CENC_INFO_KEY_IV_SUBSAMPLES_SET); if (errNo != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } // Set CencInfo to the AVBuffer. errNo = OH_AVCencInfo_SetAVBuffer(cencInfo, buffer); if (errNo != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } // Destroy the CencInfo instance. errNo = OH_AVCencInfo_Destroy(cencInfo); if (errNo != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` @@ -991,13 +992,13 @@ Currently, the VideoDecoder module supports only data rotation in asynchronous m std::shared_ptr bufferInfo = inQueue.Dequeue(); std::shared_lock lock(codecMutex); if (bufferInfo == nullptr || !bufferInfo->isValid) { - // Exception handling. + // Handle exceptions. } // Write stream data. uint8_t *addr = OH_AVBuffer_GetAddr(bufferInfo->buffer); int32_t capcacity = OH_AVBuffer_GetCapacity(bufferInfo->buffer); if (size > capcacity) { - // Exception handling. + // Handle exceptions. } memcpy(addr, frameData, size); // Configure the size, offset, and timestamp of the frame data. @@ -1009,12 +1010,12 @@ Currently, the VideoDecoder module supports only data rotation in asynchronous m // Write the information to the buffer. ret = OH_AVBuffer_SetBufferAttr(bufferInfo->buffer, &info); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } // Send the data to the input buffer for decoding. index is the index of the buffer. int32_t ret = OH_VideoDecoder_PushInputBuffer(videoDec, bufferInfo->index); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` @@ -1023,26 +1024,26 @@ Currently, the VideoDecoder module supports only data rotation in asynchronous m In the code snippet below, the following variables are used: - **index**: parameter passed by the callback function **OnNewOutputBuffer**, which uniquely corresponds to the buffer. - - buffer: parameter passed by the callback function **OnNewOutputBuffer**. You can obtain the virtual address of an image by calling [OH_AVBuffer_GetAddr](../../reference/apis-avcodec-kit/_core.md#oh_avbuffer_getaddr). + - **buffer**: parameter passed by the callback function **OnNewOutputBuffer**. You can obtain the virtual address of an image by calling [OH_AVBuffer_GetAddr](../../reference/apis-avcodec-kit/_core.md#oh_avbuffer_getaddr). ```c++ std::shared_ptr bufferInfo = outQueue.Dequeue(); std::shared_lock lock(codecMutex); if (bufferInfo == nullptr || !bufferInfo->isValid) { - // Exception handling. + // Handle exceptions. } // Obtain the decoded information. OH_AVCodecBufferAttr info; int32_t ret = OH_AVBuffer_GetBufferAttr(bufferInfo->buffer, &info); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } // Write the decoded data (specified by data) to the output file. outputFile->write(reinterpret_cast(OH_AVBuffer_GetAddr(bufferInfo->buffer)), info.size); // Free the buffer that stores the output data. index is the index of the buffer. ret = OH_VideoDecoder_FreeOutputBuffer(videoDec, bufferInfo->index); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` @@ -1073,12 +1074,12 @@ Currently, the VideoDecoder module supports only data rotation in asynchronous m int32_t height; }; - struct DstRect // Width stride and height stride of the destination buffer. They are set by the caller. + struct DstRect // Width, height, and stride of the destination buffer. They are set by the caller. { int32_t wStride; int32_t hStride; }; - // Obtain the width and height stride of the source buffer by using the callback function OnStreamChanged or OH_VideoDecoder_GetOutputDescription. + // Obtain the width, height, and stride of the source buffer by using the callback function OnStreamChanged or OH_VideoDecoder_GetOutputDescription. struct SrcRect { int32_t wStride; @@ -1096,19 +1097,19 @@ Currently, the VideoDecoder module supports only data rotation in asynchronous m // Y: Copy the source data in the Y region to the target data in another region. for (int32_t i = 0; i < rect.height; ++i) { // Copy a row of data from the source to a row of the target. - memcpy_s(dstTemp, srcTemp, rect.width); + memcpy(dstTemp, srcTemp, rect.width); // Update the pointers to the source data and target data to copy the next row. The pointers to the source data and target data are moved downwards by one wStride each time the source data and target data are updated. dstTemp += dstRect.wStride; srcTemp += srcRect.wStride; } - // padding + // Padding. // Update the pointers to the source data and target data. The pointers move downwards by one padding. dstTemp += (dstRect.hStride - rect.height) * dstRect.wStride; srcTemp += (srcRect.hStride - rect.height) * srcRect.wStride; rect.height >>= 1; // UV: Copy the source data in the UV region to the target data in another region. for (int32_t i = 0; i < rect.height; ++i) { - memcpy_s(dstTemp, srcTemp, rect.width); + memcpy(dstTemp, srcTemp, rect.width); dstTemp += dstRect.wStride; srcTemp += srcRect.wStride; } diff --git a/en/application-dev/media/avcodec/video-encoding-configuration-typical-scenarios.md b/en/application-dev/media/avcodec/video-encoding-configuration-typical-scenarios.md new file mode 100644 index 0000000000000000000000000000000000000000..5ccb5f69697be00539b0c33ae41c04fef4a12bf1 --- /dev/null +++ b/en/application-dev/media/avcodec/video-encoding-configuration-typical-scenarios.md @@ -0,0 +1,228 @@ +# Video Encoding Configurations for Typical Scenarios + +This topic provides recommended configuration parameters for AVCodec video encoding in various scenarios. It aims to help you configure video encoders according to your specific needs. + +Video encoding is used in many scenarios, including video calls, video meetings, live streaming, video editing, and video sharing. Based on user experience requirements, these scenarios can be grouped into three main categories: low-latency, real-time streaming, and offline encoding. + +This topic offers the recommended parameter settings for video encoding in these three categories. You can select the appropriate configurations based on service requirements. + + +## General Development Steps + +**Linking Dynamic Link Libraries in the CMake Script** + +```cmake +target_link_libraries(sample PUBLIC libnative_media_codecbase.so) +target_link_libraries(sample PUBLIC libnative_media_core.so) +target_link_libraries(sample PUBLIC libnative_media_venc.so) +``` + +> **NOTE** +> +> The word 'sample' in the preceding code snippet is only an example. Use the actual project directory name. +> + +**Adding Header Files** + +```c++ +#include +#include +#include +#include +#include +``` + +## Low-Latency Encoding Scenarios + +Low-latency encoding scenarios include video calls, video meetings, and interactive live streaming applications that require low end-to-end latency. + +**How to Develop** + +This section describes only the steps involved in the encoder configuration phase. You can learn the basic encoding process in [Video Encoding](video-encoding.md). + +1. Verify the support for the low-latency feature. + + Before creating an encoder instance, check whether the video encoder supports the low-latency feature. If the feature is supported, enable it during the encoder configuration phase. Otherwise, do not configure the relevant parameters. + + ```c++ + // 1.1 Obtain the handle to the capability of the video encoder. The following uses H.265 as an example. + OH_AVCapability *cap = OH_AVCodec_GetCapability(OH_AVCODEC_MIMETYPE_VIDEO_HEVC, true); + // 1.2 Check whether the low-latency feature is supported. + bool isSupported = OH_AVCapability_IsFeatureSupported(cap, VIDEO_LOW_LATENCY); + ``` + +2. Set encoder parameters. + + Configure parameters suitable for low-latency encoding scenarios. + + In low-latency encoding scenarios, the recommended encoding parameters for typical resolution (using H.265 as an example) are as follows. + + | Resolution | Frame Rate (fps)| Bit Rate (kbit/s)| Key Frame Interval (ms)| Bit Rate Control Mode| + | ------------------| -------- | -------- | ------ | ------ | + | 1902x1080 | 30 | 1500 | -1 | CBR | + | 1280x720 | 30 | 1000 | -1 | CBR | + | 960x540 | 30 | 700 | -1 | CBR | + | 640x360 | 30 | 550 | -1 | CBR | + | 320x180 | 20 | 200 | -1 | CBR | + + In the code snippet below, the following variables are used: + + **videoEnc**: pointer to a video encoder instance. For details, see step 2 in [Video Encoding Surface Mode](video-encoding.md#surface-input). + + ```c++ + // 2.1 Create an AVFormat parameter instance. + OH_AVFormat *format = OH_AVFormat_Create(); + + // 2.2 Fill in the encoding parameter key-value pairs (using the 1080p@30 fps SDR input source as an example). + OH_AVFormat_SetIntValue(format, OH_MD_KEY_WIDTH, 1920); // (Mandatory) Video width. + OH_AVFormat_SetIntValue(format, OH_MD_KEY_HEIGHT, 1080); // (Mandatory) Video height. + OH_AVFormat_SetIntValue(format, OH_MD_KEY_PIXEL_FORMAT, AV_PIXEL_FORMAT_NV12); // (Mandatory) Format of the video source data. + OH_AVFormat_SetIntValue(format, OH_MD_KEY_RANGE_FLAG, 0); // VUI information. The value 0 means a limited range, and 1 means a full range. + OH_AVFormat_SetIntValue(format, OH_MD_KEY_COLOR_PRIMARIES, OH_ColorPrimary::COLOR_PRIMARY_BT709); // VUI information, color gamut of the video source. + OH_AVFormat_SetIntValue(format, OH_MD_KEY_TRANSFER_CHARACTERISTICS, OH_TransferCharacteristic::TRANSFER_CHARACTERISTIC_BT709); // VUI information, OETF/EOTF curve. + OH_AVFormat_SetIntValue(format, OH_MD_KEY_MATRIX_COEFFICIENTS, OH_MatrixCoefficient:: MATRIX_COEFFICIENT_BT709); // VUI information, YUV and RGB conversion matrix. + OH_AVFormat_SetIntValue(format, OH_MD_KEY_PROFILE, OH_HEVCProfile::HEVC_PROFILE_MAIN); // Video encoder profile. + OH_AVFormat_SetDoubleValue(format, OH_MD_KEY_FRAME_RATE, 30.0); // (Mandatory) Video frame rate. + if (isSupported) { + // Enable the low-latency feature: one YUV frame in, one stream data frame out. + // Mandatory if the video encoder supports the low-latency feature (isSupported = true). + OH_AVFormat_SetIntValue(format, OH_MD_KEY_VIDEO_ENABLE_LOW_LATENCY, 1) + } + OH_AVFormat_SetIntValue(format, OH_MD_KEY_I_FRAME_INTERVAL, -1); // (Mandatory) Key frame interval. + OH_AVFormat_SetIntValue(format, OH_MD_KEY_VIDEO_ENCODE_BITRATE_MODE, OH_BitrateMode::BITRATE_MODE_CBR); // (Mandatory) Set the bit rate control mode to CBR. + OH_AVFormat_SetLongValue(format, OH_MD_KEY_BITRATE, 1500000); // (Mandatory). Bit rate, in bit/s. + + // 2.3 Set the encoding parameters of the video encoder. + int32_t ret = OH_VideoEncoder_Configure(videoEnc, format); + if (ret != AV_ERR_OK) { + // Handle exceptions. + } + // 2.4 Destroy the AVFormat instance after the configuration is complete. + OH_AVFormat_Destroy(format); + ``` + + > **NOTE** + > + > A key frame interval of -1 indicates that only the first frame is a key frame. You can dynamically configure encoder parameters during running based on transmission conditions and image quality to insert new key frames (IDR). + +3. (Optional) Dynamically configure encoder parameters during running. + + For details, see step 9 in [Video Encoding Surface Mode](video-encoding.md#surface-input). + + ```c++ + // 3.1 Create an AVFormat parameter instance. + OH_AVFormat *format = OH_AVFormat_Create(); + // 3.2 Fill in the encoding parameter key-value pairs (dynamically requesting IDR frames). + OH_AVFormat_SetIntValue(format, OH_MD_KEY_REQUEST_I_FRAME, true); + // 3.3 Make the encoder parameters take effect. + ret = OH_VideoEncoder_SetParameter(videoEnc, format); + if (ret != AV_ERR_OK) { + // Handle exceptions. + } + // 3.4 Destroy the AVFormat instance after the configuration is complete. + OH_AVFormat_Destroy(format); + ``` + To adapt to network fluctuations, you are advised to use the [temporally scalable video encoding](video-encoding-temporal-scalability.md) configuration. + +## Real-Time Streaming Encoding Scenarios + +Real-time streaming encoding is used in scenarios like entertainment live streaming and gaming live streaming, where the latency requirements for video are relatively low. + +**How to Develop** + +This section describes how to configure encoder parameters for real-time streaming scenarios in the encoder configuration phase. You can learn the basic encoding process in [Video Encoding](video-encoding.md). + +In entertainment live streaming scenarios, the recommended encoding parameters for typical resolution (using H.265 as an example) are as follows. + +| Resolution | Frame Rate (fps)| Bit Rate (kbit/s)| Key Frame Interval (ms)| Bit Rate Control Mode| +| ------------------| -------- | -------- | ------ | ------ | +| 1080x1920 | 25 | 3000 | 2000 | VBR | +| 720x1080 | 25 | 1500 | 2000 | VBR | +| 544x960 | 25 | 1000 | 2000 | VBR | +| 480x864 | 25 | 800 | 2000 | VBR | + +In gaming live streaming scenarios, the recommended encoding parameters for typical resolution (using H.265 as an example) are as follows. + +| Resolution | Frame Rate (fps)| Bit Rate (kbit/s)| Key Frame Interval (ms)| Bit Rate Control Mode| +| ------------------| -------- | -------- | ------ | ------ | +| 1080x1920 | 60 | 6000 | 5000 | VBR | + +```c++ +// 1. Create an AVFormat parameter instance. +OH_AVFormat *format = OH_AVFormat_Create(); +// 2. Fill in the encoding parameter key-value pair (using the 1080p@25 fps SDR input source as an example). +OH_AVFormat_SetIntValue(format, OH_MD_KEY_WIDTH, 1080); // (Mandatory) Video width. +OH_AVFormat_SetIntValue(format, OH_MD_KEY_HEIGHT, 1920); // (Mandatory) Video height. +OH_AVFormat_SetIntValue(format, OH_MD_KEY_PIXEL_FORMAT, AV_PIXEL_FORMAT_NV12); // (Mandatory) Format of the video source data. +OH_AVFormat_SetIntValue(format, OH_MD_KEY_RANGE_FLAG, 0); // VUI information. The value 0 means a limited range, and 1 means a full range. +OH_AVFormat_SetIntValue(format, OH_MD_KEY_COLOR_PRIMARIES, OH_ColorPrimary::COLOR_PRIMARY_BT709); // VUI information, color gamut of the video source. +OH_AVFormat_SetIntValue(format, OH_MD_KEY_TRANSFER_CHARACTERISTICS, OH_TransferCharacteristic::TRANSFER_CHARACTERISTIC_BT709); // VUI information, OETF/EOTF curve. +OH_AVFormat_SetIntValue(format, OH_MD_KEY_MATRIX_COEFFICIENTS, OH_MatrixCoefficient:: MATRIX_COEFFICIENT_BT709); // VUI information, YUV and RGB conversion matrix. +OH_AVFormat_SetIntValue(format, OH_MD_KEY_PROFILE, OH_HEVCProfile::HEVC_PROFILE_MAIN); // Video encoder profile. +OH_AVFormat_SetDoubleValue(format, OH_MD_KEY_FRAME_RATE, 25.0); // (Mandatory) Video frame rate. +OH_AVFormat_SetIntValue(format, OH_MD_KEY_I_FRAME_INTERVAL, 2000); // (Mandatory) Key frame interval, in ms. +OH_AVFormat_SetIntValue(format, OH_MD_KEY_VIDEO_ENCODE_BITRATE_MODE, OH_BitrateMode::BITRATE_MODE_VBR); // (Mandatory) Set the bit rate control mode to VBR. +OH_AVFormat_SetLongValue(format, OH_MD_KEY_BITRATE, 3000000); // (Mandatory). Bit rate, in bit/s. +// 3. Set the encoding parameters of the video encoder. +int32_t ret = OH_VideoEncoder_Configure(videoEnc, format); +if (ret != AV_ERR_OK) { + // Handle exceptions. +} +// 4. Destroy the AVFormat instance after the configuration is complete. +OH_AVFormat_Destroy(format); +``` + + +## Offline Encoding Scenarios + +Offline encoding is used in scenarios such as video editing and video sharing. + + +**How to Develop** + +This section describes how to configure encoder parameters for offline editing scenarios in the encoder configuration phase. You can learn the basic encoding process in [Video Encoding](video-encoding.md). + +In video editing scenarios, the recommended encoding parameters for typical resolution (using H.265 as an example) are as follows. + +| Resolution | Frame Rate (fps)| Bit Rate (kbit/s)| Key Frame Interval (ms)| Bit Rate Control Mode| +| ------------------| -------- | -------- | ------ | ------ | +| 3840x2160 | 30 | 25000 | 5000 | VBR | +| 2560x1440 | 30 | 15000 | 5000 | VBR | +| 1920x1080 | 30 | 10000 | 5000 | VBR | +| 1280x720 | 30 | 5000 | 5000 | VBR | +| 854x480 | 30 | 2000 | 5000 | VBR | + +In video sharing scenarios, the recommended encoding parameters for typical resolution (using H.265 as an example) are as follows. + +| Resolution | Frame Rate (fps)| Bit Rate (kbit/s)| Key Frame Interval (ms)| Bit Rate Control Mode| +| ------------------| -------- | -------- | ------ | ------ | +| 3840x2160 | 30 | 5600 | 5000 | VBR | +| 2560x1440 | 30 | 4900 | 5000 | VBR | +| 1920x1080 | 30 | 2100 | 5000 | VBR | +| 1280x720 | 30 | 1400 | 5000 | VBR | +| 854x480 | 30 | 400 | 5000 | VBR | + +```c++ +// 1. Create an AVFormat parameter instance. +OH_AVFormat *format = OH_AVFormat_Create(); +// 2. Fill in the encoding parameter key-value pair (using the 1080p@30 fps SDR input source as an example). +OH_AVFormat_SetIntValue(format, OH_MD_KEY_WIDTH, 1920); // (Mandatory) Video width. +OH_AVFormat_SetIntValue(format, OH_MD_KEY_HEIGHT, 1080); // (Mandatory) Video height. +OH_AVFormat_SetIntValue(format, OH_MD_KEY_PIXEL_FORMAT, AV_PIXEL_FORMAT_NV12); // (Mandatory) Format of the video source data. +OH_AVFormat_SetIntValue(format, OH_MD_KEY_RANGE_FLAG, 0); // VUI information. The value 0 means a limited range, and 1 means a full range. +OH_AVFormat_SetIntValue(format, OH_MD_KEY_COLOR_PRIMARIES, OH_ColorPrimary::COLOR_PRIMARY_BT709); // VUI information, color gamut of the video source. +OH_AVFormat_SetIntValue(format, OH_MD_KEY_TRANSFER_CHARACTERISTICS, OH_TransferCharacteristic::TRANSFER_CHARACTERISTIC_BT709); // VUI information, OETF/EOTF curve. +OH_AVFormat_SetIntValue(format, OH_MD_KEY_MATRIX_COEFFICIENTS, OH_MatrixCoefficient:: MATRIX_COEFFICIENT_BT709); // YUV and RGB conversion matrix. +OH_AVFormat_SetIntValue(format, OH_MD_KEY_PROFILE, OH_HEVCProfile::HEVC_PROFILE_MAIN); // Video encoder profile. +OH_AVFormat_SetDoubleValue(format, OH_MD_KEY_FRAME_RATE, 30.0); // (Mandatory) Video frame rate. +OH_AVFormat_SetIntValue(format, OH_MD_KEY_I_FRAME_INTERVAL, 5000); // (Mandatory) Key frame interval, in ms. +OH_AVFormat_SetIntValue(format, OH_MD_KEY_VIDEO_ENCODE_BITRATE_MODE, OH_BitrateMode::BITRATE_MODE_VBR); // (Mandatory) Set the bit rate control mode to VBR. +OH_AVFormat_SetLongValue(format, OH_MD_KEY_BITRATE, 2100000); // (Mandatory). Bit rate, in bit/s. +// 3. Set the encoding parameters of the video encoder. +int32_t ret = OH_VideoEncoder_Configure(videoEnc, format); +if (ret != AV_ERR_OK) { + // Handle exceptions. +} +// 4. Destroy the AVFormat instance after the configuration is complete. +OH_AVFormat_Destroy(format); +``` diff --git a/en/application-dev/media/avcodec/video-encoding-temporal-scalability.md b/en/application-dev/media/avcodec/video-encoding-temporal-scalability.md index 6d0337659502bf738749e3b52fd306f30edaf3f5..b3d5a9b6855742cb635d68f045840a28d0c96d25 100644 --- a/en/application-dev/media/avcodec/video-encoding-temporal-scalability.md +++ b/en/application-dev/media/avcodec/video-encoding-temporal-scalability.md @@ -56,7 +56,7 @@ If your development scenario does not involve dynamic adjustment of the temporal The reference frame is valid only in the GOP. After an I-frame is refreshed, the DPB is cleared, so does the reference frame. In other words, the I-frame refresh location has a great impact on the reference relationship. - When temporal scalability is enabled, to temporarily request the I-frame through **OH_MD_KEY_REQUEST_I_FRAME**, you must configure the frame channel with a determined effective time to notify the framework of the I-frame refresh location, so as to avoid disorder of the reference relationship. For details, see the configuration guide of the frame channel. Do not use **OH_VideoEncoder_SetParameter**, which uses an uncertain effective time. + When temporal scalability is enabled, to temporarily request the I-frame through **OH_MD_KEY_REQUEST_I_FRAME**, you must configure the frame channel with a determined effective time to notify the framework of the I-frame refresh location, so as to avoid disorder of the reference relationship. For details, see the configuration guide of the frame channel. Do not use **OH_VideoEncoder_SetParameter**, which uses an uncertain effective time. For details, see "Step 4: Call **OH_VideoEncoder_RegisterParameterCallback()** to register the frame-specific parameter callback function" in [Video Encoding in Surface Input](video-encoding.md#surface-input). - The callback using **OH_AVBuffer** is supported, but the callback using **OH_AVMemory** is not. @@ -109,7 +109,7 @@ This section describes only the steps that are different from the basic encoding 1. When creating an encoder instance, check whether the video encoder supports the global temporal scalability feature. ```c++ - // 1.1 Obtain the handle to the capability of the video encoder. The following uses H.264 as an example. + // 1.1 Obtain the video encoder capability instance. The following uses H.264 as an example. OH_AVCapability *cap = OH_AVCodec_GetCapability(OH_AVCODEC_MIMETYPE_VIDEO_AVC, true); // 1.2 Check whether the global temporal scalability feature is supported. bool isSupported = OH_AVCapability_IsFeatureSupported(cap, VIDEO_ENCODER_TEMPORAL_SCALABILITY); @@ -131,7 +131,7 @@ This section describes only the steps that are different from the basic encoding // 2.4 Configure the parameters. int32_t ret = OH_VideoEncoder_Configure(videoEnc, format); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } // 2.5 Destroy the temporary AV format after the configuration is complete. OH_AVFormat_Destroy(format); @@ -155,7 +155,7 @@ This section describes only the steps that are different from the basic encoding if (attr.flags & AVCODEC_BUFFER_FLAG_KEY_FRAME) { outPoc = 0; } - // Skip the process when there is only the XPS output, but no frame stream. + // Skip this step only for the XPS output. if (attr.flags != AVCODEC_BUFFER_FLAG_CODEC_DATA) { int32_t tGopInner = outPoc % TGOP_SIZE; if (tGopInner == 0) { @@ -182,11 +182,11 @@ The LTR feature provides a flexible configuration of the frame-level reference r | -------- | ---------------------------- | | OH_MD_KEY_VIDEO_ENCODER_LTR_FRAME_COUNT | Number of LTR frames.| | OH_MD_KEY_VIDEO_ENCODER_PER_FRAME_MARK_LTR | Marked as an LTR frame.| -| OH_MD_KEY_VIDEO_ENCODER_PER_FRAME_USE_LTR | Number of the LTR frame referenced by the current frame. | +| OH_MD_KEY_VIDEO_ENCODER_PER_FRAME_USE_LTR | POC number of the LTR frame referenced by the current frame. | -- **OH_MD_KEY_VIDEO_ENCODER_LTR_FRAME_COUNT**: This parameter is set in the configuration phase and must be less than or equal to the maximum number of LTR frames supported. +- **OH_MD_KEY_VIDEO_ENCODER_LTR_FRAME_COUNT**: This parameter is set in the configuration phase and must be less than or equal to the maximum number of LTR frames supported. For details, see Step 3 below. - **OH_MD_KEY_VIDEO_ENCODER_PER_FRAME_MARK_LTR **: The BL layer is marked as an LTR frame, and the EL layer to skip is also marked as an LTR frame. -- **OH_MD_KEY_VIDEO_ENCODER_PER_FRAME_USE_LTR **: Number of the frame marked as the LTR frame. +- **OH_MD_KEY_VIDEO_ENCODER_PER_FRAME_USE_LTR**: POC number of the frame marked as the LTR frame. For example, to implement the four-layer temporally hierarchical structure described in [Introduction to Temporally Scalable Video Coding](#introduction-to-temporally-scalable-video-coding), perform the following steps: @@ -197,7 +197,7 @@ For example, to implement the four-layer temporally hierarchical structure descr | Configuration\POC| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | | -------- |---|---|---|---|---|---|---|---|---|---|----|----|----|----|----|----|----| | MARK_LTR | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | - | USE_LTR | \ | \ | 0 | \ | 0 | \ | 4 | \ | 0 | \ | 8 | \ | 8 | \ | 12 | 0 | 8 | + | USE_LTR | \ | \ | 0 | \ | 0 | \ | 4 | \ | 0 | \ | 8 | \ | 8 | \ | 12 | \ | 8 | ### How to Develop @@ -209,7 +209,7 @@ This section describes only the steps that are different from the basic encoding constexpr int32_t NEEDED_LTR_COUNT = 5; bool isSupported = false; int32_t supportedLTRCount = 0; - // 1.1 Obtain the handle to the capability of the encoder. The following uses H.264 as an example. + // 1.1 Obtain the encoder capability instance. The following uses H.264 as an example. OH_AVCapability *cap = OH_AVCodec_GetCapability(OH_AVCODEC_MIMETYPE_VIDEO_AVC, true); // 1.2 Check whether the LTR feature is supported. isSupported = OH_AVCapability_IsFeatureSupported(cap, VIDEO_ENCODER_LONG_TERM_REFERENCE); @@ -313,7 +313,7 @@ This section describes only the steps that are different from the basic encoding // 3.3 Configure the parameters. int32_t ret = OH_VideoEncoder_Configure(videoEnc, format); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } // 3.4 Destroy the temporary AV format after the configuration is complete. OH_AVFormat_Destroy(format); diff --git a/en/application-dev/media/avcodec/video-encoding.md b/en/application-dev/media/avcodec/video-encoding.md index e42cc03260fd1d0acefc186df87d1212e7f6ae0d..eee9b355177fdf73b4389b3eb96c551f271dc651 100644 --- a/en/application-dev/media/avcodec/video-encoding.md +++ b/en/application-dev/media/avcodec/video-encoding.md @@ -1,6 +1,6 @@ # Video Encoding -You can call the native APIs provided by the VideoEncoder module to encode a video, that is, to compress video data into video streams. +You can call the native APIs provided by the VideoEncoder module to encode a video, that is, to compress video data into a video stream. @@ -14,16 +14,18 @@ The following table lists the video encoding capabilities supported: | Capability | How to Use | | --------------------------------------- | ---------------------------------------------------------------------------------- | | Layered encoding
Setting the LTR frame and reference frame | For details, see [Temporally Scalable Video Coding](video-encoding-temporal-scalability.md). | +| Repeat encoding of historical frames | For details, see [OH_MD_KEY_VIDEO_ENCODER_REPEAT_PREVIOUS_FRAME_AFTER](../../reference/apis-avcodec-kit/_codec_base.md#oh_md_key_video_encoder_repeat_previous_frame_after) and
[OH_MD_KEY_VIDEO_ENCODER_REPEAT_PREVIOUS_MAX_COUNT](../../reference/apis-avcodec-kit/_codec_base.md#oh_md_key_video_encoder_repeat_previous_max_count). | -## Restrictions +## Constraints - The buffer mode does not support 10-bit image data. - Due to limited hardware encoder resources, you must call **OH_VideoEncoder_Destroy** to destroy every encoder instance when it is no longer needed. - If **flush()**, **reset()**, **stop()**, or **destroy()** is executed in a non-callback thread, the execution result is returned after all callbacks are executed. - Once **Flush**, **Reset**, or **Stop** is called, the system reclaims the OH_AVBuffer. Therefore, do not continue to operate the OH_AVBuffer obtained through the previous callback function. - The buffer mode and surface mode use the same APIs. Therefore, the surface mode is described as an example. -- In buffer mode, after obtaining the pointer to an OH_AVBuffer object through the callback function **OH_AVCodecOnNeedInputBuffer**, call **OH_VideoEncoder_PushInputBuffer** to notify the system that the buffer has been fully utilized. In this way, the system will proceed with encoding the data contained in the buffer. If the OH_NativeBuffer object is obtained through **OH_AVBuffer_GetNativeBuffer** and its lifecycle extends beyond that of the OH_AVBuffer pointer object, you mut perform data duplication. In this case, you should manage the lifecycle of the newly generated OH_NativeBuffer object to ensure that the object can be correctly used and released. +- In buffer mode, after obtaining the pointer to an OH_AVBuffer instance through the callback function **OH_AVCodecOnNeedInputBuffer**, call **OH_VideoEncoder_PushInputBuffer** to notify the system that the buffer has been fully utilized. In this way, the system will proceed with encoding the data contained in the buffer. If the OH_NativeBuffer instance is obtained through **OH_AVBuffer_GetNativeBuffer** and its lifecycle extends beyond that of the OH_AVBuffer pointer instance, you mut perform data duplication. In this case, you should manage the lifecycle of the newly generated OH_NativeBuffer object to ensure that the object can be correctly used and released. + ## Surface Input and Buffer Input @@ -35,7 +37,7 @@ The following table lists the video encoding capabilities supported: - The two also differ slightly in the API calling modes: - In buffer mode, the caller calls **OH_VideoEncoder_PushInputBuffer** to input data. In surface mode, the caller, before the encoder is ready, calls **OH_VideoEncoder_GetSurface** to obtain the OHNativeWindow for video data transmission. - - In buffer mode, the caller uses **attr** in **OH_AVBuffer** to pass in the End of Stream (EOS) flag, and the encoder stops when it reads the last frame. In surface mode, the caller calls **OH_VideoEncoder_NotifyEndOfStream** to notify the encoder of EOS. + - In buffer mode, you can use **attr** in **OH_AVBuffer** to pass in the End of Stream (EOS) flag, and the encoder stops when it reads the last frame. In surface mode, the caller calls **OH_VideoEncoder_NotifyEndOfStream** to notify the encoder of EOS. For details about the development procedure, see [Surface Input](#surface-input) and [Buffer Input](#buffer-input). @@ -62,7 +64,7 @@ The following figure shows the interaction between states. - When the encoder is in the Executing state, you can call **OH_VideoEncoder_Flush** to switch it to the Flushed substate. - After all data to be processed is transferred to the encoder, the [AVCODEC_BUFFER_FLAGS_EOS](../../reference/apis-avcodec-kit/_core.md#oh_avcodecbufferflags-1) flag is added to the last input buffer in the input buffers queue. Once this flag is detected, the encoder transits to the End-of-Stream substate. In this state, the encoder does not accept new inputs, but continues to generate outputs until it reaches the tail frame. -7. When the encoder is no longer needed, you must call **OH_VideoEncoder_Destroy** to destroy the encoder instance. Then the encoder enters the Released state. +7. When the encoder is no longer needed, you must call **OH_VideoEncoder_Destroy** to destroy the encoder instance, which then transitions to the Released state. ## How to Develop @@ -86,7 +88,7 @@ target_link_libraries(sample PUBLIC libnative_media_venc.so) > **NOTE** > -> The word 'sample' in the preceding code snippet is only an example. Use the actual project directory name. +> The word **sample** in the preceding code snippet is only an example. Use the actual project directory name. > ### Defining the Basic Structure @@ -165,7 +167,7 @@ The sample code provided in this section adheres to the C++17 standard and is fo }; ``` -4. Define global variables. +4. Configure global variables. These global variables are for reference only. They can be encapsulated into an object based on service requirements. @@ -221,7 +223,7 @@ Currently, the VideoEncoder module supports only data rotation in asynchronous m // Create an encoder by name. If your application has special requirements, for example, expecting an encoder that supports a certain resolution, you can call OH_AVCodec_GetCapability to query the capability first. OH_AVCapability *capability = OH_AVCodec_GetCapability(OH_AVCODEC_MIMETYPE_VIDEO_AVC, true); // Create a hardware encoder instance. - OH_AVCapability *capability= OH_AVCodec_GetCapabilityByCategory(OH_AVCODEC_MIMETYPE_VIDEO_AVC, false, HARDWARE); + OH_AVCapability *capability= OH_AVCodec_GetCapabilityByCategory(OH_AVCODEC_MIMETYPE_VIDEO_AVC, true, HARDWARE); const char *codecName = OH_AVCapability_GetName(capability); OH_AVCodec *videoEnc = OH_VideoEncoder_CreateByName(codecName); ``` @@ -299,9 +301,9 @@ Currently, the VideoEncoder module supports only data rotation in asynchronous m ```c++ // Call OH_VideoEncoder_RegisterCallback() to register the callback functions. OH_AVCodecCallback cb = {&OnError, &OnStreamChanged, &OnNeedInputBuffer, &OnNewOutputBuffer}; - int32_t ret = OH_VideoEncoder_RegisterCallback(videoEnc, cb, NULL); // NULL: userData is null. + int32_t ret = OH_VideoEncoder_RegisterCallback(videoEnc, cb, nullptr); // nullptr: userData is null. if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` @@ -324,7 +326,7 @@ Currently, the VideoEncoder module supports only data rotation in asynchronous m // 4.2 Register the frame-specific parameter callback function. OH_VideoEncoder_OnNeedInputParameter inParaCb = OnNeedInputParameter; - OH_VideoEncoder_RegisterParameterCallback(videoEnc, inParaCb, NULL); // NULL: userData is null. + OH_VideoEncoder_RegisterParameterCallback(videoEnc, inParaCb, nullptr); // nullptr: userData is null. ``` @@ -356,18 +358,18 @@ Currently, the VideoEncoder module supports only data rotation in asynchronous m // Configure the encoding profile. int32_t profile = static_cast(OH_AVCProfile::AVC_PROFILE_HIGH); // Configure the encoding bit rate mode. - int32_t rateMode = static_cast(OH_VideoEncodeBitrateMode::VBR); + int32_t rateMode = static_cast(OH_BitrateMode::BITRATE_MODE_VBR); // Configure the key frame interval, in milliseconds. int32_t iFrameInterval = 1000; - // Configure the bit rate. + // Configure the bit rate, in bit/s. int64_t bitRate = 5000000; // Set the encoding quality. int64_t quality = 90; OH_AVFormat *format = OH_AVFormat_Create(); - OH_AVFormat_SetIntValue (format, OH_MD_KEY_WIDTH, width); // Mandatory - OH_AVFormat_SetIntValue(format, OH_MD_KEY_HEIGHT, height); // Mandatory - OH_AVFormat_SetIntValue(format, OH_MD_KEY_PIXEL_FORMAT, pixelFormat); // Mandatory + OH_AVFormat_SetIntValue (format, OH_MD_KEY_WIDTH, width); // Mandatory. + OH_AVFormat_SetIntValue(format, OH_MD_KEY_HEIGHT, height); // Mandatory. + OH_AVFormat_SetIntValue(format, OH_MD_KEY_PIXEL_FORMAT, pixelFormat); // Mandatory. OH_AVFormat_SetDoubleValue(format, OH_MD_KEY_FRAME_RATE, frameRate); OH_AVFormat_SetIntValue(format, OH_MD_KEY_RANGE_FLAG, rangeFlag); @@ -376,17 +378,17 @@ Currently, the VideoEncoder module supports only data rotation in asynchronous m OH_AVFormat_SetIntValue(format, OH_MD_KEY_MATRIX_COEFFICIENTS, matrix); OH_AVFormat_SetIntValue(format, OH_MD_KEY_I_FRAME_INTERVAL, iFrameInterval); OH_AVFormat_SetIntValue(format, OH_MD_KEY_PROFILE, profile); - // Configure OH_MD_KEY_QUALITY only when OH_MD_KEY_BITRATE = CQ is used. - if (rateMode == static_cast(OH_VideoEncodeBitrateMode::CQ)) { + // Configure OH_MD_KEY_QUALITY only when OH_BitrateMode = BITRATE_MODE_CQ is used. + if (rateMode == static_cast(OH_BitrateMode::BITRATE_MODE_CQ)) { OH_AVFormat_SetIntValue(format, OH_MD_KEY_QUALITY, quality); - } else if (rateMode == static_cast(OH_VideoEncodeBitrateMode::CBR) || - rateMode == static_cast(OH_VideoEncodeBitrateMode::VBR)){ + } else if (rateMode == static_cast(OH_BitrateMode::BITRATE_MODE_CBR) || + rateMode == static_cast(OH_BitrateMode::BITRATE_MODE_VBR)){ OH_AVFormat_SetLongValue(format, OH_MD_KEY_BITRATE, bitRate); } OH_AVFormat_SetIntValue(format, OH_MD_KEY_VIDEO_ENCODE_BITRATE_MODE, rateMode); int32_t ret = OH_VideoEncoder_Configure(videoEnc, format); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } OH_AVFormat_Destroy(format); ``` @@ -397,14 +399,14 @@ Currently, the VideoEncoder module supports only data rotation in asynchronous m 6. Obtain a surface. - Obtain the OHNativeWindow in surface mode. The surface must be obtained before the encoder is prepared. + Obtain the OHNativeWindow in surface mode. The surface must be obtained before **OH_VideoEncoder_Prepare** is called. ```c++ // Obtain the surface used for data input. OHNativeWindow *nativeWindow; int32_t ret = OH_VideoEncoder_GetSurface(videoEnc, &nativeWindow); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } // Use the OHNativeWindow* variable to obtain the address of the data to be filled through the producer interface. ``` @@ -416,7 +418,7 @@ Currently, the VideoEncoder module supports only data rotation in asynchronous m ```c++ int32_t ret = OH_VideoEncoder_Prepare(videoEnc); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` @@ -430,13 +432,11 @@ Currently, the VideoEncoder module supports only data rotation in asynchronous m // Start the encoder. int32_t ret = OH_VideoEncoder_Start(videoEnc); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` 9. (Optional) Call **OH_VideoEncoder_SetParameter()** to dynamically configure encoder parameters during running. - - For details about the configurable options, see [Video Dedicated Key-Value Paris](../../reference/apis-avcodec-kit/_codec_base.md#media-data-key-value-pairs). ```c++ @@ -445,7 +445,7 @@ Currently, the VideoEncoder module supports only data rotation in asynchronous m OH_AVFormat_SetIntValue(format, OH_MD_KEY_REQUEST_I_FRAME, true); int32_t ret = OH_VideoEncoder_SetParameter(videoEnc, format); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } OH_AVFormat_Destroy(format); ``` @@ -468,14 +468,14 @@ Currently, the VideoEncoder module supports only data rotation in asynchronous m std::shared_ptr bufferInfo = inQueue.Dequeue(); std::shared_lock lock(codecMutex); if (bufferInfo == nullptr || !bufferInfo->isValid) { - // Exception handling. + // Handle exceptions. } - // The value is determined by the caller. + // You can determine the value. int32_t isIFrame; OH_AVFormat_SetIntValue(bufferInfo->parameter, OH_MD_KEY_REQUEST_I_FRAME, isIFrame); int32_t ret = OH_VideoEncoder_PushInputParameter(videoEnc, bufferInfo->index); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` @@ -486,7 +486,7 @@ Currently, the VideoEncoder module supports only data rotation in asynchronous m // In buffer mode, you need to set the AVCODEC_BUFFER_FLAGS_EOS flag and then call OH_VideoEncoder_PushInputBuffer to notify the encoder of EOS. int32_t ret = OH_VideoEncoder_NotifyEndOfStream(videoEnc); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` @@ -501,20 +501,20 @@ Currently, the VideoEncoder module supports only data rotation in asynchronous m std::shared_ptr bufferInfo = outQueue.Dequeue(); std::shared_lock lock(codecMutex); if (bufferInfo == nullptr || !bufferInfo->isValid) { - // Exception handling. + // Handle exceptions. } // Obtain the encoded information. OH_AVCodecBufferAttr info; int32_t ret = OH_AVBuffer_GetBufferAttr(bufferInfo->buffer, &info); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } // Write the encoded frame data (specified by buffer) to the output file. outputFile->write(reinterpret_cast(OH_AVBuffer_GetAddr(bufferInfo->buffer)), info.size); // Free the output buffer. index is the index of the buffer. ret = OH_VideoEncoder_FreeOutputBuffer(videoEnc, bufferInfo->index); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` @@ -529,14 +529,14 @@ Currently, the VideoEncoder module supports only data rotation in asynchronous m // Refresh the encoder. int32_t ret = OH_VideoEncoder_Flush(videoEnc); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } inQueue.Flush(); outQueue.Flush(); // Start encoding again. ret = OH_VideoEncoder_Start(videoEnc); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` @@ -549,34 +549,34 @@ Currently, the VideoEncoder module supports only data rotation in asynchronous m // Reset the encoder. int32_t ret = OH_VideoEncoder_Reset(videoEnc); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } inQueue.Flush(); outQueue.Flush(); // Reconfigure the encoder. + OH_AVFormat *format = OH_AVFormat_Create(); ret = OH_VideoEncoder_Configure(videoEnc, format); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } + OH_AVFormat_Destroy(format); // The encoder is ready again. ret = OH_VideoEncoder_Prepare(videoEnc); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` 16. (Optional) Call **OH_VideoEncoder_Stop()** to stop the encoder. - After **OH_VideoEncoder_Stop** is called, the encoder retains the encoding instance and releases the input and output buffers. You can directly call **OH_VideoEncoder_Start** to continue encoding. - - The first **buffer** passed must carry the parameter set, starting from the IDR frame. + After **OH_VideoEncoder_Stop** is called, the encoder retains the encoding instance and releases the input and output buffers. You can directly call **OH_VideoEncoder_Start** to continue encoding. The first **buffer** passed must carry the parameter set, starting from the IDR frame. ```c++ std::unique_lock lock(codecMutex); // Stop the encoder. int32_t ret = OH_VideoEncoder_Stop(videoEnc); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } inQueue.Flush(); outQueue.Flush(); @@ -587,23 +587,24 @@ Currently, the VideoEncoder module supports only data rotation in asynchronous m > **NOTE** > > This API cannot be called in the callback function. - > After the call, you must set the encoder to NULL to prevent program errors caused by wild pointers. + > + > After the call, you must set a null pointer to the encoder to prevent program errors caused by wild pointers. ```c++ std::unique_lock lock(codecMutex); // Release the nativeWindow instance. - if(nativeWindow != NULL){ + if(nativeWindow != nullptr){ OH_NativeWindow_DestroyNativeWindow(nativeWindow); - nativeWindow = NULL; + nativeWindow = nullptr; } // Call OH_VideoEncoder_Destroy to destroy the encoder. int32_t ret = AV_ERR_OK; - if (videoEnc != NULL) { + if (videoEnc != nullptr) { ret = OH_VideoEncoder_Destroy(videoEnc); - videoEnc = NULL; + videoEnc = nullptr; } if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } inQueue.Flush(); outQueue.Flush(); @@ -716,9 +717,9 @@ Currently, the VideoEncoder module supports only data rotation in asynchronous m ```c++ // Call OH_VideoEncoder_RegisterCallback() to register the callback functions. OH_AVCodecCallback cb = {&OnError, &OnStreamChanged, &OnNeedInputBuffer, &OnNewOutputBuffer}; - int32_t ret = OH_VideoEncoder_RegisterCallback(videoEnc, cb, NULL); + int32_t ret = OH_VideoEncoder_RegisterCallback(videoEnc, cb, nullptr); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` @@ -734,13 +735,13 @@ Currently, the VideoEncoder module supports only data rotation in asynchronous m ```c++ OH_AVFormat *format = OH_AVFormat_Create(); // Set the format. - OH_AVFormat_SetIntValue (format, OH_MD_KEY_WIDTH, width); // Mandatory - OH_AVFormat_SetIntValue(format, OH_MD_KEY_HEIGHT, height); // Mandatory - OH_AVFormat_SetIntValue(format, OH_MD_KEY_PIXEL_FORMAT, pixelFormat); // Mandatory + OH_AVFormat_SetIntValue (format, OH_MD_KEY_WIDTH, width); // Mandatory. + OH_AVFormat_SetIntValue(format, OH_MD_KEY_HEIGHT, height); // Mandatory. + OH_AVFormat_SetIntValue(format, OH_MD_KEY_PIXEL_FORMAT, pixelFormat); // Mandatory. // Configure the encoder. int32_t ret = OH_VideoEncoder_Configure(videoEnc, format); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } OH_AVFormat_Destroy(format); ``` @@ -752,7 +753,7 @@ Currently, the VideoEncoder module supports only data rotation in asynchronous m ```c++ ret = OH_VideoEncoder_Prepare(videoEnc); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` @@ -771,7 +772,7 @@ Currently, the VideoEncoder module supports only data rotation in asynchronous m // Start the encoder. int32_t ret = OH_VideoEncoder_Start(videoEnc); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` @@ -784,7 +785,7 @@ Currently, the VideoEncoder module supports only data rotation in asynchronous m OH_AVFormat_SetIntValue(format, OH_MD_KEY_REQUEST_I_FRAME, true); int32_t ret = OH_VideoEncoder_SetParameter(videoEnc, format); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } OH_AVFormat_Destroy(format); ``` @@ -803,7 +804,7 @@ Currently, the VideoEncoder module supports only data rotation in asynchronous m std::shared_ptr bufferInfo = inQueue.Dequeue(); std::shared_lock lock(codecMutex); if (bufferInfo == nullptr || !bufferInfo->isValid) { - // Exception handling. + // Handle exceptions. } // Write image data. if (widthStride == width) { @@ -821,22 +822,22 @@ Currently, the VideoEncoder module supports only data rotation in asynchronous m info.flags = flags; int32_t ret = OH_AVBuffer_SetBufferAttr(bufferInfo->buffer, &info); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } // Configure the buffer frame-specific information. - // The value is determined by the caller. + // You can determine the value. int32_t isIFrame; OH_AVFormat *parameter = OH_AVBuffer_GetParameter(bufferInfo->buffer); OH_AVFormat_SetIntValue(parameter, OH_MD_KEY_REQUEST_I_FRAME, isIFrame); ret = OH_AVBuffer_SetParameter(bufferInfo->buffer, parameter); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } OH_AVFormat_Destroy(parameter); // Send the data to the input buffer for encoding. index is the index of the buffer. ret = OH_VideoEncoder_PushInputBuffer(videoEnc, bufferInfo->index); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` Offset the stride. The following uses an NV12 image as an example, presenting the image layout of **width**, **height**, **wStride**, and **hStride**. @@ -857,7 +858,7 @@ Currently, the VideoEncoder module supports only data rotation in asynchronous m The following is the sample code: ```c++ - struct Rect // Width and height of the source buffer. They are set by the caller. + struct Rect // Width and height of the source buffer. You can set them as required. { int32_t width; int32_t height; @@ -869,7 +870,7 @@ Currently, the VideoEncoder module supports only data rotation in asynchronous m int32_t hStride; }; - struct SrcRect // Width stride and height stride of the source buffer. They are set by the caller. + struct SrcRect // Width stride and height stride of the source buffer. You can set them as required. { int32_t wStride; int32_t hStride; @@ -886,19 +887,19 @@ Currently, the VideoEncoder module supports only data rotation in asynchronous m // Y: Copy the source data in the Y region to the target data in another region. for (int32_t i = 0; i < rect.height; ++i) { // Copy a row of data from the source to a row of the target. - memcpy_s(dstTemp, srcTemp, rect.width); + memcpy(dstTemp, srcTemp, rect.width); // Update the pointers to the source data and target data to copy the next row. The pointers to the source data and target data are moved downwards by one wStride each time the source data and target data are updated. dstTemp += dstRect.wStride; srcTemp += srcRect.wStride; } - // padding + // Padding. // Update the pointers to the source data and target data. The pointers move downwards by one padding. dstTemp += (dstRect.hStride - rect.height) * dstRect.wStride; srcTemp += (srcRect.hStride - rect.height) * srcRect.wStride; rect.height >>= 1; // UV: Copy the source data in the UV region to the target data in another region. for (int32_t i = 0; i < rect.height; ++i) { - memcpy_s(dstTemp, srcTemp, rect.width); + memcpy(dstTemp, srcTemp, rect.width); dstTemp += dstRect.wStride; srcTemp += srcRect.wStride; } @@ -923,7 +924,7 @@ Currently, the VideoEncoder module supports only data rotation in asynchronous m std::shared_ptr bufferInfo = inQueue.Dequeue(); std::shared_lock lock(codecMutex); if (bufferInfo == nullptr || !bufferInfo->isValid) { - // Exception handling. + // Handle exceptions. } OH_AVCodecBufferAttr info; info.size = 0; @@ -932,11 +933,11 @@ Currently, the VideoEncoder module supports only data rotation in asynchronous m info.flags = AVCODEC_BUFFER_FLAGS_EOS; int32_t ret = OH_AVBuffer_SetBufferAttr(bufferInfo->buffer, &info); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ret = OH_VideoEncoder_PushInputBuffer(videoEnc, bufferInfo->index); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` @@ -948,20 +949,20 @@ Currently, the VideoEncoder module supports only data rotation in asynchronous m std::shared_ptr bufferInfo = outQueue.Dequeue(); std::shared_lock lock(codecMutex); if (bufferInfo == nullptr || !bufferInfo->isValid) { - // Exception handling. + // Handle exceptions. } // Obtain the encoded information. OH_AVCodecBufferAttr info; int32_t ret = OH_AVBuffer_GetBufferAttr(bufferInfo->buffer, &info); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } // Write the encoded frame data (specified by buffer) to the output file. outputFile->write(reinterpret_cast(OH_AVBuffer_GetAddr(bufferInfo->buffer)), info.size); // Free the output buffer. index is the index of the buffer. ret = OH_VideoEncoder_FreeOutputBuffer(videoEnc, bufferInfo->index); if (ret != AV_ERR_OK) { - // Exception handling. + // Handle exceptions. } ``` diff --git a/en/application-dev/media/avcodec/video-variable-refreshrate.md b/en/application-dev/media/avcodec/video-variable-refreshrate.md new file mode 100644 index 0000000000000000000000000000000000000000..17fa16a3dd445f5a21e8397240f0bf05c496d8ed --- /dev/null +++ b/en/application-dev/media/avcodec/video-variable-refreshrate.md @@ -0,0 +1,67 @@ +# Video Variable Frame Rate + +With the C APIs related to the video variable refresh rate feature, you can dynamically adjust the screen refresh rate based on the video content during playback. This helps save display power while maintaining smooth video playback. + +## When to Use + +The video variable refresh rate feature is ideal for video sources with high frame rates (>30 fps). For video sources with frame rates at or below 30 fps, a refresh rate of 30 Hz is recommended. + +The figure below demonstrates the playback of a 60 fps video. The algorithm adjusts the screen refresh rate in real-time based on the video content. If the refresh rate drops below the video frame rate, some frames will be discarded to save power. + +![Video variable refreshrate](figures/video-variable-refreshrate.png) + +## Constraints + +1. This feature is available only for the scenario where the video is directly sent for display after hardware decoding. +2. The overall screen refresh rate will change. It is recommended that you use this feature in full-screen playback scenarios without bullet comments or animations, as the feature may affect their smoothness. +3. This feature depends on the decoding frame rate configuration. The **OH_MD_KEY_FRAME_RATE** property must be correctly set before use. +4. This feature is platform-dependent. If the platform does not support this feature, the API calls do not report an error, but the feature does not take effect. Normal decoding and playback still function. + +## How to Develop + +This section describes only the steps that are different from the basic decoding process. You can learn the basic decoding process in [Video Decoding](video-decoding.md). + +1. Enable the video variable frame rate feature during decoder configuration. + + In the code snippet below, the following variables are used: + + **videoDec**: pointer to the video decoder instance. For details, see [Creating a Decoder Instance in Surface Mode](video-decoding.md#surface-output). + + ```cpp + OH_AVFormat *format = OH_AVFormat_Create(); + int32_t width = 1280; // Video frame width. + int32_t height = 720; // Video frame height. + int32_t fps = 60; // Video frame rate. + OH_AVFormat_SetIntValue(format, OH_MD_KEY_WIDTH, width); + OH_AVFormat_SetIntValue(format, OH_MD_KEY_HEIGHT, height); + OH_AVFormat_SetIntValue(format, OH_MD_KEY_FRAME_RATE, fps); + OH_AVFormat_SetIntValue(format, OH_MD_KEY_VIDEO_DECODER_OUTPUT_ENABLE_VRR, 1); + int32_t ret = OH_VideoDecoder_Configure(videoDec, format); + if (ret != AV_ERR_OK) { + // Handle exceptions. + } + OH_AVFormat_Destroy(format); + ``` + +2. (Optional) Dynamically enable or disable the variable frame rate feature during video playback. + + If bullet comments are enabled during playback, you can disable the variable frame rate feature to avoid wasting resources, since the refresh rate adjustments are not applied. + + The following code snippet is used to dynamically disable the feature: + + ```cpp + OH_AVFormat *format = OH_AVFormat_Create(); + OH_AVFormat_SetIntValue(format, OH_MD_KEY_VIDEO_DECODER_OUTPUT_ENABLE_VRR, 0); + OH_VideoDecoder_SetParameter(videoDec, format); + OH_AVFormat_Destroy(format); + ``` + + The following code snippet is used to dynamically enable the feature: + + ```cpp + OH_AVFormat *format = OH_AVFormat_Create(); + OH_AVFormat_SetIntValue(format, OH_MD_KEY_FRAME_RATE, fps); + OH_AVFormat_SetIntValue(format, OH_MD_KEY_VIDEO_DECODER_OUTPUT_ENABLE_VRR, 1); + OH_VideoDecoder_SetParameter(videoDec, format); + OH_AVFormat_Destroy(format); + ``` diff --git a/en/application-dev/media/avsession/Readme-EN.md b/en/application-dev/media/avsession/Readme-EN.md index 0d7515d9dc8de18999f23a3e4e117f968675aba0..a7e77f1b9a2d5dad4c25ded296808e491ab21763 100644 --- a/en/application-dev/media/avsession/Readme-EN.md +++ b/en/application-dev/media/avsession/Readme-EN.md @@ -1,7 +1,7 @@ # AVSession Kit - [Introduction to AVSession Kit](avsession-overview.md) -- Local AVSession +- Local AVSession - [Local AVSession Overview](local-avsession-overview.md) - [AVSession Provider](using-avsession-developer.md) - [AVSession Provider (C/C++)](using-ohavsession-developer.md) @@ -9,7 +9,7 @@ - [AVSession Controller (for System Applications Only)](using-avsession-controller.md) -- Distributed AVSession +- Distributed AVSession - [Distributed AVSession Overview (for System Applications Only)](distributed-avsession-overview.md) - [Using Distributed AVSession (for System Applications Only)](using-distributed-avsession.md) diff --git a/en/application-dev/media/avsession/avsession-access-scene.md b/en/application-dev/media/avsession/avsession-access-scene.md index 0e02f0a531c7de008f4cdf0e13682fdd7686f6cd..464b4ca138192e81419036c2a779808455d7b1e6 100644 --- a/en/application-dev/media/avsession/avsession-access-scene.md +++ b/en/application-dev/media/avsession/avsession-access-scene.md @@ -109,6 +109,9 @@ async function setListener() { // The LRC contains two types of elements: time tag + lyrics, and ID tag. // Example: [00:25.44]xxx\r\n[00:26.44]xxx\r\n lyric: "Lyrics in LRC format", + // The singleLyricText field stores a single line of lyric text without timestamps. + // Example: "Content of a single lyric line" + singleLyricText: "Content of a single lyric line", }; session.setAVMetadata(metadata).then(() => { console.info(`SetAVMetadata successfully`); @@ -171,7 +174,7 @@ async function setSessionInfo() { // It is assumed that an AVSession object has been created. For details about how to create an AVSession object, see the node snippet above. let session = await AVSessionManager.createAVSession(context, 'SESSION_NAME', 'audio'); - // The player logic that triggers changes in the AVSession metadata and playback state information is omitted here. + // The player logic that triggers changes in the session metadata and playback state is omitted here. // Set the playback state to paused and set isFavorite to false. let playbackState: AVSessionManager.AVPlaybackState = { state:AVSessionManager.PlaybackState.PLAYBACK_STATE_PAUSE, @@ -543,14 +546,14 @@ Currently, the system does not provide APIs for listening for multimodal key eve Register the [HandleMediaKeyEvent](../../reference/apis-avsession-kit/js-apis-avsession.md#onhandlekeyevent10) callback through AVSession. The callback directly forwards the [KeyEvent](../../reference/apis-input-kit/js-apis-keyevent.md). The application is required to identify the type of the key event and implement the corresponding functionalities. Currently, the following key events can be forwarded: | Key Type ([KeyCode](../../reference/apis-input-kit/js-apis-keycode.md#keycode))| Description | | ------ | -------------------------| - | KEYCODE_MEDIA_PLAY_PAUSE | Play/Pause key. | - | KEYCODE_MEDIA_STOP | Stop key. | - | KEYCODE_MEDIA_NEXT | Next key. | - | KEYCODE_MEDIA_PREVIOUS | Previous key. | - | KEYCODE_MEDIA_REWIND | Rewind key. | - | KEYCODE_MEDIA_FAST_FORWARD | Fast forward key. | - | KEYCODE_MEDIA_PLAY | Play key. | - | KEYCODE_MEDIA_PAUSE | Pause key. | + | KEYCODE_MEDIA_PLAY_PAUSE | Play/Pause key.| + | KEYCODE_MEDIA_STOP | Stop key.| + | KEYCODE_MEDIA_NEXT | Next key.| + | KEYCODE_MEDIA_PREVIOUS | Previous key.| + | KEYCODE_MEDIA_REWIND | Rewind key.| + | KEYCODE_MEDIA_FAST_FORWARD | Fast forward key.| + | KEYCODE_MEDIA_PLAY | Play key.| + | KEYCODE_MEDIA_PAUSE | Pause key.| ```ts import { avSession as AVSessionManager } from '@kit.AVSessionKit'; diff --git a/en/application-dev/media/avsession/using-avsession-controller.md b/en/application-dev/media/avsession/using-avsession-controller.md index fb75c05d6085b58ac8163b023f156cb98b4fc12f..a05c9412de9f23232254b66aa2b0522b7b6c6038 100644 --- a/en/application-dev/media/avsession/using-avsession-controller.md +++ b/en/application-dev/media/avsession/using-avsession-controller.md @@ -23,45 +23,46 @@ For details, see [AVSession Management](../../reference/apis-avsession-kit/js-ap ### APIs Called by the AVSessionManager Object -| API | Description | +| API| Description| | -------- | -------- | -| getAllSessionDescriptors(callback: AsyncCallback<Array<Readonly<AVSessionDescriptor>>>): void | Obtains the descriptors of all AVSessions in the system. | -| createController(sessionId: string, callback: AsyncCallback<AVSessionController>): void | Creates an AVSessionController. | -| sendSystemAVKeyEvent(event: KeyEvent, callback: AsyncCallback<void>): void | Sends a key event to the top session. | -| sendSystemControlCommand(command: AVControlCommand, callback: AsyncCallback<void>): void | Sends a playback control command to the top session. | -| getHistoricalSessionDescriptors(maxSize: number, callback: AsyncCallback\>>): void10+ | Obtains the descriptors of historical sessions. | +| getAllSessionDescriptors(callback: AsyncCallback<Array<Readonly<AVSessionDescriptor>>>): void | Obtains the descriptors of all AVSessions in the system.| +| createController(sessionId: string, callback: AsyncCallback<AVSessionController>): void | Creates an AVSessionController.| +| sendSystemAVKeyEvent(event: KeyEvent, callback: AsyncCallback<void>): void | Sends a key event to the top session.| +| sendSystemControlCommand(command: AVControlCommand, callback: AsyncCallback<void>): void | Sends a playback control command to the top session.| +| getHistoricalSessionDescriptors(maxSize: number, callback: AsyncCallback\>>): void10+ | Obtains the descriptors of historical sessions.| ### APIs Called by the AVSessionController Object -| API | Description | +| API| Description| | -------- | -------- | -| getAVPlaybackState(callback: AsyncCallback<AVPlaybackState>): void10+ | Obtains the information related to the playback state. | -| getAVMetadata(callback: AsyncCallback<AVMetadata>): void10+ | Obtains the session metadata. | -| getOutputDevice(callback: AsyncCallback<OutputDeviceInfo>): void10+ | Obtains the output device information. | +| getAVPlaybackState(callback: AsyncCallback<AVPlaybackState>): void10+ | Obtains the information related to the playback state.| +| getAVMetadata(callback: AsyncCallback<AVMetadata>): void10+ | Obtains the session metadata.| +| getOutputDevice(callback: AsyncCallback<OutputDeviceInfo>): void10+ | Obtains the output device information.| | sendAVKeyEvent(event: KeyEvent, callback: AsyncCallback<void>): void10+ | Sends a key event to the session corresponding to this controller.| -| getLaunchAbility(callback: AsyncCallback<WantAgent>): void10+ | Obtains the **WantAgent** object saved by the application in the session. | -| isActive(callback: AsyncCallback<boolean>): void10+ | Checks whether the session is activated. | -| destroy(callback: AsyncCallback<void>): void10+ | Destroys this controller. A controller can no longer be used after being destroyed. | -| getValidCommands(callback: AsyncCallback<Array<AVControlCommandType>>): void10+ | Obtains valid commands supported by the session. | -| sendControlCommand(command: AVControlCommand, callback: AsyncCallback<void>): void10+ | Sends a playback control command to the session through the controller. | -| sendCommonCommand(command: string, args: {[key: string]: Object}, callback: AsyncCallback<void>): void10+ | Sends a custom playback control command to the session through the controller. | -| getAVQueueItems(callback: AsyncCallback<Array<AVQueueItem>>): void10+ | Obtains the information related to the items in the playlist. | -| getAVQueueTitle(callback: AsyncCallback<string>): void10+ | Obtains the name of the playlist. | -| skipToQueueItem(itemId: number, callback: AsyncCallback<void>): void10+ | Sends the ID of an item in the playlist to the session for processing. The session can play the song. | -| getExtras(callback: AsyncCallback<{[key: string]: Object}>): void10+ | Obtains the custom media packet set by the provider. | -| getOutputDeviceSync(): OutputDeviceInfo10+ | Obtains the output device information. This API is a synchronous API. | -| getAVPlaybackStateSync(): AVPlaybackState10+ | Obtains the information related to the playback state. This API is a synchronous API. | -| getAVMetadataSync(): AVMetadata10+ | Obtains the session metadata. This API is a synchronous API. | -| getAVQueueTitleSync(): string10+ | Obtains the name of the playlist. This API is a synchronous API. | -| getAVQueueItemsSync(): Array<AVQueueItem>10+ | Obtains the information related to the items in the playlist. This API is a synchronous API. | -| isActiveSync(): boolean10+ | Checks whether the session is activated. This API is a synchronous API. | -| getValidCommandsSync(): Array<AVControlCommandType>10+ | Obtains valid commands supported by the session. This API is a synchronous API. | +| getLaunchAbility(callback: AsyncCallback<WantAgent>): void10+ | Obtains the **WantAgent** object saved by the application in the session.| +| isActive(callback: AsyncCallback<boolean>): void10+ | Checks whether the session is activated.| +| destroy(callback: AsyncCallback<void>): void10+ | Destroys this controller. A controller can no longer be used after being destroyed.| +| getValidCommands(callback: AsyncCallback<Array<AVControlCommandType>>): void10+ | Obtains valid commands supported by the session.| +| sendControlCommand(command: AVControlCommand, callback: AsyncCallback<void>): void10+ | Sends a playback control command to the session through the controller.| +| sendCommonCommand(command: string, args: {[key: string]: Object}, callback: AsyncCallback<void>): void10+ | Sends a custom playback control command to the session through the controller.| +| getAVQueueItems(callback: AsyncCallback<Array<AVQueueItem>>): void10+ | Obtains the information related to the items in the playlist.| +| getAVQueueTitle(callback: AsyncCallback<string>): void10+ | Obtains the name of the playlist.| +| skipToQueueItem(itemId: number, callback: AsyncCallback<void>): void10+ | Sends the ID of an item in the playlist to the session for processing. The session can play the song.| +| getExtras(callback: AsyncCallback<{[key: string]: Object}>): void10+ | Obtains the custom media packet set by the provider.| +| getOutputDeviceSync(): OutputDeviceInfo10+ | Obtains the output device information. This API returns the result synchronously. | +| getAVPlaybackStateSync(): AVPlaybackState10+ | Obtains the information related to the playback state. This API returns the result synchronously. | +| getAVMetadataSync(): AVMetadata10+ | Obtains the session metadata. This API returns the result synchronously. | +| getAVQueueTitleSync(): string10+ | Obtains the name of the playlist. This API returns the result synchronously. | +| getAVQueueItemsSync(): Array<AVQueueItem>10+ | Obtains the information related to the items in the playlist. This API returns the result synchronously. | +| isActiveSync(): boolean10+ | Checks whether the session is activated. This API returns the result synchronously.| +| getValidCommandsSync(): Array<AVControlCommandType>10+ | Obtains valid commands supported by the session. This API returns the result synchronously.| ## How to Develop To enable a system application to access the AVSession service as a controller, proceed as follows: 1. Obtain **AVSessionDescriptor** through AVSessionManager and create an **AVSessionController** object. + The controller may obtain all **AVSessionDescriptor**s in the current system, and create an **AVSessionController** object for each session, so as to perform unified playback control on all the audio and video applications. ```ts @@ -102,7 +103,7 @@ To enable a system application to access the AVSession service as a controller, ``` 2. Listen for the session state and service state events. - + The following session state events are available: - **sessionCreate**: triggered when a session is created. @@ -283,7 +284,7 @@ To enable a system application to access the AVSession service as a controller, ``` 5. Control the playback behavior, for example, sending a command to operate (play/pause/previous/next) the item being played in Media Controller. - + After listening for the playback control command event, the audio and video application serving as the provider needs to implement the corresponding operation. ```ts diff --git a/en/application-dev/media/avsession/using-avsession-developer.md b/en/application-dev/media/avsession/using-avsession-developer.md index bf178760b54ccbb368eb45a1513dfd35e0447669..ecd51d08af9275f322e077276e3ba02f032e4304 100644 --- a/en/application-dev/media/avsession/using-avsession-developer.md +++ b/en/application-dev/media/avsession/using-avsession-developer.md @@ -348,7 +348,7 @@ To enable an audio and video application to access the AVSession service as a pr // Alternatively, listen for state changes. controller.on('playbackStateChange', 'all', (state) => { - // do some things + // Do some things. }); // The AVSessionController object can perform many operations. For details, see the description of the controller. diff --git a/en/application-dev/media/avsession/using-ohavsession-developer.md b/en/application-dev/media/avsession/using-ohavsession-developer.md index 907146cf9a70f00762dd0f6121cb317e3ed15860..b6a35c515069aace69adb2cccb2e4dc9a3473fa6 100644 --- a/en/application-dev/media/avsession/using-ohavsession-developer.md +++ b/en/application-dev/media/avsession/using-ohavsession-developer.md @@ -73,7 +73,7 @@ To access a local session with the NDK, perform the following steps: OH_AVMetadataBuilder_GenerateAVMetadata(builder, &ohMetadata); ``` - When the OH_AVMetadataBuilder is no longer needed, call **OH_AVMetadataBuilder_Destroy** to destroy it and do not use it any more. + When the OH_AVMetadataBuilder is no longer needed, call **OH_AVMetadataBuilder_Destroy** to destroy it and do not use it anymore. ```c++ OH_AVMetadata_Destroy(ohMetadata); @@ -117,11 +117,11 @@ To access a local session with the NDK, perform the following steps: ```c++ // Register the callbacks for the commands of play, pause, stop, play previous, and play next. - // CONTROL_CMD_PLAY = 0; play - // CONTROL_CMD_PAUSE = 1; pause - // CONTROL_CMD_STOP = 2; stop - // CONTROL_CMD_PLAY_NEXT = 3; play previous - // CONTROL_CMD_PLAY_PREVIOUS = 4; play next + // CONTROL_CMD_PLAY = 0; play. + // CONTROL_CMD_PAUSE = 1; pause. + // CONTROL_CMD_STOP = 2; stop. + // CONTROL_CMD_PLAY_NEXT = 3; play previous. + // CONTROL_CMD_PLAY_PREVIOUS = 4; play next. AVSession_ControlCommand command = CONTROL_CMD_PLAY; OH_AVSessionCallback_OnCommand commandCallback = [](OH_AVSession* session, AVSession_ControlCommand command, void* userData) -> AVSessionCallback_Result @@ -148,7 +148,7 @@ To access a local session with the NDK, perform the following steps: |OH_AVSession_RegisterSeekCallback(OH_AVSession* avsession, OH_AVSessionCallback_OnSeek callback, void* userData); | Registers a callback for the seek operation. | |OH_AVSession_RegisterToggleFavoriteCallback(OH_AVSession* avsession, OH_AVSessionCallback_OnToggleFavorite callback, void* userData)| Registers a callback for the favorite operation. | 5. When the audio and video application exits and does not need to continue playback, cancel the listener and destroy the **AVSession** object. The sample code is as follows: - + ```c++ OH_AVSession_Destroy(avsession); ``` diff --git a/en/application-dev/media/avsession/using-switch-call-devices.md b/en/application-dev/media/avsession/using-switch-call-devices.md index d4ba529b6813e1fbaf85b6066ec48e2dd03db7c7..9eed5af1ae0fce47c92166d11c5afc82d359a11c 100644 --- a/en/application-dev/media/avsession/using-switch-call-devices.md +++ b/en/application-dev/media/avsession/using-switch-call-devices.md @@ -133,7 +133,7 @@ The differences are as follows: } } - // Custom content + // Custom content. @Builder ImageBuilder(): void { Image(this.pickerImage) diff --git a/en/application-dev/media/camera/Readme-EN.md b/en/application-dev/media/camera/Readme-EN.md index 657400a7f4529bc6bd585ca687c346af6034ab1e..86ef7db7739788ec32797104c2319b7514242f50 100644 --- a/en/application-dev/media/camera/Readme-EN.md +++ b/en/application-dev/media/camera/Readme-EN.md @@ -2,7 +2,7 @@ - [Introduction to Camera Kit](camera-overview.md) - [Camera Development Preparations](camera-preparation.md) -- Camera Development (ArkTS) +- Camera Development (ArkTS) - [Camera Device Management (ArkTS)](camera-device-management.md) - [Device Input Management (ArkTS)](camera-device-input.md) - [Camera Session Management (ArkTS)](camera-session-management.md) @@ -22,7 +22,7 @@ - [Depth Data (for System Applications Only) (ArkTS)](camera-depth-data.md) -- Camera Best Practices (ArkTS) +- Camera Best Practices (ArkTS) - [Using the Camera Picker (ArkTS)](camera-picker.md) - [Photo Capture Sample (ArkTS)](camera-shooting-case.md) - [Video Recording Sample (ArkTS)](camera-recording-case.md) @@ -33,7 +33,7 @@ - [Using Performance Improvement Features (for System Applications Only) (ArkTS)](camera-performance-improvement.md) - [High-Performance Photo Capture Sample (for System Applications Only) (ArkTS)](camera-deferred-photo-case.md) -- Camera Development (C/C++) +- Camera Development (C/C++) - [Camera Device Management (C/C++)](native-camera-device-management.md) - [Device Input Management (C/C++)](native-camera-device-input.md) - [Camera Session Management (C/C++)](native-camera-session-management.md) @@ -44,6 +44,6 @@ - [Video Recording (C/C++)](native-camera-recording.md) - [Camera Metadata (C/C++)](native-camera-metadata.md) - [Using the Flashlight (C/C++)](native-camera-torch-use.md) -- Camera Best Practices (C/C++) +- Camera Best Practices (C/C++) - [Photo Capture Sample (C/C++)](native-camera-shooting-case.md) - [Video Recording Sample (C/C++)](native-camera-recording-case.md) diff --git a/en/application-dev/media/camera/camera-background-recovery.md b/en/application-dev/media/camera/camera-background-recovery.md index 2e6df0e2ad6ed7894662620a9e1408ecee2c22a6..9497f751ac960b2dc96e8b02d9a50f81e076cf29 100644 --- a/en/application-dev/media/camera/camera-background-recovery.md +++ b/en/application-dev/media/camera/camera-background-recovery.md @@ -82,7 +82,7 @@ During the transition of the camera application from the background to the foreg console.error(`Camera input error code: ${error.code}`); }); - // Open a camera. + // Open the camera. await cameraInput.open(); // Obtain the supported modes. @@ -92,7 +92,7 @@ During the transition of the camera application from the background to the foreg console.error('photo mode not support'); return; } - // Obtain the output streams supported by the camera device. + // Obtain the output stream capability supported by the camera. let cameraOutputCap: camera.CameraOutputCapability = cameraManager.getSupportedOutputCapability(cameraArray[0], camera.SceneMode.NORMAL_PHOTO); if (!cameraOutputCap) { console.error("cameraManager.getSupportedOutputCapability error"); diff --git a/en/application-dev/media/camera/camera-deferred-capture-case.md b/en/application-dev/media/camera/camera-deferred-capture-case.md index 7badeb83015eac94201ca19986b3fe4278b70ea3..ea52a0362c194e0a0a868eb2e335c68e7930ca2c 100644 --- a/en/application-dev/media/camera/camera-deferred-capture-case.md +++ b/en/application-dev/media/camera/camera-deferred-capture-case.md @@ -126,7 +126,7 @@ async function deferredCaptureCase(baseContext: common.BaseContext, surfaceId: s console.error(`Camera input error code: ${error.code}`); }) - // Open a camera. + // Open the camera. await cameraInput.open(); // Obtain the supported modes. @@ -136,7 +136,7 @@ async function deferredCaptureCase(baseContext: common.BaseContext, surfaceId: s console.error('photo mode not support'); return; } - // Obtain the output streams supported by the camera. + // Obtain the output stream capability supported by the camera. let cameraOutputCap: camera.CameraOutputCapability = cameraManager.getSupportedOutputCapability(cameraArray[0], camera.SceneMode.NORMAL_PHOTO); if (!cameraOutputCap) { diff --git a/en/application-dev/media/camera/camera-deferred-photo-case.md b/en/application-dev/media/camera/camera-deferred-photo-case.md index 2239c96a638f521bc94cde4f18ea4f90206594fe..92f0141459d63fd84cac667e42a17fef2214c2a0 100644 --- a/en/application-dev/media/camera/camera-deferred-photo-case.md +++ b/en/application-dev/media/camera/camera-deferred-photo-case.md @@ -119,7 +119,7 @@ async function deferredPhotoCase(baseContext: common.BaseContext, surfaceId: str console.error(`Camera input error code: ${error.code}`); }) - // Open a camera. + // Open the camera. await cameraInput.open(); // Obtain the supported modes. @@ -129,7 +129,7 @@ async function deferredPhotoCase(baseContext: common.BaseContext, surfaceId: str console.error('photo mode not support'); return; } - // Obtain the output streams supported by the camera. + // Obtain the output stream capability supported by the camera. let cameraOutputCap: camera.CameraOutputCapability = cameraManager.getSupportedOutputCapability(cameraArray[0], camera.SceneMode.NORMAL_PHOTO); if (!cameraOutputCap) { console.error("cameraManager.getSupportedOutputCapability error"); diff --git a/en/application-dev/media/camera/camera-deferred-photo.md b/en/application-dev/media/camera/camera-deferred-photo.md index 3690a04dd3d26f85e81de2aa930aa35cf3abdc03..c7e5fd4e81de29959120175f2637b103ea5882a6 100644 --- a/en/application-dev/media/camera/camera-deferred-photo.md +++ b/en/application-dev/media/camera/camera-deferred-photo.md @@ -100,7 +100,7 @@ Read [Camera](../../reference/apis-camera-kit/js-apis-camera.md) for the API ref return; } console.info('photoOutPutCallBack deferredPhotoProxyAvailable'); - // Obtain the pixel map of a thumbnail. + // Obtain the PixelMap of a thumbnail. proxyObj.getThumbnail().then((thumbnail: image.PixelMap) => { AppStorage.setOrCreate('proxyThumbnail', thumbnail); }); @@ -125,7 +125,7 @@ Read [Camera](../../reference/apis-camera-kit/js-apis-camera.md) for the API ref let accessHelper = photoAccessHelper.getPhotoAccessHelper(context); let testFileName = 'testFile' + Date.now() + '.jpg'; let photoAsset = await accessHelper.createAsset(testFileName); - // Pass the thumbnail proxy class object to the mediaLibrary. + // Pass the thumbnail proxy class object to the media library. let mediaRequest: photoAccessHelper.MediaAssetChangeRequest = new photoAccessHelper.MediaAssetChangeRequest(photoAsset); mediaRequest.addResource(photoAccessHelper.ResourceType.PHOTO_PROXY, proxyObj); let res = await accessHelper.applyChanges(mediaRequest); diff --git a/en/application-dev/media/camera/camera-depth-data.md b/en/application-dev/media/camera/camera-depth-data.md index fc87650eaccf873aa8ba9cdc5a76ecd8cd64a80e..b7b0dfbd5ca6faadffbeb2d701b34ca7ae9d3075 100644 --- a/en/application-dev/media/camera/camera-depth-data.md +++ b/en/application-dev/media/camera/camera-depth-data.md @@ -17,7 +17,10 @@ Read [Camera](../../reference/apis-camera-kit/js-apis-camera.md) for the API ref ```ts function getDepthDataOutput(cameraManager: camera.CameraManager, cameraOutputCapability: camera.CameraOutputCapability): camera.DepthDataOutput | undefined { - let depthProfilesArray: Array = cameraOutputCapability.depthProfiles; + let depthProfilesArray: Array = cameraOutputCapability.depthProfiles; + if (!depthProfilesArray) { + console.error("createOutput depthProfilesArray is null"); + } let depthDataOutput: camera.DepthDataOutput | undefined = undefined; try { depthDataOutput = cameraManager.createDepthDataOutput(depthProfilesArray[0]); @@ -29,7 +32,7 @@ Read [Camera](../../reference/apis-camera-kit/js-apis-camera.md) for the API ref } ``` -3. Call [start](../../reference/apis-camera-kit/js-apis-camera-sys.md#start12) in the **depthDataOutput** class to start outputting the depth data stream. If the call fails, an error code is returned. For details about the error code types, see [CameraErrorCode](../../reference/apis-camera-kit/js-apis-camera.md#cameraerrorcode). +3. Call [start](../../reference/apis-camera-kit/js-apis-camera-sys.md#start13) in the **depthDataOutput** class to start outputting the depth data stream. If the call fails, an error code is returned. For details about the error code types, see [CameraErrorCode](../../reference/apis-camera-kit/js-apis-camera.md#cameraerrorcode). ```ts async function startDepthDataOutput(depthDataOutput: camera.DepthDataOutput): Promise { diff --git a/en/application-dev/media/camera/camera-device-input.md b/en/application-dev/media/camera/camera-device-input.md index d10a450c284d8ef0ceae23c19f80dbdc096b7a35..05ad20da42347fa8359313398b54cecb151a9e21 100644 --- a/en/application-dev/media/camera/camera-device-input.md +++ b/en/application-dev/media/camera/camera-device-input.md @@ -66,7 +66,7 @@ Read [Camera](../../reference/apis-camera-kit/js-apis-camera.md) for the API ref ```ts async function getSupportedOutputCapability(cameraDevice: camera.CameraDevice, cameraManager: camera.CameraManager, sceneMode: camera.SceneMode): Promise { - // Obtain the output streams supported by the camera device. + // Obtain the output stream capability supported by the camera. let cameraOutputCapability: camera.CameraOutputCapability = cameraManager.getSupportedOutputCapability(cameraDevice, sceneMode); if (!cameraOutputCapability) { console.error("cameraManager.getSupportedOutputCapability error"); diff --git a/en/application-dev/media/camera/camera-dual-channel-preview.md b/en/application-dev/media/camera/camera-dual-channel-preview.md index a40a4589403ffb0737eccd175261722321950145..87ada9d003db55efff03838feaa09a62cfaddde8 100644 --- a/en/application-dev/media/camera/camera-dual-channel-preview.md +++ b/en/application-dev/media/camera/camera-dual-channel-preview.md @@ -33,12 +33,12 @@ The figure below shows the recommended API calling process of the dual-channel p ```ts import { image } from '@kit.ImageKit'; - imageWidth: number = 1920; // Use the width in the profile size supported by the device. - imageHeight: number = 1080; // Use the height in the profile size supported by the device. + let imageWidth: number = 1920; // Use the width in the profile size supported by the device. + let imageHeight: number = 1080; // Use the height in the profile size supported by the device. async function initImageReceiver():Promise{ // Create an ImageReceiver object. - let size: image.Size = { width: this.imageWidth, height: this.imageHeight }; + let size: image.Size = { width: imageWidth, height: imageHeight }; let imageReceiver = image.createImageReceiver(size, image.ImageFormat.JPEG, 8); // Obtain the surface ID for the first preview stream. let imageReceiverSurfaceId = await imageReceiver.getReceivingSurfaceId(); @@ -162,6 +162,7 @@ struct example { this.surfaceId = this.xComponentCtl.getXComponentSurfaceId(); // Obtain the surface ID of the component. // Use the surface ID to create a preview stream and start the camera. The component renders the preview stream data of each frame in real time. }) + // The width and height of the surface are opposite to those of the XComponent. Alternatively, you can use .renderFit(RenderFit.RESIZE_CONTAIN) to automatically adjust the display without manually setting the width and height. .width(px2vp(this.imageHeight)) .height(px2vp(this.imageWidth)) } @@ -327,11 +328,11 @@ struct Index { .width('100%') } - // Initialize the camera. + // Initialize a camera. async initCamera(): Promise { console.info(`initCamera imageReceiverSurfaceId:${this.imageReceiverSurfaceId} xComponentSurfaceId:${this.xComponentSurfaceId}`); try { - // Obtain the camera manager instance. + // Obtain a camera manager instance. this.cameraManager = camera.getCameraManager(getContext(this)); if (!this.cameraManager) { console.error('initCamera getCameraManager'); diff --git a/en/application-dev/media/camera/camera-foldable-display.md b/en/application-dev/media/camera/camera-foldable-display.md index 776c255dfb5700613500898aebebd2e3ad24e47d..a00787438e547f6365552028c659530d865d4906 100644 --- a/en/application-dev/media/camera/camera-foldable-display.md +++ b/en/application-dev/media/camera/camera-foldable-display.md @@ -124,7 +124,7 @@ struct Index { private mCameraInput: camera.CameraInput | undefined = undefined; private mPreviewOutput: camera.PreviewOutput | undefined = undefined; private mPhotoSession: camera.PhotoSession | undefined = undefined; - // One of the recommended preview resolutions + // One of the recommended preview resolutions. private previewProfileObj: camera.Profile = { format: 1003, size: { @@ -314,7 +314,7 @@ struct Index { return; } - // Open a camera. + // Open the camera. try { await this.mCameraInput.open(); } catch (error) { @@ -322,7 +322,7 @@ struct Index { console.error(TAG + 'Failed to open device, errorCode = ' + err.code); } - // Obtain the supported scene modes. + // Obtain the supported modes. let sceneModes: Array = this.mCameraManager.getSupportedSceneModes(this.curCameraDevice); let isSupportPhotoMode: boolean = sceneModes.indexOf(camera.SceneMode.NORMAL_PHOTO) >= 0; if (!isSupportPhotoMode) { @@ -330,7 +330,7 @@ struct Index { return; } - // Obtain the output streams supported by the camera device. + // Obtain the output stream capability supported by the camera. let cameraOutputCapability: camera.CameraOutputCapability = this.mCameraManager.getSupportedOutputCapability(this.curCameraDevice, camera.SceneMode.NORMAL_PHOTO); if (!cameraOutputCapability) { diff --git a/en/application-dev/media/camera/camera-metadata.md b/en/application-dev/media/camera/camera-metadata.md index 4d77cdbe2f0fc6085c830c134693571c08633ee4..1879d8c7b982c725ea6ef0afeaf63b01a93bfab8 100644 --- a/en/application-dev/media/camera/camera-metadata.md +++ b/en/application-dev/media/camera/camera-metadata.md @@ -56,7 +56,7 @@ Read [Camera](../../reference/apis-camera-kit/js-apis-camera.md) for the API ref console.error('cameraInput is undefined'); return; } - // Open a camera. + // Open the camera. await cameraInput.open(); let session: camera.PhotoSession = cameraManager.createSession(camera.SceneMode.NORMAL_PHOTO) as camera.PhotoSession; session.beginConfig(); diff --git a/en/application-dev/media/camera/camera-performance-improvement.md b/en/application-dev/media/camera/camera-performance-improvement.md index a037d4b17b623c85fc5d4283562eaaa3ac56a327..0b58377dc6072d56733c3c96ef6e314e60e52e4a 100644 --- a/en/application-dev/media/camera/camera-performance-improvement.md +++ b/en/application-dev/media/camera/camera-performance-improvement.md @@ -121,7 +121,7 @@ async function enableQuickThumbnail(baseContext: common.BaseContext, photoProfil } function showOrSavePicture(pixelMap: image.PixelMap): void { - //do something + // Do something. } ``` diff --git a/en/application-dev/media/camera/camera-picker.md b/en/application-dev/media/camera/camera-picker.md index 330f46873a51a01abadaf7aa0d467fe279175ee5..172f0128c78ed71fa698837943b4f099bd1a0586 100644 --- a/en/application-dev/media/camera/camera-picker.md +++ b/en/application-dev/media/camera/camera-picker.md @@ -8,10 +8,6 @@ If your application only needs to obtain photos or videos taken in real time, it Given that users are the ones who actively take and confirm the photos, your application does not need to request the permission to operate the camera. -## Constraints - -During application debugging, you must call the camera picker in release mode. If it is called in debug mode, an exception occurs. - ## How to Develop Read [CameraPicker](../../reference/apis-camera-kit/js-apis-cameraPicker.md) for the API reference. diff --git a/en/application-dev/media/camera/camera-preview.md b/en/application-dev/media/camera/camera-preview.md index cae77032ccabcca5eb1a9b3aa20fa8a201e082af..27cb5117e23bb6c507c91fbc09ffe698da1ab0c4 100644 --- a/en/application-dev/media/camera/camera-preview.md +++ b/en/application-dev/media/camera/camera-preview.md @@ -62,7 +62,7 @@ Read [Camera](../../reference/apis-camera-kit/js-apis-camera.md) for the API ref console.error('cameraInput is undefined'); return; } - // Open a camera. + // Open the camera. await cameraInput.open(); let session: camera.PhotoSession = cameraManager.createSession(camera.SceneMode.NORMAL_PHOTO) as camera.PhotoSession; session.beginConfig(); diff --git a/en/application-dev/media/camera/camera-recording-case.md b/en/application-dev/media/camera/camera-recording-case.md index 10c1afccdf5943371feffa678051fe4b009238f0..2f5152dd9666c47e6e2ad83bb6bb49481d60dc25 100644 --- a/en/application-dev/media/camera/camera-recording-case.md +++ b/en/application-dev/media/camera/camera-recording-case.md @@ -6,6 +6,7 @@ This topic provides sample code that covers the complete recording process to he Before referring to the sample code, you are advised to read [Device Input Management](camera-device-input.md), [Camera Session Management](camera-session-management.md), [Video Recording](camera-recording.md), and other related topics in [Camera Development (ArkTS)](camera-preparation.md). +To save videos to the media library, follow the instructions provided in [Saving Media Assets](../medialibrary/photoAccessHelper-savebutton.md). ## Development Process After obtaining the output stream capabilities supported by the camera, create a video stream. The development process is as follows: @@ -21,11 +22,10 @@ import { camera } from '@kit.CameraKit'; import { BusinessError } from '@kit.BasicServicesKit'; import { media } from '@kit.MediaKit'; import { common } from '@kit.AbilityKit'; -import { photoAccessHelper } from '@kit.MediaLibraryKit'; import { fileIo as fs } from '@kit.CoreFileKit'; async function videoRecording(context: common.Context, surfaceId: string): Promise { - // Create a CameraManager instance. + // Create a CameraManager object. let cameraManager: camera.CameraManager = camera.getCameraManager(context); if (!cameraManager) { console.error("camera.getCameraManager error"); @@ -64,7 +64,7 @@ async function videoRecording(context: common.Context, surfaceId: string): Promi return; } - // Obtain the output stream capabilities supported by the camera. + // Obtain the output stream capability supported by the camera. let cameraOutputCap: camera.CameraOutputCapability = cameraManager.getSupportedOutputCapability(cameraArray[0], camera.SceneMode.NORMAL_VIDEO); if (!cameraOutputCap) { console.error("cameraManager.getSupportedOutputCapability error") @@ -83,21 +83,14 @@ async function videoRecording(context: common.Context, surfaceId: string): Promi } let videoProfilesArray: Array = cameraOutputCap.videoProfiles; - if (!videoProfilesArray) { + if (!videoProfilesArray || videoProfilesArray.length === 0) { console.error("createOutput videoProfilesArray == null || undefined"); } + // The width and height of videoProfile must be the same as those of AVRecorderProfile. - let videoSize: camera.Size = { - width: 640, - height: 480 - } - let videoProfile: undefined | camera.VideoProfile = videoProfilesArray.find((profile: camera.VideoProfile) => { - return profile.size.width === videoSize.width && profile.size.height === videoSize.height; - }); - if (!videoProfile) { - console.error('videoProfile is not found'); - return; - } + // In this sample code, the first video profile is selected. You need to select a video profile as required. + let videoProfile: camera.VideoProfile = videoProfilesArray[0]; + let isHdr = videoProfile.format === camera.CameraFormat.CAMERA_FORMAT_YCBCR_P010 || videoProfile.format === camera.CameraFormat.CAMERA_FORMAT_YCRCB_P010; // Configure the parameters based on those supported by the hardware device. let aVRecorderProfile: media.AVRecorderProfile = { audioBitrate: 48000, @@ -106,16 +99,13 @@ async function videoRecording(context: common.Context, surfaceId: string): Promi audioSampleRate: 48000, fileFormat: media.ContainerFormatType.CFT_MPEG_4, videoBitrate: 2000000, - videoCodec: media.CodecMimeType.VIDEO_AVC, - videoFrameWidth: videoSize.width, - videoFrameHeight: videoSize.height, - videoFrameRate: 30 + videoCodec: isHdr ? media.CodecMimeType.VIDEO_HEVC : media.CodecMimeType.VIDEO_AVC, + videoFrameWidth: videoProfile.size.width, + videoFrameHeight: videoProfile.size.height, + videoFrameRate: 30, + isHdr: isHdr }; - let options: photoAccessHelper.CreateOptions = { - title: Date.now().toString() - }; - let accessHelper: photoAccessHelper.PhotoAccessHelper = photoAccessHelper.getPhotoAccessHelper(context); - let videoUri: string = await accessHelper.createAsset(photoAccessHelper.PhotoType.VIDEO, 'mp4', options); + let videoUri: string = `file://${context.filesDir}/${Date.now()}.mp4`; // Local sandbox path. let file: fs.File = fs.openSync(videoUri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); let aVRecorderConfig: media.AVRecorderConfig = { audioSourceType: media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, @@ -230,16 +220,22 @@ async function videoRecording(context: common.Context, surfaceId: string): Promi // Create a preview output stream. For details about the surfaceId parameter, see the XComponent. The preview stream is the surface provided by the XComponent. let previewOutput: camera.PreviewOutput | undefined = undefined; + let previewProfile = previewProfilesArray.find((previewProfile: camera.Profile) => { + return Math.abs((previewProfile.size.width / previewProfile.size.height) - (videoProfile.size.width / videoProfile.size.height)) < Number.EPSILON; + }); // Select the preview resolution with the same aspect ratio as the recording resolution. + if (previewProfile === undefined) { + return; + } try { - previewOutput = cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId); + previewOutput = cameraManager.createPreviewOutput(previewProfile, surfaceId); } catch (error) { let err = error as BusinessError; console.error(`Failed to create the PreviewOutput instance. error: ${JSON.stringify(err)}`); } - if (previewOutput === undefined) { return; } + // Add the preview output stream to the session. try { videoSession.addOutput(previewOutput); @@ -248,7 +244,7 @@ async function videoRecording(context: common.Context, surfaceId: string): Promi console.error(`Failed to add previewOutput. error: ${JSON.stringify(err)}`); } - // Add a video output stream to the session. + // Add the video output stream to the session. try { videoSession.addOutput(videoOutput); } catch (error) { @@ -309,7 +305,7 @@ async function videoRecording(context: common.Context, surfaceId: string): Promi // Stop the session. await videoSession.stop(); - // Close the files. + // Close the file. fs.closeSync(file); // Release the camera input stream. diff --git a/en/application-dev/media/camera/camera-recording.md b/en/application-dev/media/camera/camera-recording.md index 645452efa858c4dbdf4426760b3c56081ac9dda2..b5a378cbee634a87fb522c760dbb1f2526938893 100644 --- a/en/application-dev/media/camera/camera-recording.md +++ b/en/application-dev/media/camera/camera-recording.md @@ -61,7 +61,7 @@ Read [Camera](../../reference/apis-camera-kit/js-apis-camera.md) for the API ref console.error("createOutput videoProfilesArray == null || undefined"); return undefined; } - // AVRecorderProfile + // AVRecorderProfile. let aVRecorderProfile: media.AVRecorderProfile = { fileFormat: media.ContainerFormatType.CFT_MPEG_4, // Video file container format. Only MP4 is supported. videoBitrate: 100000, // Video bit rate. diff --git a/en/application-dev/media/camera/camera-shooting-case.md b/en/application-dev/media/camera/camera-shooting-case.md index 196985049a1a97b1e0cce01d5787ca26af7081d5..9cd89d112dd5dbf8013df7cab748f06f164a16c0 100644 --- a/en/application-dev/media/camera/camera-shooting-case.md +++ b/en/application-dev/media/camera/camera-shooting-case.md @@ -62,7 +62,7 @@ function setPhotoOutputCb(photoOutput: camera.PhotoOutput): void { } async function cameraShootingCase(baseContext: common.BaseContext, surfaceId: string): Promise { - // Create a CameraManager instance. + // Create a CameraManager object. let cameraManager: camera.CameraManager = camera.getCameraManager(baseContext); if (!cameraManager) { console.error("camera.getCameraManager error"); @@ -120,7 +120,7 @@ async function cameraShootingCase(baseContext: common.BaseContext, surfaceId: st console.error('photo mode not support'); return; } - // Obtain the output stream capabilities supported by the camera. + // Obtain the output stream capability supported by the camera. let cameraOutputCap: camera.CameraOutputCapability = cameraManager.getSupportedOutputCapability(cameraArray[0], camera.SceneMode.NORMAL_PHOTO); if (!cameraOutputCap) { console.error("cameraManager.getSupportedOutputCapability error"); diff --git a/en/application-dev/media/camera/camera-worker.md b/en/application-dev/media/camera/camera-worker.md index d84fd39bbe7fd9bb8ff3b549dae2ad17f39985d0..9cb15fd42b0bf76e3d690e88f464ceaaa7ea3836 100644 --- a/en/application-dev/media/camera/camera-worker.md +++ b/en/application-dev/media/camera/camera-worker.md @@ -2,13 +2,13 @@ [Worker](../../arkts-utils/worker-introduction.md) is mainly used to offer applications a multithreaded environment. It enables applications to perform time-consuming operations in background threads. This greatly prevents computing-intensive or high-latency tasks from blocking the running of the main thread. -When using camera capabilities, you often need to create camera sessions and continuously receive and process preview, photo, and video streams to achieve the desired camera functionalities. If these resource-demanding operations are performed in the main thread (UI thread), UI rendering may be blocked. Therefore, you are advised to implement the camera functionalities in the worker thread. +When using camera capabilities, you often need to create camera sessions and continuously receive and process preview, photo, and video streams to achieve the desired camera functionalities. If these resource-demanding operations are performed in the main thread (UI thread), UI rendering may be blocked. Therefore, you are advised to implement the camera functionalities in the Worker thread. ## How to Develop -1. Create a worker thread file and configure the worker. +1. Create a Worker thread file and configure the Worker. - DevEco Studio supports one-click generation of worker threads. Right-click any position in the {moduleName} directory and choose **New > Worker** to generate the template file and configuration information of the worker thread. You do not need to configure the related fields in **build-profile.json5**. + DevEco Studio supports one-click generation of Worker threads. Right-click any position in the {moduleName} directory and choose **New > Worker** to generate the template file and configuration information of the Worker thread. You do not need to configure the related fields in **build-profile.json5**. Example of the CameraWorker.ets file: @@ -22,7 +22,7 @@ When using camera capabilities, you often need to create camera sessions and con interface MessageInfo { hasResolve: boolean; type: string; - context: Context; // The worker thread cannot use getContext() to obtain the context of the host thread. Instead, the context must be passed through messages from the host thread to the worker thread. + context: Context; // The Worker thread cannot use getContext() to obtain the context of the host thread. Instead, the context must be passed through messages from the host thread to the Worker thread. surfaceId: string; } @@ -30,14 +30,14 @@ When using camera capabilities, you often need to create camera sessions and con const messageInfo: MessageInfo = e.data; console.info(`worker onmessage type:${messageInfo.type}`) if ('initCamera' === messageInfo.type) { - // The worker thread receives a camera initialization message from the host thread. + // The Worker thread receives a camera initialization message from the host thread. console.info(`worker initCamera surfaceId:${messageInfo.surfaceId}`) - // Initialize the camera in the worker thread. + // Initialize the camera in the Worker thread. await CameraService.initCamera(messageInfo.context, messageInfo.surfaceId); } else if ('releaseCamera' === messageInfo.type) { - // The worker thread receives a camera release message from the host thread. + // The Worker thread receives a camera release message from the host thread. console.info('worker releaseCamera.'); - // Release the camera in the worker thread. + // Release the camera in the Worker thread. await CameraService.releaseCamera(); } } @@ -84,7 +84,7 @@ When using camera capabilities, you often need to create camera sessions and con console.error('Failed to create the camera input.'); return; } - // Open a camera. + // Open the camera. await this.cameraInput.open(); let previewProfile: camera.Profile = { @@ -154,7 +154,7 @@ When using camera capabilities, you often need to create camera sessions and con export default new CameraService(); ``` -3. Create a component to display the preview stream, create a ThreadWorker instance in the page-related lifecycle, and initialize and release the camera in the worker thread. +3. Create a component to display the preview stream, create a ThreadWorker instance in the page-related lifecycle, and initialize and release the camera in the Worker thread. ```ts import { worker } from '@kit.ArkTS'; @@ -166,12 +166,12 @@ When using camera capabilities, you often need to create camera sessions and con private surfaceId: string = ''; @State imageWidth: number = 1920; @State imageHeight: number = 1080; - // Create a ThreadWorker object to obtain a worker instance. + // Create a ThreadWorker object to obtain a Worker instance. private workerInstance: worker.ThreadWorker = new worker.ThreadWorker('entry/ets/workers/CameraWorker.ets'); onPageShow(): void { if ('' !== this.surfaceId) { - // Send a message to the worker thread through the worker instance to initialize the camera. + // Send a message to the Worker thread through the Worker instance to initialize the camera. this.workerInstance.postMessage({ type: 'initCamera', context: getContext(this), @@ -181,7 +181,7 @@ When using camera capabilities, you often need to create camera sessions and con } onPageHide(): void { - // Send a message to the worker thread through the worker instance to destroy the camera. + // Send a message to the Worker thread through the Worker instance to destroy the camera. this.workerInstance.postMessage({ type: 'releaseCamera', }) @@ -209,11 +209,11 @@ When using camera capabilities, you often need to create camera sessions and con console.error('create stage worker failed'); return; } - // The host thread sends a camera initialization message to the worker thread. + // The host thread sends a camera initialization message to the Worker thread. this.workerInstance.postMessage({ type: 'initCamera', - context: getContext(this), // Pass the context of the host thread to the worker thread. - surfaceId: this.surfaceId, // Pass the surface ID to the worker thread. + context: getContext(this), // Pass the context of the host thread to the Worker thread. + surfaceId: this.surfaceId, // Pass the surface ID to the Worker thread. }) })// The width and height of the surface are opposite to those of the XComponent. .width(px2vp(this.imageHeight)) diff --git a/en/application-dev/media/camera/native-camera-device-input.md b/en/application-dev/media/camera/native-camera-device-input.md index fe531dece58708b8f8223b7a163a68b8701a7133..cba80ab83b784848afbd80e528c905f329329d9a 100644 --- a/en/application-dev/media/camera/native-camera-device-input.md +++ b/en/application-dev/media/camera/native-camera-device-input.md @@ -108,7 +108,7 @@ Read [Camera](../../reference/apis-camera-kit/_o_h___camera.md) for the API refe ```c++ - // Obtain the output streams supported by the camera device. + // Obtain the output stream capability supported by the camera. Camera_OutputCapability* cameraOutputCapability = nullptr; const Camera_Profile* previewProfile = nullptr; const Camera_Profile* photoProfile = nullptr; diff --git a/en/application-dev/media/camera/native-camera-device-management.md b/en/application-dev/media/camera/native-camera-device-management.md index 5c62b768ab1d83720794f5d062f4ebf8c79f30d0..effc015502eabc93158d2a4bb958f808213a9258 100644 --- a/en/application-dev/media/camera/native-camera-device-management.md +++ b/en/application-dev/media/camera/native-camera-device-management.md @@ -46,7 +46,7 @@ Read [Camera](../../reference/apis-camera-kit/_o_h___camera.md) for the API refe > If obtaining the object fails, the camera device may be occupied or unusable. If it is occupied, wait until it is released. 4. Call [OH_CameraManager_GetSupportedCameras()](../../reference/apis-camera-kit/_o_h___camera.md#oh_cameramanager_getsupportedcameras) to obtain the list of cameras supported by the current device. The list stores the IDs of all cameras supported. If the list is not empty, each ID in the list can be used to create an independent camera object. If the list is empty, no camera is available for the current device and subsequent operations cannot be performed. - + ```c++ // Obtain the camera list. ret = OH_CameraManager_GetSupportedCameras(cameraManager, &cameras, &size); diff --git a/en/application-dev/media/camera/native-camera-metadata.md b/en/application-dev/media/camera/native-camera-metadata.md index 810059ce8dd9a9e8bd4e6ce0a7e6488c7c58647a..8e8f3e875f2ff1bf24405bcb94aec978a5aedb1c 100644 --- a/en/application-dev/media/camera/native-camera-metadata.md +++ b/en/application-dev/media/camera/native-camera-metadata.md @@ -55,7 +55,7 @@ Read [Camera](../../reference/apis-camera-kit/_o_h___camera.md) for the API refe if (cameraOutputCapability->previewProfilesSize < 0) { OH_LOG_ERROR(LOG_APP, "previewProfilesSize == null"); } - metaDataObjectType = cameraOutputCapability->supportedMetadataObjectTypes[2]; // 2:camera metedata types + metaDataObjectType = cameraOutputCapability->supportedMetadataObjectTypes[2]; // 2: camera metedata types. if (metaDataObjectType == nullptr) { OH_LOG_ERROR(LOG_APP, "Get metaDataObjectType failed."); } diff --git a/en/application-dev/media/camera/native-camera-preview-imageReceiver.md b/en/application-dev/media/camera/native-camera-preview-imageReceiver.md index edec720afbaf4ced747f91c0c3d7f6faf572cc33..3c581c91f463b10e1bc862ed3a674eb1a3c5d782 100644 --- a/en/application-dev/media/camera/native-camera-preview-imageReceiver.md +++ b/en/application-dev/media/camera/native-camera-preview-imageReceiver.md @@ -62,7 +62,7 @@ Read [Camera](../../reference/apis-camera-kit/_o_h___camera.md) for the API refe } ``` -4. Create a preview stream based on the surface ID obtained. For details, see step 4 in [Camera Preview (C/C++)](./native-camera-preview.md). +4. Create a preview stream based on the surface ID obtained. (Note that you must convert the surface ID type to char * before the creation of the preview stream.) For details, see step 4 in [Camera Preview (C/C++)](./native-camera-preview.md). 5. Create a session and enable it. For details, see [Camera Session Management (C/C++)](./native-camera-session-management.md). diff --git a/en/application-dev/media/camera/native-camera-recording-case.md b/en/application-dev/media/camera/native-camera-recording-case.md index c4881dc78a68d0505d6a5596b64c4ef2e30d02a8..9a77fe3a159eee254925241e7b84455735055688 100644 --- a/en/application-dev/media/camera/native-camera-recording-case.md +++ b/en/application-dev/media/camera/native-camera-recording-case.md @@ -14,19 +14,30 @@ After obtaining the output stream capabilities supported by the camera, create a 1. Link the dynamic library in the CMake script. ```txt - target_link_libraries(entry PUBLIC libohcamera.so libhilog_ndk.z.so) + target_link_libraries(entry PUBLIC libohcamera.so libhilog_ndk.z.so) ``` -2. Import the NDK APIs on the C++ side, and perform video recording based on the surface ID passed in. +2. Create the header file **ndk_camera.h**. + ```c++ + #include "ohcamera/camera.h" + #include "ohcamera/camera_input.h" + #include "ohcamera/capture_session.h" + #include "ohcamera/photo_output.h" + #include "ohcamera/preview_output.h" + #include "ohcamera/video_output.h" + #include "ohcamera/camera_manager.h" + + class NDKCamera { + public: + ~NDKCamera(); + NDKCamera(char *previewId, char *videoId); + }; + ``` + +3. Import the NDK APIs on the C++ side, and perform video recording based on the surface ID passed in. ```c++ #include "hilog/log.h" - #include "ohcamera/camera.h" - #include "ohcamera/camera_input.h" - #include "ohcamera/capture_session.h" - #include "ohcamera/photo_output.h" - #include "ohcamera/preview_output.h" - #include "ohcamera/video_output.h" - #include "ohcamera/camera_manager.h" + #include "ndk_camera.h" void OnCameraInputError(const Camera_Input* cameraInput, Camera_ErrorCode errorCode) { @@ -139,7 +150,7 @@ After obtaining the output stream capabilities supported by the camera, create a OH_LOG_ERROR(LOG_APP, "connectionType = %{public}d ", cameras[index].connectionType); // Obtain the camera connection type. } - // Obtain the output streams supported by the camera. + // Obtain the output stream capability supported by the camera. ret = OH_CameraManager_GetSupportedCameraOutputCapability(cameraManager, &cameras[cameraDeviceIndex], &cameraOutputCapability); if (cameraOutputCapability == nullptr || ret != CAMERA_OK) { @@ -215,7 +226,7 @@ After obtaining the output stream capabilities supported by the camera, create a } // Create a preview output stream. For details about the surfaceId parameter, see the XComponent. The preview stream is the surface provided by the XComponent. - ret = OH_CameraManager_CreatePreviewOutput(cameraManager, previewProfile, 0, &previewOutput); + ret = OH_CameraManager_CreatePreviewOutput(cameraManager, previewProfile, previewSurfaceId, &previewOutput); if (previewProfile == nullptr || previewOutput == nullptr || ret != CAMERA_OK) { OH_LOG_ERROR(LOG_APP, "OH_CameraManager_CreatePreviewOutput failed."); } diff --git a/en/application-dev/media/camera/native-camera-shooting-case.md b/en/application-dev/media/camera/native-camera-shooting-case.md index fb8c6ae702ac883e4e2b4c6acb9ebc420a7ca9be..912f2c684f6a374f66bc234c2ed483496088984d 100644 --- a/en/application-dev/media/camera/native-camera-shooting-case.md +++ b/en/application-dev/media/camera/native-camera-shooting-case.md @@ -23,18 +23,28 @@ After obtaining the output stream capabilities supported by the camera, create a libohfileuri.so ) ``` - -2. Import the NDK APIs on the C++ side, and perform photo capture based on the surface ID passed in. +2. Create the header file **ndk_camera.h**. + ```c++ + #include "ohcamera/camera.h" + #include "ohcamera/camera_input.h" + #include "ohcamera/capture_session.h" + #include "ohcamera/photo_output.h" + #include "ohcamera/preview_output.h" + #include "ohcamera/video_output.h" + #include "ohcamera/camera_manager.h" + + class NDKCamera { + public: + ~NDKCamera(); + NDKCamera(char *previewId); + Camera_ErrorCode RegisterBufferCb(void *cb); + }; + ``` + +3. Import the NDK APIs on the C++ side, and perform photo capture based on the surface ID passed in. ```c++ - #include "camera_manager.h" #include "hilog/log.h" - #include "ohcamera/camera.h" - #include "ohcamera/camera_input.h" - #include "ohcamera/capture_session.h" - #include "ohcamera/photo_output.h" - #include "ohcamera/preview_output.h" - #include "ohcamera/video_output.h" - #include "ohcamera/camera_manager.h" + #include "ndk_camera.h" void CaptureSessionOnFocusStateChange(Camera_CaptureSession* session, Camera_FocusState focusState) { @@ -216,7 +226,7 @@ After obtaining the output stream capabilities supported by the camera, create a OH_LOG_ERROR(LOG_APP, "OH_CameraInput_Open failed."); } - // Obtain the output streams supported by the camera. + // Obtain the output stream capability supported by the camera. ret = OH_CameraManager_GetSupportedCameraOutputCapability(cameraManager, &cameras[cameraDeviceIndex], &cameraOutputCapability); if (cameraOutputCapability == nullptr || ret != CAMERA_OK) { @@ -247,10 +257,10 @@ After obtaining the output stream capabilities supported by the camera, create a } // Create a photo output stream. - ret_ = OH_CameraManager_CreatePhotoOutputWithoutSurface(cameraManager, photoProfile, &photoOutput); + ret = OH_CameraManager_CreatePhotoOutputWithoutSurface(cameraManager, photoProfile, &photoOutput); // Listen for the one-time photo capture callback. - ret_ = OH_PhotoOutput_RegisterPhotoAvailableCallback(photoOutput, OnPhotoAvailable); + ret = OH_PhotoOutput_RegisterPhotoAvailableCallback(photoOutput, OnPhotoAvailable); // Create a session. ret = OH_CameraManager_CreateCaptureSession(cameraManager, &captureSession); @@ -312,6 +322,7 @@ After obtaining the output stream capabilities supported by the camera, create a } else { OH_LOG_ERROR(LOG_APP, "hasFlash fail"); } + // Check whether a flash mode is supported. bool isSupported = false; ret = OH_CaptureSession_IsFlashModeSupported(captureSession, flashMode, &isSupported); @@ -320,6 +331,7 @@ After obtaining the output stream capabilities supported by the camera, create a } if (isSupported) { OH_LOG_INFO(LOG_APP, "isFlashModeSupported success"); + // Set the flash mode. ret = OH_CaptureSession_SetFlashMode(captureSession, flashMode); if (ret == CAMERA_OK) { @@ -327,6 +339,7 @@ After obtaining the output stream capabilities supported by the camera, create a } else { OH_LOG_ERROR(LOG_APP, "OH_CaptureSession_SetFlashMode failed. %{public}d ", ret); } + // Obtain the flash mode in use. ret = OH_CaptureSession_GetFlashMode(captureSession, &flashMode); if (ret == CAMERA_OK) { @@ -371,6 +384,7 @@ After obtaining the output stream capabilities supported by the camera, create a OH_LOG_INFO(LOG_APP, "OH_CaptureSession_GetZoomRatioRange success. minZoom: %{public}f, maxZoom:%{public}f", minZoom, maxZoom); } + // Set a zoom ratio. ret = OH_CaptureSession_SetZoomRatio(captureSession, maxZoom); if (ret == CAMERA_OK) { @@ -378,6 +392,7 @@ After obtaining the output stream capabilities supported by the camera, create a } else { OH_LOG_ERROR(LOG_APP, "OH_CaptureSession_SetZoomRatio failed. %{public}d ", ret); } + // Obtain the zoom ratio of the camera. ret = OH_CaptureSession_GetZoomRatio(captureSession, &maxZoom); if (ret == CAMERA_OK) { diff --git a/en/application-dev/media/camera/native-camera-shooting.md b/en/application-dev/media/camera/native-camera-shooting.md index f63ccd5668a547a2224826c0bfc3c19123ce0852..30395ee1efb38c21a1a9695a4dcd502b50c678a6 100644 --- a/en/application-dev/media/camera/native-camera-shooting.md +++ b/en/application-dev/media/camera/native-camera-shooting.md @@ -287,12 +287,12 @@ Read [Camera](../../reference/apis-camera-kit/_o_h___camera.md) for the API refe import cameraDemo from 'libentry.so'; interface PhotoSettings { - quality: number, // Photo quality - rotation: number, // Photo direction - mirror: boolean, // Mirror Enable - latitude: number, // geographic location - longitude: number, // geographic location - altitude: number // geographic location + quality: number, // Photo quality. + rotation: number, // Photo direction. + mirror: boolean, // Mirror Enabled. + latitude: number, // Geographic location. + longitude: number, // Geographic location. + altitude: number // Geographic location. }; @Entry diff --git a/en/application-dev/media/drm/Readme-EN.md b/en/application-dev/media/drm/Readme-EN.md index cade7ce62e810812cd9b4e820346ce6998dc174d..133909dc177bd829316687012f60c02f097b8f8b 100644 --- a/en/application-dev/media/drm/Readme-EN.md +++ b/en/application-dev/media/drm/Readme-EN.md @@ -1,9 +1,10 @@ # DRM Kit - [Introduction to DRM Kit](drm-overview.md) -- DRM Development (ArkTS) - - [DRM Media Key System Management (ArkTS)](drm-mediakeysystem-management.md) - - [DRM Media Key Session Management (ArkTS)](drm-mediakeysession-management.md) -- DRM Development (C/C++) - - [DRM Media Key System Management (C/C++)](native-drm-mediakeysystem-management.md) - - [DRM Media Key Session Management (C/C++)](native-drm-mediakeysession-management.md) +- [DRM Development (ArkTS)](drm-arkts-dev-guide.md) +- [DRM Development (C/C++)](drm-c-dev-guide.md) + +- [DRM Solution Development](drm-solution-dev-guide.md) + +- [Using AVPlayer to Play DRM Content (ArkTS)](drm-avplayer-arkts-integration.md) +- [Using AVCodec to Play DRM Content (C/C++)](drm-avcodec-integration.md) diff --git a/en/application-dev/media/drm/drm-arkts-dev-guide.md b/en/application-dev/media/drm/drm-arkts-dev-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..57f613e76623ee6e0361a7c2a7783c4a3dfcc2e4 --- /dev/null +++ b/en/application-dev/media/drm/drm-arkts-dev-guide.md @@ -0,0 +1,245 @@ +# DRM Development (ArkTS) + +You can call the ArkTS APIs of DRM Kit to implement digital copyright protection features such as DRM certificate management, DRM license management, DRM content authorization, and DRM content decryption. + +DRM Kit provides MediaKeySystem to manage DRM certificates, DRM licenses, and MediaKeySession instances. MediaKeySession is responsible for authorizing DRM content and can work with Media Kit or AVCodec Kit to decrypt the DRM content, thereby enabling playback of DRM-protected content. + +## How to Develop + +Read [DRM](../../reference/apis-drm-kit/js-apis-drm.md) for the API reference. + +1. Import the DRM Kit module. + + ```ts + import { drm } from '@kit.DrmKit'; + ``` + +2. Import the BusinessError module to capture error codes from the DRM Kit APIs. + + ```ts + import { BusinessError } from '@kit.BasicServicesKit'; + ``` + +3. (Optional) Obtain the name and ID list of the DRM solutions supported by the device. + + ```ts + let description: drm.MediaKeySystemDescription[] = drm.getMediaKeySystems(); + ``` + + If the returned array is empty, no DRM solution is supported by the device. + +4. (Optional) Check whether the device supports the specified DRM solution based on the name, MIME type, and content protection level. + + ```ts + let isSupported: boolean = drm.isMediaKeySystemSupported("com.clearplay.drm", "video/mp4", drm.ContentProtectionLevel.CONTENT_PROTECTION_LEVEL_SW_CRYPTO); + ``` + + The value **false** means that the device does not support the specified DRM solution. + +5. Create a MediaKeySystem instance. + + ```ts + let mediaKeySystem: drm.MediaKeySystem = drm.createMediaKeySystem("com.clearplay.drm"); + ``` + + If the creation fails, **undefined** is returned, indicating that the device does not support the DRM solution. + +6. (Optional) Set a MediaKeySystem status listener. + + Register the keySystemRequired callback to listen for DRM certificate request events. This event is triggered when the device needs a DRM certificate. You are advised to complete the certificate request and handling process at this point. + + ```ts + mediaKeySystem.on('keySystemRequired', (eventInfo: drm.EventInfo) => { + console.log('keySystemRequired' + 'extra:' + eventInfo.extraInfo + ' data:' + eventInfo.info); + // Request and process the DRM certificate. + }); + ``` + +7. (Optional) Obtain the status of the DRM certificate. + + ```ts + let certificateStatus: drm.CertificateStatus = mediaKeySystem.getCertificateStatus(); + ``` + +8. (Optional) Generate a DRM certificate request and process its response. + + If the DRM certificate is not in the drm.CertificateStatus.CERT_STATUS_PROVISIONED state, generate a DRM certificate request and process its response. + + ```ts + if(certificateStatus != drm.CertificateStatus.CERT_STATUS_PROVISIONED) { + mediaKeySystem.generateKeySystemRequest().then(async (drmRequest: drm.ProvisionRequest) => { + console.info("generateKeySystemRequest success", drmRequest.data, drmRequest.defaultURL); + }).catch((err:BusinessError) =>{ + console.info("generateKeySystemRequest err end", err.code); + }); + } else { + console.info("The certificate already exists."); + } + // Send drmRequest.data returned by the DRM certificate request to the DRM certificate service through a network request to obtain a response and process the response. + let provisionResponseByte = new Uint8Array([0x00, 0x00, 0x00, 0x00]); // Response to the DRM certificate request. + mediaKeySystem.processKeySystemResponse(provisionResponseByte).then(() => { + console.info("processKeySystemResponse success"); + }).catch((err:BusinessError) =>{ + console.info("processKeySystemResponse err end", err.code); + }); + ``` + +9. Create a MediaKeySession instance. + + Create a MediaKeySession instance with the default content protection level of the DRM solution. + + ```ts + let mediaKeySession: drm.MediaKeySession = mediaKeySystem.createMediaKeySession(); + ``` + +10. (Optional) Set a MediaKeySession status listener. + + Listen for events of the MediaKeySession instance, including media key request events, media key expiration events, media key validity period update events, and media key change events. + + - Listen for media key request event. You are advised to complete the media key request and handling process at this point. + + ```ts + mediaKeySession.on('keyRequired', (eventInfo: drm.EventInfo) => { + console.log('keyRequired' + 'info:' + eventInfo.info + ' extraInfo:' + eventInfo.extraInfo); + // Request and process the media key. + }); + ``` + + - Listen for media key expiration events. + + ```ts + mediaKeySession.on('keyExpired', (eventInfo: drm.EventInfo) => { + console.log('keyExpired' + 'info:' + eventInfo.info + ' extraInfo:' + eventInfo.extraInfo); + }); + ``` + + - Listen for media key validity period update events. + + ```ts + mediaKeySession.on('expirationUpdate', (eventInfo: drm.EventInfo) => { + console.log('expirationUpdate' + 'info:' + eventInfo.info + ' extraInfo:' + eventInfo.extraInfo); + }); + ``` + + - Listen for media key change events. + + ```ts + mediaKeySession.on('keysChange', (keyInfo : drm.KeysInfo[], newKeyAvailable:boolean) => { + for(let i = 0; i < keyInfo.length; i++){ + console.log('keysChange' + 'info:' + keyInfo[i].keyId + ' extraInfo:' + keyInfo[i].value); + } + }); + ``` + +11. (Optional) Check whether secure decoding is required. + + ```ts + try { + let status: boolean = mediaKeySession.requireSecureDecoderModule("video/avc"); + } catch (err) { + let error = err as BusinessError; + console.error(`requireSecureDecoderModule ERROR: ${error}`); + } + ``` + +12. Generate a media key request and process its response. + + After obtaining the DRM information of the DRM content, generate a media key request and process its response to request a license for DRM content authorization. + + ```ts + // Generate initData based on PSSH in the DRM information as required by the DRM solution. + let initData = new Uint8Array([0x00, 0x00, 0x00, 0x00]); + // Set optional data based on the DRM solution. + let optionalData:drm.OptionsData[] = [{ + name: "optionalDataName", + value: "optionalDataValue" + }]; + // Request and response for an online media key. + mediaKeySession.generateMediaKeyRequest("video/mp4", initData, drm.MediaKeyType.MEDIA_KEY_TYPE_ONLINE, optionalData).then(async (licenseRequest: drm.MediaKeyRequest) => { + console.info("generateMediaKeyRequest success", licenseRequest.mediaKeyRequestType, licenseRequest.data, licenseRequest.defaultURL); + // Send licenseRequest.data returned by the media key request to the DRM service through a network request to obtain a media key response and process the response. + let licenseResponse = new Uint8Array([0x00, 0x00, 0x00, 0x00]); // Media key response. + mediaKeySession.processMediaKeyResponse(licenseResponse).then((mediaKeyId: Uint8Array) => { + console.info("processMediaKeyResponse success"); + }).catch((err:BusinessError) =>{ + console.info("processMediaKeyResponse err end", err.code); + }); + }).catch((err:BusinessError) =>{ + console.info("generateMediaKeyRequest err end", err.code); + }); + // Request and response for an offline media key. + let offlineMediaKeyId: Uint8Array; + mediaKeySession.generateMediaKeyRequest("video/mp4", initData, drm.MediaKeyType.MEDIA_KEY_TYPE_OFFLINE, optionalData).then((licenseRequest: drm.MediaKeyRequest) => { + console.info("generateMediaKeyRequest success", licenseRequest.mediaKeyRequestType, licenseRequest.data, licenseRequest.defaultURL); + // Send licenseRequest.data returned by the media key request to the DRM service through a network request to obtain a media key response and process the response. + let licenseResponse = new Uint8Array([0x00, 0x00, 0x00, 0x00]); // Media key response. + mediaKeySession.processMediaKeyResponse(licenseResponse).then((mediaKeyId: Uint8Array) => { + offlineMediaKeyId = new Uint8Array(mediaKeyId); + console.info("processMediaKeyResponse success"); + }).catch((err:BusinessError) =>{ + console.info("processMediaKeyResponse err end", err.code); + }); + }).catch((err:BusinessError) =>{ + console.info("generateMediaKeyRequest err end", err.code); + }); + ``` + +13. (Optional) Restore offline media keys. + + ```ts + mediaKeySession.restoreOfflineMediaKeys(offlineMediaKeyId).then(() => { + console.log("restoreOfflineMediaKeys success."); + }).catch((err: BusinessError) => { + console.error(`restoreOfflineMediaKeys: ERROR: ${err}`); + }); + ``` + +14. (Optional) Check the status of media keys. + + ```ts + let mediaKeyStatus: drm.MediaKeyStatus[] + try { + mediaKeyStatus = mediaKeySession.checkMediaKeyStatus() + } catch (err) { + let error = err as BusinessError; + console.error(`checkMediaKeyStatus: ERROR: ${error}`); + } + ``` + +15. (Optional) Obtain the IDs of offline media keys, obtain their status, and clear the keys. + + The media key ID is used for offline media key management. + + ```ts + let offlineMediaKeyIds: Uint8Array[] = mediaKeySystem.getOfflineMediaKeyIds(); + try { + let offlineMediaKeyStatus: drm.OfflineMediaKeyStatus = mediaKeySystem.getOfflineMediaKeyStatus(offlineMediaKeyIds[0]); + } catch (err) { + let error = err as BusinessError; + console.error(`getOfflineMediaKeyStatus ERROR: ${error}`); + } + try { + mediaKeySystem.clearOfflineMediaKeys(offlineMediaKeyIds[0]); + } catch (err) { + let error = err as BusinessError; + console.error(`clearOfflineMediaKeys ERROR: ${error}`); + } + ``` + +16. Destroy the MediaKeySession instance. + + Destroy the MediaKeySession instance when the encrypted content is decrypted and the instance is no longer needed. + + ```ts + // Release resources when the MediaKeySession instance is no longer needed. + mediaKeySession.destroy(); + ``` + +17. Destroy the MediaKeySystem instance. + + Destroy the MediaKeySystem instance when it is no longer needed. + + ```ts + // Release resources when the MediaKeySystem instance is no longer needed. + mediaKeySystem.destroy(); + ``` diff --git a/en/application-dev/media/drm/drm-avcodec-integration.md b/en/application-dev/media/drm/drm-avcodec-integration.md new file mode 100644 index 0000000000000000000000000000000000000000..60121518947fca700bbc411b95aef0f6a2129c1c --- /dev/null +++ b/en/application-dev/media/drm/drm-avcodec-integration.md @@ -0,0 +1,154 @@ +# Using AVPlayer to Play DRM Content (C/C++) + +## When to Use + +You can call the native APIs of DRM Kit to play DRM-protected programs. + +Currently, the following decryption capabilities are supported: + +| Audio Container Format| Audio Decryption Type| +|----------|:-------| +| mp4 | AAC | + +| Video Container Format| Video Decryption Type| +|----------|:------------| +| ts | AVC(H.264) | +| mp4 | AVC(H.264) | + + +**Usage Scenario** + +Before creating DRM, obtain the DRM information. For details, see step 4 in [Media Data Demuxing](../avcodec/audio-video-demuxer.md#how-to-develop). + +## How to Develop + +Read [DRM](../../reference/apis-drm-kit/_drm.md) for the API reference. + +Refer to the following sample code to complete the entire DRM process, including obtaining the name and ID list of the DRM solutions supported by the device, creating MediaKeySystem and MediaKeySession instances, generating a media key request, processing a media key response, checking whether secure video decoding is required, and destroying resources. + +During application development, you must call the APIs in the defined sequence. Otherwise, an exception or undefined behavior may occur. + +### Linking the Dynamic Libraries in the CMake Script + +``` cmake +target_link_libraries(sample PUBLIC libnative_drm.so) +``` + +> **NOTE** +> +> The word **sample** in the preceding code snippet is only an example. Use the actual project directory name. +> + +## How to Develop + +1. Import the DRM Kit module. + + ```c++ + #include "multimedia/drm_framework/native_drm_common.h" + #include "multimedia/drm_framework/native_drm_err.h" + #include "multimedia/drm_framework/native_mediakeysession.h" + #include "multimedia/drm_framework/native_mediakeysystem.h" + ``` + +2. Obtain the name and ID list of the DRM solutions supported by the device. + + ```c++ + uint32_t count = 3; // count indicates the number of DRM plugins supported by the device. Pass in the actual number. + DRM_MediaKeySystemDescription descriptions[3]; + memset(descriptions, 0, sizeof(descriptions)); + Drm_ErrCode ret = OH_MediaKeySystem_GetMediaKeySystems(descriptions, &count); + if (ret != DRM_ERR_OK) { + printf("OH_MediaKeySystem_GetMediaKeySystems failed."); + } + ``` + + After obtaining the name and ID list of DRM solutions supported by the device, match against the DRM information and create the corresponding DRM solution. You can obtain the DRM information by referring to step 4 in the [Media Data Demuxing](../avcodec/audio-video-demuxer.md#how-to-develop). + + Alternatively, directly parse the media protocol or media data to obtain the unique identifier of the DRM solution and the PSSH data, so as to generate the DRM information. + +3. Create a MediaKeySystem instance. + + ```c++ + MediaKeySystem *mediaKeySystem = nullptr; + ret = OH_MediaKeySystem_Create("com.clearplay.drm", &mediaKeySystem); + if (ret != DRM_ERR_OK || mediaKeySystem == nullptr) { + printf("OH_MediaKeySystem_Create failed."); + } + ``` + +4. Create a MediaKeySession instance. + + ```c++ + MediaKeySession *mediaKeySession = nullptr; + DRM_ContentProtectionLevel contentProtectionLevel = CONTENT_PROTECTION_LEVEL_SW_CRYPTO; // Set the content protection level supported by the device. + ret = OH_MediaKeySystem_CreateMediaKeySession(mediaKeySystem, &contentProtectionLevel, &mediaKeySession); + if (ret != DRM_ERR_OK || mediaKeySession == nullptr) { + printf("OH_MediaKeySystem_CreateMediaKeySession failed."); + } + ``` + +5. Check whether secure decoding is required. + + ```c++ + bool requireSecureDecoder; + ret = OH_MediaKeySession_RequireSecureDecoderModule(mediaKeySession, "video/avc", &requireSecureDecoder); + if (ret != DRM_ERR_OK) { + printf("OH_MediaKeySession_RequireSecureDecoderModule failed."); + } + ``` + +6. Generate a media key request and process its response. + + ```c++ + #define MAX_DRM_MEDIA_KEY_RESPONSE_BUF_SIZE 24576 // 24576: (2 * 12 * 1024) + DRM_MediaKeyRequest mediaKeyRequest; + DRM_MediaKeyRequestInfo info; + // initData corresponds to PSSH data in the stream. Pass in the actual data. + unsigned char initData[512] = {0x00}; + memset(&info, 0, sizeof(DRM_MediaKeyRequestInfo)); + info.initDataLen = sizeof(initData); + info.type = MEDIA_KEY_TYPE_ONLINE; // MEDIA_KEY_TYPE_ONLINE: online media key request; MEDIA_KEY_TYPE_OFFLINE: offline media key request. + memcpy(info.mimeType, (char *)"video/mp4", sizeof("video/mp4")); + memcpy(info.initData, initData, sizeof(initData)); + memcpy(info.optionName[0], (char *)"optionalDataName", sizeof("optionalDataName")); + memcpy(info.optionData[0], (char *)"optionalDataValue", sizeof("optionalDataValue")); + info.optionsCount = 1; + ret = OH_MediaKeySession_GenerateMediaKeyRequest(mediaKeySession, &info, &mediaKeyRequest); + if (ret != DRM_ERR_OK) { + printf("OH_MediaKeySession_GenerateMediaKeyRequest failed."); + } + /* + The application requests the DRM service through the network, obtains a media key response, and sends the response to OH_MediaKeySession_ProcessMediaKeyResponse. + If the response is an offline media key response, the offline media key ID is returned. Set mediaKeyId based on the actual data and length. + */ + unsigned char mediaKeyId[128] = {0x00}; + int32_t mediaKeyIdLen = 128; + // MAX_DRM_MEDIA_KEY_RESPONSE_BUF_SIZE specifies the maximum length of a media key response. Pass in the actual length. + unsigned char mediaKeyResponse[MAX_DRM_MEDIA_KEY_RESPONSE_BUF_SIZE] = {0x00}; + int32_t mediaKeyResponseLen = MAX_DRM_MEDIA_KEY_RESPONSE_BUF_SIZE; + ret = OH_MediaKeySession_ProcessMediaKeyResponse(mediaKeySession, mediaKeyResponse, + mediaKeyResponseLen, mediaKeyId, &mediaKeyIdLen); + if (ret != DRM_ERR_OK) { + printf("OH_MediaKeySession_ProcessMediaKeyResponse failed."); + } + ``` + + If required, set the audio decryption configuration by following step 4 in [Audio Decoding](../avcodec/audio-decoding.md#how-to-develop), and set the video decryption configuration by following step 4 in [Surface Output in Video Decoding](../avcodec/video-decoding.md#surface-mode) or step 4 in [Buffer Output in Video Decoding](../avcodec/video-decoding.md#buffer-mode). + +7. Destroy the MediaKeySession instance. + + ```c++ + ret = OH_MediaKeySession_Destroy(mediaKeySession); + if (ret != DRM_ERR_OK) { + printf("OH_MediaKeySession_Destroy failed."); + } + ``` + +8. Destroy the MediaKeySystem instance. + + ```c++ + ret = OH_MediaKeySystem_Destroy(mediaKeySystem); + if (ret != DRM_ERR_OK) { + printf("OH_MediaKeySystem_Destroy failed."); + } + ``` diff --git a/en/application-dev/media/drm/drm-avplayer-arkts-integration.md b/en/application-dev/media/drm/drm-avplayer-arkts-integration.md new file mode 100644 index 0000000000000000000000000000000000000000..2f7ed3978317913ca34f4d5d530b24ac119b9671 --- /dev/null +++ b/en/application-dev/media/drm/drm-avplayer-arkts-integration.md @@ -0,0 +1,95 @@ +# Using AVPlayer to Play DRM Content (ArkTS) + +You can call the ArkTS APIs of DRM Kit and Media Kit to implement the playback of DRM-protected content using the AVPlayer. + +## How to Develop + +1. Import the DRM Kit and Media Kit modules. + + ```ts + import { drm } from '@kit.DrmKit' + import { media } from '@kit.MediaKit' + ``` + +2. Import the BusinessError module to capture error codes from the DRM Kit APIs. + + ```ts + import { BusinessError } from '@kit.BasicServicesKit' + ``` + +3. Create an AVPlayer instance and set a DRM information listener. + + ```ts + let playerHandle: media.AVPlayer = await media.createAVPlayer() + playerHandle.on('mediaKeySystemInfoUpdate', async (mediaKeySystemInfo: drm.MediaKeySystemInfo[]) => { + console.info('player has received drmInfo signal: ' + JSON.stringify(mediaKeySystemInfo)) + // Process DRM information. + // Set a decryption session. + }) + ``` + +4. Create MediaKeySystem and MediaKeySession instances based on the UUID in the DRM information. + + ```ts + let mediaKeySystem: drm.MediaKeySystem + let mediaKeySession: drm.MediaKeySession + let drmInfoArr: drm.MediaKeySystemInfo[] = mediaKeySystemInfo + for (let i = 0; i < drmInfoArr.length; i++) { + console.info('drmInfoArr - uuid: ' + drmInfoArr[i].uuid) + console.info('drmInfoArr - pssh: ' + drmInfoArr[i].pssh) + let description: drm.MediaKeySystemDescription[] = drm.getMediaKeySystems(); + let solutionName: string = "com.clearplay.drm" + for (let item of description) { + if (drmInfoArr[i].uuid == item.uuid) { + solutionName = item.name + } + } + let isSupported: boolean = drm.isMediaKeySystemSupported(solutionName, "video/mp4"); + if (isSupported) { + mediaKeySystem = drm.createMediaKeySystem(solutionName); + mediaKeySession = mediaKeySystem.createMediaKeySession(); + } + // Request and process the media key. + } + ``` + +5. Generate a media key request based on the PSSH information in the DRM information and process its response. + + ```ts + let initData: Uint8Array = new Uint8Array(drmInfoArr[i].pssh); + const optionsData: drm.OptionsData[] = [{ + name: "optionalDataName", + value: "optionalDataValue" + }] + mediaKeySession.generateMediaKeyRequest("video/mp4", initData, drm.MediaKeyType.MEDIA_KEY_TYPE_ONLINE, optionsData).then(async (licenseRequest) => { + console.info("generateMediaKeyRequest success", licenseRequest.mediaKeyRequestType, licenseRequest.data, licenseRequest.defaultURL); + // Send licenseRequest.data returned by the media key request to the DRM service through a network request to obtain a media key response and process the response. + let licenseResponse = new Uint8Array([0x00, 0x00, 0x00, 0x00]); + mediaKeySession.processMediaKeyResponse(licenseResponse).then((mediaKeyId: Uint8Array) => { + console.info("processMediaKeyResponse success"); + }).catch((err:BusinessError) =>{ + console.info("processMediaKeyResponse err end", err.code); + }); + }).catch((err:BusinessError) =>{ + console.info("generateMediaKeyRequest err end", err.code); + }); + ``` + +6. Set the decryption session after the media key response is successfully processed. + + ```ts + let svp: boolean = mediaKeySession.requireSecureDecoderModule('video/avc'); + playerHandle.setDecryptionConfig(mediaKeySession, svp) + ``` + +7. Destroy the AVPlayer instance and destroy the MediaKeySession and MediaKeySystem instances based on the released event. + + ```ts + playerHandle.on('stateChange', async (state: string, reason: media.StateChangeReason) => { + if (state == 'released') { + mediaKeySession.destroy(); + mediaKeySystem.destroy(); + } + } + await this.playerHandle.release() + ``` diff --git a/en/application-dev/media/drm/drm-c-dev-guide.md b/en/application-dev/media/drm/drm-c-dev-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..31a84598abf324d80a683189de9041db67fbe84d --- /dev/null +++ b/en/application-dev/media/drm/drm-c-dev-guide.md @@ -0,0 +1,259 @@ +# DRM Development (C/C++) + +## When to Use + +You can call the C/C++ APIs of DRM Kit to implement digital copyright protection features such as DRM certificate management, DRM license management, DRM content authorization, and DRM content decryption. + +DRM Kit provides MediaKeySystem to manage DRM certificates, DRM licenses, and MediaKeySession instances. MediaKeySession is responsible for authorizing DRM content and can work with Media Kit or AVCodec Kit to decrypt the DRM content, thereby enabling playback of DRM-protected content. + +## How to Develop + +Read [DRM](../../reference/apis-drm-kit/_drm.md) for the API reference. + +1. Import the DRM Kit module. + + ```c++ + #include "multimedia/drm_framework/native_drm_common.h" + #include "multimedia/drm_framework/native_drm_err.h" + #include "multimedia/drm_framework/native_mediakeysession.h" + #include "multimedia/drm_framework/native_mediakeysystem.h" + ``` + +2. Link the dynamic libraries in the CMake script. + + ```txt + target_link_libraries(PUBLIC libnative_drm.so) + ``` + +3. Obtain the name and ID list of the DRM solutions supported by the device. + + ```c++ + uint32_t count = 3; // count indicates the number of DRM plugins supported by the device. Pass in the actual number. + DRM_MediaKeySystemDescription descriptions[3]; + memset(descriptions, 0, sizeof(descriptions)); + Drm_ErrCode ret = OH_MediaKeySystem_GetMediaKeySystems(descriptions, &count); + if (ret != DRM_ERR_OK) { + printf("OH_MediaKeySystem_GetMediaKeySystems failed."); + } + ``` + +4. (Optional) Check whether the device supports the specified DRM solution based on the name, MIME type, and content protection level. + + ```c++ + bool isSupported = OH_MediaKeySystem_IsSupported3("com.clearplay.drm", "video/mp4", CONTENT_PROTECTION_LEVEL_SW_CRYPTO); + if (isSupported != true) { + printf("The device does not support the content protection level."); + } + ``` + +5. Create a MediaKeySystem instance. + + ```c++ + MediaKeySystem *mediaKeySystem = nullptr; + ret = OH_MediaKeySystem_Create("com.clearplay.drm", &mediaKeySystem); + if (ret != DRM_ERR_OK || mediaKeySystem == nullptr) { + printf("OH_MediaKeySystem_Create failed."); + } + ``` + +6. (Optional) Set the MediaKeySystem event listener callback. + + ```c++ + static Drm_ErrCode SystemCallBackWithObj(MediaKeySystem *mediaKeySystem, DRM_EventType eventType, + uint8_t *info, int32_t infoLen, char *extra) + { + printf("SystemCallBackWithObj enter"); + if (eventType == EVENT_PROVISION_REQUIRED) { + // Request and process the DRM certificate. + } + return DRM_ERR_OK; + } + + ret = OH_MediaKeySystem_SetCallback(mediaKeySystem, SystemCallBackWithObj); + if (ret != DRM_ERR_OK) { + printf("OH_MediaKeySystem_SetCallback failed."); + } + ``` + +7. (Optional) Obtain the status of the DRM certificate. + + ```c++ + DRM_CertificateStatus certStatus = CERT_STATUS_INVALID; + // Check the DRM certificate status of the device. + ret = OH_MediaKeySystem_GetCertificateStatus(mediaKeySystem, &certStatus); + if (ret == DRM_ERR_OK && certStatus != CERT_STATUS_PROVISIONED) { + // Request and process the DRM certificate. + } + ``` + +8. (Optional) Generate a DRM certificate request and process its response. + + ```c++ + #define MAX_DRM_PROVISION_BUF_SIZE 24576 // 24576: (2 * 12 * 1024) + unsigned char request[MAX_DRM_PROVISION_BUF_SIZE] = { 0x00 }; // MAX_DRM_PROVISION_BUF_SIZE specifies the maximum length of a DRM certificate request. Apply for memory based on the actual length. + int32_t requestLen = MAX_DRM_PROVISION_BUF_SIZE; + // The maximum length of the DRM service URL is 2048. + char defaultUrl[2048] = { 0x00 }; + int32_t defaultUrlLen = 2048; + ret = OH_MediaKeySystem_GenerateKeySystemRequest(mediaKeySystem, request, &requestLen, defaultUrl, + defaultUrlLen); + if (ret != DRM_ERR_OK) { + printf("OH_MediaKeySystem_GenerateKeySystemRequest failed."); + } + /* + The application sends a DRM certificate request to the DRM service through a network request, obtains a response, + and sets the response to the device. Pass in the actual data and length. + */ + unsigned char keySystemResponse[MAX_DRM_PROVISION_BUF_SIZE] = {0x00}; + ret = OH_MediaKeySystem_ProcessKeySystemResponse(mediaKeySystem, keySystemResponse, sizeof(keySystemResponse)); + if (ret != DRM_ERR_OK) { + printf("OH_MediaKeySystem_ProcessKeySystemResponse failed."); + } + ``` + +9. (Optional) Obtain the maximum content protection level supported by the device. + + ```c++ + DRM_ContentProtectionLevel maxContentProtectionLevel = CONTENT_PROTECTION_LEVEL_UNKNOWN; + ret = OH_MediaKeySystem_GetMaxContentProtectionLevel(mediaKeySystem, &maxContentProtectionLevel); + if (ret != DRM_ERR_OK) { + printf("OH_MediaKeySystem_GetMaxContentProtectionLevel failed."); + } + ``` + +10. Create a MediaKeySession instance. + + ```c++ + MediaKeySession *mediaKeySession = nullptr; + DRM_ContentProtectionLevel contentProtectionLevel = CONTENT_PROTECTION_LEVEL_SW_CRYPTO; // Set the content protection level supported by the device. + ret = OH_MediaKeySystem_CreateMediaKeySession(mediaKeySystem, &contentProtectionLevel, &mediaKeySession); + if (ret != DRM_ERR_OK || mediaKeySession == nullptr) { + printf("OH_MediaKeySystem_CreateMediaKeySession failed."); + } + ``` + +11. (Optional) Set the MediaKeySession event listener callback. + + ```c++ + static Drm_ErrCode SessionEventCallBackWithObj(MediaKeySession *mediaKeySession, DRM_EventType eventType, uint8_t *info, int32_t infoLen, char *extra) + { + if (eventType == EVENT_KEY_REQUIRED) { + // Request and process the media key. + } + return DRM_ERR_OK; + } + + static Drm_ErrCode SessionKeyChangeCallBackWithObj(MediaKeySession *mediaKeySession, DRM_KeysInfo *keysInfo, bool hasNewGoodKeys) + { + return DRM_ERR_OK; + } + + OH_MediaKeySession_Callback sessionCallback = { SessionEventCallBackWithObj, SessionKeyChangeCallBackWithObj }; + ret = OH_MediaKeySession_SetCallback(mediaKeySession, &sessionCallback); + if (ret != DRM_ERR_OK) { + printf("OH_MediaKeySession_SetCallback failed."); + } + ``` + +12. (Optional) Check whether secure decoding is required. + + ```c++ + bool requireSecureDecoder; + ret = OH_MediaKeySession_RequireSecureDecoderModule(mediaKeySession, "video/avc", &requireSecureDecoder); + if (ret != DRM_ERR_OK) { + printf("OH_MediaKeySession_RequireSecureDecoderModule failed."); + } + ``` + +13. Generate a media key request and process its response to request a license for DRM content authorization. + + ```c++ + #define MAX_DRM_MEDIA_KEY_RESPONSE_BUF_SIZE 24576 // 24576: (2 * 12 * 1024) + DRM_MediaKeyRequest mediaKeyRequest; + DRM_MediaKeyRequestInfo info; + // initData corresponds to PSSH data in the stream. Pass in the actual data. + unsigned char initData[512] = {0x00}; + memset(&info, 0, sizeof(DRM_MediaKeyRequestInfo)); + info.initDataLen = sizeof(initData); + info.type = MEDIA_KEY_TYPE_ONLINE; // MEDIA_KEY_TYPE_ONLINE: online media key request; MEDIA_KEY_TYPE_OFFLINE: offline media key request. + memcpy(info.mimeType, (char *)"video/mp4", sizeof("video/mp4")); + memcpy(info.initData, initData, sizeof(initData)); + memcpy(info.optionName[0], (char *)"optionalDataName", sizeof("optionalDataName")); + memcpy(info.optionData[0], (char *)"optionalDataValue", sizeof("optionalDataValue")); + info.optionsCount = 1; + ret = OH_MediaKeySession_GenerateMediaKeyRequest(mediaKeySession, &info, &mediaKeyRequest); + if (ret != DRM_ERR_OK) { + printf("OH_MediaKeySession_GenerateMediaKeyRequest failed."); + } + /* + The application requests the DRM service through the network, obtains a media key response, and sends the response to OH_MediaKeySession_ProcessMediaKeyResponse. + If the response is an offline media key response, the offline media key ID is returned. Set mediaKeyId based on the actual data and length. + */ + unsigned char mediaKeyId[128] = {0x00}; + int32_t mediaKeyIdLen = 128; + // MAX_DRM_MEDIA_KEY_RESPONSE_BUF_SIZE specifies the maximum length of a media key response. Pass in the actual length. + unsigned char mediaKeyResponse[MAX_DRM_MEDIA_KEY_RESPONSE_BUF_SIZE] = {0x00}; + int32_t mediaKeyResponseLen = MAX_DRM_MEDIA_KEY_RESPONSE_BUF_SIZE; + ret = OH_MediaKeySession_ProcessMediaKeyResponse(mediaKeySession, mediaKeyResponse, + mediaKeyResponseLen, mediaKeyId, &mediaKeyIdLen); + if (ret != DRM_ERR_OK) { + printf("OH_MediaKeySession_ProcessMediaKeyResponse failed."); + } + ``` + +14. (Optional) Restore offline media keys. + + ```c++ + // Load the media key with the specified media key ID to the current session. + ret = OH_MediaKeySession_RestoreOfflineMediaKeys(mediaKeySession, mediaKeyId, mediaKeyIdLen); + if (ret != DRM_ERR_OK) { + printf("OH_MediaKeySession_RestoreOfflineMediaKeys failed."); + } + ``` + +15. (Optional) Check the status of media keys. + + ```c++ + DRM_MediaKeyStatus mediaKeyStatus; + ret = OH_MediaKeySession_CheckMediaKeyStatus(mediaKeySession, &mediaKeyStatus); + if (ret != DRM_ERR_OK) { + printf("OH_MediaKeySession_CheckMediaKeyStatus failed."); + } + ``` + +16. (Optional) Obtain the IDs of offline media keys, obtain their status, and clear the keys. + + ```c++ + DRM_OfflineMediakeyIdArray offlineMediaKeyIds; + ret = OH_MediaKeySystem_GetOfflineMediaKeyIds(mediaKeySystem, &offlineMediaKeyIds); + if (ret != DRM_ERR_OK) { + printf("OH_MediaKeySystem_GetOfflineMediaKeyIds failed."); + } + DRM_OfflineMediaKeyStatus OfflineMediaKeyStatus = OFFLINE_MEDIA_KEY_STATUS_UNKNOWN; + ret = OH_MediaKeySystem_GetOfflineMediaKeyStatus(mediaKeySystem, offlineMediaKeyIds.ids[0], offlineMediaKeyIds.idsLen[0], &OfflineMediaKeyStatus); + if (ret != DRM_ERR_OK) { + printf("OH_MediaKeySystem_GetOfflineMediaKeyStatus failed."); + } + ret = OH_MediaKeySystem_ClearOfflineMediaKeys(mediaKeySystem, offlineMediaKeyIds.ids[0], offlineMediaKeyIds.idsLen[0]); + if (ret != DRM_ERR_OK) { + printf("OH_MediaKeySystem_ClearOfflineMediaKeys failed."); + } + ``` + +17. Destroy the MediaKeySession instance. + + ```c++ + ret = OH_MediaKeySession_Destroy(mediaKeySession); + if (ret != DRM_ERR_OK) { + printf("OH_MediaKeySession_Destroy failed."); + } + ``` + +18. Destroy the MediaKeySystem instance. + + ```c++ + ret = OH_MediaKeySystem_Destroy(mediaKeySystem); + if (ret != DRM_ERR_OK) { + printf("OH_MediaKeySystem_Destroy failed."); + } + ``` diff --git a/en/application-dev/media/drm/drm-mediakeysession-management.md b/en/application-dev/media/drm/drm-mediakeysession-management.md deleted file mode 100644 index 6c569eea086584097c5f484ab9da3263fdc658fe..0000000000000000000000000000000000000000 --- a/en/application-dev/media/drm/drm-mediakeysession-management.md +++ /dev/null @@ -1,177 +0,0 @@ -# DRM Media Key Session Management (ArkTS) - -The **MediaKeySystem** class of the DRM module supports media key management and media decryption. **MediaKeySession** instances are created and destroyed by **MediaKeySystem** instances. - -## How to Develop - -Read [DRM](../../reference/apis-drm-kit/js-apis-drm.md) for the API reference. - -1. Import the module. - - ```ts - import { drm } from '@kit.DrmKit'; - ``` - -2. Import the **BusinessError** module, which provides the error codes thrown by the APIs of the DRM module. - - ```ts - import { BusinessError } from '@kit.BasicServicesKit'; - ``` - -3. Listen for the session status. - - You can listen for the following events of a **MediaKeySession** instance: key request events, key expiry events, vendor-defined events, key update on expiry events, and key change events. - - - Listen for key request events, which are triggered when a media key is requested. - - ```ts - mediaKeySession.on('keyRequired', (eventInfo: drm.EventInfo) => { - console.log('keyRequired' + 'info:' + eventInfo.info + ' extraInfo:' + eventInfo.extraInfo); - }); - ``` - - - Listen for key expiry events, which are triggered when a media key expires. - - ```ts - mediaKeySession.on('keyExpired', (eventInfo: drm.EventInfo) => { - console.log('keyExpired' + 'info:' + eventInfo.info + ' extraInfo:' + eventInfo.extraInfo); - }); - ``` - - - Listen for vendor-defined events, which are triggered when a custom event of the DRM scheme occurs. - - ```ts - mediaKeySession.on('vendorDefined', (eventInfo: drm.EventInfo) => { - console.log('vendorDefined' + 'info:' + eventInfo.info + ' extraInfo:' + eventInfo.extraInfo); - }); - ``` - - - Listen for key update on expiry events, which are triggered when a media key updates upon expiry. - - ```ts - mediaKeySession.on('expirationUpdate', (eventInfo: drm.EventInfo) => { - console.log('expirationUpdate' + 'info:' + eventInfo.info + ' extraInfo:' + eventInfo.extraInfo); - }); - ``` - - - Listen for key change events, which are triggered when a media key is changed. - - ```ts - mediaKeySession.on('keysChange', (keyInfo : drm.KeysInfo[], newKeyAvailable:boolean) => { - for(let i = 0; i < keyInfo.length; i++){ - console.log('keysChange' + 'info:' + keyInfo[i].keyId + ' extraInfo:' + keyInfo[i].value); - } - }); - ``` - -4. Generate a media key request and process its response. - - ```ts - let initData = new Uint8Array([0x00, 0x00, 0x00, 0x00]); - // Set optional data based on the DRM scheme. - let optionalData:drm.OptionsData[] = [{ - name: "...", - value: "..." - }]; - // The following example shows how to set an online media key request and response. - mediaKeySession.generateMediaKeyRequest("video/avc", initData, drm.MediaKeyType.MEDIA_KEY_TYPE_ONLINE, optionalData).then(async (licenseRequest) => { - console.info("generateMediaKeyRequest success", licenseRequest.mediaKeyRequestType, licenseRequest.data, licenseRequest.defaultURL); - // Send licenseRequest.data returned by the media key request to the DRM service through a network request to obtain a response and process the response. - let licenseResponse = new Uint8Array([0x00, 0x00, 0x00, 0x00]); - mediaKeySession.processMediaKeyResponse(licenseResponse).then((mediaKeyId: Uint8Array) => { - console.info("processMediaKeyResponse success"); - }).catch((err:BusinessError) =>{ - console.info("processMediaKeyResponse err end", err.code); - }); - }).catch((err:BusinessError) =>{ - console.info("generateMediaKeyRequest err end", err.code); - }); - // The following example shows how to set an offline media key request and response. - let offlineMediaKeyId = new Uint8Array([0x00, 0x00, 0x00, 0x00]); - mediaKeySession.generateMediaKeyRequest("video/avc", initData, drm.MediaKeyType.MEDIA_KEY_TYPE_OFFLINE, optionalData).then((licenseRequest: drm.MediaKeyRequest) => { - console.info("generateMediaKeyRequest success", licenseRequest.mediaKeyRequestType, licenseRequest.data, licenseRequest.defaultURL); - // Send licenseRequest.data returned by the media key request to the DRM service through a network request to obtain a response and process the response. - let licenseResponse = new Uint8Array([0x00, 0x00, 0x00, 0x00]); - mediaKeySession.processMediaKeyResponse(licenseResponse).then((mediaKeyId: Uint8Array) => { - offlineMediaKeyId = mediaKeyId; - console.info("processMediaKeyResponse success"); - }).catch((err:BusinessError) =>{ - console.info("processMediaKeyResponse err end", err.code); - }); - }).catch((err:BusinessError) =>{ - console.info("generateMediaKeyRequest err end", err.code); - }); - ``` - -5. (Optional) Check the media key status of the media key session. - - ```ts - try { - let keyvalue: drm.MediaKeyStatus[] = mediaKeySession.checkMediaKeyStatus(); - console.info("checkMediaKeyStatus success", keyvalue[0].value); - } catch (err) { - let error = err as BusinessError; - console.error(`checkMediaKeyStatus ERROR: ${error}`); - } - ``` - -6. (Optional) Generate an offline media key release request and process its response. - - ```ts - mediaKeySession.generateOfflineReleaseRequest(offlineMediaKeyId).then((OfflineReleaseRequest: Uint8Array) => { - console.info("generateOfflineReleaseRequest success", OfflineReleaseRequest); - // Send OfflineReleaseRequest returned by the offline media key release request to the DRM service through a network request to obtain a response and process the response. - let OfflineReleaseResponse = new Uint8Array([0x00, 0x00, 0x00, 0x00]); - mediaKeySession.processOfflineReleaseResponse(offlineMediaKeyId, OfflineReleaseResponse).then(() => { - console.info("processOfflineReleaseResponse success"); - }).catch((err:BusinessError) =>{ - console.info("processOfflineReleaseResponse err end", err.code); - }); - }).catch((err:BusinessError) =>{ - console.info("generateOfflineReleaseRequest err end", err.code); - }); - ``` - -7. (Optional) Restore offline media keys. - - ```ts - // Restore the specified media key information to the media key session. - mediaKeySession.restoreOfflineMediaKeys(offlineMediaKeyId).then(() => { - console.log("restoreOfflineMediaKeys success."); - }).catch((err: BusinessError) => { - console.error(`restoreOfflineMediaKeys: ERROR: ${err}`); - }); - ``` - -8. (Optional) Obtain the content protection level of the media key session. - - ```ts - try { - let contentProtectionLevel: drm.ContentProtectionLevel = mediaKeySession.getContentProtectionLevel(); - } catch (err) { - let error = err as BusinessError; - console.error(`getContentProtectionLevel ERROR: ${error}`); - } - ``` - -9. (Optional) Check whether secure decoding is required. - - ```ts - try { - let status: boolean = mediaKeySession.requireSecureDecoderModule("video/avc"); - } catch (err) { - let error = err as BusinessError; - console.error(`requireSecureDecoderModule ERROR: ${error}`); - } - ``` - -10. (Optional) Clear the media keys of the media key session. - - ```ts - try { - mediaKeySession.clearMediaKeys(); - } catch (err) { - let error = err as BusinessError; - console.error(`clearMediaKeys ERROR: ${error}`); - } - ``` diff --git a/en/application-dev/media/drm/drm-mediakeysystem-management.md b/en/application-dev/media/drm/drm-mediakeysystem-management.md deleted file mode 100644 index cdce86d0f66a2451e82dc78cf99b69e3ab2b9208..0000000000000000000000000000000000000000 --- a/en/application-dev/media/drm/drm-mediakeysystem-management.md +++ /dev/null @@ -1,196 +0,0 @@ -# DRM Media Key System Management (ArkTS) - -Using the **MediaKeySystem** class of the DRM module, you can manage **MediaKeySystem** instances, generate media key system requests to obtain DRM certificates, process responses to these requests, manage media key sessions, manage offline media keys, and obtain DRM statistics and device configuration information. - -Before using DRM Kit, check whether the device supports the DRM capabilities of a specific DRM scheme. - -In DRM Kit, the DRM scheme exists as a plug-in. - -## How to Develop - -Read [DRM](../../reference/apis-drm-kit/js-apis-drm.md) for the API reference. - -1. Import the module. - - ```ts - import { drm } from '@kit.DrmKit'; - ``` - -2. Import the **BusinessError** module, which provides the error codes thrown by the APIs of the DRM module. - - ```ts - import { BusinessError } from '@kit.BasicServicesKit'; - ``` - -3. Check whether the device supports the specified DRM scheme. - - > **NOTE** - > - > The value **false** means that the device does not support the specified DRM scheme. - - ```ts - let isSupported: boolean = drm.isMediaKeySystemSupported("com.clearplay.drm", "video/avc", drm.ContentProtectionLevel.CONTENT_PROTECTION_LEVEL_SW_CRYPTO); - ``` - -4. (Optional) Obtain the name and ID list of the DRM schemes on the device. - - > **NOTE** - > - > If the returned array is empty, no DRM scheme is supported by the device. - - ```ts - let description: drm.MediaKeySystemDescription[] = drm.getMediaKeySystems(); - ``` - -5. Create a **MediaKeySystem** instance. - - > **NOTE** - > - > If the creation fails, **undefined** is returned, indicating that the device does not support the DRM capability. - - ```ts - let mediaKeySystem: drm.MediaKeySystem = drm.createMediaKeySystem("com.clearplay.drm"); - ``` - -6. (Optional) Obtain the UUID corresponding to the specified DRM scheme name. - - > **NOTE** - > - > If the length of the returned UUID is 0, no DRM scheme is supported by the device. - - ```ts - let uuid: string = drm.getMediaKeySystemUuid("com.clearplay.drm"); - ``` - -7. (Optional) Set and obtain the configuration items supported by the DRM scheme. - - ```ts - // If the DRM scheme supports configuration item setting, set the value of a configuration item of the string type supported by the DRM scheme. - mediaKeySystem.setConfigurationString("configName", "configValue"); - // Obtain the value of a configuration item in the form of a string. - let configValueString : string = mediaKeySystem.getConfigurationString("version"); - let configValueUint8ArrayA: Uint8Array = new Uint8Array([0x00, 0x00, 0x00, 0x00]); - // If the DRM scheme supports configuration item setting, set the value of a configuration item of the array type supported by the DRM scheme. - mediaKeySystem.setConfigurationByteArray("Uint8ArrayConfigName", configValueUint8ArrayA); - // Obtain the value of a configuration item in the form of an array. - let configValueUint8ArrayB: Uint8Array = mediaKeySystem.getConfigurationByteArray("Uint8ArrayConfigName"); - ``` - -8. (Optional) Obtain the maximum content protection level supported by the device. - - ```ts - let contentProtectionLevel: drm.ContentProtectionLevel = drm.ContentProtectionLevel.CONTENT_PROTECTION_LEVEL_UNKNOWN; - try { - contentProtectionLevel = mediaKeySystem.getMaxContentProtectionLevel(); - } catch (err) { - let error = err as BusinessError; - console.error(`getMaxContentProtectionLevel ERROR: ${error}`); - } - ``` - -9. Start listening. - - Listen for the event indicating that the application requests a DRM certificate. - - Register the event **'keySystemRequired'**. This event can be listened for when a **MediaKeySystem** instance is created and is triggered when the application requests a DRM certificate. - - ```ts - mediaKeySystem.on('keySystemRequired', (eventInfo: drm.EventInfo) => { - console.log('keySystemRequired' + 'extra:' + eventInfo.extraInfo + ' data:' + eventInfo.info); - }); - ``` - -10. (Optional) Obtain the status of the DRM certificate. - - ```ts - let certificateStatus: drm.CertificateStatus = mediaKeySystem.getCertificateStatus(); - ``` - -11. Generate a provision request. - - During the creation of a **MediaKeySession** session, if no DRM certificate is available, the **keySystemRequired** event is triggered. In this case, the DRM certificate status on the device is obtained first. If the device does not have a DRM certificate or the DRM certificate status is abnormal (not **drm.CertificateStatus.CERT_STATUS_PROVISIONED**), a provision request is generated to obtain a DRM certificate. - - ```ts - if(certificateStatus != drm.CertificateStatus.CERT_STATUS_PROVISIONED){ - mediaKeySystem.generateKeySystemRequest().then(async (drmRequest: drm.ProvisionRequest) => { - console.info("generateKeySystemRequest success", drmRequest.data, drmRequest.defaultURL); - }).catch((err:BusinessError) =>{ - console.info("generateKeySystemRequest err end", err.code); - }); - } else { - console.info("The certificate already exists."); - } - ``` - -12. Process the provision response. - - A response to the provision request is received. You need to process this response. - - ```ts - // Send drmRequest.data returned by the provision request to the DRM certificate service through a network request to obtain a provision response and process the response. - let provisionResponseByte = new Uint8Array([0x00, 0x00, 0x00, 0x00]); - mediaKeySystem.processKeySystemResponse(provisionResponseByte).then(() => { - console.info("processKeySystemResponse success"); - }).catch((err:BusinessError) =>{ - console.info("processKeySystemResponse err end", err.code); - }); - ``` - -13. Create a **MediaKeySession** instance. - - Create a **MediaKeySession** instance with the specified content protection level or a **MediaKeySession** instance with the default content protection level of the DRM scheme. - ```ts - let mediaKeySession: drm.MediaKeySession = mediaKeySystem.createMediaKeySession(); - ``` - -14. (Optional) Obtain the list of offline media key IDs, which are used to manage offline media keys. - - ```ts - let offlineMediaKeyIds: Uint8Array[] = mediaKeySystem.getOfflineMediaKeyIds(); - ``` - -15. (Optional) Obtain the status of offline media keys. - - ```ts - try { - let offlineMediaKeyStatus: drm.OfflineMediaKeyStatus = mediaKeySystem.getOfflineMediaKeyStatus(offlineMediaKeyIds[0]); - } catch (err) { - let error = err as BusinessError; - console.error(`getOfflineMediaKeyStatus ERROR: ${error}`); - } - ``` - -16. (Optional) Clear offline media keys. - - ```ts - try { - mediaKeySystem.clearOfflineMediaKeys(offlineMediaKeyIds[0]); - } catch (err) { - let error = err as BusinessError; - console.error(`clearOfflineMediaKeys ERROR: ${error}`); - } - ``` - -17. (Optional) Obtain DRM statistical information, including the number of current sessions, decryption times, and decryption failures, as well as the plug-in version. - - ```ts - let statisticKeyValue: drm.StatisticKeyValue[] = mediaKeySystem.getStatistics(); - ``` - -18. Destroy the **MediaKeySession** instance. - - Destroy the **MediaKeySession** instance when the encrypted content is decrypted and the instance is no longer needed. - - ```ts - // Release resources when the MediaKeySession instance is no longer needed. - mediaKeySession.destroy(); - ``` - -19. Destroy this **MediaKeySystem** instance. - - Destroy the **MediaKeySystem** instance when it is no longer used. - - ```ts - // Release resources when the MediaKeySystem instance is no longer needed. - mediaKeySystem.destroy(); - ``` \ No newline at end of file diff --git a/en/application-dev/media/drm/drm-overview.md b/en/application-dev/media/drm/drm-overview.md index bec53f015465cd4cb417cb80749f5fc2001e53b7..12603addf31da327937534f708ce2d16ba66eb32 100644 --- a/en/application-dev/media/drm/drm-overview.md +++ b/en/application-dev/media/drm/drm-overview.md @@ -1,53 +1,91 @@ # Introduction to DRM Kit -You can call the APIs provided by Digital Rights Management Kit (DRM Kit) to decrypt DRM-protected audio and video content and manage DRM certificates and media keys on devices. +Digital Rights Management Kit (DRM Kit) is a digital rights protection service that supports authorization and decryption of DRM-encrypted content. It provides features such as DRM plugin management, DRM certificate management, DRM license management, DRM content authorization, and DRM content decryption. It enables the integration of DRM solutions, certificate provisioning for DRM solutions, content authorization, and content decryption. ## Available Capabilities -- Decryption and playback: provides unified audio and video decryption capabilities, which enable audio and video applications to play DRM-protected content after integrating with DRM. -- DRM scheme support: supports various DRM schemes. +With DRM Kit, DRM solution integrators can seamlessly integrate DRM solutions into their systems. Application developers can leverage these integrations to authorize and decrypt DRM-encrypted content, thereby enabling the playback of DRM-protected content. -- Online certificate download: supports device certificate requests and settings. +- DRM plugin management: By implementing the DRM HDI provided by DRM Kit, you can support various DRM solutions. This is typically handled by DRM solution integrators. + +- DRM certificate management: supports the request and processing of device certificates for DRM solutions, and enables certificate provisioning for the corresponding DRM solutions. + +- DRM license management: supports the request, processing, and deletion of offline licenses. + +- DRM content authorization: includes online license requests and processing, loading of offline licenses, querying the status of media keys, and authorizing DRM content based on the permissions specified in the DRM license. + +- DRM content decryption: Supported media protocols include HLS and DASH; container formats include MP4 and TS; video encoding format is H.264; audio encoding format is AAC. + +> **NOTE** +> +> DRM certificate management, DRM license management, DRM content authorization, and DRM content decryption all depend on the implementation of the corresponding DRM solutions. You can independently extend the supported media protocols, container formats, and audio/video encoding formats. -- Online/Offline media key authorization: supports online media key requests and settings, and offline media key requests, loading, updates, deletion, and status query. ## Features -- Media key and decryption session management +- **License and decryption session management** - DRM Kit supports multiple sessions, allows users to request and set media keys in sessions, and binds decryption sessions to media keys. + DRM Kit supports multiple MediaKeySession instances, allowing for license requests and settings within sessions. Decryption sessions can be bound to licenses. -- Secure and non-secure video channels +- **Secure video channels** - DRM Kit supports secure video channels with encrypted memory calls and decoding. It also supports non-secure channels with non-encrypted memory calls and decoding. + DRM Kit supports secure video channels, ensuring secure decryption, decoding, rendering, and output. However, the kit only provides the APIs for secure decryption. The actual secure decryption, decoding, rendering, and output rely on the implementation of the DRM solution and the operating system. ## Basic Concepts + Be familiar with the following basic concepts before development: -- DRM scheme (DRM plugin) +- DRM plugin + + A DRM solution driver integrated into the system, implementing the DRM HDI and providing DRM-related features. + +- MediaKeySystem - Below the DRM framework layer, there are drivers that implement the DRM Hardware Device Interface (HDI) layer. Content decryption is implemented in the drivers. + Used to manage DRM certificates and MediaKeySession lifecycle. -- DRM session (MediaKeySession) +- MediaKeySession - DRM sessions are used for media key management and media decryption. Their lifecycle are managed by DRM instances (MediaKeySystem). + Used to manage licenses and decrypt media content. Its lifecycle is managed by MediaKeySystem. -## Development Model +- DRM information (MediaKeySystemInfo) + + Descriptive information for DRM content encryption, such as the DRM solution UUID and PSSH data. -Specific DRM implementation manners and technical details vary according to the types of the content, protection requirements, and use scenarios. +- PSSH -The DRM working process can be summarized into three parts: device certificate management, media key management, and decryption management. + Protection System Specific Header Box, which contains data used by the DRM solution to describe how DRM content is encrypted. -- After creating a DRM instance, the client creates a DRM decryption session. If the client detects that the device does not have a device DRM certificate or the certificate is abnormal, it starts the online certificate download process. +- DRM certificate -- After the certificate is downloaded, the client creates a DRM decryption session and generates a media key request. The client obtains the response to the media key request from the server and sets it on the device. There are online and offline media keys. You can obtain the IDs of media keys, check their status, and clear them. + A certificate required by DRM solutions for normal operation. Different DRM solutions have different DRM certificates. -- The client sets the decryption configuration to decrypt the content. +- DRM certificate provisioning + + A process used by DRM solutions to provision certificates. The process varies among different DRM solutions. For specific requirements, refer to the implementation guidelines of the DRM solution. -The figure below illustrates the DRM development model for you to better develop applications with digital rights protection. +- License + + Used by DRM solutions to implement DRM authorization for devices. Common permission control policies include security levels, output control, start playback time, and end playback time. Different DRM solutions may use different license formats and support different permission control policies. -**Figure 1** DRM development model +- Audio/Video Data Frame Encryption Information (cencInfo) + + Descriptive information for encryption of audio/video data frames, such as encryption algorithms and modes, KeyId, IV, and subsample information. +## Workflow + +DRM plugin management is typically implemented by DRM solution integrators. For details, see[DRM Solution Development](drm-solution-dev-guide.md). + +The following figure shows the process of integrating DRM Kit into your application. ![Drm Development Model](figures/drm-development-model.png) -The player application calls DRM APIs to implement basic operations such as device certificate management, media key management, and decryption management. To implement these basic operations, you need to create a DRM instance and request and set a device certificate. Then, you need to create a session instance and request and set a media key. When an encrypted stream arrives, the player application sends it to a specific DRM plugin for decryption through the bottom-layer HDI. +The working process includes: + +1. Creation of MediaKeySystem and MediaKeySession instances: The application obtains the DRM information of the content and creates MediaKeySystem and MediaKeySession instances based on the solution UUID in the DRM information. This can be done using service-provided DRM descriptions or through the mediaKeySystemInfoUpdate event or MediaKeySystemInfo callback from Media Kit or AVCodec Kit. + +2. Certificate provisioning: When a MediaKeySession instance is created, if there is no DRM certificate or if the certificate is invalid, DRM Kit will trigger an event requiring DRM certificate provisioning (keySystemRequired). At this point, the certificate provisioning API of MediaKeySystem is called to complete the provisioning. Alternatively, based on the DRM solution's requirements, the DRM certificate status can be checked. If there is no valid certificate, the certificate provisioning API of MediaKeySystem can be proactively invoked. If the certificate is valid or if no provisioning is required, this step can be skipped. + +3. License retrieval: The application calls the license-related API of MediaKeySession based on the PSSH data in the DRM event to request and process the DRM license. + +4. DRM content decryption: The application sets MediaKeySession to Media Kit or AVCodec Kit to support DRM content decryption. When AVCodec Kit is used, the cencInfo of the audio/video data frames can be set and placed into the AVBuffer, enabling decryption and decoding of the audio/video data frames during the PushInputBuffer call. + +5. License update or expiration: During content playback, if a license update is required, MediaKeySession will trigger a license update event (keyRequired), prompting a re-request for the DRM license. If MediaKeySession triggers a license expiration event (keyExpired), DRM content playback should be stopped. diff --git a/en/application-dev/media/drm/drm-solution-dev-guide.md b/en/application-dev/media/drm/drm-solution-dev-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..2af11403d6ff2046ca3e25c6f456ca49f8f8f9fb --- /dev/null +++ b/en/application-dev/media/drm/drm-solution-dev-guide.md @@ -0,0 +1,502 @@ +# DRM Solution Development + +DRM plugins implement the DRM HDI, and the DRM framework of DRM Kit loads the DRM plugins through the HDI. + +Plugins are developed by DRM solution integrators and placed in the /vendor partition of devices. + +For details about the development process of the OpenHarmony HDI plugin driver service, see [HDF Driver Development Process](../../../device-dev/driver/driver-hdf-manage.md). The IDL of the DRM HDI API is defined in the **ohos/drivers/interface/drm/v1_0** directory, where **v1_0** is the HDI API version number and should be changed to the actual version number. + +After the IDL of the DRM HDI API is built, you can find the generated .h and .cpp files of the corresponding version in **//ohos/out/*productModel*/gen/drivers/interface/drm/v1_0/**. + +To implement a DRM plugin (clearplay used as an example), perform the following steps: + +1. [Plugin Development](#plugin-development) + - Module addition + - Driver entry implementation + - HDI API implementation + - Compilation configuration + - Component configuration + - Component compilation entry configuration + - Service code compilation + +2. [DRM Plugin Service Configuration](#drm-plugin-service-configuration) + - hcs configuration + - Host user and group configuration + - Dynamic loading + +3. [Adding SELinux Permissions](#adding-selinux-permissions) + +## Plugin Development + +### Module Addition + +Create a plugin directory. The following is an example: +``` +//drivers/peripheral/clearplay +. +├── BUILD.gn # Module compilation file. +├── bundle.json # Component configuration file. +├── hdi_service # HDI service code of the DRM solution. +│ ├── BUILD.gn # Configuration file for the HDI service code of the DRM solution. +│ ├── common # Utility code for the HDI service of the DRM solution, including JSON parsing and Base64 encoding/decoding. +│ ├── include # Header file for the HDI service of the DRM solution. +│ └── src # Implementation code for the HDI service of DRM solution. +├── interfaces # Capability interfaces for the HDI service of the DRM solution. +│ ├── BUILD.gn # Configuration file for the capability interfaces of the HDI service code of the DRM solution. +│ ├── include # Capability interface file for the HDI service of the DRM solution. +│ └── src # Implementation of the capability interfaces of the HDI service of the DRM solution. +└── README.md # Description of the HDI service component in the DRM solution. +``` + +### Driver Entry Implementation + +Refer to **//ohos/out/productModel/gen/drivers/interface/drm/v1_0/media_key_system_factory_driver.cpp** for the driver entry implementation. Make the following modifications in the driver entry and configure the compilation manually: + +``` +using namespace OHOS::HDI::Drm::V1_0; // 1. V1_0 indicates the HDI API version number. Replace it with the actual version number. + +struct HdfMediaKeySystemFactoryHost { + struct IDeviceIoService ioService; + OHOS::sptr stub; +}; +static int HdfMediaKeySystemFactoryDriverBind(struct HdfDeviceObject *deviceObject) +{ + auto *hdfMediaKeySystemFactoryHost = new (std::nothrow) HdfMediaKeySystemFactoryHost; + if (hdfMediaKeySystemFactoryHost == nullptr) { + HDF_LOGE("%{public}s: failed to create create HdfMediaKeySystemFactoryHost object", __func__); + return HDF_FAILURE; + } + int ret = HdfDeviceObjectSetInterfaceDesc(deviceObject, "ohos.hdi.drm.v1_0.IMediaKeySystemFactory"); // 2. Bind the service interface descriptor. This allows the DRM framework to access the HDI service of the DRM solution via the descriptor. Adjust according to the specific HDI API version number. + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s: failed to HdfDeviceObjectSetInterfaceDesc", __func__); + } + + hdfMediaKeySystemFactoryHost->ioService.Dispatch = MediaKeySystemFactoryDriverDispatch; + hdfMediaKeySystemFactoryHost->ioService.Open = NULL; + hdfMediaKeySystemFactoryHost->ioService.Release = NULL; + + auto serviceImpl = OHOS::HDI::Drm::V1_0::IMediaKeySystemFactory::Get("clearplay_service", true); // 3. Obtain the HDI service instance of the DRM solution. + if (serviceImpl == nullptr) { + HDF_LOGE("%{public}s: failed to get of implement service", __func__); + delete hdfMediaKeySystemFactoryHost; + return HDF_FAILURE; + } + + hdfMediaKeySystemFactoryHost->stub = OHOS::HDI::ObjectCollector::GetInstance().GetOrNewObject(serviceImpl, + OHOS::HDI::Drm::V1_0::IMediaKeySystemFactory::GetDescriptor()); // 4. Obtain the stub object corresponding to the HDI service implementation of the DRM solution. + if (hdfMediaKeySystemFactoryHost->stub == nullptr) { + HDF_LOGE("%{public}s: failed to get stub object", __func__); + delete hdfMediaKeySystemFactoryHost; + return HDF_FAILURE; + } + + deviceObject->service = &hdfMediaKeySystemFactoryHost->ioService; + return HDF_SUCCESS; +} + +static int32_t MediaKeySystemFactoryDriverDispatch(struct HdfDeviceIoClient *client, int cmdId, struct HdfSBuf *data, + struct HdfSBuf *reply) +{ + auto *hdfMediaKeySystemFactoryHost = + CONTAINER_OF(client->device->service, struct HdfMediaKeySystemFactoryHost, ioService); + + OHOS::MessageParcel *dataParcel = nullptr; + OHOS::MessageParcel *replyParcel = nullptr; + OHOS::MessageOption option; + + if (SbufToParcel(data, &dataParcel) != HDF_SUCCESS) { + HDF_LOGE("%{public}s: invalid data sbuf object to dispatch", __func__); + return HDF_ERR_INVALID_PARAM; + } + if (SbufToParcel(reply, &replyParcel) != HDF_SUCCESS) { + HDF_LOGE("%{public}s: invalid reply sbuf object to dispatch", __func__); + return HDF_ERR_INVALID_PARAM; + } + + return hdfMediaKeySystemFactoryHost->stub->SendRequest(cmdId, *dataParcel, *replyParcel, option); +} +``` + +### HDI API Implementation + +Refer to the .cpp file automatically generated in **//ohos/out/*productModel*/gen/drivers/interface/drm/v1_0/** for the HDI API implementation. You can modify or add files based on service requirements. The following uses **media_key_system_factory_service.cpp** as an example. + +``` +extern "C" IMediaKeySystemFactory *MediaKeySystemFactoryImplGetInstance(void) +{ + // Add implementation here. + return new (std::nothrow) MediaKeySystemFactoryService(); +} + +int32_t MediaKeySystemFactoryService::IsMediaKeySystemSupported(const std::string& name, const std::string& mimeType, + OHOS::HDI::Drm::V1_0::ContentProtectionLevel level, bool& isSupported) +{ + // Add implementation here. + return HDF_SUCCESS; +} + +int32_t MediaKeySystemFactoryService::CreateMediaKeySystem(sptr& mediaKeySystem) +{ + // Add implementation here. + return HDF_SUCCESS; +} + +int32_t MediaKeySystemFactoryService::GetMediaKeySystemDescription(std::string& name, std::string& uuid) +{ + // Add implementation here. + return HDF_SUCCESS; +} + +``` + +### Compilation Configuration +//drivers/peripheral/clearplay/BUILD.gn + +``` +if (defined(ohos_lite)) { + group("clearplay_entry") { + deps = [] + } +} else { + group("clearplay_entry") { + deps = [ + "./hdi_service:hdf_clearplay_service", + "./interfaces:hdf_clearplay_interfaces", + ] + } +} +``` + +//drivers/peripheral/clearplay/hdi_service/BUILD.gn +``` +import("//build/ohos.gni") + +ohos_shared_library("libmedia_key_system_factory_clearplay_service_1.0") { + include_dirs = [ + "./include", + "./include/drm/v1_0", + "./include/drm", + "./../interfaces/include", + "./../interfaces/include/drm/v1_0", + "./../interfaces/include/drm", + "./common", + ] + sources = [ + "./common/base64_utils.cpp", + "./src/media_decrypt_module_service.cpp", + "./src/media_key_session_callback_service.cpp", + "./src/media_key_session_service.cpp", + "./src/media_key_system_callback_service.cpp", + "./src/media_key_system_factory_service.cpp", + "./src/media_key_system_service.cpp", + "./src/oem_certificate_service.cpp", + ] + + deps = [ ] + + cflags = [ + "-Wall", + "-Wextra", + "-Werror", + "-fsigned-char", + "-fno-common", + "-fno-strict-aliasing", + ] + + external_deps = [ + "c_utils:utils", + "hdf_core:libhdf_utils", + "hilog:libhilog", + "ipc:ipc_single", + ] + + install_images = [ chipset_base_dir ] + subsystem_name = "hdf" + part_name = "drivers_peripheral_clearplay" +} + +group("hdf_clearplay_service") { + deps = [ ":libmedia_key_system_factory_clearplay_service_1.0" ] +} +``` + +//drivers/peripheral/clearplay/interfaces/BUILD.gn + +``` +import("//build/ohos.gni") + +ohos_shared_library("libclearplay_driver") { + include_dirs = [ + "./include", + "./include/drm", + ] + + public_configs = [ ":clearplay_imp_external_library_config" ] + sources = [ "./src/media_key_system_factory_driver.cpp" ] + + external_deps = [ + "c_utils:utils", + "drivers_interface_drm:libdrm_stub_1.0", + "hdf_core:libhdf_host", + "hdf_core:libhdf_ipc_adapter", + "hdf_core:libhdf_utils", + "hdf_core:libhdi", + "hilog:libhilog", + "ipc:ipc_single", + ] + cflags = [ + "-Wall", + "-Wextra", + "-Werror", + "-fsigned-char", + "-fno-common", + "-fno-strict-aliasing", + ] + shlib_type = "hdi" + install_images = [ chipset_base_dir ] + subsystem_name = "hdf" + part_name = "drivers_peripheral_clearplay" +} + +config("clearplay_imp_external_library_config") { + include_dirs = + [ "//drivers/peripheral/clearplay/interfaces/include/drm/v1_0" ] +} +group("hdf_clearplay_interfaces") { + deps = [ ":libclearplay_driver" ] +} +``` + +### Component Configuration + +Create the **drivers/peripheral/clearplay/build.json** file to define the new drivers_peripheral_clearplay component. + +``` +{ + "name": "@ohos/drivers_peripheral_clearplay", + "description": "clearplay drm device driver", + "version": "4.0", + "license": "Apache License 2.0", + "publishAs": "code-segment", + "segment": { + "destPath": "drivers/peripheral/clearplay" + }, + "dirs": {}, + "scripts": {}, + "component": { + "name": "drivers_peripheral_clearplay", + "subsystem": "hdf", + "syscap": [], + "adapted_system_type": ["standard"], + "rom": "", + "ram": "", + "deps": { + "components": [ + "bounds_checking_function", + "drivers_interface_drm", + "c_utils", + "hdf_core", + "hilog", + "ipc" + ], + "third_party": [] + }, + "build": { + "sub_component": [ + "//drivers/peripheral/clearplay:clearplay_entry" + ], + "inner_kits": [ + { + "type":"so", + "name": "//drivers/peripheral/clearplay/hdi_service:libmedia_key_system_factory_clearplay_service_1.0", + "header": { + "header_files": [ + "imedia_decrypt_module.h", + "imedia_key_session_callback.h", + "imedia_key_session.h", + "imedia_key_system_callback.h", + "imedia_key_system_factory.h", + "imedia_key_system.h", + "ioem_certificate.h", + "media_decrypt_module_proxy.h", + "media_decrypt_module_stub.h", + "media_key_session_callback_proxy.h", + "media_key_session_callback_stub.h", + "media_key_session_proxy.h", + "media_key_session_stub.h", + "media_key_system_callback_proxy.h", + "media_key_system_callback_stub.h", + "media_key_system_factory_proxy.h", + "media_key_system_factory_stub.h", + "media_key_system_proxy.h", + "media_key_system_stub.h", + "media_key_system_types.h", + "oem_certificate_proxy.h", + "oem_certificate_stub.h" + ], + "header_base": "//drivers/peripheral/clearplay/interfaces/include/drm/v1_0" + } + }, + { + "type":"so", + "name": "//drivers/peripheral/clearplay/interfaces:libclearplay_driver", + "header": { + "header_files": [], + "header_base": "//drivers/peripheral/clearplay/interfaces/include/drm/v1_0" + } + } + ] + } + } +} +``` +### Component Compilation Entry Configuration + +The following uses RK3568 as an example. The entry configuration file is **//productdefine/common/inherit/chipset_common.json**. + +``` +{ + "component": "drivers_peripheral_clearplay", + "features": [] +} +``` + +### Service Code Compilation + +This process is similar to the compilation of system components. +`./build.sh --product-name rk3568 --ccache --build-target drivers_peripheral_clearplay` +The binary files generated after compilation are as follows: +//ohos/out/rk3568/hdf/drivers_peripheral_clearplay/libclearplay_driver.z.so +//ohos/out/rk3568/hdf/drivers_peripheral_clearplay/libmedia_key_system_factory_clearplay_service_1.0.z.so + +## DRM Plugin Service Configuration + +### hcs Configuration + +The following uses RK3568 as an example. Add the driver service configuration to **vendor/hihope/rk3568/hdf_config/uhdf/device_info.hcs**. + +``` +clearplay :: host { + hostName = "clearplay_host"; // Process name. + priority = 50; + uid = ""; // uid of the user-mode process. It is left empty by default. If you do not set the value, this parameter will be set to the value of hostName, which indicates a common user. + gid = ""; // gid of the user-mode process. It is left empty by default. If you do not set the value, this parameter will be set to the value of hostName, which indicates a common user group. + caps = ["DAC_OVERRIDE", "DAC_READ_SEARCH"]; // Linux capabilities of the user-mode process. It is left empty by default. Set this parameter based on service requirements. + clearplay_device :: device { + device0 :: deviceNode { + policy = 2; + priority = 100; + moduleName = "libclearplay_driver.z.so"; // Driver loading entry. + serviceName = "clearplay_service"; // Service name. + } + } +} +``` + +### Host User and Group Configuration + +For the new host node in hcs, you must configure the uid and gid of the corresponding process. + +The **passwd** file is a system user configuration file that stores basic information about all users in the system. The following is an example: + +``` +//base/startup/init/services/etc/passwd +clearplay_host:x:1089:1089:::/bin/false +``` + +In **//base/startup/init/services/etc/passwd**, each line of user information is divided into 7 fields, separated by colons (:). The meaning of each field is as follows: + +Username: Password: uid: gid: Description: Home directory: Default shell + +The **group** file is the user group configuration file that stores information about all user groups. The following is an example: + +``` +base/startup/init/services/etc/group +clearplay_host:x:1089: +``` + +In **base/startup/init/services/etc/group**, each line indicates a user group. The user group is divided into four fields, separated by colons (:). The meaning of each field is as follows: + +Group name: Password: gid: List of users in the user group + +**NOTE** + +- **clearplay_host** in **passwd** corresponds to **uid** in **device_info.hcs**. If **uid** in **device_info.hcs** is not specified, the default value **hostName** is used. +- **clearplay_host** in **group** corresponds to **gid** in **device_info.hcs**. If **gid** in **device_info.hcs** is not specified, the default value **hostName** is used. + +### Dynamic Loading + +To reduce RAM memory usage, the DRM framework supports dynamic loading of DRM plugins. After the DRM framework calls the plugin, it should promptly unload the plugin to release the occupied RAM memory. The plugin must modify its service startup properties to configure itself as a lazy loading service and add itself to the lazy loading list configuration file for the DRM framework on the device. The HDI service provides dynamic loading capabilities, which are not loaded by default during system startup but can be loaded dynamically. Here is an example: + +Set **preload** to **2** in **device_info.hcs**. + +``` +clearplay :: host { + hostName = "clearplay_host"; + priority = 50; + clearplay_device :: device { + device0 :: deviceNode { + policy = 2; + priority = 100; + preload = 2; // If preload is set to 2, the system does not load the file during startup by default. You can manually load the file later. + moduleName = "libclearplay_driver.z.so"; + serviceName = "clearplay_service"; + } + } +} +``` +The **/etc/drm/drm_plugin_lazyloding.cfg** file on the device is the lazy loading list configuration file of the DRM framework. The file is in the format of key-value pairs, where the solution name of the DRM plugin is the key and the service name of the DRM solution is the value. +``` +{ + "plugin_services": { + "lazy_load_service": [ + "com.clearplay.drm:clearplay_service" + ] + } +} +``` + +## Adding SELinux Permissions + +SELinux is used to restrict resources that can be accessed by service processes. The following provides the basic SELinux configuration. Add required rules based on services. + +In the following example, **clearplay_host** indicates the value of **hostName** in hcs, and **clearplay_service** indicates the service name. + +//base/security/selinux_adapter/sepolicy/ohos_policy/drivers/adapter/public/hdf_service_contexts +`clearplay_service u:object_r:hdf_clearplay_service:s0` + +//base/security/selinux_adapter/sepolicy/ohos_policy/drivers/adapter/public/hdf_service.te +`type hdf_clearplay_service, hdf_service_attr;` + +//base/security/selinux_adapter/sepolicy/ohos_policy/startup/init/public/chipset_init.te +`allow init clearplay_host:process { rlimitinh siginh transition };` + +//base/security/selinux_adapter/sepolicy/ohos_policy/drivers/peripheral/clearplay/vendor/hdf_devmgr.te +``` +allow hdf_devmgr clearplay_host:binder { call transfer }; +allow hdf_devmgr clearplay_host:dir { search }; +allow hdf_devmgr clearplay_host:file { open read }; +allow hdf_devmgr clearplay_host:process { getattr }; +``` + +//base/security/selinux_adapter/sepolicy/ohos_policy/drivers/adapter/public/type.te +`type clearplay_host, hdfdomain, domain;` + +//base/security/selinux_adapter/sepolicy/ohos_policy/drivers/peripheral/clearplay/vendor/clearplay_host.te (Create this directory.) +``` +allow clearplay_host chip_prod_file:dir { search }; +allow clearplay_host dev_console_file:chr_file { read write }; +allow clearplay_host dev_hdf_kevent:chr_file { open read write ioctl getattr }; +allow clearplay_host dev_unix_socket:dir { search }; +allow clearplay_host hdf_device_manager:hdf_devmgr_class { get }; +allow clearplay_host hdf_devmgr:binder { call transfer }; +allow clearplay_host hdf_clearplay_service:hdf_devmgr_class { add }; +allow clearplay_host hilog_param:file { open read map }; +allow clearplay_host musl_param:file { open read map }; +allow clearplay_host sa_device_service_manager:samgr_class { get }; +allow clearplay_host samgr:binder { call }; +allow clearplay_host sh:binder { call }; +allow clearplay_host vendor_etc_file:dir { open read getattr search }; +allow clearplay_host vendor_etc_file:file { open read getattr }; +allowxperm clearplay_host dev_hdf_kevent:chr_file ioctl { 0x6202 0x6203 }; +``` diff --git a/en/application-dev/media/drm/native-drm-mediakeysession-management.md b/en/application-dev/media/drm/native-drm-mediakeysession-management.md deleted file mode 100644 index 44e54ef9252a2ab20be46831b9c83bec049ce67a..0000000000000000000000000000000000000000 --- a/en/application-dev/media/drm/native-drm-mediakeysession-management.md +++ /dev/null @@ -1,172 +0,0 @@ -# DRM Media Key Session Management (C/C++) - -The **MediaKeySystem** class of the DRM module supports media key management and media decryption. **MediaKeySession** instances are created and destroyed by **MediaKeySystem** instances. - -## How to Develop - -Read [DRM](../../reference/apis-drm-kit/_drm.md) for the API reference. - -1. Import the NDK, which provides DRM-related attributes and methods. - - ```c++ - #include "multimedia/drm_framework/native_drm_common.h" - #include "multimedia/drm_framework/native_drm_err.h" - #include "multimedia/drm_framework/native_mediakeysession.h" - #include "multimedia/drm_framework/native_mediakeysystem.h" - ``` - -2. Link the DRM NDK dynamic library in the CMake script. - - ```txt - target_link_libraries(PUBLIC libnative_drm.so) - ``` - -3. Declare the MediaKeySystem event listener callback. - - ```c++ - // This callback applies to the scenario where there is only one MediaKeySystem instance. - static Drm_ErrCode SessoinEventCallBack(DRM_EventType eventType, uint8_t *info, int32_t infoLen, char *extra) - { - return DRM_ERR_OK; - } - - static Drm_ErrCode SessoinKeyChangeCallBack(DRM_KeysInfo *keysInfo, bool newKeysAvailable) - { - return DRM_ERR_OK; - } - - // This callback applies to the scenario where there are multiple MediaKeySystem instances. - static Drm_ErrCode SessoinEventCallBackWithObj(MediaKeySession *mediaKeySessoin, DRM_EventType eventType, uint8_t *info, int32_t infoLen, char *extra) - { - return DRM_ERR_OK; - } - - static Drm_ErrCode SessoinKeyChangeCallBackWithObj(MediaKeySession *mediaKeySessoin, DRM_KeysInfo *keysInfo, bool hasNewGoodKeys) - { - return DRM_ERR_OK; - } - ``` - -4. Set the MediaKeySystem event listener callback. - - ```c++ - // This callback applies to the scenario where there is only one MediaKeySystem instance. - MediaKeySession_Callback sessionCallback = { SessoinEventCallBack, SessoinKeyChangeCallBack }; - Drm_ErrCode ret = OH_MediaKeySession_SetMediaKeySessionCallback(mediaKeySession, &sessionCallback); - if (ret != DRM_ERR_OK) { - printf("OH_MediaKeySession_SetMediaKeySessionCallback failed."); - } - - // This callback applies to the scenario where there are multiple MediaKeySystem instances. - OH_MediaKeySession_Callback sessionCallback = { SessoinEventCallBackWithObj, SessoinKeyChangeCallBackWithObj }; - ret = OH_MediaKeySession_SetCallback(mediaKeySession, &sessionCallback); - if (ret != DRM_ERR_OK) { - printf("OH_MediaKeySession_SetCallback failed."); - } - ``` - -5. Generate a media key request and process its response. - - ```c++ - DRM_MediaKeyRequest mediaKeyRequest; - DRM_MediaKeyRequestInfo info; - // initData corresponds to the PSSH data in the stream. Pass in the actual data. - unsigned char initData[128] = {0x00}; - memset_s(&info, sizeof(DRM_MediaKeyRequestInfo), 0, sizeof(DRM_MediaKeyRequestInfo)); - info.initDataLen = sizeof(initData); - info.type = MEDIA_KEY_TYPE_ONLINE; - memcpy_s(info.mimeType, sizeof("video/avc"), (char *)"video/avc", sizeof("video/avc")); - memcpy_s(info.initData, sizeof(initData), initData, sizeof(initData)); - memcpy_s(info.optionName[0], sizeof("optionalDataName"), (char *)"optionalDataName", sizeof("optionalDataName")); - memcpy_s(info.optionData[0], sizeof("optionalDataValue"), (char *)"optionalDataValue", sizeof("optionalDataValue")); - info.optionsCount = 1; - ret = OH_MediaKeySession_GenerateMediaKeyRequest(mediaKeySession, &info, &mediaKeyRequest); - if (ret != DRM_ERR_OK) { - printf("OH_MediaKeySession_GenerateMediaKeyRequest failed."); - } - /* The composition of an offline media key ID varies according to the DRM scheme. You can obtain an ID in either of the following ways: - 1. The application calls OH_MediaKeySystem_GetOfflineMediaKeyIds to obtain the ID. - 2. The application requests the DRM service through the network, obtains a keySessionResponse, and sends the response to OH_MediaKeySession_ProcessMediaKeyResponse for parsing. - An offline media key ID is obtained. The maximum length of a media key ID is 128. The following code is an example. Set the media key ID based on the actual media key data and length. - */ - unsigned char mediaKeyId[26] = {0x00}; - int32_t mediaKeyIdLen = 26; - // The maximum length of a media key response is 12288. Enter the actual length. - unsigned char mediaKeyResponse[12288] = {0x00}; - int32_t mediaKeyResponseLen = 12288; - ret = OH_MediaKeySession_ProcessMediaKeyResponse(mediaKeySession, mediaKeyResponse, - mediaKeyResponseLen, mediaKeyId, &mediaKeyIdLen); - if (ret != DRM_ERR_OK) { - printf("OH_MediaKeySession_ProcessMediaKeyResponse failed."); - } - ``` - -6. (Optional) Check the media key status of the media key session. - - ```c++ - DRM_MediaKeyStatus mediaKeyStatus; - ret = OH_MediaKeySession_CheckMediaKeyStatus(mediaKeySession, &mediaKeyStatus); - if (ret != DRM_ERR_OK) { - printf("OH_MediaKeySession_CheckMediaKeyStatus failed."); - } - ``` - -7. (Optional) Clear all media keys in the media key session. - - ```c++ - ret = OH_MediaKeySession_ClearMediaKeys(mediaKeySession); - if (ret != DRM_ERR_OK) { - printf("OH_MediaKeySession_ClearMediaKeys failed."); - } - ``` - -8. (Optional) Generate an offline media key release request and process its response. - - ```c++ - uint8_t releaseRequest[MAX_MEDIA_KEY_REQUEST_DATA_LEN]; - int32_t releaseRequestLen = MAX_MEDIA_KEY_REQUEST_DATA_LEN; - ret = OH_MediaKeySession_GenerateOfflineReleaseRequest(mediaKeySession, - mediaKeyId, mediaKeyIdLen, releaseRequest, &releaseRequestLen); - if (ret != DRM_ERR_OK) { - printf("OH_MediaKeySession_GenerateOfflineReleaseRequest failed."); - } - // keyReleaseResponse is obtained from the DRM service through the network request using the request body releaseRequest. Pass in the actual data obtained. - unsigned char keyReleaseResponse[12288] = {0x00}; - int32_t keyReleaseResponseLen = 12288; - ret = OH_MediaKeySession_ProcessOfflineReleaseResponse(mediaKeySession, mediaKeyId, mediaKeyIdLen, - keyReleaseResponse, keyReleaseResponseLen); - if (ret != DRM_ERR_OK) { - printf("OH_MediaKeySession_ProcessOfflineReleaseResponse failed."); - } - ``` - -9. (Optional) Restore offline media keys. - - ```c++ - // Load the media key with the specified media key ID to the current session. The loaded media key can belong to the current session or another session. - ret = OH_MediaKeySession_RestoreOfflineMediaKeys(mediaKeySession, mediaKeyId, mediaKeyIdLen); - if (ret != DRM_ERR_OK) { - printf("OH_MediaKeySession_RestoreOfflineMediaKeys failed."); - } - ``` - -10. (Optional) Call **OH_MediaKeySession_GetContentProtectionLevel** in the **MediaKeySession** class to obtain the content protection level of the current session. - - ```c++ - DRM_ContentProtectionLevel sessionContentProtectionLevel; - ret = OH_MediaKeySession_GetContentProtectionLevel(mediaKeySession, - &sessionContentProtectionLevel); - if (ret != DRM_ERR_OK) { - printf("OH_MediaKeySession_GetContentProtectionLevel failed."); - } - ``` - -11. (Optional) Check whether secure decoding is required. - - ```c++ - bool requireSecureDecoder; - ret = OH_MediaKeySession_RequireSecureDecoderModule(mediaKeySession, "video/avc", &requireSecureDecoder); - if (ret != DRM_ERR_OK) { - printf("OH_MediaKeySession_RequireSecureDecoderModule failed."); - } - ``` diff --git a/en/application-dev/media/drm/native-drm-mediakeysystem-management.md b/en/application-dev/media/drm/native-drm-mediakeysystem-management.md deleted file mode 100644 index 5d55c190ba2a139e371730c47089da5969d1c2da..0000000000000000000000000000000000000000 --- a/en/application-dev/media/drm/native-drm-mediakeysystem-management.md +++ /dev/null @@ -1,210 +0,0 @@ -# DRM Media Key System Management (C/C++) - -Using the **MediaKeySystem** class of the DRM module, you can manage **MediaKeySystem** instances, generate media key system requests to obtain DRM certificates, process responses to these requests, manage media key sessions, manage offline media keys, and obtain DRM statistics and device configuration information. Before using DRM Kit, check whether the device supports the DRM capabilities of a specific DRM scheme. In DRM Kit, the DRM scheme exists as a plug-in. - -## How to Develop - -Read [DRM](../../reference/apis-drm-kit/_drm.md) for the API reference. - -1. Import the NDK. - - ```c++ - #include "multimedia/drm_framework/native_drm_common.h" - #include "multimedia/drm_framework/native_drm_err.h" - #include "multimedia/drm_framework/native_mediakeysession.h" - #include "multimedia/drm_framework/native_mediakeysystem.h" - ``` - -2. Link the DRM NDK dynamic library in the CMake script. - - ```txt - target_link_libraries(PUBLIC libnative_drm.so) - ``` - -3. Check whether the device supports the DRM scheme based on the specified name, MIME type, and content protection level. - - ```c++ - bool isSupported = OH_MediaKeySystem_IsSupported3("com.clearplay.drm", "video/avc", CONTENT_PROTECTION_LEVEL_SW_CRYPTO); - if (isSupported != true) { - printf("The device does not support the content protection level."); - } - ``` - -4. (Optional) Obtain the name and ID list of the DRM schemes supported by the device. - - ```c++ - uint32_t count = 1; // count indicates the number of DRM plug-ins supported by the device. Pass in the actual number. - DRM_MediaKeySystemDescription descriptions[1]; - memset(descriptions, 0, sizeof(descriptions)); - Drm_ErrCode ret = OH_MediaKeySystem_GetMediaKeySystems(descriptions, &count); - if (ret != DRM_ERR_OK) { - printf("OH_MediaKeySystem_GetMediaKeySystems failed."); - } - ``` - -5. Create a **MediaKeySystem** instance. - - ```c++ - MediaKeySystem *mediaKeySystem = NULL; - Drm_ErrCode ret = OH_MediaKeySystem_Create("com.clearplay.drm", &mediaKeySystem); - if (ret != DRM_ERR_OK) { - printf("OH_MediaKeySystem_Create failed."); - } - ``` - -6. (Optional) Declare the MediaKeySystem event listener callback. - - ```c++ - // This callback applies to the scenario where there are multiple MediaKeySystem instances. - static Drm_ErrCode SystemCallBack(DRM_EventType eventType, uint8_t *info, int32_t infoLen, char *extra) - { - printf("SystemCallBack"); - } - // This callback applies to the scenario where there is only one MediaKeySystem instance. - static Drm_ErrCode SystemCallBackWithObj(MediaKeySystem *mediaKeySystem, DRM_EventType eventType, - uint8_t *info, int32_t infoLen, char *extra) - { - printf("TestSystemCallBackWithObj"); - } - ``` - -7. (Optional) Set the MediaKeySystem event listener callback. - - ```c++ - // This callback applies to the scenario where there are multiple MediaKeySystem instances. - Drm_ErrCode ret = OH_MediaKeySystem_SetMediaKeySystemCallback(mediaKeySystem, SystemCallBack); - if (ret != DRM_ERR_OK) { - printf("OH_MediaKeySystem_SetMediaKeySystemCallback failed."); - } - - // This callback applies to the scenario where there is only one MediaKeySystem instance. - ret = OH_MediaKeySystem_SetCallback(mediaKeySystem, SystemCallBackWithObj); - if (ret != DRM_ERR_OK) { - printf("OH_MediaKeySystem_SetCallback failed."); - } - ``` - -8. Create a **MediaKeySession** instance. - - ```c++ - MediaKeySession *mediaKeySession = nullptr; - DRM_ContentProtectionLevel contentProtectionLevel = CONTENT_PROTECTION_LEVEL_SW_CRYPTO; - ret = OH_MediaKeySystem_CreateMediaKeySession(mediaKeySystem, &contentProtectionLevel, &mediaKeySession); - if (ret != DRM_ERR_OK || mediaKeySession == nullptr) { - printf("OH_MediaKeySystem_CreateMediaKeySession failed."); - } - ``` - -9. Check the DRM certificate status of the device. If the device does not have a DRM certificate or the DRM certificate status is abnormal, generate a provision request to obtain a DRM certificate and process its response. - - ```c++ - unsigned char request[12288] = { 0x00 }; // The maximum length of a provision request is 12288. Apply for memory based on the actual length. - int32_t requestLen = 12288; - // The maximum length of the DRM service URL is 2048. - char defaultUrl[2048] = { 0x00 }; - int32_t defaultUrlLen = 2048; - DRM_CertificateStatus certStatus = CERT_STATUS_INVALID; - // Check the DRM certificate status of the device. - ret = OH_MediaKeySystem_GetCertificateStatus(mediaKeySystem, &certStatus); - if (ret == DRM_ERR_OK && certStatus == CERT_STATUS_NOT_PROVISIONED) { - ret = OH_MediaKeySystem_GenerateKeySystemRequest(mediaKeySystem, request, &requestLen, defaultUrl, - defaultUrlLen); - /* - The application sends a provision request to the DRM service through a network request, obtains a response, - and sets the response to the device. Pass in the actual value and length. - */ - unsigned char KeySystemResponse[12288] = {0x00}; - ret = OH_MediaKeySystem_ProcessKeySystemResponse(mediaKeySystem, KeySystemResponse, sizeof(KeySystemResponse)); - if (ret != DRM_ERR_OK) { - printf("OH_MediaKeySystem_ProcessKeySystemResponse failed."); - } - } - ``` - -10. (Optional) Obtain the IDs of offline media keys, obtain their status, and clear the keys. - - ```c++ - DRM_OfflineMediakeyIdArray offlineMediaKeyIds; - ret = OH_MediaKeySystem_GetOfflineMediaKeyIds(mediaKeySystem, &offlineMediaKeyIds); - if (ret != DRM_ERR_OK) { - printf("OH_MediaKeySystem_GetOfflineMediaKeyIds failed."); - } - DRM_OfflineMediaKeyStatus OfflineMediaKeyStatus = OFFLINE_MEDIA_KEY_STATUS_UNKNOWN; - ret = OH_MediaKeySystem_GetOfflineMediaKeyStatus(mediaKeySystem, offlineMediaKeyIds.ids[0], offlineMediaKeyIds.idsLen[0], &OfflineMediaKeyStatus); - if (ret != DRM_ERR_OK) { - printf("OH_MediaKeySystem_GetOfflineMediaKeyStatus failed."); - } - ret = OH_MediaKeySystem_ClearOfflineMediaKeys(mediaKeySystem, offlineMediaKeyIds.ids[0], offlineMediaKeyIds.idsLen[0]); - if (ret != DRM_ERR_OK) { - printf("OH_MediaKeySystem_ClearOfflineMediaKeys failed."); - } - ``` - -11. (Optional) Set and obtain the DRM configuration information. - - > **NOTE** - > - > The configuration information may vary according to the DRM scheme. The supported configuration item names are "vendor", "version", "description", "algorithms", "maxSessionNum", and "currentHDCPLevel." The DRM configuration information can be set only when the scheme supports the setting of configuration items. - - ```c++ - ret = OH_MediaKeySystem_SetConfigurationString(mediaKeySystem, "version", "2.0"); // Set the configuration information of the string type. - if (ret == DRM_ERR_OK) { - printf("MediaKeySystem_SetConfigurationString success"); - } else { - printf("MediaKeySystem_SetConfigurationString failed. %d ", ret); - } - char value[32]; - int32_t valueLen = 32; - // Obtain the value of a configuration item in the form of a string. - ret = OH_MediaKeySystem_GetConfigurationString(mediaKeySystem, "version", value, valueLen); - if (ret == DRM_ERR_OK) { - printf("OH_MediaKeySystem_GetConfigurationString success"); - } else { - printf("OH_MediaKeySystem_GetConfigurationString failed. %d ", ret); - } - // Set the configuration information of the character array type based on the actual data and length. - uint8_t description[4] = {0x00, 0x00, 0x00, 0x00}; - ret = OH_MediaKeySystem_SetConfigurationByteArray(mediaKeySystem, "description", description, sizeof(description)/sizeof(uint8_t)); - if (ret == DRM_ERR_OK) { - printf("OH_MediaKeySystem_SetConfigurationByteArray success "); - } else { - printf("OH_MediaKeySystem_SetConfigurationByteArray failed. %d ", ret); - } - // Obtain the configuration information of the character array type. Pass in the actual data. - uint8_t descriptionValue[32]; - int32_t descriptionValueLen = 32; - ret = OH_MediaKeySystem_GetConfigurationByteArray(mediaKeySystem, "description", descriptionValue, &descriptionValueLen); - if (ret == DRM_ERR_OK) { - printf("OH_MediaKeySystem_GetConfigurationByteArray success "); - } else { - printf("OH_MediaKeySystem_GetConfigurationByteArray failed. %d ", ret); - } - ``` - -12. (Optional) Obtain the maximum content protection level supported by the device. - - ```c++ - DRM_ContentProtectionLevel contentProtectionLevel = CONTENT_PROTECTION_LEVEL_UNKNOWN; - ret = OH_MediaKeySystem_GetMaxContentProtectionLevel(mediaKeySystem, &contentProtectionLevel); - if (ret != DRM_ERR_OK) { - printf("OH_MediaKeySystem_GetMaxContentProtectionLevel failed."); - } - ``` - -13. Destroy the **MediaKeySession** instance. - - ```c++ - ret = OH_MediaKeySession_Destroy(mediaKeySession); - if (ret != DRM_ERR_OK) { - printf("OH_MediaKeySession_Destroy failed."); - } - ``` - -14. Destroy the **MediaKeySystem** instance. - - ```c++ - ret = OH_MediaKeySystem_Destroy(mediaKeySystem); - if (ret != DRM_ERR_OK) { - printf("OH_MediaKeySystem_Destroy failed."); - } - ``` \ No newline at end of file diff --git a/en/application-dev/media/image/Readme-EN.md b/en/application-dev/media/image/Readme-EN.md index 0606baa970cd343266627b32c5e9c4d32a7950be..3c829abf0441bdcdfc9e0619e6f787aa624ccc1c 100644 --- a/en/application-dev/media/image/Readme-EN.md +++ b/en/application-dev/media/image/Readme-EN.md @@ -1,7 +1,7 @@ # Image Kit - [Introduction to Image Kit](image-overview.md) -- Image Development (ArkTS) +- Image Development (ArkTS) - [Using ImageSource to Decode Images](image-decoding.md) - [Using ImageSource to Decode Pictures](image-picture-decoding.md) - [Using PixelMap to Transform Images](image-transformation.md) @@ -9,7 +9,8 @@ - [Using ImagePacker to Encode Images](image-encoding.md) - [Using ImagePacker to Encode Pictures](image-picture-encoding.md) - [Editing EXIF Data](image-tool.md) -- Image Development (C/C++) + - [Allocating Memory for Image Decoding](image-allocator-type.md) +- Image Development (C/C++) - [Introduction to the Image_NativeModule Structs](image-structure-c.md) - [Using Image_NativeModule to Decode Images](image-source-c.md) - [Using Image_NativeModule to Decode Pictures](image-source-picture-c.md) @@ -19,7 +20,8 @@ - [Using Image_NativeModule to Encode Images](image-packer-c.md) - [Using Image_NativeModule to Encode Pictures](image-packer-picture-c.md) - [Using ImageEffect to Edit Images](image-effect-guidelines.md) -- Image Development (Dependent on JS Objects) (C/C++) + - [Allocating Memory for Image Decoding](image-allocator-type-c.md) +- Image Development (Dependent on JS Objects) (C/C++) - [Using Image to Decode Images](image-decoding-native.md) - [Using Image to Receive Images](image-receiver-native.md) - [Using Image to Transform Images](image-transformation-native.md) diff --git a/en/application-dev/media/image/image-allocator-type-c.md b/en/application-dev/media/image/image-allocator-type-c.md new file mode 100644 index 0000000000000000000000000000000000000000..e835daaa7acc76b7952eac6a4e155eb7d021ab72 --- /dev/null +++ b/en/application-dev/media/image/image-allocator-type-c.md @@ -0,0 +1,160 @@ +# Allocating Memory for Image Decoding (C/C++) + +When an application performs image decoding, it needs to allocate the corresponding memory. This guide describes different types of memory and how to allocate them. + +The application obtains a PixelMap through the decoding API and passes it to the **Image** component for display. + +When the PixelMap is large and uses regular memory, the RenderService main thread will experience a longer texture upload time, leading to lag. The zero-copy feature of DMA memory provided by the graphics side can avoid the time cost of texture upload when the system renders images of the same size. + +## Memory Types + +The memory types for the PixelMap are as follows: + +- DMA_ALLOC: ION memory. IPC latency is relatively low, and texture upload is not required. +- SHARE_MEMORY: shared memory. IPC latency is minimal, but texture upload is required. + +Given that the current memory allocation strategy of the decoding API cannot meet the requirements in certain scenarios, the system provides [OH_ImageSourceNative_CreatePixelmapUsingAllocator](../../reference/apis-image-kit/_image___native_module.md#oh_imagesourcenative_createpixelmapusingallocator), allowing you to customize the memory allocation type for decoding. + +### Differences Between DMA_ALLOC and SHARE_MEMORY + +| Item | DMA_ALLOC | SHARE_MEMORY | +| ------------------ | ----------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| Definition | The hardware decoder directly transfers decoded image data to memory or video memory without CPU intervention. | The memory sharing mechanism provided by the operating system allows multiple threads and processes to directly access the same physical memory for collaborative image data processing.| +| Working principle | The decoder uses the DMA controller to directly transfer the decoded image data from the device to memory or display buffer.| Image data decoded by the GPU is directly mapped into shared memory for collaborative processing or access by multiple threads or processes. | +| Use case | Used for high-speed data transfer. | Used for data sharing between processes or threads. | +| CPU usage | Extremely low CPU usage: The CPU is only involved in the configuration of the DMA controller, with no intervention in actual data transfer. | The CPU is involved in managing and synchronizing shared memory (for example, locking and unlocking), which incurs additional overhead. | +| Hardware dependency | Strongly dependent on the hardware DMA controller. | Dependent on the shared memory mechanism of the operating system. | +| Memory allocation and access permissions| The DMA controller directly operates the physical memory, requiring pre-allocated DMA buffers (usually contiguous memory). | The system allocates physical or virtual memory areas for shared memory, with access requiring user or kernel mapping operations. | +| Advantages | High efficiency and low latency, suitable for transfer of large data volumes and continuous data blocks. | High flexibility. Supports simultaneous data sharing by multiple threads or processes, facilitating image post-processing and collaboration. | +| Disadvantages | Hardware support is required, and the data transfer range is limited by DMA address space (usually requiring contiguous physical memory). | Shared memory operations require additional synchronization mechanisms, increasing programming complexity and CPU load. | +| Use in the decoding workflow| The hardware decoder directly outputs data to the target memory through DMA without CPU intervention. | After the decoding is complete, the data is stored in the shared memory for other processes or threads to read and process. | + +### Advantages of Using DMA_ALLOC Memory + +- **Reduced texture upload time** + + When SHARE_MEMORY is used, image data needs to be copied to GPU memory through the CPU, increasing the texture upload time. With DMA_ALLOC, data is directly stored in memory that is accessible by the GPU, avoiding the time-consuming copy process. + + - Traditional upload time: For a 4K image, a single frame rendering takes about 20 ms. + - DMA_ALLOC upload time: For a 4K image, the time for a single frame rendering can be reduced to about 4 ms. This optimization is particularly significant in scenarios involving the display of large images and frequent dynamic image loading. +- **Reduced CPU load** + + DMA_ALLOC allows the GPU to directly access decoded data, reducing the load caused by memory copying. + +## Default Memory Allocation Method + +When [OH_ImageSourceNative_CreatePixelmap](../../reference/apis-image-kit/_image___native_module.md#oh_imagesourcenative_createpixelmap) is called for decoding, different memory allocation types are used in different scenarios. + +DMA_ALLOC is used in the following scenarios: + +- Decoding HDR images. +- Decoding HEIF images. +- Decoding JPEG images, when the original image's width and height are both between 1024 and 8192, [desiredPixelFormat](../../reference/apis-image-kit/_image___native_module.md#oh_decodingoptions) is RGBA_8888 or NV21, and the hardware is not busy (concurrency is 3). +- Decoding images in other formats. The value of [desiredSize](../../reference/apis-image-kit/_image___native_module.md#oh_decodingoptions) must be greater than or equal to 512 * 512 (consider the original image size if **desiredSize** is not set), and the width must be a multiple of 64. + +In all other cases, SHARE_MEMORY is used. + +## Custom Memory Allocation Method + +By default, the system selects the optimal memory allocation method for performance. In specific scenarios, applications can use a specified memory allocation method. + +When you call [OH_ImageSourceNative_CreatePixelmapUsingAllocator](../../reference/apis-image-kit/_image___native_module.md#oh_imagesourcenative_createpixelmapusingallocator) for decoding, the system automatically selects hardware or software decoding based on the [decoding options](../../reference/apis-image-kit/_image___native_module.md#oh_decodingoptions) and [memory application type](../../reference/apis-image-kit/_image___native_module.md#image_allocator_type). + +When creating a PixelMap, the system determines whether to use DMA_ALLOC or SHARE_MEMORY based on the user-specified allocator type. + +### Restrictions + +The current image decoding feature has the following restrictions on memory allocation modes: + +- HDR image decoding supports only DMA_ALLOC. +- Hardware decoding supports only DMA_ALLOC. +- SVG image decoding supports only SHARE_MEMORY. + +When [OH_ImageSourceNative_CreatePixelmapUsingAllocator](../../reference/apis-image-kit/_image___native_module.md#oh_imagesourcenative_createpixelmapusingallocator) is used for decoding, if the specified memory allocation mode does not match the image format or decoding method, an exception indicating a memory allocation failure is thrown. + +If the allocation type is set to AUTO, the system determines whether to use DMA_ALLOC or SHARE_MEMORY based on the decoding and rendering time. + +Different memory allocation strategies can result in differences in the stride of the image. For memory allocated by using DMA_ALLOC, the stride must be used for operations such as editing on the PixelMap. The following describes how to obtain the stride. + +### Obtaining the Stride + +The stride describes the storage width of each row of pixel data of an image in memory. It is an important parameter in the image drawing process and is used to correctly locate the layout of the image data in the memory. + +When memory is allocated using DMA_ALLOC, the stride must meet the hardware alignment requirements. + +- The stride value must be an integer multiple of the number of bytes required by the hardware platform. +- If the stride calculated using the above formula does not meet the alignment requirements, the system automatically pads the data. + The stride value can be obtained by calling [OH_PixelmapNative_GetImageInfo](../../reference/apis-image-kit/_image___native_module.md#oh_pixelmapnative_getimageinfo). + +1. Call [OH_PixelmapNative_GetImageInfo](../../reference/apis-image-kit/_image___native_module.md#oh_pixelmapnative_getimageinfo) to obtain an **OH_Pixelmap_ImageInfo** object. +2. Call [OH_PixelmapImageInfo_GetRowStride](../../reference/apis-image-kit/_image___native_module.md#oh_pixelmapimageinfo_getrowstride) to obtain the stride value. + +The sample code for obtaining and operating the stride by the C APIs is as follows: + +```C++ +struct PixelmapInfo { + uint32_t width = 0; + uint32_t height = 0; + uint32_t rowStride = 0; + int32_t pixelFormat = 0; + uint32_t byteCount = 0; + uint32_t allocationByteCount = 0; +}; + +static void GetPixelmapInfo(OH_PixelmapNative *pixelmap, PixelmapInfo *info) { + OH_Pixelmap_ImageInfo *srcInfo = nullptr; + OH_PixelmapImageInfo_Create(&srcInfo); + OH_PixelmapNative_GetImageInfo(pixelmap, srcInfo); + OH_PixelmapImageInfo_GetWidth(srcInfo, &info->width); + OH_PixelmapImageInfo_GetHeight(srcInfo, &info->height); + OH_PixelmapImageInfo_GetRowStride(srcInfo, &info->rowStride); + OH_PixelmapImageInfo_GetPixelFormat(srcInfo, &info->pixelFormat); + OH_PixelmapImageInfo_Release(srcInfo); + return; +} + +static void GetPixelmapAddrInfo(OH_PixelmapNative *pixelmap, PixelmapInfo *info) { + OH_PixelmapNative_GetByteCount(pixelmap, &info->byteCount); + OH_PixelmapNative_GetAllocationByteCount(pixelmap, &info->allocationByteCount); + return; +} + +OH_PixelmapNative* TestStrideWithAllocatorType() { + size_t filePathSize = 1024; + OH_ImageSourceNative* imageSource = nullptr; + Image_ErrorCode image_ErrorCode = OH_ImageSourceNative_CreateFromUri("/data/storage/el2/base/haps/entry/files/test.jpg", filePathSize, &imageSource); + OH_DecodingOptions *options = nullptr; + OH_DecodingOptions_Create(&options); + IMAGE_ALLOCATOR_TYPE allocatorType = IMAGE_ALLOCATOR_TYPE::IMAGE_ALLOCATOR_TYPE_DMA; // Use DMA to create a PixelMap. + OH_PixelmapNative *pixelmap = nullptr; + image_ErrorCode = OH_ImageSourceNative_CreatePixelmapUsingAllocator(imageSource, options, allocatorType, &pixelmap); + PixelmapInfo srcInfo; + GetPixelmapInfo(pixelmap, &srcInfo); + GetPixelmapAddrInfo(pixelmap, &srcInfo); + + void *pixels = nullptr; + OH_PixelmapNative_AccessPixels(pixelmap, &pixels); + OH_PixelmapNative *newPixelmap = nullptr; + uint32_t dstRowStride = srcInfo.width * GetPixelFormatBytes(srcInfo.pixelFormat); + void *newPixels = nullptr; + OH_PixelmapNative_AccessPixels(newPixelmap, &newPixels); + OH_PixelmapNative_UnaccessPixels(newPixelmap); + uint8_t *src = reinterpret_cast(pixels); + uint8_t *dst = reinterpret_cast(newPixels); + uint32_t dstSize = srcInfo.byteCount; + uint32_t rowSize; + if (allocatorType == IMAGE_ALLOCATOR_TYPE::IMAGE_ALLOCATOR_TYPE_DMA) { + rowSize = srcInfo.rowStride; + } else { + rowSize = dstRowStride; + } + for (uint32_t i = 0; i < srcInfo.height; ++i) { + memcpy(dst, src, dstRowStride); + src += rowSize; + dst += dstRowStride; + dstSize -= dstRowStride; + } + OH_PixelmapNative_UnaccessPixels(pixelmap); + return newPixelmap; +} +``` diff --git a/en/application-dev/media/image/image-allocator-type.md b/en/application-dev/media/image/image-allocator-type.md new file mode 100644 index 0000000000000000000000000000000000000000..024e3f4b3914cba90cbca619f6b27510a00e1d77 --- /dev/null +++ b/en/application-dev/media/image/image-allocator-type.md @@ -0,0 +1,113 @@ +# Allocating Memory for Image Decoding (ArkTS) + +When an application performs image decoding, it needs to allocate the corresponding memory. This guide describes different types of memory and how to allocate them. + +The application obtains a PixelMap through the decoding API and passes it to the **Image** component for display. + +When the PixelMap is large and uses regular memory, the RenderService main thread will experience a longer texture upload time, leading to lag. The zero-copy feature of DMA memory provided by the graphics side can avoid the time cost of texture upload when the system renders images of the same size. + +## Memory Types + +The memory types for the PixelMap are as follows: +- DMA_ALLOC: ION memory. IPC latency is relatively low, and texture upload is not required. +- SHARE_MEMORY: shared memory. IPC latency is minimal, but texture upload is required. + +Given that the current memory allocation strategy of the decoding API cannot meet the requirements in certain scenarios, the system provides [createPixelMapUsingAllocator](../../reference/apis-image-kit/js-apis-image.md#createpixelmapusingallocator15), allowing you to customize the memory allocation type for decoding. For details about the API definition and usage example, see [Image Decoding API](../../reference/apis-image-kit/js-apis-image.md#imagesource). + +### Differences Between DMA_ALLOC and SHARE_MEMORY + +| Item | DMA_ALLOC | SHARE_MEMORY | +| ------------------ | --------------------- | ----------------------------------------- | +| Definition | The hardware decoder directly transfers decoded image data to memory or video memory without CPU intervention. | The memory sharing mechanism provided by the operating system allows multiple threads and processes to directly access the same physical memory for collaborative image data processing.| +| Working principle | The decoder uses the DMA controller to directly transfer the decoded image data from the device to memory or display buffer.| Image data decoded by the GPU is directly mapped into shared memory for collaborative processing or access by multiple threads or processes. | +| Use case | Used for high-speed data transfer. | Used for data sharing between processes or threads. | +| CPU usage | Extremely low CPU usage: The CPU is only involved in the configuration of the DMA controller, with no intervention in actual data transfer. | The CPU is involved in managing and synchronizing shared memory (for example, locking and unlocking), which incurs additional overhead. | +| Hardware dependency | Strongly dependent on the hardware DMA controller. | Dependent on the shared memory mechanism of the operating system. | +| Memory allocation and access permissions| The DMA controller directly operates the physical memory, requiring pre-allocated DMA buffers (usually contiguous memory). | The system allocates physical or virtual memory areas for shared memory, with access requiring user or kernel mapping operations. | +| Advantages | High efficiency and low latency, suitable for transfer of large data volumes and continuous data blocks. | High flexibility. Supports simultaneous data sharing by multiple threads or processes, facilitating image post-processing and collaboration. | +| Disadvantages | Hardware support is required, and the data transfer range is limited by DMA address space (usually requiring contiguous physical memory). | Shared memory operations require additional synchronization mechanisms, increasing programming complexity and CPU load. | +| Use in the decoding workflow| The hardware decoder directly outputs data to the target memory through DMA without CPU intervention. | After the decoding is complete, the data is stored in the shared memory for other processes or threads to read and process. | + +### Advantages of Using DMA_ALLOC Memory + +- **Reduced texture upload time** + + When SHARE_MEMORY is used, image data needs to be copied to GPU memory through the CPU, increasing the texture upload time. With DMA_ALLOC, data is directly stored in memory that is accessible by the GPU, avoiding the time-consuming copy process. + - Traditional upload time: For a 4K image, a single frame rendering takes about 20 ms. + - DMA_ALLOC upload time: For a 4K image, the time for a single frame rendering can be reduced to about 4 ms. This optimization is particularly significant in scenarios involving the display of large images and frequent dynamic image loading. + +- **Reduced CPU load** + + DMA_ALLOC allows the GPU to directly access decoded data, reducing the load caused by memory copying. + +## Default Memory Allocation Method + +When [createPixelMap](../../reference/apis-image-kit/js-apis-image.md#createpixelmap7) is called for decoding, different memory allocation types are used in different scenarios. + +DMA_ALLOC is used in the following scenarios: + +- Decoding HDR images. +- Decoding HEIF images. +- Decoding JPEG images, when the original image's width and height are both between 1024 and 8192, [desiredPixelFormat](../../reference/apis-image-kit/js-apis-image.md#decodingoptions7) is RGBA_8888 or NV21, and the hardware is not busy (concurrency is 3). +- Decoding images in other formats. The value of [desiredSize](../../reference/apis-image-kit/js-apis-image.md#decodingoptions7) must be greater than or equal to 512 * 512 (consider the original image size if **desiredSize** is not set), and the width must be a multiple of 64. + +In all other cases, SHARE_MEMORY is used. + +## Custom Memory Allocation Method + +By default, the system selects the optimal memory allocation method for performance. In specific scenarios, applications can use a specified memory allocation method. + +When you call [createPixelMapUsingAllocator](../../reference/apis-image-kit/js-apis-image.md#createpixelmapusingallocator15) for decoding, the system automatically selects hardware or software decoding based on the [decoding options](../../reference/apis-image-kit/js-apis-image.md#decodingoptions7) and [memory application type](../../reference/apis-image-kit/js-apis-image.md#allocatortype15). + +When creating a PixelMap, the system determines whether to use DMA_ALLOC or SHARE_MEMORY based on the user-specified allocator type. + +### Restrictions + +The current image decoding feature has the following restrictions on memory allocation modes: + +- HDR image decoding supports only DMA_ALLOC. +- Hardware decoding supports only DMA_ALLOC. +- SVG image decoding supports only SHARE_MEMORY. + +When [createPixelMapUsingAllocator](../../reference/apis-image-kit/js-apis-image.md#createpixelmapusingallocator15) is used for decoding, if the specified memory allocation mode does not match the image format or decoding method, an exception indicating a memory allocation failure is thrown. + +If the allocation type is set to AUTO, the system determines whether to use DMA_ALLOC or SHARE_MEMORY based on the decoding and rendering time. + +Different memory allocation strategies can result in differences in the stride of the image. For memory allocated by using DMA_ALLOC, the stride must be used for operations such as editing on the PixelMap. The following describes how to obtain the stride. + +### Obtaining the Stride + +The stride describes the storage width of each row of pixel data of an image in memory. It is an important parameter in the image drawing process and is used to correctly locate the layout of the image data in the memory. + +When memory is allocated using DMA_ALLOC, the stride must meet the hardware alignment requirements. + +- The stride value must be an integer multiple of the number of bytes required by the hardware platform. +- If the stride calculated using the above formula does not meet the alignment requirements, the system automatically pads the data. +The stride value can be obtained by calling [PixelMap::GetImageInfo()](../../reference/apis-image-kit/js-apis-image.md#getimageinfo-1). + +1. Call [GetImageInfo()](../../reference/apis-image-kit/js-apis-image.md#getimageinfo-1) to obtain an **ImageInfo** object. +2. Access the stride value (**info.stride**) from the **ImageInfo** object. + +```ts +import image from '@ohos.multimedia.image'; + +async CreatePixelMapUsingAllocator() { + const context = getContext(); + const resourceMgr = context.resourceManager; + const rawFile = await resourceMgr.getRawFileContent("test.jpg"); // Test image. + let imageSource: image.ImageSource | null = await image.createImageSource(rawFile.buffer as ArrayBuffer); + let options: image.DecodingOptions = {}; + let pixelmap = await imageSource.createPixelMapUsingAllocator(options, image.AllocatorType.AUTO); + let info = await pixelmap.getImageInfo(); + // The stride of the PixelMap allocated by using DMA_ALLOC is different from that of the PixelMap allocated by using SHARE_MEMORY. + console.log("stride = " + info.stride); + let region: image.Region = { x: 0, y: 0, size: {height: 100, width:35} }; + if (pixelmap != undefined) { + await pixelmap.crop(region); + let imageInfo = await pixelmap.getImageInfo(); + if (imageInfo != undefined) { + console.info("stride =", imageInfo.stride); + } + } +} +``` diff --git a/en/application-dev/media/image/image-decoding.md b/en/application-dev/media/image/image-decoding.md index f091087bacfb80df951b8577937a0f69a458e64e..fc96bde1f642b076dd86c8353fe4b0d3223761d8 100644 --- a/en/application-dev/media/image/image-decoding.md +++ b/en/application-dev/media/image/image-decoding.md @@ -152,10 +152,12 @@ Read [Image](../../reference/apis-image-kit/js-apis-image.md#imagesource) for AP ``` After the decoding is complete and the PixelMap is obtained, you can perform subsequent [image processing](image-transformation.md). -5. Release the **PixelMap** instance. +5. Release the **PixelMap** and **ImageSource** instances. + Ensure that the asynchronous operations of the **PixelMap** and **ImageSource** instances have finished executing. After these variables are no longer needed, you can manually call the APIs below to release them. ```ts pixelMap.release(); + imageSource.release(); ``` ## Sample Code - Decoding an Image in Resource Files diff --git a/en/application-dev/media/image/image-effect-guidelines.md b/en/application-dev/media/image/image-effect-guidelines.md index fb856c0a5dd19b740631ff6b139a416c85a58060..a7046e392d0d2a464a20ab35316822116af0240d 100644 --- a/en/application-dev/media/image/image-effect-guidelines.md +++ b/en/application-dev/media/image/image-effect-guidelines.md @@ -119,7 +119,7 @@ Add the following dynamic link libraries based on the image type: **libpixelmap. libraryname: 'entry' }) .onLoad(() => { - // Obtain the surface ID of the . + // Obtain the surface ID of the XComponent. this.mSurfaceId = this.mXComponentController.getXComponentSurfaceId() // Obtain the input surface ID. @@ -232,7 +232,7 @@ To implement and register a custom filter, perform the following steps: root["name"] = "CustomBrightness"; root["values"] = values; -    // Convert the JSON object into a string. +    // Convert the JSON object into the string infoStr. // ... // Assign a serialized string address to *info. diff --git a/en/application-dev/media/image/image-encoding-native.md b/en/application-dev/media/image/image-encoding-native.md index 8df33f782d06b608b26d55c422058b4963998ea8..a10ace3cc53afd6e638847b9b9ef8053b1162555 100644 --- a/en/application-dev/media/image/image-encoding-native.md +++ b/en/application-dev/media/image/image-encoding-native.md @@ -79,7 +79,7 @@ target_link_libraries(sample PUBLIC libimage_packer_ndk.z.so) Example: output data to the buffer (memory) ```cpp - // Encoding parameters + // Encoding parameters. struct ImagePacker_Opts_ opts; // (Mandatory) Configure the encoding format. opts.format = "image/jpeg"; @@ -96,7 +96,7 @@ target_link_libraries(sample PUBLIC libimage_packer_ndk.z.so) Example: output data to a file ```cpp - // Encoding parameters + // Encoding parameters. struct ImagePacker_Opts_ opts; // (Mandatory) Configure the encoding format. opts.format = "image/jpeg"; @@ -107,7 +107,7 @@ target_link_libraries(sample PUBLIC libimage_packer_ndk.z.so) if (fd >= 0) { // Start to encode the input source. If IMAGE_RESULT_SUCCESS is returned, the encoding is successful. int32_t result = OH_ImagePacker_PackToFile(nativePacker, source, &opts, fd); - // Close the file. + // Close the file. close(fd); } ``` @@ -122,7 +122,7 @@ target_link_libraries(sample PUBLIC libimage_packer_ndk.z.so) // Call OH_ImagePacker_Release to destroy the encoder. int32_t ret = OH_ImagePacker_Release(nativePacker); if (result != IMAGE_RESULT_SUCCESS) { - // Exception handling. + // Handle exceptions. } else { nativePacker = NULL; // The encoder cannot be destroyed repeatedly. } diff --git a/en/application-dev/media/image/image-overview.md b/en/application-dev/media/image/image-overview.md index b49c934271f1113e226e254d3a662fd23ac8a05d..2712d5499cc2a0f49bc0ae770608391f1eb35616 100644 --- a/en/application-dev/media/image/image-overview.md +++ b/en/application-dev/media/image/image-overview.md @@ -18,7 +18,7 @@ Before image development, be familiar with the following basic concepts: - Image processing - A series of operations on the PixelMap, such as rotation, scaling, opacity setting, image information obtaining, and pixel data reading and writing. + A series of operations on the PixelMap, such as rotation, scaling, opacity setting, image information obtaining, and pixel data reading and writing. The origin of the coordinate system is at the upper left corner. - Image encoding diff --git a/en/application-dev/media/image/image-picture-decoding.md b/en/application-dev/media/image/image-picture-decoding.md index 5291859b44b8e8de25d6be175736dd7bf9d068fd..b921a19521e02eb5642a1932f493fffebdecd57b 100644 --- a/en/application-dev/media/image/image-picture-decoding.md +++ b/en/application-dev/media/image/image-picture-decoding.md @@ -20,8 +20,7 @@ Read [Image](../../reference/apis-image-kit/js-apis-image.md#imagesource) for AP const filePath : string = context.cacheDir + '/test.jpg'; ``` - - Method 2: Obtain the file descriptor of the image through the sandbox path. For details, see [file.fs API Reference](../../reference/apis-core-file-kit/js-apis-file-fs.md). - To use this method, you must import the \@kit.CoreFileKit module first. + - Method 2: Obtain the file descriptor of the image through the sandbox path. For details, see [file.fs API Reference](../../reference/apis-core-file-kit/js-apis-file-fs.md). To use this method, you must import the \@kit.CoreFileKit module first. ```ts import { fileIo } from '@kit.CoreFileKit'; diff --git a/en/application-dev/media/image/image-receiver-native.md b/en/application-dev/media/image/image-receiver-native.md index 94449109ec60d199915947010057a8e3df22c511..8e6e0ac150142ff2e33125d3b3d3e5bf80cd4e0a 100644 --- a/en/application-dev/media/image/image-receiver-native.md +++ b/en/application-dev/media/image/image-receiver-native.md @@ -77,7 +77,7 @@ To obtain input data of an image from a camera, you must request the **ohos.perm // Create an output object for the preview stream. let previewOutput: camera.PreviewOutput = cameraManager.createPreviewOutput(profileObj,receiverSurfaceId); let cameraInput : camera.CameraInput = cameraManager.createCameraInput(cameraDevices[0]); - // Open a camera. + // Open the camera. await cameraInput.open(); // Create a session. let session : camera.PhotoSession = cameraManager.createSession(camera.SceneMode.NORMAL_PHOTO) as camera.PhotoSession; diff --git a/en/application-dev/media/media/Readme-EN.md b/en/application-dev/media/media/Readme-EN.md index 9bd9675f84ec751f6f66dbf48a9a63be5125b7de..62e1571b7afe6745f21c99c838d56e8e93d2720a 100644 --- a/en/application-dev/media/media/Readme-EN.md +++ b/en/application-dev/media/media/Readme-EN.md @@ -6,7 +6,7 @@ - Playback - [Using AVPlayer to Play Audio (ArkTS)](using-avplayer-for-playback.md) - [Using AVPlayer to Play Videos (ArkTS)](video-playback.md) - - [Using AVPlayer to Set Playback URLs](playback-url-setting-method.md) + - [Using AVPlayer to Set Playback URLs (ArkTS)](playback-url-setting-method.md) - [Using AVPlayer to Play Streaming Media (ArkTS)](streaming-media-playback-development-guide.md) - [Using AVPlayer to Add External Subtitles to Videos (ArkTS)](video-subtitle.md) - [Using SoundPool to Play Short Sounds (ArkTS)](using-soundpool-for-playback.md) @@ -22,7 +22,12 @@ - Media Development (C/C++) - Playback - [Using AVPlayer to Play Audio (C/C++)](using-ndk-avplayer-for-playback.md) - - [Using AVPlayer to Play Video (C/C++)](using-ndk-avplayer-for-video-playback.md) - - Screen Capture + - [Using AVPlayer to Play Videos (C/C++)](using-ndk-avplayer-for-video-playback.md) + - Recording + - [Using AVRecorder to Record Audio (C/C++)](using-ndk-avrecorder-for-audio-recording.md) + - [Using AVRecorder to Record Videos (C/C++)](using-ndk-avrecorder-for-video-recording.md) - [Using AVScreenCapture to Capture Screens and Obtain Streams (C/C++)](using-avscreencapture-for-buffer.md) - [Using AVScreenCapture to Capture Screens and Write Them to Files (C/C++)](using-avscreencapture-for-file.md) + - Media Information Query + - [Using AVMetadataExtractor to Obtain Metadata (C/C++)](using-ndk-avmetadataextractor-for-media.md) + - [Using AVImageGenerator to Obtain Video Frames (C/C++)](using-ndk-avimagegenerator-for-video.md) diff --git a/en/application-dev/media/media/avmetadataextractor.md b/en/application-dev/media/media/avmetadataextractor.md index 939ad5112dead57704c2efa430c9afb4d675a816..172cb380360f78f9ffd40fec97a2bdebab9771fa 100644 --- a/en/application-dev/media/media/avmetadataextractor.md +++ b/en/application-dev/media/media/avmetadataextractor.md @@ -19,7 +19,7 @@ Read [AVMetadataExtractor](../../reference/apis-media-kit/js-apis-media.md#avmet > > - To set **dataSrc**, set **callback** in **dataSrc** to ensure that the corresponding resource can be correctly read when the callback is invoked, and use the application sandbox directory to access the resource. For details, see [Obtaining Application File Paths](../../application-models/application-context-stage.md#obtaining-application-file-paths). For details about the application sandbox and how to push files to the application sandbox directory, see [File Management](../../file-management/app-sandbox-directory.md). > - > - If different AVMetadataExtractor or [AVImageGenerator](../../reference/apis-media-kit/js-apis-media.md#avmetadataextractor11) instances need to operate the same resource, the file descriptor needs to be opened for multiple times. Therefore, do not share a file descriptor. + > - If different AVMetadataExtractor or [AVImageGenerator](../../reference/apis-media-kit/js-apis-media.md#avimagegenerator12) instances need to operate the same resource, the file descriptor needs to be opened for multiple times. Therefore, do not share a file descriptor. 3. Obtain the metadata. Specifically, call **fetchMetadata()** to obtain an **AVMetadata** object, the attributes of which are the metadata of the media asset. diff --git a/en/application-dev/media/media/figures/recording-status-change-ndk.png b/en/application-dev/media/media/figures/recording-status-change-ndk.png new file mode 100644 index 0000000000000000000000000000000000000000..888aaf063c4607e6b3143b9149b0b4543113ee42 Binary files /dev/null and b/en/application-dev/media/media/figures/recording-status-change-ndk.png differ diff --git a/en/application-dev/media/media/media-kit-intro.md b/en/application-dev/media/media/media-kit-intro.md index b8b91d8749eec813df417e4bb64a84667731e8bd..2874c26545c6720ed29fa71409b98cc924164ac9 100644 --- a/en/application-dev/media/media/media-kit-intro.md +++ b/en/application-dev/media/media/media-kit-intro.md @@ -226,6 +226,8 @@ The table below lists the supported audio and video encoding formats. | video/avc | Video encoding format AVC.| | audio/mpeg | Audio encoding format MPEG.| | audio/g711mu | Audio encoding format G.711 μ-law.| +| audio/3gpp | Audio in AMR-NB format.| +| audio/amr-wb | Audio in AMR-WB format.| The table below lists the supported output file formats. @@ -235,6 +237,7 @@ The table below lists the supported output file formats. | m4a | Audio container format M4A.| | mp3 | Audio container format MP3.| | wav | Audio container format WAV.| +| amr | Audio container format AMR.| ## AVScreenCapture @@ -309,24 +312,33 @@ The AVTranscoder provides the following services: The encoding parameters (format and bit rate) and container format of the source video file can be modified. The audio and video encoding and container formats of the source video are compatible with the AVCodec for decoding and demuxing purposes, whereas those of the target video are compatible with the AVCodec for encoding and muxing purposes. + - The following source video formats are supported: - - [Demuxing formats](../avcodec/audio-video-demuxer.md) - - [Audio decoding formats](../avcodec/audio-decoding.md) - - [Video decoding formats](../avcodec/video-decoding.md) + - [Demuxing formats](../avcodec/avcodec-support-formats.md#media-data-demuxing) + - [Audio decoding formats](../avcodec/avcodec-support-formats.md#audio-decoding) + - [Video decoding formats](../avcodec/avcodec-support-formats.md#video-decoding) > **NOTE** > > Currently, H.265 is not supported. + - The following target video formats are supported: - - [Container formats](../avcodec/audio-video-muxer.md) - - [Audio encoding formats](../avcodec/audio-encoding.md) - - [Video encoding formats](../avcodec/video-encoding.md) + - [Container formats](../avcodec/avcodec-support-formats.md#media-data-muxing) + - [Audio encoding formats](../avcodec/avcodec-support-formats.md#audio-encoding) + - [Video encoding formats](../avcodec/avcodec-support-formats.md#video-encoding) > **NOTE** > > Currently, H.265 is not supported. +- The support for tracks is as follows: + - Subtitle tracks are not supported. If subtitle tracks exist, they are discarded. + - If there are multiple video tracks, only one video track is output. + - If there are multiple audio tracks, only one audio track is output. - +> **NOTE** +> +> - The transcoded video output supports only the MP4 container format. +> - The formats of both the source and target videos must be met during transcoding. diff --git a/en/application-dev/media/media/playback-url-setting-method.md b/en/application-dev/media/media/playback-url-setting-method.md index a83676a9a87597dd33dc26fd409a66652b183492..634f1b8a6e654cdfa2dddb4477c0f933e3c8eae7 100644 --- a/en/application-dev/media/media/playback-url-setting-method.md +++ b/en/application-dev/media/media/playback-url-setting-method.md @@ -26,7 +26,7 @@ This guide describes the following scenarios: **Case 3: setting the HTTP request header information for playback** -If the server needs to verify the HTTP request header, you can set the HTTP request header information through [createMediaSourceWithUrl](../../reference/apis-media-kit/js-apis-media.md#createmediasourcewithurl12). +If the server needs to verify the HTTP request header, you can set the HTTP request header information through [createMediaSourceWithUrl](../../reference/apis-media-kit/js-apis-media.md#mediacreatemediasourcewithurl12). ```ts // Create an AVPlayer instance. let avPlayer: media.AVPlayer = await media.createAVPlayer(); diff --git a/en/application-dev/media/media/streaming-media-playback-development-guide.md b/en/application-dev/media/media/streaming-media-playback-development-guide.md index d2673e09b88627d8ada587c25eb65ba20b5efd0e..93b9ed1589e9fb0815cf9f8051a4726ad2c24a12 100644 --- a/en/application-dev/media/media/streaming-media-playback-development-guide.md +++ b/en/application-dev/media/media/streaming-media-playback-development-guide.md @@ -43,13 +43,17 @@ The full streaming media playback process includes creating an AVPlayer instance > - The playback format and protocol must be supported. > -4. Call **prepare()** to switch the AVPlayer to the **prepared** state. In this state, you can obtain the duration of the media asset to play and set the volume. +4. Obtain and set the surface ID of the window to display the video. -5. Call **play()**, **pause()**, **seek()**, and **stop()** to perform audio playback control as required. + The application obtains the surface ID from the **XComponent**. For details about the process, see [XComponent](../../reference/apis-arkui/arkui-ts/ts-basic-components-xcomponent.md). -6. (Optional) Call **reset()** to reset the AVPlayer. The AVPlayer enters the **idle** state again and you can change the media asset URL. +5. Call **prepare()** to switch the AVPlayer to the **prepared** state. In this state, you can obtain the duration of the media asset to play and set the scale type and volume. -7. Call **release()** to switch the AVPlayer to the **released** state. Now your application exits the playback. +6. Call **play()**, **pause()**, **seek()**, and **stop()** to perform video playback control as required. + +7. (Optional) Call **reset()** to reset the AVPlayer. The AVPlayer enters the **idle** state again and you can change the media asset URL. + +8. Call **release()** to switch the AVPlayer to the **released** state. Now your application exits the playback. ## Special Notes @@ -78,7 +82,7 @@ HLS streams currently support playback at multiple bit rates. By default, the AV let avPlayer: media.AVPlayer = await media.createAVPlayer(); // Listen for the available bit rates of the current HLS stream. avPlayer.on('availableBitrates', (bitrates: Array) => { - consle.info('availableBitrates called, and availableBitrates length is: ' + bitrates.length); + console.info('availableBitrates called, and availableBitrates length is: ' + bitrates.length); }) ``` @@ -89,7 +93,7 @@ HLS streams currently support playback at multiple bit rates. By default, the AV let avPlayer: media.AVPlayer = await media.createAVPlayer(); // Check whether the bit rate setting takes effect. avPlayer.on('bitrateDone', (bitrate: number) => { - consle.info('bitrateDone called, and bitrate value is: ' + bitrate); + console.info('bitrateDone called, and bitrate value is: ' + bitrate); }) // Set the playback bit rate. let bitrate: number = 96000; @@ -112,11 +116,11 @@ avPlayer.setMediaSource(mediaSource, playbackStrategy); DASH streaming media generally include multiple audio, video, and subtitle tracks, each with distinct parameters like resolution, bit rate, sampling rate, and encoding format. By default, the AVPlayer automatically select video tracks with different bit rates based on the network status. You can manually select an audio or video track for playback based on service requirements. In this case, the adaptive bit rate switching feature becomes invalid. -1. Set the [trackChange](../../reference/apis-media-kit/js-apis-media.md) event. +1. Set the [trackChange](../../reference/apis-media-kit/js-apis-media.md#ontrackchange12) event. ```ts avPlayer.on('trackChange', (index: number, isSelect: boolean) => { - console.info(`trackChange info, index: ${error}, isSelect: ${isSelect}`); + console.info(`trackChange info, index: ${index}, isSelect: ${isSelect}`); }) ``` @@ -167,11 +171,21 @@ import { BusinessError } from '@kit.BasicServicesKit'; export class AVPlayerDemo { private count: number = 0; + private surfaceID: string = ''; // The surfaceID parameter specifies the window used to display the video. Its value is obtained through XComponent. private isSeek: boolean = true; // Specify whether the seek operation is supported. public audioTrackList: number[] = []; public videoTrackList: number[] = []; + + constructor(surfaceID: string) { + this.surfaceID = surfaceID; + } + // Set AVPlayer callback functions. setAVPlayerCallback(avPlayer: media.AVPlayer) { + // startRenderFrame: callback function invoked when the first frame starts rendering. + avPlayer.on('startRenderFrame', () => { + console.info(`AVPlayer start render frame`); + }); // Callback function for the seek operation. avPlayer.on('seekDone', (seekDoneTime: number) => { console.info(`AVPlayer seek succeeded, seek time is ${seekDoneTime}`); @@ -184,7 +198,7 @@ export class AVPlayerDemo { console.error(`Invoke avPlayer failed, code is ${err.code}, message is ${err.message}`); avPlayer.reset(); // Call reset() to reset the AVPlayer, which enters the idle state. }) - // Callback function for state changes. + // Callback for state changes. avPlayer.on('stateChange', async (state: string, reason: media.StateChangeReason) => { switch (state) { case 'idle': // This state is reported upon a successful callback of reset(). @@ -193,10 +207,7 @@ export class AVPlayerDemo { break; case 'initialized': // This state is reported when the AVPlayer sets the playback source. console.info('AVPlayer state initialized called.'); - this.avPlayer.audioRendererInfo = { - usage: audio.StreamUsage.STREAM_USAGE_MUSIC, - rendererFlags: 0 - } + avPlayer.surfaceId = this.surfaceID; // Set the window to display the video. This setting is not required when a pure audio asset is to be played. avPlayer.prepare(); break; case 'prepared': // This state is reported upon a successful callback of prepare(). @@ -235,7 +246,7 @@ export class AVPlayerDemo { async avPlayerVodDemo() { // Create an AVPlayer instance. let avPlayer: media.AVPlayer = await media.createAVPlayer(); - // Create a callback for state changes. + // Set a callback for state changes. this.setAVPlayerCallback(avPlayer); this.isSeek = true; // The seek operation is supported in VOD scenarios. avPlayer.url = 'http://xxx.xxx.xxx.xxx:xx/xx/index.m3u8'; @@ -245,7 +256,7 @@ export class AVPlayerDemo { async avPlayerLiveDemo() { // Create an AVPlayer instance. let avPlayer: media.AVPlayer = await media.createAVPlayer(); - // Create a callback for state changes. + // Set a callback for state changes. this.setAVPlayerCallback(avPlayer); this.isSeek = false; // The seek operation is not supported in live streaming scenarios. avPlayer.url = 'http://xxx.xxx.xxx.xxx:xx/xx/index.m3u8'; @@ -255,7 +266,7 @@ export class AVPlayerDemo { async avPlayerDashDemo() { // Create an AVPlayer instance. let avPlayer: media.AVPlayer = await media.createAVPlayer(); - // Create a callback for state changes. + // Set a callback for state changes. this.setAVPlayerCallback(avPlayer); // Set the playback strategy. // let mediaSource : media.MediaSource = media.createMediaSourceWithUrl("http://test.cn/dash/aaa.mpd", {"User-Agent" : "User-Agent-Value"}); @@ -290,7 +301,7 @@ export class AVPlayerDemo { async preDownloadDemo() { // Create an AVPlayer instance. let avPlayer: media.AVPlayer = await media.createAVPlayer(); - // Create a callback for state changes. + // Set a callback for state changes. this.setAVPlayerCallback(avPlayer); this.isSeek = true; // The seek operation is supported in VOD scenarios. // Create a mediaSource instance, set the media source, and customize an HTTP request. If necessary, set fields such as User-Agent, Cookie, and Referer in key-value pairs. diff --git a/en/application-dev/media/media/using-avplayer-for-playback.md b/en/application-dev/media/media/using-avplayer-for-playback.md index cba0572a09c0b5d10292b65cd81028cc4221d03e..62f74d3b3f6f67cb07f32b4370d2446ecd84d329 100644 --- a/en/application-dev/media/media/using-avplayer-for-playback.md +++ b/en/application-dev/media/media/using-avplayer-for-playback.md @@ -12,7 +12,7 @@ During application development, you can use the **state** attribute of the AVPla ![Playback status change](figures/playback-status-change.png) -For details about the state, see [AVPlayerState](../../reference/apis-media-kit/js-apis-media.md#avplayerstate9). When the AVPlayer is in the **prepared**, **playing**, **paused**, or **completed** state, the playback engine is working and a large amount of RAM is occupied. If your application does not need to use the AVPlayer, call **reset()** or **release()** to release the instance.. +For details about the state, see [AVPlayerState](../../reference/apis-media-kit/js-apis-media.md#avplayerstate9). When the AVPlayer is in the **prepared**, **playing**, **paused**, or **completed** state, the playback engine is working and a large amount of RAM is occupied. If your application does not need to use the AVPlayer, call **reset()** or **release()** to release the instance. ## Developer's Tips @@ -92,7 +92,7 @@ export class AVPlayerDemo { console.error(`Invoke avPlayer failed, code is ${err.code}, message is ${err.message}`); avPlayer.reset(); // Call reset() to reset the AVPlayer, which enters the idle state. }); - // Callback function for state changes. + // Callback for state changes. avPlayer.on('stateChange', async (state: string, reason: media.StateChangeReason) => { switch (state) { case 'idle': // This state is reported upon a successful callback of reset(). @@ -102,8 +102,8 @@ export class AVPlayerDemo { case 'initialized': // This state is reported when the AVPlayer sets the playback source. console.info('AVPlayer state initialized called.'); avPlayer.audioRendererInfo = { - usage: audio.StreamUsage.STREAM_USAGE_MUSIC, - rendererFlags: 0 + usage: audio.StreamUsage.STREAM_USAGE_MUSIC, // Audio stream usage type: music. Set this parameter based on the service scenario. + rendererFlags: 0 // AudioRenderer flag. }; avPlayer.prepare(); break; @@ -158,7 +158,7 @@ export class AVPlayerDemo { async avPlayerUrlDemo() { // Create an AVPlayer instance. let avPlayer: media.AVPlayer = await media.createAVPlayer(); - // Set a callback function for state changes. + // Set a callback for state changes. this.setAVPlayerCallback(avPlayer); let fdPath = 'fd://'; // Obtain the sandbox address filesDir through UIAbilityContext. The stage model is used as an example. @@ -176,7 +176,7 @@ export class AVPlayerDemo { async avPlayerFdSrcDemo() { // Create an AVPlayer instance. let avPlayer: media.AVPlayer = await media.createAVPlayer(); - // Set a callback function for state changes. + // Set a callback for state changes. this.setAVPlayerCallback(avPlayer); // Call getRawFd of the resourceManager member of UIAbilityContext to obtain the media asset URL. // The return type is {fd,offset,length}, where fd indicates the file descriptor address of the HAP file, offset indicates the media asset offset, and length indicates the duration of the media asset to play. @@ -193,7 +193,7 @@ export class AVPlayerDemo { async avPlayerDataSrcSeekDemo() { // Create an AVPlayer instance. let avPlayer: media.AVPlayer = await media.createAVPlayer(); - // Set a callback function for state changes. + // Set a callback for state changes. this.setAVPlayerCallback(avPlayer); // dataSrc indicates the playback source address. When the seek operation is supported, fileSize indicates the size of the file to be played. The following describes how to assign a value to fileSize. let src: media.AVDataSrcDescriptor = { @@ -228,7 +228,7 @@ export class AVPlayerDemo { async avPlayerDataSrcNoSeekDemo() { // Create an AVPlayer instance. let avPlayer: media.AVPlayer = await media.createAVPlayer(); - // Set a callback function for state changes. + // Set a callback for state changes. this.setAVPlayerCallback(avPlayer); let context = getContext(this) as common.UIAbilityContext; let src: media.AVDataSrcDescriptor = { @@ -259,7 +259,7 @@ export class AVPlayerDemo { async avPlayerLiveDemo() { // Create an AVPlayer instance. let avPlayer: media.AVPlayer = await media.createAVPlayer(); - // Set a callback function for state changes. + // Set a callback for state changes. this.setAVPlayerCallback(avPlayer); this.isSeek = false; // The seek operation is not supported. avPlayer.url = 'http://xxx.xxx.xxx.xxx:xx/xx/index.m3u8'; diff --git a/en/application-dev/media/media/using-avrecorder-for-recording.md b/en/application-dev/media/media/using-avrecorder-for-recording.md index 0cebcab419b9ccd674860535df80fac0b0e4ff6d..c3f7231457f12a7fa8b1af2ae87ae9edf60178a8 100644 --- a/en/application-dev/media/media/using-avrecorder-for-recording.md +++ b/en/application-dev/media/media/using-avrecorder-for-recording.md @@ -2,7 +2,7 @@ In this topic, you will learn how to use the [AVRecorder](media-kit-intro.md#avrecorder) to develop audio recording functionalities including starting, pausing, resuming, and stopping recording. -During application development, you can use the **state** attribute of the AVRecorder to obtain the AVRecorder state or call **on('stateChange')** to listen for state changes. Your code must meet the state machine requirements. For example, **pause()** is called only when the AVRecorder is in the **started** state, and **resume()** is called only when it is in the **paused** state. +During application development, you can use the **state** property of the AVRecorder to obtain the AVRecorder state or call **on('stateChange')** to listen for state changes. Your code must meet the state machine requirements. For example, **pause()** is called only when the AVRecorder is in the **started** state, and **resume()** is called only when it is in the **paused** state. **Figure 1** Recording state transition @@ -18,7 +18,7 @@ Before your development, configure the following permissions for your applicatio > **NOTE** > -> When the application needs to clone, back up, or synchronize audio files in users' public directory, request the ohos.permission.READ_AUDIO and ohos.permission.WRITE_AUDIO permissions for reading and writing audio files. For details, see [Requesting Restricted Permissions](../../security/AccessToken/declare-permissions-in-acl.md). +> To clone, back up, or synchronize audio files in users' public directory, request the ohos.permission.READ_AUDIO and ohos.permission.WRITE_AUDIO permissions for reading and writing audio files. For details, see [Requesting Restricted Permissions](../../security/AccessToken/declare-permissions-in-acl.md). ## How to Develop @@ -46,20 +46,20 @@ Read [AVRecorder](../../reference/apis-media-kit/js-apis-media.md#avrecorder9) f 2. Set the events to listen for. | Event Type| Description| | -------- | -------- | - | stateChange | Mandatory; used to listen for changes of the **state** attribute of the AVRecorder.| + | stateChange | Mandatory; used to listen for changes of the **state** property of the AVRecorder.| | error | Mandatory; used to listen for AVRecorder errors.| ```ts import { BusinessError } from '@kit.BasicServicesKit'; // Callback function for state changes. - avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => { + this.avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => { console.log(`current state is ${state}`); // You can add the action to be performed after the state is switched. }) // Callback function for errors. - avRecorder.on('error', (err: BusinessError) => { + this.avRecorder.on('error', (err: BusinessError) => { console.error(`avRecorder failed, code is ${err.code}, message is ${err.message}`); }) ``` @@ -72,12 +72,13 @@ Read [AVRecorder](../../reference/apis-media-kit/js-apis-media.md#avrecorder9) f > - Before parameter configuration, ensure that you have gained the required permissions. For details, see [Requesting Permissions](#requesting-permissions). > > - In pure audio recording scenarios, set only audio-related parameters in **avConfig** of **prepare()**. If video-related parameters are configured, an error will be reported in subsequent steps. If video recording is required, follow the instructions provided in [Video Recording Development](video-recording.md). - > - The [recording formats](media-kit-intro.md#supported-formats) in use must be those supported by the system. - > - The recording output URL (URL in **avConfig** in the sample code) must be in the format of fd://xx (where xx indicates a file descriptor). You must call [ohos.file.fs of Core File Kit](../../reference/apis-core-file-kit/js-apis-file-fs.md) to implement access to the application file. For details, see [Application File Access and Management](../../file-management/app-file-access.md). + > - The [recording specifications](media-kit-intro.md#supported-formats) in use must be those supported. The specific recording parameters must strictly comply with the specified [recording parameter configuration](../../reference/apis-media-kit/js-apis-media.md#avrecorderprofile9). + > - The recording output URL (URL in **avConfig** in the sample code) must be in the format of fd://xx (where xx indicates a file descriptor). You must call [ohos.file.fs of Core File Kit](../../reference/apis-core-file-kit/js-apis-file-fs.md) to implement access to the application file. For details, see [Accessing Application Files](../../file-management/app-file-access.md). ```ts import { media } from '@kit.MediaKit'; import { BusinessError } from '@kit.BasicServicesKit'; + import { fileIo as fs } from '@kit.CoreFileKit'; let avProfile: media.AVRecorderProfile = { audioBitrate: 100000, // Audio bit rate. @@ -87,18 +88,18 @@ Read [AVRecorder](../../reference/apis-media-kit/js-apis-media.md#avrecorder9) f fileFormat: media.ContainerFormatType.CFT_MPEG_4A, // Container format. Currently, MP4, M4A, MP3, and WAV are supported. }; - const context: Context = getContext(this); // Refer to Application File Access and Management. + const context: Context = getContext(this); // Refer to Accessing Application Files. let filePath: string = context.filesDir + '/example.mp3'; - let audioFile: fs.File = fs.openSync(filePath, OpenMode.READ_WRITE | OpenMode.CREATE); - let fileFd = this.audioFile.fd; // Obtain the file FD. + let audioFile: fs.File = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); + let fileFd: number = this.audioFile.fd; // Obtain the file FD. let avConfig: media.AVRecorderConfig = { audioSourceType: media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, // Audio input source. In this example, the microphone is used. profile: avProfile, - url: 'fd://' + fileFd.toString(), // Obtain the file descriptor of the created audio file by referring to the sample code in Application File Access and Management. + url: 'fd://' + fileFd.toString(), // Obtain the file descriptor of the created audio file by referring to the sample code in Accessing Application Files. }; - avRecorder.prepare(avConfig).then(() => { + this.avRecorder.prepare(avConfig).then(() => { console.log('Invoke prepare succeeded.'); }, (err: BusinessError) => { console.error(`Invoke prepare failed, code is ${err.code}, message is ${err.message}`); @@ -154,6 +155,7 @@ Refer to the sample code below to complete the process of starting, pausing, res ```ts import { media } from '@kit.MediaKit'; import { BusinessError } from '@kit.BasicServicesKit'; +import { fileIo as fs } from '@kit.CoreFileKit'; export class AudioRecorderDemo { private avRecorder: media.AVRecorder | undefined = undefined; @@ -167,7 +169,7 @@ export class AudioRecorderDemo { private avConfig: media.AVRecorderConfig = { audioSourceType: media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, // Audio input source. In this example, the microphone is used. profile: this.avProfile, - url: 'fd://35', // Create, read, and write a file by referring to the sample code in Application File Access and Management. + url: 'fd://35', // Create, read, and write a file by referring to the sample code in Accessing Application Files. }; private uriPath: string = ''; private filePath: string = ''; @@ -176,7 +178,7 @@ export class AudioRecorderDemo { async createAndSetFd(): Promise { const context: Context = getContext(this); const path: string = context.filesDir + '/example.mp3'; // File sandbox path. The file name extension must match the container format. - const audioFile: fs.File = fs.openSync(path, OpenMode.READ_WRITE | OpenMode.CREATE); + const audioFile: fs.File = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); this.avConfig.url = 'fd://' + audioFile.fd; // Update the URL. this.filePath = path; } @@ -184,7 +186,7 @@ export class AudioRecorderDemo { // Set AVRecorder callback functions. setAudioRecorderCallback() { if (this.avRecorder != undefined) { - // Callback function for state changes. + // Callback for state changes. this.avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => { console.log(`AudioRecorder current state is ${state}`); }) diff --git a/en/application-dev/media/media/using-avscreencapture-ArkTs.md b/en/application-dev/media/media/using-avscreencapture-ArkTs.md index 8a969fc175c1a170d9f939417003c0ede6a7330e..e20d1f652cbe42d80f5e306d28b7306affc2206c 100644 --- a/en/application-dev/media/media/using-avscreencapture-ArkTs.md +++ b/en/application-dev/media/media/using-avscreencapture-ArkTs.md @@ -19,12 +19,12 @@ If microphone data collection is configured, configure the permission **ohos.per Before your development, configure the following permissions for your application. - To use the microphone, request the ohos.permission.MICROPHONE permission. For details about how to request user authorization, see [Requesting User Authorization](../../security/AccessToken/request-user-authorization.md). -- To read images or videos, you are advised to use the media library [Picker to access them](../medialibrary/photoAccessHelper-photoviewpicker.md). -- To save images or videos, use the [security component to save them](../medialibrary/photoAccessHelper-savebutton.md). +- To read images or videos, preferentially use the media library [Picker for access](../medialibrary/photoAccessHelper-photoviewpicker.md). +- To save images or videos, preferentially use the [security component for storage](../medialibrary/photoAccessHelper-savebutton.md). > **NOTE** > -> When the application needs to clone, back up, or synchronize images and videos in users' public directory, request the ohos.permission.READ_IMAGEVIDEO and ohos.permission.WRITE_IMAGEVIDEO permissions for reading and writing audio files. For details, see [Requesting Restricted Permissions](../../security/AccessToken/declare-permissions-in-acl.md). +> To clone, back up, or synchronize images and videos in users' public directory, request the ohos.permission.READ_IMAGEVIDEO and ohos.permission.WRITE_IMAGEVIDEO permissions for reading and writing audio files. For details, see [Requesting Restricted Permissions](../../security/AccessToken/declare-permissions-in-acl.md). ## How to Develop @@ -101,7 +101,9 @@ After an **AVScreenCaptureRecorder** instance is created, different APIs can be ​After creating the **screenCapture** instance, you can set the parameters required for screen capture. - ​Parameters **videoBitrate**, **audioSampleRate**, **audioChannelCount**, **audioBitrate**, and **preset** are optional, with default values provided in the code snippet below. The audio streams of the microphone and system sound share a set of audio parameters: **audioSampleRate**, **audioChannelCount**, and **audioBitrate**. + ​Parameters **videoBitrate**, **audioSampleRate**, **audioChannelCount**, **audioBitrate**, **preset**, and **displayId** are optional, with default values provided in the code snippet below. The audio streams of the microphone and system sound share a set of audio parameters: **audioSampleRate**, **audioChannelCount**, and **audioBitrate**. + + If **displayId** is set to the extended display ID of a 2-in-1 device, a dialog box for screen capture selection can be opened. Users can select the screen to capture in the dialog box, and the recorded content will match the user's choices. ```javascript captureConfig: media.AVScreenCaptureRecordConfig = { @@ -115,6 +117,7 @@ After an **AVScreenCaptureRecorder** instance is created, different APIs can be audioSampleRate: 48000, audioChannelCount: 2, audioBitrate: 96000, + displayId: 0, preset: media.AVScreenCaptureRecordPreset.SCREEN_RECORD_PRESET_H264_AAC_MP4 }; ``` @@ -174,6 +177,7 @@ export class AVScreenCaptureDemo { audioSampleRate: 48000, audioChannelCount: 2, audioBitrate: 96000, + displayId: 0, preset: media.AVScreenCaptureRecordPreset.SCREEN_RECORD_PRESET_H264_AAC_MP4 }; @@ -181,9 +185,9 @@ export class AVScreenCaptureDemo { public async startRecording() { this.screenCapture = await media.createAVScreenCaptureRecorder(); if (this.screenCapture != undefined) { - // success + // success. } else { - // failed + // failed. return; } this.screenCapture?.on('stateChange', async (infoType: media.AVScreenCaptureStateCode) => { @@ -245,7 +249,7 @@ export class AVScreenCaptureDemo { // Proactively call stopRecording to stop screen capture. public async stopRecording() { if (this.screenCapture == undefined) { - // Error + // Error. return; } await this.screenCapture?.stopRecording(); diff --git a/en/application-dev/media/media/using-avscreencapture-for-buffer.md b/en/application-dev/media/media/using-avscreencapture-for-buffer.md index 9d23903d80b4f1e2d5794eb09f69b68f2f3432ef..de305f69269bed32470190717ce98528bea2ab7f 100644 --- a/en/application-dev/media/media/using-avscreencapture-for-buffer.md +++ b/en/application-dev/media/media/using-avscreencapture-for-buffer.md @@ -86,12 +86,13 @@ target_link_libraries(entry PUBLIC libnative_avscreen_capture.so libnative_buffe OH_AVScreenCapture_SetMicrophoneEnabled(capture, isMic); ``` -6. Set callback functions, which are used to listen for errors that may occur during screen capture and the generation of audio and video stream data. See [Detailed Description](#detailed-description) for more information. +6. Set callback functions, which are used to listen for errors that may occur during screen capture, the generation of audio and video stream data, and the retrieval of the display ID. See [Detailed Description](#detailed-description) for more information. ```c++ OH_AVScreenCapture_SetErrorCallback(capture, OnError, userData); OH_AVScreenCapture_SetStateCallback(capture, OnStateChange, userData); OH_AVScreenCapture_SetDataCallback(capture, OnBufferAvailable, userData); + OH_AVScreenCapture_SetDisplayCallback(capture, OnDisplaySelected, userData); ``` 7. Call **StartScreenCapture()** to start screen capture. @@ -119,13 +120,13 @@ target_link_libraries(entry PUBLIC libnative_avscreen_capture.so libnative_buffe OH_AVScreenCapture_Release(capture); ``` -## Specifications for Selecting the Window to Capture on 2-in-1 Devices -For 2-in-1 devices, a selection page is offered to users for capturing a specific window. To maintain compatibility with the existing interface design, when third-party applications set the screen capture mode to **OH_CAPTURE_SPECIFIED_SCREEN** or **OH_CAPTURE_SPECIFIED_WINDOW**, a picker dialog appears with the designated window ID pre-selected. The content that gets captured ultimately depends on the user's choice within the picker. +## Specifications for Selecting the Window to Capture on PCs or 2-in-1 Devices +For PCs or 2-in-1 devices, a selection page is offered to users for capturing a specific window. To maintain compatibility with the existing interface design, when third-party applications set the screen capture mode to **OH_CAPTURE_SPECIFIED_SCREEN** or **OH_CAPTURE_SPECIFIED_WINDOW**, a picker dialog appears with the designated window ID pre-selected. The content that gets captured ultimately depends on the user's choice within the picker. -It is recommended that the selection page be used in **OH_CAPTURE_SPECIFIED_WINDOW** mode. You need to configure the screen capture height and width based on the 2-in-1 device's resolution and pass the display ID (and a window ID if you want to capture a specific window). +It is recommended that the selection page be used in **OH_CAPTURE_SPECIFIED_WINDOW** mode. You need to configure the screen capture height and width based on the PC's or 2-in-1 device's resolution and pass the display ID (and a window ID if you want to capture a specific window). ```c++ -// Configure the screen capture width and height in config_ based on the 2-in-1 device's resolution. +// Configure the screen capture width and height in config_ based on the PC's or 2-in-1 device's resolution. config_.videoInfo.videoCapInfo.videoFrameWidth = 2880; config_.videoInfo.videoCapInfo.videoFrameHeight = 1920; @@ -143,10 +144,10 @@ The selection page is also compatible with the following screen capture modes: 1. OH_CAPTURE_SPECIFIED_WINDOW mode, with multiple window IDs passed. - The 2-in-1 device does not display a picker dialog box. Instead, it displays a privacy dialog box to ask for user approval. Multiple windows can be captured at the same time. + The PC or 2-in-1 device does not display a picker dialog box. Instead, it displays a privacy dialog box to ask for user approval. Multiple windows can be captured at the same time. ```c++ - // Configure the screen capture width and height in config_ based on the 2-in-1 device's resolution. + // Configure the screen capture width and height in config_ based on the PC's or 2-in-1 device's resolution. config_.videoInfo.videoCapInfo.videoFrameWidth = 2880; config_.videoInfo.videoCapInfo.videoFrameHeight = 1920; @@ -162,10 +163,10 @@ The selection page is also compatible with the following screen capture modes: 2. OH_CAPTURE_SPECIFIED_SCREEN mode. - The 2-in-1 device displays a picker dialog box, with the display (specified by the passed display ID) pre-selected. + The PC or 2-in-1 device displays a picker dialog box, with the display (specified by the passed display ID) pre-selected. ```c++ - // Configure the screen capture width and height in config_ based on the 2-in-1 device's resolution. + // Configure the screen capture width and height in config_ based on the PC's or 2-in-1 device's resolution. config_.videoInfo.videoCapInfo.videoFrameWidth = 2880; config_.videoInfo.videoCapInfo.videoFrameHeight = 1920; @@ -176,10 +177,10 @@ The selection page is also compatible with the following screen capture modes: 3. OH_CAPTURE_HOME_SCREEN mode. - The 2-in-1 device does not display a picker dialog box. Instead, it displays a privacy dialog box to ask for user approval. + The PC or 2-in-1 device does not display a picker dialog box. Instead, it displays a privacy dialog box to ask for user approval. ```c++ - // Configure the screen capture width and height in config_ based on the 2-in-1 device's resolution. + // Configure the screen capture width and height in config_ based on the PC's or 2-in-1 device's resolution. config_.videoInfo.videoCapInfo.videoFrameWidth = 2880; config_.videoInfo.videoCapInfo.videoFrameHeight = 1920; @@ -252,10 +253,21 @@ This section describes how to set screen capture parameters, set callback functi if (stateCode == OH_SCREEN_CAPTURE_STATE_INTERRUPTED_BY_OTHER) { // Process the event indicating that screen capture is interrupted by others. } - ... + if (stateCode == OH_SCREEN_CAPTURE_STATE_MIC_MUTED_BY_USER) { + // Process the event indicating that the user mutes the microphone during during screen capture. + } + if (stateCode == OH_SCREEN_CAPTURE_STATE_MIC_UNMUTED_BY_USER) { + // Process the event indicating that the user unmutes the microphone during screen capture. + } + if (stateCode == OH_SCREEN_CAPTURE_STATE_ENTER_PRIVATE_SCENE) { + // Process the event indicating that the application enter the privacy mode during screen capture. + } if (stateCode == OH_SCREEN_CAPTURE_STATE_EXIT_PRIVATE_SCENE) { // Process the event indicating that the application exits the privacy mode during screen capture. } + if (stateCode == OH_SCREEN_CAPTURE_STATE_STOPPED_BY_USER_SWITCHES) { + // Process the event indicating that screen capture is interrupted by the user. + } (void)userData; } @@ -317,6 +329,13 @@ This section describes how to set screen capture parameters, set callback functi } } } + + // The callback OnDisplaySelected() is invoked to obtain the display ID. + void OnDisplaySelected(struct OH_AVScreenCapture *capture, uint64_t displayId, void *userData) { + (void)capture; + (void)displayId; + (void)userData; + } ``` 3. Stops the screen capture service and releases resources. @@ -364,6 +383,114 @@ Currently, the buffer holds original streams, which can be encoded and saved in #include #include "string" #include "unistd.h" +// OnError(), a callback function invoked when an error occurs. +void OnError(OH_AVScreenCapture *capture, int32_t errorCode, void *userData) { + (void)capture; + (void)errorCode; + (void)userData; +} + +// OnStageChange(), a callback function invoked when the state changes. +void OnStageChange(struct OH_AVScreenCapture *capture, OH_AVScreenCaptureStateCode stateCode, void *userData) { + (void)capture; + if (stateCode == OH_SCREEN_CAPTURE_STATE_STARTED) { + // Process the screen capture start event. + } + if (stateCode == OH_SCREEN_CAPTURE_STATE_CANCELED) { + // Process the screen capture cancellation event. + } + if (stateCode == OH_SCREEN_CAPTURE_STATE_STOPPED_BY_CALL) { + // Process the event indicating that screen capture is interrupted by a call. + } + if (stateCode == OH_SCREEN_CAPTURE_STATE_MIC_UNAVAILABLE) { + // Process the event indicating that the microphone is unavailable during screen capture. + } + if (stateCode == OH_SCREEN_CAPTURE_STATE_INTERRUPTED_BY_OTHER) { + // Process the event indicating that screen capture is interrupted by others. + } + if (stateCode == OH_SCREEN_CAPTURE_STATE_MIC_MUTED_BY_USER) { + // Process the event indicating that the user mutes the microphone during during screen capture. + } + if (stateCode == OH_SCREEN_CAPTURE_STATE_MIC_UNMUTED_BY_USER) { + // Process the event indicating that the user unmutes the microphone during screen capture. + } + if (stateCode == OH_SCREEN_CAPTURE_STATE_ENTER_PRIVATE_SCENE) { + // Process the event indicating that the application enter the privacy mode during screen capture. + } + if (stateCode == OH_SCREEN_CAPTURE_STATE_EXIT_PRIVATE_SCENE) { + // Process the event indicating that the application exits the privacy mode during screen capture. + } + if (stateCode == OH_SCREEN_CAPTURE_STATE_STOPPED_BY_USER_SWITCHES) { + // Process the event indicating that screen capture is interrupted by the user. + } + (void)userData; +} + +// Obtain and process the OnBufferAvailable() callback function of the original audio and video stream data. +void OnBufferAvailable(OH_AVScreenCapture *capture, OH_AVBuffer *buffer, OH_AVScreenCaptureBufferType bufferType, int64_t timestamp, void *userData) { + // Screen capture is in progress. + if (IsCaptureStreamRunning) { + if (bufferType == OH_SCREEN_CAPTURE_BUFFERTYPE_VIDEO) { + // Video buffer. + OH_NativeBuffer *nativeBuffer = OH_AVBuffer_GetNativeBuffer(buffer); + if (nativeBuffer != nullptr && capture != nullptr) { + // Obtain the buffer capacity. + int bufferLen = OH_AVBuffer_GetCapacity(buffer); + + // Obtain the buffer attribute. + OH_AVCodecBufferAttr info; + OH_AVBuffer_GetBufferAttr(buffer, &info); + + // Obtain the native buffer configuration. + OH_NativeBuffer_Config config; + OH_NativeBuffer_GetConfig(nativeBuffer, &config); + + // Obtain the buffer address. + uint8_t *buf = OH_AVBuffer_GetAddr(buffer); + if (buf != nullptr) { + return; + } + // Use the buffer data. + + // The reference count of the native buffer is decremented by 1. When the reference count reaches 0, the buffer is released. + OH_NativeBuffer_Unreference(nativeBuffer); + } + } else if (bufferType == OH_SCREEN_CAPTURE_BUFFERTYPE_AUDIO_INNER) { + // Buffer for internal recording. + // Obtain the buffer attribute. + OH_AVCodecBufferAttr info; + OH_AVBuffer_GetBufferAttr(buffer, &info); + + // Obtain the buffer capacity. + int bufferLen = OH_AVBuffer_GetCapacity(buffer); + + // Obtain the buffer address. + uint8_t *buf = OH_AVBuffer_GetAddr(buffer); + if (buf != nullptr) { + return; + } + // Use the buffer data. + } else if (bufferType == OH_SCREEN_CAPTURE_BUFFERTYPE_AUDIO_MIC) { + // Microphone buffer. + // Obtain the buffer capacity. + int bufferLen = OH_AVBuffer_GetCapacity(buffer); + + // Obtain the buffer address. + uint8_t *buf = OH_AVBuffer_GetAddr(buffer); + if (buf != nullptr) { + return; + } + // Use the buffer data. + } + } +} + +// The callback OnDisplaySelected() is invoked to obtain the display ID. +void OnDisplaySelected(struct OH_AVScreenCapture *capture, uint64_t displayId, void *userData) { + (void)capture; + (void)displayId; + (void)userData; +} struct OH_AVScreenCapture *capture; static napi_value Screencapture(napi_env env, napi_callback_info info) { @@ -391,7 +518,11 @@ static napi_value Screencapture(napi_env env, napi_callback_info info) { OH_AVScreenCapture_SetErrorCallback(capture, OnError, nullptr); OH_AVScreenCapture_SetStateCallback(capture, OnStateChange, nullptr); OH_AVScreenCapture_SetDataCallback(capture, OnBufferAvailable, nullptr); + // (Optional) Set a callback to obtain the display ID. This operation must be performed before screen capture starts. + OH_AVScreenCapture_SetDisplayCallback(capture, OnDisplaySelected, nullptr); + // (Optional) Set the cursor display switch. This operation must be performed before screen capture starts. + OH_AVScreenCapture_ShowCursor(capture, false); // (Optional) Configure screen capture rotation. This API should be called when the device screen rotation is detected. If the device screen does not rotate, the API call is invalid. OH_AVScreenCapture_SetCanvasRotation(capture, true); // Optional. Filter audio. diff --git a/en/application-dev/media/media/using-avscreencapture-for-file.md b/en/application-dev/media/media/using-avscreencapture-for-file.md index 383c711249d758d6d11bdac72dc8d3a5f71ec481..bf3eda3de653fc25529fb67009546b3d0c229061 100644 --- a/en/application-dev/media/media/using-avscreencapture-for-file.md +++ b/en/application-dev/media/media/using-avscreencapture-for-file.md @@ -152,6 +152,13 @@ void OnStateChange(struct OH_AVScreenCapture *capture, OH_AVScreenCaptureStateCo (void)userData; } +// The callback OnDisplaySelected() is invoked to obtain the display ID. +void OnDisplaySelected(struct OH_AVScreenCapture *capture, uint64_t displayId, void *userData) { + (void)capture; + (void)displayId; + (void)userData; +} + static napi_value Screencapture(napi_env env, napi_callback_info info) { OH_AVScreenCaptureConfig config; OH_AudioCaptureInfo micCapInfo = { @@ -215,6 +222,12 @@ static napi_value Screencapture(napi_env env, napi_callback_info info) { // Set a callback to respond to state changes. OH_AVScreenCapture_SetStateCallback(capture, OnStateChange, nullptr); + // (Optional) Set a callback to obtain the display ID. This operation must be performed before screen capture starts. + OH_AVScreenCapture_SetDisplayCallback(capture, OnDisplaySelected, nullptr); + + // (Optional) Set the cursor display switch. This operation must be performed before screen capture starts. + OH_AVScreenCapture_ShowCursor(capture, false); + // Initialize AVScreenCapture. int32_t retInit = OH_AVScreenCapture_Init(capture, config); @@ -230,7 +243,7 @@ static napi_value Screencapture(napi_env env, napi_callback_info info) { // Release the AVScreenCapture instance. int32_t retRelease = OH_AVScreenCapture_Release(capture); - // Return the invoking result. In the example, only a random number is returned. + // Return the call result. In the example, only a random number is returned. napi_value sum; napi_create_double(env, 5, &sum); diff --git a/en/application-dev/media/media/using-avtranscoder-for-transcodering.md b/en/application-dev/media/media/using-avtranscoder-for-transcodering.md index 49443a1fb9032fae19deab8bdcb712eb59848071..b4c843d6e900ac883e9036de138342469083660f 100644 --- a/en/application-dev/media/media/using-avtranscoder-for-transcodering.md +++ b/en/application-dev/media/media/using-avtranscoder-for-transcodering.md @@ -79,6 +79,8 @@ Read [AVTranscoder](../../reference/apis-media-kit/js-apis-media.md#avtranscoder > **NOTE** > > Only transcoding-related parameters are set in the input parameter **avConfig** of the **prepare()** API. + > + > Only the supported [transcoding formats](media-kit-intro.md#avtranscoder) can be used due to the limited demuxing, muxing, encoding, and decoding capabilities. ```ts import { media } from '@kit.MediaKit'; diff --git a/en/application-dev/media/media/using-ndk-avimagegenerator-for-video.md b/en/application-dev/media/media/using-ndk-avimagegenerator-for-video.md new file mode 100644 index 0000000000000000000000000000000000000000..0b4e4a33874d697f0aaca78da73e9a5143397a11 --- /dev/null +++ b/en/application-dev/media/media/using-ndk-avimagegenerator-for-video.md @@ -0,0 +1,202 @@ +# Using AVImageGenerator to Obtain Video Frames (C/C++) + +You can use the AVImageGenerator to obtain the video frame at the specified time from the raw media asset. + +The full process of obtaining the video frame includes creating an AVImageGenerator instance, setting resources, obtaining the video frame, and releasing the instance. + +## How to Develop +Link the dynamic library in the CMake script. +``` +target_link_libraries(entry PUBLIC libavimage_generator.so libace_napi.z.so) +``` + +To use [OH_PixelmapNative_ConvertPixelmapNativeToNapi()](../../reference/apis-image-kit/_image___native_module.md#oh_pixelmapnative_convertpixelmapnativetonapi) to convert a nativePixelMap object into a PixelMapnapi object and use [OH_PixelmapNative_Release()](../../reference/apis-image-kit/_image___native_module.md#oh_pixelmapnative_release) to release the OH_PixelmapNative object, include the following header file: +``` +#include +``` + +In addition, link the following dynamic link library in the CMake script: +``` +target_link_libraries(entry PUBLIC libpixelmap.so libpixelmap_ndk.z.so) +``` + +To use system logging, include the following header file: +``` +#include +``` + +In addition, link the following dynamic link library in the CMake script: +``` +target_link_libraries(entry PUBLIC libhilog_ndk.z.so) +``` + +You can use the APIs related to video frame retrieval by including the header files [avimage_generator.h](../../reference/apis-media-kit/avimage__generator_8h.md), [avimage_generator_base.h](../../reference/apis-media-kit/avimage__generator__base_8h.md), and [native_averrors.h](../../reference/apis-avcodec-kit/native__averrors_8h.md). +Read [AVImageGenerator](../../reference/apis-media-kit/_a_v_image_generator.md) for the API reference. + +1. Call [OH_AVImageGenerator_Create()](../../reference/apis-media-kit/_a_v_image_generator.md#oh_avimagegenerator_create) to create an instance. + +2. Call [OH_AVImageGenerator_SetFDSource()](../../reference/apis-media-kit/_a_v_image_generator.md#oh_avimagegenerator_setfdsource) to set the file descriptor of a video resource. + +3. Call [OH_AVImageGenerator_FetchFrameByTime()](../../reference/apis-media-kit/_a_v_image_generator.md#oh_avimagegenerator_fetchframebytime) to obtain the video frame at a specified time, which is an **OH_PixelmapNative** object. + +> When the object is no longer required, call **OH_PixelmapNative_Release** to release the object. For details, see [Image_NativeModule](../../reference/apis-image-kit/_image___native_module.md). + +4. Call [OH_AVImageGenerator_Release()](../../reference/apis-media-kit/_a_v_image_generator.md#oh_avimagegenerator_release) to destroy the instance and release resources. + +## Sample Code + +Refer to the sample code below to set the file descriptor and obtain the video frame of a video at the specified time. + +```c +#include "napi/native_api.h" + +#include +#include +#include +#include + +#include + +#define LOG_PRINT_DOMAIN 0xFF00 +#define APP_LOG_DOMAIN 0x0001 +constexpr const char *APP_LOG_TAG = "AVImageGenerator"; +#define H_LOGI(...) ((void)OH_LOG_Print(LOG_APP, LOG_INFO, LOG_DOMAIN, APP_LOG_TAG, __VA_ARGS__)) + +// Auxiliary function: Check the number and type of parameters. +bool CheckArgs(napi_env env, napi_callback_info info, size_t expectedArgc) { + size_t argc; + napi_value thisArg; + void* data; + napi_get_cb_info(env, info, &argc, nullptr, &thisArg, &data); + if (argc < expectedArgc) { + napi_throw_error(env, "EINVAL", "Insufficient arguments"); + return false; + } + napi_value argv[expectedArgc]; + napi_get_cb_info(env, info, &argc, argv, &thisArg, &data); + for (size_t i = 0; i < expectedArgc; ++i) { + napi_valuetype type; + napi_typeof(env, argv[i], &type); + if (type != napi_number) { + napi_throw_type_error(env, "EINVAL", "All arguments must be numbers"); + return false; + } + } + return true; +} + +// Auxiliary function: Obtain a value of the int32 type and perform error processing. +bool GetInt32Value(napi_env env, napi_value value, int32_t* result) { + napi_status status = napi_get_value_int32(env, value, result); + if (status != napi_ok) { + napi_throw_error(env, "EINVAL", "Failed to get int32 value"); + return false; + } + return true; +} + +// Auxiliary function: Obtain a value of the int64 type and perform error processing. +bool GetInt64Value(napi_env env, napi_value value, int64_t* result) { + napi_status status = napi_get_value_int64(env, value, result); + if (status != napi_ok) { + napi_throw_error(env, "EINVAL", "Failed to get int64 value"); + return false; + } + return true; +} + +// Describe the mapped OhAvImageGeneratorFetchFrameByTime method in the index.d.ts file. +// export const OhAvImageGeneratorFetchFrameByTime: (fdsrc : number, size : number, timeus : number, +// options : number, offset : number) => image.PixelMap; +// Pass in the media file descriptor (fdsrc), media file size (size), and specified time (timeus, in μs). +// Specify the mappings between the time points and the video frames (options) and the offset of the media source in the file descriptor. +// Return a PixelMap object. +static napi_value OhAvImageGeneratorFetchFrameByTime(napi_env env, napi_callback_info info) +{ + if (!CheckArgs(env, info, 5)) { + return nullptr; + } + size_t argc = 5; + napi_value argv[5]; + napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); + int64_t timeUs = 0; + int64_t offset = 0; + int32_t fileDescribe = -1; + int32_t fileSize = 0; + int32_t options = OH_AVIMAGE_GENERATOR_QUERY_CLOSEST; + if (!GetInt32Value(env, argv[0], &fileDescribe)) return nullptr; + if (!GetInt32Value(env, argv[1], &fileSize)) return nullptr; + if (!GetInt64Value(env, argv[2], &timeUs)) return nullptr; + if (!GetInt32Value(env, argv[3], &options)) return nullptr; + if (!GetInt64Value(env, argv[4], &offset)) return nullptr; + // Verify the parameter. + if (options < OH_AVIMAGE_GENERATOR_QUERY_NEXT_SYNC || options > OH_AVIMAGE_GENERATOR_QUERY_CLOSEST) { + napi_throw_range_error(env, "EINVAL", "Invalid options value"); + return nullptr; + } + // Create an OH_AVImageGenerator instance. + OH_AVImageGenerator* generator = OH_AVImageGenerator_Create(); + // Handle exceptions. + if (!generator) { + napi_throw_error(env, "EFAILED", "Create generator failed"); + return nullptr; + } + // Set the file descriptor of the video resource. + OH_AVErrCode avErrCode = OH_AVImageGenerator_SetFDSource(generator, fileDescribe, offset, fileSize); + // Handle exceptions. + if (avErrCode != AV_ERR_OK) { + OH_AVImageGenerator_Release(generator); + napi_throw_error(env, "EFAILED", "SetFDSource failed"); + return nullptr; + } + // Obtain the video frame at a specified time. + OH_PixelmapNative* pixelMap = nullptr; + avErrCode = OH_AVImageGenerator_FetchFrameByTime(generator, timeUs, + (OH_AVImageGenerator_QueryOptions)options, &pixelMap); + // Handle exceptions. + if (avErrCode != AV_ERR_OK || !pixelMap) { + OH_AVImageGenerator_Release(generator); + napi_throw_error(env, "EFAILED", "FetchFrameByTime failed"); + return nullptr; + } + // Convert the nativePixelMap object into a PixelMapnapi object. + napi_value pixelmapNapi = nullptr; + Image_ErrorCode errCode = OH_PixelmapNative_ConvertPixelmapNativeToNapi(env, pixelMap, &pixelmapNapi); + // Release the OH_PixelmapNative resource. + OH_PixelmapNative_Release(pixelMap); + // Release the OH_AVImageGenerator resource. + OH_AVImageGenerator_Release(generator); + // Handle exceptions. + if (errCode != IMAGE_SUCCESS) { + napi_throw_error(env, "EFAILED", "Convert PixelMap failed"); + return nullptr; + } + return pixelmapNapi; +} + +EXTERN_C_START +static napi_value Init(napi_env env, napi_value exports) +{ + napi_property_descriptor desc[] = { + {"OhAvImageGeneratorFetchFrameByTime", nullptr, OhAvImageGeneratorFetchFrameByTime, nullptr, nullptr, nullptr, napi_default, nullptr}, + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); + return exports; +} +EXTERN_C_END + +static napi_module demoModule = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = Init, + .nm_modname = "entry", + .nm_priv = ((void *)0), + .reserved = {0}, +}; + +extern "C" __attribute__((constructor)) void RegisterEntryModule(void) +{ + napi_module_register(&demoModule); +} +``` diff --git a/en/application-dev/media/media/using-ndk-avmetadataextractor-for-media.md b/en/application-dev/media/media/using-ndk-avmetadataextractor-for-media.md new file mode 100644 index 0000000000000000000000000000000000000000..1ac05be1682361d0fb3b4335eede363097abb3f5 --- /dev/null +++ b/en/application-dev/media/media/using-ndk-avmetadataextractor-for-media.md @@ -0,0 +1,511 @@ +# Using AVMetadataExtractor to Obtain Metadata (C/C++) + +You can use the AVMetadataExtractor to obtain metadata from a raw media asset. This topc walks you through on how to obtain the metadata of an audio asset. The process of obtaining the metadata of a video asset is similar. The only difference is that the process of obtaining the album cover is not required for a video asset, because no album cover is available in the video asset. + +The full process of obtaining the metadata of an audio asset includes creating an AVMetadataExtractor instance, setting resources, obtaining the metadata, obtaining the album cover, and releasing the instance. + +## How to Develop +Link the dynamic library in the CMake script. +``` +target_link_libraries(entry PUBLIC libavmetadata_extractor.so libace_napi.z.so ) +``` + +To use [OH_AVFormat](../../reference/apis-avcodec-kit/_core.md#oh_avformat) APIs, include the following header file: +``` +#include +``` + +In addition, link the following dynamic link library in the CMake script: +``` +target_link_libraries(entry PUBLIC libnative_media_core.so) +``` + +To use [OH_PixelmapNative_ConvertPixelmapNativeToNapi()](../../reference/apis-image-kit/_image___native_module.md#oh_pixelmapnative_convertpixelmapnativetonapi) to convert a nativePixelMap object into a PixelMapnapi object and use [OH_PixelmapNative_Release()](../../reference/apis-image-kit/_image___native_module.md#oh_pixelmapnative_release) to release the OH_PixelmapNative object, include the following header file: +``` +#include +``` + +In addition, link the following dynamic link library in the CMake script: +``` +target_link_libraries(entry PUBLIC libpixelmap.so libpixelmap_ndk.z.so) +``` + +To use system logging, include the following header file: +``` +#include +``` + +In addition, link the following dynamic link library in the CMake script: +``` +target_link_libraries(entry PUBLIC libhilog_ndk.z.so) +``` + +You can use the APIs related to metadata retrieval by including the header files [avmetadata_extractor.h](../../reference/apis-media-kit/avmetadata__extractor_8h.md), [avmetadata_extractor_base.h](../../reference/apis-media-kit/avmetadata__extractor__base_8h.md), and [native_averrors.h](../../reference/apis-avcodec-kit/native__averrors_8h.md). +Read [AVMetadataExtractor](../../reference/apis-media-kit/_a_v_metadata_extractor.md) for the API reference. + +1. Call [OH_AVMetadataExtractor_Create()](../../reference/apis-media-kit/_a_v_metadata_extractor.md#oh_avmetadataextractor_create) to create an instance. + +2. Call [OH_AVMetadataExtractor_SetFDSoucre()](../../reference/apis-media-kit/_a_v_metadata_extractor.md#oh_avmetadataextractor_setfdsource) to set the file descriptor of a video resource. + +> If different AVMetadataExtractor or [AVImageGenerator](../../reference/apis-media-kit/_a_v_image_generator.md) instances need to operate the same resource, the file descriptor needs to be opened for multiple times. Therefore, do not share a file descriptor. + +3. Call [OH_AVMetadataExtractor_FetchMetadata()](../../reference/apis-media-kit/_a_v_metadata_extractor.md#oh_avmetadataextractor_fetchmetadata) to obtain metadata. + +> First, call **OH_AVFormat_Create()** to create an **OH_AVFormat** object and obtain the metadata by accessing the key-value pairs of the object. When the object is no longer required, call **OH_AVFormat_Destroy** to release the object to prevent memory leakage. For details, see [OH_AVFormat](../../reference/apis-avcodec-kit/_core.md#oh_avformat). + +4. (Optional) Call [OH_AVMetadataExtractor_FetchAlbumCover()](../../reference/apis-media-kit/_a_v_metadata_extractor.md#oh_avmetadataextractor_fetchalbumcover) to obtain the album cover. + +> When the object is no longer required, call **OH_PixelmapNative_Release** to release the object. For details, see [Image_NativeModule](../../reference/apis-image-kit/_image___native_module.md). + +5. Call [OH_AVMetadataExtractor_Release()](../../reference/apis-media-kit/_a_v_metadata_extractor.md#oh_avmetadataextractor_release) to destroy the instance and release resources. + + +## Sample Code + +Refer to the sample code below to set the file descriptor and obtain the metadata and album cover of an audio asset. + +```c +#include "napi/native_api.h" + +#include +#include +#include +#include +#include +#include + +#include + +#define LOG_PRINT_DOMAIN 0xFF00 +#define APP_LOG_DOMAIN 0x0001 +constexpr const char *APP_LOG_TAG = "AVMetadataExtractor"; +#define H_LOGI(...) ((void)OH_LOG_Print(LOG_APP, LOG_INFO, LOG_DOMAIN, APP_LOG_TAG, __VA_ARGS__)) + +// Auxiliary function: Check the number and type of parameters. +bool CheckArgs(napi_env env, napi_callback_info info, size_t expectedArgc) { + size_t argc; + napi_value thisArg; + void* data; + napi_get_cb_info(env, info, &argc, nullptr, &thisArg, &data); + if (argc < expectedArgc) { + napi_throw_error(env, "EINVAL", "Insufficient arguments"); + return false; + } + napi_value argv[expectedArgc]; + napi_get_cb_info(env, info, &argc, argv, &thisArg, &data); + for (size_t i = 0; i < expectedArgc; ++i) { + napi_valuetype type; + napi_typeof(env, argv[i], &type); + if (type != napi_number) { + napi_throw_type_error(env, "EINVAL", "All arguments must be numbers"); + return false; + } + } + return true; +} + +// Auxiliary function: Obtain a value of the int32 type and perform error processing. +bool GetInt32Value(napi_env env, napi_value value, int32_t* result) { + napi_status status = napi_get_value_int32(env, value, result); + if (status != napi_ok) { + napi_throw_error(env, "EINVAL", "Failed to get int32 value"); + return false; + } + return true; +} + +// Auxiliary function: Obtain a value of the int64 type and perform error processing. +bool GetInt64Value(napi_env env, napi_value value, int64_t* result) { + napi_status status = napi_get_value_int64(env, value, result); + if (status != napi_ok) { + napi_throw_error(env, "EINVAL", "Failed to get int64 value"); + return false; + } + return true; +} + +// Auxiliary function: Convert a value of the string type to a napi object and perform error processing. +bool SetPropertyString(napi_env env, napi_value &obj, const std::string &key, const std::string &value) { + napi_value keyNapi = nullptr; + napi_status status = napi_create_string_utf8(env, key.c_str(), NAPI_AUTO_LENGTH, &keyNapi); + if (status != napi_ok) { + // napi_throw_error(env, "EFAILED", "Failed to create string key"); + return false; + } + napi_value valueNapi = nullptr; + status = napi_create_string_utf8(env, value.c_str(), NAPI_AUTO_LENGTH, &valueNapi); + if (status != napi_ok) { + // napi_throw_error(env, "EFAILED", "Failed to create string value"); + return false; + } + status = napi_set_property(env, obj, keyNapi, valueNapi); + if (status != napi_ok) { + // napi_throw_error(env, "EFAILED", "Failed to set property"); + return false; + } + return true; +} + +// Auxiliary function: Convert a value of the double type to a napi object and perform error processing. +bool SetPropertyDouble(napi_env env, napi_value &obj, const std::string &key, double value) { + napi_value keyNapi = nullptr; + napi_status status = napi_create_string_utf8(env, key.c_str(), NAPI_AUTO_LENGTH, &keyNapi); + if (status != napi_ok) { + // napi_throw_error(env, "EFAILED", "Failed to create string key"); + return false; + } + napi_value valueNapi = nullptr; + status = napi_create_double(env, value, &valueNapi); + if (status != napi_ok) { + // napi_throw_error(env, "EFAILED", "Failed to create double value"); + return false; + } + status = napi_set_property(env, obj, keyNapi, valueNapi); + if (status != napi_ok) { + // napi_throw_error(env, "EFAILED", "Failed to set property"); + return false; + } + return true; +} + +// Auxiliary function: Convert a value of the int type to a napi object and perform error processing. +bool SetPropertyInt(napi_env env, napi_value &obj, const std::string &key, int value) { + napi_value keyNapi = nullptr; + napi_status status = napi_create_string_utf8(env, key.c_str(), NAPI_AUTO_LENGTH, &keyNapi); + if (status != napi_ok) { + // napi_throw_error(env, "EFAILED", "Failed to create string key"); + return false; + } + napi_value valueNapi = nullptr; + status = napi_create_int32(env, value, &valueNapi); + if (status != napi_ok) { + // napi_throw_error(env, "EFAILED", "Failed to create int value"); + return false; + } + status = napi_set_property(env, obj, keyNapi, valueNapi); + if (status != napi_ok) { + // napi_throw_error(env, "EFAILED", "Failed to set property"); + return false; + } + return true; +} + +// Obtain the album cover. +// Describe the mapped OhAVMetadataExtractorFetchAlbumCover method in the index.d.ts file. +// export const OhAVMetadataExtractorFetchAlbumCover: (fdsrc : number, size : number, offset : number) => image.PixelMap; +// Pass the media file descriptor (fdsrc), media file size (size), and offset of the media source in the file descriptor (offset). +// Return a PixelMap object. +static napi_value OhAVMetadataExtractorFetchAlbumCover(napi_env env, napi_callback_info info) { + if (!CheckArgs(env, info, 3)) { + return nullptr; + } + size_t argc = 3; + napi_value argv[3]; + napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); + int64_t offset = 0; + int32_t fileDescribe = -1; + int64_t fileSize = 0; + if (!GetInt32Value(env, argv[0], &fileDescribe)) return nullptr; + if (!GetInt64Value(env, argv[1], &fileSize)) return nullptr; + if (!GetInt64Value(env, argv[2], &offset)) return nullptr; + // Create an OH_AVMetadataExtractor instance. + OH_AVMetadataExtractor* mainExtractor = OH_AVMetadataExtractor_Create(); + // Handle exceptions. + if (!mainExtractor) { + napi_throw_error(env, "EFAILED", "Create metadata extractor failed"); + return nullptr; + } + // Set the file descriptor of the video resource. + OH_AVErrCode avErrCode = OH_AVMetadataExtractor_SetFDSource(mainExtractor, fileDescribe, offset, fileSize); + // Handle exceptions. + if (avErrCode != AV_ERR_OK) { + OH_AVMetadataExtractor_Release(mainExtractor); + napi_throw_error(env, "EFAILED", "SetFDSource for metadata extractor failed"); + return nullptr; + } + // Obtain the album cover. + OH_PixelmapNative* pixelMap = nullptr; + avErrCode = OH_AVMetadataExtractor_FetchAlbumCover(mainExtractor, &pixelMap); + // Handle exceptions. + if (avErrCode != AV_ERR_OK || !pixelMap) { + OH_AVMetadataExtractor_Release(mainExtractor); + napi_throw_error(env, "EFAILED", "Fetch album cover failed"); + return nullptr; + } + // Convert the nativePixelMap object into a PixelMapnapi object. + napi_value pixelmapNapi = nullptr; + Image_ErrorCode errCode = OH_PixelmapNative_ConvertPixelmapNativeToNapi(env, pixelMap, &pixelmapNapi); + // Release the OH_PixelmapNative resource. + OH_PixelmapNative_Release(pixelMap); + // Release the OH_AVMetadataExtractor resource. + OH_AVMetadataExtractor_Release(mainExtractor); + // Handle exceptions. + if (errCode != IMAGE_SUCCESS) { + napi_throw_error(env, "EFAILED", "Convert PixelMap failed"); + return nullptr; + } + return pixelmapNapi; +} + +// Obtain the metadata. +// Describe the mapped OhAVMetadataExtractorFetchMetadata method in the index.d.ts file. +// export const OhAVMetadataExtractorFetchMetadata: (fdsrc : number, size : number, offset : number) => media.AVMetadata; +// Pass the media file descriptor (fdsrc), media file size (size), and offset of the media source in the file descriptor (offset). +// Return the AVMetadata object. +static napi_value OhAVMetadataExtractorFetchMetadata(napi_env env, napi_callback_info info) { + if (!CheckArgs(env, info, 3)) { + return nullptr; + } + size_t argc = 3; + napi_value argv[3]; + napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); + int64_t offset = 0; + int32_t fileDescribe = -1; + int64_t fileSize = 0; + if (!GetInt32Value(env, argv[0], &fileDescribe)) return nullptr; + if (!GetInt64Value(env, argv[1], &fileSize)) return nullptr; + if (!GetInt64Value(env, argv[2], &offset)) return nullptr; + // Create an OH_AVMetadataExtractor instance. + OH_AVMetadataExtractor* mainExtractor = OH_AVMetadataExtractor_Create(); + // Handle exceptions. + if (!mainExtractor) { + napi_throw_error(env, "EFAILED", "Create metadata extractor failed"); + return nullptr; + } + // Set the file descriptor of the video resource. + OH_AVErrCode avErrCode = OH_AVMetadataExtractor_SetFDSource(mainExtractor, fileDescribe, offset, fileSize); + // Handle exceptions. + if (avErrCode != AV_ERR_OK) { + OH_AVMetadataExtractor_Release(mainExtractor); + napi_throw_error(env, "EFAILED", "SetFDSource for metadata extractor failed"); + return nullptr; + } + // Create an OH_AVFormat object. + OH_AVFormat* avMetadata = OH_AVFormat_Create(); + // Handle exceptions. + if (!avMetadata) { + OH_AVMetadataExtractor_Release(mainExtractor); + napi_throw_error(env, "EFAILED", "Create AVFormat failed"); + return nullptr; + } + // Obtain the metadata. + avErrCode = OH_AVMetadataExtractor_FetchMetadata(mainExtractor, avMetadata); + // Handle exceptions. + if (avErrCode != AV_ERR_OK) { + OH_AVFormat_Destroy(avMetadata); + OH_AVMetadataExtractor_Release(mainExtractor); + napi_throw_error(env, "EFAILED", "Fetch metadata failed"); + return nullptr; + } + napi_value JsMetadata = nullptr; + napi_status status = napi_create_object(env, &JsMetadata); + // Handle exceptions. + if (status != napi_ok) { + OH_AVFormat_Destroy(avMetadata); + OH_AVMetadataExtractor_Release(mainExtractor); + napi_throw_error(env, "EFAILED", "Create JavaScript object failed"); + return nullptr; + } + + const char* out = nullptr; + bool ret = false; + // Parse each metadata value from the OH_AVFormat object and save the value to the AVMetadata required by JS. + ret = OH_AVFormat_GetStringValue(avMetadata, OH_AVMETADATA_EXTRACTOR_ALBUM, &out); + H_LOGI("OH_AVMETADATA_EXTRACTOR_ALBUM : %{public}s",out); + if (ret && out) { + SetPropertyString(env, JsMetadata, OH_AVMETADATA_EXTRACTOR_ALBUM,out); + } + + out = nullptr; + ret = OH_AVFormat_GetStringValue(avMetadata, OH_AVMETADATA_EXTRACTOR_ALBUM_ARTIST, &out); + H_LOGI("OH_AVMETADATA_EXTRACTOR_ALBUM_ARTIST : %{public}s",out); + if (ret && out) { + SetPropertyString(env, JsMetadata, OH_AVMETADATA_EXTRACTOR_ALBUM_ARTIST,out); + } + + out = nullptr; + ret = OH_AVFormat_GetStringValue(avMetadata, OH_AVMETADATA_EXTRACTOR_ARTIST, &out); + H_LOGI("OH_AVMETADATA_EXTRACTOR_ARTIST : %{public}s",out); + if (ret && out) { + SetPropertyString(env, JsMetadata, OH_AVMETADATA_EXTRACTOR_ARTIST,out); + } + + out = nullptr; + ret = OH_AVFormat_GetStringValue(avMetadata, OH_AVMETADATA_EXTRACTOR_AUTHOR, &out); + H_LOGI("OH_AVMETADATA_EXTRACTOR_AUTHOR : %{public}s",out); + if (ret && out) { + SetPropertyString(env, JsMetadata, OH_AVMETADATA_EXTRACTOR_AUTHOR,out); + } + + out = nullptr; + ret = OH_AVFormat_GetStringValue(avMetadata, OH_AVMETADATA_EXTRACTOR_DATE_TIME, &out); + H_LOGI("OH_AVMETADATA_EXTRACTOR_DATE_TIME : %{public}s",out); + if (ret && out) { + SetPropertyString(env, JsMetadata, OH_AVMETADATA_EXTRACTOR_DATE_TIME,out); + } + + out = nullptr; + ret = OH_AVFormat_GetStringValue(avMetadata, OH_AVMETADATA_EXTRACTOR_DATE_TIME_FORMAT, &out); + H_LOGI("OH_AVMETADATA_EXTRACTOR_DATE_TIME_FORMAT : %{public}s",out); + if (ret && out) { + SetPropertyString(env, JsMetadata, OH_AVMETADATA_EXTRACTOR_DATE_TIME_FORMAT,out); + } + + out = nullptr; + ret = OH_AVFormat_GetStringValue(avMetadata, OH_AVMETADATA_EXTRACTOR_COMPOSER, &out); + H_LOGI("OH_AVMETADATA_EXTRACTOR_COMPOSER : %{public}s",out); + if (ret && out) { + SetPropertyString(env, JsMetadata, OH_AVMETADATA_EXTRACTOR_COMPOSER,out); + } + + int64_t duration = 0; + ret = OH_AVFormat_GetLongValue(avMetadata, OH_AVMETADATA_EXTRACTOR_DURATION, &duration); + H_LOGI("OH_AVMETADATA_EXTRACTOR_DURATION : %{public}lld",duration); + if (ret) { + out = std::to_string(duration).c_str(); + SetPropertyString(env, JsMetadata, OH_AVMETADATA_EXTRACTOR_DURATION,out); + } + + out = nullptr; + ret = OH_AVFormat_GetStringValue(avMetadata, OH_AVMETADATA_EXTRACTOR_GENRE, &out); + H_LOGI("OH_AVMETADATA_EXTRACTOR_GENRE : %{public}s",out); + if (ret && out) { + SetPropertyString(env, JsMetadata, OH_AVMETADATA_EXTRACTOR_GENRE,out); + } + + int32_t hasAudio; + ret = OH_AVFormat_GetIntValue(avMetadata, OH_AVMETADATA_EXTRACTOR_HAS_AUDIO, &hasAudio); + H_LOGI("OH_AVMETADATA_EXTRACTOR_HAS_AUDIO : %{public}d",hasAudio); + if (ret) { + out = std::to_string(hasAudio).c_str(); + SetPropertyString(env, JsMetadata, OH_AVMETADATA_EXTRACTOR_HAS_AUDIO,out); + } + + int32_t hasVideo; + ret = OH_AVFormat_GetIntValue(avMetadata, OH_AVMETADATA_EXTRACTOR_HAS_VIDEO, &hasVideo); + H_LOGI("OH_AVMETADATA_EXTRACTOR_HAS_VIDEO : %{public}d",hasVideo); + if (ret) { + out = std::to_string(hasVideo).c_str(); + SetPropertyString(env, JsMetadata, OH_AVMETADATA_EXTRACTOR_HAS_VIDEO,out); + } + + out = nullptr; + ret = OH_AVFormat_GetStringValue(avMetadata, OH_AVMETADATA_EXTRACTOR_MIME_TYPE, &out); + H_LOGI("OH_AVMETADATA_EXTRACTOR_MIME_TYPE : %{public}s",out); + if (ret && out) { + SetPropertyString(env, JsMetadata, OH_AVMETADATA_EXTRACTOR_MIME_TYPE,out); + } + + int32_t trackCount; + ret = OH_AVFormat_GetIntValue(avMetadata, OH_AVMETADATA_EXTRACTOR_TRACK_COUNT, &trackCount); + H_LOGI("OH_AVMETADATA_EXTRACTOR_NUM_TRACKS : %{public}d",trackCount); + if (ret) { + out = std::to_string(trackCount).c_str(); + SetPropertyString(env, JsMetadata, OH_AVMETADATA_EXTRACTOR_TRACK_COUNT,out); + } + + int32_t sampleRate; + ret = OH_AVFormat_GetIntValue(avMetadata, OH_AVMETADATA_EXTRACTOR_SAMPLE_RATE, &sampleRate); + H_LOGI("OH_AVMETADATA_EXTRACTOR_SAMPLE_RATE : %{public}d",sampleRate); + if (ret) { + out = std::to_string(sampleRate).c_str(); + SetPropertyString(env, JsMetadata, OH_AVMETADATA_EXTRACTOR_SAMPLE_RATE,out); + } + + out = nullptr; + ret = OH_AVFormat_GetStringValue(avMetadata, OH_AVMETADATA_EXTRACTOR_TITLE, &out); + H_LOGI("OH_AVMETADATA_EXTRACTOR_TITLE : %{public}s",out); + if (ret && out) { + SetPropertyString(env, JsMetadata, OH_AVMETADATA_EXTRACTOR_TITLE,out); + } + + int32_t videoHeight; + ret = OH_AVFormat_GetIntValue(avMetadata, OH_AVMETADATA_EXTRACTOR_VIDEO_HEIGHT, &videoHeight); + H_LOGI("OH_AVMETADATA_EXTRACTOR_VIDEO_HEIGHT : %{public}d",videoHeight); + if (ret) { + out = std::to_string(videoHeight).c_str(); + SetPropertyString(env, JsMetadata, OH_AVMETADATA_EXTRACTOR_VIDEO_HEIGHT,out); + } + + int32_t videoWidth; + ret = OH_AVFormat_GetIntValue(avMetadata, OH_AVMETADATA_EXTRACTOR_VIDEO_WIDTH, &videoWidth); + H_LOGI("OH_AVMETADATA_EXTRACTOR_VIDEO_WIDTH : %{public}d",videoWidth); + if (ret) { + out = std::to_string(videoWidth).c_str(); + SetPropertyString(env, JsMetadata, OH_AVMETADATA_EXTRACTOR_VIDEO_WIDTH,out); + } + + int32_t videoOrientation; + ret = OH_AVFormat_GetIntValue(avMetadata, OH_AVMETADATA_EXTRACTOR_VIDEO_ORIENTATION, &videoOrientation); + H_LOGI("OH_AVMETADATA_EXTRACTOR_VIDEO_ORIENTATION : %{public}d",videoOrientation); + if (ret) { + out = std::to_string(videoOrientation).c_str(); + SetPropertyString(env, JsMetadata, OH_AVMETADATA_EXTRACTOR_VIDEO_ORIENTATION,out); + } + + int32_t hdrType; + ret = OH_AVFormat_GetIntValue(avMetadata, OH_AVMETADATA_EXTRACTOR_VIDEO_IS_HDR_VIVID, &hdrType); + H_LOGI("OH_AVMETADATA_EXTRACTOR_VIDEO_IS_HDR_VIVID : %{public}d ret %{public}d",hdrType, ret); + if (ret) { + bool hh = SetPropertyInt(env, JsMetadata, OH_AVMETADATA_EXTRACTOR_VIDEO_IS_HDR_VIVID,hdrType); + H_LOGI("OH_AVMETADATA_EXTRACTOR_VIDEO_IS_HDR_VIVID : %{public}d hh %{public}d",hdrType, hh); + } + + napi_value location = nullptr; + napi_create_object(env, &location); + float latitude; + bool retLatitude = OH_AVFormat_GetFloatValue(avMetadata, OH_AVMETADATA_EXTRACTOR_LOCATION_LATITUDE, &latitude); + H_LOGI("OH_AVMETADATA_EXTRACTOR_LOCATION_LATITUDE : %{public}f",latitude); + if (retLatitude) { + SetPropertyDouble(env, location, OH_AVMETADATA_EXTRACTOR_LOCATION_LATITUDE,latitude); + } + + float longitude; + bool retLongitude = OH_AVFormat_GetFloatValue(avMetadata, OH_AVMETADATA_EXTRACTOR_LOCATION_LONGITUDE, &longitude); + H_LOGI("OH_AVMETADATA_EXTRACTOR_LOCATION_LONGITUDE : %{public}f",longitude); + if (retLongitude) { + SetPropertyDouble(env, location, OH_AVMETADATA_EXTRACTOR_LOCATION_LONGITUDE,longitude); + } + + if (retLatitude || retLongitude) { + napi_value keyNapi = nullptr; + std::string key = "location"; + napi_create_string_utf8(env, key.c_str(), NAPI_AUTO_LENGTH, &keyNapi); + napi_set_property(env, JsMetadata, keyNapi, location); + } + // Release the OH_AVFormat resource. + OH_AVFormat_Destroy(avMetadata); + // Release the OH_AVMetadataExtractor resource. + OH_AVMetadataExtractor_Release(mainExtractor); + return JsMetadata; +} + +EXTERN_C_START +static napi_value Init(napi_env env, napi_value exports) +{ + napi_property_descriptor desc[] = { + {"OhAVMetadataExtractorFetchAlbumCover", nullptr, OhAVMetadataExtractorFetchAlbumCover, nullptr, nullptr, + nullptr, napi_default, nullptr}, + {"OhAVMetadataExtractorFetchMetadata", nullptr, OhAVMetadataExtractorFetchMetadata, nullptr, nullptr, + nullptr, napi_default, nullptr}, + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); + return exports; +} +EXTERN_C_END + +static napi_module demoModule = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = Init, + .nm_modname = "entry", + .nm_priv = ((void *)0), + .reserved = {0}, +}; + +extern "C" __attribute__((constructor)) void RegisterEntryModule(void) +{ + napi_module_register(&demoModule); +} +``` diff --git a/en/application-dev/media/media/using-ndk-avplayer-for-playback.md b/en/application-dev/media/media/using-ndk-avplayer-for-playback.md index 85a6f10313c37009097492308a3d29a92cf393b7..14737193c4425f4ab6b08bbff83a786f3c1a0158 100644 --- a/en/application-dev/media/media/using-ndk-avplayer-for-playback.md +++ b/en/application-dev/media/media/using-ndk-avplayer-for-playback.md @@ -79,6 +79,7 @@ Read [AVPlayer](../../reference/apis-media-kit/_a_v_player.md) for the API refer ```c #include "napi/native_api.h" +#include #include #include #include @@ -119,51 +120,52 @@ typedef struct DemoNdkPlayer { } DemoNdkPlayer; void HandleStateChange(OH_AVPlayer *player, AVPlayerState state) { + int32_t ret; switch (state) { case AV_IDLE: // This state is reported upon a successful callback of OH_AVPlayer_Reset(). // ret = OH_AVPlayer_SetURLSource(player, url); // Set the URL. // if (ret != AV_ERR_OK) { -// // Handle the exception. +// // Handle exceptions. // } break; case AV_INITIALIZED: ret = OH_AVPlayer_Prepare(player); // This state is reported when the AVPlayer sets the playback source. if (ret != AV_ERR_OK) { - // Exception processing. + // Handle exceptions. } break; case AV_PREPARED: // ret = OH_AVPlayer_SetAudioEffectMode(player, EFFECT_NONE); // Set the audio effect mode. // if (ret != AV_ERR_OK) { -// // Handle the exception. +// // Handle exceptions. // } ret = OH_AVPlayer_Play(player); // Call OH_AVPlayer_Play() to start playback. if (ret != AV_ERR_OK) { - // Exception processing. + // Handle exceptions. } break; case AV_PLAYING: // ret = OH_AVPlayer_Pause(player); // Call OH_AVPlayer_Pause() to pause the playback. // if (ret != AV_ERR_OK) { -// // Handle the exception. +// // Handle exceptions. // } break; case AV_PAUSED: // ret = OH_AVPlayer_Play(player); // Call OH_AVPlayer_Play() again to start playback. // if (ret != AV_ERR_OK) { -// // Handle the exception. +// // Handle exceptions. // } break; case AV_STOPPED: ret = OH_AVPlayer_Release(player); // Call OH_AVPlayer_Reset() to reset the AVPlayer state. if (ret != AV_ERR_OK) { - // Exception processing. + // Handle exceptions. } break; case AV_COMPLETED: ret = OH_AVPlayer_Stop(player);// Call OH_AVPlayer_Stop() to stop the playback. if (ret != AV_ERR_OK) { - // Exception processing. + // Handle exceptions. } break; default: @@ -299,13 +301,14 @@ void OHAVPlayerOnErrorCallback(OH_AVPlayer *player, int32_t errorCode, const cha return; } demoNdkPlayer->errorCode = errorCode; - // do something + // do something. } // Describe the mapped play method in the index.d.ts file and pass in a parameter of the string type. // When calling the player method in the .ets file, pass in the file path testNapi.play("/data/test/test.mp3"). static napi_value Play(napi_env env, napi_callback_info info) { + int32_t ret = -1; size_t argc = 1; napi_value args[1] = {nullptr}; @@ -314,26 +317,26 @@ static napi_value Play(napi_env env, napi_callback_info info) // Obtain the parameter type. napi_valuetype stringType; if (napi_ok != napi_typeof(env, args[0], &stringType)) { - // Exception processing. + // Handle exceptions. return nullptr; } // Verify the parameter. if (napi_null == stringType) { - // Exception processing. + // Handle exceptions. return nullptr; } // Obtain the length of the passed-in string. size_t length = 0; if (napi_ok != napi_get_value_string_utf8(env, args[0], nullptr, 0, &length)) { - // Exception processing. + // Handle exceptions. return nullptr; } // If "" is passed in, the result is directly returned. if (length == 0) { - // Exception processing. + // Handle exceptions. return nullptr; } @@ -342,12 +345,13 @@ static napi_value Play(napi_env env, napi_callback_info info) if (napi_ok != napi_get_value_string_utf8(env, args[0], url, length + 1, &length)) { delete[] url; url = nullptr; - // Exception processing. + // Handle exceptions. return nullptr; } // Use the new function to set the information callback and error callback. Do not use OH_AVPlayer_SetPlayerCallback. // Release the object when it is no longer needed. + OH_AVPlayer *player = OH_AVPlayer_Create(); DemoNdkPlayer *demoNdkPlayer = new DemoNdkPlayer({ .player = player, .url = url, @@ -360,23 +364,23 @@ static napi_value Play(napi_env env, napi_callback_info info) LOG("OH_AVPlayer_SetPlayerOnErrorCallback ret:%d", ret); if (ret != AV_ERR_OK) { - // Exception processing. + // Handle exceptions. } ret = OH_AVPlayer_SetURLSource(player, url); // Set the URL. if (ret != AV_ERR_OK) { - // Exception processing. + // Handle exceptions. } // Set the audio stream type. OH_AudioStream_Usage streamUsage = OH_AudioStream_Usage::AUDIOSTREAM_USAGE_UNKNOWN; ret = OH_AVPlayer_SetAudioRendererInfo(player, streamUsage); if (ret != AV_ERR_OK) { - // Handle the exception. + // Handle exceptions. } // Set the audio interruption mode. OH_AudioInterrupt_Mode interruptMode = OH_AudioInterrupt_Mode::AUDIOSTREAM_INTERRUPT_MODE_INDEPENDENT; ret = OH_AVPlayer_SetAudioInterruptMode(player, interruptMode); if (ret != AV_ERR_OK) { - // Handle the exception. + // Handle exceptions. } napi_value value; napi_create_int32(env, 0, &value); diff --git a/en/application-dev/media/media/using-ndk-avplayer-for-video-playback.md b/en/application-dev/media/media/using-ndk-avplayer-for-video-playback.md index 0bd3acc7efd7453068ba37e7154bb123ac44232c..7f789c300c3335bc68475580de733bc9cff165d7 100644 --- a/en/application-dev/media/media/using-ndk-avplayer-for-video-playback.md +++ b/en/application-dev/media/media/using-ndk-avplayer-for-video-playback.md @@ -1,11 +1,10 @@ -# Using AVPlayer to Play Video (C/C++) +# Using AVPlayer to Play Videos (C/C++) The [AVPlayer](../../reference/apis-media-kit/_a_v_player.md#avplayer) is used to play raw media assets in an end-to-end manner. In this topic, you will learn how to use the AVPlayer to play a complete video. The full playback process includes creating an AVPlayer instance, setting callback functions, setting the media asset to play, setting playback parameters (volume, speed, and focus mode), setting the playback window, controlling playback (play, pause, seek, and stop), resetting the playback configuration, and releasing the AVPlayer instance. - During application development, you can obtain the playback process information through the callbacks [OH_AVPlayerOnInfoCallback](../../reference/apis-media-kit/_a_v_player.md#oh_avplayeroninfocallback) and [OH_AVPlayerOnErrorCallback](../../reference/apis-media-kit/_a_v_player.md#oh_avplayeronerrorcallback) of the AVPlayer. If the application performs an operation when the AVPlayer is not in the given state, the system may throw an exception or generate other undefined behavior. **Figure 1** Playback state transition @@ -131,7 +130,7 @@ void HandleStateChange(OH_AVPlayer *player, AVPlayerState state) { case AV_IDLE: // This state is reported upon a successful callback of OH_AVPlayer_Reset(). // ret = OH_AVPlayer_SetURLSource(player, url); // Set the URL. // if (ret != AV_ERR_OK) { -// // Handle the exception. +// // Handle exceptions. // } break; case AV_INITIALIZED: @@ -139,41 +138,41 @@ void HandleStateChange(OH_AVPlayer *player, AVPlayerState state) { LOG("OH_AVPlayer_SetVideoSurface ret:%d", ret); ret = OH_AVPlayer_Prepare(player); // This state is reported when the AVPlayer sets the playback source. if (ret != AV_ERR_OK) { - // Handle the exception. + // Handle exceptions. } break; case AV_PREPARED: // ret = OH_AVPlayer_SetAudioEffectMode(player, EFFECT_NONE); // Set the audio effect mode. // if (ret != AV_ERR_OK) { -// // Handle the exception. +// // Handle exceptions. // } ret = OH_AVPlayer_Play(player); // Call OH_AVPlayer_Play() to start playback. if (ret != AV_ERR_OK) { - // Handle the exception. + // Handle exceptions. } break; case AV_PLAYING: // ret = OH_AVPlayer_Pause(player); // Call OH_AVPlayer_Pause() to pause the playback. // if (ret != AV_ERR_OK) { -// // Handle the exception. +// // Handle exceptions. // } break; case AV_PAUSED: // ret = OH_AVPlayer_Play(player); // Call OH_AVPlayer_Play() again to start playback. // if (ret != AV_ERR_OK) { -// // Handle the exception. +// // Handle exceptions. // } break; case AV_STOPPED: ret = OH_AVPlayer_Release(player); // Call OH_AVPlayer_Reset() to reset the AVPlayer state. if (ret != AV_ERR_OK) { - // Handle the exception. + // Handle exceptions. } break; case AV_COMPLETED: ret = OH_AVPlayer_Stop(player);// Call OH_AVPlayer_Stop() to stop the playback. if (ret != AV_ERR_OK) { - // Handle the exception. + // Handle exceptions. } break; default: @@ -309,7 +308,7 @@ void OHAVPlayerOnErrorCallback(OH_AVPlayer *player, int32_t errorCode, const cha return; } demoNdkPlayer->errorCode = errorCode; - // do something + // Do something. } // Describe the mapped play method in the index.d.ts file and pass in a parameter of the string type. @@ -325,26 +324,26 @@ static napi_value Play(napi_env env, napi_callback_info info) // Obtain the parameter type. napi_valuetype stringType; if (napi_ok != napi_typeof(env, args[0], &stringType)) { - // Handle the exception. + // Handle exceptions. return nullptr; } // Verify the parameter. if (napi_null == stringType) { - // Handle the exception. + // Handle exceptions. return nullptr; } // Obtain the length of the passed-in string. size_t length = 0; if (napi_ok != napi_get_value_string_utf8(env, args[0], nullptr, 0, &length)) { - // Handle the exception. + // Handle exceptions. return nullptr; } // If "" is passed in, the result is directly returned. if (length == 0) { - // Handle the exception. + // Handle exceptions. return nullptr; } @@ -353,7 +352,7 @@ static napi_value Play(napi_env env, napi_callback_info info) if (napi_ok != napi_get_value_string_utf8(env, args[0], url, length + 1, &length)) { delete[] url; url = nullptr; - // Handle the exception. + // Handle exceptions. return nullptr; } @@ -372,23 +371,23 @@ static napi_value Play(napi_env env, napi_callback_info info) LOG("OH_AVPlayer_SetPlayerOnErrorCallback ret:%d", ret); if (ret != AV_ERR_OK) { - // Handle the exception. + // Handle exceptions. } ret = OH_AVPlayer_SetURLSource(player, url); // Set the URL. if (ret != AV_ERR_OK) { - // Handle the exception. + // Handle exceptions. } // Set the audio stream type. OH_AudioStream_Usage streamUsage = OH_AudioStream_Usage::AUDIOSTREAM_USAGE_UNKNOWN; ret = OH_AVPlayer_SetAudioRendererInfo(player, streamUsage); if (ret != AV_ERR_OK) { - // Handle the exception. + // Handle exceptions. } // Set the audio interruption mode. OH_AudioInterrupt_Mode interruptMode = OH_AudioInterrupt_Mode::AUDIOSTREAM_INTERRUPT_MODE_INDEPENDENT; ret = OH_AVPlayer_SetAudioInterruptMode(player, interruptMode); if (ret != AV_ERR_OK) { - // Handle the exception. + // Handle exceptions. } napi_value value; napi_create_int32(env, 0, &value); diff --git a/en/application-dev/media/media/using-ndk-avrecorder-for-audio-recording.md b/en/application-dev/media/media/using-ndk-avrecorder-for-audio-recording.md new file mode 100644 index 0000000000000000000000000000000000000000..cc56fc04b65bd58c8289613a0e9b6ceab74948a0 --- /dev/null +++ b/en/application-dev/media/media/using-ndk-avrecorder-for-audio-recording.md @@ -0,0 +1,495 @@ +# Using AVRecorder to Record Audio (C/C++) + +You can use the AVRecorder to develop the audio or video recording service. The AVRecorder supports audio capture, audio encoding, video encoding, audio encapsulation, and video encapsulation. It is applicable to simple audio/video recording scenarios and can be used to generate local media files directly. + +In this topic, you will learn how to use the AVRecorder to complete the process of starting, pausing, resuming, and stopping audio recording. + +During application development, you can use the **state** property of the AVRecorder to obtain the AVRecorder state or call **OH_AVRecorder_SetStateCallback** to listen for state changes. Your code must meet the state machine requirements. For example, **OH_AVRecorder_Pause()** is called only when the AVRecorder is in the **started** state, and **OH_AVRecorder_Resume()** is called only when it is in the **paused** state. + +**Figure 1** Recording state transition + +![Recording state change](figures/recording-status-change-ndk.png) + +For details about the states, see [AVRecorderState](../../reference/apis-media-kit/js-apis-media.md#avrecorderstate9). + + +## Requesting Permissions + +Before your development, configure the following permissions for your application. +- To use the microphone, request the ohos.permission.MICROPHONE permission. For details about how to request user authorization, see [Requesting User Authorization](../../security/AccessToken/request-user-authorization.md). +- To read and save audio files, preferentially use [AudioViewPicker](../../reference/apis-core-file-kit/js-apis-file-picker.md#audioviewpicker). + +> **NOTE** +> +> To clone, back up, or synchronize audio files in users' public directory, request the ohos.permission.READ_AUDIO and ohos.permission.WRITE_AUDIO permissions for reading and writing audio files. For details, see [Requesting Restricted Permissions](../../security/AccessToken/declare-permissions-in-acl.md). + +## How to Develop + +> **NOTE** +> +> To record only audio, you do not need to set video-related parameters such as **videoFrameWidth** and **videoFrameHeight**. Similarly, to record only videos, you do not need to set audio-related parameters such as **audioBitrate** and **audioChannels**. + +Read [AVRecorder](../../reference/apis-media-kit/_a_v_recorder.md) for the API reference. + +1. Create an AVRecorder instance. The AVRecorder is in the **idle** state. + + ```C++ + #include + #include + + static struct OH_AVRecorder *g_avRecorder = {}; + g_avRecorder = OH_AVRecorder_Create(); + ``` + +2. Set the events to listen for. + | Event Type| Description| + | -------- | -------- | + | OnStateChange | Listens for AVRecorder state changes.| + | OnError | Listens for AVRecorder errors.| + | OnUri | Listens for media files generated by the AVRecorder.| + + ```C++ + // Set a callback to respond to state changes. + void OnStateChange(OH_AVRecorder *recorder, OH_AVRecorder_State state, + OH_AVRecorder_StateChangeReason reason, void *userData) { + (void)recorder; + (void)userData; + + // Convert reason into a string. + const char *reasonStr = (reason == AVRECORDER_USER) ? "USER" : (reason == AVRECORDER_BACKGROUND) ? "BACKGROUND" : "UNKNOWN"; + + if (state == AVRECORDER_IDLE) { + OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange IDLE, reason: %{public}s", reasonStr); + // Process the state change. + } + if (state == AVRECORDER_PREPARED) { + OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange PREPARED, reason: %{public}s", reasonStr); + // Process the state change. + } + if (state == AVRECORDER_STARTED) { + OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange STARTED, reason: %{public}s", reasonStr); + // Process the state change. + } + if (state == AVRECORDER_PAUSED) { + OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange PAUSED, reason: %{public}s", reasonStr); + // Process the state change. + } + if (state == AVRECORDER_STOPPED) { + OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange STOPPED, reason: %{public}s", reasonStr); + // Process the state change. + } + if (state == AVRECORDER_RELEASED) { + OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange RELEASED, reason: %{public}s", reasonStr); + // Process the state change. + } + if (state == AVRECORDER_ERROR) { + OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange ERROR, reason: %{public}s", reasonStr); + // Process the state change. + } + } + + // Set an error callback. + void OnError(OH_AVRecorder *recorder, int32_t errorCode, const char *errorMsg, void *userData) + { + (void)recorder; + (void)userData; + OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnError errorCode: %{public}d, error message: %{public}s", + errorCode, errorMsg); + } + + // Set a callback to listen for the generation of media files. (This operation is required when AUTO_CREATE is selected.) + void OnUri(OH_AVRecorder *recorder, OH_MediaAsset *asset, void *userData) + { + (void)recorder; + (void)userData; + OH_LOG_INFO(LOG_APP, "==NDKDemo== OnUri in!"); + if (asset != nullptr) { + auto changeRequest = OH_MediaAssetChangeRequest_Create(asset); + if (changeRequest == nullptr) { + OH_LOG_ERROR(LOG_APP, "==NDKDemo== changeRequest is null!"); + return; + } + MediaLibrary_ImageFileType imageFileType = MEDIA_LIBRARY_IMAGE_JPEG; // Available video interfaces are provided by the media library. + uint32_t result = OH_MediaAssetChangeRequest_SaveCameraPhoto(changeRequest, imageFileType); + OH_LOG_INFO(LOG_APP, "result of OH_MediaAssetChangeRequest_SaveCameraPhoto: %d", result); + + uint32_t resultChange = OH_MediaAccessHelper_ApplyChanges(changeRequest); + OH_LOG_INFO(LOG_APP, "result of OH_MediaAccessHelper_ApplyChanges: %d", resultChange); + + OH_MediaAsset_Release(asset); + OH_MediaAssetChangeRequest_Release(changeRequest); + } else { + OH_LOG_ERROR(LOG_APP, "Received null media asset!"); + } + OH_LOG_INFO(LOG_APP, "==NDKDemo== OnUri out!"); + } + ``` + +3. Set video recording parameters and call **OH_AVRecorder_Prepare()**. The AVRecorder enters the **prepared** state. + + > **NOTE** + > + > Pay attention to the following when configuring parameters: + > + > - Before parameter configuration, ensure that you have gained the required permissions. For details, see [Requesting Permissions](#requesting-permissions). + > + > - In pure video recording scenarios, set only video-related parameters in **OH_AVRecorder_Config** of **OH_AVRecorder_Prepare()**. + > + > - The recording output URL (URL in **avConfig** in the sample code) must be in the format of fd://xx (where xx indicates a file descriptor). You must call the basic file operation APIs to implement access to the application file. For details, see [Accessing Application Files](../../file-management/native-fileio-guidelines.md). + + ```C++ + void SetConfig(OH_AVRecorder_Config &config) + { + config.audioSourceType = AVRECORDER_MIC; + + // Set media properties. + config.profile.audioBitrate = 100000; + config.profile.audioChannels = 2; + config.profile.audioCodec = AVRECORDER_AUDIO_AAC; + config.profile.audioSampleRate = 48000; + + config.profile.fileFormat = AVRECORDER_CFT_MPEG_4A; + config.fileGenerationMode = AVRECORDER_APP_CREATE; + + config.metadata.location.latitude = 27.791863; + config.metadata.location.longitude = 64.574687; + } + + // Prepare for recording. + static napi_value PrepareAVRecorder(napi_env env, napi_callback_info info) + { + (void)info; + OH_LOG_INFO(LOG_APP, "==NDKDemo== PrepareAVRecorder in!"); + g_avRecorder = OH_AVRecorder_Create(); + OH_LOG_INFO(LOG_APP, "==NDKDemo== AVRecorder Create ok! g_avRecorder: %{public}p", g_avRecorder); + if (g_avRecorder == nullptr) { + OH_LOG_ERROR(LOG_APP, "==NDKDemo== AVRecorder Create failed!"); + } + OH_AVRecorder_Config *config = new OH_AVRecorder_Config(); + + SetConfig(*config); + + // 1. Set the URL. (This operation is required when APP_CREATE is selected.) + const std::string AVREORDER_ROOT = "/data/storage/el2/base/files/"; + int32_t outputFd = open((AVREORDER_ROOT + "avrecorder01.mp3").c_str(), O_RDWR | O_CREAT, 0777); // Set the file name. + std::string fileUrl = "fd://" + std::to_string(outputFd); + config->url = const_cast(fileUrl.c_str()); + OH_LOG_INFO(LOG_APP, "config.url is: %s", const_cast(fileUrl.c_str())); + + // 2. Set the callbacks. + // State callback. + OH_AVRecorder_SetStateCallback(g_avRecorder, OnStateChange, nullptr); + + // Callback triggered when an error occurs. + OH_AVRecorder_SetErrorCallback(g_avRecorder, OnError, nullptr); + + // Callback triggered when a media file is generated. (This operation is required when AUTO_CREATE is selected.) + OH_LOG_INFO(LOG_APP, "==NDKDemo== OH_AVRecorder_SetUriCallback in!"); + OH_AVErrCode ret = OH_AVRecorder_SetUriCallback(g_avRecorder, OnUri, nullptr); + OH_LOG_INFO(LOG_APP, "==NDKDemo== OH_AVRecorder_SetUriCallback out!"); + if (ret == AV_ERR_OK) { + OH_LOG_INFO(LOG_APP, "==NDKDemo== OH_AVRecorder_SetUriCallback succeed!"); + } else { + OH_LOG_ERROR(LOG_APP, "==NDKDemo== Failed to set URI callback, error code: %d", ret); + } + + // 3. Call the prepare API. + int result = OH_AVRecorder_Prepare(g_avRecorder, config); + if (result != AV_ERR_OK) { + OH_LOG_ERROR(LOG_APP, "==NDKDemo== AVRecorder Prepare failed %{public}d", result); + } + + napi_value res; + napi_create_int32(env, result, &res); + return res; + } + ``` + +4. Call **OH_AVRecorder_Start()** to start recording. The AVRecorder enters the **started** state. + + ```C++ + OH_AVRecorder_Start(g_avRecorder); + ``` + +5. Call **OH_AVRecorder_Pause()** to pause recording. The AVRecorder enters the **paused** state. In addition, pause data input, + + ```C++ + OH_AVRecorder_Pause(g_avRecorder); + ``` + +6. Call **OH_AVRecorder_Resume()** to resume recording. The AVRecorder enters the **started** state again. + + ```C++ + OH_AVRecorder_Resume(g_avRecorder); + ``` + +7. Call **OH_AVRecorder_Stop()** to stop recording. The AVRecorder enters the **stopped** state. + + ```C++ + OH_AVRecorder_Stop(g_avRecorder); + ``` + +8. Call **OH_AVRecorder_Reset()** to reset the resources. The AVRecorder enters the **idle** state. In this case, you can reconfigure the recording parameters. + + ```C++ + OH_AVRecorder_Reset(g_avRecorder); + ``` + +9. Call **OH_AVRecorder_Release()** to switch the AVRecorder to the **released** state. Now your application exits the recording. + + ```C++ + OH_AVRecorder_Release(g_avRecorder); + ``` + + +## Sample Code + +Refer to the sample code below to complete the process of creating a recorder instance, preparing for, starting, pausing, resuming, and stopping recording, resetting the recording state, and releasing the recording resources. + + ```C++ + #include + #include "hilog/log.h" + #include + #include + #include + #include + #include + + static struct OH_AVRecorder *g_avRecorder = {}; + + // Set a callback to respond to state changes. + void OnStateChange(OH_AVRecorder *recorder, OH_AVRecorder_State state, + OH_AVRecorder_StateChangeReason reason, void *userData) { + (void)recorder; + (void)userData; + + // Convert reason into a string. + const char *reasonStr = (reason == AVRECORDER_USER) ? "USER" : (reason == AVRECORDER_BACKGROUND) ? "BACKGROUND" : "UNKNOWN"; + + if (state == AVRECORDER_IDLE) { + OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange IDLE, reason: %{public}s", reasonStr); + // Process the state change. + } + if (state == AVRECORDER_PREPARED) { + OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange PREPARED, reason: %{public}s", reasonStr); + // Process the state change. + } + if (state == AVRECORDER_STARTED) { + OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange STARTED, reason: %{public}s", reasonStr); + // Process the state change. + } + if (state == AVRECORDER_PAUSED) { + OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange PAUSED, reason: %{public}s", reasonStr); + // Process the state change. + } + if (state == AVRECORDER_STOPPED) { + OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange STOPPED, reason: %{public}s", reasonStr); + // Process the state change. + } + if (state == AVRECORDER_RELEASED) { + OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange RELEASED, reason: %{public}s", reasonStr); + // Process the state change. + } + if (state == AVRECORDER_ERROR) { + OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange ERROR, reason: %{public}s", reasonStr); + // Process the state change. + } + } + + // Set an error callback. + void OnError(OH_AVRecorder *recorder, int32_t errorCode, const char *errorMsg, void *userData) + { + (void)recorder; + (void)userData; + OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnError errorCode: %{public}d, error message: %{public}s", + errorCode, errorMsg); + } + + // Set a callback to listen for the generation of media files. (This operation is required when AUTO_CREATE is selected.) + void OnUri(OH_AVRecorder *recorder, OH_MediaAsset *asset, void *userData) + { + (void)recorder; + (void)userData; + OH_LOG_INFO(LOG_APP, "==NDKDemo== OnUri in!"); + if (asset != nullptr) { + auto changeRequest = OH_MediaAssetChangeRequest_Create(asset); + if (changeRequest == nullptr) { + OH_LOG_ERROR(LOG_APP, "==NDKDemo== changeRequest is null!"); + return; + } + MediaLibrary_ImageFileType imageFileType = MEDIA_LIBRARY_IMAGE_JPEG; // Available video interfaces are provided by the media library. + uint32_t result = OH_MediaAssetChangeRequest_SaveCameraPhoto(changeRequest, imageFileType); + OH_LOG_INFO(LOG_APP, "result of OH_MediaAssetChangeRequest_SaveCameraPhoto: %d", result); + + uint32_t resultChange = OH_MediaAccessHelper_ApplyChanges(changeRequest); + OH_LOG_INFO(LOG_APP, "result of OH_MediaAccessHelper_ApplyChanges: %d", resultChange); + + OH_MediaAsset_Release(asset); + OH_MediaAssetChangeRequest_Release(changeRequest); + } else { + OH_LOG_ERROR(LOG_APP, "Received null media asset!"); + } + OH_LOG_INFO(LOG_APP, "==NDKDemo== OnUri out!"); + } + + void SetConfig(OH_AVRecorder_Config &config) + { + config.audioSourceType = AVRECORDER_MIC; + + // Set media properties. + config.profile.audioBitrate = 96000; + config.profile.audioChannels = 2; + config.profile.audioCodec = AVRECORDER_AUDIO_AAC; + config.profile.audioSampleRate = 48000; + + config.profile.fileFormat = AVRECORDER_CFT_MPEG_4; + config.fileGenerationMode = AVRECORDER_APP_CREATE; + + config.metadata.location.latitude = 27.791863; + config.metadata.location.longitude = 64.574687; + } + + // 1. Prepare for recording. + static napi_value PrepareAVRecorder(napi_env env, napi_callback_info info) + { + (void)info; + OH_LOG_INFO(LOG_APP, "==NDKDemo== PrepareAVRecorder in!"); + g_avRecorder = OH_AVRecorder_Create(); + OH_LOG_INFO(LOG_APP, "==NDKDemo== AVRecorder Create ok! g_avRecorder: %{public}p", g_avRecorder); + if (g_avRecorder == nullptr) { + OH_LOG_ERROR(LOG_APP, "==NDKDemo== AVRecorder Create failed!"); + } + OH_AVRecorder_Config *config = new OH_AVRecorder_Config(); + + SetConfig(*config); + + // 1.1 Set the URL. (This operation is required when APP_CREATE is selected.) + const std::string AVREORDER_ROOT = "/data/storage/el2/base/files/"; + int32_t outputFd = open((AVREORDER_ROOT + "avrecorder01.mp3").c_str(), O_RDWR | O_CREAT, 0777); // Set the file name. + std::string fileUrl = "fd://" + std::to_string(outputFd); + config->url = const_cast(fileUrl.c_str()); + OH_LOG_INFO(LOG_APP, "config.url is: %s", const_cast(fileUrl.c_str())); + + // 1.2 Set the callbacks. + // State callback. + OH_AVRecorder_SetStateCallback(g_avRecorder, OnStateChange, nullptr); + + // Callback triggered when an error occurs. + OH_AVRecorder_SetErrorCallback(g_avRecorder, OnError, nullptr); + + // Callback triggered when a media file is generated. (This operation is required when AUTO_CREATE is selected.) + OH_AVErrCode ret = OH_AVRecorder_SetUriCallback(g_avRecorder, OnUri, nullptr); + if (ret == AV_ERR_OK) { + OH_LOG_INFO(LOG_APP, "==NDKDemo== OH_AVRecorder_SetUriCallback succeed!"); + } else { + OH_LOG_ERROR(LOG_APP, "==NDKDemo== Failed to set URI callback, error code: %d", ret); + } + + // 1.3 Call the prepare API. + int result = OH_AVRecorder_Prepare(g_avRecorder, config); + if (result != AV_ERR_OK) { + OH_LOG_ERROR(LOG_APP, "==NDKDemo== AVRecorder Prepare failed %{public}d", result); + } + + napi_value res; + napi_create_int32(env, result, &res); + return res; + } + + // 2. Start recording. + static napi_value StartAVRecorder(napi_env env, napi_callback_info info) + { + (void)info; + OH_LOG_INFO(LOG_APP, "==NDKDemo== g_avRecorder start: %{public}p", g_avRecorder); + int result = OH_AVRecorder_Start(g_avRecorder); + if (result != AV_ERR_OK) { + OH_LOG_ERROR(LOG_APP, "==NDKDemo== AVRecorder Start failed %{public}d", result); + } + napi_value res; + napi_create_int32(env, result, &res); + return res; + } + + // 3. Pause recording. + static napi_value PauseAVRecorder(napi_env env, napi_callback_info info) + { + (void)info; + int result = OH_AVRecorder_Pause(g_avRecorder); + if (result != AV_ERR_OK) { + OH_LOG_ERROR(LOG_APP, "==NDKDemo== AVRecorder Pause failed %{public}d", result); + } + napi_value res; + napi_create_int32(env, result, &res); + return res; + } + + // 4. Resume recording. + static napi_value ResumeAVRecorder(napi_env env, napi_callback_info info) + { + (void)info; + int result = OH_AVRecorder_Resume(g_avRecorder); + if (result != AV_ERR_OK) { + OH_LOG_ERROR(LOG_APP, "==NDKDemo== AVRecorder Resume failed %{public}d", result); + } + napi_value res; + napi_create_int32(env, result, &res); + return res; + } + + // 5. Stop recording. + static napi_value StopAVRecorder(napi_env env, napi_callback_info info) + { + (void)info; + int result = OH_AVRecorder_Stop(g_avRecorder); + if (result != AV_ERR_OK) { + OH_LOG_ERROR(LOG_APP, "==NDKDemo== AVRecorder Stop failed %{public}d", result); + } + napi_value res; + napi_create_int32(env, result, &res); + return res; + } + + // 6. Reset the recording state. + static napi_value ResetAVRecorder(napi_env env, napi_callback_info info) + { + (void)info; + // Check whether g_avRecorder is valid. + if (g_avRecorder == nullptr) { + OH_LOG_ERROR(LOG_APP, "==NDKDemo== g_avRecorder is nullptr!"); + napi_value res; + napi_create_int32(env, AV_ERR_INVALID_VAL, &res); + return res; + } + + int result = OH_AVRecorder_Reset(g_avRecorder); + if (result != AV_ERR_OK) { + OH_LOG_ERROR(LOG_APP, "==NDKDemo== AVRecorder Reset failed %{public}d", result); + } + napi_value res; + napi_create_int32(env, result, &res); + return res; + } + + // 7. Release recording resources. + static napi_value ReleaseAVRecorder(napi_env env, napi_callback_info info) + { + (void)info; + // Check whether g_avRecorder is valid. + if (g_avRecorder == nullptr) { + OH_LOG_ERROR(LOG_APP, "==NDKDemo== g_avRecorder is nullptr!"); + napi_value res; + napi_create_int32(env, AV_ERR_INVALID_VAL, &res); + return res; + } + + int result = OH_AVRecorder_Release(g_avRecorder); + g_avRecorder = nullptr; // After recording resources are released, the g_avRecorder pointer must be explicitly set to null. + + if (result != AV_ERR_OK) { + OH_LOG_ERROR(LOG_APP, "==NDKDemo== AVRecorder Release failed %{public}d", result); + } + napi_value res; + napi_create_int32(env, result, &res); + return res; + } + ``` diff --git a/en/application-dev/media/media/using-ndk-avrecorder-for-video-recording.md b/en/application-dev/media/media/using-ndk-avrecorder-for-video-recording.md new file mode 100644 index 0000000000000000000000000000000000000000..d7f823e35087f5c86edfb1792f00ce8db2559af1 --- /dev/null +++ b/en/application-dev/media/media/using-ndk-avrecorder-for-video-recording.md @@ -0,0 +1,582 @@ +# Using AVRecorder to Record Videos (C/C++) + +You can use the AVRecorder to develop the audio and video recording service. The AVRecorder supports audio capture, audio encoding, video encoding, audio encapsulation, and video encapsulation. It is applicable to simple video recording scenarios and can be used to generate local media files directly. + +In this topic, you will learn how to use the AVRecorder to complete the process of starting, pausing, resuming, and stopping video recording. + +During application development, you can use the **state** property of the AVRecorder to obtain the AVRecorder state or call **OH_AVRecorder_SetStateCallback** to listen for state changes. Your code must meet the state machine requirements. For example, **OH_AVRecorder_Pause()** is called only when the AVRecorder is in the **started** state, and **OH_AVRecorder_Resume()** is called only when it is in the **paused** state. + +**Figure 1** Recording state transition + +![Recording state change](figures/recording-status-change-ndk.png) + +For details about the states, see [AVRecorderState](../../reference/apis-media-kit/js-apis-media.md#avrecorderstate9). + + +## Requesting Permissions + +Before your development, configure the following permissions for your application. +- To use the microphone, request the ohos.permission.MICROPHONE permission. For details about how to request user authorization, see [Requesting User Authorization](../../security/AccessToken/request-user-authorization.md). +- To use the camera for photo capture, request the ohos.permission.CAMERA permission. For details about how to request user authorization, see [Requesting User Authorization](../../security/AccessToken/request-user-authorization.md). +- To read images or videos from Gallery, preferentially use the media library [Picker for access](../medialibrary/photoAccessHelper-photoviewpicker.md). +- To save images or videos to Gallery, preferentially use the [security component for storage](../medialibrary/photoAccessHelper-savebutton.md). + +> **NOTE** +> +> To clone, back up, or synchronize images and videos in users' public directory, request the ohos.permission.READ_IMAGEVIDEO and ohos.permission.WRITE_IMAGEVIDEO permissions for reading and writing audio files. For details, see [Requesting Restricted Permissions](../../security/AccessToken/declare-permissions-in-acl.md). + + +## How to Develop + +> **NOTE** +> +> The AVRecorder only processes video data. To complete video recording, it must work with the video data collection module, which transfers the captured video data to the AVRecorder for data processing through the surface. Currently, the commonly used data collection module is the camera module. For details, see [Camera Recording](../camera/native-camera-recording.md). +> +> For details about how to create and save a file, see [Accessing Application Files](../../file-management/app-file-access.md). By default, files are saved in the sandbox path of the application. To save them to Gallery, use the [security components](../medialibrary/photoAccessHelper-savebutton.md). + + +Read [AVRecorder](../../reference/apis-media-kit/_a_v_recorder.md) for the API reference. + +1. Create an AVRecorder instance. The AVRecorder is in the **idle** state. + + ```C++ + #include + #include + + static struct OH_AVRecorder *g_avRecorder = {}; + g_avRecorder = OH_AVRecorder_Create(); + ``` + +2. Set the events to listen for. + | Event Type| Description| + | -------- | -------- | + | OnStateChange | Listens for AVRecorder state changes.| + | OnError | Listens for AVRecorder errors.| + | OnUri | Listens for media files generated by the AVRecorder.| + + ```C++ + // Set a callback to respond to state changes. + void OnStateChange(OH_AVRecorder *recorder, OH_AVRecorder_State state, + OH_AVRecorder_StateChangeReason reason, void *userData) { + (void)recorder; + (void)userData; + + // Convert reason into a string. + const char *reasonStr = (reason == AVRECORDER_USER) ? "USER" : (reason == AVRECORDER_BACKGROUND) ? "BACKGROUND" : "UNKNOWN"; + + if (state == IDLE) { + OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange IDLE, reason: %{public}s", reasonStr); + // Process the state change. + } + if (state == PREPARED) { + OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange PREPARED, reason: %{public}s", reasonStr); + // Process the state change. + } + if (state == STARTED) { + OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange STARTED, reason: %{public}s", reasonStr); + // Process the state change. + } + if (state == PAUSED) { + OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange PAUSED, reason: %{public}s", reasonStr); + // Process the state change. + } + if (state == STOPPED) { + OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange STOPPED, reason: %{public}s", reasonStr); + // Process the state change. + } + if (state == RELEASED) { + OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange RELEASED, reason: %{public}s", reasonStr); + // Process the state change. + } + if (state == ERROR) { + OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange ERROR, reason: %{public}s", reasonStr); + // Process the state change. + } + } + + // Set an error callback. + void OnError(OH_AVRecorder *recorder, int32_t errorCode, const char *errorMsg, void *userData) { + (void)recorder; + (void)userData; + OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnError errorCode: %{public}d, error message: %{public}s", + errorCode, errorMsg); + } + + // Set a callback to listen for the generation of media files. (This operation is required when AUTO_CREATE is selected.) + void OnUri(OH_AVRecorder *recorder, OH_MediaAsset *asset, void *userData) { + (void)recorder; + (void)userData; + if (asset != nullptr) { + auto changeRequest = OH_MediaAssetChangeRequest_Create(asset); + if (changeRequest == nullptr) { + OH_LOG_ERROR(LOG_APP, "==NDKDemo== changeRequest is null!"); + return; + } + MediaLibrary_ImageFileType imageFileType = MEDIA_LIBRARY_IMAGE_JPEG; // Available video interfaces are provided by the media library. + uint32_t result = OH_MediaAssetChangeRequest_SaveCameraPhoto(changeRequest, imageFileType); + OH_LOG_INFO(LOG_APP, "result of OH_MediaAssetChangeRequest_SaveCameraPhoto: %d", result); + + uint32_t resultChange = OH_MediaAccessHelper_ApplyChanges(changeRequest); + OH_LOG_INFO(LOG_APP, "result of OH_MediaAccessHelper_ApplyChanges: %d", resultChange); + + OH_MediaAsset_Release(asset); + OH_MediaAssetChangeRequest_Release(changeRequest); + } else { + OH_LOG_ERROR(LOG_APP, "Received null media asset!"); + } + } + ``` + +3. Set video recording parameters and call **OH_AVRecorder_Prepare()**. The AVRecorder enters the **prepared** state. + + > **NOTE** + > + > Pay attention to the following when configuring parameters: + > + > - Before parameter configuration, ensure that you have gained the required permissions. For details, see [Requesting Permissions](#requesting-permissions). + > + > - In pure video recording scenarios, set only video-related parameters in **OH_AVRecorder_Config** of **OH_AVRecorder_Prepare()**. + > + > - The [recording specifications](media-kit-intro.md#supported-formats) in use must be those supported. The video bit rate, resolution, and frame rate are subject to the ranges supported by the hardware device. + > + > - The recording output URL (URL in **OH_AVRecorder_Config** in the sample code) must be in the format of fd://xx (where xx indicates a file descriptor). You must call the basic file operation APIs to implement access to the application file. For details, see [Accessing Application Files](../../file-management/native-fileio-guidelines.md). + + ```C++ + void SetConfig(OH_AVRecorder_Config &config) + { + config.audioSourceType = AVRECORDER_MIC; + config.videoSourceType = AVRECORDER_SURFACE_ES; + + // Set media properties. + config.profile.audioBitrate = 96000; + config.profile.audioChannels = 2; + config.profile.audioCodec = AVRECORDER_AUDIO_AAC; + config.profile.audioSampleRate = 48000; + + config.profile.videoBitrate = 2000000; + config.profile.videoFrameWidth = 1280; + config.profile.videoFrameHeight = 720; + config.profile.videoFrameRate = 30; + config.profile.videoCodec = AVRECORDER_VIDEO_AVC; + config.profile.isHdr = false; + config.profile.enableTemporalScale = false; + + config.profile.fileFormat = AVRECORDER_CFT_MPEG_4; + config.fileGenerationMode = AVRECORDER_APP_CREATE; + + config.metadata.videoOrientation = (char*)malloc(2); + if (config.metadata.videoOrientation != nullptr) { + strcpy(config.metadata.videoOrientation, "0"); // Video rotation angle, which can be 0, 90, 180, or 270. + } + OH_LOG_INFO(LOG_APP, "==NDKDemo== videoOrientation: %{public}s", config.metadata.videoOrientation); + + config.metadata.location.latitude = 27.791863; + config.metadata.location.longitude = 64.574687; + } + + // Prepare for recording. + static napi_value PrepareAVRecorder(napi_env env, napi_callback_info info) + { + (void)info; + OH_LOG_INFO(LOG_APP, "==NDKDemo== PrepareAVRecorder in!"); + g_avRecorder = OH_AVRecorder_Create(); + OH_LOG_INFO(LOG_APP, "==NDKDemo== AVRecorder Create ok! g_avRecorder: %{public}p", g_avRecorder); + if (g_avRecorder == nullptr) { + OH_LOG_ERROR(LOG_APP, "==NDKDemo== AVRecorder Create failed!"); + } + OH_AVRecorder_Config *config = new OH_AVRecorder_Config(); + + SetConfig(*config); + + // 1. Set the URL. (This operation is required when APP_CREATE is selected.) + const std::string AVREORDER_ROOT = "/data/storage/el2/base/files/"; + int32_t outputFd = open((AVREORDER_ROOT + "avrecorder01.mp4").c_str(), O_RDWR | O_CREAT, 0777); // Set the file name. + std::string fileUrl = "fd://" + std::to_string(outputFd); + config->url = const_cast(fileUrl.c_str()); + OH_LOG_INFO(LOG_APP, "config.url is: %s", const_cast(fileUrl.c_str())); + + // 2. Set the callbacks. + // Callback triggered when the state changes. + OH_AVRecorder_SetStateCallback(g_avRecorder, OnStateChange, nullptr); + + // Callback triggered when an error occurs. + OH_AVRecorder_SetErrorCallback(g_avRecorder, OnError, nullptr); + + // Callback triggered when a media file is generated. (This operation is required when AUTO_CREATE is selected.) + OH_AVErrCode ret = OH_AVRecorder_SetUriCallback(g_avRecorder, OnUri, nullptr); + if (ret == AV_ERR_OK) { + OH_LOG_INFO(LOG_APP, "==NDKDemo== OH_AVRecorder_SetUriCallback succeed!"); + } else { + OH_LOG_ERROR(LOG_APP, "==NDKDemo== Failed to set URI callback, error code: %d", ret); + } + + // 3. Call the prepare API. + int result = OH_AVRecorder_Prepare(g_avRecorder, config); + if (result != AV_ERR_OK) { + OH_LOG_ERROR(LOG_APP, "==NDKDemo== AVRecorder Prepare failed %{public}d", result); + } + + napi_value res; + napi_create_int32(env, result, &res); + return res; + } + ``` + +4. Obtain the surface ID required for video recording and initialize the video data input source. This step is performed in the video data collection module. For the camera module, you need to create a Camera instance, obtain the camera list, create a camera input stream, and create a video output stream. For details, see [Video Recording](../camera/native-camera-recording.md). + + Call **getInputSurface()**. The returned surface ID is transferred to the video data collection module, which is generally the camera module. The following sample code demonstrates only the procedure for obtaining the surface ID. + + The video data collection module obtains the surface based on the surface ID and transmits video data to the AVRecorder through the surface. Then the AVRecorder processes the video data. + + ```C++ + // Obtain the surface ID. + OHNativeWindow *window = nullptr; + int resultCode = OH_AVRecorder_GetInputSurface(g_avRecorder, &window); + uint64_t surfaceId = 0; + OH_NativeWindow_GetSurfaceId(window, &surfaceId); + ``` + +5. Initialize the video data input source. + + This step is performed in the video data collection module. For the camera module, you need to create a Camera instance, obtain the camera list, create a camera input stream, and create a video output stream. For details, see [Video Recording](../camera/native-camera-recording.md). + +6. Start recording. + + Start the input source to input video data, for example, by calling **OH_VideoOutput_Start()** of the camera module. Then call **OH_AVRecorder_Start()** to switch the AVRecorder to the **started** state. + + ``` + OH_AVRecorder_Start(g_avRecorder); + ``` +7. Call **OH_AVRecorder_Pause()** to pause recording. The AVRecorder enters the **paused** state. In addition, pause data input, for example, by calling **OH_VideoOutput_Stop()** of the camera module. + ``` + OH_AVRecorder_Pause(g_avRecorder); + ``` +8. Call **OH_AVRecorder_Resume()** to resume recording. The AVRecorder enters the **started** state again. + ``` + OH_AVRecorder_Resume(g_avRecorder); + ``` +9. Call **OH_AVRecorder_Stop()** to stop recording. The AVRecorder enters the **stopped** state again. In addition, stop camera recording. + ``` + OH_AVRecorder_Stop(g_avRecorder); + ``` +10. Call **OH_AVRecorder_Reset()** to reset the resources. The AVRecorder enters the **idle** state. In this case, you can reconfigure the recording parameters. + + ``` + OH_AVRecorder_Reset(g_avRecorder); + ``` + +11. Call **OH_AVRecorder_Release()** to release the resources. The AVRecorder enters the **released** state. In addition, release the video data input source resources (camera resources in this example). + + ``` + OH_AVRecorder_Release(g_avRecorder); + ``` + + +## Sample Code + +Refer to the sample code below to complete the process of creating a recorder instance, preparing for, starting, pausing, resuming, and stopping recording, resetting the recording state, and releasing the recording resources. + + ```C++ + #include + #include "hilog/log.h" + #include + #include + #include + #include + #include + + static struct OH_AVRecorder *g_avRecorder = {}; + + // Set a callback to respond to state changes. + void OnStateChange(OH_AVRecorder *recorder, OH_AVRecorder_State state, + OH_AVRecorder_StateChangeReason reason, void *userData) + { + (void)recorder; + (void)userData; + + // Convert reason into a string. + const char *reasonStr = (reason == AVRECORDER_USER) ? "USER" : + (reason == AVRECORDER_BACKGROUND) ? "BACKGROUND" : "UNKNOWN"; + + if (state == AVRECORDER_IDLE) { + OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange IDLE, reason: %{public}s", reasonStr); + // Process the state change. + } + if (state == AVRECORDER_PREPARED) { + OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange PREPARED, reason: %{public}s", reasonStr); + // Process the state change. + } + if (state == AVRECORDER_STARTED) { + OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange STARTED, reason: %{public}s", reasonStr); + // Process the state change. + } + if (state == AVRECORDER_PAUSED) { + OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange PAUSED, reason: %{public}s", reasonStr); + // Process the state change. + } + if (state == AVRECORDER_STOPPED) { + OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange STOPPED, reason: %{public}s", reasonStr); + // Process the state change. + } + if (state == AVRECORDER_RELEASED) { + OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange RELEASED, reason: %{public}s", reasonStr); + // Process the state change. + } + if (state == AVRECORDER_ERROR) { + OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnStateChange ERROR, reason: %{public}s", reasonStr); + // Process the state change. + } + } + + // Set an error callback. + void OnError(OH_AVRecorder *recorder, int32_t errorCode, const char *errorMsg, void *userData) + { + (void)recorder; + (void)userData; + OH_LOG_INFO(LOG_APP, "==NDKDemo== Recorder OnError errorCode: %{public}d, error message: %{public}s", + errorCode, errorMsg); + } + + // Set a callback to listen for the generation of media files. (This operation is required when AUTO_CREATE is selected.) + void OnUri(OH_AVRecorder *recorder, OH_MediaAsset *asset, void *userData) + { + (void)recorder; + (void)userData; + OH_LOG_INFO(LOG_APP, "==NDKDemo== OnUri in!"); + if (asset != nullptr) { + auto changeRequest = OH_MediaAssetChangeRequest_Create(asset); + if (changeRequest == nullptr) { + OH_LOG_ERROR(LOG_APP, "==NDKDemo== changeRequest is null!"); + return; + } + MediaLibrary_ImageFileType imageFileType = MEDIA_LIBRARY_IMAGE_JPEG; // Available video interfaces are provided by the media library. + uint32_t result = OH_MediaAssetChangeRequest_SaveCameraPhoto(changeRequest, imageFileType); + OH_LOG_INFO(LOG_APP, "result of OH_MediaAssetChangeRequest_SaveCameraPhoto: %d", result); + + uint32_t resultChange = OH_MediaAccessHelper_ApplyChanges(changeRequest); + OH_LOG_INFO(LOG_APP, "result of OH_MediaAccessHelper_ApplyChanges: %d", resultChange); + + OH_MediaAsset_Release(asset); + OH_MediaAssetChangeRequest_Release(changeRequest); + } else { + OH_LOG_ERROR(LOG_APP, "Received null media asset!"); + } + OH_LOG_INFO(LOG_APP, "==NDKDemo== OnUri out!"); + } + + void SetConfig(OH_AVRecorder_Config &config) + { + config.audioSourceType = AVRECORDER_MIC; + config.videoSourceType = AVRECORDER_SURFACE_ES; + + // Set media properties. + config.profile.audioBitrate = 96000; + config.profile.audioChannels = 2; + config.profile.audioCodec = AVRECORDER_AUDIO_AAC; + config.profile.audioSampleRate = 48000; + + config.profile.videoBitrate = 2000000; + config.profile.videoFrameWidth = 1280; + config.profile.videoFrameHeight = 720; + config.profile.videoFrameRate = 30; + config.profile.videoCodec = AVRECORDER_VIDEO_AVC; + config.profile.isHdr = false; + config.profile.enableTemporalScale = false; + + config.profile.fileFormat = AVRECORDER_CFT_MPEG_4; + config.fileGenerationMode = AVRECORDER_APP_CREATE; + + config.metadata.videoOrientation = (char *)malloc(2); + if (config.metadata.videoOrientation != nullptr) { + strcpy(config.metadata.videoOrientation, "0"); // Video rotation angle, which can be 0, 90, 180, or 270. + } + OH_LOG_INFO(LOG_APP, "==NDKDemo== videoOrientation: %{public}s", config.metadata.videoOrientation); + + config.metadata.location.latitude = 27.791863; + config.metadata.location.longitude = 64.574687; + } + + // 1. Prepare for recording. + static napi_value PrepareAVRecorder(napi_env env, napi_callback_info info) + { + (void)info; + OH_LOG_INFO(LOG_APP, "==NDKDemo== PrepareAVRecorder in!"); + g_avRecorder = OH_AVRecorder_Create(); + OH_LOG_INFO(LOG_APP, "==NDKDemo== AVRecorder Create ok! g_avRecorder: %{public}p", g_avRecorder); + if (g_avRecorder == nullptr) { + OH_LOG_ERROR(LOG_APP, "==NDKDemo== AVRecorder Create failed!"); + } + OH_AVRecorder_Config *config = new OH_AVRecorder_Config(); + + SetConfig(*config); + + // 1.1 Set the URL. (This operation is required when APP_CREATE is selected.) + const std::string AVREORDER_ROOT = "/data/storage/el2/base/files/"; + int32_t outputFd = open((AVREORDER_ROOT + "avrecorder01.mp4").c_str(), O_RDWR | O_CREAT, 0777); // Set the file name. + std::string fileUrl = "fd://" + std::to_string(outputFd); + config->url = const_cast(fileUrl.c_str()); + + // 1.2 Set the callbacks. + // State callback. + OH_AVRecorder_SetStateCallback(g_avRecorder, OnStateChange, nullptr); + + // Callback triggered when an error occurs. + OH_AVRecorder_SetErrorCallback(g_avRecorder, OnError, nullptr); + + // Callback triggered when a media file is generated. (This operation is required when AUTO_CREATE is selected.) + OH_AVErrCode ret = OH_AVRecorder_SetUriCallback(g_avRecorder, OnUri, nullptr); + if (ret == AV_ERR_OK) { + OH_LOG_INFO(LOG_APP, "==NDKDemo== OH_AVRecorder_SetUriCallback succeed!"); + } else { + OH_LOG_ERROR(LOG_APP, "==NDKDemo== Failed to set URI callback, error code: %d", ret); + } + + // 1.3 Call the prepare API. + int result = OH_AVRecorder_Prepare(g_avRecorder, config); + if (result != AV_ERR_OK) { + OH_LOG_ERROR(LOG_APP, "==NDKDemo== AVRecorder Prepare failed %{public}d", result); + } + + napi_value res; + napi_create_int32(env, result, &res); + return res; + } + + // 2. Start the camera. + static napi_value PrepareCamera(napi_env env, napi_callback_info info) + { + OH_LOG_INFO(LOG_APP, "==NDKDemo== AVRecorder PrepareCamera"); + (void)info; + + // 2.1 Initialize the camera. + + size_t argc = 6; + napi_value args[6] = {nullptr}; + size_t typeLen = 0; + napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); + + int32_t focusMode; + napi_get_value_int32(env, args[0], &focusMode); + + uint32_t cameraDeviceIndex; + napi_get_value_uint32(env, args[1], &cameraDeviceIndex); + + uint32_t sceneMode; + napi_get_value_uint32(env, args[2], &sceneMode); + + char *previewId = nullptr; + napi_get_value_string_utf8(env, args[3], nullptr, 0, &typeLen); + previewId = new char[typeLen + 1]; + napi_get_value_string_utf8(env, args[3], previewId, typeLen + 1, &typeLen); + + char *photoId = nullptr; + napi_get_value_string_utf8(env, args[4], nullptr, 0, &typeLen); + photoId = new char[typeLen + 1]; + napi_get_value_string_utf8(env, args[4], photoId, typeLen + 1, &typeLen); + + uint32_t previewWidth; + napi_get_value_uint32(env, args[5], &previewWidth); + + int ret = OH_AVRecorder_PrepareCamera(g_avRecorder, cameraDeviceIndex, sceneMode, focusMode, previewId, photoId); + OH_LOG_INFO(LOG_APP, "==NDKDemo== OH_AVRecorder_PrepareCamera result: %d", ret); + napi_value result; + napi_create_int32(env, ret, &result); + return result; + } + + // 3. Start recording. + static napi_value StartAVRecorder(napi_env env, napi_callback_info info) + { + (void)info; + int result = OH_AVRecorder_Start(g_avRecorder); + if (result != AV_ERR_OK) { + OH_LOG_ERROR(LOG_APP, "==NDKDemo== AVRecorder Start failed %{public}d", result); + } + napi_value res; + napi_create_int32(env, result, &res); + return res; + } + + // 4. Pause recording. + static napi_value PauseAVRecorder(napi_env env, napi_callback_info info) + { + (void)info; + int result = OH_AVRecorder_Pause(g_avRecorder); + if (result != AV_ERR_OK) { + OH_LOG_ERROR(LOG_APP, "==NDKDemo== AVRecorder Pause failed %{public}d", result); + } + napi_value res; + napi_create_int32(env, result, &res); + return res; + } + + // 5. Resume recording. + static napi_value ResumeAVRecorder(napi_env env, napi_callback_info info) + { + (void)info; + int result = OH_AVRecorder_Resume(g_avRecorder); + if (result != AV_ERR_OK) { + OH_LOG_ERROR(LOG_APP, "==NDKDemo== AVRecorder Resume failed %{public}d", result); + } + napi_value res; + napi_create_int32(env, result, &res); + return res; + } + + // 6. Stop recording. + static napi_value StopAVRecorder(napi_env env, napi_callback_info info) + { + (void)info; + int result = OH_AVRecorder_Stop(g_avRecorder); + if (result != AV_ERR_OK) { + OH_LOG_ERROR(LOG_APP, "==NDKDemo== AVRecorder Stop failed %{public}d", result); + } + napi_value res; + napi_create_int32(env, result, &res); + return res; + } + + // 7. Reset the recording state. + static napi_value ResetAVRecorder(napi_env env, napi_callback_info info) + { + (void)info; + // Check whether g_avRecorder is valid. + if (g_avRecorder == nullptr) { + OH_LOG_ERROR(LOG_APP, "==NDKDemo== g_avRecorder is nullptr!"); + napi_value res; + napi_create_int32(env, AV_ERR_INVALID_VAL, &res); + return res; + } + + int result = OH_AVRecorder_Reset(g_avRecorder); + if (result != AV_ERR_OK) { + OH_LOG_ERROR(LOG_APP, "==NDKDemo== AVRecorder Reset failed %{public}d", result); + } + napi_value res; + napi_create_int32(env, result, &res); + return res; + } + + // 8. Release recording resources. + static napi_value ReleaseAVRecorder(napi_env env, napi_callback_info info) + { + (void)info; + // Check whether g_avRecorder is valid. + if (g_avRecorder == nullptr) { + OH_LOG_ERROR(LOG_APP, "==NDKDemo== g_avRecorder is nullptr!"); + napi_value res; + napi_create_int32(env, AV_ERR_INVALID_VAL, &res); + return res; + } + + int result = OH_AVRecorder_Release(g_avRecorder); + g_avRecorder = nullptr; // After recording resources are released, the g_avRecorder pointer must be explicitly set to null. + + if (result != AV_ERR_OK) { + OH_LOG_ERROR(LOG_APP, "==NDKDemo== AVRecorder Release failed %{public}d", result); + } + napi_value res; + napi_create_int32(env, result, &res); + return res; + } + ``` diff --git a/en/application-dev/media/media/using-soundpool-for-playback.md b/en/application-dev/media/media/using-soundpool-for-playback.md index 148c4690103dbd1a67d07daad24b6842489a5918..028b101bd575cce13051fd14d914709e248a7732 100644 --- a/en/application-dev/media/media/using-soundpool-for-playback.md +++ b/en/application-dev/media/media/using-soundpool-for-playback.md @@ -29,8 +29,8 @@ During application development, you must subscribe to playback state changes and // If the value of usage in audioRenderInfo is STREAM_USAGE_UNKNOWN, STREAM_USAGE_MUSIC, STREAM_USAGE_MOVIE, // or STREAM_USAGE_AUDIOBOOK, SoundPool plays a short sound in audio mixing mode, without interrupting the playback of other audio streams. let audioRendererInfo: audio.AudioRendererInfo = { - usage : audio.StreamUsage.STREAM_USAGE_MUSIC, - rendererFlags : 0 + usage: audio.StreamUsage.STREAM_USAGE_MUSIC, // Audio stream usage type: music. Set this parameter based on the service scenario. + rendererFlags: 0 // AudioRenderer flag. }; media.createSoundPool(5, audioRendererInfo).then((soundpool_: media.SoundPool) => { @@ -53,12 +53,19 @@ During application development, you must subscribe to playback state changes and }); ``` -3. Call **on('playFinished')** to listen for the completion of sound playing. +3. Call **on('playFinished')** or **on('playFinishedWithStreamId')** to listen for the completion of audio playback. + + When only **'playFinished'** or **'playFinishedWithStreamId'** is subscribed to, the registered callback is triggered when the audio playback is complete. + + When both **'playFinished'** and **'playFinishedWithStreamId'** are subscribed to, the **'playFinishedWithStreamId'** callback is triggered, but the **'playFinished'** callback is not triggered, when the audio playback is complete. ```ts soundPool.on('playFinished', () => { console.info("receive play finished message"); }); + soundPool.on('playFinishedWithStreamId', (streamId) => { + console.info("receive play finished message, streamId: " + streamId); + }); ``` 4. Call **on('error')** to listen for errors that may occur. @@ -228,8 +235,8 @@ let soundId: number = 0; // If the value of usage in audioRenderInfo is STREAM_USAGE_UNKNOWN, STREAM_USAGE_MUSIC, STREAM_USAGE_MOVIE, // or STREAM_USAGE_AUDIOBOOK, SoundPool plays a short sound in audio mixing mode, without interrupting the playback of other audio streams. let audioRendererInfo: audio.AudioRendererInfo = { - usage: audio.StreamUsage.STREAM_USAGE_MUSIC, - rendererFlags: 1 + usage: audio.StreamUsage.STREAM_USAGE_MUSIC, // Audio stream usage type: music. Set this parameter based on the service scenario. + rendererFlags: 1 // AudioRenderer flag. }; let playParameters: media.PlayParameters = { loop: 3, // The sound is played four times (three loops). @@ -261,7 +268,12 @@ function loadCallback() { } // Set the listener when the sound finishes playing. function finishPlayCallback() { - // Callback invoked when the sound finishes playing. + // Callback invoked when the audio playback is complete. You can register either 'playFinished' or 'playFinishedWithStreamId' as required. + // When both 'playFinished' and 'playFinishedWithStreamId' are registered, only the 'playFinishedWithStreamId' callback is triggered when the audio playback is complete. + soundPool.on('playFinishedWithStreamId', (streamId) => { + console.info("receive play finished message, streamId: " + streamId); + // The sound can be played again. + }) soundPool.on('playFinished', () => { console.info("receive play finished message"); // The sound can be played again. @@ -303,6 +315,7 @@ async function release() { // Unregister the listeners. function setOffCallback() { soundPool.off('loadComplete'); + soundPool.off('playFinishedWithStreamId'); soundPool.off('playFinished'); soundPool.off('error'); } diff --git a/en/application-dev/media/media/video-playback.md b/en/application-dev/media/media/video-playback.md index f1a08d963d377355b9fefedbd677c667341ea563..42219dfada1ce2a6a6a5c66815c5840551846b0a 100644 --- a/en/application-dev/media/media/video-playback.md +++ b/en/application-dev/media/media/video-playback.md @@ -107,7 +107,7 @@ export class AVPlayerDemo { console.error(`Invoke avPlayer failed, code is ${err.code}, message is ${err.message}`); avPlayer.reset(); // Call reset() to reset the AVPlayer, which enters the idle state. }); - // Callback function for state changes. + // Callback for state changes. avPlayer.on('stateChange', async (state: string, reason: media.StateChangeReason) => { switch (state) { case 'idle': // This state is reported upon a successful callback of reset(). @@ -164,7 +164,7 @@ export class AVPlayerDemo { async avPlayerUrlDemo() { // Create an AVPlayer instance. let avPlayer: media.AVPlayer = await media.createAVPlayer(); - // Set a callback function for state changes. + // Set a callback for state changes. this.setAVPlayerCallback(avPlayer); let fdPath = 'fd://'; let context = getContext(this) as common.UIAbilityContext; @@ -182,7 +182,7 @@ export class AVPlayerDemo { async avPlayerFdSrcDemo() { // Create an AVPlayer instance. let avPlayer: media.AVPlayer = await media.createAVPlayer(); - // Set a callback function for state changes. + // Set a callback for state changes. this.setAVPlayerCallback(avPlayer); // Call getRawFd of the resourceManager member of UIAbilityContext to obtain the media asset URL. // The return type is {fd,offset,length}, where fd indicates the file descriptor address of the HAP file, offset indicates the media asset offset, and length indicates the duration of the media asset to play. @@ -199,7 +199,7 @@ export class AVPlayerDemo { async avPlayerDataSrcSeekDemo() { // Create an AVPlayer instance. let avPlayer: media.AVPlayer = await media.createAVPlayer(); - // Set a callback function for state changes. + // Set a callback for state changes. this.setAVPlayerCallback(avPlayer); // dataSrc indicates the playback source address. When the seek operation is supported, fileSize indicates the size of the file to be played. The following describes how to assign a value to fileSize. let src: media.AVDataSrcDescriptor = { @@ -234,7 +234,7 @@ export class AVPlayerDemo { async avPlayerDataSrcNoSeekDemo() { // Create an AVPlayer instance. let avPlayer: media.AVPlayer = await media.createAVPlayer(); - // Set a callback function for state changes. + // Set a callback for state changes. this.setAVPlayerCallback(avPlayer); let context = getContext(this) as common.UIAbilityContext; let src: media.AVDataSrcDescriptor = { @@ -265,7 +265,7 @@ export class AVPlayerDemo { async avPlayerLiveDemo() { // Create an AVPlayer instance. let avPlayer: media.AVPlayer = await media.createAVPlayer(); - // Set a callback function for state changes. + // Set a callback for state changes. this.setAVPlayerCallback(avPlayer); this.isSeek = false; // The seek operation is not supported. avPlayer.url = 'http://xxx.xxx.xxx.xxx:xx/xx/index.m3u8'; // Play live webcasting streams using HLS. diff --git a/en/application-dev/media/media/video-recording.md b/en/application-dev/media/media/video-recording.md index 1337a14c45c5d58edfd705f89f51590ac847a948..a29d23a22b726e4fba338cd1dc82ca7996cc3291 100644 --- a/en/application-dev/media/media/video-recording.md +++ b/en/application-dev/media/media/video-recording.md @@ -1,16 +1,16 @@ # Using AVRecorder to Record Videos (ArkTS) -The system provides the [AVRecorder](media-kit-intro.md#avrecorder) for you to develop the video recording service. The AVRecorder supports audio recording, audio encoding, video encoding, audio encapsulation, and video encapsulation. It is applicable to simple video recording scenarios and can be used to generate local video files directly. +You can use the [AVRecorder](media-kit-intro.md#avrecorder) to develop the video recording service. The AVRecorder supports audio capture, audio encoding, video encoding, audio encapsulation, and video encapsulation. It is applicable to simple video recording scenarios and can be used to generate local video files directly. -You will learn how to use the AVRecorder to complete the process of starting, pausing, resuming, and stopping recording. +In this topic, you will learn how to use the AVRecorder to complete the process of starting, pausing, resuming, and stopping video recording. -During application development, you can use the **state** attribute of the AVRecorder to obtain the AVRecorder state or call **on('stateChange')** to listen for state changes. Your code must meet the state machine requirements. For example, **pause()** is called only when the AVRecorder is in the **started** state, and **resume()** is called only when it is in the **paused** state. +During application development, you can use the **state** property of the AVRecorder to obtain the AVRecorder state or call **on('stateChange')** to listen for state changes. Your code must meet the state machine requirements. For example, **pause()** is called only when the AVRecorder is in the **started** state, and **resume()** is called only when it is in the **paused** state. **Figure 1** Recording state transition ![Recording state change](figures/video-recording-status-change.png) -For details about the state, see [AVRecorderState](../../reference/apis-media-kit/js-apis-media.md#avrecorderstate9). +For details about the states, see [AVRecorderState](../../reference/apis-media-kit/js-apis-media.md#avrecorderstate9). ## Requesting Permissions @@ -18,21 +18,21 @@ For details about the state, see [AVRecorderState](../../reference/apis-media-ki Before your development, configure the following permissions for your application. - To use the microphone, request the ohos.permission.MICROPHONE permission. For details about how to request user authorization, see [Requesting User Authorization](../../security/AccessToken/request-user-authorization.md). - To use the camera for photo capture, request the ohos.permission.CAMERA permission. For details about how to request user authorization, see [Requesting User Authorization](../../security/AccessToken/request-user-authorization.md). -- To read images or videos from Gallery, you are advised to use the media library [Picker to access them](../medialibrary/photoAccessHelper-photoviewpicker.md). -- To save images or videos to Gallery, use the [security component to save them](../medialibrary/photoAccessHelper-savebutton.md). +- To read images or videos from Gallery, preferentially use the media library [Picker for access](../medialibrary/photoAccessHelper-photoviewpicker.md). +- To save images or videos to Gallery, preferentially use the [security component for storage](../medialibrary/photoAccessHelper-savebutton.md). > **NOTE** > -> When the application needs to clone, back up, or synchronize images and videos in users' public directory, request the ohos.permission.READ_IMAGEVIDEO and ohos.permission.WRITE_IMAGEVIDEO permissions for reading and writing audio files. For details, see [Requesting Restricted Permissions](../../security/AccessToken/declare-permissions-in-acl.md). +> To clone, back up, or synchronize images and videos in users' public directory, request the ohos.permission.READ_IMAGEVIDEO and ohos.permission.WRITE_IMAGEVIDEO permissions for reading and writing audio files. For details, see [Requesting Restricted Permissions](../../security/AccessToken/declare-permissions-in-acl.md). ## How to Develop > **NOTE** > -> The AVRecorder only processes video data. To complete video recording, it must work with the video data collection module, which transfers the captured video data to the AVRecorder for data processing through the surface. Currently, the commonly used data collection module is the camera module. For details, see [Camera Recording](../camera/camera-recording.md). +> The AVRecorder only processes video data. To complete video recording, it must work with the video data collection module, which transfers the captured video data to the AVRecorder for data processing through the surface. Currently, the commonly used data collection module is the camera module. For details, see [Video Recording](../camera/camera-recording.md). > -> For details about how to create and save a file, see [Application File Access and Management](../../file-management/app-file-access.md). By default, files are saved in the sandbox path of the application. To save them to Gallery, use the [security components](../medialibrary/photoAccessHelper-savebutton.md). +> For details about how to create and save a file, see [Accessing Application Files](../../file-management/app-file-access.md). By default, files are saved in the sandbox path of the application. To save them to Gallery, use the [security components](../medialibrary/photoAccessHelper-savebutton.md). Read [AVRecorder](../../reference/apis-media-kit/js-apis-media.md#avrecorder9) for the API reference. @@ -54,7 +54,7 @@ Read [AVRecorder](../../reference/apis-media-kit/js-apis-media.md#avrecorder9) f 2. Set the events to listen for. | Event Type| Description| | -------- | -------- | - | stateChange | Mandatory; used to listen for changes of the **state** attribute of the AVRecorder.| + | stateChange | Mandatory; used to listen for changes of the **state** property of the AVRecorder.| | error | Mandatory; used to listen for AVRecorder errors.| ```ts @@ -62,11 +62,11 @@ Read [AVRecorder](../../reference/apis-media-kit/js-apis-media.md#avrecorder9) f import { BusinessError } from '@kit.BasicServicesKit'; // Callback function for state changes. - avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => { + this.avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => { console.info('current state is: ' + state); }) // Callback function for errors. - avRecorder.on('error', (err: BusinessError) => { + this.avRecorder.on('error', (err: BusinessError) => { console.error('error happened, error message is ' + err); }) ``` @@ -83,11 +83,12 @@ Read [AVRecorder](../../reference/apis-media-kit/js-apis-media.md#avrecorder9) f > > - The [recording specifications](media-kit-intro.md#supported-formats) in use must be those supported. The video bit rate, resolution, and frame rate are subject to the ranges supported by the hardware device. > - > - The recording output URL (URL in **avConfig** in the sample code) must be in the format of fd://xx (where xx indicates a file descriptor). You must call [ohos.file.fs of Core File Kit](../../reference/apis-core-file-kit/js-apis-file-fs.md) to implement access to the application file. For details, see [Application File Access and Management](../../file-management/app-file-access.md). + > - The recording output URL (URL in **avConfig** in the sample code) must be in the format of fd://xx (where xx indicates a file descriptor). You must call [ohos.file.fs of Core File Kit](../../reference/apis-core-file-kit/js-apis-file-fs.md) to implement access to the application file. For details, see [Accessing Application Files](../../file-management/app-file-access.md). ```ts import { media } from '@kit.MediaKit'; import { BusinessError } from '@kit.BasicServicesKit'; + import { fileIo as fs } form '@kit.CoreFileKit'; let avProfile: media.AVRecorderProfile = { fileFormat: media.ContainerFormatType.CFT_MPEG_4, // Video file container format. Only MP4 is supported. @@ -100,16 +101,16 @@ Read [AVRecorder](../../reference/apis-media-kit/js-apis-media.md#avrecorder9) f const context: Context = getContext(this); // Refer to Application File Access and Management. let filePath: string = context.filesDir + '/example.mp4'; - let videoFile: fs.File = fs.openSync(filePath, OpenMode.READ_WRITE | OpenMode.CREATE); + let videoFile: fs.File = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); let fileFd = videoFile.fd; // Obtain the file FD. - + let avConfig: media.AVRecorderConfig = { videoSourceType: media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, // Video source type. YUV and ES are supported. profile : avProfile, url: 'fd://' + fileFd.toString(), // Create, read, and write a video file by referring to the sample code in Application File Access and Management. rotation: 0 // Video rotation angle. The default value is 0, indicating that the video is not rotated. The value can be 0, 90, 180, or 270. }; - avRecorder.prepare(avConfig).then(() => { + this.avRecorder.prepare(avConfig).then(() => { console.info('avRecorder prepare success'); }, (error: BusinessError) => { console.error('avRecorder prepare failed'); @@ -118,14 +119,14 @@ Read [AVRecorder](../../reference/apis-media-kit/js-apis-media.md#avrecorder9) f 4. Obtain the surface ID required for video recording. - Call **getInputSurface()**. The returned surface ID is transferred to the video data collection module (video input source), which is the camera module in the sample code. + Call **getInputSurface()**. The returned surface ID is transferred to the video data collection module, which is the camera module in the sample code. The video data collection module obtains the surface based on the surface ID and transmits video data to the AVRecorder through the surface. Then the AVRecorder processes the video data. ```ts import { BusinessError } from '@kit.BasicServicesKit'; - avRecorder.getInputSurface().then((surfaceId: string) => { + this.avRecorder.getInputSurface().then((surfaceId: string) => { console.info('avRecorder getInputSurface success'); }, (error: BusinessError) => { console.error('avRecorder getInputSurface failed'); @@ -134,17 +135,17 @@ Read [AVRecorder](../../reference/apis-media-kit/js-apis-media.md#avrecorder9) f 5. Initialize the video data input source. - This step is performed in the video data collection module. For the camera module, you need to create a Camera instance, obtain the camera list, create a camera input stream, and create a video output stream. For details, see [Camera Recording](../camera/camera-recording.md). + This step is performed in the video data collection module. For the camera module, you need to create a Camera instance, obtain the camera list, create a camera input stream, and create a video output stream. For details, see [Video Recording](../camera/camera-recording.md). 6. Start recording. - Start the input source to input video data, for example, by calling **camera.VideoOutput.start**. Then call **AVRecorder.start()** to switch the AVRecorder to the **started** state. + Start the input source to input video data, for example, by calling **camera.VideoOutput.start** of the camera module. Then call **AVRecorder.start()** to switch the AVRecorder to the **started** state. -7. Call **pause()** to pause recording. The AVRecorder enters the **paused** state. In addition, pause data input in the video data collection module, for example, by calling **camera.VideoOutput.stop**. +7. Call **pause()** to pause recording. The AVRecorder enters the **paused** state. In addition, pause data input, for example, by calling **camera.VideoOutput.stop** of the camera module. 8. Call **resume()** to resume recording. The AVRecorder enters the **started** state again. -9. Call **stop()** to stop recording. The AVRecorder enters the **stopped** state again. In addition, stop camera recording in the video data collection module. +9. Call **stop()** to stop recording. The AVRecorder enters the **stopped** state again. In addition, stop camera recording. 10. Call **reset()** to reset the resources. The AVRecorder enters the **idle** state. In this case, you can reconfigure the recording parameters. @@ -159,18 +160,21 @@ Refer to the sample code below to complete the process of starting, pausing, res ```ts import { media } from '@kit.MediaKit'; import { BusinessError } from '@kit.BasicServicesKit'; -import { fileIo as fs, ReadOptions } from '@kit.CoreFileKit'; +import { fileIo as fs, fileUri } from '@kit.CoreFileKit'; import { photoAccessHelper } from '@kit.MediaLibraryKit'; const TAG = 'VideoRecorderDemo:'; export class VideoRecorderDemo { - const context: Context = getContext(this); + private context: Context; + constructor() { + this.context = getContext(this); + } private avRecorder: media.AVRecorder | undefined = undefined; private videoOutSurfaceId: string = ""; private avProfile: media.AVRecorderProfile = { fileFormat: media.ContainerFormatType.CFT_MPEG_4, // Video file container format. Only MP4 is supported. - videoBitrate : 100000, // Video bit rate. + videoBitrate: 100000, // Video bit rate. videoCodec: media.CodecMimeType.VIDEO_AVC, // Video file encoding format. AVC is supported. videoFrameWidth: 640, // Video frame width. videoFrameHeight: 480, // Video frame height. @@ -189,8 +193,8 @@ export class VideoRecorderDemo { // Create a file and set avConfig.url. async createAndSetFd() { - const path: string = context.filesDir + '/example.mp4'; // File sandbox path. The file name extension must match the container format. - const videoFile: fs.File = fs.openSync(path, OpenMode.READ_WRITE | OpenMode.CREATE); + const path: string = this.context.filesDir + '/example.mp4'; // File sandbox path. The file name extension must match the container format. + const videoFile: fs.File = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); this.avConfig.url = 'fd://' + videoFile.fd; // Set the URL. this.fileFd = videoFile.fd; // File FD. this.filePath = path; @@ -199,7 +203,7 @@ export class VideoRecorderDemo { // Set AVRecorder callback functions. setAvRecorderCallback() { if (this.avRecorder != undefined) { - // Callback function for state changes. + // Callback for state changes. this.avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => { console.info(TAG + 'current state is: ' + state); }) @@ -279,7 +283,7 @@ export class VideoRecorderDemo { // 3. Release the AVRecorder instance. await this.avRecorder.release(); // 4. After the file is recorded, close the file descriptor. The implementation is omitted here. - await fs.close(videoFile); + await fs.close(this.fileFd); // 5. Release the camera instance. await this.releaseCamera(); } @@ -289,7 +293,7 @@ export class VideoRecorderDemo { async saveRecorderAsset() { let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(this.context); // Ensure that the asset specified by uriPath exists. - this.uriPath = file.Uri.getUriFromPath(this.filePath); // Obtain the file URI, which is used by the security component when saving the file to Gallery. + this.uriPath = fileUri.getUriFromPath(this.filePath); // Obtain the file URI, which is used by the security component when saving the file to Gallery. let assetChangeRequest: photoAccessHelper.MediaAssetChangeRequest = photoAccessHelper.MediaAssetChangeRequest.createVideoAssetRequest(this.context, this.uriPath); await phAccessHelper.applyChanges(assetChangeRequest); diff --git a/en/application-dev/media/medialibrary/photoAccessHelper-savebutton.md b/en/application-dev/media/medialibrary/photoAccessHelper-savebutton.md index 76bdc5e06677fd93babad94062e1b9f7ababe6cb..6de49ba953dd9e6e406af485458ba51b0b679389 100644 --- a/en/application-dev/media/medialibrary/photoAccessHelper-savebutton.md +++ b/en/application-dev/media/medialibrary/photoAccessHelper-savebutton.md @@ -2,6 +2,45 @@ When users wish to save images, videos, or similar files to Gallery, it is not necessary for the application to request the ohos.permission.WRITE_IMAGEVIDEO permission. Instead, the application can use the [SaveButton](#creating-a-media-asset-using-savebutton) or [authorization pop-up](#saving-a-media-asset-using-an-authorization-pop-up) to save the media assets to Gallery. +## Obtaining Supported Resource Formats for Saving + +The following describes how to obtain image resource formats that can be saved. + +**How to Develop** + +Call [phAccessHelper.getSupportedPhotoFormats](../../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#getsupportedphotoformats18) to obtain the supported image formats that can be saved. + +```ts +import photoAccessHelper from '@ohos.file.photoAccessHelper'; + +let context = getContext(this); +let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context); +@Entry +@Component + +struct Index { + @State outputText: string = 'Supported formats:\n'; + + async function example(){ + try { + this.outputText = 'Supported formats:\n'; + // The value 1 means the supported image formats, and 2 means the supported video formats. + let imageFormat = await phAccessHelper.getSupportedPhotoFormats(1); + let result = ""; + for (let i = 0; i < imageFormat.length; i++) { + result += imageFormat[i]; + if (i !== imageFormat.length - 1) { + result += ', '; + } + } + this.outputText += result; + console.info('getSupportedPhotoFormats success, data is ' + outputText); + } catch (error) { + console.error('getSupportedPhotoFormats failed, errCode is', error); + } + } +``` + ## Creating a Media Asset Using SaveButton For details about the **SaveButton** component, see [SaveButton](../../reference/apis-arkui/arkui-ts/ts-security-components-savebutton.md). @@ -24,12 +63,12 @@ struct Index { icon: SaveIconStyle.FULL_FILLED, text: SaveDescription.SAVE_IMAGE, buttonType: ButtonType.Capsule - } // Set the attributes of the security component. + } // Set properties of SaveButton. build() { Row() { Column() { - SaveButton(this.saveButtonOptions) // Create a security component. + SaveButton(this.saveButtonOptions) // Create a button with SaveButton. .onClick(async (event, result: SaveButtonOnClickResult) => { if (result == SaveButtonOnClickResult.SUCCESS) { try { diff --git a/en/application-dev/napi/Readme-EN.md b/en/application-dev/napi/Readme-EN.md index fe9ee1f5a22b6feaa61d0f10c99d05af60b45fec..d53e1f83fa55c951beab8195c5b759f267ac1a41 100644 --- a/en/application-dev/napi/Readme-EN.md +++ b/en/application-dev/napi/Readme-EN.md @@ -49,6 +49,7 @@ - [Loading a Module Using Node-API](use-napi-load-module-with-info.md) - [Passing a Task with the Specified Priority to an ArkTS Thread from an Asynchronous Thread Using Node-API](use-call-threadsafe-function-with-priority.md) - [Analyzing Exceptions and Crashes Triggered by Using Node-API](use-napi-about-crash.md) + - [Calling an ArkTS Method with Return Value of a Promise Using Node-API](use-napi-method-promise.md) - [Node-API FAQs](use-napi-faqs.md) - Using JSVM-API - [JSVM-API Overview](jsvm-introduction.md) diff --git a/en/application-dev/napi/native-netmanager-guidelines.md b/en/application-dev/napi/native-netmanager-guidelines.md index 0eb83e0cd797a15eb44f6384300e56047ffdda03..402f147236ec0ca5384a6e356e62567b1dd8895a 100644 --- a/en/application-dev/napi/native-netmanager-guidelines.md +++ b/en/application-dev/napi/native-netmanager-guidelines.md @@ -1,6 +1,6 @@ -# NetConnection Development +# Network Connection Development -## Use Cases +## When to Use The **NetConnection** module provides the capability of querying common network information. @@ -9,7 +9,7 @@ The **NetConnection** module provides the capability of querying common network The following table lists the common **NetConnection** APIs. For details, see [NetConnection](../reference/apis-network-kit/_net_connection.md). -| Name| Description| +| API| **Test Description**| | -------- | -------- | | OH_NetConn_HasDefaultNet(int32_t \*hasDefaultNet) | Checks whether the default data network is activated and determines whether a network connection is available.| | OH_NetConn_GetDefaultNet(NetConn_NetHandle \*netHandle) | Obtains the default active data network.| @@ -20,20 +20,23 @@ The following table lists the common **NetConnection** APIs. For details, see [N | OH_NetConn_GetAddrInfo (char \*host, char \*serv, struct addrinfo \*hint, struct addrinfo \*\*res, int32_t netId) | Obtains the DNS result based on the specified **netId**.| | OH_NetConn_FreeDnsResult(struct addrinfo \*res) | Releases the DNS query result.| | OH_NetConn_GetAllNets(NetConn_NetHandleList \*netHandleList) | Obtains the list of all connected networks.| -| OHOS_NetConn_RegisterDnsResolver(OH_NetConn_CustomDnsResolver resolver) | Registers a custom DNS resolver.
Note: This API is deprecated since API version 13. You are advised to use **OH_NetConn_RegisterDnsResolver** instead.| -| OHOS_NetConn_UnregisterDnsResolver(void) | Unregisters a custom DNS resolver.
Note: This API is deprecated since API version 13. You are advised to use **OH_NetConn_UnregisterDnsResolver** instead.| -| OH_NetConn_BindSocket(int32_t socketFd, NetConn_NetHandle \*netHandle) | Binds a socket to the specified network.| +| OHOS_NetConn_RegisterDnsResolver(OH_NetConn_CustomDnsResolver resolver) | Registers a custom DNS resolver.
Note: This API is deprecated since API version 13.
You are advised to use **OH_NetConn_RegisterDnsResolver** instead.| +| OHOS_NetConn_UnregisterDnsResolver(void) | Unregisters a custom DNS resolver.
Note: This API is deprecated since API version 13.
You are advised to use **OH_NetConn_UnregisterDnsResolver** instead.| | OH_NetConn_RegisterDnsResolver(OH_NetConn_CustomDnsResolver resolver) | Registers a custom DNS resolver.| | OH_NetConn_UnregisterDnsResolver(void) | Unregisters a custom DNS resolver.| +| OH_NetConn_SetPacUrl(const char \*pacUrl) | Sets the URL of the system-level proxy auto-config (PAC) script.| +| OH_NetConn_GetPacUrl(char \*pacUrl) | Obtains the URL of the system-level PAC script.| ## Development Example ### How to Develop -To use related APIs to obtain network information, you need to create a Native C++ project, encapsulate the APIs in the source file, and call these APIs at the ArkTS layer. You can use hilog or console.log to print the log information on the console or generate device logs. +To use related APIs to obtain network information, you need to create a Native C++ project, encapsulate the APIs in the source file, and call these APIs at the ArkTs layer. You can use hilog or console.log to print the log information on the console or generate device logs. This document describes how to obtain the default active data network as an example. +For details about other APIs, see the [Complete Sample Code](https://gitee.com/openharmony/applications_app_samples/tree/master/code/DocsSample/NetWork_Kit/NetWorkKit_NetManager/NetConnection_Exploitation_case). + ### Adding Dependencies **Adding the Dynamic Link Library** @@ -55,7 +58,7 @@ libnet_connection.so ### Building the Project -1. Write the code for calling the API in the source file, encapsulate it into a value of the `napi_value` type, and return the value to the `Node.js` environment. +1. Write the code for calling the API in the source file, encapsulate it into a value of the `napi_value` type, and return the value to the Node.js environment. ```C // Get the execution results of the default network connection. @@ -94,7 +97,7 @@ static napi_value NetId(napi_env env, napi_callback_info info) { } ``` -> **NOTE**
The two functions are used to obtain information about the default network connection of the system. Wherein, GetDefaultNet is used to receive the test parameters passed from ArkTS and return the corresponding return value after the API is called. You can change param as needed. If the return value is **0**, the parameters are obtained successfully. If the return value is **401**, the parameters are incorrect. If the return value is **201**, the user does not have the operation permission. NetId indicates the ID of the default network connection. You can use the information for further network operations. +> **NOTE**
The two functions are used to obtain information about the default network connection of the system. Wherein, GetDefaultNet is used to receive the test parameters passed from ArkTs and return the corresponding return value after the API is called. You can change param as needed. If the return value is **0**, the parameters are obtained successfully. If the return value is **401**, the parameters are incorrect. If the return value is **201**, the user does not have the operation permission. NetId indicates the ID of the default network connection. You can use the information for further network operations. 2. Initialize and export the `napi_value` objects encapsulated through **NAPI**, and expose the preceding two functions to JavaScript through external function APIs. @@ -113,7 +116,7 @@ static napi_value Init(napi_env env, napi_value exports) EXTERN_C_END ``` -3. Register the objects successfully initialized in the previous step into the `Node.js` file by using the `napi_module_register` function of `RegisterEntryModule`. +3. Register the objects successfully initialized in the previous step into the Node.js file by using the `napi_module_register` function of `RegisterEntryModule`. ```C static napi_module demoModule = { @@ -132,9 +135,9 @@ extern "C" __attribute__((constructor)) void RegisterEntryModule(void) } ``` -4. Define the types of the two functions in the `index.d.ts` file of the project. +4. Define the types of the two functions in the `index.d.ts ` file of the project. -- The `GetDefaultNet` function accepts the numeric parameter `code` and returns a numeric value. +- The `GetDefaultNet ` function accepts the numeric parameter code and returns a numeric value. - The `NetId` function does not accept parameters and returns a numeric value. ```ts @@ -192,7 +195,7 @@ struct Index { 6. Configure the `CMakeLists.txt` file. Add the required shared library, that is, `libnet_connection.so`, to `target_link_libraries` in the `CMakeLists.txt` file automatically generated by the project. -Note: As shown in the following figure, `entry` in `add_library` is the `modename` automatically generated by the project. If you want to change the `modename`, ensure that it is the same as the `.nm_modname` in step 3. +Note: As shown in the following figure, `entry` in `add_library` is the modename automatically generated by the project. If you want to change the `modename`, ensure that it is the same as the `.nm_modname` in step 3. ![netmanager-4.png](./figures/netmanager-4.png) diff --git a/en/application-dev/napi/use-napi-about-property.md b/en/application-dev/napi/use-napi-about-property.md index 6eebf8d146c578d7818a3ca14674a2d16522ee16..fa172f1571d8f6e33bf42a866972f18fec298792 100644 --- a/en/application-dev/napi/use-napi-about-property.md +++ b/en/application-dev/napi/use-napi-about-property.md @@ -1,4 +1,4 @@ -# Working with Properties Using Node-API +# Setting ArkTS Object Properties Using Node-API ## Introduction @@ -97,6 +97,8 @@ CPP code: ```cpp #include "napi/native_api.h" +static constexpr int INT_ARG_2 = 2; // Input parameter index. + static napi_value SetProperty(napi_env env, napi_callback_info info) { // Obtain the parameters passed from ArkTS. The first parameter specifies the object, the second parameter specifies the property name, and the third parameter specifies the property value to set. @@ -107,7 +109,7 @@ static napi_value SetProperty(napi_env env, napi_callback_info info) napi_throw_error(env, nullptr, "Node-API napi_get_cb_info fail"); } // Call napi_set_property to set the property name and value to the object. If the operation fails, throw an error. - status = napi_set_property(env, args[0], args[1], args[2]); + status = napi_set_property(env, args[0], args[1], args[INT_ARG_2]); if (status != napi_ok) { napi_throw_error(env, nullptr, "Node-API napi_set_property fail"); return nullptr; @@ -343,7 +345,7 @@ static napi_value NapiHasOwnProperty(napi_env env, napi_callback_info info) napi_throw_error(env, nullptr, "Second argument must be a string."); return nullptr; } - // Check whether the object has the specified property and return the result in hasProperty. + // Check whether the object has the specified property and returns the result in hasProperty. bool hasProperty; napi_status status = napi_has_own_property(env, args[0], args[1], &hasProperty); if (status != napi_ok) { @@ -520,7 +522,7 @@ static napi_value NapiHasNamedProperty(napi_env env, napi_callback_info info) // Obtain the property name. size_t keyLength; napi_get_value_string_utf8(env, args[1], strKey, strLength, &keyLength); - // Check whether the object has the specified property and store the result in hasProperty. + // Check whether the object has the specified property and stores the result in hasProperty. bool hasProperty = false; napi_status status = napi_has_named_property(env, args[0], strKey, &hasProperty); if (status != napi_ok) { diff --git a/en/application-dev/napi/use-napi-method-promise.md b/en/application-dev/napi/use-napi-method-promise.md new file mode 100644 index 0000000000000000000000000000000000000000..39eabe63142c2e87edd8115078d7b7b015d01360 --- /dev/null +++ b/en/application-dev/napi/use-napi-method-promise.md @@ -0,0 +1,152 @@ +# Calling an ArkTS Method with Return Value of a promise Using Node-API + +## When to Use +You can call the ArkTS APIs, which return a promise, in the created ArkTS runtime environment as follows: + +## Calling an ArkTS Method Asynchronously +Use Node-API to call the ArkTS method that returns a promise in C++. +Handle the promise object: Bind the promise object to a C++ callback to process the result returned asynchronously. +Convert the data type: In the callback, convert the JavaScript (JS) result to the data that can be used by C++. +Conduct thread-safe processing to ensure security of cross-thread operations. + +### Sample Code +- Register the module. + ```c++ + #include "hilog/log.h" + #include "napi/native_api.h" + #include + #include + + // Callback for processing a resolved promise. + static napi_value ResolvedCallback(napi_env env, napi_callback_info info) + { + size_t argc = 1; + napi_value args[1]; + napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); + + int result; + napi_get_value_int32(env, args[0], &result); + OH_LOG_INFO(LOG_APP, "Promise resolved with result:%{public}d", result); + return nullptr; + } + + // Callback for processing a rejected promise. + static napi_value RejectedCallback(napi_env env, napi_callback_info info) + { + size_t argc = 1; + napi_value args[1]; + napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); + + napi_value error; + napi_coerce_to_string(env, args[0], &error); + char errorMsg[1024]; + size_t len; + napi_get_value_string_utf8(env, error, errorMsg, sizeof(errorMsg), &len); + OH_LOG_ERROR(LOG_APP, "Promise rejected with error:%{public}s", errorMsg); + return nullptr; + } + + static napi_value CallArkTSAsync(napi_env env, napi_callback_info info) + { + size_t argc = 1; + napi_value argv[1] = { nullptr }; + napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); + napi_value promise = nullptr; + napi_call_function(env, nullptr, argv[0], 0, nullptr, &promise); + + napi_value thenFunc = nullptr; + if (napi_get_named_property(env, promise, "then", &thenFunc) != napi_ok) { + return nullptr; + } + + napi_value onResolve = nullptr; + napi_value onReject = nullptr; + napi_create_function(env, "onResolve", NAPI_AUTO_LENGTH, ResolvedCallback, nullptr, &onResolve); + napi_create_function(env, "onReject", NAPI_AUTO_LENGTH, RejectedCallback, nullptr, &onReject); + napi_value argv1[2] = {onResolve, onReject}; + napi_call_function(env, promise, thenFunc, 2, argv1, nullptr); + + return nullptr; + } + + // Register the module. + EXTERN_C_START + static napi_value Init(napi_env env, napi_value exports) + { + napi_property_descriptor desc[] = { + {"callArkTSAsync", nullptr, CallArkTSAsync, nullptr, nullptr, nullptr, napi_default, nullptr} + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); + return exports; + } + EXTERN_C_END + + static napi_module nativeModule = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = Init, + .nm_modname = "entry", + .nm_priv = nullptr, + .reserved = { 0 }, + }; + + extern "C" __attribute__((constructor)) void RegisterEntryModule() + { + napi_module_register(&nativeModule); + } + ``` + +- Declare APIs. + ```ts + // index.d.ts + export const callArkTSAsync: (func: Function) => object; + ``` + +- Configure compile settings. +1. Configure the **CMakeLists.txt** file as follows: + ``` + // CMakeLists.txt + # the minimum version of CMake. + cmake_minimum_required(VERSION 3.4.1) + project(myapplication) + + set(NATIVERENDER_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR}) + + if(DEFINED PACKAGE_FIND_FILE) + include(${PACKAGE_FIND_FILE}) + endif() + + include_directories(${NATIVERENDER_ROOT_PATH} + ${NATIVERENDER_ROOT_PATH}/include) + add_library(entry SHARED hello.cpp) + target_link_libraries(entry PUBLIC libace_napi.z.so) + ``` +2. Add the following to the **build-profile.json5** file of the project. + ```json + { + "buildOption" : { + "arkOptions" : { + "runtimeOnly" : { + "sources": [ + "./src/main/ets/pages/ObjectUtils.ets" + ] + } + } + } + } + ``` +- ArkTS sample code + ```ts + // index.ets + import testNapi from 'libentry.so' + + export function SetTimeout() : Promise { + return new Promise((resolve) => { + setTimeout(() => { + resolve(42); + }, 1000) + }) + } + testNapi.callArkTSAsync(SetTimeout); + ``` diff --git a/en/application-dev/network/Readme-EN.md b/en/application-dev/network/Readme-EN.md index b36789e46fda4ee0de5a5c56d623cfe9e23cc327..7b429e7682e6ace91ede2b313152ff6b3acb0626 100644 --- a/en/application-dev/network/Readme-EN.md +++ b/en/application-dev/network/Readme-EN.md @@ -1,19 +1,21 @@ -# Network Kit +# Network Kit - [Introduction to Network Kit](net-mgmt-overview.md) -- Data Transmission Capabilities +- Data Transmission Capabilities - [HTTP Data Request](http-request.md) - [WebSocket Connection](websocket-connection.md) + - [WebSocket Connection (C/C++)](native-websocket-guidelines.md) - [Socket Connection](socket-connection.md) - [MDNS Management](net-mdns.md) -- Network Management Capabilities +- Network Management Capabilities - [Network Connection Management](net-connection-manager.md) - - [NetConnection Development (C/C++)](native-netmanager-guidelines.md) + - [NetConnection Development (C/C++)] (native-netmanager-guidelines.md) - [Traffic Management](net-statistics.md) + - [VPN Extension Development](net-vpnExtension.md) + - [Network Firewall](net-netfirewall.md) - - [Network Firewall (For System Applications Only)](net-netfirewall.md) - [Network Sharing (for System Applications Only)](net-sharing.md) - [Ethernet Connection Management (for System Applications Only)](net-ethernet.md) - [VPN Management (for System Applications Only)](net-vpn.md) diff --git a/en/application-dev/network/figures/websocket-demo-1.jpg b/en/application-dev/network/figures/websocket-demo-1.jpg new file mode 100644 index 0000000000000000000000000000000000000000..4b162e636380fca201ddaf519be1bb310baf6280 Binary files /dev/null and b/en/application-dev/network/figures/websocket-demo-1.jpg differ diff --git a/en/application-dev/network/figures/websocket-demo-2.jpg b/en/application-dev/network/figures/websocket-demo-2.jpg new file mode 100644 index 0000000000000000000000000000000000000000..4f5fd60463cb3aed9ab373f384c57101f1f756dd Binary files /dev/null and b/en/application-dev/network/figures/websocket-demo-2.jpg differ diff --git a/en/application-dev/network/figures/websocket-demo-log.png b/en/application-dev/network/figures/websocket-demo-log.png new file mode 100644 index 0000000000000000000000000000000000000000..f4d62a403d83d77e8526ee1e0f71b367e410dd2a Binary files /dev/null and b/en/application-dev/network/figures/websocket-demo-log.png differ diff --git a/en/application-dev/network/figures/websocket-notemod.png b/en/application-dev/network/figures/websocket-notemod.png new file mode 100644 index 0000000000000000000000000000000000000000..a53d554adbd3a731a496a4fceb68ab1b8287f279 Binary files /dev/null and b/en/application-dev/network/figures/websocket-notemod.png differ diff --git a/en/application-dev/network/native-netmanager-guidelines.md b/en/application-dev/network/native-netmanager-guidelines.md index 9a6b60dc81fa6090d63a13e236e4f7b4762a838c..402f147236ec0ca5384a6e356e62567b1dd8895a 100644 --- a/en/application-dev/network/native-netmanager-guidelines.md +++ b/en/application-dev/network/native-netmanager-guidelines.md @@ -24,6 +24,8 @@ The following table lists the common **NetConnection** APIs. For details, see [N | OHOS_NetConn_UnregisterDnsResolver(void) | Unregisters a custom DNS resolver.
Note: This API is deprecated since API version 13.
You are advised to use **OH_NetConn_UnregisterDnsResolver** instead.| | OH_NetConn_RegisterDnsResolver(OH_NetConn_CustomDnsResolver resolver) | Registers a custom DNS resolver.| | OH_NetConn_UnregisterDnsResolver(void) | Unregisters a custom DNS resolver.| +| OH_NetConn_SetPacUrl(const char \*pacUrl) | Sets the URL of the system-level proxy auto-config (PAC) script.| +| OH_NetConn_GetPacUrl(char \*pacUrl) | Obtains the URL of the system-level PAC script.| ## Development Example @@ -33,6 +35,8 @@ To use related APIs to obtain network information, you need to create a Native C This document describes how to obtain the default active data network as an example. +For details about other APIs, see the [Complete Sample Code](https://gitee.com/openharmony/applications_app_samples/tree/master/code/DocsSample/NetWork_Kit/NetWorkKit_NetManager/NetConnection_Exploitation_case). + ### Adding Dependencies **Adding the Dynamic Link Library** diff --git a/en/application-dev/network/native-websocket-guidelines.md b/en/application-dev/network/native-websocket-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..00f5df903b4afe4d0f581cfc4913d34c3e2a1641 --- /dev/null +++ b/en/application-dev/network/native-websocket-guidelines.md @@ -0,0 +1,353 @@ +# WebSocket Connection (C/C++) + +## When to Use + +The WebSocket module can be used to establish bidirectional connections between the server and the client. + +## Available APIs + +The following table lists the common **WebSocket** APIs. For details, see [net_websocket.h](../reference/apis-network-kit/net__websocket_8h.md). + + +| API| Description| +| -------- | -------- | +| OH_WebSocketClient_Constructor(WebSocket_OnOpenCallback onOpen, WebSocket_OnMessageCallback onMessage, WebSocket_OnErrorCallback onError, WebSocket_OnCloseCallback onclose) | Constructor used to create a **WebSocketClient** instance. | +| OH_WebSocketClient_AddHeader(struct WebSocket \*client, struct WebSocket_Header header) | Adds the header information to the client request. | +| OH_WebSocketClient_Connect(struct WebSocket \*client, const char \*url, struct WebSocket_RequestOptions options) | Connects the WebSocket client to the server. | +| OH_WebSocketClient_Send(struct WebSocket \*client, char \*data, size_t length) | Sends data from the WebSocket client to the server. | +| OH_WebSocketClient_Close(struct WebSocket \*client, struct WebSocket_CloseOption options) | Lets the WebSocket client proactively close the connection. | +| OH_WebSocketClient_Destroy(struct WebSocket \*client) | Releases the context and resources of the WebSocket connection. | + +## Development Example + +### How to Develop + +To use related APIs to establish a connection to the WebSocket server, you need to create a Native C++ project, encapsulate the APIs in the source file, and call these APIs at the ArkTS layer. You can use hilog or console.log to print the log information on the console or generate device logs. + +The following walks you through on how to establish a connection to the WebSocket server, send messages to the WebSocket server, and close the WebSocket connection. + +### Adding Dependencies + +**Adding Dynamic Link Libraries** + +Add the following library to **CMakeLists.txt**. + +```txt +libace_napi.z.so +libnet_websocket.so +``` + +**Including Header Files** + +```c +#include "napi/native_api.h" +#include "network/netstack/net_websocket.h" +#include "network/netstack/net_websocket_type.h" +``` + +### Building the Project + +1. Write the API call code in the source file to allow applications to receive the URL string passed from ArkTS, create a pointer to the **WebSocketClient** object, and check whether the connection to the WebSocket server is successful. + +```cpp +#include "napi/native_api.h" +#include "network/netstack/net_websocket.h" +#include "network/netstack/net_websocket_type.h" +#include "hilog/log.h" + +#include + +#undef LOG_DOMAIN +#undef LOG_TAG +#define LOG_DOMAIN 0x3200 // Global domain, which identifies the service domain. +#define LOG_TAG "WSDEMO" // Global tag, which identifies the module log tag. + +// Global variables of the WebSocket client +static struct WebSocket *client = nullptr; + +static void onOpen(struct WebSocket *client, WebSocket_OpenResult openResult) +{ + (void)client; + OH_LOG_INFO(LOG_APP, "onOpen: code: %{public}u, reason: %{public}s", + openResult.code, openResult.reason); +} + +static void onMessage(struct WebSocket *client, char *data, uint32_t length) +{ + (void)client; + char *tmp = new char[length + 1]; + for (uint32_t i = 0; i < length; i++) { + tmp[i] = data[i]; + } + tmp[length] = '\0'; + OH_LOG_INFO(LOG_APP, "onMessage: len: %{public}u, data: %{public}s", + length, tmp); +} + +static void onError(struct WebSocket *client, WebSocket_ErrorResult errorResult) +{ + (void)client; + OH_LOG_INFO(LOG_APP, "onError: code: %{public}u, message: %{public}s", + errorResult.errorCode, errorResult.errorMessage); +} + +static void onClose(struct WebSocket *client, WebSocket_CloseResult closeResult) +{ + (void)client; + OH_LOG_INFO(LOG_APP, "onClose: code: %{public}u, reason: %{public}s", + closeResult.code, closeResult.reason); +} + +static napi_value ConnectWebsocket(napi_env env, napi_callback_info info) +{ + size_t argc = 2; + napi_value args[2] = {nullptr}; + napi_value result; + + napi_get_cb_info(env, info, &argc, args , nullptr, nullptr); + + size_t length = 0; + napi_status status = napi_get_value_string_utf8(env, args[0], nullptr, 0, &length); + if (status != napi_ok) { + napi_get_boolean(env, false, &result); + return result; + } + + if (client != nullptr) { + OH_LOG_INFO(LOG_APP, "there is already one websocket client running."); + napi_get_boolean(env, false, &result); + return result; + } + char *buf = new char[length + 1]; + std::memset(buf, 0, length + 1); + napi_get_value_string_utf8(env, args[0], buf, length + 1, &length); + // Create a pointer to the WebSocketClient object. + client = OH_WebSocketClient_Constructor(onOpen, onMessage, onError, onClose); + if (client == nullptr) { + delete[] buf; + napi_get_boolean(env, false, &result); + return result; + } + // Connect to the WebSocket server identified by the URL stored in the buffer. + int connectRet = OH_WebSocketClient_Connect(client, buf, {}); + + delete[] buf; + napi_get_boolean(env, connectRet == 0, &result); + return result; +} + +static napi_value SendMessage(napi_env env, napi_callback_info info) +{ + size_t argc = 1; + napi_value args[1] = {nullptr}; + napi_value result; + + napi_get_cb_info(env, info, &argc, args , nullptr, nullptr); + + size_t length = 0; + napi_status status = napi_get_value_string_utf8(env, args[0], nullptr, 0, &length); + if (status != napi_ok) { + napi_create_int32(env, -1, &result); + return result; + } + + if (client == nullptr) { + OH_LOG_INFO(LOG_APP, "websocket client not connected."); + napi_create_int32(env, WebSocket_ErrCode::WEBSOCKET_CLIENT_NULL, &result); + return result; + } + char *buf = new char[length + 1]; + std::memset(buf, 0, length + 1); + napi_get_value_string_utf8(env, args[0], buf, length + 1, &length); + // Send the messages in the buffer to the server. + int ret = OH_WebSocketClient_Send(client, buf, length); + + delete[] buf; + napi_create_int32(env, ret, &result); + return result; +} + +static napi_value CloseWebsocket(napi_env env, napi_callback_info info) +{ + napi_value result; + if (client == nullptr) { + OH_LOG_INFO(LOG_APP, "websocket client not connected."); + napi_create_int32(env, -1, &result); + return result; + } + // Close the WebSocket connection. + int ret = OH_WebSocketClient_Close(client, { + .code = 0, + .reason = "Actively Close", + }); + // Release the WebSocket resources. + OH_WebSocketClient_Destroy(client); + client = nullptr; + napi_create_int32(env, ret, &result); + return result; +} + +``` + +On receiving a WebSocket URL, the `ConnectWebsocket` function attempts to connect to the server identified by the URL. If the connection is successful, **true** is returned. Otherwise, **false** is returned. Before creating a pointer to the **WebSocketClient** object, define the **onOpen**, **onMessage**, **onError**, and **onClose** callbacks for the WebSocket connection. In the sample code, functions such as `OH_WebSocketClient_Send` and `OH_WebSocketClient_Close` are also called to send messages to the server and proactively close the WebSocket connection. + + +2. Initialize and export the `napi_value` objects encapsulated through **NAPI**, and expose the preceding functions to JavaScript through external function APIs. In the sample code, the `ConnectWebsocket` function is exposed as the external function `Connect`, the `SendMessage` function is exposed as the external function `Send`, and the `CloseWebsocket` function is exposed as the external function `Close`. + +```C +EXTERN_C_START +static napi_value Init(napi_env env, napi_value exports) { + napi_property_descriptor desc[] = { + {"Connect", nullptr, ConnectWebsocket, nullptr, nullptr, nullptr, napi_default, nullptr }, + {"Send", nullptr, SendMessage, nullptr, nullptr, nullptr, napi_default, nullptr }, + {"Close", nullptr, CloseWebsocket, nullptr, nullptr, nullptr, napi_default, nullptr}, + }; + napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); + return exports; +} +EXTERN_C_END +``` + +3. Register the objects successfully initialized in the previous step into the Node.js file by using the `napi_module_register` function of `RegisterEntryModule`. + +```C +static napi_module demoModule = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = Init, + .nm_modname = "entry", + .nm_priv = ((void*)0), + .reserved = { 0 }, +}; + +extern "C" __attribute__((constructor)) void RegisterEntryModule(void) +{ + napi_module_register(&demoModule); +} +``` + +4. Define the types of the functions in the `index.d.ts` file of the project. For example, the `Connect` function takes a string parameter as the input parameter and returns a Boolean value indicating whether the WebSocket connection is successfully established. + +```ts +export const Connect: (url: string) => boolean; +export const Send: (data: string) => number; +export const Close: () => number; +``` + +5. Call the encapsulated APIs in the `index.ets` file. + +```ts +import testWebsocket from 'libentry.so' + +@Entry +@Component +struct Index { + @State wsUrl: string = '' + @State content: string = '' + @State connecting: boolean = false + + build() { + Navigation() { + Column() { + Column() { + Text("WebSocket address: ") + .fontColor(Color.Gray) + .textAlign(TextAlign.Start) + .width('100%') + TextInput() + .width('100%') + .onChange((value) => { + this.wsUrl = value + }) + } + .margin({ + bottom: 16 + }) + .padding({ + left: 16, + right: 16 + }) + + Column() { + Text("Content: ") + .fontColor(Color.Gray) + .textAlign(TextAlign.Start) + .width('100%') + TextInput() + .width('100%') + .enabled(this.connecting) + .onChange((value) => { + this.content = value + }) + } + .margin({ + bottom: 16 + }) + .padding({ + left: 16, + right: 16 + }) + + Blank() + + Column({ space: 12 }) { + Button('Connect') + .enabled(!this.connecting) + .onClick(() => { + let connRet = testWebsocket.Connect(this.wsUrl) + if (connRet) { + this.connecting = true; + } + }) + Button('Send') + .enabled(this.connecting) + .onClick(() => { + testWebsocket.Send(this.content) + }) + Button('Close') + .enabled(this.connecting) + .onClick(() => { + let closeResult = testWebsocket.Close() + if (closeResult != -1) { + this.connecting = false + } + }) + } + } + } + } +} +``` + +6. Configure the `CMakeLists.txt` file. Add the required shared library, that is, `libnet_websocket.so`, to `target_link_libraries` in the `CMakeLists.txt` file automatically generated by the project. + +Note: As shown in the following figure, `entry` in `add_library` is the `modename` automatically generated by the project. If you want to change its value, ensure that it is the same as the `.nm_modname` in step 3. + +![netmanager-4.png](./figures/websocket-notemod.png) + +7. To call WebSocket C APIs, make sure that you have the `ohos.permission.INTERNET` permission. Add this permission to the `requestPermissions` item in the `module.json5` file. + +After the preceding steps, the entire project is set up. Then, you can connect to the device to run the project to view logs. + +## Test Procedure + +1. Connect the device and use DevEco Studio to open the project. + +2. Run the project. The following page is displayed. + +![Demo initial image](./figures/websocket-demo-1.jpg) + +Description of settings: + +- In the text box in the first line, enter a WebSocket URL starting with `ws://` or `wss://`. + +- Tap `Connect`. If the connection is successful, the **onOpen** callback is triggered and logs are printed. + +- Enter the content to be sent to the server in the `Content` text box and tap `Send`. If the server returns a message, the `onMessage` callback is triggered and logs are printed. + +- Tap `Close`. The WebSocket connection is released. You can enter a new WebSocket URL to establish a new connection. + +![Demo input](./figures/websocket-demo-2.jpg) + +![Demo log output](./figures/websocket-demo-log.png) diff --git a/en/application-dev/network/net-connection-manager.md b/en/application-dev/network/net-connection-manager.md index 2dbcbf740905b2834e91bdf0fcd7b6152ac21d33..1319954dba872d5e84969e8203a326a62b2ead92 100644 --- a/en/application-dev/network/net-connection-manager.md +++ b/en/application-dev/network/net-connection-manager.md @@ -5,11 +5,12 @@ The Network Connection Management module provides basic network management capabilities, including management of Wi-Fi/cellular/Ethernet connection priorities, network quality evaluation, subscription to network connection status changes, query of network connection information, and DNS resolution. > **NOTE** +> > To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the promise mode. For details about the APIs, see [API Reference](../reference/apis-network-kit/js-apis-net-connection.md). ## Basic Concepts -- Producer: a provider of data networks, such as Wi-Fi, cellular, and Ethernet. +- Producer: a provider of data networks, such as Wi-Fi, cellular, and Ethernet. - Consumer: a user of data networks, for example, an application or a system service. - Network probe: a mechanism used to detect the network availability to prevent the switch from an available network to an unavailable network. The probe type can be binding network detection, DNS detection, HTTP detection, or HTTPS detection. - Network selection: a mechanism used to select the optimal network when multiple networks coexist. It is triggered when the network status, network information, or network quality evaluation score changes. @@ -48,19 +49,18 @@ For the complete list of APIs and example code, see [Network Connection Manageme | getConnectionProperties(netHandle: NetHandle, callback: AsyncCallback\): void; |Obtains network connection information of the network corresponding to the **netHandle**. This API uses an asynchronous callback to return the result.| | getNetCapabilities(netHandle: NetHandle, callback: AsyncCallback\): void; |Obtains capability information of the network corresponding to the **netHandle**. This API uses an asynchronous callback to return the result.| | isDefaultNetMetered(callback: AsyncCallback\): void; |Checks whether the data traffic usage on the current network is metered. This API uses an asynchronous callback to return the result.| -| reportNetConnected(netHandle: NetHandle, callback: AsyncCallback\): void;| Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager. This API uses an asynchronous callback to return the result.| -| reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback\): void;| Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager. This API uses an asynchronous callback to return the result.| +| reportNetConnected(netHandle: NetHandle, callback: AsyncCallback\): void;| Reports a **netAvailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager. This API uses an asynchronous callback to return the result.| +| reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback\): void;| Reports a **netAvailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager. This API uses an asynchronous callback to return the result.| | getAddressesByName(host: string, callback: AsyncCallback\>): void; |Obtains all IP addresses of the specified network by resolving the domain name. This API uses an asynchronous callback to return the result.| | enableAirplaneMode(callback: AsyncCallback\): void; | Enables the airplane mode. This API uses an asynchronous callback to return the result.| | disableAirplaneMode(callback: AsyncCallback\): void;| Disables the airplane mode. This API uses an asynchronous callback to return the result.| -| createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection; | Creates a **NetConnection** object. **netSpecifier** specifies the network, and **timeout** specifies the timeout interval in ms. **timeout** is configurable only when **netSpecifier** is specified. If neither of them is present, the default network is used.| +| createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection; | Creates a **NetConnection** object. **netSpecifier** specifies the network to be concerned. **timeout** specifies the timeout interval in ms. **timeout** is configurable only when **netSpecifier** is specified. If neither of them is present, the default network is used.| | bindSocket(socketParam: TCPSocket \| UDPSocket, callback: AsyncCallback\): void; | Binds a **TCPSocket** or **UDPSocket** to the current network. This API uses an asynchronous callback to return the result.| -| getAddressesByName(host: string, callback: AsyncCallback\>): void; |Obtains all IP addresses of the specified network by resolving the domain name. This API uses an asynchronous callback to return the result.| | getAddressByName(host: string, callback: AsyncCallback\): void; |Obtains an IP address of the specified network by resolving the domain name. This API uses an asynchronous callback to return the result.| | on(type: 'netAvailable', callback: Callback\): void; |Subscribes to **netAvailable** events.| | on(type: 'netCapabilitiesChange', callback: Callback\): void; |Subscribes to **netCapabilitiesChange** events.| | on(type: 'netConnectionPropertiesChange', callback: Callback\<{ netHandle: NetHandle, connectionProperties: ConnectionProperties }>): void; |Subscribes to **netConnectionPropertiesChange** events.| -| on(type: 'netBlockStatusChange', callback: Callback<{ netHandle: NetHandle, blocked: boolean }>): void; |Subscribes to **netBlockStatusChange** events.| +| on(type: 'netBlockStatusChange', callback: Callback<{ netHandle: NetHandle, blocked: boolean }>): void; |Registers a listener for **netBlockStatusChange** events. This API uses an asynchronous callback to return the result.| | on(type: 'netLost', callback: Callback\): void; |Subscribes to **netLost** events.| | on(type: 'netUnavailable', callback: Callback\): void; |Subscribes to **netUnavailable** events.| | register(callback: AsyncCallback\): void; |Subscribes to network status changes.| @@ -69,22 +69,22 @@ For the complete list of APIs and example code, see [Network Connection Manageme ## Subscribing to Status Changes of the Specified Network 1. Declare the required permission: **ohos.permission.GET_NETWORK_INFO**. -This permission is of the **normal** level. Before applying for the permission, ensure that the [basic principles for permission management](../security/AccessToken/app-permission-mgmt-overview.md#basic-principles-for-using-permissions) are met. Declare the permissions required by your application. For details, see [Declaring Permissions in the Configuration File](accesstoken-guidelines.md#declaring-permissions-in-the configuration-file). +This permission is of the **normal** level. Before applying for the permission, ensure that the [basic principles for permission management](../security/AccessToken/app-permission-mgmt-overview.md#basic-principles-for-using-permissions) are met. Declare the permissions required by your application. For details, see [Declaring Permissions](../security/AccessToken/declare-permissions.md). -1. Import the **connection** namespace from **@kit.NetworkKit**. +2. Import the **connection** namespace from **@kit.NetworkKit**. -2. Call **createNetConnection()** to create a **NetConnection** object. You can specify the network type, capability, and timeout interval. If you do not specify parameters, the default values will be used. +3. Call [createNetConnection](../reference/apis-network-kit/js-apis-net-connection.md#connectioncreatenetconnection) to create a **NetConnection** object. You can specify the network type, capability, and timeout interval. If you do not specify parameters, the default values will be used. -3. Call **conn.on()** to subscribe to the target event. You must pass in **type** and **callback**. +4. Call [on()](../reference/apis-network-kit/js-apis-net-connection.md#onnetavailable) to subscribe to desired events. You must pass in **type** and **callback**. -4. Call **conn.register()** to subscribe to network status changes of the specified network. +5. Call [register()](../reference/apis-network-kit/js-apis-net-connection.md#register) to subscribe to network status changes of the specified network. -5. When the network is available, the callback will be invoked to return the **netAvailable** event. When the network is unavailable, the callback will be invoked to return the **netUnavailable** event. +6. When the network is available, the callback will be invoked to return the **netAvailable** event. When the network is unavailable, the callback will be invoked to return the **netUnavailable** event. -6. Call **conn.unregister()** to unsubscribe from the network status changes if required. +7. Call [unregister()](../reference/apis-network-kit/js-apis-net-connection.md#unregister) to unsubscribe from the network status changes. ```ts -// Import the connection namespace. +// Import the required namespaces. import { connection } from '@kit.NetworkKit'; import { BusinessError } from '@kit.BasicServicesKit'; @@ -108,12 +108,12 @@ conn.register((err: BusinessError, data: void) => { console.log(JSON.stringify(err)); }); -// Listen to network status change events. If the network is available, an on_netAvailable event is returned. +// Subscribe to network status change events. If the network is available, an on_netAvailable event is returned. conn.on('netAvailable', ((data: connection.NetHandle) => { console.log("net is available, netId is " + data.netId); })); -// Listen to network status change events. If the network is unavailable, an on_netUnavailable event is returned. +// Subscribe to network status change events. If the network is unavailable, an on_netUnavailable event is returned. conn.on('netUnavailable', ((data: void) => { console.log("net is unavailable, data is " + JSON.stringify(data)); })); @@ -255,14 +255,14 @@ Close the original socket and re-establish a socket connection when the default ## Obtaining the List of All Registered Networks 1. Declare the required permission: **ohos.permission.GET_NETWORK_INFO**. -This permission is of the **normal** level. Before applying for the permission, ensure that the [basic principles for permission management](../security/AccessToken/app-permission-mgmt-overview.md#basic-principles-for-using-permissions) are met. Declare the permissions required by your application. For details, see [Declaring Permissions in the Configuration File](accesstoken-guidelines.md#declaring-permissions-in-the configuration-file). +This permission is of the **normal** level. Before applying for the permission, ensure that the [basic principles for permission management](../security/AccessToken/app-permission-mgmt-overview.md#basic-principles-for-using-permissions) are met. Declare the permissions required by your application. For details, see [Declaring Permissions](../security/AccessToken/declare-permissions.md). 2. Import the **connection** namespace from **@kit.NetworkKit**. -3. Call **getAllNets** to obtain the list of all connected networks. +3. Call [getAllNets](../reference/apis-network-kit/js-apis-net-connection.md#connectiongetallnets) to obtain the list of all connected networks. ```ts -// Import the connection namespace. +// Import the required namespaces. import { connection } from '@kit.NetworkKit'; import { BusinessError } from '@kit.BasicServicesKit'; @@ -301,15 +301,15 @@ connection.getAllNets().then((data: connection.NetHandle[]) => { ## Querying Network Capability Information and Connection Information of Specified Data Network 1. Declare the required permission: **ohos.permission.GET_NETWORK_INFO**. -This permission is of the **normal** level. Before applying for the permission, ensure that the [basic principles for permission management](../security/AccessToken/app-permission-mgmt-overview.md#basic-principles-for-using-permissions) are met. Declare the permissions required by your application. For details, see [Declaring Permissions in the Configuration File](accesstoken-guidelines.md#declaring-permissions-in-the configuration-file). +This permission is of the **normal** level. Before applying for the permission, ensure that the [basic principles for permission management](../security/AccessToken/app-permission-mgmt-overview.md#basic-principles-for-using-permissions) are met. Declare the permissions required by your application. For details, see [Declaring Permissions](../security/AccessToken/declare-permissions.md). 2. Import the **connection** namespace from **@kit.NetworkKit**. -3. Call **getDefaultNet** to obtain the default data network via **NetHandle** or call **getAllNets** to obtain the list of all connected networks via **Array\**. +3. Call [getDefaultNet](../reference/apis-network-kit/js-apis-net-connection.md#connectiongetdefaultnet) to obtain the default data network specified by **NetHandle** or call [getAllNets](../reference/apis-network-kit/js-apis-net-connection.md#connectiongetallnets) to obtain the list of all connected networks specified by **Array\**. -4. Call **getNetCapabilities** to obtain the network capability information of the data network specified by **NetHandle**. The capability information includes information such as the network type (cellular, Wi-Fi, or Ethernet network) and the specific network capabilities. +4. Call [getNetCapabilities](../reference/apis-network-kit/js-apis-net-connection.md#connectiongetnetcapabilities) to obtain the network capability information of the data network specified by **NetHandle**. The capability information includes information such as the network type (cellular, Wi-Fi, or Ethernet network) and the specific network capabilities. -5. Call **getConnectionProperties** to obtain the connection information of the data network specified by **NetHandle**. +5. Call [getConnectionProperties](../reference/apis-network-kit/js-apis-net-connection.md#connectiongetconnectionproperties) to obtain the connection information of the data network specified by **NetHandle**. ```ts import { connection } from '@kit.NetworkKit'; @@ -339,7 +339,7 @@ export class GlobalContext { } } -// Call getDefaultNet to obtain the default data network specified by **NetHandle**. +// Call getDefaultNet to obtain the default data network specified by NetHandle. connection.getDefaultNet().then((data:connection.NetHandle) => { if (data.netId == 0) { // If the obtained netid of netHandler is 0 when no default network is specified, an exception has occurred and extra processing is needed. @@ -348,7 +348,7 @@ connection.getDefaultNet().then((data:connection.NetHandle) => { if (data) { console.info("getDefaultNet get data: " + JSON.stringify(data)); GlobalContext.getContext().netHandle = data; - // Obtain the network capability information of the data network specified by **NetHandle**. The capability information includes information such as the network type and specific network capabilities. + // Obtain the network capability information of the data network specified by NetHandle. The capability information includes information such as the network type and specific network capabilities. connection.getNetCapabilities(GlobalContext.getContext().netHandle).then( (data: connection.NetCapabilities) => { console.info("getNetCapabilities get data: " + JSON.stringify(data)); @@ -398,7 +398,7 @@ connection.getConnectionProperties(GlobalContext.getContext().netHandle).then((d console.info("getConnectionProperties get data: " + JSON.stringify(data)); }) -// Call getAllNets to obtain the list of all connected networks via Array. +// Call getAllNets to obtain the list of all connected networks specified by Array. connection.getAllNets().then((data: connection.NetHandle[]) => { console.info("getAllNets get data: " + JSON.stringify(data)); if (data) { @@ -424,14 +424,14 @@ connection.getAllNets().then((data: connection.NetHandle[]) => { ## Resolving the Domain Name of a Network to Obtain All IP Addresses 1. Declare the required permission: **ohos.permission.INTERNET**. -This permission is of the **normal** level. Before applying for the permission, ensure that the [basic principles for permission management](../security/AccessToken/app-permission-mgmt-overview.md#basic-principles-for-using-permissions) are met. Declare the permissions required by your application. For details, see [Declaring Permissions in the Configuration File](accesstoken-guidelines.md#declaring-permissions-in-the configuration-file). +This permission is of the **normal** level. Before applying for the permission, ensure that the [basic principles for permission management](../security/AccessToken/app-permission-mgmt-overview.md#basic-principles-for-using-permissions) are met. Declare the permissions required by your application. For details, see [Declaring Permissions](../security/AccessToken/declare-permissions.md). 2. Import the **connection** namespace from **@kit.NetworkKit**. -3. Call **getAddressesByName** to use the default network to resolve the host name to obtain the list of all IP addresses. +3. Call [getAddressesByName](../reference/apis-network-kit/js-apis-net-connection.md#connectiongetaddressesbyname) to use the default network to resolve the host name to obtain the list of all IP addresses. ```ts -// Import the connection namespace. +// Import the required namespaces. import { connection } from '@kit.NetworkKit'; import { BusinessError } from '@kit.BasicServicesKit'; diff --git a/en/application-dev/network/net-mgmt-overview.md b/en/application-dev/network/net-mgmt-overview.md index e56776e1106588f5b7f4feac7597215352cbb74a..718a6a4ee7f1b9f4748da4a26b77f7aea4dcd748 100644 --- a/en/application-dev/network/net-mgmt-overview.md +++ b/en/application-dev/network/net-mgmt-overview.md @@ -6,8 +6,7 @@ Network Kit provides the following functions: - [WebSocket connection](websocket-connection.md): establishes a bidirectional connection between the server and client through WebSocket. - [Socket connection](socket-connection.md): transmits data through Socket. - [Network connection management](net-connection-manager.md): provides basic network management capabilities, including management of Wi-Fi/cellular/Ethernet connection priorities, network quality evaluation, subscription to network connection status changes, query of network connection information, and DNS resolution. -- [mDNS management](net-mdns.md): provides Multicast DNS (mDNS) management capabilities, such as adding, removing, discovering, and resolving local services on a LAN. - +- [mDNS management](net-mdns.md): provides Multicast DNS (mDNS) management capabilities, such as adding, removing, discovering, and resolving local services on a LAN. - [Network sharing](net-sharing.md): shares a device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing, and queries the network sharing state and shared mobile data volume. - [Ethernet connection](net-ethernet.md): provides wired network capabilities, which allow you to set the IP address, subnet mask, gateway, and Domain Name System (DNS) server of a wired network. diff --git a/en/application-dev/network/net-netfirewall.md b/en/application-dev/network/net-netfirewall.md index ffaa775b5c9a882fdfd992ce0e7a4e073c930a76..076490769afde4d83960775c6271c6333fa0865a 100644 --- a/en/application-dev/network/net-netfirewall.md +++ b/en/application-dev/network/net-netfirewall.md @@ -1,8 +1,8 @@ -# Network Firewall (For System Applications Only) +# Network Firewall ## Introduction -Network firewalls provide the following functions: +The network firewall module provides the following functions: - Basic firewall management functions, such as enabling and disabling of firewalls and firewall rules, and audit. - Firewall rule configuration, including the rule name, description, operation, applicable application, protocol type, address, port, and outbound/inbound direction. - DNS policy configuration, including the domain names allowed or not allowed for resolution and the DNS server (active or standby) used for resolution (application level). @@ -26,9 +26,11 @@ Typical firewall scenarios include: 1. Restricting DNS resolution of an application for specific domain names (This function is applicable to standard unencrypted DNS protocols, but not encrypted and private DNS protocols.) 2. Restricting DNS resolution of specific applications for specific domain names (This function is applicable to standard unencrypted DNS protocols, but not encrypted and private DNS protocols.) 3. Putting interception rules into effect immediately after delivery (This function is applicable only to the TCP protocol. An intercepted TCP connection must be disconnected.) + - Traceable network access 1. Query of interception records for system applications 2. Automatic saving of interception rules and automatic recovery upon startup + The following describes the development procedure specific to each application scenario. @@ -38,19 +40,19 @@ For the complete list of APIs and example code, see [Network Firewall](../refere | Name | Description | | -------------------------------------------------------------------------------------------------- | ----------------- | -| setNetFirewallPolicy(userId: number, policy: NetFirewallPolicy): Promise\ | Sets the firewall status. | -| getNetFirewallPolicy(userId: number): Promise\ | Obtains the firewall status. | -| addNetFirewallRule(rule: NetFirewallRule): Promise\ | Adds firewall rules. | -| updateNetFirewallRule(rule: NetFirewallRule): Promise\ | Updates firewall rules. | -| removeNetFirewallRule(userId: number, ruleId: number): Promise\ | Removes firewall rules. | +| setNetFirewallPolicy(userId: number, policy: NetFirewallPolicy): Promise\ | Sets a firewall policy. | +| getNetFirewallPolicy(userId: number): Promise\ | Obtains a firewall policy. | +| addNetFirewallRule(rule: NetFirewallRule): Promise\ | Adds a firewall rule. | +| updateNetFirewallRule(rule: NetFirewallRule): Promise\ | Updates a firewall rule. | +| removeNetFirewallRule(userId: number, ruleId: number): Promise\ | Removes a firewall rule. | | getNetFirewallRules(userId: number, requestParam: RequestParam): Promise\ | Performs pagination query on firewall rules.| | getNetFirewallRule(userId: number, ruleId: number): Promise\ | Queries a firewall rule.| -| getInterceptedRecords(userId: number, requestParam: RequestParam): Promise\ | Queries firewall interception records.| +| getInterceptedRecords(userId: number, requestParam: RequestParam): Promise\ | Queries firewall interception records.| -## IP Address-based Access Control +## IP address-based access control 1. Use a network cable to connect the device to a network port. -2. Import the **netfirewall** namespace from **@ohos.net.netFirewall**. +2. Import the **netFirewall** namespace from **@kit.NetworkKit**. 3. Call **setNetFirewallPolicy** to enable the firewall. 4. Call **addNetFirewallRule** to add firewall rules. @@ -132,12 +134,12 @@ netFirewall.addNetFirewallRule(ipRule).then((result: number) => { ## Domain Name-based Access Control 1. Use a network cable to connect the device to a network port. -2. Import the **netFirewall** namespace from **@ohos.net.netfirewall**. +2. Import the **netFirewall** namespace from **@kit.NetworkKit**. 3. Call **setNetFirewallPolicy** to enable the firewall in user mode. 4. Call **addNetFirewallRule** to add firewall rules in user mode. ```ts -// Import the netfirewall namespace from @kit.NetworkKit. +// Import the netFirewall namespace from @kit.NetworkKit. import { netFirewall } '@kit.NetworkKit'; import { BusinessError } from '@kit.BasicServicesKit'; @@ -181,10 +183,11 @@ netFirewall.addNetFirewallRule(domainRule).then((result: number) => { }); ``` + ## Query of Firewall Interception Records 1. Use a network cable to connect the device to a network port. -2. Import the **netfirewall** namespace from **@ohos.net.netFirewall**. +2. Import the **netFirewall** namespace from **@kit.NetworkKit**. 3. Call **getInterceptRecords** to query firewall interception records in user mode. ```ts @@ -205,3 +208,4 @@ netFirewall.getInterceptedRecords(100, interceptRecordParam).then((result: netFi console.error("get intercept records failed: " + JSON.stringify(error)); }); ``` + diff --git a/en/application-dev/network/net-vpnExtension.md b/en/application-dev/network/net-vpnExtension.md new file mode 100644 index 0000000000000000000000000000000000000000..f86af2623df3e453e7638c1c55c8096170379019 --- /dev/null +++ b/en/application-dev/network/net-vpnExtension.md @@ -0,0 +1,244 @@ +# VPN Extension Ability Development + +## Introduction + +A virtual private network (VPN) is a dedicated network established on a public network. Unlike a traditional private network, a VPN does not require an end-to-end physical link between any two nodes. It is built over a network platform (for example, Internet) provided by a public network service provider. User data is transmitted over the logical link. + +OpenHarmony provides the VPN Extension solution for enhanced VPN management. The following guides you through on how to develop your own VPN client. + +> **NOTE** +> +> To maximize the application running efficiency, all APIs are called asynchronously in callback or promise mode. The following code examples use the promise mode. For details about the APIs, see [API Reference](../reference/apis-network-kit/js-apis-net-vpnExtension.md). + +## VPN Extension Ability UI + +With the VPN Extension APIs provided by OpenHarmony, you can build VPN services that support different protocols. OpenHarmony provides a UI for users to learn about VPN startup and connection. + +- When the VPN application sets up a connection for the first time, the VPN connection authorization dialog box is displayed. The dialog box prompts users whether to trust the VPN application and accept the VPN connection request. +- If the VPN connection is successful, a VPN icon (a key) is displayed in the status bar to remind the user that the VPN is connected. + +To facilitate the query and configuration, your VPN application needs to provide the following UIs: + +- UI for manually starting and stopping the VPN connection. +- UI for displaying the connection status of the VPN application in the notification bar or providing network statistics (such as the connection duration and traffic) of the VPN connection. Touching the notification in notification bar should bring your VPN application to the foreground. + +## Available APIs + +For details about the complete JavaScript APIs and sample code, see [API Reference](../reference/apis-network-kit/js-apis-net-vpnExtension.md). + +## Creating a VPN Extension Ability + +To enable your application to support the VPN functionality, you need to create an **ExtensionAbilities** instance inherited from **VpnExtensionAbility**. + +```ts +// Assume that the VNP application is named MyVpnExtAbility. Define it in module.json5. +"extensionAbilities": [ + { + "name": "MyVpnExtAbility", + "description": "vpnservice", + "type": "vpn", + "srcEntry": "./ets/serviceextability/MyVpnExtAbility.ts" + } +] +``` + +> **NOTE** +> +> If the DevEco Studio tool displays a message indicating unrecognizable **"type": "vpn"**, you need to manually add **vpn** to the **type** enums corresponding to **extensionAbilities** in the **toolchains\modulecheck\module.json** file of the SDK and clear the build cache. + +Next, you need to configure, start, and stop the VPN in the created **VpnExtensionAbility**. + +- Create a VPN tunnel. The TCP tunnel is used as an example. For details, see **TcpConnect()** in [vpn_client](https://gitee.com/openharmony/applications_app_samples/blob/master/code/BasicFeature/Connectivity/VPN/entry/src/main/cpp/vpn_client.cpp) demo project. +- Use [VpnConnection.protect](../reference/apis-network-kit/js-apis-net-vpnExtension.md#protect) to enable protection for the TCP tunnel. +- Construct VPN Config parameters. For details, see [VPN Config Parameters](#description-of-vpn-config-parameters). +- Use [VpnConnection.create](../reference/apis-network-kit/js-apis-net-vpnExtension.md#create) to establish a VPN connection. +- Process data of the virtual network interface card (vNIC), such as reading or writing data. + + +## Starting the VPN Extension Ability + +To start a connection from the VPN application, you need to call **startVpnExtensionAbility** with the **VpnExtensionAbility** information specified. Make sure that **bundleName** is the same as that of the VPN application, and **abilityName** is the name of the **VpnExtensionAbility** you created. The sample code is as follows: + +```ts +import { common, Want } from '@kit.AbilityKit'; +import { vpnExtension } from '@kit.NetworkKit'; + +let context = getContext(this) as common.VpnExtensionContext; +let want: Want = { + deviceId: "", + bundleName: "com.example.myvpndemo", + abilityName: "MyVpnExtAbility", +}; + +@Entry +@Component +struct Index { + @State message: string = 'Hello World'; + + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold).onClick(() => { + console.info("btn click") }) + Button('Start Extension').onClick(() => { + vpnExtension.startVpnExtensionAbility(want); + }).width('70%').fontSize(45).margin(16) + }.width('100%') + }.height('100%') + } +} +``` + +If your VPN app is not trusted by the user, the system displays a dialog box asking the user to authorize the VPN connection. After obtaining the authorization, the system automatically calls [onCreate](../reference/apis-network-kit/js-apis-VpnExtensionAbility.md#vpnextensionabilityoncreate) of the **VpnExtensionAbility**. + +Currently, only one active VPN connection is supported. If the application calls **startVpnExtensionAbility** when a VPN connection is active, it will receive a system rejection error. In this case, you are advised to remind the user to disconnect the active VPN connection first. + + + +## Stopping the VPN Extension Ability + +To stop a VPN connection, the VPN application needs to call **stopVpnExtensionAbility** with the target **VpnExtensionAbility** specified. The system verifies the permission of the caller. The caller of **stopVpnExtensionAbility** must have obtained the VPN connection authorization of the user and can only stop the **VpnExtensionAbility** it started. Therefore, make sure that the value of **bundleName** passed by the API is the same as that of the VPN application, and the value of **abilityName** is the same as that of the target **VpnExtensionAbility**. + +The sample code is as follows: + +```ts +import { common, Want } from '@kit.AbilityKit'; +import { vpnExtension } from '@kit.NetworkKit'; + +let context = getContext(this) as common.VpnExtensionContext; +let want: Want = { + deviceId: "", + bundleName: "com.example.myvpndemo", + abilityName: "MyVpnExtAbility", +}; + +@Entry +@Component +struct Index { + @State message: string = 'Hello World'; + + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold).onClick(() => { + console.info("btn click") }) + Button('Start Extension').onClick(() => { + vpnExtension.startVpnExtensionAbility(want); + }).width('70%').fontSize(45).margin(16) + Button('Stop Extension').onClick(() => { + console.info("btn end") + vpnExtension.stopVpnExtensionAbility(want); + }).width('70%').fontSize(45).margin(16) + + }.width('100%') + }.height('100%') + } +} +``` + +After the **VPNExtensionAbility** is stopped, call [onDestroy](../reference/apis-network-kit/js-apis-VpnExtensionAbility.md#vpnextensionabilityondestroy) to destroy the VPN connection and release related resources. + +```ts +import { vpnExtension, VpnExtensionAbility } from '@kit.NetworkKit'; +import { common, Want } from '@kit.AbilityKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +let context: vpnExtension.VpnExtensionContext; +export default class MyVpnExtAbility extends VpnExtensionAbility { + onDestroy() { + let VpnConnection : vpnExtension.VpnConnection = vpnExtension.createVpnConnection(context); + console.info("vpn createVpnConnection: " + JSON.stringify(VpnConnection)); + VpnConnection.destroy().then(() => { + console.info("destroy success."); + }).catch((error : BusinessError) => { + console.error("destroy fail" + JSON.stringify(error)); + }); + } +} +``` + +## Service Lifecycle Management + +To ensure network connectivity, the system automatically stops the VPN connection when detecting that the VPN application is abnormal: + +- The application process that calls **startVpnExtensionAbility** exits. +- The VPN service process is destroyed. + +## Description of VPN Config parameters + +| Name | Type | Mandatory| Description | +| ------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| addresses | Array\<[LinkAddress](../reference/apis-network-kit/js-apis-net-connection.md#linkaddress)\> | Yes | IP addresses of virtual network interface cards (vNICs). | +| routes | Array\<[RouteInfo](../reference/apis-network-kit/js-apis-net-connection.md#routeinfo)\> | No | Routes of vNICs. Currently, a maximum of 1024 routes can be configured. | +| dnsAddresses | Array\ | No | IP addresses of DNS servers. Trusted VPN applications can access the network through these IP addresses. If this parameter is not configured, IP address allocated by the system will be used.| +| searchDomains | Array\ | No | List of DNS search domains. | +| mtu | number | No | Maximum transmission unit (MTU), in bytes. | +| isIPv4Accepted | boolean | No | Whether IPv4 is supported. The default value is **true**. | +| isIPv6Accepted | boolean | No | Whether IPv6 is supported. The default value is **false**. | +| isInternal | boolean | No | Whether the built-in VPN is supported. The default value is **false**. | +| isBlocking | boolean | No | Whether the blocking mode is used. The default value is **false**. | +| trustedApplications | Array\ | No | Trusted VPN applications, which are represented by bundle names of the string type | +| blockedApplications | Array\ | No | Blocked VPN applications, which are represented by bundle names of the string type | + +**Example** + +```ts +import { vpnExtension} from '@kit.NetworkKit'; + +let vpnConfig: vpnExtension.VpnConfig = { + // Configure the IP address of the vNIC. + addresses: [{ + address: { + address:'192.x.x.5', + family:1 + }, + prefixLength:24 + }], + // Configure route information. + routes: [{ + // Set the name of the vNIC, which has a fixed value of vpn-tun. + interface: 'vpn-tun', + destination: { + address: { + address:'10.x.x.8', + family:1, + port:8080 + }, + prefixLength:24 + }, + gateway: { + address:'10.x.x.5', + family:1, + port:8080 + }, + hasGateway: false, + isDefaultRoute: false, + }], + // Configure the MTU. + mtu: 1400, + // Configure IP addresses of DNS serves. + dnsAddresses: ['223.x.x.5', '223.x.x.6'], + // Configure trusted VPN applications. + trustedApplications: ['com.test.browser'], + // Configure blocked VPN applications. + blockedApplications: ['com.test.games'], +} +let context: vpnExtension.VpnExtensionContext; + +function vpnCreate(){ + let VpnConnection: vpnExtension.VpnConnection = vpnExtension.createVpnConnection(context); + VpnConnection.create(vpnConfig).then((data) => { + console.info("vpn create " + JSON.stringify(data)); + }) +} +``` + + + +## VPN Demo + +The OpenHarmony project provides a sample application named [VPN](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Connectivity/VPN), which showcases how to implement the VPN service. diff --git a/en/application-dev/notification/notification-overview.md b/en/application-dev/notification/notification-overview.md index 719d07ac8fdef03e74ade2b57bcae89c50e71dc6..8bc668a0c60b4b5a3575e7bbaaeecedde0a763f1 100644 --- a/en/application-dev/notification/notification-overview.md +++ b/en/application-dev/notification/notification-overview.md @@ -46,7 +46,12 @@ Common notification styles in the Notification Kit are as follows. ## Constraints - There is a limit on the number of notifications per application in the system windows. The current limit is 24. - The notification cannot exceed 200 KB (due to cross-process serialization). -- The total number of notifications published by all system applications cannot exceed 10 per second, and that of notifications updated cannot exceed 20 per second. +- The publication and update frequencies for notifications must meet the following requirements. Otherwise, the publication or update fails and the corresponding error code is returned. + - The total number of notifications published by an application cannot exceed 10 per second, and that of notifications updated cannot exceed 20 per second. + - The total number of notifications published by all third-party applications cannot exceed 15 per second, and that of notifications updated cannot exceed 30 per second. + + - The total number of notifications published by all system applications cannot exceed 15 per second, and that of notifications updated cannot exceed 30 per second. + ## Relationship with Related Kits - Notifications created by Notification Kit are displayed in the notification panel in real time. To publish scheduled notifications when your application is in the background or is not running, you can use [BackGroundTask Kit](../reference/apis-backgroundtasks-kit/js-apis-backgroundTaskManager.md). For example, you can use it to publish a flash sale reminder for your shopping application. Currently, the notification reminder feature is available for countdown, calendar, and alarm events. diff --git a/en/application-dev/quick-start/Readme-EN.md b/en/application-dev/quick-start/Readme-EN.md index 3496a82b156e59541904a0d99bd9a61d7d76ac40..16ad3962a50b8b5fd8d1c65bff3ddd808a877f36 100644 --- a/en/application-dev/quick-start/Readme-EN.md +++ b/en/application-dev/quick-start/Readme-EN.md @@ -102,12 +102,13 @@ - [PersistenceV2: Persisting Application State](arkts-new-persistencev2.md) - [!! Syntax: Two-Way Binding](arkts-new-binding.md) - [Freezing a Custom Component](arkts-custom-components-freezeV2.md) - - [Repeat: Reusing Child Components](arkts-new-rendering-control-repeat.md) + - [Repeat: Reusable Repeated Rendering](arkts-new-rendering-control-repeat.md) - [getTarget API: Obtaining Original Objects](arkts-new-getTarget.md) - [makeObserved API: Changing Unobservable Data to Observable Data](arkts-new-makeObserved.md) - [MVVM (V2)](arkts-mvvm-V2.md) - Mixed Use and Migration Guide for V1 and V2 - [Mixing Use of Custom Components](arkts-custom-component-mixed-scenarios.md) + - [Mixing Use of State Management V1 and V2](arkts-v1-v2-mixusage.md) - [Migrating Applications from V1 to V2](arkts-v1-v2-migration.md) - Rendering Control - [Rendering Control Overview](arkts-rendering-control-overview.md) @@ -115,3 +116,4 @@ - [ForEach: Rendering Repeated Content](arkts-rendering-control-foreach.md) - [LazyForEach: Lazy Data Loading](arkts-rendering-control-lazyforeach.md) - [ContentSlot: Representing a Placeholder in Hybrid Development](arkts-rendering-control-contentslot.md) + diff --git a/en/application-dev/quick-start/app-clone.md b/en/application-dev/quick-start/app-clone.md index e5dbef9d3c8bb898cfaab753210586a37126291e..5dd1eaf2f1a0fc478e62fa9f4fb4832bf1b93592 100644 --- a/en/application-dev/quick-start/app-clone.md +++ b/en/application-dev/quick-start/app-clone.md @@ -12,11 +12,15 @@ The following figure shows the effect. ![Figure 1](figures/app-clone1.png) +## Constraints +The input method application cannot create an application clone. ## How to Develop -1. Configure the [multiAppMode](app-configuration-file.md#multiappmode) field in the **AppScope/application.json5** configuration file in the project. The code snippet is as follows: -```json +1. + + Configure the [multiAppMode](app-configuration-file.md#multiappmode) field in the **AppScope/application.json5** configuration file in the project. The code snippet is as follows: + ```json { "app": { "multiAppMode": { @@ -27,10 +31,12 @@ The following figure shows the effect. } ``` + + 2. Create an application clone. - Build and package the configured project and install it on the device. - + ![Figure 2](figures/app-clone4.png) - Choose **Settings** > **System** > **App Clone**, and touch **Create**. @@ -44,4 +50,3 @@ The following figure shows the effect. ![Figure 1](figures/app-clone1.png) The three applications in the figure are independent of each other in terms of running, data, and notification. - diff --git a/en/application-dev/quick-start/app-configuration-file.md b/en/application-dev/quick-start/app-configuration-file.md index 45678f250a96b535d4199d38a81dbd7f657c1731..b944aa57ac1cdd580cb373dbe65e0a10e042ae5f 100644 --- a/en/application-dev/quick-start/app-configuration-file.md +++ b/en/application-dev/quick-start/app-configuration-file.md @@ -57,15 +57,15 @@ As shown above, the **app.json5** file contains several tags. | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | | bundleName | Bundle name, which uniquely identifies an application. The value must comply with the following rules:
- The bundle name contains at least three segments, separated by periods (.). Each segment can contain only letters, digits, and underscores (_).
- The first segment starts with a letter, and other segments start with a digit or letter. Each segment ends with a digit or letter.
- Consecutive periods (.) are not allowed.
- Contains 7 to 128 bytes.
You are advised to use the reverse domain name notation, for example, *com.example.demo*, where the first part is the domain suffix **com**, the second part is the vendor/individual name, and the third part is the application name, which can be of multiple levels.
If an application is built with the system source code, you are advised to name it in *com.ohos.demo* notation, where **ohos** signifies that the application is a system application.| String| No| -| bundleType| Bundle type, which is used to distinguish applications and atomic services. The options are as follows:
- **app**: The bundle is an application.
- **atomicService**: The bundle is an atomic service.
- **shared**: The bundle is a shared library. This option is reserved.
- **appService**: The bundle is a system-level shared library and can be used only by system applications.| String| Yes (initial value: **app**)| -| debug | Whether the application can be debugged.
- **true**: Can be debugged. Used in the development phase.
- **false**: Cannot be debugged. Used in the release phase.| Boolean| Yes (initial value: **false**)
This tag is generated by DevEco Studio during compilation and build. | +| bundleType| Bundle type, which is used to distinguish applications and atomic services. The options are as follows:
- **app**: The bundle is an application.
- **atomicService**: The bundle is an atomic service.
- **shared**: The bundle is a shared library. This option is reserved.
- **appService**: The bundle is a system-level shared library and can be used only by system applications.
- **appPlugin**: The bundle is the plugin package of an application.| String| Yes (initial value: **app**)| +| debug | Whether the application can be debugged.
- **true**: Can be debugged. Used in the development phase.
- **false**: Cannot be debugged. Used in the release phase.| Boolean| Generated by DevEco Studio during compilation and building. Yes (initial value: **false**)| | [icon](#icon)| [Application icon](../application-models/application-component-configuration-stage.md). The value is the index to an icon resource file.| String| No| -| label | [Application name](../application-models/application-component-configuration-stage.md). The value is the index to a string resource. It is a string with a maximum of 63 bytes. | String| No| +| label | [Application name](../application-models/application-component-configuration-stage.md). The value is the index to a string resource. It is a string with a maximum of 63 bytes.| String| No| | description | Description of an application. The value is a string of a maximum of 255 bytes, indicating the string resource index of the description. This field can be used to display application information on, for example, the **About** page.| String| Yes (initial value: left empty)| | vendor | Vendor of the application. The value is a string with a maximum of 255 bytes. This field can be used to display the vendor information on, for example, the **About** page.| String| Yes (initial value: left empty)| | versionCode | Version code of the application. The value is a positive integer less than 2 to the power of 31. It is used only to determine whether a version is later than another version. A larger value indicates a later version.
Ensure that a new version of the application uses a value greater than any of its predecessors.| Number| No| | versionName | Version number of the application displayed to users.
The value contains a maximum of 127 bytes and consists of only digits and dots. The four-part format *A.B.C.D* is recommended, wherein:
Part 1 (*A*): major version number, which ranges from 0 to 99. A major version consists of major new features or large changes.
Part 2 (*B*): minor version number, which ranges from 0 to 99. A minor version consists of some new features or large bug fixes.
Part 3 (*C*): feature version number, which ranges from 0 to 99. A feature version consists of scheduled new features.
Part 4 (*D*): maintenance release number or patch number, which ranges from 0 to 999. A maintenance release or patch consists of resolution to security flaws or minor bugs.| String| No| -| minCompatibleVersionCode | Minimum historical version compatible with the application. It is used for collaboration across devices, data migration, and cross-device compatibility determination. This field is reserved and the value ranges from **0** to **2147483647**.| Number| Yes (initial value: value of **versionCode**)| +| minCompatibleVersionCode | Minimum historical version compatible with the application. It is used for collaboration across devices, data migration, and cross-device compatibility determination. This field is reserved and the value ranges from 0 to 2147483647.| Number| Yes (initial value: value of **versionCode**)| | minAPIVersion | Minimum API version required for running the application. The value ranges from 0 to 2147483647.| Number| Yes (initial value: value of **compatibleSdkVersion** in **build-profile.json5**)| | targetAPIVersion | Target API version required for running the application. The value ranges from 0 to 2147483647.| Number| Yes (initial value: value of **compileSdkVersion** in **build-profile.json5**)| | apiReleaseType | Type of the target API version required for running the application. The value can be **"CanaryN"**, **"BetaN"**, or **"Release"**, where **N** represents a positive integer.
- **Canary**: indicates a restricted release.
- **Beta**: indicates a publicly released beta version.
- **Release**: indicates a publicly released official version.| String| Yes (the value is automatically set by DevEco Studio based on the stage of the SDK in use; a manually set value will be overwritten during compilation and building)| @@ -94,13 +94,13 @@ As shown above, the **app.json5** file contains several tags. [Application icon](../application-models/application-component-configuration-stage.md) and the index to the layered icon configuration files. -Layered icons can be configured as follows: +The configuration of layered icons is as follows: -1. Place the foreground and background resources of the icon in the **AppScope/resources/base/media** directory. +1. Place the foreground and background resources of the icon in the **AppScope/resources/base/media** directory, or use the default foreground and background resources in the directory. -2. Create a JSON file (for example, **layered-image.json**) in the **media** directory and reference the foreground and background resources in the file. For details, see [Icon Resource Specifications](https://developer.huawei.com/consumer/en/doc/design-guides/application-icon-0000001953444009#section634668113212). +2. The **media** directory contains the **layered-image.json** file, which references foreground and background resources. For details, see [Icon Resource Specifications](https://developer.huawei.com/consumer/en/doc/design-guides/application-icon-0000001953444009#section634668113212). -Example of the layered icon resource file: +Example of the **layered-image.json** file: ```json { @@ -188,7 +188,7 @@ Example of the **configuration** structure: Define the **configuration.json** file under **AppScope/resources/base/profile** in the development view. The file name (**configuration** in this example) can be customized, but must be consistent with the information specified by the **configuration** tag. The file lists the attributes that enable the application font size to change with the system. - **Table 4** configuration +**Table 4** configuration | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | diff --git a/en/application-dev/quick-start/application-package-install-uninstall.md b/en/application-dev/quick-start/application-package-install-uninstall.md index 6c7955d74ed1a086d0ab96ee66ad84cc2c647c11..8a4e68fe1be23346ff73b4f37393c714d1108354 100644 --- a/en/application-dev/quick-start/application-package-install-uninstall.md +++ b/en/application-dev/quick-start/application-package-install-uninstall.md @@ -5,19 +5,22 @@ This topic describes how to install, uninstall, and update an application. ## Installing or Uninstalling an Application You can install and uninstall applications by running debug commands. For details, see the [compilation, release, and deployment process](./application-package-structure-stage.md#package-structure-in-the-release-phase). -**Figure 1** Process of installing and uninstalling an application (applicable to developers) +**Figure 1** Process of installing and uninstalling an application (applicable to developers) + ![hap-intall-uninstall](figures/hap-install-uninstall-developer.png) When an application has been released to the application market, consumers can install or uninstall the application on their device through the application market. **Figure 2** Process of installing and uninstalling an application (applicable to consumers) + ![hap-intall-uninstall](figures/hap-install-uninstall-user.png) ## Updating an Application -For developers, the application update and installation processes are the same. For users, the application may be updated in the following approaches: +For developers, to update an application, you need to first update the **versionCode** field in the [app.json5](./app-configuration-file.md#appjson5-configuration-file) file, package the application using DevEco Studio, and release the application in the AppGallery. For users, the application may be updated in the following approaches: + +- [On the AppGallery](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V14/store-update-V14?catalogVersion=V14): The application market notifies the user of an available update, and the user can install the update by following the onscreen instructions. +- [In the application](https://developer.huawei.com/consumer/en/doc/AppGallery-connect-Guides/appgallerykit-app-update-0000001055118286): When the application for which an update is available starts up, the AppGallery notifies the user of the update, and the user can install the update by following the onscreen instructions. -- In the application market: The application market notifies the user of an available update, and the user can install the update by following the onscreen instructions. -- In the application: When the application for which an update is available starts up, the application market notifies the user of the update, and the user can install the update by following the onscreen instructions. diff --git a/en/application-dev/quick-start/arkts-appstorage.md b/en/application-dev/quick-start/arkts-appstorage.md index c7f9654d7819279614a884142e35d21dcc2b9f3a..302377273a1b23e9f949588be6925189a9b97f8a 100644 --- a/en/application-dev/quick-start/arkts-appstorage.md +++ b/en/application-dev/quick-start/arkts-appstorage.md @@ -42,7 +42,7 @@ By decorating a variable with \@StorageProp(key), a one-way data synchronization | \@StorageProp Decorator| Description | | ----------------------- | ------------------------------------------------------------ | | Decorator parameters | **key**: constant string, mandatory (the string must be quoted) | -| Allowed variable types | Object, class, string, number, Boolean, enum, and array of these types.
(Applicable to API version 12 or later) Map, Set, and Date types. For details about the scenarios of nested objects, see [Observed Changes and Behavior](#observed-changes-and-behavior).
The type must be specified. Whenever possible, use the same type as that of the corresponding attribute in AppStorage. Otherwise, implicit type conversion occurs, which may cause application behavior exceptions.
**any** is not supported. **undefined** and **null** are supported since API version 12.
(Applicable to API version 12 or later) Union type of the preceding types, for example, **string \| number**, **string \| undefined** or **ClassA \| null**. For details, see [Union Type](#union-type).
**NOTE**
When **undefined** or **null** is used, you are advised to explicitly specify the type to pass the TypeScript type check. For example, **@StorageProp("AA") a: number \| null = null** is recommended; **@StorageProp("AA") a: number = null** is not recommended. | +| Allowed variable types | Object, class, string, number, Boolean, enum, and array of these types.
(Applicable to API version 12 or later) Map, Set, and Date types. For details about the scenarios of nested objects, see [Observed Changes and Behavior](#observed-changes-and-behavior).
The type must be specified. Whenever possible, use the same type as that of the corresponding attribute in AppStorage. Otherwise, implicit type conversion occurs, which may cause application behavior exceptions.
**any** is not supported. **undefined** and **null** are supported since API version 12.
(Applicable to API version 12 or later) Union type of the preceding types, for example, **string \| number**, **string \| undefined**, or **ClassA \| null**. For details, see [Union Type](#union-type).
**NOTE**
When **undefined** or **null** is used, you are advised to explicitly specify the type to pass the TypeScript type check. For example, **@StorageProp("AA") a: number \| null = null** is recommended; **@StorageProp("AA") a: number = null** is not recommended.| | Synchronization type | One-way: from the attribute in AppStorage to the component variable.
The component variable can be changed locally, but an update from AppStorage will overwrite local changes.| | Initial value for the decorated variable | Mandatory. If the attribute does not exist in AppStorage, it will be created and initialized with this value.| @@ -109,7 +109,7 @@ By decorating a variable with \@StorageProp(key), a one-way data synchronization | \@StorageLink Decorator| Description | | ------------------ | ---------------------------------------- | | Decorator parameters | **key**: constant string, mandatory (the string must be quoted) | -| Allowed variable types | Object, class, string, number, Boolean, enum, and array of these types.
(Applicable to API version 12 or later) Map, Set, and Date types. For details about the scenarios of nested objects, see [Observed Changes and Behavior](#observed-changes-and-behavior).
The type must be specified. Whenever possible, use the same type as that of the corresponding attribute in AppStorage. Otherwise, implicit type conversion occurs, which may cause application behavior exceptions.
**any** is not supported. **undefined** and **null** are supported since API version 12.
(Applicable to API version 12 or later) Union type of the preceding types, for example, **string \| number**, **string \| undefined** or **ClassA \| null**. For details, see [Union Type](#union-type).
**NOTE**
When **undefined** or **null** is used, you are advised to explicitly specify the type to pass the TypeScript type check. For example, **@StorageLink("AA") a: number \| null = null** is recommended; **@StorageLink("AA") a: number = null** is not recommended. | +| Allowed variable types | Object, class, string, number, Boolean, enum, and array of these types.
(Applicable to API version 12 or later) Map, Set, and Date types. For details about the scenarios of nested objects, see [Observed Changes and Behavior](#observed-changes-and-behavior-1).
The type must be specified. Whenever possible, use the same type as that of the corresponding attribute in AppStorage. Otherwise, implicit type conversion occurs, which may cause application behavior exceptions.
**any** is not supported. **undefined** and **null** are supported since API version 12.
(Applicable to API version 12 or later) Union type of the preceding types, for example, **string \| number**, **string \| undefined**, or **ClassA \| null**. For details, see [Union Type](#union-type).
**NOTE**
When **undefined** or **null** is used, you are advised to explicitly specify the type to pass the TypeScript type check. For example, **@StorageLink("AA") a: number \| null = null** is supported, but **@StorageLink("AA") a: number = null** is not.| | Synchronization type | Two-way: from the attribute in AppStorage to the custom component variable and vice versa| | Initial value for the decorated variable | Mandatory. If the attribute does not exist in AppStorage, it will be created and initialized with this value.| diff --git a/en/application-dev/quick-start/arkts-basic-syntax-overview.md b/en/application-dev/quick-start/arkts-basic-syntax-overview.md index 4a090c1679039d3117af0f5b1f882f56a8a21170..8ab222705dcf14ff16bc45bb7a3dbd2e07ca2ae8 100644 --- a/en/application-dev/quick-start/arkts-basic-syntax-overview.md +++ b/en/application-dev/quick-start/arkts-basic-syntax-overview.md @@ -22,19 +22,17 @@ In this example, the basic composition of ArkTS is as follows. > The name of a custom variable cannot be the same as that of any universal attribute or event. -- Decorator: design pattern used to decorate classes, structs, methods, and variables to assign special meanings to them. In the preceding sample code, \@Entry, \@Component, and \@State are decorators. [@Component](arkts-create-custom-components.md#basic-structure-of-a-custom-component) indicates a custom component, [@Entry](arkts-create-custom-components.md#basic-structure-of-a-custom-component) indicates that the custom component is an entry component, and [@State](arkts-state.md) indicates a state variable in the component, whose change will trigger the UI to re-render. +- Decorator: design pattern used to decorate classes, structs, methods, and variables to assign special meanings to them. In the preceding figure, the [@Component](arkts-create-custom-components.md#component) decorator indicates the custom component, the [@Entry](arkts-create-custom-components.md#entry) decorator indicates that the custom component is an entry component, and the [@State](arkts-state.md) decorator indicates the state variables in the component, whose changes trigger the UI re-render. -- [UI description](arkts-declarative-ui-description.md): declarative description of the UI structure, such as the code block of the **build()** method. +- [UI description](arkts-declarative-ui-description.md): declarative description of the UI structure, such as the code block of **build()**. - [Custom component](arkts-create-custom-components.md): reusable UI unit, which can be used with other components, such as the struct **Hello** decorated by @Component. - Built-in component: default basic or container component preset in ArkTS, which can be directly invoked, such as **Column**, **Text**, **Divider**, and **Button** components in the sample code. -- Attribute method: method used to configure component attributes, such as **fontSize()**, **width()**, **height()**, and **backgroundColor()**. You can configure multiple attributes of a component in method chaining mode. +- [Attribute method](../reference/apis-arkui/arkui-ts/ts-component-general-attributes.md): A component can configure multiple attributes through chain calls, such as **fontSize()**, **width()**, **height()**, and **backgroundColor()**. -- Event method: method used to add the logic for a component to respond to an event. In the sample code, **onClick()** following **Button** is an event method. You can configure response logic for multiple events in method chaining mode. - -- For details about how to use built-in components, attribute methods, and event methods, see [ArkTS-based Declarative Development Paradigm](../reference/apis-arkui/arkui-ts/ts-universal-events-click.md). +- [Event method](../reference/apis-arkui/arkui-ts/ts-component-general-events.md): A component can set the response logic of multiple events through chain calls, for example, **onClick()** following **Button**. ArkTS extends multiple syntax paradigms to make development a more enjoyable experience. @@ -45,3 +43,11 @@ ArkTS extends multiple syntax paradigms to make development a more enjoyable exp - [@Extend](arkts-extend.md)/[@Styles](arkts-style.md): decorator that extends built-in components and encapsulates attribute styles to combine built-in components more flexibly. - [stateStyles](arkts-statestyles.md): polymorphic style, which can be set based on the internal state of the component. + +## + + + +- + +- diff --git a/en/application-dev/quick-start/arkts-builder.md b/en/application-dev/quick-start/arkts-builder.md index e29314105ed5a5d8c46d811e09e8c0555929c06b..244826a52db2ac79a9afd090772b3fb7cc52c510 100644 --- a/en/application-dev/quick-start/arkts-builder.md +++ b/en/application-dev/quick-start/arkts-builder.md @@ -17,7 +17,7 @@ Before reading this topic, you are advised to read [Basic Syntax Overview](./ark The \@Builder decorator can be used for the private custom build function defined in the custom component and global custom build function defined globally. -### Private Custom Build Function +### Private Custom Builder Function Syntax: @@ -330,7 +330,8 @@ function overBuilder() { struct customBuilderDemo { @State arr: number[] = [0, 1, 2, 3, 4]; - @Builder privateBuilder() { + @Builder + privateBuilder() { Row() { Text('Local Builder') .fontSize(30) @@ -342,7 +343,7 @@ struct customBuilderDemo { Column() { List({ space: 10 }) { ForEach(this.arr, (item: number) => { - ListItem(){ + ListItem() { Text(`${item}`) .width('100%') .height(100) @@ -351,15 +352,17 @@ struct customBuilderDemo { .borderRadius(10) .backgroundColor(0xFFFFFF) } - .swipeAction({ - start: { - builder: overBuilder() - }, - end: { - builder: () => { this.privateBuilder() } + .swipeAction({ + start: { + builder: overBuilder() + }, + end: { + builder: () => { + this.privateBuilder() } - }) - }, (item: string) => JSON.stringify(item)) + } + }) + }, (item: number) => JSON.stringify(item)) } } } diff --git a/en/application-dev/quick-start/arkts-builderparam.md b/en/application-dev/quick-start/arkts-builderparam.md index 64dafbdfe48f982501576a8b04b56284c39039bd..2eb550d21a3fda5c439ae35062251c20dff2424b 100644 --- a/en/application-dev/quick-start/arkts-builderparam.md +++ b/en/application-dev/quick-start/arkts-builderparam.md @@ -77,7 +77,7 @@ An \@BuilderParam decorated method can be initialized only by an \@Builder funct ```ts @Component struct Child { - label: string = `Child`; + label: string = 'Child'; @Builder customBuilder() {}; @Builder customChangeThisBuilder() {}; @BuilderParam customBuilderParam: () => void = this.customBuilder; @@ -94,7 +94,7 @@ An \@BuilderParam decorated method can be initialized only by an \@Builder funct @Entry @Component struct Parent { - label: string = `Parent`; + label: string = 'Parent'; @Builder componentBuilder() { Text(`${this.label}`) @@ -283,7 +283,7 @@ const builder_value: string = 'Hello World'; @Entry @ComponentV2 struct ParentPage { - @Local label: string = `Parent Page`; + @Local label: string = 'Parent Page'; @Builder componentBuilder() { Row(){ @@ -321,7 +321,7 @@ In a custom component, the \@BuilderParam decorated variable is used to receive ```ts @Component struct ChildPage { - label: string = `Child Page`; + label: string = 'Child Page'; @Builder customBuilder() {}; @BuilderParam customBuilderParam: () => void = this.customBuilder; @BuilderParam customChangeThisBuilderParam: () => void = this.customBuilder; @@ -346,7 +346,7 @@ const builder_value: string = 'Hello World'; @Entry @Component struct ParentPage { - label: string = `Parent Page`; + label: string = 'Parent Page'; @Builder componentBuilder() { Row(){ @@ -389,12 +389,12 @@ struct ParentPage { ### Using @BuilderParam in a @ComponentV2 Decorated Custom Component -Use global @Builder and local @Builder to initialize the @BuilderParam attribute of the @CompoentV2 decorated custom component. +Use global @Builder and local @Builder to initialize the @BuilderParam attribute of the @ComponentV2 decorated custom component. ```ts @ComponentV2 struct ChildPage { - @Param label: string = `Child Page`; + @Param label: string = 'Child Page'; @Builder customBuilder() {}; @BuilderParam customBuilderParam: () => void = this.customBuilder; @BuilderParam customChangeThisBuilderParam: () => void = this.customBuilder; @@ -419,7 +419,7 @@ const builder_value: string = 'Hello World'; @Entry @ComponentV2 struct ParentPage { - @Local label: string = `Parent Page`; + @Local label: string = 'Parent Page'; @Builder componentBuilder() { Row(){ @@ -472,7 +472,7 @@ When the custom component **ChildPage** is called, \@Builder is passed as a para ```ts @Component struct ChildPage { - @State label: string = `Child Page`; + @State label: string = 'Child Page'; @Builder customBuilder() {}; @BuilderParam customChangeThisBuilderParam: () => void = this.customBuilder; @@ -486,7 +486,7 @@ struct ChildPage { @Entry @Component struct ParentPage { - @State label: string = `Parent Page`; + @State label: string = 'Parent Page'; @Builder componentBuilder() { Row(){ @@ -519,7 +519,7 @@ The dynamic UI rendering can also be implemented by changing @Builder to @LocalB ```ts @Component struct ChildPage { - @State label: string = `Child Page`; + @State label: string = 'Child Page'; @Builder customBuilder() {}; @BuilderParam customChangeThisBuilderParam: () => void = this.customBuilder; @@ -533,7 +533,7 @@ struct ChildPage { @Entry @Component struct ParentPage { - @State label: string = `Parent Page`; + @State label: string = 'Parent Page'; @Builder componentBuilder() { Row(){ diff --git a/en/application-dev/quick-start/arkts-create-custom-components.md b/en/application-dev/quick-start/arkts-create-custom-components.md index d7314a81a4cda338c51265659db742b2564750fb..9097c5edc8d3d8abb1487f48b484b30c715eb8bb 100644 --- a/en/application-dev/quick-start/arkts-create-custom-components.md +++ b/en/application-dev/quick-start/arkts-create-custom-components.md @@ -40,6 +40,8 @@ struct HelloComponent { Multiple **HelloComponent** instances can be created in **build()** of other custom components. In this way, **HelloComponent** is reused by those custom components. + + ```ts @Entry @Component @@ -109,7 +111,7 @@ The \@Component decorator can decorate only the structs declared by the **struct } ``` -### The build Function +### build() The **build** function is used to define the declarative UI description of a custom component. Every custom component must define a **build** function. @@ -129,7 +131,7 @@ A custom component decorated with \@Entry is used as the default entry component > > This decorator can be used in ArkTS widgets since API version 9. > - > Since API version 10, the \@Entry decorator accepts an optional parameter of type [LocalStorage](arkts-localstorage.md) or type [EntryOptions](#entryOptions). + > Since API version 10, the \@Entry decorator accepts an optional parameter of type [LocalStorage](arkts-localstorage.md) or type [EntryOptions](#entryoptions10). > > This decorator can be used in atomic services since API version 11. @@ -394,7 +396,7 @@ Whatever declared in **build()** are called UI descriptions. UI descriptions mus } ``` -- Directly changing a state variable is not allowed. For details, see [Changing State Variables in build() Is Forbidden](./arkts-state.md#changing-state-variables-in-build-is-forbidden). The following example should be avoided: +- Directly changing a state variable is not allowed. The following example should be avoided. For details, see [Changing State Variables in build() Is Forbidden](./arkts-state.md#changing-state-variables-in-build-is-forbidden). ```ts @Component diff --git a/en/application-dev/quick-start/arkts-custom-component-mixed-scenarios.md b/en/application-dev/quick-start/arkts-custom-component-mixed-scenarios.md index 0c747fd9a85157521fc2e916ec096e3bcab753ff..c72a705edd4d39df1efa00091bce77dcd5424e33 100644 --- a/en/application-dev/quick-start/arkts-custom-component-mixed-scenarios.md +++ b/en/application-dev/quick-start/arkts-custom-component-mixed-scenarios.md @@ -1,14 +1,15 @@ # Mixing Use of Custom Components -For the \@Component decorated custom components (referred to as the custom components of V1), corresponding state variable decorators (referred to as the decorators of V1), such as \@State, \@Prop, and \@Link, are provided. However, state management V1 (V1 for short) has many restrictions on the observation of nested classes. For example, you need to use \@ObjectLink to continuously disassemble nested classes so that in-depth data can be observed. Therefore, a new set of state management V2 (V2 for short) is developed in API version 12. You can declare \@ComponentV2 decorated custom components (referred to as custom components of V2) and use them with new decorators (referred to as the decorators of V2), such as \@Local and \@Param. The proposal of V2 not only compensates the deficiency of V1 in nested class observation, but also enhances some decorator functions. For example, compared with \@Watch of V1, \@Monitor of V2 can sense the changed data and obtain the data before the change. +For the \@Component decorated custom components (referred to as the custom components of V1), corresponding state variable decorators (referred to as the decorators of V1), such as \@State, \@Prop, and \@Link, are provided. However, state management V1 (V1 for short) has many restrictions on the observation of nested classes. For example, you need to use \@ObjectLink to continuously disassemble nested classes so that in-depth data can be observed. Therefore, a new set of state management V2 (V2 for short) is provided in API version 12. You can declare \@ComponentV2 decorated custom components (referred to as custom components of V2) and use them with new decorators (referred to as the decorators of V2), such as \@Local and \@Param. The proposal of V2 not only compensates the deficiency of V1 in nested class observation, but also enhances some decorator functions. For example, compared with \@Watch of V1, \@Monitor of V2 can sense the changed data and obtain the data before the change. In terms of design, the code of V1 and V2 are expected to be completely isolated because V2 can do better than V1 in certain scenarios. However, from the actual perspective, the code developed in V1 have a solid foundation and it is not practical to migrate the entire code to V2 at a time. Therefore, it is allowed to use some capabilities of V2 in the code of V1 and capabilities of V1 is not completely prohibited in V2. For example, a custom component of V1 uses a custom component of V2, or V1 uses a decorator of V2. In this way, a problem of mixed use of V1 and V2 occurs. -This document describes the mixed use of V1 and V2, aiming at guiding you to migrate code of V1 to V2. +This topic describes the mixed use of V1 and V2, aiming at guiding you to migrate code of V1 to V2. > **NOTE** > > State management V2 is supported since API version 12. +> The rules for mixed use described in this topic apply only to API version 17 and earlier. Since API version 18, state management provides new APIs [enableV2Compatibility](../reference/apis-arkui/js-apis-StateManagement.md#enablev2compatibility18) and [makeV1Observed](../reference/apis-arkui/js-apis-StateManagement.md#makev1observed18) to help you solve the problem of mixed use during the migration from V1 to V2. For details, see [Mixing Use of State Management V1 and V2](./arkts-v1-v2-mixusage.md). ## Overview @@ -497,7 +498,7 @@ struct Child { Divider() .color(Color.Blue) - Text ('undefineVal:${this.undefineVal}') // Display undefineVal. + Text(`undefineVal:${this.undefineVal}`) // Display undefineVal. .fontSize(30) .fontWeight(FontWeight.Bold) .onClick(() => { @@ -505,7 +506,7 @@ struct Child { }) Divider() .color(Color.Blue) - Text ('info id:${this.info.myId}') // Display info:myId. + Text(`info id:${this.info.myId}`) // Display info:myId. .fontSize(30) .fontWeight(FontWeight.Bold) .onClick(() => { @@ -596,7 +597,7 @@ struct Child { }) Divider() .color(Color.Blue) - Text ('info id:${this.info.myId}') // Display info:myId. + Text('info id:${this.info.myId}') // Display info:myId. .fontSize(30) .fontWeight(FontWeight.Bold) .onClick(() => { @@ -885,7 +886,7 @@ struct GrandSon { build() { Column() { - Text ('ObjectLink info info.myId:${this.info.myId}') // After @ObjectLink disassembles the level twice, the change is observable. + Text(`ObjectLink info info.myId:${this.info.myId}`) // After @ObjectLink disassembles the level twice, the change is observable. .fontSize(30) .onClick(() => { this.info.myId++; @@ -1043,3 +1044,5 @@ The sample code shows: * \@ObservedV2 and \@Trace nest the observation capability to the class properties. Therefore, when a class property is marked by @Trace, the change can be observed regardless of the number of nested levels. * When \@ObservdV2 and \@Observed are used together, the decorator used by the outermost class determines whether the class object can be decorated by the decorator of V1. For example, the class decorated by \@ObservedV2 in the lower level does not affect the outermost class decorated by the decorator of V1. + + \ No newline at end of file diff --git a/en/application-dev/quick-start/arkts-custom-components-access-restrictions.md b/en/application-dev/quick-start/arkts-custom-components-access-restrictions.md index 0f0f4fbe8fd9d0e4cab2ed0f051c9292fa1d9b93..dcbd5d4956a0b6753978b3c536232c37cc89656d 100644 --- a/en/application-dev/quick-start/arkts-custom-components-access-restrictions.md +++ b/en/application-dev/quick-start/arkts-custom-components-access-restrictions.md @@ -1,6 +1,6 @@ # Constraints on Access Modifiers of Custom Component Member Variables -In state management V1, after you encapsulates a custom component, the caller cannot determine the input variables as the component input parameters based on the unified standard because the component does not have specific input and output identifiers. +In state management V1, after you encapsulate a custom component, the invoker cannot determine the input variables as the component input parameters based on the unified standard because the component does not have specific input and output identifiers. You can use the **private** qualifier to prevent the current variable from being externally initialized. To prevent a state variable from being initialized externally, you can use the **private** qualifier to remind the component caller. However, external initialization must comply with the rules of the decorator. For details, see [Constraints](#constraints). @@ -17,7 +17,7 @@ Before reading this topic, you are advised to read [State Management Overview](. - The regular variables (which do not involve re-rendering) and variables decorated by [\@State](./arkts-state.md), [\@Prop](./arkts-prop.md), [\@Provide](./arkts-provide-and-consume.md), or [\@BuilderParam](./arkts-builderparam.md) can be initialized externally or using local values. However, **private** access is not allowed. -- Variables decorated by [\@StorageLink](./arkts-appstorage.md), [\@StorageProp](./arkts-appstorage.md), [\@LocalStorageLink](./arkts-localstorage.md), [\@LocalStorageProp](./arkts-localstorage.md), or [\@Consume](./arkts-provide-and-consume.md) cannot be initialized externally. Therefore, **public** access is not allowed. +- Variables decorated by [\@StorageLink](./arkts-appstorage.md#storagelink), [\@StorageProp](./arkts-appstorage.md#storageprop), [\@LocalStorageLink](./arkts-localstorage.md#localstoragelink), [\@LocalStorageProp](./arkts-localstorage.md#localstorageprop), or [\@Consume](./arkts-provide-and-consume.md) cannot be initialized externally. Therefore, **public** access is not allowed. - Variables decorated by [\@Link](./arkts-link.md) or [\@ObjectLink](./arkts-observed-and-objectlink.md) must be initialized externally and local initialization is prohibited. Therefore, **private** access is not allowed. @@ -139,7 +139,7 @@ struct ComponentsChild { } ``` -2. If a member variable is decorated by both the **public** access modifier and the \@StorageLink, \@StorageProp, \@LocalStorageLink, \@LocalStorageProp, or \@Consume decorator, and is initialized through the parent component, a build error is reported. +2. If a member variable is decorated by both **public** and the \@StorageLink, \@StorageProp, \@LocalStorageLink, \@LocalStorageProp, or \@Consume decorator, and is initialized through the parent component, a build error is reported. [Negative Example] ```ts @@ -219,7 +219,7 @@ struct ComponentChild { } ``` -3. If a member variable is decorated by both the **private** access modifier and the \@Link/ or \@ObjectLink decorator, and is initialized through the parent component, a build error is reported. +3. If a member variable is decorated by both **private** and the \@Link/ or \@ObjectLink decorator, and is initialized through the parent component, a build error is reported. [Negative Example] ```ts @@ -296,7 +296,7 @@ struct ComponentChild { } ``` -4. If a member variable is decorated by the **protected** access modifier and is initialized through the parent component, a build error is reported. +4. If a member variable is decorated by **protected** and is initialized through the parent component, a build error is reported. [Negative Example] ```ts @@ -357,7 +357,7 @@ struct ComponentChild { } ``` -5. If a member variable is decorated by both the **private** access modifier and the \@Require, \@State, \@Prop, \@Provide, or \@BuilderParam decorator, and is initialized through the parent component, a build error is reported. +5. If a member variable is decorated by both **private** and the \@Require, \@State, \@Prop, \@Provide, or \@BuilderParam decorator, and is initialized through the parent component, a build error is reported. [Negative Example] ```ts diff --git a/en/application-dev/quick-start/arkts-custom-components-freeze.md b/en/application-dev/quick-start/arkts-custom-components-freeze.md index d85bdbfd20767eb7d8dfcc1fea04aaaac3b0bf84..7cb2dc4451624aa8976dc5c118c32fcf9004a809 100644 --- a/en/application-dev/quick-start/arkts-custom-components-freeze.md +++ b/en/application-dev/quick-start/arkts-custom-components-freeze.md @@ -16,7 +16,7 @@ Note that the active or inactive state of a component is not equivalent to its v 3. LazyForEach: Only the custom component in the currently displayed LazyForEach is in the active state, and the component of the cache node is in the inactive state. 4. Navigation: Only the custom component in the currently displayed NavDestination is in the active state. 5. Component reuse: The component that enters the reuse pool is in the inactive state, and the node attached from the reuse pool is in the active state. -6. Mixed use: For example, if **LazyForEach** is used under **TabContent**, all nodes in **LazyForEach** of API version 15 or earlier are set to the active state since when switching tabs. Since API version 16, only the on-screen nodes of **LazyForEach** are set to the active state, and other nodes are set to the inactive state. +6. Mixed use: For example, if **LazyForEach** is used under **TabContent**, all nodes in **LazyForEach** of API version 17 or earlier are set to the active state since when switching tabs. Since API version 18, only the on-screen nodes of **LazyForEach** are set to the active state, and other nodes are set to the inactive state. Before reading this topic, you are advised to read [Creating a Custom Component](./arkts-create-custom-components.md) to learn about the basic syntax. @@ -24,7 +24,7 @@ Before reading this topic, you are advised to read [Creating a Custom Component] > > Custom component freezing is supported since API version 11. > -> Mixed use of custom component freezing is supported since API version 16. +> Mixed use of custom component freezing is supported since API version 18. ## Use Scenarios @@ -550,7 +550,7 @@ In the preceding example: ### Reusing Components -[Components reuse](../performance/component-recycle.md) existing nodes in the cache pool instead of creating new nodes to optimize UI performance and improve application smoothness. Although the nodes in the reuse pool are not displayed in the UI component tree, the change of the state variable still triggers the UI re-render. To solve the problem that components in the reuse pool are re-rendered abnormally, you can perform component freezing. +[Components reuse](./arkts-reusable.md) existing nodes in the cache pool instead of creating new nodes to optimize UI performance and improve application smoothness. Although the nodes in the reuse pool are not displayed in the UI component tree, the change of the state variable still triggers the UI re-render. To solve the problem that components in the reuse pool are re-rendered abnormally, you can perform component freezing. #### Mixed Use of Component Reuse, if, and Component Freezing The following example shows that when the state variable bound to the **if** component changes to **false**, the detach of **ChildComponent** is triggered. Because **ChildComponent** is marked as component reuse, it is not destroyed but enters the reuse pool, in this case, if the component freezing is enabled at the same time, the component will not be re-rendered in the reuse pool. @@ -625,7 +625,7 @@ In this case, if you trigger the re-render of all subnodes in **List**, the numb Example: 1. Swipe the list to the position whose index is 14. There are 15 **ChildComponent** in the visible area on the current page. 2. During swiping: - - **ChildComponent** in the upper part of the list is swiped out of the visible area. In this case, **ChildComponent** enters the cache area of LazyForEach and is set to inactive. After the component slides out of the **LazyForEach** area, the component is not destructed and enters the reuse pool because the component is marked for reuse. In this case, the component is set to inactive again. + - **ChildComponent** in the upper part of the list is swiped out of the visible area. In this case, **ChildComponent** enters the cache area of LazyForEach and is set to inactive. After the component slides out of the **LazyForEach** cache area, the component is not destructed and enters the reuse pool because the component is marked for reuse. In this case, the component is set to inactive again. - The cache node of **LazyForEach** at the bottom of the list enters the list. In this case, the system attempts to create a node to enter the cache of **LazyForEach**. If a node that can be reused is found, the system takes out the existing node from the reuse pool and triggers the **aboutToReuse** lifecycle callback, in this case, the node enters the cache area of **LazyForEach** and the state of the node is still inactive. 3. Click **change desc** to trigger the change of the member variable **desc** of **Page**. - The change of \@State decorated **desc** will be notified to \@Link decorated **desc** of **ChildComponent**. @@ -788,7 +788,7 @@ struct Page { ``` #### Mixed Use of LazyForEach, if, Component Reuse, and Component Freezing -Under the same parent custom component, reusable nodes may enter the reuse pool in different ways. For example: + Under the same parent custom component, reusable nodes may enter the reuse pool in different ways. For example: - Detaching from the cache area of LazyForEach by swiping. - Notifying the subnodes to detach by switching the if condition. @@ -975,7 +975,7 @@ struct Page { ### Mixing the Use of Components -In the scenario where mixed use of component freezing is supported, the freezing behavior varies according to the API version. Set the component freezing flag for the parent component. In API version 15 or earlier, when the parent component is unfrozen, all nodes of its child components are unfrozen. Since API version 16, when the parent component is unfrozen, only the on-screen nodes of the child component are unfrozen. +In the scenario where mixed use of component freezing is supported, the freezing behavior varies according to the API version. Set the component freezing flag for the parent component. In API version 17 or earlier, when the parent component is unfrozen, all nodes of its child components are unfrozen. Since API version 18, when the parent component is unfrozen, only the on-screen nodes of the child component are unfrozen. #### Mixed Use of Navigation and TabContent @@ -1153,9 +1153,9 @@ struct pageTwoStack { Final effect -![freeze](figures/freeze_tabcontent.png) +![freeze](figures/freeze_tabcontent.gif) -There are two tabs on the page. By default, the component freezing function is enabled on the **Update** tab. If the **Tabcontent** tab is not selected, the state variable is not refreshed. +Click the **Next Page** button to enter the **pageOne** page. There are two tabs on the page and the **Update** tab is displayed by default. Enable component freezing. If the **Tabcontent** tab is not selected, the state variable is not refreshed. Click the **Incr state** button to query **Appmonitor** in the log. Three records are displayed. @@ -1165,13 +1165,13 @@ Switch to the **DelayUpdate** tab and click the **Incr state** button to query * ![freeze](figures/freeze_tabcontent_delayupdate.png) -For API version 15 or earlier: +For API version 17 or earlier: Click **Next page** to enter the next page and then return. The tab is **DelayUpdate** by default. Click **Incr state** to query **Appmonitor** in the log and four records are displayed. When the page route is returned, all tabs of **Tabcontent** are unfrozen. ![freeze](figures/freeze_tabcontent_back_api15.png) -For API version 16 or later: +For API version 18 or later: Click **Next page** to enter the next page and then return. The tab is **DelayUpdate** by default. Click **Incr state** to query **Appmonitor** in the log and two records are displayed. When the page route is returned, only the nodes with the corresponding tabs are unfrozen. @@ -1347,13 +1347,13 @@ Swipe down **LazyForEach** to add nodes to **cachedCount**. Click the **add sum* ![freeze](figures/freeze_lazyforeach_add.png) -For API version 15 or earlier: +For API version 17 or earlier: Turn off and on the screen to trigger **OnPageShow** and then click **add sum**. The number of printed records is equal to the number of on-screen nodes and the **cachedCount** nodes. ![freeze](figures/freeze_lazyforeach_api15.png) -For API version 16 or later: +For API version 18 or later: Turn off and on the screen to trigger **OnPageShow** and then click **add sum**. Only the number of on-screen nodes is displayed, and the **cachedCount** nodes are not unfrozen. diff --git a/en/application-dev/quick-start/arkts-custom-components-freezeV2.md b/en/application-dev/quick-start/arkts-custom-components-freezeV2.md index 3ee05193d715fe95e97f96568b4f3b9599ce138a..2bad10d57845132344ec23230c182ff58266ea3a 100644 --- a/en/application-dev/quick-start/arkts-custom-components-freezeV2.md +++ b/en/application-dev/quick-start/arkts-custom-components-freezeV2.md @@ -6,9 +6,9 @@ Before reading this topic, you are advised to read [\@ComponentV2](./arkts-new-c > **NOTE** > -> @ComponentV2 decorated custom component freezing is supported since API version 12. +> Freezing of @ComponentV2 decorated custom component is supported since API version 12. > -> Mixed use of custom component freezing is supported since API version 16. +> Mixed use of custom component freezing is supported since API version 18. > > Different from freezing the @Component decorated components, custom components decorated by @ComponentV2 do not support freezing the cached list items in the **LazyForEach** scenario. @@ -350,7 +350,11 @@ In the preceding example: ### Repeat virtualScroll -Freeze the custom components in the Repeat virtualScroll cache pool to avoid unnecessary component re-renders. You are advised to read [Component Generation and Reuse Rules](./arkts-new-rendering-control-repeat.md#virtualscroll-1) of **Repeat** in advance. +> **NOTE** +> +> Repeat virtualScroll supports custom component freezing since API version 18. + +Freeze the custom components in the Repeat virtualScroll cache pool to avoid unnecessary component re-renders. You are advised to read [Child Component Rendering Logic](./arkts-new-rendering-control-repeat.md#child-component-rendering-logic-1) of virtualScroll in advance. ```ts @Entry @@ -452,7 +456,7 @@ struct ChildComponent { ### Mixed Use of Component Freezing -In the scenario where mixed use of component freezing is supported, the freezing behavior varies according to the API version. Set the component freezing flag for the parent component. In API version 15 or earlier, when the parent component is unfrozen, all nodes of its child components are unfrozen. Since API version 16, when the parent component is unfrozen, only the on-screen nodes of the child component are unfrozen. For details, see [Mixing the Use of Components](./arkts-custom-components-freeze.md#mixing-the-use-of-components). +In the scenario where mixed use of component freezing is supported, the freezing behavior varies according to the API version. Set the component freezing flag for the parent component. In API version 17 or earlier, when the parent component is unfrozen, all nodes of its child components are unfrozen. Since API version 18, when the parent component is unfrozen, only the on-screen nodes of the child component are unfrozen. For details, see [Mixing the Use of Components](./arkts-custom-components-freeze.md#mixing-the-use-of-components). #### Mixing Use of Navigation and TabContent @@ -622,11 +626,11 @@ struct pageTwoStack { } ``` -For API version 15 or earlier: +For API version 17 or earlier: Click **Next page** to enter the next page and then return to the previous page. All labels of **Tabcontent** are unfrozen. -For API version 16 or later: +For API version 18 or later: Click **Next page** to enter the next page and then return to the previous page. Only the nodes with the corresponding labels are unfrozen. @@ -763,3 +767,5 @@ struct FreezeBuildNode { Click **Button("change")** to change the value of **message**. The **onMessageUpdated** method registered in @Watch of the **TabContent** component that is being displayed is triggered, and that under the **BuilderNode** node of **TabContent** that is not displayed is also triggered. ![builderNode.gif](figures/builderNode.gif) + + \ No newline at end of file diff --git a/en/application-dev/quick-start/arkts-environment.md b/en/application-dev/quick-start/arkts-environment.md index c414a3223a11841b4b4611a60ea51f5ad18253cc..347db384f4bc1dcb1d0746945253271bc5da29c8 100644 --- a/en/application-dev/quick-start/arkts-environment.md +++ b/en/application-dev/quick-start/arkts-environment.md @@ -20,7 +20,7 @@ Before reading this topic, you are advised to read [AppStorage](./arkts-appstora | fontScale | number | Font scale. To enable the font scale to change with the system, set the [configuration](./app-configuration-file.md#configuration) tag. | | fontWeightScale | number | Font weight. | | layoutDirection | LayoutDirection | Layout direction. The options are as follows:
- **LayoutDirection.LTR**: from left to right.
- **LayoutDirection.RTL**: from right to left. | -| languageCode | string | Current system language. The value is in lowercase, for example, **zh**. | +| languageCode | string | System language value. The value must be in lowercase, for example, **zh**. | ## Use Scenarios @@ -38,7 +38,7 @@ Before reading this topic, you are advised to read [AppStorage](./arkts-appstora - Decorate the variables with \@StorageProp to link them with components. ```ts - @StorageProp('languageCode') lang : string = 'en'; + @StorageProp('languageCode') lang: string = 'en'; ``` The chain of updates is as follows: Environment > AppStorage > Component. @@ -73,7 +73,7 @@ struct Index { ```ts -// Use Environment.EnvProp to save the device language code to AppStorage. +// Use Environment.envProp to save the device language code to AppStorage. Environment.envProp('languageCode', 'en'); // Obtain the one-way bound languageCode variable from AppStorage. const lang: SubscribedAbstractProperty = AppStorage.prop('languageCode'); diff --git a/en/application-dev/quick-start/arkts-link.md b/en/application-dev/quick-start/arkts-link.md index 76ca85450ccdb40e81c30e861e501940a9a2a351..2078d250a94b0aea289a6cd728709b4c44d32fe9 100644 --- a/en/application-dev/quick-start/arkts-link.md +++ b/en/application-dev/quick-start/arkts-link.md @@ -22,7 +22,7 @@ An \@Link decorated variable in a child component shares the same value with a v | ------------------------------------------------------------ | ------------------------------------------------------------ | | Decorator parameters | None. | | Synchronization type | Two-way:
The state variable in the parent component can be synchronized with the child component \@Link in a two-way manner. When one of them changes, the other can sense the change.| -| Allowed variable types | Object, class, string, number, Boolean, enum, and array of these types.
Date type.
(Applicable to API version 11 or later) Map and Set types.
The union types defined by the ArkUI framework, including Length, ResourceStr, and ResourceColor, are supported.
The type must be specified and must be the same as that of the counterpart variable of the parent component.
For details about the scenarios of supported types, see [Observed Changes](#observed-changes).
**any** is not supported.
(Applicable to API version 11 and later versions) Union type of the preceding types, for example, **string \| number**, **string \| undefined** or **ClassA \| null**. For details, see [Union Type @Link](#union-type-link).
**NOTE**
When **undefined** or **null** is used, you are advised to explicitly specify the type to pass the TypeScript type check. For example, **@Link a: string \| undefined = undefined**. | +| Allowed variable types | Object, class, string, number, Boolean, enum, and array of these types.
Date type.
(Applicable to API version 11 or later) Map and Set types.
The union types defined by the ArkUI framework, including Length, ResourceStr, and ResourceColor, are supported.
The type must be specified and must be the same as that of the counterpart variable of the parent component.
For details about the scenarios of supported types, see [Observed Changes](#observed-changes).
**any** is not supported.
(Applicable to API version 11 and later versions) Union type of the preceding types, for example, **string \| number**, **string \| undefined**, or **ClassA \| null**. For details, see [Union Type @Link](#union-type-link).
**NOTE**
When **undefined** or **null** is used, you are advised to explicitly specify the type to pass the TypeScript type check. For example, **@Link a: string \| undefined**.| | Initial value for the decorated variable | Forbidden. | @@ -130,153 +130,153 @@ To understand the value initialization and update mechanism of the \@Link decora 2. The \@Link in the child component and \@State in the parent component traverse the dependent system components and update the corresponding UI. In this way, the \@Link decorated variable in the child component is synchronized back to the \@State decorated variable in the parent component. -## Restrictions +## Constraints 1. The @Link decorator cannot be used in custom components decorated by [\@Entry](https://gitee.com/openharmony/docs/blob/master/en/application-dev/quick-start/arkts-create-custom-components.md#basic-structure-of-a-custom-component). 2. Do not initialize variables decorated by \@Link locally. Otherwise, an error will be reported during compilation. -```ts -// Incorrect format. An error is reported during compilation. -@Link count: number = 10; + ```ts + // Incorrect format. An error is reported during compilation. + @Link count: number = 10; -// Correct format. -@Link count: number; -``` + // Correct format. + @Link count: number; + ``` 3. The type of the variable decorated by \@Link must be the same as the data source type. Otherwise, the framework throws a runtime error. -[Incorrect Example] + [Incorrect Example] -```ts -class Info { - info: string = 'Hello'; -} + ```ts + class Info { + info: string = 'Hello'; + } -class Cousin { - name: string = 'Hello'; -} + class Cousin { + name: string = 'Hello'; + } -@Component -struct Child { - // Incorrect format. The data source types of @Link and @State are different. - @Link test: Cousin; + @Component + struct Child { + // Incorrect format. The data source types of @Link and @State are different. + @Link test: Cousin; - build() { - Text(this.test.name) + build() { + Text(this.test.name) + } } -} -@Entry -@Component -struct LinkExample { - @State info: Info = new Info(); + @Entry + @Component + struct LinkExample { + @State info: Info = new Info(); - build() { - Column() { - // Incorrect format. The data source types of @Link and @State are different. - Child({test: new Cousin()}) + build() { + Column() { + // Incorrect format. The data source types of @Link and @State are different. + Child({test: new Cousin()}) + } } } -} -``` + ``` -[Correct Example] + [Correct Example] -```ts -class Info { - info: string = 'Hello'; -} + ```ts + class Info { + info: string = 'Hello'; + } -@Component -struct Child { - // Correct format. - @Link test: Info; + @Component + struct Child { + // Correct format. + @Link test: Info; - build() { - Text(this.test.info) + build() { + Text(this.test.info) + } } -} -@Entry -@Component -struct LinkExample { - @State info: Info = new Info(); + @Entry + @Component + struct LinkExample { + @State info: Info = new Info(); - build() { - Column() { - // Correct format. - Child({test: this.info}) + build() { + Column() { + // Correct format. + Child({test: this.info}) + } } } -} -``` + ``` 4. \@Link decorated variables can be initialized only by state variables. Initializing the variables using constants will cause a warn alarm during compilation, and an error "is not callable" is reported during runtime. -[Incorrect Example] + [Incorrect Example] -```ts -class Info { - info: string = 'Hello'; -} + ```ts + class Info { + info: string = 'Hello'; + } -@Component -struct Child { - @Link msg: string; - @Link info: string; + @Component + struct Child { + @Link msg: string; + @Link info: string; - build() { - Text(this.msg + this.info) + build() { + Text(this.msg + this.info) + } } -} -@Entry -@Component -struct LinkExample { - @State message: string = 'Hello'; - @State info: Info = new Info(); + @Entry + @Component + struct LinkExample { + @State message: string = 'Hello'; + @State info: Info = new Info(); - build() { - Column() { - // Incorrect format. Common variables cannot initialize the @Link decorated variables. - Child({msg: 'World', info: this.info.info}) + build() { + Column() { + // Incorrect format. Common variables cannot initialize the @Link decorated variables. + Child({msg: 'World', info: this.info.info}) + } } } -} -``` + ``` -[Correct Example] + [Correct Example] -```ts -class Info { - info: string = 'Hello'; -} + ```ts + class Info { + info: string = 'Hello'; + } -@Component -struct Child { - @Link msg: string; - @Link info: Info; + @Component + struct Child { + @Link msg: string; + @Link info: Info; - build() { - Text(this.msg + this.info.info) + build() { + Text(this.msg + this.info.info) + } } -} -@Entry -@Component -struct LinkExample { - @State message: string = 'Hello'; - @State info: Info = new Info(); + @Entry + @Component + struct LinkExample { + @State message: string = 'Hello'; + @State info: Info = new Info(); - build() { - Column() { - // Correct format. - Child({msg: this.message, info: this.info}) + build() { + Column() { + // Correct format. + Child({msg: this.message, info: this.info}) + } } } -} -``` + ``` 5. \@Link cannot decorate variables of the function type. Otherwise, the framework throws a runtime error. @@ -510,7 +510,7 @@ struct Child { build() { Column() { - ForEach(Array.from(this.message.entries()), (item: [number, string]) => { + ForEach(Array.from(this.message.entries()), (item: [number, number]) => { Text(`${item[0]}`).fontSize(30) Divider() }) @@ -739,7 +739,7 @@ struct Parent { ### Using the a.b(this.object) Format Fails to Trigger UI Re-render -In the **build** method, when the variable decorated by @Link is of the object type and is called using the **a.b(this.object)** format, the native object of **this.object** is passed in the b method. If the property of **this.object** is changed, the UI cannot be re-rendered. In the following example, when the static method **Score.changeScore1** or **this.changeScore2** is used to change **this.score.value** in the **Child** component, the UI is not re-rendered. +In the **build** method, when the variable decorated by @Link is of the object type and is called using the **a.b(this.object)** format, the original object of **this.object** is passed in the b method. If the property of **this.object** is changed, the UI cannot be re-rendered. In the following example, when the static method **Score.changeScore1** or **this.changeScore2** is used to change **this.score.value** in the **Child** component, the UI is not re-rendered. [Incorrect Example] @@ -861,4 +861,4 @@ struct Child { } ``` - + diff --git a/en/application-dev/quick-start/arkts-localBuilder.md b/en/application-dev/quick-start/arkts-localBuilder.md index 5a019c6b63b41928d2f7da4fa9f53c308709d33a..026b2c6b6762ba298cec3de91fa39ef73412965b 100644 --- a/en/application-dev/quick-start/arkts-localBuilder.md +++ b/en/application-dev/quick-start/arkts-localBuilder.md @@ -1,4 +1,4 @@ -# \@LocalBuilder decorator: Maintaining the Parent-Child Relationship Between Component and State Management +# \@LocalBuilder Decorator: Maintaining the Parent-Child Relationship Between Component and State Management When use @Builder to pass data, the parent-child relationship of components is considered. After **bind(this)** is used, the parent-child relationship of components is inconsistent with that of state management. As a result, the @LocalBuilder decorator is used to fix the inconsistency. @LocalBuilder has the same features as local @Builder and provides a better determination of the parent-child relationship of components and state management. @@ -8,7 +8,6 @@ Before reading this topic, you are advised to read [\@Builder](./arkts-builder.m > > This decorator is supported since API version 12. > -> ## How to Use @@ -61,7 +60,8 @@ For @LocalBuilder functions, parameters can be passed [by value](#by-value-param ### By-Reference Parameter Passing In by-reference parameter passing, state variables can be passed, and the change of these state variables causes the UI re-rendering in the \@LocalBuilder decorated method. -If the child component calls the @LocalBuilder function of the parent component and the input parameters are changed, the UI in the \@LocalBuilder method is not re-rendered. + +Note that if the \@LocalBuilder function is used together with the **$$** parameter, the passed parameters change when the child component calls the @LocalBuilder function of the parent component and the UI in \@LocalBuilder is not re-rendered. Use scenario: @@ -80,13 +80,13 @@ struct Parent { @LocalBuilder citeLocalBuilder(params: ReferenceType) { Row() { - Text(`UseStateVarByReference: ${params.paramString} `) + Text(`UseStateVarByReference: ${params.paramString}`) } }; build() { Column() { - this.citeLocalBuilder({ paramString: this.variableValue }); + this.citeLocalBuilder({ paramString: this.variableValue }) Button('Click me').onClick(() => { this.variableValue = 'Hi World'; }) @@ -112,7 +112,7 @@ struct HelloComponent { build() { Row() { - Text(`HelloComponent===${this.message}`); + Text(`HelloComponent===${this.message}`) } } } @@ -126,15 +126,15 @@ struct Parent { citeLocalBuilder($$: ReferenceType) { Row() { Column() { - Text(`citeLocalBuilder===${$$.paramString}`); - HelloComponent({ message: $$.paramString }); + Text(`citeLocalBuilder===${$$.paramString}`) + HelloComponent({ message: $$.paramString }) } } } build() { Column() { - this.citeLocalBuilder({ paramString: this.variableValue }); + this.citeLocalBuilder({ paramString: this.variableValue }) Button('Click me').onClick(() => { this.variableValue = 'Hi World'; }) @@ -145,93 +145,74 @@ struct Parent { The child component references the @LocalBuilder function of the parent component with a state variable as the parameter. The change of the state variable does not trigger the UI re-render in the @LocalBuilder method because the function decorated by @Localbuilder is bound to the parent component and only the current component and its child components are re-rendered. Therefore, the re-render of the parent component cannot be triggered. If @Builder is used, the UI can be re-rendered. The reason is that @Builder has the pointer of the **this** keyword changed. In this case, the function is bound to the child component, and the UI can be re-rendered. -Use scenario: -The **Child** component passes the @State decorated **label** value to the @Builder and @LocalBuilder functions of the **Parent** component. In the @Builder decorated function, **this** points to **Child** and parameter changes trigger UI re-render, while in the @LocalBuilder decorated function, **this** points to **Parent** and UI re-render cannot be triggered. +Use scenario: +The **Child** component passes the state variable to the @Builder and @LocalBuilder functions of the **Parent** component. In the @Builder function, **this** points to the **Child** component and parameter changes can trigger a UI re-rendering. In the @LocalBuilder function, **this** points to the **Parent** component and parameter changes cannot trigger the UI re-rendering. If the state variable of **Parent** referenced in the @LocalBuilder function changes, the UI can be re-rendered properly. ```ts -class LayoutSize { - size:number = 0; +class Data { + size: number = 0; } @Entry @Component struct Parent { - label:string = 'parent'; - @State layoutSize:LayoutSize = {size:0}; - - @LocalBuilder - // @Builder - componentBuilder($$:LayoutSize) { - Text(`${'this :'+this.label}`); - Text(`${'size :'+$$.size}`); - } - - build() { - Column() { - Child({contentBuilder: this.componentBuilder }); - } + label: string = 'parent'; + @State data: Data = new Data(); + + @Builder + componentBuilder($$: Data) { + Text(`builder + $$`) + Text(`${'this -> ' + this.label}`) + Text(`${'size : ' + $$.size}`) + Text(`------------------------`) } -} - -@Component -struct Child { - label:string = 'child'; - @BuilderParam contentBuilder:((layoutSize: LayoutSize) => void); - @State layoutSize:LayoutSize = {size:0}; - build() { - Column() { - this.contentBuilder({size: this.layoutSize.size}); - Button("add child size").onClick(()=>{ - this.layoutSize.size += 1; - }) - } + @LocalBuilder + componentLocalBuilder($$: Data) { + Text(`LocalBuilder + $$ data`) + Text(`${'this -> ' + this.label}`) + Text(`${'size : ' + $$.size}`) + Text(`------------------------`) } -} -``` - -Use scenario: - -The **Child** component passes the @State decorated **label** value of the **Parent** component referenced by @Link to the @Builder and @LocalBuilder functions of the **Parent** component. In the @Builder decorated function, **this** points to **Child** and parameter changes trigger UI re-render, while in the @LocalBuilder decorated function, **this** points to **Parent** and UI re-render cannot be triggered. - -```ts -class LayoutSize { - size:number = 0; -} - -@Entry -@Component -struct Parent { - label:string = 'parent'; - @State layoutSize:LayoutSize = {size:0}; @LocalBuilder - // @Builder - componentBuilder($$:LayoutSize) { - Text(`${'this :'+this.label}`); - Text(`${'size :'+$$.size}`); + contentLocalBuilderNoArgument() { + Text(`LocalBuilder + local data`) + Text(`${'this -> ' + this.label}`) + Text(`${'size : ' + this.data.size}`) + Text(`------------------------`) } build() { Column() { - Child({contentBuilder: this.componentBuilder,layoutSize:this.layoutSize}); + Child({ + contentBuilder: this.componentBuilder, + contentLocalBuilder: this.componentLocalBuilder, + contentLocalBuilderNoArgument: this.contentLocalBuilderNoArgument, + data: this.data + }) } } } @Component struct Child { - label:string = 'child'; - @BuilderParam contentBuilder:((layoutSize: LayoutSize) => void); - @Link layoutSize:LayoutSize; + label: string = 'child'; + @Builder customBuilder() {}; + @BuilderParam contentBuilder: ((data: Data) => void) = this.customBuilder; + @BuilderParam contentLocalBuilder: ((data: Data) => void) = this.customBuilder; + @BuilderParam contentLocalBuilderNoArgument: (() => void) = this.customBuilder; + @Link data: Data; build() { Column() { - this.contentBuilder({size: this.layoutSize.size}); - Button("add child size").onClick(()=>{ - this.layoutSize.size += 1; + this.contentBuilder({ size: this.data.size }) + this.contentLocalBuilder({ size: this.data.size }) + this.contentLocalBuilderNoArgument() + Button("add child size").onClick(() => { + this.data.size += 1; }) } } @@ -256,13 +237,13 @@ struct Parent { @LocalBuilder citeLocalBuilder(paramA1: string) { Row() { - Text(`UseStateVarByValue: ${paramA1} `) + Text(`UseStateVarByValue: ${paramA1}`) } } build() { Column() { - this.citeLocalBuilder(this.label); + this.citeLocalBuilder(this.label) } } } @@ -281,7 +262,7 @@ When the **componentBuilder** function is decorated by @Builder, the **Child** c ```ts @Component struct Child { - label: string = `Child`; + label: string = 'Child'; @BuilderParam customBuilderParam: () => void; build() { @@ -294,7 +275,7 @@ struct Child { @Entry @Component struct Parent { - label: string = `Parent`; + label: string = 'Parent'; @Builder componentBuilder() { Text(`${this.label}`) diff --git a/en/application-dev/quick-start/arkts-localstorage.md b/en/application-dev/quick-start/arkts-localstorage.md index 912f573b20e9cc806a8bec06fe8ac55ad3f8751b..907623f62d8424872122c1bc5a6f6a39b084c5e0 100644 --- a/en/application-dev/quick-start/arkts-localstorage.md +++ b/en/application-dev/quick-start/arkts-localstorage.md @@ -7,7 +7,7 @@ LocalStorage provides storage for the page-level UI state. The parameters of the This topic describes only the LocalStorage application scenarios and related decorators: \@LocalStorageProp and \@LocalStorageLink. -Before reading this topic, you are advised to read [State Management Overview](./arkts-state-management-overview.md) to have a basic understanding of the state management framework. +Before reading this topic, you are advised to read [State Management Overview](./arkts-state-management-overview.md) to have a basic understanding of the positioning of AppStorage in the state management framework. LocalStorage also provides APIs for you to manually add, delete, change, and query keys of Storage outside the custom component. You are advised to read this topic together with [LocalStorage API reference](../reference/apis-arkui/arkui-ts/ts-state-management.md#localstorage9). @@ -59,7 +59,7 @@ By decorating a variable with \@LocalStorageProp(key), a one-way data synchroniz | \@LocalStorageProp Decorator| Description | | ----------------------- | ---------------------------------------- | | Decorator parameters | **key**: constant string, mandatory (the string must be quoted) | -| Allowed variable types | Object, class, string, number, Boolean, enum, and array of these types.
(Applicable to API version 12 or later) Map, Set, and Date types. For details about the scenarios of nested objects, see [Observed Changes and Behavior](#observed-changes-and-behavior).
The type must be specified. Whenever possible, use the same type as that of the corresponding attribute in LocalStorage. Otherwise, implicit type conversion occurs, causing application behavior exceptions.
**any** is not supported. **undefined** and **null** are supported since API version 12.
(Applicable to API version 12 or later) Union type of the preceding types, for example, **string \| number**, **string \| undefined** or **ClassA \| null**. For details, see [Union Type @LocalStorage](#union-type).
**NOTE**
When **undefined** or **null** is used, you are advised to explicitly specify the type to pass the TypeScript type check. For example, **@LocalStorageProp("AA") a: number \| null = null** is recommended; **@LocalStorageProp("AA") a: number = null** is not recommended.| +| Allowed variable types | Object, class, string, number, Boolean, enum, and array of these types.
(Applicable to API version 12 or later) Map, Set, and Date types. For details about the scenarios of nested objects, see [Observed Changes and Behavior](#observed-changes-and-behavior).
The type must be specified. Whenever possible, use the same type as that of the corresponding attribute in LocalStorage. Otherwise, implicit type conversion occurs, causing application behavior exceptions.
**any** is not supported. **undefined** and **null** are supported since API version 12.
(Applicable to API version 12 or later) Union type of the preceding types, for example, **string \| number**, **string \| undefined**, or **ClassA \| null**. For details, see [Union Type @LocalStorage](#union-type).
**NOTE**
When **undefined** or **null** is used, you are advised to explicitly specify the type to pass the TypeScript type check. For example, **@LocalStorageProp("AA") a: number \| null = null** is supported, but **@LocalStorageProp("AA") a: number = null** is not.| | Synchronization type | One-way: from the attribute in LocalStorage to the component variable. The component variable can be changed locally, but an update from LocalStorage will overwrite local changes.| | Initial value for the decorated variable | Mandatory. If the attribute does not exist in LocalStorage, it will be created and initialized with this value.| @@ -126,7 +126,7 @@ By decorating a variable with \@LocalStorageProp(key), a one-way data synchroniz | \@LocalStorageLink Decorator| Description | | ----------------------- | ---------------------------------------- | | Decorator parameters | **key**: constant string, mandatory (the string must be quoted) | -| Allowed variable types | Object, class, string, number, Boolean, enum, and array of these types.
(Applicable to API version 12 or later) Map, Set, and Date types. For details about the scenarios of nested objects, see [Observed Changes and Behavior](#observed-changes-and-behavior).
The type must be specified. Whenever possible, use the same type as that of the corresponding attribute in LocalStorage. Otherwise, implicit type conversion occurs, causing application behavior exceptions.
**any** is not supported. **undefined** and **null** are supported since API version 12.
(Applicable to API version 12 or later) Union type of the preceding types, for example, **string \| number**, **string \| undefined** or **ClassA \| null**. For details, see [Union Type @LocalStorage](#union-type).
**NOTE**
When **undefined** or **null** is used, you are advised to explicitly specify the type to pass the TypeScript type check. For example, **@LocalStorageLink("AA") a: number \| null = null** is recommended. **@LocalStorageLink("AA") a: number = null** is not recommended.| +| Allowed variable types | Object, class, string, number, Boolean, enum, and array of these types.
(Applicable to API version 12 or later) Map, Set, and Date types. For details about the scenarios of nested objects, see [Observed Changes and Behavior](#observed-changes-and-behavior-1).
The type must be specified. Whenever possible, use the same type as that of the corresponding attribute in LocalStorage. Otherwise, implicit type conversion occurs, causing application behavior exceptions.
**any** is not supported. **undefined** and **null** are supported since API version 12.
(Applicable to API version 12 or later) Union type of the preceding types, for example, **string \| number**, **string \| undefined**, or **ClassA \| null**. For details, see [Union Type @LocalStorage](#union-type).
**NOTE**
When **undefined** or **null** is used, you are advised to explicitly specify the type to pass the TypeScript type check. For example, **@LocalStorageLink("AA") a: number \| null = null** is supported, but **@LocalStorageLink("AA") a: number = null** is not.| | Synchronization type | Two-way: from the attribute in LocalStorage to the custom component variable and back| | Initial value for the decorated variable | Mandatory. If the attribute does not exist in LocalStorage, it will be created and initialized with this value.| @@ -180,20 +180,20 @@ By decorating a variable with \@LocalStorageProp(key), a one-way data synchroniz 1. The parameter of \@LocalStorageProp and \@LocalStorageLink must be of the string type. Otherwise, an error is reported during compilation. -```ts -let storage = new LocalStorage(); -storage.setOrCreate('PropA', 48); + ```ts + let storage = new LocalStorage(); + storage.setOrCreate('PropA', 48); -// Incorrect format. An error is reported during compilation. -@LocalStorageProp() localStorageProp: number = 1; -@LocalStorageLink() localStorageLink: number = 2; + // Incorrect format. An error is reported during compilation. + @LocalStorageProp() localStorageProp: number = 1; + @LocalStorageLink() localStorageLink: number = 2; -// Correct format. -@LocalStorageProp('PropA') localStorageProp: number = 1; -@LocalStorageLink('PropA') localStorageLink: number = 2; -``` + // Correct format. + @LocalStorageProp('PropA') localStorageProp: number = 1; + @LocalStorageLink('PropA') localStorageLink: number = 2; + ``` -2. \@StorageProp and \@StorageLink cannot decorate variables of the function type. Otherwise, the framework throws a runtime error. +2. \@LocalStorageProp and \@LocalStorageLink cannot decorate variables of the function type. Otherwise, the framework throws a runtime error. 3. Once created, a named attribute cannot have its type changed. Subsequent calls to **Set** must set a value of same type. @@ -290,7 +290,7 @@ struct Parent { } } } - ``` +``` ### Simple Example of Using \@LocalStorageProp with LocalStorage @@ -639,91 +639,91 @@ struct Child { 1. If a custom component does not have any attribute defined, it can accept a LocalStorage instance as the only input parameter. -```ts -let localStorage1: LocalStorage = new LocalStorage(); -localStorage1.setOrCreate('PropA', 'PropA'); - -let localStorage2: LocalStorage = new LocalStorage(); -localStorage2.setOrCreate('PropB', 'PropB'); + ```ts + let localStorage1: LocalStorage = new LocalStorage(); + localStorage1.setOrCreate('PropA', 'PropA'); + + let localStorage2: LocalStorage = new LocalStorage(); + localStorage2.setOrCreate('PropB', 'PropB'); + + @Entry(localStorage1) + @Component + struct Index { + // PropA is in two-way synchronization with PropA in localStorage1. + @LocalStorageLink('PropA') PropA: string = 'Hello World'; + @State count: number = 0; + + build() { + Row() { + Column() { + Text(this.PropA) + .fontSize(50) + .fontWeight(FontWeight.Bold) + // Use the LocalStorage instance localStorage2. + Child(localStorage2) + } + .width('100%') + } + .height('100%') + } + } -@Entry(localStorage1) -@Component -struct Index { - // PropA is in two-way synchronization with PropA in localStorage1. - @LocalStorageLink('PropA') PropA: string = 'Hello World'; - @State count: number = 0; - build() { - Row() { - Column() { - Text(this.PropA) + @Component + struct Child { + build() { + Text("hello") .fontSize(50) .fontWeight(FontWeight.Bold) - // Use the LocalStorage instance localStorage2. - Child(localStorage2) } - .width('100%') } - .height('100%') - } -} - - -@Component -struct Child { - build() { - Text("hello") - .fontSize(50) - .fontWeight(FontWeight.Bold) - } -} -``` + ``` 2. If the defined attribute does not need to be initialized from the parent component, {} must be passed in as the first parameter. -```ts -let localStorage1: LocalStorage = new LocalStorage(); -localStorage1.setOrCreate('PropA', 'PropA'); + ```ts + let localStorage1: LocalStorage = new LocalStorage(); + localStorage1.setOrCreate('PropA', 'PropA'); + + let localStorage2: LocalStorage = new LocalStorage(); + localStorage2.setOrCreate('PropB', 'PropB'); + + @Entry(localStorage1) + @Component + struct Index { + // PropA is in two-way synchronization with PropA in localStorage1. + @LocalStorageLink('PropA') PropA: string = 'Hello World'; + @State count: number = 0; + + build() { + Row() { + Column() { + Text(this.PropA) + .fontSize(50) + .fontWeight(FontWeight.Bold) + // Use the LocalStorage instance localStorage2. + Child({}, localStorage2) + } + .width('100%') + } + .height('100%') + } + } -let localStorage2: LocalStorage = new LocalStorage(); -localStorage2.setOrCreate('PropB', 'PropB'); -@Entry(localStorage1) -@Component -struct Index { - // PropA is in two-way synchronization with PropA in localStorage1. - @LocalStorageLink('PropA') PropA: string = 'Hello World'; - @State count: number = 0; + @Component + struct Child { + @State count: number = 5; + // Hello World is in two-way synchronization with PropB in localStorage2. If there is no PropB in localStorage2, the default value Hello World is used. + @LocalStorageLink('PropB') PropB: string = 'Hello World'; - build() { - Row() { - Column() { - Text(this.PropA) + build() { + Text(this.PropB) .fontSize(50) .fontWeight(FontWeight.Bold) - // Use the LocalStorage instance localStorage2. - Child({}, localStorage2) } - .width('100%') } - .height('100%') - } -} - - -@Component -struct Child { - @State count: number = 5; - // Hello World is in two-way synchronization with PropB in localStorage2. If there is no PropB in localStorage2, the default value Hello World is used. - @LocalStorageLink('PropB') PropB: string = 'Hello World'; - - build() { - Text(this.PropB) - .fontSize(50) - .fontWeight(FontWeight.Bold) - } -} -``` + ``` ### Using LocalStorage with a Navigation Component diff --git a/en/application-dev/quick-start/arkts-migration-background.md b/en/application-dev/quick-start/arkts-migration-background.md index f881f25278586ee12697f6cacb2cff62885589da..2a209ef3dcba4cfa91288ff788581600ce206105 100644 --- a/en/application-dev/quick-start/arkts-migration-background.md +++ b/en/application-dev/quick-start/arkts-migration-background.md @@ -1,20 +1,17 @@ # ArkTS Migration Background -This chapter explains why it makes sense to migrate from the standard TypeScript to ArkTS. In general, there are two reasons for doing this: +Building on the basic syntax of TypeScript (TS), ArkTS further strengthens static checks and analysis. This allows for the detection of more errors during development, thereby enhancing code robustness and achieving better runtime performance. This chapter explains why it makes sense to migrate from the standard TypeScript to ArkTS. ## Program Stability -Dynamically typed languages like JavaScript are very good at allowing programs to write code fast. At the same time, these languages are -notorious for unexpected runtime errors. For example, a developer may forget to check some value for `undefined`, and as a result of this, the program may crash, which causes inconvenience to the users. Detecting such issues during development time would be much more beneficial. TypeScript helps greatly here: It allows to annotate the code with types, and many errors will be detected by the compiler, prior to deployment and usage of the code. However, even TypeScript has limitations and sometimes permits to annotate the code with types “loosely”, which still leaves a gap for runtime errors. ArkTS tries to overcome this drawback: It enforces static typing for even stricter type checking and less runtime errors. +Dynamically typed languages like JavaScript are very good at allowing programs to write code fast. At the same time, these languages are notorious for unexpected runtime errors. For example, a developer may forget to check some value for **undefined**, and as a result of this, the program may crash, which causes inconvenience to the users. Detecting such issues during development time would be much more beneficial. TypeScript helps greatly here: It allows to annotate the code with types, and many errors will be detected by the compiler, prior to deployment and usage of the code. However, even TypeScript has limitations and sometimes permits to annotate the code with types "loosely", which still leaves a gap for runtime errors. ArkTS tries to overcome this drawback: It enforces static typing for even stricter type checking and less runtime errors. The following case demonstrates how we can improve stability and correctness of our code by enforcing stricter type checking in ArkTS. **Explicit Initialization of Fields for Better Stability** -ArkTS requires that all fields are explicitly initialized with some values either when the field is declared or in the `constructor`. This is similar to `strictPropertyInitialization` mode of the standard TypeScript. - -Let’s take a look at the following TypeScript code: +ArkTS requires that all fields are explicitly initialized with some values either when the field is declared or in **constructor**. This is similar to **strictPropertyInitialization** mode of the standard TypeScript. Let's take a look at the following TypeScript code: ```typescript class Person { @@ -26,16 +23,14 @@ class Person { getName(): string { // Return type "string" hides from the developers the fact that name can be undefined. - // The most correct would be to write the return type as "string | undefined". By doing so - // we tell the users of our API about all possible return values. + // The most correct would be to write the return type as "string | undefined". By doing so, we tell the users of our API about all possible return values. return this.name } } let buddy = new Person() -// Let's assume that the developer forgets to call setName: -// buddy.setName("John") -buddy.getName().length; // runtime exception: name is undefined +// Let's assume that the developer forgets to call buddy.setName("John"). +buddy.getName().length; // Runtime exception: name is undefined. ``` Since ArkTS requires explicit initialization, the code looks like this: @@ -55,55 +50,46 @@ class Person { } let buddy = new Person() -// Let's assume that the developer forgets to call setName: -// buddys.setName("John") +// Let's assume that the developer forgets to call buddy.setName("John"). buddy.getName().length; // 0, no runtime error ``` -If `name` can be `undefined`, this is also should be specified explicitly: +If **name** can be **undefined**, it should be specified explicitly: ```typescript class Person { - name ?: string // The field may be undefined + name?: string // The field may be undefined. setName(n: string): void { this.name = n } - // Compile-time error: - // name can be "undefined", so we cannot say to those who use this API - // that it returns only strings: + // Compile-time error: name can be "undefined", so the return type of this API cannot be marked as "string". getNameWrong(): string { return this.name } - getName(): string | undefined { // Return type matches the type of name + getName(): string | undefined { // Return type matches the type of name. return this.name } } let buddy = new Person() -// Let's assume that the developer forgets to call setName: -// buddy.setName("John") +// Let's assume that the developer forgets to call buddy.setName("John"). -// Compile-time(!) error: Compiler suspects that we -// may possibly access something undefined and won't build the code: -buddy.getName().length; // The code won't build and run +// Compile-time error: Compiler suspects that we may possibly access something undefined and will not build the code: +buddy.getName().length; // The code will not build and run. -buddy.getName()?.length; // Builds ok, no runtime error +buddy.getName()?.length; // Successful builds and no runtime error. ``` - - ## Program Performance -To ensure correctness of the program, dynamically languages have to check actual types of objects when the program actually runs. Back to our example, JavaScript does not allow to read a property from `undefined`. But the only way to check if some value is `undefined` is to perform a runtime check, that all JavaScript engines do: if the value is not `undefined`, the property is read, otherwise an exception is thrown. Modern engines can optimize such checks greatly, but these checks cannot be eliminated completely, which leads to code slowdown. Since the standard TypeScript compiles to JavaScript, the code written in TypeScript has exactly the same issues as described above. ArkTS addresses this problem. Since static typing is enforced, ArkTS compiles the program not to JavaScript, but to ARK bytecode, which is faster to execute and easier to optimize even further. +To ensure correctness of the program, dynamically languages have to check actual types of objects when the program actually runs. Back to our example, JavaScript does not allow to read a property from **undefined**. But the only way to check if some value is **undefined** is to perform a runtime check, that all JavaScript engines do: if the value is not **undefined**, the property is read, otherwise an exception is thrown. Modern engines can optimize such checks greatly, but these checks cannot be eliminated completely, which leads to code slowdown. Since the standard TypeScript compiles to JavaScript, the code written in TypeScript has exactly the same issues as described above. ArkTS addresses this problem. Since static typing is enforced, ArkTS compiles the program not to JavaScript, but to ARK bytecode, which is faster to execute and easier to optimize even further. **Null Safety** -Let’s take a look at the following code: - ```typescript function notify(who: string, what: string) { console.log(`Dear ${who}, a message for you: ${what}`) @@ -112,7 +98,8 @@ function notify(who: string, what: string) { notify('Jack', 'You look great today') ``` -In most cases, the `notify` function will take two string variables as an input and produces a new string. However, what if we pass some “special” values to the function, for example `notify(null, undefined)`? The program will continue to work, the output will be as expected (`Dear null, a message for you: undefined`), so from the first glance everything is fine. But please note that the engine that runs our code should always check for such special cases to ensure correct behavior. In pseudocode, something like this happens: +In most cases, the **notify** function will take two **string** variables as an input and produces a new string. However, what if we pass some "special" values to the function, for example **notify(null, undefined)**? +The program will continue to work, the output will be as expected (**Dear null, a message for you: undefined**), so from the first glance everything is fine. But please note that the engine that runs our code should always check for such special cases to ensure correct behavior. In pseudocode, something like this happens: ```typescript function __internal_tostring(s: any): string { @@ -126,13 +113,9 @@ function __internal_tostring(s: any): string { } ``` -Now imagine that our `notify` function is a part of some complex heavy-loaded system which sends real notifications instead of just writing to the log. In -this scenario, executing all these checks from our `__internal_tostring` function may turn into a performance problem. +Now imagine that our **notify** function is a part of some complex heavy-loaded system which sends real notifications instead of just writing to the log. In this scenario, executing all these checks from our **__internal_tostring** function may turn into a performance problem. -But what if we could somehow guarantee to our exectuion engine that the only values that are passed to the `notify` function are “real” strings, but not -some “special” values like `null` or `undefined`? In this case, checks like `__internal_tostring` become redundant because when we execute the program -we are 100% sure that there will be no corner cases. For this particular case this mechanism would be called “null-safety”, i.e. guarantee that `null` is -not a valid value of the `string` type. If we had such feature, the code would not simply build: +But what if we could somehow guarantee to our execution engine that the only values that are passed to the **notify** function are "real" strings, but not some "special" values like **null** or **undefined**? In this case, checks like **__internal_tostring** become redundant because when we execute the program we are 100% sure that there will be no corner cases. For this particular case this mechanism would be called "null-safety", i.e. guarantee that **null** is not a valid value of the **string** type. If we had such feature, the code would not simply build: ```typescript function notify(who: string, what: string) { @@ -143,9 +126,8 @@ notify('Jack', 'You look great today') notify(null, undefined) // Compile-time error ``` -In TypeScript such behavior can be turned on by a special compiler flag called `strictNullChecks`. But since the standard TypeScript is compiled to JavaScript, which does not have such feature, “strict null checks” work only in compile-time, for better type checking. However, ArkTS considers null-safety a very -important feature from both stability and performance points of view. That’s why it is enforced in the language and the example above always produces -compile-time errors. In exchange, we give our running engine much more information and guarantees about possible type values, which helps better optimize performance. +In TypeScript such behavior can be turned on by a special compiler flag called **strictNullChecks**. But since the standard TypeScript is compiled to JavaScript, which does not have such feature, strict null checks work only in compile-time, for better type checking. However, ArkTS considers null-safety a very important feature from both stability and performance points of view. That's why it is enforced in the language and the example above always produces compile-time errors. In exchange, we give our running engine much more information and guarantees about possible type values, which helps better optimize performance. + ## .ets Code Compatibility @@ -154,8 +136,29 @@ Prior to API version 10, ArkTS (.ets file) completely adopted the syntax of stan Syntax issues are classified as warning or error, depending on the **compatibleSdkVersion** of the project: - In compatible mode, where the value of **compatibleSdkVersion** is greater than or equal to 10, syntax issues are reported as errors and will block the compilation process. The compilation can be successful only after the ArkTS syntax is fully adapted. - - In compatible mode, where the value of **compatibleSdkVersion** is smaller than 10, syntax issues are reported as warnings and will not block the compilation process. + - In compatible mode, where the value of **compatibleSdkVersion** is smaller than 10, syntax issues are reported as warnings and will not block the compilation process. and will not block the compilation process. + +## Interaction with TS/JS + +ArkTS supports efficient interoperability with TS/JS. In the current version, ArkTS is compatible with dynamic object semantics. In the scenario of interaction with TS/JS, when data and objects of TS/JS are used as that of ArkTS, the static compilation check of ArkTS may be bypassed, causing unexpected behavior or extra overhead. + +```typescript +// lib.ts +export class C { + v: string +} + +export let c = new C() +// app.ets +import { C, c } from './lib' + +function foo(c: C) { + c.v.length +} + +foo(c) // Runtime exception: v is undefined +``` ## ArkCompiler Runtime Compatibility with TS/JS @@ -163,11 +166,24 @@ The OpenHarmony SDK of API version 11 uses TypeScript 4.9.5, with the **target** **Application Environment Restrictions** -1. Force the use of strict mode (use strict) -2. Prohibit the use of `eval()` -3. Prohibit the use of `with() {}` -4. Prohibit creating functions with strings as code +1. Force the use of strict mode (use strict). +2. Prohibit the use of **eval()**. +3. Prohibit the use of **with() {}**. +4. Prohibit creating functions with strings as code. +5. Prohibit circular dependency. + + Example of circular dependency: + ```typescript + // bar.ets + import {v} from './foo' // bar.ets depends on foo.ets. + export let u = 0; + + // foo.ets + import {u} from './bar' // foo.ets depends on bar.ets reversely. + export let v = 0; + + ``` **Differences from Standard TS/JS** -In standard TS/JS, the number format of JSON, the decimal point must be followed by a number. Scientific notation such as `2.e3` is not allowed and throws `SyntaxError`. In the ArkCompiler Runtime, this type of scientific notation is allowed. +In standard TS/JS, the number format of JSON, the decimal point must be followed by a number. Scientific notation such as **2.e3** is not allowed and throws **SyntaxError**. In the ArkCompiler Runtime, this type of scientific notation is allowed. diff --git a/en/application-dev/quick-start/arkts-mvvm-V2.md b/en/application-dev/quick-start/arkts-mvvm-V2.md index 495ddb17787d485d9e0ab19a30b55c558aa24abc..39a5d2e1423ab1efbc3ebb3113dcd55f1b689a45 100644 --- a/en/application-dev/quick-start/arkts-mvvm-V2.md +++ b/en/application-dev/quick-start/arkts-mvvm-V2.md @@ -179,7 +179,7 @@ struct TodoList { As the number of task list items increases after the function of adding or deleting tasks is added, a method for efficiently rendering multiple child components with the same structure is required to improve the performance of the UI. Therefore, the **Repeat** method is introduced to optimize the rendering process of the task list. **Repeat** supports two modes: virtualScroll is applicable to scenarios with a large amount of data. It loads components as required in scrolling containers, greatly saving memory and improving rendering efficiency; non-virtualScroll is applicable to scenarios with a small amount of data. All components are rendered at a time, and only the changed data is updated, avoiding overall re-rendering. -In this example, the non-virtualScroll mode is selected because of few task items. Create an array **tasks**, use the **Repeat** method to iterate each item in the array, and dynamically generate and reuse the **TaskItem** component. When a task is added or deleted, this method can efficiently reuse existing components to avoid rendering repeated components, improving the UI response speed and performance. +In this example, the non-virtualScroll mode is selected because of few task items. Create an array **tasks**, use the **Repeat** method to iterate each item in the array, and dynamically generate and reuse the **TaskItem** component. In this way, you can efficiently reuse existing components when adding or deleting a task to avoid repeated component renderings, improving code reusability and rendering efficiency. ```ts // src/main/ets/pages/5-Repeat.ets @@ -1204,7 +1204,7 @@ struct TodoList { } ``` -- **SettingPage**: settings page, which is used to set whether to show finished tasks. It uses \@AppStorageV2 to store the global settings. The user can switch the status of **showCompletedTask** by using the toggle switch. +- **SettingPage**: settings page, which is used to set whether to show finished tasks. It uses **AppStorageV2** to store the global settings. The user can switch the status of **showCompletedTask** by using the toggle switch. ```ts // src/main/ets/pages/SettingPage.ets @@ -1250,4 +1250,3 @@ This guide uses a simple to-do list application as an example to introduce decor ## Sample Code [Complete Source Code](https://gitee.com/openharmony/applications_app_samples/tree/master/code/DocsSample/ArkUISample/StateMgmtV2MVVM/entry) - diff --git a/en/application-dev/quick-start/arkts-mvvm.md b/en/application-dev/quick-start/arkts-mvvm.md index 9feca4b689dae109d2890535ba7b87d0e7ed4c07..a9290d0f29fdfca277c6c813509d56c075ee869d 100644 --- a/en/application-dev/quick-start/arkts-mvvm.md +++ b/en/application-dev/quick-start/arkts-mvvm.md @@ -33,7 +33,7 @@ The UI development mode of ArkUI is the MVVM mode, in which the state variables **ViewModel** -* Page data: organized by page. When a user opens a page, some pages may not be switched to. Therefore, it is recommended that the page data be designed in lazy loading mode. +* Page data: Data that is organized by page. When a user browses a page, some pages may not be displayed. Therefore, it is recommended that the page data be designed using lazy import. > The differences between the ViewModel data and the Model data are as follows: > @@ -43,15 +43,7 @@ The UI development mode of ArkUI is the MVVM mode, in which the state variables **Model** -Model provides the original data of applications. From the perspective of the UI, there are two ways to implement this layer: - -* Local implementation: through native C++. - -* Remote implementation: through the I/O port (RESTful). - -> **NOTE** -> -> When the local implementation is used, the non-UI thread model must exist when the system processes data. At this time, the processed data change needs to be notified to the ViewModel in real time, causing data changes and UI re-renders. In this case, automatic thread switching becomes very important. Generally, the ViewModel and View can work properly only when they are executed in the UI thread. Therefore, a mechanism is required to automatically complete thread switching when the UI needs to be notified of a re-render. +The Model layer is the original data provider of applications. ### Core Principles of the Architecture @@ -68,7 +60,7 @@ The lower layer can only notify the upper layer to update the data. In the servi This is the core principle of View design. A component should comply with the following logic: -* Do not directly access the parent component (using the event or subscription capability). +* Do not directly access the parent component. Event or subscription capability must be used. * Do not directly access sibling components. This is because components can access only the child nodes (through parameter passing) and parent nodes (through events or notifications) that they can see. In this way, components are decoupled. Reasons: @@ -589,170 +581,301 @@ The file structure is reconstructed based on the MVVM mode as follows: * src * ets + * Model + * ThingsModel + * TodoListModel * pages - * index + * Index * View - * TodoComponent - * AllchooseComponent + * AllChooseComponent * ThingsComponent + * TodoComponent + * TodoListComponent * ViewModel * ThingsViewModel + * TodoListViewModel + * resources + * rawfile + * defaultTasks.json The code is as follows: * Index.ets ```typescript - // import view - import { TodoComponent } from './../View/TodoComponent' - import { MultiChooseComponent } from './../View/AllchooseComponent' - import { ThingsComponent } from './../View/ThingsComponent' - - // import viewModel - import { TodoListData } from '../ViewModel/ThingsViewModel' - + import { common } from '@kit.AbilityKit'; + // import ViewModel + import TodoListViewModel from '../ViewModel/TodoListViewModel'; + + // import View + import { TodoComponent } from '../View/TodoComponent'; + import { AllChooseComponent } from '../View/AllChooseComponent'; + import { TodoListComponent } from '../View/TodoListComponent'; + @Entry @Component - struct Index { - @State isFinished: boolean = false; - @State data: TodoListData = new TodoListData(); - + struct TodoList { + @State thingsTodo: TodoListViewModel = new TodoListViewModel(); + private context = getContext(this) as common.UIAbilityContext; + + async aboutToAppear() { + await this.thingsTodo.loadTasks(this.context); + } + build() { Column() { - Row({space: 40}) { + Row({ space: 40 }) { // All To-Do items. TodoComponent() - // Select all. - MultiChooseComponent({isFinished: this.isFinished}) + AllChooseComponent({ thingsViewModel: this.thingsTodo }) } - - List() { - ForEach(this.data.planList, (item: string) => { - // Task 1 - ThingsComponent({isFinished: this.isFinished, things: item}) - .margin(5) - }) + + Column() { + TodoListComponent({ thingsViewModelArray: this.thingsTodo.things }) } - } .height('100%') .width('100%') - .margin({top: 5, bottom: 5}) + .margin({ top: 5, bottom: 5 }) .backgroundColor('#90f1f3f5') } } ``` - * TodoComponent + * ThingsModel.ets ```typescript - @Component - export struct TodoComponent { - build() { - Row() { - Text('To-Dos') - .fontSize(30) - .fontWeight(FontWeight.Bold) - } - .padding({left: 15}) - .width('50%') - .margin({top: 10, bottom: 10}) + export default class ThingsModel { + thingsName: string = 'Todo'; + isFinish: boolean = false; + } + ``` + + * TodoListModel.ets + + ```typescript + import { common } from '@kit.AbilityKit'; + import util from '@ohos.util'; + import ThingsModel from './ThingsModel'; + + export default class TodoListModel { + things: Array = []; + + constructor(things: Array) { + this.things = things; + } + + async loadTasks(context: common.UIAbilityContext) { + let getJson = await context.resourceManager.getRawFileContent('defaultTasks.json'); + let textDecoderOptions: util.TextDecoderOptions = { ignoreBOM: true }; + let textDecoder = util.TextDecoder.create('utf-8', textDecoderOptions); + let result = textDecoder.decodeToString(getJson, { stream: false }); + this.things = JSON.parse(result); } } ``` - * AllchooseComponent.ets + * AllChooseComponent.ets ```typescript -@Component - export struct MultiChooseComponent { - @Link isFinished: boolean; - + import TodoListViewModel from "../ViewModel/TodoListViewModel"; + + @Component + export struct AllChooseComponent { + @State titleName: string = 'Select All'; + @Link thingsViewModel: TodoListViewModel; + build() { Row() { - Button('Multiselect', {type: ButtonType.Capsule}) + Button(`${this.titleName}`, { type: ButtonType.Capsule }) .onClick(() => { - this.isFinished = !this.isFinished; + this.thingsViewModel.chooseAll(); + this.titleName = this.thingsViewModel.isChoosen ? 'Select All' : 'Deselect All' }) .fontSize(30) .fontWeight(FontWeight.Bold) .backgroundColor('#f7f6cc74') } - .padding({left: 15}) + .padding({ left: this.thingsViewModel.isChoosen ? 15 : 0 }) .width('100%') - .margin({top: 10, bottom: 10}) + .margin({ top: 10, bottom: 10 }) } } ``` - - * ThingsComponent + + * ThingsComponent.ets ```typescript -@Component + import ThingsViewModel from "../ViewModel/ThingsViewModel"; + + @Component export struct ThingsComponent { - @Prop isFinished: boolean; - @Prop things: string; - - @Builder displayIcon(icon: Resource) { + @Prop things: ThingsViewModel; + + @Builder + displayIcon(icon: Resource) { Image(icon) .width(28) .height(28) .onClick(() => { - this.isFinished = !this.isFinished; + this.things.updateIsFinish(); }) } - + build() { - // Task 1 - Row({space: 15}) { - if (this.isFinished) { + // To-Do list + Row({ space: 15 }) { + if(this.things.isFinish) { // 'app.media.finished' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed. this.displayIcon($r('app.media.finished')); - } - else { + } else { // 'app.media.unfinished' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed. this.displayIcon($r('app.media.unfinished')); } - Text(`${this.things}`) + + Text(`${this.things.thingsName}`) .fontSize(24) .fontWeight(450) - .decoration({type: this.isFinished ? TextDecorationType.LineThrough : TextDecorationType.None}) + .decoration({ type: this.things.isFinish ? TextDecorationType.LineThrough: TextDecorationType.None }) .onClick(() => { - this.things += '!' + this.things.addSuffixes(); }) } .height('8%') .width('90%') - .padding({left: 15}) - .opacity(this.isFinished ? 0.3: 1) - .border({width:1}) + .padding({ left: 15 }) + .opacity(this.things.isFinish ? 0.3 : 1) + .border({ width: 1 }) .borderColor(Color.White) .borderRadius(25) .backgroundColor(Color.White) } } - ``` - -* ThingsViewModel.ets + + * TodoComponent.ets ```typescript -@Observed - export class TodoListData { - planList: string[] = [ - '7:30 Get up' - '8:30 Breakfast' - '11:30 Lunch' - '17:30 Dinner' - '21:30 Snack' - '22:30 Shower' - '1:30 Go to bed' - ]; + @Component + export struct TodoComponent { + build() { + Row() { + Text('To-Dos') + .fontSize(30) + .fontWeight(FontWeight.Bold) + } + .padding({ left: 15 }) + .width('50%') + .margin({ top: 10, bottom: 10 }) + } } ``` - - After the code is split in MVVM mode, the project structure and responsibilities of each module are clearer. If a new page needs to use the event component, you only need to import the corresponding component because the local data is fixed and the logic at the Model layer is not written. You can reconstruct your project structures based on the example. + + * TodoListComponent.ets + + ```typescript + import ThingsViewModel from "../ViewModel/ThingsViewModel"; + import { ThingsViewModelArray } from "../ViewModel/TodoListViewModel" + import { ThingsComponent } from "./ThingsComponent"; + + @Component + export struct TodoListComponent { + @ObjectLink thingsViewModelArray: ThingsViewModelArray; + + build() { + Column() { + List() { + ForEach(this.thingsViewModelArray, (item: ThingsViewModel) => { + // To-Do list + ListItem() { + ThingsComponent({ things: item }) + .margin(5) + } + }, (item: ThingsViewModel) => { + return item.thingsName; + }) + } + } + } + } + ``` + + * ThingsViewModel.ets + + ```typescript + import ThingsModel from "../Model/ThingsModel"; + + @Observed + export default class ThingsViewModel { + @Track thingsName: string = 'Todo'; + @Track isFinish: boolean = false; + + updateTask(things: ThingsModel) { + this.thingsName = things.thingsName; + this.isFinish = things.isFinish; + } + + updateIsFinish(): void { + this.isFinish = !this.isFinish; + } + + addSuffixes(): void { + this.thingsName += '!'; + } + } + ``` + + * TodoListViewModel.ets + + ```typescript + import ThingsViewModel from "./ThingsViewModel"; + import { common } from "@kit.AbilityKit"; + import TodoListModel from "../Model/TodoListModel"; + + @Observed + export class ThingsViewModelArray extends Array { + } + + @Observed + export default class TodoListViewModel { + @Track isChoosen: boolean = true; + @Track things: ThingsViewModelArray = new ThingsViewModelArray(); + + async loadTasks(context: common.UIAbilityContext) { + let todoList = new TodoListModel([]); + await todoList.loadTasks(context); + for(let things of todoList.things) { + let thingsViewModel = new ThingsViewModel(); + thingsViewModel.updateTask(things); + this.things.push(thingsViewModel); + } + } + + chooseAll(): void { + for(let things of this.things) { + things.isFinish = this.isChoosen; + } + this.isChoosen = !this.isChoosen; + } + } + ``` + + * defaultTasks.json + + ```typescript + [ + {"thingsName": "7:30 Get up," "isFinish": false}, + {"thingsName": "8:30 Breakfast," "isFinish": false}, + {"thingsName": "11:30 Lunch," "isFinish": false}, + {"thingsName": "17:30 Dinner," "isFinish": false}, + {"thingsName": "21:30 Snack," "isFinish": false}, + {"thingsName": "22:30 Shower," "isFinish": false}, + {"thingsName": "1:30 Go to bed," "isFinish": false} + ] + ``` + + After the code is split in MVVM mode, the project structure and the responsibilities of each module are clearer. If a new page needs to use an event component, for example, **TodoListComponent**, you only need to import the component. The following figure shows the effect. diff --git a/en/application-dev/quick-start/arkts-new-Computed.md b/en/application-dev/quick-start/arkts-new-Computed.md index d219195b3eaa8738e6167d34505ec161655d8922..385e068be05b9ddffd8914c4c8c0819921533769 100644 --- a/en/application-dev/quick-start/arkts-new-Computed.md +++ b/en/application-dev/quick-start/arkts-new-Computed.md @@ -117,7 +117,7 @@ get varName(): T { ``` ## Use Scenarios -### When the computed property changes, the **getter** accessor decorated by \@Computed is solved only once. +### \@Computed Decorated getter Accessor Is Solved Only Once Upon Property Change 1. Using computed property in a custom component. - Click the first button to change the value of **lastName**, triggering **\@Computed fullName** recomputation. @@ -248,7 +248,7 @@ struct MyView { } ``` ### \@Computed Decorated Properties Initialize \@Param -The following example shows how \@Computed Initialize \@Param. +The following example uses \@Computed to initialize \@Param. - Click **Button('-')** and **Button('+')** to change the offering quantity. The **quantity** is decorated by \@Trace and can be observed when it is changed. - The change of **quantity** triggers the recomputation of **total** and **qualifiesForDiscount**. In this way, you can get a result of the total price of the offering and the available discounts. - The change of **total** and **qualifiesForDiscount** triggers the update of the **Text** component corresponding to the **Child** component. diff --git a/en/application-dev/quick-start/arkts-new-appstoragev2.md b/en/application-dev/quick-start/arkts-new-appstoragev2.md index 9998bc0877ae9d200bbdf063596461947f53e230..11e1859e70420dc2a124e054646355f3a378e482 100644 --- a/en/application-dev/quick-start/arkts-new-appstoragev2.md +++ b/en/application-dev/quick-start/arkts-new-appstoragev2.md @@ -35,16 +35,16 @@ static connect( | connect | Description | | ------------ | ----------------------------------------------------- | -| Parameter | **type**: specified type. If no **key** is specified, the name of the **type** is used as the **key**.
**keyOrDefaultCreater**: specified key or default constructor.
**defaultCreator**: default constructor. | +| Parameter | **type**: specified type. If no **key** is specified, the name of the **type** is used as the **key**.
**keyOrDefaultCreator**: specified key or default constructor.
**defaultCreator**: default constructor. | | Return value | After creating or obtaining data, value is returned. Otherwise, **undefined** is returned.| >**NOTE** > ->1. The third parameter is used when no **key** is specified or the second parameter is invalid. Otherwise, the second parameter is used. +>1. The third parameter is used when no **key** is specified or the second parameter is invalid, and the third parameter is used in all other cases. > ->2. If the data has been stored in AppStorageV2, you can obtain the stored data without using the default constructor. Otherwise, you must specify the default constructor. If no constructor is specified, the application exception occurs. +>2. If the data has been stored in AppStorageV2, you can obtain the stored data without using the default constructor. If the data has not been stored, you must specify a default constructor; otherwise, an application exception will be thrown. > ->3. Ensure that the data types match the key. If different types of data are connected to the same key, the application exception occurs. +>3. Ensure that the data types match the key. Connecting different types of data to the same key will result in an application exception. > >4. You are advised to use meaningful values for keys. The values can contain letters, digits, and underscores (_) and a maximum of 255 characters. Using invalid characters or null characters will result in undefined behavior. > @@ -89,8 +89,20 @@ static keys(): Array; ### Storing Data Between Two Pages +Data page +```ts +// Data center +// Sample.ets +@ObservedV2 +export class Sample { + @Trace p1: number = 0; + p2: number = 10; +} +``` + Page 1 ```ts +// Page1.ets import { AppStorageV2 } from '@kit.ArkUI'; import { Sample } from '../Sample'; @@ -145,6 +157,7 @@ struct Page1 { Page 2 ```ts +// Page2.ets import { AppStorageV2 } from '@kit.ArkUI'; import { Sample } from '../Sample'; @@ -198,22 +211,12 @@ When using **Navigation**, you need to add the **route_map.json** file to the ** "routerMap": [ { "name": "Page2", - "pageSourceFile": "src/main/ets/pages/PersistenceV2-2.ets", + "pageSourceFile": "src/main/ets/pages/Page2.ets", "buildFunction": "Page2Builder", "data": { - "description" : "PersistenceV2 example" + "description" : "AppStorageV2 example" } } ] } ``` - -Data page -```ts -// Data center -@ObservedV2 -export class Sample { - @Trace p1: number = 0; - p2: number = 10; -} -``` diff --git a/en/application-dev/quick-start/arkts-new-binding.md b/en/application-dev/quick-start/arkts-new-binding.md index a180cf631b303bfd38749fef9c606ba74439b3e2..3ae46a20172ed1c260e9eb9612455a787976c3fa 100644 --- a/en/application-dev/quick-start/arkts-new-binding.md +++ b/en/application-dev/quick-start/arkts-new-binding.md @@ -65,7 +65,7 @@ struct Star { ## Constraints - **!!** does not support multi-layer parent-child component transfer. -- **!!** cannot be used together with @Event. When it is used, parameters cannot be passed to the corresponding @Event method when parameters are passed to the child component. +- **!!** cannot be used together with @Event. Since API version 18, when **!!** is used to pass parameters to the @Event method of a child component, a compilation error is reported. - When three or more exclamation marks (!!!, !!!!, or !!!!!) are used, two-way binding is not supported. @@ -84,12 +84,20 @@ What the internal state is depends on the component. For example, the **isShow** | [bindMenu](../reference/apis-arkui/arkui-ts/ts-universal-attributes-menu.md#bindmenu11) | isShow | 13 | | [bindContextMenu](../reference/apis-arkui/arkui-ts/ts-universal-attributes-menu.md#bindcontextmenu12) | isShown | 13 | | [bindPopup](../reference/apis-arkui/arkui-ts/ts-universal-attributes-popup.md#bindpopup) | show | 13 | - | [TextInput](../reference/apis-arkui/arkui-ts/ts-basic-components-textinput.md) | text | 16 | - | [TextArea](../reference/apis-arkui/arkui-ts/ts-basic-components-textarea.md) | text | 16 | - | [Search](../reference/apis-arkui/arkui-ts/ts-basic-components-search.md) | value | 16 | - | [BindSheet](../reference/apis-arkui/arkui-ts/ts-universal-attributes-sheet-transition.md) | isShow | 16 | - | [BindContentCover](../reference/apis-arkui/arkui-ts/ts-universal-attributes-modal-transition.md) | isShow | 16 | - + | [TextInput](../reference/apis-arkui/arkui-ts/ts-basic-components-textinput.md#textinputoptions)| text | 18 | + | [TextArea](../reference/apis-arkui/arkui-ts/ts-basic-components-textarea.md#textareaoptions)| text | 18 | + | [Search](../reference/apis-arkui/arkui-ts/ts-basic-components-search.md#searchoptions18)| value | 18 | + | [BindSheet](../reference/apis-arkui/arkui-ts/ts-universal-attributes-sheet-transition.md) | isShow | 18 | + | [BindContentCover](../reference/apis-arkui/arkui-ts/ts-universal-attributes-modal-transition.md) | isShow | 18 | + | [Toggle](../reference/apis-arkui/arkui-ts/ts-basic-components-toggle.md#toggleoptions18)| isOn | 18 | + | [Checkbox](../reference/apis-arkui/arkui-ts/ts-basic-components-checkbox.md#select) | select | 18 | + | [CheckboxGroup](../reference/apis-arkui/arkui-ts/ts-basic-components-checkboxgroup.md#selectall) | selectAll | 18 | + | [Radio](../reference/apis-arkui/arkui-ts/ts-basic-components-radio.md#checked) | checked | 18 | + | [Rating](../reference/apis-arkui/arkui-ts/ts-basic-components-rating.md#ratingoptions18)| rating | 18 | + | [Slider](../reference/apis-arkui/arkui-ts/ts-basic-components-slider.md#slideroptions)| value | 18 | + | [Select](../reference/apis-arkui/arkui-ts/ts-basic-components-select.md#selected) | selected | 18 | + | [Select](../reference/apis-arkui/arkui-ts/ts-basic-components-select.md#value) | value | 18 | + | [MenuItem](../reference/apis-arkui/arkui-ts/ts-basic-components-menuitem.md#selected) | selected | 18 | - When the [\@Local](arkts-new-local.md) decorated variable bound to **!!** changes, the UI is rendered synchronously. diff --git a/en/application-dev/quick-start/arkts-new-event.md b/en/application-dev/quick-start/arkts-new-event.md index a570a32549590d3f746cb3df5dd4ef3c9d6bf7b3..5feb41bbdf9199e42c317d16b6a929134ce902d9 100644 --- a/en/application-dev/quick-start/arkts-new-event.md +++ b/en/application-dev/quick-start/arkts-new-event.md @@ -58,7 +58,7 @@ You can use \@Event to change a variable in the parent component. When the varia @Entry @ComponentV2 struct Index { - @Local title: string = "Titile One"; + @Local title: string = "Title One"; @Local fontColor: Color = Color.Red; build() { diff --git a/en/application-dev/quick-start/arkts-new-getTarget.md b/en/application-dev/quick-start/arkts-new-getTarget.md index 8babd5efb04d6d6e75f832e54099e0b815fa3c07..9449448c7a7da810c7f0846feceef71a00ab3d4e 100644 --- a/en/application-dev/quick-start/arkts-new-getTarget.md +++ b/en/application-dev/quick-start/arkts-new-getTarget.md @@ -10,7 +10,7 @@ Before reading this topic, you are advised to read [\@Observed](./arkts-observed ## Overview -The state management framework adds proxies to original objects of the Class, Date, Map, Set, and Array types to observe attribute changes and API invoking. Proxies will change the variable types. In scenarios such as type determination and Node-API invoking, unexpected results may be generated because the variable type is not the type of the original object. +The state management framework adds proxies to original objects of the class, Date, Map, Set, and Array types to observe attribute changes and API invoking. Proxies will change the variable types. In scenarios such as type determination and Node-API invoking, unexpected results may be generated because the variable type is not the type of the original object. - Import the UIUtils to use the **getTarget** API. @@ -18,7 +18,7 @@ The state management framework adds proxies to original objects of the Class, Da import { UIUtils } from '@kit.ArkUI'; ``` -- In state management V1, a proxy is added to the class objects decorated by @Observed and the Class, Date, Map, Set, and Array decorated by @State or other state variable decorators to observe the changes of top-level attributes or changes invoked by APIs. +- In state management V1, a proxy is added to the class objects decorated by @Observed and the class, Date, Map, Set, and Array decorated by @State or other state variable decorators to observe the changes of top-level attributes or changes invoked by APIs. - In state management V2, a proxy is added to Date, Map, Set, and Array decorated by \@Trace, \@Local or other state variable decorators to observe changes invoked by APIs. Use **getTarget** to obtain the original objects of these proxy objects. @@ -70,7 +70,7 @@ Use **getTarget** to obtain the original objects of these proxy objects. ## Use Scenarios -### Obtains the original object before adding a proxy in the state management V1. +### Obtaining the Original Object Before Adding a Proxy in the State Management V1 State management V1 adds proxies to objects in the following scenarios: @@ -165,7 +165,7 @@ struct Index { } ``` -### Obtains the original object before adding a proxy in the state management V2. +### Obtaining the Original Object Before Adding a Proxy in the State Management V2 A proxy is added to the Map, Set, Date, and Array decorated by \@Trace, \@Local, or other state variable decorators in state management V2. Different from state management V1, the class object instances are not proxied in state management V2. diff --git a/en/application-dev/quick-start/arkts-new-monitor.md b/en/application-dev/quick-start/arkts-new-monitor.md index 61861a3b6e276357b719a09cfc7f94a4630cb09c..cd3055459e2358039d2096f820e9eaa048cfd64c 100644 --- a/en/application-dev/quick-start/arkts-new-monitor.md +++ b/en/application-dev/quick-start/arkts-new-monitor.md @@ -17,7 +17,7 @@ To listen for value changes of the state variables in a lower level, you can use - The \@Monitor decorator can be used in custom components decorated by \@ComponentV2. But it cannot listen for the changes of the state variables that are not decorated by these decorators: [\@Local](arkts-new-local.md), [\@Param](arkts-new-param.md), [\@Provider](arkts-new-Provider-and-Consumer.md), [\@Consumer](arkts-new-Provider-and-Consumer.md), and [\@Computed](arkts-new-Computed.md). - The \@Monitor decorator can be used in a class together with [\@ObservedV2 and \@Trace](arkts-new-observedV2-and-trace.md) decorators. But it cannot be used in a class that is not decorated by \@ObservedV2. \@Monitor cannot listen for the properties that are not decorated by \@Trace. -- When the listened property changes, the callback defined by \@Monitor will be called. Strict equality (===) is used to determine whether a property changes. If **false** is returned, the \@Monitor callback is triggered. When a property is changed for multiple times in an event, the initial value will be compared with the final value to determine whether the property is changed. +- When the listened property changes, the callback defined by \@Monitor will be called. Strict equality (===) is used to determine whether a property is changed. If **false** is return, the \@Monitor decorated callback is triggered. When a property is changed for multiple times in an event, the initial value will be compared with the final value to determine whether the property is changed. - A single \@Monitor decorator can listen for the changes of multiple properties at the same time. When these properties change together in an event, the \@Monitor callback method is triggered only once. - The \@Monitor decorator has lower-level listening capability and can listen for changes of specified items in nested classes, multi-dimensional arrays, and object arrays. The observation requires that \@ObservedV2 decorate the nested class and \@Trace decorate the member properties in an object array. - In the inheritance scenario, you can define \@Monitor for the same property in the parent and child components for listening. When the property changes, the \@Monitor callback defined in the parent and child components is called. @@ -1059,7 +1059,7 @@ property path:age change from 24 to 25 property path:name change from John to Johny ``` -Actually, the **name** attribute is not an observable variable and should not be added to the input parameters of \@Monitor. You are advised to remove the listening from the **name** attribute or add \@Trace to decorate the **name** attribute as a state variable. +Actually, the **name** attribute is not an observable variable and should not be added to the input parameters of \@Monitor. You are advised to remove the listening from the **name** attribute or use \@Trace to decorate the **name** attribute as a state variable. [Correct example 1] diff --git a/en/application-dev/quick-start/arkts-new-persistencev2.md b/en/application-dev/quick-start/arkts-new-persistencev2.md index 6de30b8e553106d63cbf343e1db6611db5350dcd..e8919e57d6c3248e8e095e9cc31180b01a20fd69 100644 --- a/en/application-dev/quick-start/arkts-new-persistencev2.md +++ b/en/application-dev/quick-start/arkts-new-persistencev2.md @@ -12,7 +12,7 @@ Before reading this topic, you are advised to read [\@ComponentV2](./arkts-new-c > >**PersistenceV2** is supported since API version 12. > ->**globalConnect** is supported since API version 16. The behavior of **globalConnect** is the same as that of **connect**. The only difference is that the underlying storage path of **connect** is a module-level path, while that of **globalConnect** is an application-level path. For details, see the section [Using connect and globalConnect in Different Modules](#using-connect-and-globalconnect-in-different-modules). +>**globalConnect** is supported since API version 18. The behavior of **globalConnect** is the same as that of **connect**. The only difference is that the underlying storage path of **connect** is a module-level path, while that of **globalConnect** is an application-level path. For details, see the section [Using connect and globalConnect in Different Modules](#using-connect-and-globalconnect-in-different-modules). ## Overview @@ -39,7 +39,7 @@ static connect( | connect | Description | | ------------ | ----------------------------------------------------- | -| Parameter | **type**: specified type. If no **key** is specified, the name of the **type** is used as the **key**.
**keyOrDefaultCreater**: specified key or default constructor.
**defaultCreator**: default constructor. | +| Parameter | **type**: specified type. If no **key** is specified, the name of the **type** is used as the **key**.
**keyOrDefaultCreator**: specified key or default constructor.
**defaultCreator**: default constructor. | | Return value | After creating or obtaining data, value is returned. Otherwise, **undefined** is returned.| >**NOTE** @@ -87,7 +87,7 @@ class ConnectOptions { | type | **TypeConstructorWithArgs\**: (mandatory) specified type. | | key | Input key of the string type. If no value is passed in, the type name is used as the key. | | defaultCreator | **StorageDefaultCreator\**: default constructor. It is recommended that this parameter be passed in. If **globalConnect** is connected to the key for the first time, an error is reported if no parameter is passed in.| -| areaMode | **contextConstant.AreaMode**: encryption level, ranging from EL1 to EL5 (corresponding to the value from 0 to 4). For details, see [Encryption Levels](../application-models/application-context-stage.md). If no value is passed in, EL2 is used by default. Storage paths vary based on the encryption levels. If the input value of encryption level is not in the range of **0** to **4**, a crash occurs.| +| areaMode | **contextConstant.AreaMode**: encryption level, ranging from EL1 to EL5 (corresponding to the value from 0 to 4). For details, see [Encryption Levels](../application-models/application-context-stage.md#obtaining-and-modifying-encryption-levels). If no value is passed in, EL2 is used by default. Storage paths vary based on the encryption levels. If the input value of encryption level is not in the range of **0** to **4**, a crash occurs.| > **NOTE** > @@ -346,7 +346,7 @@ When using **Navigation**, you need to add the **route_map.json** file to the ** "pageSourceFile": "src/main/ets/pages/Page2.ets", "buildFunction": "Page2Builder", "data": { - "description" : "AppStorageV2 example" + "description" : "PersistenceV2 example" } } ] diff --git a/en/application-dev/quick-start/arkts-new-rendering-control-repeat.md b/en/application-dev/quick-start/arkts-new-rendering-control-repeat.md index 7c9c887646d9aecff7877fbdbfa0babc1320900e..9713f072c0e6822661f4d8089007a8646fb0f86c 100644 --- a/en/application-dev/quick-start/arkts-new-rendering-control-repeat.md +++ b/en/application-dev/quick-start/arkts-new-rendering-control-repeat.md @@ -1,126 +1,257 @@ -# Repeat: Reusing Child Components +# Repeat: Reusable Repeated Rendering > **NOTE** > -> Repeat is supported since API version 12. +> **Repeat** is supported since API version 12. +> +> This topic is a developer guide. For details about API parameters, see [Repeat](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis-arkui/arkui-ts/ts-rendering-control-repeat.md). + +## Overview + +**Repeat** is used to perform repeated rendering based on array data. Generally, it is used together with container components. The **Repeat** component supports two modes: -This topic is a developer guide. For details about API parameters, see [Repeat](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis-arkui/arkui-ts/ts-rendering-control-repeat.md). +- Non-virtualScroll: All child components in the list are loaded during page initialization. This mode applies to scenarios where all short data lists or components are loaded. For details, see [Non-virtualscroll](#non-virtualscroll). +- virtualScroll: (For details about how to enable virtualScroll, see [virtualScroll](../reference/apis-arkui/arkui-ts/ts-rendering-control-repeat.md#virtualscroll)) The child components are loaded based on the valid loading area (including visible area and preload area) of the container components. When the container slides or the array changes, **Repeat** recalculates the valid loading range based on the parameters passed by the parent container component and manages the creation and destruction of list nodes in real time. +This mode applies to scenarios where long data lists need to be lazy loaded or performance needs to be optimized through component reuse. For details, see [virtualScroll](#virtualscroll). -In the non-virtualScroll scenario of (that is, [virtualScroll](../reference/apis-arkui/arkui-ts/ts-rendering-control-repeat.md#virtualscroll) is disabled), **Repeat**, used together with container components, renders repeated components based on the data source. In addition, the component returned by the API must be a child component that can be contained in the **Repeat** parent container component. Compared with ForEach, **Repeat** optimizes the rendering performance in some update scenarios and generates function with the index maintained by the framework. +> **NOTE** +> +> The differences between **Repeat**, **ForEach**, and **LazyForEach** are as follows: +> +> - Compared with [ForEach](arkts-rendering-control-foreach.md), the non-virtualScroll mode optimizes the rendering performance in specific array updates and manages the content and index of child components at the framework layer. +> - Compared with [LazyForEach](arkts-rendering-control-lazyforeach.md), the virtualScroll mode directly listens to the changes of state variables. However, **LazyForEach** requires you to implement the [IDataSource](../reference/apis-arkui/arkui-ts/ts-rendering-control-lazyforeach.md#idatasource10) API to manually manage the modification of the content and index of the child component. In addition, Repeat enhances the node reuse capability and improves the rendering performance for long list sliding and data update. The template function is added to **Repeat**. In the same array, different child components are rendered based on the custom template type. + +The following sample code uses the virtualScroll mode for repeated rendering. + +```ts +// Use the virtualScroll mode in the List container component. +@Entry +@ComponentV2 // The decorator of V2 is recommended. +struct RepeatExample { + @Local dataArr: Array = []; // Data source -When virtualScroll is enabled, **Repeat** iterates data from the provided data source as required and creates the corresponding component during each iteration. In this way, **Repeat** must be used together with the scrolling container component. When **Repeat** is used in the scrolling container component, the framework creates components as required based on the visible area of the scrolling container. When a component slides out of the visible area, the framework caches the component and uses it in the next iteration. + aboutToAppear(): void { + for (let i = 0; i < 50; i++) { + this.dataArr.push(`data_${i}`); // Add data to the array. + } + } + + build() { + Column() { + List() { + Repeat(this.dataArr) + .each((ri: RepeatItem) => { // Default template + ListItem() { + Text('each_A_' + ri.item).fontSize(30).fontColor(Color.Red) // The text color is red. + } + }) + .key((item: string, index: number): string => item) // Key generator. + .virtualScroll({ totalCount: this.dataArr.length }) // Enable the virtualScroll mode. totalCount indicates the data length to be loaded. + .templateId((item: string, index: number): string => { // Search for the corresponding template child component for rendering based on the return value. + return index <= 4 ? 'A' : (index <= 10 ? 'B' : ''); // The first five node templates are A, the next five node templates are B, and the rest are default templates. + }) + .template('A', (ri: RepeatItem) => { // Template A + ListItem() { + Text('ttype_A_' + ri.item).fontSize(30).fontColor(Color.Green) // The text color is green. + } + }, { cachedCount: 3 }) // The cache list capacity of template A is 3. + .template('B', (ri: RepeatItem) => { // Template B + ListItem() { + Text('ttype_B_' + ri.item).fontSize(30).fontColor(Color.Blue) // The text color is blue. + } + }, { cachedCount: 4 }) // The cache list capacity of template B is 4. + } + .cachedCount(2) // Size of the preload area of the container component + .height('70%') + .border({ width: 1 }) // Border + } + } +} +``` + +Execute the sample code, and you will see the following screen: + +![Repeat-NonVS-KeyGen](./figures/Repeat-Example.png) ## Constraints -- Repeat uses key value as identifiers. Therefore, **key()** must generate a unique value for each data. -- **Repeat virtualScroll** must be used in the scrolling container component. Only the [List](../reference/apis-arkui/arkui-ts/ts-container-list.md), [Grid](../reference/apis-arkui/arkui-ts/ts-container-grid.md), [Swiper](../reference/apis-arkui/arkui-ts/ts-container-swiper.md), and [WaterFlow](../reference/apis-arkui/arkui-ts/ts-container-waterflow.md) components support this scenario. In this case, **cachedCount** takes effect. Other container components apply only to the non-virtualScroll scenario. -- After **virtualScroll** is enabled for **Repeat**, only one child component can be created in each iteration. Otherwise, there is no constraint. The generated child components must be allowed in the parent container component of **Repeat**. -- When **Repeat** and custom component (or the @Builder function) are used together, the **RepeatItem** type must be passed as a whole so that the component can listen for data changes. If only **RepeatItem.item** or **RepeatItem.index** is passed, UI rendering exceptions occur. -- Currently, the template applies to scenarios where **virtualScroll** is enabled. If multiple template types are the same, **Repeat** overrides old **template()** and only the latest **template()** takes effect. -- If the value of **totalCount** is greater than that of **array.length**, when the parent component container is scrolling, the application should ensure that subsequent data is requested when the list is about to slide to the end of the data source until all data sources are loaded. Otherwise, the scrolling effect is abnormal. For details about the solution, see [The totalCount Value Is Greater Than the Length of Data Source](#the-totalcount-value-is-greater-than-the-length-of-data-source). -- Only one **Repeat** can be used in a scrolling container component (**List**, **Grid**, **Swiper**, or **WaterFlow**). Take **List** as an example. Containing **ListItem**, **ForEach**, and **LazyForEach** together in this component, or containing multiple **Repeat** components at the same time is not recommended. -- When **virtualScroll** is enabled, the decorators of V1 are not supported in **Repeat**. Using them together may throw an exception during rendering. +- Generally, **Repeat** is used together with the container component and the child component is allowed to be contained in the container component. For example, when **Repeat** is used together with the [List](../reference/apis-arkui/arkui-ts/ts-container-list.md) component, the child component must be the [ListItem](../reference/apis-arkui/arkui-ts/ts-container-listitem.md) component. +- When **Repeat** is used together with a custom component or the [@Builder function](./arkts-builder.md), the **RepeatItem** type must be passed as a whole so that the component can listen for data changes. If only **RepeatItem.item** or **RepeatItem.index** is passed, the UI rendering is abnormal. For details, see [Constraints on the Mixed Use of Repeat and @Builder](#constraints-on-the-mixed-use-of-repeat-and-builder). -## Key Generation Rules +Constraints on using the virtualScroll mode: -The purpose of **key()** is to allow **Repeat** to identify the details of array changes, including addition, deletion, and location (index) of data. +- This mode must be used in the scrolling container component. Only the [List](../reference/apis-arkui/arkui-ts/ts-container-list.md), [Grid](../reference/apis-arkui/arkui-ts/ts-container-grid.md), [Swiper](../reference/apis-arkui/arkui-ts/ts-container-swiper.md), and [WaterFlow](../reference/apis-arkui/arkui-ts/ts-container-waterflow.md) components support the virtualScroll mode. +- Decorators of V1 are not supported. If this mode is used together with the decorators of V1, the rendering is abnormal. +- Only one child component can be created. The generated child component must be allowed to be contained in the **Repeat** parent container component. +- The scrolling container component can contain only one **Repeat**. Take **List** as an example. Containing **ListItem**, **ForEach**, and **LazyForEach** together in this component, or containing multiple **Repeat** components at the same time is not recommended. +- If the value of **totalCount** is greater than the array length, when the parent component container is scrolling, the application should ensure that subsequent data is requested when the list is about to slide to the end of the data source until all data sources are loaded. Otherwise, the scrolling effect is abnormal. For details about the solution, see [The totalCount Value Is Greater Than the Length of Data Source](#the-totalcount-value-is-greater-than-the-length-of-data-source). -Suggestions: +**Repeat** uses keys to identify which data is added or deleted, and which data changes its position (index). You are advised to use **.key()** as follows: -- Even if there are duplicate data items (or the data source changes), you must ensure that the key is unique . -- Each time **key()** is executed, the same data item is used as the input, and the output must be consistent. -- Using index in **key()** is allowed, but not recommended. The reason is that the index changes when the data item is moved, that is, the key changes. Therefore, **Repeat** considers that the data item changes and triggers UI re-rendering, which deteriorates the performance. -- You are advised to convert a simple array to a class object array, add a **readonly id** property, and assign a unique value to it in the constructor. +- Even if the array changes, you must ensure that the key is unique. +- Each time **.key()** is executed, the same data item is used as the input, and the output must be consistent. +- (Not recommended) Use index in **.key()**. When the data item is moved, the index changes, and the key changes accordingly. As a result, **Repeat** considers that the data changes and triggers the child component to be rendered again, which deteriorates the performance. +- (Recommended) Convert a simple array to a class object array, add the **readonly id** property, and assign a unique value to it in the constructor. -### Non-virtualScroll +Since API version 18, you are not advised to use **.key()**. However, if you use **.key()** according to the preceding suggestions, **Repeat** can still maintain its compatibility and performance. -**key()** can be left empty. **Repeat** will generate the default key. +> **NOTE** +> +> The **Repeat** child component node can be created, updated, reused, and destroyed. A difference between node update and node reuse is as follows: +> +> - Node update: Nodes are not detached from the component tree. Only state variables are updated. +> - Node reuse: Old nodes are detached from the component tree and stored in the idle node cache pool. New nodes obtain reusable nodes from the cache pool and are attached to the tree again. -![Repeat-NonVS-KeyGen](./figures/Repeat-NonVS-KeyGen.png) +## Non-virtual scroll -### virtualScroll +### Key Generation Rules -The rule is basically the same as that of non-virtualScroll: **key()** can be left empty. +The following figure shows the logic of **.key()**. -![Repeat-VS-KeyGen](./figures/Repeat-VS-KeyGen.png) +If **.key()** is not specified, **Repeat** generates a new random key. If a duplicate key is found, **Repeat** recursively generates a key based on the existing key until no duplicate key exists. -## Component Generation and Reuse Rules +![Repeat-NonVS-KeyGen](./figures/Repeat-NonVS-KeyGen.png) -### Non-virtualScroll +### Child Component Rendering Logic -All child components are created when **Repeat** is rendered for the first time. The original components are reused when data is updated. +When **Repeat** is rendered for the first time, all child components are created. After the array is changed, Repeat performs the following operations: -When the **Repeat** component updates data, it compares all keys in the last update with those in the latest update. If the current key is the same as the last one, **Repeat** reuses the child component and updates **RepeatItem.index**. +First, traverse the old array keys. If the key does not exist in the new array, add it to the key set **deletedKeys**. -After **Repeat** compares all duplicate keys and reuses them, if the last key is unique and a new key is generated after this update, a child component needs to be created. In this case, **Repeat** will reuse redundant child components, update the **RepeatItem.item** data source and **RepeatItem.index**, and re-render the UI. +Second, traverse the new array keys and perform the corresponding operation when any of the following conditions is met: -If the number of remaining child components is greater than or equal to the number of newly updated components, the components are fully reused and redundant components are released. If the number of remaining child components is less than the number of newly updated components, **Repeat** will create components corresponding to the extra data items after the remaining data items are all reused. +1. If the same key can be found in the old array, the corresponding child component node is directly used and the index is updated. +2. If **deletedKeys** is not empty, update nodes corresponding to the keys in the set according to the last in first out (LIFO) policy. +3. If **deletedKeys** is empty, that is, no node can be updated. In this case, create a node. + +Third, if **deletedKeys** is not empty after the new array keys are traversed, the nodes corresponding to the keys in the set are destroyed. ![Repeat-NonVS-FuncGen](./figures/Repeat-NonVS-FuncGen.png) -### virtualScroll +The following figure shows an example of array changes. -At the first time when **Repeat** renders child components, only the required component is generated. During sliding and data update, nodes on the lower screen are cached. When a new component needs to be generated, the cached component is reused. +![Repeat-NonVS-Example](./figures/Repeat-NonVS-Example.png) -By default, the reuse function is enabled for **Repeat** in virtualScroll mode. You can configure the **reusable** field to determine whether to enable the reuse function since API version 16. To improve rendering performance, you are advised to enable the reuse function. +According to the preceding logic, **item_0** does not change, **item_1** and **item_2** only update indexes, **item_n1** and **item_n2** are obtained by updating **item_4** and **item_3**, respectively, and **item_n3** is the created node. -#### Slide shortcut +## virtualScroll -The following figure describes the node state before sliding. +### Key Generation Rules -![Repeat-Start](./figures/Repeat-Start.png) +Versions earlier than API version 18: -Currently, **Repeat** has two types of template. template type a sets three as its maximum cache value for the corresponding cache pool. template type b sets four as its maximum cache value and preloads one note for its parent components by default. Now the screen is swiped to the right, and **Repeat** will reuse the nodes in the cache pool. +If **.key()** is not defined, **Repeat** generates a new random key for each child node. If duplicate keys exist, **Repeat** generates a random key as the key of the current child node. Note that each time the page is refreshed, **.key()** is recalculated (that is, duplicate keys are generated again) to further generate a new random key. The format of a random key is **___${index}_+_${key}_+_${Math.random()}**, in which the variables are index, old key, and random number. -![Repeat-Slide](./figures/Repeat-Slide.png) +![Repeat-VS-KeyGen](./figures/Repeat-VS-KeyGen.png) -The data of **index=18** enters the screen and the preloading range of the parent component, coming up with b as this data's template type. In this case, **Repeat** obtains a node from the type b cache pool for reuse and updates its key, index, and data. Other grandchildren notes that use the data and index in the child node are updated based on the state management V2 rules. +Since API version 18: -The **index=10** note slides out of the screen and the preloading range of the parent component. When the UI main thread is idle, it checks whether the cache pool of template type a has sufficient space. In this case, there are four nodes in the cache pool, which exceeds the rated three, so **Repeat** will release the last node. +If you do not define **.key()**, **Repeat** directly compares the array data changes to determine whether the child nodes are changed. (If yes, the page refresh logic is triggered.) If duplicate keys exist, **Repeat** generates a random key as the key of the current data item. Note that each time the page is refreshed, **.key()** is recalculated (that is, duplicate keys are generated again) to further generate a new random key. The format of a random key is **___${index}_+_${key}_+_${Math.random()}**, in which the variables are index, old key, and random number. -![Repeat-Slide-Done](./figures/Repeat-Slide-Done.png) +### Child Component Rendering Logic -#### Data Update Scenarios +When **Repeat** is rendered for the first time, the required child components are created based on the valid loading area (including visible area and preload area) of the container component. + +When the container slides or the array changes, the invalid child component nodes (which are out of the valid loading area) are added to the idle node cache list (that is, detached from the component tree without destruction). When a new component needs to be generated, reuse the components in the cache (the variable values of the reused child components are updated and attached to the tree again). Since API version 18, **Repeat** supports [custom component freezing in virtualScroll mode](./arkts-custom-components-freezeV2.md#repeat-virtualscroll). + +By default, the reuse function is enabled for **Repeat** in virtualScroll mode. You can configure the **reusable** field to determine whether to enable the reuse function since API version 18. To improve rendering performance, you are advised to enable the reuse function. For details about the sample code, see [VirtualScrollOptions](../reference/apis-arkui/arkui-ts/ts-rendering-control-repeat.md#virtualscrolloptions). + +The following uses [sliding scenario](#sliding-scenario) and [data update scenario](#data-update-scenario) to show the rendering logic of the child component in virtualScroll mode. Define an array with a length of 20. The template type for the first five items in the array is **aa** and for the others are **bb**. The capacity of the buffer pool **aa** is 3 and that of **bb** is 4. The size of the preload area of the container component is 2. For easy understanding, one and two idle nodes are added to the cache pools **aa** and **bb** respectively. + +The following figure shows the node status in the list during initial rendering. ![Repeat-Start](./figures/Repeat-Start.png) -In this case, delete the **index=12** node, update the data of the **index=13** node, change the template type b to template type a of the **index=14** node, and update the key of the **index=15** node. +#### Sliding Scenario + +Swipe the screen to the right for a distance of one node and **Repeat** starts to reuse the nodes in the cache pool. The node whose index is 10 enters the valid loading area. Its template type is **bb**. Because the cache pool **bb** is not empty, **Repeat** obtains an idle node from this pool for reuse and updates the node attributes. Other grandchild components related to the data item and index in the child component are updated synchronously based on the rules of state management of V2. The rest nodes are still in the valid loading area and only their indexes are updated. + +The node whose index is 0 is out of the valid loading area. When the UI main thread is idle, the system checks whether the cache pool **aa** is full. If it is not full, the system adds the node to the corresponding cache pool; + +otherwise, **Repeat** destroys redundant nodes. + +![Repeat-Slide](./figures/Repeat-Slide.png) + +#### Data Update Scenario + +Perform the following array update operations based on the previous section. Delete the node whose index is 4 and change **item_7** to **new_7**. + +After the node whose index is 4 is deleted, this invalid node is added to the cache pool **aa**. The subsequent nodes move leftwards. The **item_11** node that enters the valid loading area reuses the idle node in the cache pool **bb**. For other nodes, only the index is updated, as shown in the following figure. ![Repeat-Update1](./figures/Repeat-Update1.png) -In this case, **Repeat** instructs the parent component to re-lay out and compare the template type values one by one. If the template type value of the node is the same as that of the original node, the node is reused; if the template type value changes, the node in the cache pool of the corresponding template type is reused. In both cases, the key, index, and data are updated. +Then, the **item_5** node move leftwards and its index is updated to 4. According to the calculation rule, the **item_5** node changes its template type to **aa**, reuses an idle node from the cache pool **aa**, and adds the old node to the cache pool **bb**, as shown in the following figure. ![Repeat-Update2](./figures/Repeat-Update2.png) -As shown in the preceding figure, node13 updates data and index; node14 updates the template type and index and reuses a node from the cache pool; node15 reuses its own node and updates key, index, and data synchronously because of the changed key and the unchanged template type; node 16 and node 17 only update index. The **index=17** node is new and reused from the cache pool. +### template: Child Component Rendering Template + +Currently, the template can be used only in virtualScroll mode. -![Repeat-Update-Done](./figures/Repeat-Update-Done.png) +- Each node obtains the template type based on **.templateId()** and renders the child component in the corresponding **.template()**. +- If multiple template types are the same, **Repeat** overwrites the previously defined **.template()** and only the last defined **.template()** takes effect. +- If the corresponding template type cannot be found, the child component in **.template()** whose type is empty is rendered first. If the child component does not exist, the child component in **.each()** is rendered. -## totalCount +### cachedCount: Size of the Idle Node Cache List -Total length of the data source, which can be greater than the number of loaded data items. Define the data source length as **arr.length**. The processing rules of **totalCount** are as follows: +**cachedCount** indicates the maximum number of child components that can be cached in the cache pool of the corresponding template type. This parameter is valid only in virtualScroll mode. + +> **NOTE** +> +> The **.cachedCount()** attribute of the scrolling container component and the **cachedCount** parameter of the **.template()** attribute of **Repeat** are used to balance performance and memory, but their meanings are different. +> - **.cachedCount()** indicates the nodes that are attached to the component tree and treated as invisible. Container components such as **List** or **Grid** render these nodes to achieve better performance. However, **Repeat** treats these nodes as visible. +> - **cachedCount** in **.template()** indicates the nodes that are treated as invisible by **Repeat**. These nodes are idle and are temporarily stored in the framework. You can update these nodes as required to implement reuse. + +When **cachedCount** is set to the maximum number of nodes that may appear on the screen of the current template, **Repeat** can be reused as much as possible. However, when there is no node of the current template on the screen, the cache pool is not released and the application memory increases. You need to set the configuration based on the actual situation. + +- If the default value is used, the framework calculates the value of **cachedCount** for each template based on the number of nodes displayed on the screen and the number of preloaded nodes. If the number increases, the value of **cachedCount** increases accordingly. Note that the value of cachedCount does not decrease. +- Explicitly specify **cachedCount**. It is recommended that the value be the same as the number of nodes on the screen. Yet, setting **cachedCount** to less than 2 is not advised. Doing so may lead to the creation of new nodes during rapid scrolling, which could result in performance degradation. + +### totalCount: Length of the Data to Be Loaded + +**totalCount** indicates the length of the data to be loaded. The default value is the length of the original array. The value can be greater than the number of loaded data items. Define the data source length as **arr.length**. The processing rules of **totalCount** are as follows: - When **totalCount** is set to the default value or a non-natural number, the value of **totalCount** is **arr.length**, and the list scrolls normally. -- When **0** <= **totalCount** < **arr.length**, only **totalCount** list items are rendered. -- When **totalCount** is greater than **arr.length**, Repeat renders **totalCount** list items, and the scroll bar style changes based on the value of **totalCount**. +- When **totalCount** is greater that or equal to **0** and smaller than **arr.length**, only data within the range of [0, *totalCount* - 1] is rendered. +- When **totalCount** is greater than **arr.length**, data in the range of [0, *totalCount* - 1] will be rendered. The scrollbar style changes based on the value of **totalCount**. > **NOTE** > -> If **totalCount** is greater than **array.length**, when the parent component container is scrolling, the application needs to ensure that subsequent data is requested when the list is about to slide to the end of the data source. You need to fix the data request error (caused by, for example, network delay) until all data sources are loaded. Otherwise, the scrolling effect is abnormal. +> If **totalCount** is greater than **arr.length**, the application should request subsequent data when the list scrolls to the end of the data source. You need to fix the data request error (caused by, for example, network delay) until all data sources are loaded. Otherwise, the scrolling effect is abnormal. -## cachedCount +### onTotalCount: Calculating the Expected Data Length -**cachedCount** indicates the maximum number of subnodes that can be cached in the **Repeat** cache pool of the current template. This parameter is valid only when **virtualScroll** is enabled. +onTotalCount?(): number; -You need to understand the differences between **.cachedCount()** of the scrolling container component and **cachedCount()** of **Repeat**. Both are used to balance performance and memory, but their definitions are different. +It is supported since API version 18 and must be used in virtualScroll mode. You can customize a method to calculate the expected array length. The return value must be a natural number and may not be equal to the actual data source length **arr.length**. The processing rules of **onTotalCount** are as follows: -- **.cachedCount()** indicates the nodes that are located in the component tree and treated as invisible. Container components such as **List** or **Grid** render these nodes to achieve better performance. But **Repeat** treats these nodes as visible. -- **cachedCount()** of **Repeat** indicates the nodes that are treated as invisible by **Repeat**. These nodes are idle and are temporarily stored in the framework. You can update these nodes as required to implement reuse. +- When the return value is a non-natural number, **arr.length** is used as the return value and the list scrolls normally. +- When the return value of **onTotalCount** is greater that or equal to **0** and smaller than **arr.length**, only data within the range of [0, *return value* - 1] is rendered. +- When the return value of **onTotalCount** is greater than **arr.length**, the data within the range of [0, *return value* - 1] is rendered. The scrollbar style changes based on the return value of **onTotalCount**. -When **cachedCount** is set to the maximum number of nodes that may appear on the screen of the current template, **Repeat** can be reused as much as possible. However, when there is no node of the current template on the screen, the cache pool is not released and the application memory increases. You need to set the configuration based on the actual situation. +> **NOTE** +> +> - Compared with using **totalCount**, **Repeat** can proactively call the **onTotalCount** method to update the expected data length when necessary. +> - Either **totalCount** or **onTotalCount** can be set. If neither of them is set, the default **arr.length** is used. If both of them are set, **totalCount** is ignored. +> - When the return value of **onTotalCount** is greater than **arr.length**, you are advised to use **onLazyLoading** to implement lazy loading. -- If the default value is used, the framework calculates the value of **cachedCount** for each template based on the number of nodes displayed on the screen and the number of preloaded nodes. If the number increases, the value of **cachedCount** increases accordingly. Note that the value of cachedCount does not decrease. -- Explicitly specify **cachedCount**. It is recommended that the value be the same as the number of nodes on the screen. Yet, setting **cachedCount** to less than 2 is not advised. Doing so may lead to the creation of new nodes during rapid scrolling, which could result in performance degradation. +### onLazyLoading: Precise Lazy Loading + +onLazyLoading?(index: number): void; + +It is supported since API version 18 and must be used in virtualScroll mode. You can customize a method to write data to a specified index in the data source. The processing rules of **onLazyLoading** are as follows: + +- Before reading the data corresponding to an index in the data source, **Repeat** checks whether the index contains data. +- If no data exists and a custom method is defined, **Repeat** calls this method. +- In the **onLazyLoading** method, data should be written to the index specified by **Repeat** in the format of **arr[index] = ...**. In addition, array operations except **[]** are not allowed, and elements except the specified index cannot be written. Otherwise, the system throws an exception. +- After the **onLazyLoading** method is executed, if no data exists in the specified index, the rendering is abnormal. + +> **NOTE** +> +> - When using **onLazyLoading**, you are advised to use **onTotalCount** together instead of **totalCount**. +> - If the expected data source length is greater than the actual one, **onLazyLoading** is recommended. +> - Avoid using the **onLazyLoading** method to execute time-consuming operations. If data loading takes a long time, you can create a placeholder for the data in the **onLazyLoading** method and then create an asynchronous task to load the data. +> - When **onLazyLoading** is used and **onTotalCount** is set to **arr.length + 1**, data can be loaded infinitely. In this scenario, you need to provide the initial data required for the first screen display and set **cachedCount** that is greater than 0 for the parent container component. Otherwise, the rendering is abnormal. If the **onLazyLoading** method is used together with the loop mode of **Swipe**, the **onLazyLoading** method will be triggered continuously when screen stays at the node whose index is 0 Therefore, you are advised not to use them together. In addition, you need to pay attention to the memory usage to avoid excessive memory consumption caused by continuous data loading. ## Use Scenarios @@ -231,11 +362,11 @@ struct ChildItem { ### VirtualScroll -This section describes the actual application scenarios of **Repeat** and the reuse of component nodes in the **virtualScroll** scenario. A large number of test scenarios can be derived based on reuse rules. This section only describes typical data changes. +This section describes the actual use scenarios of **Repeat** and the reuse of component nodes in virtualScroll mode. A large number of test scenarios can be derived based on reuse rules. This section only describes typical data changes. #### One Template -The following code designs typical data source operations in the **virtualScroll** scenario of the **Repeat** component, including inserting, modifying, deleting, and exchanging data. Select an index value from the drop-down list and click the corresponding button to change the data. You can click two data items in sequence to exchange them. +The following sample code shows how to insert, modify, delete, and exchange data in an array in virtualScroll mode. Select an index value from the drop-down list and click the corresponding button to change the data. You can click two data items in sequence to exchange them. ```ts @ObservedV2 @@ -369,7 +500,7 @@ The application list contains 100 **message** properties of the custom class **R #### Multiple Templates -``` +```ts @ObservedV2 class Repeat006Clazz { @Trace message: string = ''; @@ -509,9 +640,153 @@ struct RepeatVirtualScroll2T { ![Repeat-VirtualScroll-2T-Demo](./figures/Repeat-VirtualScroll-2T-Demo.gif) +#### Precise Lazy Loading + +If the total length of a data source or data item loading duration is long, you can use lazy loading to prevent all data from being loaded during initialization. + +**Example 1** + +The total length of the data source is long. When the data is rendered for the first time, the screen is scrolled, or the display area is switched, the data in the corresponding area is dynamically loaded. + +```ts +@Entry +@ComponentV2 +struct RepeatLazyLoading { + // Assume that the total length of the data source is 1000. The initial array does not provide data. + @Local arr: Array = []; + scroller: Scroller = new Scroller(); + build() { + Column({ space: 5 }) { + // The initial index displayed on the screen is 100. The data can be automatically obtained through lazy loading. + List({ scroller: this.scroller, space: 5, initialIndex: 100 }) { + Repeat(this.arr) + .virtualScroll({ + // The expected total length of the data source is 1000. + onTotalCount: () => { return 1000; }, + // Implement lazy loading. + onLazyLoading: (index: number) => { this.arr[index] = index.toString(); } + }) + .each((obj: RepeatItem) => { + ListItem() { + Row({ space: 5 }) { + Text(`${obj.index}: Item_${obj.item}`) + } + } + .height(50) + }) + } + .height('80%') + .border({ width: 1}) + // Redirect to the index whose value is 500. The data can be automatically obtained through lazy loading. + Button('ScrollToIndex 500') + .onClick(() => { this.scroller.scrollToIndex(500); }) + } + } +} +``` + +The figure below shows the effect. + +![Repeat-Lazyloading-1](./figures/repeat-lazyloading-demo1.gif) + +**Example 2** + +Data loading takes a long time. In the **onLazyLoading** method, placeholders are created for data items, and then data is loaded through asynchronous tasks. + +```ts +@Entry +@ComponentV2 +struct RepeatLazyLoading { + @Local arr: Array = []; + build() { + Column({ space: 5 }) { + List({ space: 5 }) { + Repeat(this.arr) + .virtualScroll({ + onTotalCount: () => { return 100; }, + // Implement lazy loading. + onLazyLoading: (index: number) => { + // Create a placeholder. + this.arr[index] = ''; + // Simulate a time-consuming loading process and load data through an asynchronous task. + setTimeout(() => { this.arr[index] = index.toString(); }, 1000); + } + }) + .each((obj: RepeatItem) => { + ListItem() { + Row({ space: 5 }) { + Text(`${obj.index}: Item_${obj.item}`) + } + } + .height(50) + }) + } + .height('100%') + .border({ width: 1}) + } + } +} +``` + +The figure below shows the effect. + +![Repeat-Lazyloading-2](./figures/repeat-lazyloading-demo2.gif) + +**Example 3** + +Lazy loading is used together with **onTotalCount: () => { return this.arr.length + 1; }** to implement unlimited lazy loading. + +> **NOTE** +> +> - In this scenario, you need to provide the initial data required for the first screen display and set **cachedCount** that is greater than 0 for the parent container component. Otherwise, the rendering is abnormal. +> - If the **onLazyLoading** method is used together with the loop mode of **Swipe**, the **onLazyLoading** method will be triggered continuously when screen stays at the node whose index is 0 Therefore, you are advised not to use them together. +> - You need to pay attention to the memory usage to avoid excessive memory consumption caused by continuous data loading. + +```ts +@Entry +@ComponentV2 +struct RepeatLazyLoading { + @Local arr: Array = []; + // Provide the initial data required for the first screen display. + aboutToAppear(): void { + for (let i = 0; i < 15; i++) { + this.arr.push(i.toString()); + } + } + build() { + Column({ space: 5 }) { + List({ space: 5 }) { + Repeat(this.arr) + .virtualScroll({ + // Unlimited lazy loading. + onTotalCount: () => { return this.arr.length + 1; }, + onLazyLoading: (index: number) => { this.arr[index] = index.toString(); } + }) + .each((obj: RepeatItem) => { + ListItem() { + Row({ space: 5 }) { + Text(`${obj.index}: Item_${obj.item}`) + } + } + .height(50) + }) + } + .height('100%') + .border({ width: 1}) + // You are advised to set cachedCount to a value greater than 0. + .cachedCount(1) + } + } +} +``` + +The figure below shows the effect. + +![Repeat-Lazyloading-3](./figures/repeat-lazyloading-demo3.gif) + ### Using Repeat in a Nesting Manner -Example: +**Repeat** can be nested in other components. The following showcases the sample code for nesting **Repeat** in virtualScroll mode: ```ts // Repeat can be nested in other components. @@ -549,6 +824,7 @@ struct RepeatNest { } }) .key((item) => "innerList_" + item) + .virtualScroll() } .width('80%') .border({ width: 1 }) @@ -560,6 +836,7 @@ struct RepeatNest { .border({ width: 1 }) }) .key((item) => "outerList_" + item) + .virtualScroll() } .width('80%') .border({ width: 1 }) @@ -575,11 +852,13 @@ The figure below shows the effect. ![Repeat-Nest](./figures/Repeat-Nest.png) -## Application Scenario of the Parent Container Component +### Use Scenarios of the Parent Container Component + +This section describes the common use scenarios of virtualScroll mode and container components. -### Using Together with List +#### Using Together with List -Use **virtualScroll** of **Repeat** in the **List** container component. The following is an example: +Use virtualScroll mode of **Repeat** in the **List** container component. The following is an example: ```ts class DemoListItemInfo { @@ -676,11 +955,12 @@ struct DemoList { } } ``` + Swipe left and touch the **Delete** button, or touch the button at the bottom to delete the video widget. ![Repeat-Demo-List](./figures/Repeat-Demo-List.gif) -### Using Together with Grid +#### Using Together with Grid Use **virtualScroll** of **Repeat** in the **Grid** container component. The following is an example: @@ -804,11 +1084,12 @@ struct DemoGrid { } } ``` + Swipe down on the screen, touch the **Refresh** button, or touch **Last viewed here. Touch to refresh.** to load new videos. ![Repeat-Demo-Grid](./figures/Repeat-Demo-Grid.gif) -### Using Together with Swiper +#### Using Together with Swiper Use **virtualScroll** of **Repeat** in the **Swiper** container component. The following is an example: @@ -822,8 +1103,8 @@ const remotePictures: Array = [ 'https://www.example.com/xxx/0006.jpg', 'https://www.example.com/xxx/0007.jpg', 'https://www.example.com/xxx/0008.jpg', - 'https://www.example.com/xxx/0009.jpg', -] + 'https://www.example.com/xxx/0009.jpg' +]; @ObservedV2 class DemoSwiperItemInfo { @@ -887,10 +1168,192 @@ struct DemoSwiper { } } ``` + Load the image 1s later to simulate the network latency. ![Repeat-Demo-Swiper](./figures/Repeat-Demo-Swiper.gif) +### Enabling Drag and Sort + +If **Repeat** is used in a list, and the **onMove** event is set, you can enable drag and sort for the list items. Both the non-virtualScroll and virtualScroll modes support drag and sort. + +#### Constraints +- If an item changes the position after you drag and sort the data, the **onMove** event is triggered to report the original index and target index of the item. The data source needs to be modified in the **onMove** event based on the reported start index and target index. Before and after the data source is modified, the value of each item must remain unchanged to ensure that the drop animation can be executed properly. +- During the drag and sort, the data source cannot be modified. + +#### Sample Code +```ts +@Entry +@ComponentV2 +struct RepeatVirtualScrollOnMove { + @Local simpleList: Array = []; + + aboutToAppear(): void { + for (let i = 0; i < 100; i++) { + this.simpleList.push(`${i}`); + } + } + + build() { + Column() { + List() { + Repeat(this.simpleList) + // Set onMove to enable the drag and sort. + .onMove((from: number, to: number) => { + let temp = this.simpleList.splice(from, 1); + this.simpleList.splice(to, 0, temp[0]); + }) + .each((obj: RepeatItem) => { + ListItem() { + Text(obj.item) + .fontSize(16) + .textAlign(TextAlign.Center) + .size({height: 100, width: "100%"}) + }.margin(10) + .borderRadius(10) + .backgroundColor("#FFFFFFFF") + }) + .key((item: string, index: number) => { + return item; + }) + .virtualScroll({ totalCount: this.simpleList.length }) + } + .border({ width: 1 }) + .backgroundColor("#FFDCDCDC") + .width('100%') + .height('100%') + } + } +} +``` + +The figure below shows the effect. + +![Repeat-Drag-Sort](figures/ForEach-Drag-Sort.gif) + +### Using .key() to Control the Node Refresh Range + +Since API version 18, when you customize **.key()**, the child nodes of **Repeat** determine whether to update themselves based on the key. After the array is modified: (1) If the key is changed, the page is refreshed immediately and the data is updated to the new value. (2) If the key is not changed, the page is not refreshed. + +Prerequisites: The array is rendered in virtualScroll mode. The data item **RepeatData** is a class decorated by @ObservedV2. Two properties of this class, **id** and **msg**, are decorated by @Trace. The value of **msg** is used as the content of the node rendered in the list. Click the **click** button to modify the content of the first node in the list. + +Scenario 1: When the property value of the list node data changes, the page is refreshed, and the data of the first list node is updated to the modified value. + +This scenario can be implemented in either of the following ways: (1) Define **.key()** and change the key value of the corresponding node. (2) If **.key()** is not defined, **Repeat** directly checks whether the data object is changed. The sample code is as follows: + +```ts +@ObservedV2 +class RepeatData { + @Trace id: string; + @Trace msg: string; + + constructor(id: string, msg: string) { + this.id = id; + this.msg = msg; + } +} + +@Entry +@ComponentV2 +struct RepeatRerender { + @Local dataArr: Array = []; + + aboutToAppear(): void { + for (let i = 0; i < 10; i++) { + this.dataArr.push(new RepeatData(`key${i}`, `data${i}`)); + } + } + + build() { + Column({ space: 20 }) { + List() { + Repeat(this.dataArr) + .each((ri: RepeatItem) => { + ListItem() { + Text(ri.item.msg).fontSize(30) + } + }) + .key((item: RepeatData, index: number) => item.msg) // Method 1: Set the return value of .key() to be consistent with the value of changed node data, for example, the value of msg. + // Method 2: Delete .key(). + .virtualScroll() + } + .cachedCount(2) + .width('100%') + .height('40%') + .border({ width: 1 }) + .backgroundColor(0xFAEEE0) + + Button('click').onClick(() => { + this.dataArr.splice(0, 1, new RepeatData('key0', 'new msg')); // Change the value of msg of the first node. + }) + } + } +} +``` + +After you click the button, the data changes as follows. + +![Repeat-Rerender-Wrong](./figures/Repeat-Rerender-Wrong.gif) + +Scenario 2: When the property value of the list node data changes but the key remains unchanged, page refresh is not triggered immediately, so that a node refresh frequency is controlled and overall rendering performance of the page is improved. + +Implementation: Define **.key()**. The return value is the **id** property of the node data object. After you click the button, the value of **id** (key) remains unchanged. After you change the value of **msg**, the page is not refreshed. The sample code is as follows: + +Note that if you directly modify the **msg** property (**this.dataArr[0].msg ='new msg'**), the page is still refreshed. This is because the value of **msg** is decorated by @Trace. If the value is directly modified, the change logic of state variable is triggered and the page is refreshed immediately. + +```ts +@ObservedV2 +class RepeatData { + @Trace id: string; + @Trace msg: string; + + constructor(id: string, msg: string) { + this.id = id; + this.msg = msg; + } +} + +@Entry +@ComponentV2 +struct RepeatRerender { + @Local dataArr: Array = []; + + aboutToAppear(): void { + for (let i = 0; i < 10; i++) { + this.dataArr.push(new RepeatData(`key${i}`, `data${i}`)); + } + } + + build() { + Column({ space: 20 }) { + List() { + Repeat(this.dataArr) + .each((ri: RepeatItem) => { + ListItem() { + Text(ri.item.msg).fontSize(30) + } + }) + .key((item: RepeatData, index: number) => item.id) // Set the return value of .key() to a value that is not affected by the change of child node, for example, the value of id. + .virtualScroll() + } + .cachedCount(2) + .width('100%') + .height('40%') + .border({ width: 1 }) + .backgroundColor(0xFAEEE0) + + Button('click').onClick(() => { + this.dataArr.splice(0, 1, new RepeatData('key0', 'new msg')); // Change the value of msg of the first node data and retain the value of id. + }) + } + } +} +``` + +After you click the button, the data does not change. + +![Repeat-Rerender-Correct](./figures/Repeat-Rerender-Correct.gif) + ## FAQs ### Ensure that the Position of the Scrollbar Remains Unchanged When the List Data Outside the Screen Changes @@ -1025,7 +1488,7 @@ The figure below shows the effect. When the total length of the data source is large, the lazy loading is used to load some data first. To enable **Repeat** to display the correct scrollbar style, you need to change the value of **totalCount** to the total length of data. That is, before all data sources are loaded, the value of **totalCount** is greater than that of **array.length**. -If **totalCount** is greater than **array.length**, when the parent component container is scrolling, the application needs to ensure that subsequent data is requested when the list is about to slide to the end of the data source. You need to fix the data request error (caused by, for example, network delay) until all data sources are loaded. Otherwise, the scrolling effect is abnormal. +If **totalCount** is greater than **array.length**, the application should request subsequent data when the list scrolls to the end of the data source. You need to fix the data request error (caused by, for example, network delay) until all data sources are loaded. Otherwise, the scrolling effect is abnormal. You can use the callback of [onScrollIndex](https://gitee.com/openharmony/docs/blob/master/en/application-dev/ui/arkts-layout-development-create-list.md#controlling-the-scrolling-position) attribute of the **List** or **Grid** parent component to implement the preceding specification. The sample code is as follows: @@ -1046,7 +1509,7 @@ class VehicleDB { public vehicleItems: VehicleData[] = []; constructor() { - // init data size 20 + // The initial size of the array is 20. for (let i = 1; i <= 20; i++) { this.vehicleItems.push(new VehicleData(`Vehicle${i}`, i)); } @@ -1065,7 +1528,7 @@ struct entryCompSucc { Column({ space: 3 }) { List({ scroller: this.scroller }) { Repeat(this.vehicleItems) - .virtualScroll({ totalCount: 50 }) // total data size 50 + .virtualScroll({ totalCount: 50 }) // The expected array length is 50. .templateId(() => 'default') .template('default', (ri) => { ListItem() { @@ -1099,7 +1562,7 @@ struct entryCompSucc { .alignListItem(ListItemAlign.Center) .onScrollIndex((start, end) => { console.log('onScrollIndex', start, end); - // lazy data loading + // Lazy loading if (this.vehicleItems.length < 50) { for (let i = 0; i < 10; i++) { if (this.vehicleItems.length < 50) { diff --git a/en/application-dev/quick-start/arkts-new-reusableV2.md b/en/application-dev/quick-start/arkts-new-reusableV2.md index 88d5d0c6dfa686a783e46b3d0bf75a769e27a341..232252ee94f16650a290f44eadd60fe2ed5be468 100644 --- a/en/application-dev/quick-start/arkts-new-reusableV2.md +++ b/en/application-dev/quick-start/arkts-new-reusableV2.md @@ -6,7 +6,7 @@ Before reading this topic, you are advised to read [\@Reusable Decorator: Reusin >**NOTE** > ->The \@ReusableV2 decorator is supported since API version 16. +>The \@ReusableV2 decorator is supported since API version 18. > ## Overview @@ -267,9 +267,9 @@ struct ReusableV2Component { You are advised to follow the steps below: 1. Click **step1. appear** to change the value of **condition1** to **true**. The **if** component in **Index** switches the branch and creates a **NormalV2Component**. Due to the initial value **true** of **condition2**, the **if** condition in **NormalV2Component** is met and the system attempts to create a **ReusableV2Component**. In this case, there is no element in the reuse pool. Therefore, **ReusableV2Component** is created, the **aboutToAppear** method is called back, and the log **ReusableV2Component aboutToAppear called** is output. -2. Click **step2. recycle** to change the value of **condition2** to **false** and synchronize this change to **NormalComponent** through \@Param. The **if** condition is switched. Because **ReusableV2Component** uses \@ReusableV2, the component is recycled to the reuse pool instead of being destroyed. The **aboutToRecycle** method is called back and the log **ReusableV2Component aboutToRecycle called** is output. -3. Click **step3. reuse** to change the value of **condition2** to **true** and is transferred to `NormalComponent` through \@Param. The **if** condition is switched. Because **ReusableV2Component** uses \@ReusableV2, the system attempts to search for the component in the reuse pool when creating the component. In this case, the component recycled in step 2 is reused from the reuse pool, the **aboutToReuse** method is called back, and the log **ReusableV2Component aboutToReuse called** is output. -4. Click **step4. disappear** to change the value of **condition1** to **false**. The **if** component in **Index** switches the branch and destroys **NormalComponent**. In this case, **ReusableV2Component** is destroyed due to the destroyed parent component, the **aboutToDisappear** method is called back, and the log **ReusableV2Component aboutToDisappear called** is output. +2. Click **step2. recycle** to change the value of **condition2** to **false** and synchronize this change to **NormalV2Component** through \@Param. The **if** condition is switched. Because **ReusableV2Component** uses \@ReusableV2, the component is recycled to the reuse pool instead of being destroyed. The **aboutToRecycle** method is called back and the log **ReusableV2Component aboutToRecycle called** is output. +3. Click **step3. reuse** to change the value of **condition2** to **true** and synchronize this change to **NormalV2Component** through \@Param. The **if** condition is switched. Because **ReusableV2Component** uses \@ReusableV2, the system attempts to search for the component in the reuse pool when creating the component. In this case, the component recycled in step 2 is reused from the reuse pool, the **aboutToReuse** method is called back, and the log **ReusableV2Component aboutToReuse called** is output. +4. Click **step4. disappear** to change the value of **condition1** to **false**. The **if** component in **Index** switches the branch and destroys **NormalV2Component**. In this case, **ReusableV2Component** is destroyed due to the destroyed parent component, the **aboutToDisappear** method is called back, and the log **ReusableV2Component aboutToDisappear called** is output. If the reusable component has child components, **aboutToRecycle** and **aboutToReuse** of the child components are recursively called during recycling and reuse (irrelevant to whether the child components are marked for reuse) until all child components are traversed. @@ -350,7 +350,7 @@ The reset is performed based on the sequence of variables defined in the compone | Decorator | Method for Resetting | | ---------- | ------------------------------------------------------------ | | \@Local | Use the initial value for reassignment. | -| \@Param | Use external input value for re-assignment. If there is no external input value, use the local initial value. Note that variables decorated by \@Once are also reset and initialized.| +| \@Param | Use external input value for reassignment. If there is no external input value, use the local initial value. Note that variables decorated by \@Once are also reset and initialized.| | \@Event | Use external input value for reassignment. If there is no external input value, use the local initial value. If there is no local initial value, the default empty implementation is generated.| | \@Provider | Use the initial value for reassignment. | | \@Consumer | If the corresponding \@Provider exists, use the value of \@Provider. Otherwise, use the local initial value for reassignment.| @@ -671,7 +671,7 @@ struct ReusableV2Component { > >You are advised to use the non-virtualScroll scenarios of **Repeat** to replace **ForEach**. -In the following example, ForEach is used to render multiple reusable components. Each time the `Click to change` button is clicked, the key value changes. Therefore, recycling and reuse are triggered from the second click. (When ForEach determines whether there is reusable nodes, the reuse pool is not initialized. Therefore, when ForEach is clicked for the first time, a new node is created. Then, the reuse pool is initialized from the second click and the node is recycled at the same time.) +In the following example, ForEach is used to render multiple reusable components. Each time the **Click to change** button is clicked, the key value changes. Therefore, recycling and reuse are triggered from the second click. (When ForEach determines whether there is reusable nodes, the reuse pool is not initialized. Therefore, when ForEach is clicked for the first time, a new node is created. Then, the reuse pool is initialized from the second click and the node is recycled at the same time.) ```ts @Entry diff --git a/en/application-dev/quick-start/arkts-observed-and-objectlink.md b/en/application-dev/quick-start/arkts-observed-and-objectlink.md index 54b05e5ee024eb10e23ae7976cbd7c381af2d549..09245969fb2346867beeb82a5594541478c90264 100644 --- a/en/application-dev/quick-start/arkts-observed-and-objectlink.md +++ b/en/application-dev/quick-start/arkts-observed-and-objectlink.md @@ -32,7 +32,7 @@ The decorators including [\@State](./arkts-state.md), [\@Prop](./arkts-prop.md), | \@ObjectLink Decorator| Description | | ----------------- | ---------------------------------------- | | Decorator parameters | None. | -| Allowed variable types | Objects of \@Observed decorated classes. The type must be specified.
\@ObjectLink does not support simple types. To use simple types, you can use [\@Prop](arkts-prop.md).
Objects of classes that extend Date, [Array](#two-dimensional-array), [Map](#extended-map-class), and [Set](#extended-set-class) (the latter two are supported since API version 11). For an example, see [Observed Changes](#observed-changes).
(Applicable to API version 11 or later) Union type of @Observed decorated classes and **undefined** or **null**, for example, **ClassA \| ClassB**, **ClassA \| undefined**, or **ClassA \| null**. For details, see [Union Type @ObjectLink](#union-type-objectlink).
An \@ObjectLink decorated variable accepts changes to its properties, but assignment is not allowed. In other words, an \@ObjectLink decorated variable is read-only and cannot be changed.| +| Allowed variable types | (Application to API version 18 or earlier) \@Observed decorated class instance.
(Application to API version 18 or later) \@ObjectLink can also be initialized by the return value of [makeV1Observed](../reference/apis-arkui/js-apis-StateManagement.md#makev1observed18).
\@ObjectLink does not support simple types. To use simple types, you can use [\@Prop](arkts-prop.md).
Objects of classes that extend Date, [Array](#two-dimensional-array), [Map](#extended-map-class), and [Set](#extended-set-class) (the latter two are supported since API version 11). For an example, see [Observed Changes](#observed-changes).
(Applicable to API version 11 or later) Union type of @Observed decorated classes and **undefined** or **null**, for example, **ClassA \| ClassB**, **ClassA \| undefined**, or **ClassA \| null**. For details, see [Union Type @ObjectLink](#union-type-objectlink).
An @ObjectLink decorated variable accepts changes to its properties, but assignment is not allowed. In other words, an @ObjectLink decorated variable is read-only and cannot be changed.| | Initial value for the decorated variable | Not allowed. | Example of a read-only \@ObjectLink decorated variable: @@ -192,7 +192,7 @@ For a class that extends **Set**, the value changes of the **Set** instance can b. The \@ObjectLink decorated variable in the child component is initialized from the parent component and accepts the instance of the \@Observed decorated class. The \@ObjectLink decorated wrapped object registers itself with the \@Observed decorated class. -2. Property update: When the property of the \@Observed decorated class is updated, the framework executes the **setter** and **getter** methods of the proxy, traverses the \@ObjectLink decorated wrapped objects that depend on it, and notifies the data update. +2. Property update: When the property of the \@Observed decorated class is updated, the framework executes **setter** and **getter** methods of the proxy, traverses the \@ObjectLink decorated wrapped objects that depend on it, and notifies the data update. ## Constraints @@ -201,7 +201,10 @@ For a class that extends **Set**, the value changes of the **Set** instance can 2. The \@ObjectLink decorator cannot be used in custom components decorated by \@Entry. -3. The variable type decorated by \@ObjectLink must be an explicit class decorated by @Observed. If the type is not specified or the class is not decorated by \@Observed, an error is reported during compilation. +3. \@ObjectLink decorated type must be the complex type. Otherwise, an error is reported during compilation. + +4. For API version 18 or earlier, the variable type decorated by \@ObjectLink must be the class explicitly decorated by @Observed. If no type is specified or the class is not decorated by \@Observed, an error is reported during compilation. +For API version 18 and later, \@ObjectLink can also be initialized by the return value of [makeV1Observed](../reference/apis-arkui/js-apis-StateManagement.md#makev1observed18). Otherwise, an error is reported during runtime. ```ts @Observed @@ -230,7 +233,7 @@ For a class that extends **Set**, the value changes of the **Set** instance can @ObjectLink count: Info; ``` -4. Variables decorated by \@ObjectLink cannot be initialized locally. You can only pass in the initial value from the parent component through construction parameters. Otherwise, an error is reported during compilation. +5. Variables decorated by \@ObjectLink cannot be initialized locally. You can only pass in the initial value from the parent component through construction parameters. Otherwise, an error is reported during compilation. ```ts @Observed @@ -249,7 +252,7 @@ For a class that extends **Set**, the value changes of the **Set** instance can @ObjectLink count: Info; ``` -5. The variables decorated by \@ObjectLink are read-only and cannot be assigned values. Otherwise, an error "Cannot set property when setter is undefined" is reported during runtime. If you need to replace all variables decorated by \@ObjectLink, you can replace them in the parent component. +6. The variables decorated by \@ObjectLink are read-only and cannot be assigned values. Otherwise, an error "Cannot set property when setter is undefined" is reported during runtime. If you need to replace all variables decorated by \@ObjectLink, you can replace them in the parent component. [Incorrect Usage] @@ -341,148 +344,156 @@ For a class that extends **Set**, the value changes of the **Set** instance can ## Use Scenarios - -### Nested Object - -> **NOTE** -> -> **NextID** is used to generate a unique, persistent key for each array item during [ForEach rendering](./arkts-rendering-control-foreach.md) to identify the corresponding component. - +### Inheritance Object ```ts -// objectLinkNestedObjects.ets -let NextID: number = 1; - @Observed -class Bag { - public id: number; - public size: number; +class Animal { + name: string; + age: number; - constructor(size: number) { - this.id = NextID++; - this.size = size; + constructor(name: string, age: number) { + this.name = name; + this.age = age; } } @Observed -class User { - public bag: Bag; +class Dog extends Animal { + kinds: string; - constructor(bag: Bag) { - this.bag = bag; + constructor(name: string, age: number, kinds: string) { + super(name, age); + this.kinds = kinds; } } -@Observed -class Book { - public bookName: BookName; +@Entry +@Component +struct Index { + @State dog: Dog = new Dog('Molly', 2, 'Husky'); - constructor(bookName: BookName) { - this.bookName = bookName; + @Styles + pressedStyles() { + .backgroundColor('#ffd5d5d5') } -} -@Observed -class BookName extends Bag { - public nameSize: number; - - constructor(nameSize: number) { - // Invoke the parent class method to process nameSize. - super(nameSize); - this.nameSize = nameSize; + @Styles + normalStyles() { + .backgroundColor('#ffffff') } -} - -@Component -struct Son { - label: string = 'Son'; - @ObjectLink bag: Bag; build() { Column() { - Text(`Son [${this.label}] this.bag.size = ${this.bag.size}`) - .fontColor('#ffffffff') - .backgroundColor('#ff3d9dba') + Text(`${this.dog.name}`) + .width(320) + .margin(10) + .fontSize(30) + .textAlign(TextAlign.Center) + .stateStyles({ + pressed: this.pressedStyles, + normal: this.normalStyles + }) + .onClick(() => { + this.dog.name = 'DouDou'; + }) + + Text(`${this.dog.age}`) .width(320) - .height(50) - .borderRadius(25) .margin(10) + .fontSize(30) .textAlign(TextAlign.Center) - Button(`Son: this.bag.size add 1`) + .stateStyles({ + pressed: this.pressedStyles, + normal: this.normalStyles + }) + .onClick(() => { + this.dog.age = 3; + }) + + Text(`${this.dog.kinds}`) .width(320) - .backgroundColor('#ff17a98d') .margin(10) + .fontSize(30) + .textAlign(TextAlign.Center) + .stateStyles({ + pressed: this.pressedStyles, + normal: this.normalStyles + }) .onClick(() => { - this.bag.size += 1; + this.dog.kinds = 'Samoyed'; }) } } } +``` -@Component -struct Father { - label: string = 'Father'; - @ObjectLink bookName: BookName; +![Observed_ObjectLink_inheritance_object](figures/Observed_ObjectLink_inheritance_object.gif) - build() { - Row() { - Column() { - Text(`Father [${this.label}] this.bookName.size = ${this.bookName.size}`) - .fontColor('#ffffffff') - .backgroundColor('#ff3d9dba') - .width(320) - .height(50) - .borderRadius(25) - .margin(10) - .textAlign(TextAlign.Center) - Button(`Father: this.bookName.size add 1`) - .width(320) - .backgroundColor('#ff17a98d') - .margin(10) - .onClick(() => { - this.bookName.size += 1; - console.log('this.bookName.size:' + this.bookName.size); - }) - } - .width(320) - } +In the preceding example, some properties (**name** and **age**) in the **Dog** class are inherited from the **Animal** class. You can directly change **name** and **age** in the **dog** variable decorated by \@State to trigger UI re-rendering. + +### Nested Object + +```ts +@Observed +class Book { + name: string; + + constructor(name: string) { + this.name = name; + } +} + +@Observed +class Bag { + book: Book; + + constructor(book: Book) { + this.book = book; } } -@Entry @Component -struct GrandFather { - @State user: User = new User(new Bag(0)); - @State child: Book = new Book(new BookName(0)); +struct BookCard { + @ObjectLink book: Book; build() { Column() { - Son({ label: 'Son #1', bag: this.user.bag }) - .width(320) - Father({ label: 'Father #3', bookName: this.child.bookName }) + Text(`BookCard: ${this.book.name}`) // The name change can be observed. .width(320) - Button(`GrandFather: this.child.bookName.size add 10`) + .margin(10) + .textAlign(TextAlign.Center) + + Button('change book.name') .width(320) - .backgroundColor('#ff17a98d') .margin(10) .onClick(() => { - this.child.bookName.size += 10; - console.log('this.child.bookName.size:' + this.child.bookName.size); + this.book.name = 'C++'; }) - Button(`GrandFather: this.user.bag = new Bag(10)`) + } + } +} + +@Entry +@Component +struct Index { + @State bag: Bag = new Bag(new Book('JS')); + + build() { + Column() { + Text(`Index: ${this.bag.book.name}`) // The name change cannot be observed. .width(320) - .backgroundColor('#ff17a98d') .margin(10) - .onClick(() => { - this.user.bag = new Bag(10); - }) - Button(`GrandFather: this.user = new User(new Bag(20))`) + .textAlign(TextAlign.Center) + + Button('change bag.book.name') .width(320) - .backgroundColor('#ff17a98d') .margin(10) .onClick(() => { - this.user = new User(new Bag(20)); + this.bag.book.name = 'TS'; }) + + BookCard({ book: this.bag.book }) } } } @@ -490,29 +501,15 @@ struct GrandFather { ![Observed_ObjectLink_nested_object](figures/Observed_ObjectLink_nested_object.gif) -The @Observed decorated **BookName** class can observe changes in the properties inherited from the base class. - - -Event handles in **GrandFather**: - - -- **this.user.bag = new Bag(10)** and **this.user = new User(new Bag(20))**: Change to the \@State decorated variable **user** and its properties. - -- **this.child.bookName.size += ...**: Change at the second layer. Though \@State cannot observe changes at the second layer, the change of a property of \@Observed decorated **Bag**, which is property **size** in this example, can be observed by \@ObjectLink. - - -Event handles in **Father**: - - -- **this.bookName.size += 1**: A change to the \@ObjectLink decorated variable **size** causes the **Text** component to be updated. Unlike \@Prop, \@ObjectLink does not have a copy of its source. Instead, \@ObjectLink creates a reference to its source. - -- The \@ObjectLink decorated variable is read-only. Assigning **this.bookName = new bookName(...)** is not allowed. Once value assignment occurs, the reference to the data source is reset and the synchronization is interrupted. - +In the preceding example, the **Text** component in the **Index** component is not re-rendered because the change belongs to the second layer and \@State cannot observe the change at the second layer. However, **Book** is decorated by \@Observed, and the **name** property of **Book** can be observed by \@ObjectLink. Therefore, no matter which button is clicked, the **Text** component in the **BookCard** component is re-rendered. ### Object Array An object array is a frequently used data structure. The following example shows the usage of array objects. +> **NOTE** +> +> **NextID** is used to generate a unique, persistent key for each array item during [ForEach rendering](./arkts-rendering-control-foreach.md) to identify the corresponding component. ```ts let NextID: number = 1; @@ -624,9 +621,6 @@ struct Parent { ```ts @Observed class ObservedArray extends Array { - constructor(args: T[]) { - super(...args); - } } ``` @@ -637,9 +631,6 @@ The following example shows how to use \@Observed to observe the changes of a tw ```ts @Observed class ObservedArray extends Array { - constructor(args: T[]) { - super(...args); - } } @Component @@ -660,7 +651,7 @@ struct Item { @Entry @Component struct IndexPage { - @State arr: Array> = [new ObservedArray(['apple']), new ObservedArray(['banana']), new ObservedArray(['orange'])]; + @State arr: Array> = [new ObservedArray('apple'), new ObservedArray('banana'), new ObservedArray('orange')]; build() { Column() { @@ -679,7 +670,71 @@ struct IndexPage { Button('push array item') .margin(10) .onClick(() => { - this.arr.push(new ObservedArray(['pear'])); + this.arr.push(new ObservedArray('pear')); + }) + + Button('change two-dimensional array first item') + .margin(10) + .onClick(() => { + this.arr[0][0] = 'APPLE'; + }) + + Button('change array first item') + .margin(10) + .onClick(() => { + this.arr[0] = new ObservedArray('watermelon'); + }) + } + } +} +``` + +Since API version 18, \@ObjectLink can also be initialized by the return value of [makeV1Observed](../reference/apis-arkui/js-apis-StateManagement.md#makev1observed18). Therefore, if you do not want to declare the class that inherits from array, you can use **makeV1Observed** to achieve the same effect. + +A complete example is as follows: + +```ts +import { UIUtils } from '@kit.ArkUI'; + +@Component +struct Item { + @ObjectLink itemArr: Array; + + build() { + Row() { + ForEach(this.itemArr, (item: string, index: number) => { + Text(`${index}: ${item}`) + .width(100) + .height(100) + }, (item: string) => item) + } + } +} + +@Entry +@Component +struct IndexPage { + @State arr: Array> = + [UIUtils.makeV1Observed(['apple']), UIUtils.makeV1Observed(['banana']), UIUtils.makeV1Observed(['orange'])]; + + build() { + Column() { + ForEach(this.arr, (itemArr: Array) => { + Item({ itemArr: itemArr }) + }) + + Divider() + + Button('push two-dimensional array item') + .margin(10) + .onClick(() => { + this.arr[0].push('strawberry'); + }) + + Button('push array item') + .margin(10) + .onClick(() => { + this.arr.push(UIUtils.makeV1Observed(['pear'])); }) Button('change two-dimensional array first item') @@ -691,7 +746,7 @@ struct IndexPage { Button('change array first item') .margin(10) .onClick(() => { - this.arr[0] = new ObservedArray(['watermelon']); + this.arr[0] = UIUtils.makeV1Observed(['watermelon']); }) } } @@ -1958,7 +2013,7 @@ struct Child { } ``` -The data source update of \@ObjectLink depends on its parent component. When the data source of the parent component changes trigger a re-rendering on the parent component, the data source of the child component \@ObjectLink is reset. This process does not occur immediately after the data source of the parent component changes. Instead, it occurs when the parent component is re-rendered. In the preceding example, **Parent** contains **Child** and passes the arrow function to **Child**. When the child component is clicked, the log printing sequence is from 1 to 5. When the log is printed to log 4, the click event process ends. In this case, only **Child** is marked as the node that needs to be updated by the parent component, therefore, the value of **this.per.name** in log 4 is still **Bob**. The data source of **Child** is updated only when the parent component is re-rendered. +The data source update of \@ObjectLink depends on its parent component. When the data source changes of the parent component trigger a re-rendering on the parent component, the data source of the child component \@ObjectLink is reset. This process does not occur immediately after the data source of the parent component changes. Instead, it occurs when the parent component is re-rendered. In the preceding example, **Parent** contains **Child** and passes the arrow function to **Child**. When the child component is clicked, the log printing sequence is from 1 to 5. When the log is printed to log 4, the click event process ends. In this case, only **Child** is marked as the node that needs to be updated by the parent component, therefore, the value of **this.per.name** in log 4 is still **Bob**. The data source of **Child** is updated only when the parent component is re-rendered. When the \@Watch function of **@ObjectLink @Watch('onChange02') per: Person** is executed, the data source of \@ObjectLink has been updated by the parent component. In this case, the value printed in log 5 is **Jack**. @@ -1971,7 +2026,7 @@ The meaning of the log is as follows: - Log 4: After **clickEvent** in the **onClickType** method is executed, **Child** is marked as the node that needs to be updated by the parent component, and the latest value is not updated to **Child @ObjectLink @Watch('onChange02') per: Person**. Therefore, the value of **this.per.name** in log 4 is still **Bob**. -- Log 5: The next VSYNC triggers **Child** re-rendering. **@ObjectLink @Watch('onChange02') per: Person** is re-rendered and its @Watch method is triggered. In this case, the new value of the **@ObjectLink @Watch('onChange02') per: Person** is **Jack**. +- Log 5: The next VSync triggers **Child** re-rendering. **@ObjectLink @Watch('onChange02') per: Person** is re-rendered and its @Watch method is triggered. In this case, the new value of the **@ObjectLink @Watch('onChange02') per: Person** is **Jack**. The parent-child synchronization principle of \@Prop is the same as that of \@ObjectLink. @@ -1991,7 +2046,7 @@ The **Text** component in **Parent** is not re-rendered because **this.info.pers ### Using the a.b(this.object) Format Fails to Trigger UI Re-render -In the **build** method, when the variable decorated by @Observed and @ObjectLink is of the object type and is called using the **a.b(this.object)** format, the native object of **this.object** is passed in the b method. If the property of **this.object** is changed, the UI cannot be re-rendered. In the following example, the UI re-render is not triggered when **this.weather.temperature** in the component is changed by using a static method or using **this** to call the internal method of the component. +In the **build** method, when the variable decorated by @Observed and @ObjectLink is of the object type and is called using the **a.b(this.object)** format, the original object of **this.object** is passed in the b method. If the property of **this.object** is changed, the UI cannot be re-rendered. In the following example, the UI re-render is not triggered when **this.weather.temperature** in the component is changed by using a static method or using **this** to call the internal method of the component. [Incorrect Usage] @@ -2132,3 +2187,5 @@ struct Child { } } ``` + + \ No newline at end of file diff --git a/en/application-dev/quick-start/arkts-page-custom-components-lifecycle.md b/en/application-dev/quick-start/arkts-page-custom-components-lifecycle.md index a675626bf931c924e14ddf52ff6c2fcc93325c1a..b3d7c0188221699d7ef3db765397aeba146c80da 100644 --- a/en/application-dev/quick-start/arkts-page-custom-components-lifecycle.md +++ b/en/application-dev/quick-start/arkts-page-custom-components-lifecycle.md @@ -84,12 +84,13 @@ import { router } from '@kit.ArkUI'; @Component struct MyComponent { @State showChild: boolean = true; - @State btnColor:string = "#FF007DFF"; + @State btnColor: string = "#FF007DFF"; // Only components decorated by @Entry can call the lifecycle callbacks of a page. onPageShow() { console.info('Index onPageShow'); } + // Only components decorated by @Entry can call the lifecycle callbacks of a page. onPageHide() { console.info('Index onPageHide'); @@ -98,8 +99,8 @@ struct MyComponent { // Only components decorated by @Entry can call the lifecycle callbacks of a page. onBackPress() { console.info('Index onBackPress'); - this.btnColor ="#FFEE0606"; - return true // The value true means that the page executes its own return logic instead of the , and false (default) means that the default return logic is used. + this.btnColor = "#FFEE0606"; + return true // The value true means that the page executes its own return logic, and false means that the default return logic is used. } // Component lifecycle @@ -123,17 +124,17 @@ struct MyComponent { if (this.showChild) { Child() } - // When this.showChild is false, delete the Child child component and invoke Child aboutToDisappear. Button('delete Child') .margin(20) .backgroundColor(this.btnColor) .onClick(() => { + // When this.showChild is false, delete the Child child component and invoke Child aboutToDisappear. this.showChild = false; }) - // Push to the page and execute onPageHide. + // Push to Page and execute onPageHide. Button('push to next page') .onClick(() => { - router.pushUrl({ url: 'pages/page' }); + router.pushUrl({ url: 'pages/Page' }); }) } } @@ -168,26 +169,30 @@ struct Child { } ``` ```ts -// page.ets +// Page.ets @Entry @Component -struct page { +struct Page { @State textColor: Color = Color.Black; @State num: number = 0; + // Only components decorated by @Entry can call the lifecycle callbacks of a page. onPageShow() { this.num = 5; } + // Only components decorated by @Entry can call the lifecycle callbacks of a page. onPageHide() { - console.log("page onPageHide"); + console.log("Page onPageHide"); } + // Only components decorated by @Entry can call the lifecycle callbacks of a page. onBackPress() { // If the value is not set, false is used. this.textColor = Color.Grey; this.num = 0; } + // Component lifecycle aboutToAppear() { this.textColor = Color.Blue; } @@ -211,7 +216,8 @@ struct page { In the preceding example, the **Index** page contains two custom components. One is **MyComponent** decorated with \@Entry, which is also the entry component (root node) of the page. The other is **Child**, which is a child component of **MyComponent**. Only components decorated by \@Entry can call the page lifecycle callbacks. Therefore, the lifecycle callbacks of the **Index** page – **onPageShow**, **onPageHide**, and **onBackPress**, are declared in **MyComponent**. In **MyComponent** and its child components, component lifecycle callbacks – **aboutToAppear**, **onDidBuild**, and **aboutToDisappear** – are also declared. -- The initialization process of application cold start is as follows: **MyComponent aboutToAppear** -> **MyComponent build** -> **MyComponent onDidBuild** -> **Child aboutToAppear** -> **Child build** -> **Child onDidBuild** -> **Index onPageShow**, +- The initialization process of application cold start is as follows: **MyComponent aboutToAppear** -> **MyComponent build** -> **MyComponent onDidBuild** -> **Child aboutToAppear** -> **Child build** -> **Child onDidBuild** -> **Index onPageShow** + - When **delete Child** is clicked, the value of **this.showChild** linked to **if** changes to **false**. As a result, the **Child** component is deleted, and the **Child aboutToDisappear** callback is invoked. @@ -224,7 +230,7 @@ In the preceding example, the **Index** page contains two custom components. One - When the application is minimized or switched to the background, the **Index onPageHide** callback is invoked. As the current **Index** page is not destroyed, **aboutToDisappear** of the component is not executed. When the application returns to the foreground, the **Index onPageShow** callback is invoked. -- When the application exits, the following callbacks are executed in order: Index onPageHide -> MyComponent aboutToDisappear -> Child aboutToDisappear. +- When the application exits, the following callbacks are executed in order: **Index onPageHide** -> **MyComponent aboutToDisappear** -> **Child aboutToDisappear**. ## Custom Component's Listening for Page Changes diff --git a/en/application-dev/quick-start/arkts-prop.md b/en/application-dev/quick-start/arkts-prop.md index 7c8915801519eb98dc9ee40dfa69dc3806a448cc..4421489ecdda60946fd1a3c02af17eb52f64a646 100644 --- a/en/application-dev/quick-start/arkts-prop.md +++ b/en/application-dev/quick-start/arkts-prop.md @@ -19,9 +19,7 @@ For the \@Prop decorated variable of a child component, the change synchronizati - Whenever the data source changes, the \@Prop decorated variable gets updated, and any locally made changes are overwritten. In other words, the change is synchronized from the parent component to the (owning) child component, but not the other way around. - - -## Restrictions +## Constraints - When decorating variables, \@Prop makes a deep copy, during which all types, except primitive types, Map, Set, Date, and Array, will be lost. For example, for complex types provided by N-API, such as [PixelMap](../reference/apis-image-kit/js-apis-image.md#pixelmap7), because they are partially implemented in the native code, complete data cannot be obtained through a deep copy in ArkTS. @@ -32,7 +30,7 @@ For the \@Prop decorated variable of a child component, the change synchronizati | ----------- | ---------------------------------------- | | Decorator parameters | None. | | Synchronization type | One-way: from the data source provided by the parent component to the \@Prop decorated variable. For details about the scenarios of nested types, see [Observed Changes](#observed-changes).| -| Allowed variable types | Object, class, string, number, Boolean, enum, and array of these types.
**undefined** or **null** (**any** is not supported).
Date type.
(Applicable to API version 11 or later) Map and Set types.
The union types defined by the ArkUI framework, including Length, ResourceStr, and ResourceColor, are supported.
The type must be specified.
The type must be the same as that of the [data source](arkts-state-management-overview.md#basic-concepts). There are three cases:
- Synchronizing the \@Prop decorated variable from a variable decorated by \@State or other decorators. Example: [Simple Type @Prop Synced from @State in Parent Component](#simple-type-prop-synced-from-state-in-parent-component).
- Synchronizing the \@Prop decorated variable from the item of an array decorated by an \@State or other decorators. Example: [Simple Type @Prop Synced from @State Array Item in Parent Component](#simple-type-prop-synced-from-state-array-item-in-parent-component).
- Synchronizing the \@Prop decorated variable from a state property of the Object or class type in the parent component. Example: [Class Object Type @Prop Synced from @State Class Object Property in Parent Component](#class-object-type-prop-synced-from-state-class-object-property-in-parent-component).
For details about the scenarios of supported types, see [Observed Changes](#observed-changes).
(Applicable to API version 11 or later) Union type of the preceding types, for example, **string \| number**, **string \| undefined** or **ClassA \| null**. For details, see [Union Type @Prop](#union-type-prop).
**NOTE**
When **undefined** or **null** is used, you are advised to explicitly specify the type to pass the TypeScript type check. For example, **@Prop a: string \| undefined = undefined** is recommended; **@Prop a: string = undefined** is not recommended.| +| Allowed variable types | Object, class, string, number, Boolean, enum, and array of these types.
**undefined** or **null** (**any** is not supported).
Date type.
(Applicable to API version 11 or later) Map and Set types.
The union types defined by the ArkUI framework, including Length, ResourceStr, and ResourceColor, are supported.
The type must be specified.
The type must be the same as that of the [data source](arkts-state-management-overview.md#basic-concepts). There are three cases:
- Synchronizing the \@Prop decorated variable from a variable decorated by \@State or other decorators. Example: [Simple Type @Prop Synced from @State in Parent Component](#simple-type-prop-synced-from-state-in-parent-component).
- Synchronizing the \@Prop decorated variable from the item of an array decorated by an \@State or other decorators. Example: [Simple Type @Prop Synced from @State Array Item in Parent Component](#simple-type-prop-synced-from-state-array-item-in-parent-component).
- Synchronizing the \@Prop decorated variable from a state property of the Object or class type in the parent component. Example: [Class Object Type @Prop Synced from @State Class Object Property in Parent Component](#class-object-type-prop-synced-from-state-class-object-property-in-parent-component).
For details about the scenarios of supported types, see [Observed Changes](#observed-changes).
(Applicable to API version 11 or later) Union type of the preceding types, for example, **string \| number**, **string \| undefined**, or **ClassA \| null**. For details, see [Union Type @Prop](#union-type-prop).
**NOTE**
When **undefined** or **null** is used, you are advised to explicitly specify the type to pass the TypeScript type check. For example, **@Prop a: string \| undefined = undefined** is supported, but **@Prop a: string = undefined** is not.| | Number of nested layers | In component reuse scenarios, it is recommended that @Prop be nested with no more than five layers of data. If @Prop is nested with too many layers of data, garbage collection and increased memory usage caused by deep copy will arise, resulting in performance issues. To avoid such issues, use [\@ObjectLink](arkts-observed-and-objectlink.md) instead.| | Initial value for the decorated variable | Local initialization is allowed. If this decorator is used together with [\@Require](arkts-require.md) in API version 11, the parent component must construct input parameters.| @@ -45,8 +43,7 @@ For the \@Prop decorated variable of a child component, the change synchronizati | Child component initialization | \@Prop can be used for initialization of a regular variable or \@State, \@Link, \@Prop, or \@Provide decorated variable in the child component.| | Access| Private, accessible only within the component. | - - **Figure 1** Initialization rule +**Figure 1** Initialization rule ![en-us_image_0000001552972029](figures/en-us_image_0000001552972029.png) @@ -209,8 +206,6 @@ In this example, the \@Prop decorated **count** variable in the **CountDownCompo Updating **countDownStartValue** in the **ParentComponent** will update the value of the @Prop decorated **count**. - - ```ts @Component struct CountDownComponent { @@ -275,8 +270,6 @@ In the preceding example: The \@State decorated array an array item in the parent component can be used as data source to initialize and update a @Prop decorated variable. In the following example, the \@State decorated array **arr** in the parent component **Index** initializes the \@Prop decorated **value** variable in the child component **Child**. - - ```ts @Component struct Child { @@ -1016,7 +1009,7 @@ struct Parent { ### Using the a.b(this.object) Format Fails to Trigger UI Re-render -In the **build** method, when the variable decorated by @Prop is of the object type and is called using the **a.b(this.object)** format, the native object of **this.object** is passed in the b method. If the property of **this.object** is changed, the UI cannot be re-rendered. In the following example, when the static method **Score.changeScore1** or **this.changeScore2** is used to change **this.score.value** in the custom component **Child**, the UI is not re-rendered. +In the **build** method, when the variable decorated by @Prop is of the object type and is called using the **a.b(this.object)** format, the original object of **this.object** is passed in the b method. If the property of **this.object** is changed, the UI cannot be re-rendered. In the following example, when the static method **Score.changeScore1** or **this.changeScore2** is used to change **this.score.value** in the custom component **Child**, the UI is not re-rendered. [Incorrect Example] @@ -1137,3 +1130,4 @@ struct Child { } } ``` + diff --git a/en/application-dev/quick-start/arkts-provide-and-consume.md b/en/application-dev/quick-start/arkts-provide-and-consume.md index 596f29a7a4828f385d364321300b861b6616c24a..27dc73118f55d695c2ae123415429d97e9cd0fd9 100644 --- a/en/application-dev/quick-start/arkts-provide-and-consume.md +++ b/en/application-dev/quick-start/arkts-provide-and-consume.md @@ -47,16 +47,16 @@ The rules of \@State also apply to \@Provide. The difference is that \@Provide a | -------------- | ---------------------------------------- | | Decorator parameters | Alias: constant string, optional.
If the alias is specified, the variable is provided under the alias name only. If the alias is not specified, the variable is provided under the variable name.| | Synchronization type | Two-way:
from the \@Provide decorated variable to all \@Consume decorated variables; and the other way around. The two-way synchronization behaviour is the same as that of the combination of \@State and \@Link.| -| Allowed variable types | Object, class, string, number, Boolean, enum, and array of these types.
Date type.
(Applicable to API version 11 or later) Map and Set types.
The union types defined by the ArkUI framework, including Length, ResourceStr, and ResourceColor, are supported.
The type must be specified.
The type of the provided and the consumed variables must be the same.
For details about the scenarios of supported types, see [Observed Changes](#observed-changes).
**any** is not supported.
(Applicable to API version 11 and later versions) Union type of the preceding types, for example, **string \| number**, **string \| undefined** or **ClassA \| null**. For details, see [Support for Union Type](#support-for-union-type).
**NOTE**
When **undefined** or **null** is used, you are advised to explicitly specify the type to pass the TypeScript type check. For example, **@Provide a: string \| undefined = undefined** is recommended; **@Provide a: string = undefined** is not recommended. | -| Initial value for the decorated variable | Mandatory. | -| Support for the **allowOverride** parameter | Yes. After **allowOverride** is declared, both aliases and attribute names can be overridden. For details, see [Support for the allowOverride Parameter](#support-for-the-allowoverride-parameter).| +| Allowed variable types | Object, class, string, number, Boolean, enum, and array of these types.
Date type.
(Applicable to API version 11 or later) Map and Set types.
The union types defined by the ArkUI framework, including Length, ResourceStr, and ResourceColor, are supported.
The type must be specified.
The type of the provided and the consumed variables must be the same.
For details about the scenarios of supported types, see [Observed Changes](#observed-changes).
**any** is not supported.
(Applicable to API version 11 and later versions) Union type of the preceding types, for example, **string \| number**, **string \| undefined**, or **ClassA \| null**. For details, see [Support for Union Type](#support-for-union-type).
**NOTE**
When **undefined** or **null** is used, you are advised to explicitly specify the type to pass the TypeScript type check. For example, **@Provide a: string \| undefined = undefined** is recommended; **@Provide a: string = undefined** is not recommended. | +| Initial value for the decorated variable | Mandatory. | +| Support for the **allowOverride** parameter | Yes. After **allowOverride** is declared, both aliases and attribute names can be overridden. For details, see [Support for the allowOverride Parameter](#support-for-the-allowoverride-parameter). | | \@Consume Decorator| Description | | -------------- | ---------------------------------------- | | Decorator parameters | Alias: constant string, optional.
If the alias is specified, the alias name is used for matching with the \@Provide decorated variable. Otherwise, the variable name is used.| | Synchronization type | Two-way: from the \@Provide decorated variable to all \@Consume decorated variables; and the other way around. The two-way synchronization behaviour is the same as that of the combination of \@State and \@Link.| -| Allowed variable types | Object, class, string, number, Boolean, enum, and array of these types.
Date type.
The union types defined by the ArkUI framework, including Length, ResourceStr, and ResourceColor, are supported. The type must be specified.
The type of the provided and the consumed variables must be the same.
An \@Consume decorated variable must have a matching \@Provide decorated variable with the corresponding attribute and alias on its parent or ancestor component.
For details about the scenarios of supported types, see [Observed Changes](#observed-changes).
**any** is not supported.
(Applicable to API version 11 and later versions) Union type of the preceding types, for example, **string \| number**, **string \| undefined**, or **ClassA \| null**. For details, see [Support for Union Type](#support-for-union-type).
**NOTE**
When **undefined** or **null** is used, you are advised to explicitly specify the type to pass the TypeScript type check. For example, **@Consume a: string \| undefined**. | -| Initial value for the decorated variable | Initialization of the decorated variables is forbidden. | +| Allowed variable types | Object, class, string, number, Boolean, enum, and array of these types.
Date type.
The union types defined by the ArkUI framework, including Length, ResourceStr, and ResourceColor, are supported. The type must be specified.
The type of the provided and the consumed variables must be the same.
An \@Consume decorated variable must have a matching \@Provide decorated variable with the corresponding attribute and alias on its parent or ancestor component.
For details about the scenarios of supported types, see [Observed Changes](#observed-changes).
**any** is not supported.
(Applicable to API version 11 and later versions) Union type of the preceding types, for example, **string \| number**, **string \| undefined**, or **ClassA \| null**. For details, see [Support for Union Type](#support-for-union-type).
**NOTE**
When **undefined** or **null** is used, you are advised to explicitly specify the type to pass the TypeScript type check. For example, **@Consume a: string \| undefined**. | +| Initial value for the decorated variable | Initialization of the decorated variables is forbidden. | ## Variable Transfer/Access Rules @@ -181,152 +181,152 @@ struct Parent { ## Constraints -1. The **key** parameter of \@Provider and \@Consumer must be of the string type. Otherwise, an error is reported during compilation. +1. The **key** parameter of \@Provide and \@Consume must be of the string type. Otherwise, an error is reported during compilation. -```ts -// Incorrect format. An error is reported during compilation. -let change: number = 10; -@Provide(change) message: string = 'Hello'; + ```ts + // Incorrect format. An error is reported during compilation. + let change: number = 10; + @Provide(change) message: string = 'Hello'; -// Correct format. -let change: string = 'change'; -@Provide(change) message: string = 'Hello'; -``` + // Correct format. + let change: string = 'change'; + @Provide(change) message: string = 'Hello'; + ``` 2. Variables decorated by \@Consume cannot be initialized locally or using constructor parameters. Otherwise, an error is reported during compilation. \@Consume can be initialized only by matching the corresponding \@Provide variable based on the key. -[Negative example] + [Negative example] -```ts -@Component -struct Child { - @Consume msg: string; - // Incorrect format. Local initialization is not allowed. - @Consume msg1: string = 'Hello'; + ```ts + @Component + struct Child { + @Consume msg: string; + // Incorrect format. Local initialization is not allowed. + @Consume msg1: string = 'Hello'; - build() { - Text(this.msg) + build() { + Text(this.msg) + } } -} -@Entry -@Component -struct Parent { - @Provide message: string = 'Hello'; + @Entry + @Component + struct Parent { + @Provide message: string = 'Hello'; - build() { - Column() { - // Incorrect format. External initialization is not allowed. - Child({msg: 'Hello'}) + build() { + Column() { + // Incorrect format. External initialization is not allowed. + Child({msg: 'Hello'}) + } } } -} -``` + ``` -[Positive example] + [Positive example] -```ts -@Component -struct Child { - @Consume num: number; + ```ts + @Component + struct Child { + @Consume num: number; - build() { - Column() { - Text(`Value of num: ${this.num}`) + build() { + Column() { + Text(`Value of num: ${this.num}`) + } } } -} -@Entry -@Component -struct Parent { - @Provide num: number = 10; + @Entry + @Component + struct Parent { + @Provide num: number = 10; - build() { - Column() { - Text(`Value of num: ${this.num}`) - Child() + build() { + Column() { + Text(`Value of num: ${this.num}`) + Child() + } } } -} -``` + ``` 3. \@When the **key** of \@Provide is defined repeatedly, the framework throws a runtime error to remind you. If you need to define the **key** repeatedly, use [allowoverride](#support-for-the-allowoverride-parameter). -```ts -// Incorrect format. "a" is defined repeatedly. -@Provide('a') count: number = 10; -@Provide('a') num: number = 10; + ```ts + // Incorrect format. "a" is defined repeatedly. + @Provide('a') count: number = 10; + @Provide('a') num: number = 10; -// Correct format. -@Provide('a') count: number = 10; -@Provide('b') num: number = 10; -``` + // Correct format. + @Provide('a') count: number = 10; + @Provide('b') num: number = 10; + ``` 4. If you do not define the \@Provide variable of the corresponding key when initializing the \@Consume variable, the framework throws a runtime error, indicating that the \@Consume variable fails to be initialized because the \@Provide variable of the corresponding key cannot be found. -[Negative example] + [Negative example] -```ts -@Component -struct Child { - @Consume num: number; + ```ts + @Component + struct Child { + @Consume num: number; - build() { - Column() { - Text(`Value of num: ${this.num}`) + build() { + Column() { + Text(`Value of num: ${this.num}`) + } } } -} -@Entry -@Component -struct Parent { - // Incorrect format. @Provide is missing. - num: number = 10; + @Entry + @Component + struct Parent { + // Incorrect format. @Provide is missing. + num: number = 10; - build() { - Column() { - Text(`Value of num: ${this.num}`) - Child() + build() { + Column() { + Text(`Value of num: ${this.num}`) + Child() + } } } -} -``` + ``` -[Positive example] + [Positive example] -```ts -@Component -struct Child { - @Consume num: number; + ```ts + @Component + struct Child { + @Consume num: number; - build() { - Column() { - Text(`Value of num: ${this.num}`) + build() { + Column() { + Text(`Value of num: ${this.num}`) + } } } -} -@Entry -@Component -struct Parent { - // Correct format. - @Provide num: number = 10; + @Entry + @Component + struct Parent { + // Correct format. + @Provide num: number = 10; - build() { - Column() { - Text(`Value of num: ${this.num}`) - Child() + build() { + Column() { + Text(`Value of num: ${this.num}`) + Child() + } } } -} -``` + ``` 5. \@Provide and \@Consume cannot decorate variables of the function type. Otherwise, the framework throws a runtime error. -## Application Scenarios +## Use Scenarios The following example shows the two-way synchronization between \@Provide and \@Consume decorated variables. When you click the **ToDo** and **ToDoItem** buttons, the **count** changes in both components are synchronized in a two-way manner. @@ -746,7 +746,7 @@ struct CustomWidgetChild { ### Using the a.b(this.object) Format Fails to Trigger UI Re-render -In the **build** method, when the variable decorated by @Provide and @Consume is of the object type and is called using the **a.b(this.object)** format, the native object of **this.object** is passed in the b method. If the property of **this.object** is changed, the UI cannot be re-rendered. In the following example, the UI re-render is not triggered when **this.dog.age** and **this.dog.name** in the component is changed by using a static method or using **this** to call the internal method of the component. +In the **build** method, when the variable decorated by @Provide and @Consume is of the object type and is called using the **a.b(this.object)** format, the original object of **this.object** is passed in the b method. If the property of **this.object** is changed, the UI cannot be re-rendered. In the following example, the UI re-render is not triggered when **this.dog.age** and **this.dog.name** in the component is changed by using a static method or using **this** to call the internal method of the component. [Negative example] diff --git a/en/application-dev/quick-start/arkts-rendering-control-foreach.md b/en/application-dev/quick-start/arkts-rendering-control-foreach.md index 43f56c21cf2f6ac2670a9fd158d52f62bede747c..6226d5835f11100c1ed476bf75ddbfa32ca1f0a7 100644 --- a/en/application-dev/quick-start/arkts-rendering-control-foreach.md +++ b/en/application-dev/quick-start/arkts-rendering-control-foreach.md @@ -343,7 +343,7 @@ The following figure shows the initial screen (on the left) and the screen after In this example, the **ArticleCard** component functions as a child component of the **ArticleListView** component and receives an **Article** object through the @Prop decorator to render article widgets. -1. When the list scrolls to the bottom, if the distance of finger movement exceeds the threshold 80, the **loadMoreArticle()** function is triggered. This function adds a new data item to the tail of the **articleList** data source, increasing the length of the data source. +1. When the list scrolls to the bottom, if the distance of finger movement exceeds the threshold 80, the **loadMoreArticles()** function is triggered. This function adds a new data item to the tail of the **articleList** data source, increasing the length of the data source. 2. Because the data source is decorated by @State, the ArkUI framework can detect the change of the data source length and trigger **ForEach** for re-rendering. ### Properties of Data Source Array Items Changed @@ -457,10 +457,7 @@ The following figure shows the initial screen (on the left) and the screen after In this example, the **Article** class is decorated by the @Observed decorator. The parent component **ArticleListView** passes an **Article** object instance to the child component **ArticleCard**, and the child component uses the @ObjectLink decorator to receive the instance. 1. When the Like icon of Article 1 is clicked, the **handleLiked** function of the **ArticleCard** component is triggered. This function changes the values of the **isLiked** and **likesCount** properties of the **article** instance in the component pertaining to Article 1. -2. Because **article** in the child component **ArticleCard** uses the @ObjectLink decorator, the parent and child components share the same article data. As such, the values of **isLiked** and **likedCounts** of the first array item of **articleList** in the parent component are changed synchronously. -3. When the parent component detects property changes of the data source array items, **ForEach** is triggered for re-rendering. -4. Here, the **ForEach** key generation rule is the **id** property value of the array item. If **ForEach** traverses the new data source and finds no changes in the **id** values, no component is created. -5. When the **ArticleCard** component corresponding to the first array item is rendered, the obtained values of **isLiked** and **likesCount** are the new values. +2. The **article** instance is a state variable decorated by @ObjectLink. When its property value changes, the corresponding **ArticleCard** component is rendered. The changed values of **isLiked** and **likesCount** are read. ### Enabling Drag and Sort If **ForEach** is used in a list, and the **onMove** event is set, you can enable drag and sort for the list items. If an item changes the position after you drag and sort the data, the **onMove** event is triggered to report the original index and target index of the item. The data source needs to be modified in the **onMove** event based on the reported start index and target index. Before and after the data source is modified, the value of each item must remain unchanged to ensure that the drop animation can be executed properly. @@ -508,9 +505,10 @@ struct ForEachSort { - To ensure unique keys for array items of the Object type, you are advised to use the unique IDs of objects as keys. - Avoid including the data item **index** in the final key generation rule to prevent [unexpected rendering results](#rendering-result-not-as-expected) and [deteriorated rendering performance](#deteriorated-rendering-performance). If including **index** is required, for example, when the list needs to be rendered based on the index, prepare for the performance loss resulting from component creation by **ForEach** to account for data source changes. -- Data items of primitive data types do not have a unique ID. If you use the primitive data type itself as the key, you must ensure that the array items are not duplicate. In scenarios where the data source changes, you are advised to convert the array of a primitive data type into an array of the Object type with the **id** property, and then use the **id** property as the key generation rule. +- Data items of primitive data types do not have a unique ID. If you use the primitive data type itself as the key, you must ensure that the array items are not duplicate. In scenarios where the data source changes, you are advised to convert the array of a primitive data type into an array of the Object type with the **id** property, and then use the unique ID as the key. - For the preceding restriction rules, the **index** parameter is the final method for you to ensure the uniqueness of the keys. When modifying a data item, you need to use the index value to modify the data source because the **item** parameter in **itemGenerator** cannot be modified. In this way, the UI re-rendering is triggered. - Do not use **ForEach** together with [LazyForEach](./arkts-rendering-control-lazyforeach.md) in [List](../reference/apis-arkui/arkui-ts/ts-container-list.md), [Grid](../reference/apis-arkui/arkui-ts/ts-container-grid.md), [Swiper](../reference/apis-arkui/arkui-ts/ts-container-swiper.md), and [WaterFlow](../reference/apis-arkui/arkui-ts/ts-container-waterflow.md). +- If an array item is of the object data type, you are not advised to replace the old array item with an array item with the same content. If the array item is changed but the key remains unchanged, [data changes fail to trigger renderings](#data-changes-fail-to-trigger-renderings). ## Common Pitfalls @@ -640,3 +638,124 @@ ForEach(this.simpleList, (item: string) => { }, (item: string) => item) // Ensure that the key is unique. ``` The third parameter **KeyGenerator** is provided. In the preceding example, different keys are generated for different data items of the data source, and the same key is generated for the same data item each time. + +### Data Changes Fail to Trigger Renderings +When the **Like/UnLike first article** button is clicked, the like gesture is triggered and the number of likes changes in the first component. However, after the **Replace first article** button is clicked, the **Like/UnLike first article** button does not take effect. After the **articleList[0]** is replaced, the state variable **articleList** changes, triggering **ForEach** to re-render. However, the key generated by the new **articleList[0]** does not change, and **ForEach** does not synchronize the updated data to the child component. Therefore, the first component is still bound to the old **articleList[0]**. When the property of the new **articleList[0]** is changed, the first component cannot detect the change and fails to trigger a re-render. Touching the like icon can trigger rendering. This is because the property of the array item bound to the component is changed, the component detects the change and renders it again. +```ts +@Observed +class Article { + id: string; + title: string; + brief: string; + isLiked: boolean; + likesCount: number; + + constructor(id: string, title: string, brief: string, isLiked: boolean, likesCount: number) { + this.id = id; + this.title = title; + this.brief = brief; + this.isLiked = isLiked; + this.likesCount = likesCount; + } +} + +@Entry +@Component +struct ArticleListView { + @State articleList: Array
= [ + new Article('001','Article 0','Abstract', false, 100), + new Article('002','Article 1','Abstract', false, 100), + new Article('003','Article 2','Abstract', false, 100), + new Article('004','Article 4','Abstract', false, 100), + new Article('005','Article 5','Abstract', false, 100), + new Article('006','Article 6','Abstract', false, 100), + ]; + + build() { + Column() { + Button('Replace first article') + .onClick(() => { + this.articleList[0] = new Article ('001','Article 0','Abstract', false, 100); + }) + .width(300) + .margin(10) + + Button('Like/Unlike first article') + .onClick(() => { + this.articleList[0].isLiked = !this.articleList[0].isLiked; + this.articleList[0].likesCount = + this.articleList[0].isLiked ? this.articleList[0].likesCount + 1 : this.articleList[0].likesCount - 1; + }) + .width(300) + .margin(10) + + List() { + ForEach(this.articleList, (item: Article) => { + ListItem() { + ArticleCard({ + article: item + }) + .margin({ top: 20 }) + } + }, (item: Article) => item.id) + } + .padding(20) + .scrollBar(BarState.Off) + .backgroundColor(0xF1F3F5) + } + } +} + +@Component +struct ArticleCard { + @ObjectLink article: Article; + + handleLiked() { + this.article.isLiked = !this.article.isLiked; + this.article.likesCount = this.article.isLiked ? this.article.likesCount + 1 : this.article.likesCount - 1; + } + + build() { + Row() { + // 'app.media.icon' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed. + Image($r('app.media.icon')) + .width(80) + .height(80) + .margin({ right: 20 }) + + Column() { + Text(this.article.title) + .fontSize(20) + .margin({ bottom: 8 }) + Text(this.article.brief) + .fontSize(16) + .fontColor(Color.Gray) + .margin({ bottom: 8 }) + + Row() { + // 'app.media.iconLiked' and 'app.media.iconUnLiked' are only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed. + Image(this.article.isLiked ? $r('app.media.iconLiked') : $r('app.media.iconUnLiked')) + .width(24) + .height(24) + .margin({ right: 8 }) + Text(this.article.likesCount.toString()) + .fontSize(16) + } + .onClick(() => this.handleLiked()) + .justifyContent(FlexAlign.Center) + } + .alignItems(HorizontalAlign.Start) + .width('80%') + .height('100%') + } + .padding(20) + .borderRadius(12) + .backgroundColor('#FFECECEC') + .height(120) + .width('100%') + .justifyContent(FlexAlign.SpaceBetween) + } +} +``` +**Figure 12** Data changes fail to trigger renderings +![ForEach-StateVarNoRender](figures/ForEach-StateVarNoRender.PNG) diff --git a/en/application-dev/quick-start/arkts-rendering-control-ifelse.md b/en/application-dev/quick-start/arkts-rendering-control-ifelse.md index dfa5c0f04e1db28e9848be45236d81bf0c16a051..260bd058f21662b851325d0f20c900916ab5b79a 100644 --- a/en/application-dev/quick-start/arkts-rendering-control-ifelse.md +++ b/en/application-dev/quick-start/arkts-rendering-control-ifelse.md @@ -11,7 +11,7 @@ ArkTS provides conditional rendering. It supports the use of the **if**, **else* - The **if**, **else**, and **else if** statements are supported. -- The condition statements following the **if** or **else if** statement can use state variables or normal variables. (Value change of state variables can trigger UI rendering in real time, but value change of normal variables cannot.) +- The conditional statements following the **if** or **else if** statement can use state variables or normal variables. (Value change of state variables can trigger UI rendering in real time, but value change of normal variables cannot.) - Conditional statements can be used within a container component to build different child components. @@ -44,7 +44,7 @@ A condition can include Typescript expressions. As for any expression inside bui ```ts @Entry @Component -struct ViewA { +struct MyComponent { @State count: number = 0; build() { @@ -194,7 +194,7 @@ The nesting of **if** statements makes no difference to the rule about the paren ```ts @Entry @Component -struct CompA { +struct MyComponent { @State toggle: boolean = false; @State toggleColor: boolean = false; diff --git a/en/application-dev/quick-start/arkts-rendering-control-lazyforeach.md b/en/application-dev/quick-start/arkts-rendering-control-lazyforeach.md index 92b167e71acce9b0763e67f3c765fa54bfea0900..635cc2b026912b7e532faedabc575ae502e75655 100644 --- a/en/application-dev/quick-start/arkts-rendering-control-lazyforeach.md +++ b/en/application-dev/quick-start/arkts-rendering-control-lazyforeach.md @@ -7,6 +7,7 @@ For details about API parameters, see [LazyForEach](https://gitee.com/openharmon ## Constraints - **LazyForEach** must be used in a container component. Only the [List](../reference/apis-arkui/arkui-ts/ts-container-list.md), [Grid](../reference/apis-arkui/arkui-ts/ts-container-grid.md), [Swiper](../reference/apis-arkui/arkui-ts/ts-container-swiper.md), and [WaterFlow](../reference/apis-arkui/arkui-ts/ts-container-waterflow.md) components support lazy loading (the **cachedCount** property can be configured, that is, only the visible part and a small amount of data before and after the visible part are loaded for caching). For other components, all data is loaded at once. +- **LazyForEach** depends on the generated key to determine whether to re-render the child component. If the key does not change, **LazyForEach** cannot trigger a re-render for the corresponding child component. - Only one **LazyForEach** can be used in a container component. Take **List** as an example. Containing **ListItem**, **ForEach**, and **LazyForEach** together in this component, or containing multiple **LazyForEach** at the same time is not recommended. - In each iteration, only one child component must be created for **LazyForEach**. That is, the child component generation function of **LazyForEach** has only one root component. - The generated child components must be allowed in the parent container component of **LazyForEach**. @@ -34,7 +35,7 @@ After the key generation rules are determined, the **itemGenerator** function When used for initial render, **LazyForEach** generates a unique key for each array item of the data source based on the key generation rules, and creates a component. ```ts -/** For details about the BasicDataSource code of the string array, see the attachment at the end of this topic. **/ +/** For details about the BasicDataSource code of the string array, see the sample code at the end of this topic. **/ class MyDataSource extends BasicDataSource { private dataArray: string[] = []; @@ -93,7 +94,7 @@ The figure below shows the effect. When the keys generated for different data items are the same, the behavior of the framework is unpredictable. For example, in the following code, the keys of the data items rendered by **LazyForEach** are the same. During the swipe process, **LazyForEach** preloads child components for the current page. Because the new child component and the destroyed component have the same key, the framework may incorrectly obtain the cache. As a result, the child component rendering is abnormal. ```ts -/** For details about the BasicDataSource code of the string array, see the attachment at the end of this topic. **/ +/** For details about the BasicDataSource code of the string array, see the sample code at the end of this topic. **/ class MyDataSource extends BasicDataSource { private dataArray: string[] = []; @@ -152,7 +153,7 @@ When the **LazyForEach** data source is changed and a re-render is required, cal #### Adding Data ```ts -/** For details about the BasicDataSource code of the string array, see the attachment at the end of this topic. **/ +/** For details about the BasicDataSource code of the string array, see the sample code at the end of this topic. **/ class MyDataSource extends BasicDataSource { private dataArray: string[] = []; @@ -213,7 +214,7 @@ The figure below shows the effect. #### Deleting Data ```ts -/** For details about the BasicDataSource code of the string array, see the attachment at the end of this topic. **/ +/** For details about the BasicDataSource code of the string array, see the sample code at the end of this topic. **/ class MyDataSource extends BasicDataSource { private dataArray: string[] = []; @@ -282,7 +283,7 @@ The figure below shows the effect. #### Swapping Data ```ts -/** For details about the BasicDataSource code of the string array, see the attachment at the end of this topic. **/ +/** For details about the BasicDataSource code of the string array, see the sample code at the end of this topic. **/ class MyDataSource extends BasicDataSource { private dataArray: string[] = []; @@ -358,7 +359,7 @@ The figure below shows the effect. #### Changing a Data Item ```ts -/** For details about the BasicDataSource code of the string array, see the attachment at the end of this topic. **/ +/** For details about the BasicDataSource code of the string array, see the sample code at the end of this topic. **/ class MyDataSource extends BasicDataSource { private dataArray: string[] = []; @@ -424,7 +425,7 @@ The figure below shows the effect. #### Changing Multiple Data Items ```ts -/** For details about the BasicDataSource code of the string array, see the attachment at the end of this topic. **/ +/** For details about the BasicDataSource code of the string array, see the sample code at the end of this topic. **/ class MyDataSource extends BasicDataSource { private dataArray: string[] = []; @@ -495,7 +496,7 @@ The figure below shows the effect. #### Changing Data in Batches Precisely ```ts -/** For details about the BasicDataSource code of the string array, see the attachment at the end of this topic. **/ +/** For details about the BasicDataSource code of the string array, see the sample code at the end of this topic. **/ class MyDataSource extends BasicDataSource { private dataArray: string[] = []; @@ -578,7 +579,7 @@ The **onDatasetChange** API allows you to notify **LazyForEach** at a time to ad In the second example, values are directly changed in the array without using **splice()**. Result of **operations** is directly obtained by comparing the original array with the new array. ```ts -/** For details about the BasicDataSource code of the string array, see the attachment at the end of this topic. **/ +/** For details about the BasicDataSource code of the string array, see the sample code at the end of this topic. **/ class MyDataSource extends BasicDataSource { private dataArray: string[] = []; @@ -674,7 +675,7 @@ which is shown in the following example: When **LazyForEach** is used for UI re-renders, a child component needs to be destroyed and rebuilt when the data item changes. This may result in low re-render performance when the child component structure is complex. This is where @Observed and @ObjectLink come into picture. By providing in-depth observation, @Observed and @ObjectLink enable precise re-renders of only components that use the changed properties. You can select a re-render mode that better suits your needs. ```ts -/** For details about the BasicDataSource code of the StringData array, see the attachment at the end of this topic. **/ +/** For details about the BasicDataSource code of the StringData array, see the sample code at the end of this topic. **/ class MyDataSource extends BasicDataSource { private dataArray: StringData[] = []; @@ -753,7 +754,7 @@ State management V2 provides the @ObservedV2 and @Trace decorators to implement #### Observing Nested Class Property Changes ```ts -/** For details about the BasicDataSource code of the StringData array, see the attachment at the end of this topic. **/ +/** For details about the BasicDataSource code of the StringData array, see the sample code at the end of this topic. **/ class MyDataSource extends BasicDataSource { private dataArray: StringData[] = []; @@ -836,7 +837,7 @@ struct MyComponent { #### Observing Component Internal State ```ts -/** For details about the BasicDataSource code of the StringData array, see the attachment at the end of this topic. **/ +/** For details about the BasicDataSource code of the StringData array, see the sample code at the end of this topic. **/ class MyDataSource extends BasicDataSource { private dataArray: StringData[] = []; @@ -915,7 +916,7 @@ struct ChildComponent { #### Receiving External Input ```ts -/** For details about the BasicDataSource code of the StringData array, see the attachment at the end of this topic. **/ +/** For details about the BasicDataSource code of the StringData array, see the sample code at the end of this topic. **/ class MyDataSource extends BasicDataSource { private dataArray: StringData[] = []; @@ -986,7 +987,7 @@ The @Param decorator enables the child component to receive external input param If **LazyForEach** is used in a list, and the **onMove** event is set, you can enable drag and sort for the list items. If an item changes the position after you drag and sort the data, the **onMove** event is triggered to report the original index and target index of the item. The data source needs to be modified in the **onMove** event based on the reported start index and target index. The **DataChangeListener** API does not need to be called to notify the data source change. ```ts -/** For details about the BasicDataSource code of the string array, see the attachment at the end of this topic. **/ +/** For details about the BasicDataSource code of the string array, see the sample code at the end of this topic. **/ class MyDataSource extends BasicDataSource { private dataArray: string[] = []; @@ -1054,7 +1055,7 @@ struct Parent { ### Unexpected Rendering Result ```ts -/** For details about the BasicDataSource code of the string array, see the attachment at the end of this topic. **/ +/** For details about the BasicDataSource code of the string array, see the sample code at the end of this topic. **/ class MyDataSource extends BasicDataSource { private dataArray: string[] = []; @@ -1118,7 +1119,7 @@ When child components are clicked to be deleted, there may be cases where the de The following shows the code snippet after optimization: ```ts -/** For details about the BasicDataSource code of the string array, see the attachment at the end of this topic. **/ +/** For details about the BasicDataSource code of the string array, see the sample code at the end of this topic. **/ class MyDataSource extends BasicDataSource { private dataArray: string[] = []; @@ -1188,7 +1189,7 @@ After a data item is deleted, the **reloadData** method is called to rebuild the ### Image Flickering During Re-renders ```ts -/** For details about the BasicDataSource code of the StringData array, see the attachment at the end of this topic. **/ +/** For details about the BasicDataSource code of the StringData array, see the sample code at the end of this topic. **/ class MyDataSource extends BasicDataSource { private dataArray: StringData[] = []; @@ -1265,7 +1266,7 @@ In the example, when a list item is clicked, only the **message** property of th The following shows the code snippet after optimization: ```ts -/** For details about the BasicDataSource code of the StringData array, see the attachment at the end of this topic. **/ +/** For details about the BasicDataSource code of the StringData array, see the sample code at the end of this topic. **/ class MyDataSource extends BasicDataSource { private dataArray: StringData[] = []; @@ -1302,6 +1303,7 @@ struct MyComponent { aboutToAppear() { for (let i = 0; i <= 20; i++) { + // 'app.media.img' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed. this.data.pushData(new StringData(`Hello ${i}`, $r('app.media.img'))); } } @@ -1344,7 +1346,7 @@ struct ChildComponent { ### UI Not Re-rendered When @ObjectLink Property Is Changed ```ts -/** For details about the BasicDataSource code of the StringData array, see the attachment at the end of this topic. **/ +/** For details about the BasicDataSource code of the StringData array, see the sample code at the end of this topic. **/ class MyDataSource extends BasicDataSource { private dataArray: StringData[] = []; @@ -1427,7 +1429,7 @@ The member variable decorated by @ObjectLink can observe only changes of its sub The following shows the code snippet after optimization: ```ts -/** For details about the BasicDataSource code of the StringData array, see the attachment at the end of this topic. **/ +/** For details about the BasicDataSource code of the StringData array, see the sample code at the end of this topic. **/ class MyDataSource extends BasicDataSource { private dataArray: StringData[] = []; @@ -1510,7 +1512,7 @@ struct ChildComponent { List has an **onScrollIndex** callback function. When **onDataReloaded** is called in **onScrollIndex**, there is a risk of screen flickering. ```ts -/** For details about the BasicDataSource code of the string array, see the attachment at the end of this topic. **/ +/** For details about the BasicDataSource code of the string array, see the sample code at the end of this topic. **/ class MyDataSource extends BasicDataSource { private dataArray: string[] = []; @@ -1582,7 +1584,7 @@ When **List** is scrolled to the bottom, screen flicks like the following. Replacing **onDataReloaded** by **onDatasetChange** cannot only fix this issue but also improves load performance. ```ts -/** For details about the BasicDataSource code of the string array, see the attachment at the end of this topic. **/ +/** For details about the BasicDataSource code of the string array, see the sample code at the end of this topic. **/ class MyDataSource extends BasicDataSource { private dataArray: string[] = []; @@ -1657,7 +1659,7 @@ Fixed result If @Reusable and @ComponentV2 are used together, the component rendering is abnormal. ```ts -/** For details about the BasicDataSource code of the StringData array, see the attachment at the end of this topic. **/ +/** For details about the BasicDataSource code of the StringData array, see the sample code at the end of this topic. **/ class MyDataSource extends BasicDataSource { private dataArray: StringData[] = []; @@ -1741,7 +1743,81 @@ The negative example shows that in @ComponentV2 decorated **MyComponent**, the * Change @ComponentV2 to @Component to rectify the rendering exception. After that, when the swipe event triggers the detach of a component node, the corresponding reusable component **ChildComponent** is added from the component tree to the reuse cache instead of being destroyed, the **aboutToRecycle** event is triggered, and log is recorded. When a new node needs to be displayed, the reusable component attaches to the node tree from the reuse cache, triggers **aboutToReuse** to update the component data, and output logs. -## Attachments +### Component Re-Rendering Failure + +You need to define a proper function for key generation and return a key associated with the target data. When the target data changes, **LazyForEach** re-renders the corresponding component only after identifying the key change. + +```ts +/** For details about the BasicDataSource code of the string array, see the sample code at the end of this topic. **/ + +class MyDataSource extends BasicDataSource { + private dataArray: string[] = []; + + public totalCount(): number { + return this.dataArray.length; + } + + public getData(index: number): string { + return this.dataArray[index]; + } + + public pushData(data: string): void { + this.dataArray.push(data); + this.notifyDataAdd(this.dataArray.length - 1); + } + + public updateAllData(): void { + this.dataArray = this.dataArray.map((item: string) => item + `!`); + this.notifyDataReload(); + } +} + +@Entry +@Component +struct MyComponent { + private data: MyDataSource = new MyDataSource(); + + aboutToAppear() { + for (let i = 0; i <= 20; i++) { + this.data.pushData(`Hello ${i}`); + } + } + + build() { + Column() { + Button(`update all`) + .onClick(() => { + this.data.updateAllData(); + }) + List({ space: 3 }) { + LazyForEach(this.data, (item: string) => { + ListItem() { + Text(item).fontSize(50) + } + }) + }.cachedCount(5) + } + } +} +``` + +Click **update all** but the components are not re-rendered. +![LazyForEach-Refresh-Not-Expected](./figures/LazyForEach-Refresh-Not-Expected.gif) + +**LazyForEach** depends on the generated key to determine whether to re-render the child component. If the key is not changed during data update, **LazyForEach** does not re-render the corresponding component. For example, if the key generation function is not defined, the key is related only to the component index and the key remains unchanged during data update. + +```ts +LazyForEach(this.data, (item: string) => { + ListItem() { + Text(item).fontSize(50) + } +}, (item: string) => item) // Define a function for key generation. +``` + +After the function is defined, click **update all** to re-render the components. +![LazyForEach-Refresh-Not-Expected-Repair](./figures/LazyForEach-Refresh-Not-Expected-Repair.gif) + +## BasicDataSource Sample Code ### BasicDataSource Code of the String Array diff --git a/en/application-dev/quick-start/arkts-reusable.md b/en/application-dev/quick-start/arkts-reusable.md index 7da911ccc37e686ea82a8f0c19772205ad419bfd..be208e6fbd08f16d80071ae773ec087c52ca2879 100644 --- a/en/application-dev/quick-start/arkts-reusable.md +++ b/en/application-dev/quick-start/arkts-reusable.md @@ -46,7 +46,7 @@ export struct Crash { @Component struct Index { @State message: string = 'Hello World'; - private uicontext = this.getUIContext() + private uicontext = this.getUIContext(); build() { RelativeContainer() { @@ -74,6 +74,7 @@ struct Index { ```ts import { ComponentContent } from "@kit.ArkUI"; + @Builder function buildCreativeLoadingDialog(closedClick: () => void) { Crash() @@ -102,7 +103,7 @@ export struct Crash { @Component struct Index { @State message: string = 'Hello World'; - private uicontext = this.getUIContext() + private uicontext = this.getUIContext(); build() { RelativeContainer() { @@ -159,7 +160,7 @@ struct Index { .fontSize(14) PlayButton02({ isPlaying02: $isPlaying02 }) } - Text(`==================`).fontSize(14); + Text(`------------------------`) // Initial state of the button: hidden if (this.isPlaying01) { @@ -167,7 +168,7 @@ struct Index { .fontSize(14) PlayButton02({ isPlaying02: $isPlaying01 }) } - Text(`==================`).fontSize(14); + Text(`------------------------`) // Parent-child nesting if (this.isPlaying) { @@ -175,7 +176,7 @@ struct Index { .fontSize(14) PlayButton({ buttonPlaying: $isPlaying }) } - Text(`==================`).fontSize(14); + Text(`------------------------`) // Parent-child nesting control Text(`Parent=child==is ${this.isPlaying ? '' : 'not'} playing`).fontSize(14) @@ -185,7 +186,7 @@ struct Index { this.isPlaying = !this.isPlaying; }) - Text(`==================`).fontSize(14); + Text(`------------------------`) // Hide the button control by default. Text(`Hiddenchild==is ${this.isPlaying01 ? '' : 'not'} playing`).fontSize(14) @@ -194,7 +195,7 @@ struct Index { .onClick(() => { this.isPlaying01 = !this.isPlaying01; }) - Text(`==================`).fontSize(14); + Text(`------------------------`) // Display the button control by default. Text(`shownchid==is ${this.isPlaying02 ? '' : 'not'} playing`).fontSize(14) @@ -281,6 +282,7 @@ export class Message { @Component struct Index { @State switch: boolean = true; + build() { Column() { Button('Hello') @@ -290,8 +292,8 @@ struct Index { this.switch = !this.switch; }) if (this.switch) { + // If only one component to be reused, you do not need to set reuseId. Child({ message: new Message('Child') }) - // If only one component to be reused, you do not need to set reuseId. .reuseId('Child') } } @@ -324,8 +326,7 @@ struct Child { ### Using List Scrolling with LazyForEach - In the sample code, the **CardView** custom component is marked as a reusable component, and the list is scrolled up and down to trigger **CardView** reuse. -- \@Reusable: The custom component to reuse is decorated by @Reusable. -- \@State: The variable **item** can be updated only when it is decorated by \@State. +- Only the \@State decorated variable **item** can be updated. ```ts class MyDataSource implements IDataSource { @@ -364,7 +365,7 @@ struct ReuseDemo { aboutToAppear() { for (let i = 1; i < 1000; i++) { - this.data.pushData(i+""); + this.data.pushData(i + ""); } } @@ -403,7 +404,7 @@ export struct CardView { } ``` -### The if Statement +### if Statement - In the sample code, the **OneMoment** custom component is marked as a reusable component, and the list is scrolled up and down to trigger **OneMoment** reuse. - You can use **reuseId** to assign reuse groups to reusable components. Components with the same **reuseId** will be reused in the same reuse group. If there is only one reusable component, you do not need to set **reuseId**. @@ -418,12 +419,12 @@ struct Index { aboutToAppear(): void { for (let i = 0; i < 20; i++) { let title = i + 1 + "test_if"; - this.dataSource.pushData(new FriendMoment(i.toString(), title, 'app.media.app_icon')) + this.dataSource.pushData(new FriendMoment(i.toString(), title, 'app.media.app_icon')); } for (let i = 0; i < 50; i++) { let title = i + 1 + "test_if"; - this.dataSource.pushData(new FriendMoment(i.toString(), title, '')) + this.dataSource.pushData(new FriendMoment(i.toString(), title, '')); } } @@ -433,7 +434,8 @@ struct Index { List({ space: 3 }) { LazyForEach(this.dataSource, (moment: FriendMoment) => { ListItem() { - OneMoment({ moment: moment })// Use reuseId to control component reuse. + // Use reuseId to control component reuse. + OneMoment({ moment: moment }) .reuseId((moment.image !== '') ? 'withImage' : 'noImage') } }, (moment: FriendMoment) => moment.id) @@ -473,10 +475,10 @@ export struct OneMoment { // if branch judgment if (this.moment.image !== '') { Flex({ wrap: FlexWrap.Wrap }) { - Image($r(this.moment.image)).height(50).width(50); - Image($r(this.moment.image)).height(50).width(50); - Image($r(this.moment.image)).height(50).width(50); - Image($r(this.moment.image)).height(50).width(50); + Image($r(this.moment.image)).height(50).width(50) + Image($r(this.moment.image)).height(50).width(50) + Image($r(this.moment.image)).height(50).width(50) + Image($r(this.moment.image)).height(50).width(50) } } } @@ -511,7 +513,7 @@ class BasicDataSource implements IDataSource { notifyDataAdd(index: number): void { this.listeners.forEach(listener => { listener.onDataAdd(index); - }) + }); } } @@ -598,7 +600,7 @@ struct Index { let obj = new ListItemObject(); obj.id = i; obj.uuid = Math.random().toString(); - obj.isExpand = false + obj.isExpand = false; this.dataSource.push(obj); } }).height(40) @@ -612,7 +614,7 @@ struct Index { }) } }, (item: ListItemObject) => { - return item.uuid.toString() + return item.uuid.toString(); }) }.cachedCount(0) @@ -739,7 +741,6 @@ struct MyComponent { } } -// The custom component is decorated by the @Reusable decorator. @Reusable @Component struct ReusableChildComponent { @@ -792,7 +793,7 @@ class WaterFlowDataSource implements IDataSource { notifyDataAdd(index: number): void { this.listeners.forEach(listener => { listener.onDataAdd(index); - }) + }); } // Obtain the total number of data records. @@ -1043,7 +1044,7 @@ class BasicDataSource implements IDataSource { notifyDataAdd(index: number): void { this.listeners.forEach(listener => { listener.onDataAdd(index); - }) + }); } } @@ -1101,7 +1102,7 @@ struct ListItemGroupAndReusable { ListItemGroup({ header: this.itemHead(index.toString()) }) { LazyForEach(item, (ii: string, index: number) => { ListItem() { - Inner({ str: ii }); + Inner({ str: ii }) } }) } @@ -1118,7 +1119,7 @@ struct ListItemGroupAndReusable { @Reusable @Component struct Inner { - @State str: string = '' + @State str: string = ''; aboutToReuse(param: ESObject) { this.str = param.str; @@ -1160,35 +1161,35 @@ class DataSrc1 implements IDataSource { notifyDataReload(): void { this.listeners.forEach(listener => { listener.onDataReloaded(); - }) + }); } // Notify LazyForEach that a child component needs to be added for the data item with the specified index. notifyDataAdd(index: number): void { this.listeners.forEach(listener => { listener.onDataAdd(index); - }) + }); } // Notify LazyForEach that the data item with the specified index has changed and the child component needs to be rebuilt. notifyDataChange(index: number): void { this.listeners.forEach(listener => { listener.onDataChange(index); - }) + }); } // Notify LazyForEach that the child component needs to be deleted from the data item with the specified index. notifyDataDelete(index: number): void { this.listeners.forEach(listener => { listener.onDataDelete(index); - }) + }); } // Notify LazyForEach that data needs to be swapped between the from and to positions. notifyDataMove(from: number, to: number): void { this.listeners.forEach(listener => { listener.onDataMove(from, to); - }) + }); } } @@ -1223,35 +1224,35 @@ class DataSrc2 implements IDataSource { notifyDataReload(): void { this.listeners.forEach(listener => { listener.onDataReloaded(); - }) + }); } // Notify LazyForEach that a child component needs to be added for the data item with the specified index. notifyDataAdd(index: number): void { this.listeners.forEach(listener => { listener.onDataAdd(index); - }) + }); } // Notify LazyForEach that the data item with the specified index has changed and the child component needs to be rebuilt. notifyDataChange(index: number): void { this.listeners.forEach(listener => { listener.onDataChange(index); - }) + }); } // Notify LazyForEach that the child component needs to be deleted from the data item with the specified index. notifyDataDelete(index: number): void { this.listeners.forEach(listener => { listener.onDataDelete(index); - }) + }); } // Notify LazyForEach that data needs to be swapped between the from and to positions. notifyDataMove(from: number, to: number): void { this.listeners.forEach(listener => { listener.onDataMove(from, to); - }) + }); } } ``` @@ -1306,7 +1307,7 @@ struct Index { aboutToAppear() { for (let i = 0; i < 1000; i++) { - this.data.pushData(i+""); + this.data.pushData(i + ""); } } @@ -1350,7 +1351,6 @@ struct ReusableComponent { }.margin({ left: 10, right: 10 }) } } - ``` #### Composite @@ -1396,11 +1396,11 @@ struct MyComponent { aboutToAppear() { for (let i = 0; i < 1000; i++) { - this.data.pushData(i.toString()) + this.data.pushData(i.toString()); } } -// Convert itemBuilderOne to Builder. + // Convert itemBuilderOne to Builder. @Builder itemBuilderOne(item: string) { Column() { @@ -1410,7 +1410,7 @@ struct MyComponent { } } -// Convert itemBuilderTwo to Builder. + // Convert itemBuilderTwo to Builder. @Builder itemBuilderTwo(item: string) { Column() { @@ -1420,7 +1420,7 @@ struct MyComponent { } } -// Convert itemBuilderThree to Builder. + // Convert itemBuilderThree to Builder. @Builder itemBuilderThree(item: string) { Column() { @@ -1476,7 +1476,7 @@ struct ChildComponentA { .margin({ left: 10 }) .fontColor(Color.Blue) Grid() { - ForEach((new Array(20)).fill(''), (item: string,index: number) => { + ForEach((new Array(20)).fill(''), (item: string, index: number) => { GridItem() { // Add the app.media.startIcon image to the src/main/resources/base/media directory. Otherwise, an error will be reported due to missing resources. Image($r('app.media.startIcon')) diff --git a/en/application-dev/quick-start/arkts-state.md b/en/application-dev/quick-start/arkts-state.md index a29f74bbb50eae20f04ac1bc3716ff9c107ad3b7..c33eef72fa9cfd347091971c571b54c678ee723b 100644 --- a/en/application-dev/quick-start/arkts-state.md +++ b/en/application-dev/quick-start/arkts-state.md @@ -31,7 +31,7 @@ An @State decorated variable, like all other decorated variables in the declarat | ------------------ | ------------------------------------------------------------ | | Decorator parameters | None. | | Synchronization type | Does not synchronize with any type of variable in the parent component. | -| Allowed variable types| Object, class, string, number, Boolean, enum, and array of these types.
Date type.
(Applicable to API version 11 or later) [Map](#decorating-variables-of-the-map-type) or [Set](#decorating-variables-of-the-set-type) type.
**undefined** or **null**.
Union types defined by the ArkUI framework, for example, [Length](../reference/apis-arkui/arkui-ts/ts-types.md#length), [ResourceStr](../reference/apis-arkui/arkui-ts/ts-types.md#resourcestr) and [ResourceColor](../reference/apis-arkui/arkui-ts/ts-types.md#resourcecolor).
The type must be specified.
For details about the scenarios of supported types, see [Observed Changes](#observed-changes).
**any** is not supported.
(Applicable to API version 11 or later) Union type of the preceding types, for example, **string \| number**, **string \| undefined** or **ClassA \| null**. For details, see [Union Type](#union-type).
**NOTE**
When **undefined** or **null** is used, you are advised to explicitly specify the type to pass the TypeScript type check. For example, **@State a : string \| undefined = undefined** is recommended; **@State a: string = undefined** is not recommended.| +| Allowed variable types| Object, class, string, number, Boolean, enum, and array of these types.
Date type.
(Applicable to API version 11 or later) [Map](#decorating-variables-of-the-map-type) or [Set](#decorating-variables-of-the-set-type) type.
**undefined** or **null**.
Union types defined by the ArkUI framework, for example, [Length](../reference/apis-arkui/arkui-ts/ts-types.md#length), [ResourceStr](../reference/apis-arkui/arkui-ts/ts-types.md#resourcestr) and [ResourceColor](../reference/apis-arkui/arkui-ts/ts-types.md#resourcecolor).
The type must be specified.
For details about the scenarios of supported types, see [Observed Changes](#observed-changes).
**any** is not supported.
(Applicable to API version 11 or later) Union type of the preceding types, for example, **string \| number**, **string \| undefined**, or **ClassA \| null**. For details, see [Union Type](#union-type).
**NOTE**
When **undefined** or **null** is used, you are advised to explicitly specify the type to pass the TypeScript type check. For example, **@State a: string \| undefined = undefined** is supported, but **@Prop a: string = undefined** is not.| | Initial value for the decorated variable| Local initialization is required. | @@ -65,54 +65,55 @@ Not all changes to state variables cause UI updates. Only changes that can be ob ``` - When the decorated variable is of the class or Object type, its value change and value changes of all its properties, that is, the properties that **Object.keys(observedObject)** returns, can be observed. Below are some examples: - Declare the **Person** and **Model** classes. - - ```ts - class Person { - public value: string; - - constructor(value: string) { - this.value = value; - } - } - - class Model { - public value: string; - public name: Person; - constructor(value: string, person: Person) { - this.value = value; - this.name = person; - } - } - ``` + + Declare the **Person** and **Model** classes. + + ```ts + class Person { + public value: string; + + constructor(value: string) { + this.value = value; + } + } + + class Model { + public value: string; + public name: Person; + constructor(value: string, person: Person) { + this.value = value; + this.name = person; + } + } + ``` - Use \@State to decorate a variable of the Model class object type. + Use \@State to decorate a variable of the Model class object type. - ```ts - // Class type - @State title: Model = new Model('Hello', new Person('World')); - ``` + ```ts + // Class type + @State title: Model = new Model('Hello', new Person('World')); + ``` - Assign a value to the \@State decorated variable. + Assign a value to the \@State decorated variable. - ```ts - // Assign a value to the class object. - this.title = new Model('Hi', new Person('ArkUI')); - ``` + ```ts + // Assign a value to the class object. + this.title = new Model('Hi', new Person('ArkUI')); + ``` - Assign a value to a property of the \@State decorated variable. + Assign a value to a property of the \@State decorated variable. - ```ts - // Assign a value to a property of the class object. - this.title.value = 'Hi'; - ``` + ```ts + // Assign a value to a property of the class object. + this.title.value = 'Hi'; + ``` - The value assignment of the nested property cannot be observed. + The value assignment of the nested property cannot be observed. - ```ts - // The value assignment of the nested property cannot be observed. - this.title.name.value = 'ArkUI'; - ``` + ```ts + // The value assignment of the nested property cannot be observed. + this.title.name.value = 'ArkUI'; + ``` - When the decorated variable is of the array type, the addition, deletion, and updates of array items can be observed. Below are some examples: Declare the **Model** class. @@ -224,18 +225,18 @@ Not all changes to state variables cause UI updates. Only changes that can be ob 1. Variables decorated by \@State must be initialized. Otherwise, an error is reported during compilation. -```ts -// Incorrect format. An error is reported during compilation. -@State count: number; + ```ts + // Incorrect format. An error is reported during compilation. + @State count: number; -// Correct format. -@State count: number = 10; -``` + // Correct format. + @State count: number = 10; + ``` 2. \@State cannot decorate variables of the function type. Otherwise, the framework throws a runtime error. -## Application Scenarios +## Use Scenarios ### Decorating Variables of Simple Types @@ -433,7 +434,7 @@ struct SetSample { ## Union Type -\@State supports **undefined**, **null**, and union types. In the following example, the type of **count** is number | undefined. If the property or type of **count** is changed when the button is clicked, the change will be synced to the view. +\@State supports **undefined**, **null**, and union types. In the following example, the type of **count** is **number | undefined**. If the property or type of **count** is changed when the button is clicked, the change will be synced to the view. ```ts @Entry @@ -474,7 +475,7 @@ Incorrect usage: ```ts export default class PlayDetailViewModel { - coverUrl: string = '#00ff00' + coverUrl: string = '#00ff00'; changeCoverUrl= ()=> { this.coverUrl = '#00F5FF'; @@ -484,7 +485,7 @@ export default class PlayDetailViewModel { ``` ```ts -import PlayDetailViewModel from './PlayDetailViewModel' +import PlayDetailViewModel from './PlayDetailViewModel'; @Entry @Component @@ -515,17 +516,17 @@ Example: ```ts export default class PlayDetailViewModel { - coverUrl: string = '#00ff00' + coverUrl: string = '#00ff00'; changeCoverUrl= (model:PlayDetailViewModel)=> { - model.coverUrl = '#00F5FF' + model.coverUrl = '#00F5FF'; } } ``` ```ts -import PlayDetailViewModel from './PlayDetailViewModel' +import PlayDetailViewModel from './PlayDetailViewModel'; @Entry @Component @@ -550,13 +551,13 @@ struct PlayDetailPage { } ``` -### State Variable Changes in the Constructor Not Taking Effect +### Capturing this in constructor() Fails to Observe Variable Changes In state management, classes are wrapped with a proxy. When a member variable of a class is changed in a component, the proxy intercepts the change. When the value in the data source is changed, the proxy notifies the bound component of the change. In this way, the change can be observed and trigger UI re-rendering. -If you initialize the arrow function for modifying **success** in the constructor, **this** points to the original **TestModel** class, which has not been wrapped with a proxy. As a result, the change can be observed through query event triggering. +When an arrow function for changing **success** is initialized in the **constructor** function, the **TestModel** instance is not encapsulated by the proxy and is pointed by **this**. Therefore, the change of the query event triggered later cannot be observed by the state management. -To enable the change to be observable, place the arrow function for modifying **success** in **query**. As **query** is wrapped with a proxy and has an object initialized, **this** points to the proxy object. +When the arrow function for changing **success** in **query**, the **TestModel** object has been initialized and encapsulated by the proxy. Call **this.viewModel.query()** and **this** in the function points to the **viewModel** object. In this case, the change of **isSuccess** is observable, so that the change of the query event can be observed by the state management. [Incorrect Usage] @@ -666,115 +667,115 @@ In the preceding example, the state variable is changed through a method of the Example 1 ```ts -class Parent { - son: string = '000'; +class Info { + address: string = 'Hangzhou' } @Entry @Component struct Test { - @State son: string = '111'; - @State parent: Parent = new Parent(); + @State message: string =' Shanghai' + @State info: Info = new Info(); aboutToAppear(): void { - this.parent.son = this.son; + this.info.address = this.message; } build() { Column() { - Text(`${this.son}`); - Text(`${this.parent.son}`); + Text(`${this.message}`); + Text(`${this.info.address}`); Button('change') .onClick(() => { - this.parent.son = '222'; + this.info.address = 'Beijing' }) } } } ``` -In the preceding example, clicking **Button('change')** changes the second-line text from **'111'** to **'222'**, but does not change the first-line text. This is because **son** is of the primitive string type, for which a shallow copy is performed. In shallow copy, clicking the button changes the value of **son** in **parent**, but the value of **this.son** remains unchanged. +In the preceding example, when **Button('change')** is clicked, only the second **Text** component is re-rendered. Because **message** is of the simple type string, the value of this.message is not changed while the value of **address** in **info** is changed when the button is clicked. Example 2 ```ts -class Son { - son: string = '000'; +class Info { + address: string = 'Hangzhou' - constructor(son: string) { - this.son = son; + constructor(address: string) { + this.address = address; } } -class Parent { - son: Son = new Son('111'); +class User { + info: Info = new Info('Tianjin'); } @Entry @Component struct Test { - @State son: Son = new Son('222'); - @State parent: Parent = new Parent(); + @State info: Info = new Info('Shanghai'); + @State user: User = new User(); aboutToAppear(): void { - this.parent.son = this.son; + this.user.info = this.info; } build() { Column() { - Text(`${this.son.son}`); - Text(`${this.parent.son.son}`); + Text(`${this.info.address}`); + Text(`${this.user.info.address}`); Button('change') .onClick(() => { - this.parent.son.son = '333'; + this.user.info.address = 'Beijing' }) } } } ``` -In the preceding example, a reference of **son** is assigned to the **son** property of **parent** in **aboutToAppear**. In this case, if you click the button to change the property in **son**, the first **Text** component is re-rendered, but not the second **Text** component, which is unable to observe changes at the second layer. +In the preceding example, the reference of **info** is assigned to member property **info** of **user** in **aboutToAppear**. Therefore, when the button is clicked to change the property in **info**, the first **Text** component is re-rendered. However, only the first layer of the second **Text** component is observable, so the second **Text** component is not re-rendered. Example 3 ```ts -class Son { - son: string = '000'; +class Info { + address: string = 'Hangzhou' - constructor(son: string) { - this.son = son; + constructor(address: string) { + this.address = address; } } -class Parent { - son: Son = new Son('111'); +class User { + info: Info = new Info('Tianjin'); } @Entry @Component struct Test { - @State son: Son = new Son('222'); - @State parent: Parent = new Parent(); + @State info: Info = new Info('Shanghai'); + @State user: User = new User(); aboutToAppear(): void { - this.parent.son = this.son; + this.user.info = this.info; } build() { Column() { - Text(`${this.son.son}`); - Text(`${this.parent.son.son}`); + Text(`${this.info.address}`); + Text(`${this.user.info.address}`); Button('change') .onClick(() => { - this.parent.son = new Son('444'); - this.parent.son.son = '333'; + this.user.info = new Info('Guangzhou'); + this.user.info.address = 'Beijing' }) } } } ``` -In the preceding example, clicking **Button('change')** changes the second-line text from **'222'** to **'333'**, but does not change the first-line text. This is because **this.parent.son = new Son('444')'** is executed after the button is clicked, which means that a **Son** object is created, and then **this.parent.son.son = '333'** is executed. As a result, clicking the button changes the value of **son** in the new **Son** object, and the one in the original Son object is not affected. +In the preceding example, if you click **Button('change')**, only the second **Text** component is re-rendered. This is because after the button is clicked, **this.user.info = new Info('Guangzhou')** creates a new **Info** object, and then **this.user.info.address = 'Beijing'** changes the value of **address** in the newly created **Info** object. However, the value of **address** in the original **Info** object is not changed. ### Repeated Value Changes to State Variables by Complex Constants Trigger Re-rendering @@ -811,15 +812,20 @@ struct ConsumerChild { console.log("dataObj changed"); } + getContent() { + console.log(`this.dataObj.name change: ${this.dataObj.name}`); + return this.dataObj.name; + } + build() { Column() { - Text(this.dataObj.name).fontSize(30) + Text(this.getContent()).fontSize(30) } } } ``` -In the preceding example, each time you click **Button('change to self')**, the same class constant is assigned to a state variable of the **Class** type, triggering re-rendering. In state management V1, a proxy is added to the @Observed decorated class objects and the @State decorated objects of the Class, Date, Map, Set, or Array type to observe the changes of top-level properties or API invoking. +In the preceding example, each time the **change to self** button is clicked, the same class constant is assigned to a state variable of the class type. This operation triggers re-render and generates the log **this.dataObj.name change: a**. In state management V1, a proxy is added to the @Observed decorated class objects and the @State decorated objects of the Class, Date, Map, Set, or Array type to observe the changes of top-level properties or API invoking. **dataObjFromList** is of a **Proxy** type but **list[0]** is of an **Object** type. As a result, when **list[0]** is assigned to **dataObjFromList**, the value changes trigger re-rendering. To avoid unnecessary value changes and re-renders, use \@Observed to decorate the class, or use [UIUtils.getTarget()](./arkts-new-getTarget.md) to obtain the original value and determine whether the original and new values are the same. If they are the same, do not perform value changes. Method 1: Add \@Observed decorator. @@ -998,7 +1004,7 @@ Therefore, you are not advised to change the state variables in **build**. When ### Using the a.b(this.object) Format Fails to Trigger UI Re-render -In the **build** method, when the variable decorated by \@State is of the object type and is called in the **a.b(this.object)** format, the native object of **this.object** is passed in the b method. If the property of **this.object** is changed, the UI cannot be re-rendered. In the following example, when the static method **Balloon.increaseVolume** or **this.reduceVolume** is used to change the **volume** of **Balloon**, the UI is not re-rendered. +In the **build** method, when the variable decorated by \@State is of the object type and is called in the **a.b(this.object)** format, the original object of **this.object** is passed in the b method. If the property of **this.object** is changed, the UI cannot be re-rendered. In the following example, when the static method **Balloon.increaseVolume** or **this.reduceVolume** is used to change the **volume** of **Balloon**, the UI is not re-rendered. [Incorrect Usage] @@ -1092,13 +1098,13 @@ struct Index { } ``` -### Changing State Variables Outside a Custom Component +### Unregistration Existing Functions Before Changing State Variables by Registering a Callback You can register the arrow function in **aboutToAppear** to change the state variables in the component. Note that the registered function must be left empty in **aboutToDisappear**. Otherwise, the custom component cannot be released because the arrow function captures the **this** instance of the component, causing memory leakage. ```ts class Model { - private callback: Function | undefined = () => {} + private callback: (() => void) | undefined = () => {}; add(callback: () => void): void { this.callback = callback; diff --git a/en/application-dev/quick-start/arkts-statestyles.md b/en/application-dev/quick-start/arkts-statestyles.md index 915cf92bacf0c08c7f43db262e15f253e87a092a..04f8e9f82fdeedeca704fead1328e08484254b43 100644 --- a/en/application-dev/quick-start/arkts-statestyles.md +++ b/en/application-dev/quick-start/arkts-statestyles.md @@ -5,7 +5,7 @@ Unlike \@Styles, which are used to reuse styles only on static pages, stateStyle > **NOTE** > -> Polymorphic style supports only universal attributes. +> Polymorphic style supports only universal attributes. If the polymorphic style does not take effect, the attribute may be a private attribute of the component, for example, [fontColor](../reference/apis-arkui/arkui-ts/ts-universal-attributes-text-style.md) or [backgroundColor](../reference/apis-arkui/arkui-ts/ts-universal-attributes-background.md) of the [TextInput](../reference/apis-arkui/arkui-ts/ts-basic-components-textinput.md) component. In this case, you can use [attributeModifier](../reference/apis-arkui/arkui-ts/ts-universal-attributes-attribute-modifier.md#attributemodifier) to dynamically set component attributes to enable the polymorphic style. ## Overview @@ -25,8 +25,7 @@ stateStyles is an attribute method that sets the style based on the internal sta > > Currently, only the **Tab** button and arrow buttons on the external keyboard can be used to trigger the focused state. Sequential keyboard navigation is not supported for nested scrollable components. - -## Application Scenarios +## Use Scenarios ### Common Scenarios diff --git a/en/application-dev/quick-start/arkts-style.md b/en/application-dev/quick-start/arkts-style.md index e0777e9954780b6b98db8718811f8802dc6602a3..923ebcab4454309c78173ce2524d89ffb9ac2515 100644 --- a/en/application-dev/quick-start/arkts-style.md +++ b/en/application-dev/quick-start/arkts-style.md @@ -14,7 +14,7 @@ If the style of each component needs to be set separately, this will result in a ## Rules of Use -- \@Styles supports only [universal attributes](../reference/apis-arkui/arkui-ts/ts-universal-attributes-size.md) and [universal events](../reference/apis-arkui/arkui-ts/ts-universal-events-click.md). +- Currently, \@Styles supports only [general attributes](../reference/apis-arkui/arkui-ts/ts-component-general-attributes.md) and [general events](../reference/apis-arkui/arkui-ts/ts-component-general-events.md). - \@Styles can be defined inside or outside a component declaration. When it is defined outside a component declaration, the method name must be preceded by the keyword **function**. @@ -171,3 +171,5 @@ struct FancyUse { } } ``` + + \ No newline at end of file diff --git a/en/application-dev/quick-start/arkts-track.md b/en/application-dev/quick-start/arkts-track.md index 8e26b79eb292e746dd09c10fec087608aa595745..bc1460bf3eb2ffd7dbe2c6a085988f93f5d1edf5 100644 --- a/en/application-dev/quick-start/arkts-track.md +++ b/en/application-dev/quick-start/arkts-track.md @@ -4,7 +4,7 @@ \@Track is a decorator used to decorate properties of class objects. Any changes to the properties decorated by \@Track will trigger only updates to the UI associated with those properties. -Before reading this topic, you are advised to read [\@State](./arkts-state.md) to have a basic understanding of the observation capabilities of state management. +Before reading this topic, you are advised to read [\@State](./arkts-state.md) to have an understanding of the basic observation capabilities of state management. > **NOTE** > @@ -23,6 +23,8 @@ Before reading this topic, you are advised to read [\@State](./arkts-state.md) t | Decorator parameters | None.| | Allowed variable types| Non-static properties of class objects.| + + ## Observed Changes and Behavior When a class object is a state variable, any changes to its properties decorated by \@Track will trigger only updates to the UI associated with those properties. @@ -111,7 +113,9 @@ In the preceding example: ## Constraints -- If the \@Track decorator is used in a class, the non-\@Track decorated properties in the class cannot be used in the UI. For example, these properties cannot be bound to components nor be used to initialize child components; otherwise, an error is reported during runtime. For details, see [Improperly Using Non-\@Track Decorated Properties Causes Errors](#improperly-using-non-track-decorated-properties-causes-errors). Non-\@Track decorated properties can be used in non-UI functions, such as event callback functions and lifecycle functions. +- If the \@Track decorator is used in a class, the non-\@Track decorated properties in the class cannot be used in the \@Component decorated UI. For example, these properties cannot be bound to components nor be used to initialize child components; otherwise, an error is reported during runtime. For details, see [Improperly Using Non-\@Track Decorated Properties Causes Errors](#improperly-using-non-track-decorated-properties-causes-errors). Non-\@Track decorated properties can be used in non-UI functions, such as event callback functions and lifecycle functions. + +- Since API version 18 and later, \@Track is used in the \@ComponentV2 decorated UI. In this case, an error is not reported during runtime, but the refresh is not responded. For details, see [Common Scenarios](./arkts-v1-v2-mixusage.md#observed-decorated-class). - Whenever possible, avoid any combination of class objects that contain \@Track and those that do not in, for example, union types and class inheritance. @@ -183,7 +187,7 @@ Processing steps: ### Improperly Using Non-\@Track Decorated Properties Causes Errors -If a property that is not decorated by \@Track is used in the UI, an error is reported during runtime. +If a non-\@Track decorated property is used in the UI, an error is reported during runtime. ```ts class Person { diff --git a/en/application-dev/quick-start/arkts-v1-v2-migration.md b/en/application-dev/quick-start/arkts-v1-v2-migration.md index 6a146820549aad577fd08e275cfd59348612efa3..01b2fa1a6d706e194d999682cd5742c289b339c3 100644 --- a/en/application-dev/quick-start/arkts-v1-v2-migration.md +++ b/en/application-dev/quick-start/arkts-v1-v2-migration.md @@ -22,7 +22,7 @@ During the evolution of the state management framework, state management V1 and | \@Observed | \@ObservedV2 | Indicates that this object is an observable object. However, they have different capabilities.
\@Observed is used to observe the top-level properties and it takes effect only when it is used together with \@ObjectLink.
\@ObservedV2 does not have the observation capability. It only indicates that this class is observable. To observe the class properties, use together with \@Trace. | | \@Track | \@Trace | \@Track is used for accurate observation. If it is not used, class properties cannot be accurately observed.
\@Trace decorated properties can be accurately traced and observed.| | \@Component | \@ComponentV2 | \@Component is the custom component decorator used with the state variables of V1.
@ComponentV2 is the custom component decorator used with the state variables of V2.| -|\@State | No external initialization: @Local
External initialization once: \@Param and \@Once| Similar to \@Local, \@State decorated variables can work as the data source which can be directly migrated without external initialization. If the external initialization is required, use \@Param and \@Once. For details, see [@State -> @Local](#state-local).| +|\@State | No external initialization: @Local
External initialization once: \@Param and \@Once| Similar to \@Local, \@State decorated variables can work as the data source which can be directly migrated without external initialization. If the external initialization is required, use \@Param and \@Once. For details, see [@State->@Local](#state-local).| | \@Prop | \@Param | Similar to \@Param, \@Prop is used to decorate custom component variables. When the input parameter is of the complex type, \@Prop is used to deep copy and \@Param is used to import the parameter.| | \@Link | \@Param\@Event | \@Link implements a two-way synchronization encapsulated by the framework of V1. Developers using V2 can implement the two-way synchronization through @Param and @Event.| | \@ObjectLink | \@Param | Compatible. \@ObjectLink needs to be initialized by the instance of the @Observed decorated class, but \@Param does not have this constraint.| @@ -1159,7 +1159,7 @@ struct Index { } } ``` -### LocalStorage -> Global @ObservedV2 or @Trace +### LocalStorage->Global @ObservedV2 or @Trace #### Migration Rules LocalStorage is used to share state variables between pages. This capability is provided because state variables of V1 are coupled with the view level and cannot be shared between pages. For V2, the observation capability of state variables is embedded in the data and is not coupled with the view level. Therefore, V2 does not require a capability similar to **LocalStorage**. You can use the global @ObservedV2 or @Trace to import and export data by yourself, sharing state variables between pages. @@ -2122,7 +2122,7 @@ struct Index1 { } ``` -### Environment -> Ability APIs +### Environment->Ability APIs In V1, you can obtain environment variables through **Environment**. However, the result obtained by **Environment** cannot be directly used. You need to use **Environment** together with **AppStorage** to obtain the value of the corresponding environment variable. After migration to V2, you can directly obtain the system environment variables through the [config](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#properties) property of **UIAbilityContext** without using **Environment**. V1: diff --git a/en/application-dev/quick-start/arkts-v1-v2-mixusage.md b/en/application-dev/quick-start/arkts-v1-v2-mixusage.md new file mode 100644 index 0000000000000000000000000000000000000000..07f72b8a6ba0d651426088103eaa5fdc61126c0e --- /dev/null +++ b/en/application-dev/quick-start/arkts-v1-v2-mixusage.md @@ -0,0 +1,1026 @@ +# Mixing Use of State Management V1 and V2 + +## Overview + +During the evolution of the state management framework, state managements V1 and V2 are launched based on API version 7 and API version 12, respectively. For applications that have used state management V1 and need to be migrated to state management V2, see [Migrating Applications from V1 to V2](./arkts-v1-v2-migration.md). + +For large-scale applications, V1 and V2 may be used together during the migration. In versions earlier than API version 18, strict verification is performed in the mixed use scenario, mainly in the transfer of complex objects. For details, see [Mixing Use of Custom Components](./arkts-custom-component-mixed-scenarios.md). To facilitate smooth migration to V2, API version 18 and later versions reduce the restrictions on the mixed use of V1 and V2. In addition, new methods [enableV2Compatibility](../reference/apis-arkui/js-apis-StateManagement.md#enablev2compatibility18) and [makeV1Observed](../reference/apis-arkui/js-apis-StateManagement.md#makev1observed18) are provided to help you solve related problems. + +> **NOTE** +> +> In this topic, the symbol "->" is used to indicate the transfer of variables. For example, "V1 -> V2" indicates that the state variable of V1 is transferred to the V2. + + +## Verification Rules +In versions earlier than API version 18, the mixed use rules of state managements V1 and V2 can be summarized as follows: +1. Decorators of V1 cannot be used together with @ObservedV2. +2. Decorators of V2 cannot be used together with @Observed. +3. Only simple types can be transferred from V1 to V2. Complex types (built-in types), including Array, Map, Set, and Date, are not allowed. +4. Simple types or a common class can be transferred from V2 to V1, but built-in types such as Array, Map, Set, or Date are not allowed. + +Since API version 18, only the first rule is still enabled, and the rest rules are open for verification. The following table lists the verification during compilation. + +| Scenario | Earlier than API Version 18| API Version 18 and Later | +|------|----|------| +| Decorators of V1 and \@ObservedV2 are used together. | An error is reported.| An error is reported.| +| Decorators of V2 and \@Observed are used together.| An error is reported.| No error is reported.| +| A common class is transferred from V1 to V2. | An error is reported.| No error is reported.| +| Built-in types such as Array, Map, Set, Date are transferred from V1 to V2. | An error is reported.| No error is reported.| +| A \@Observed decorated class is transferred from V1 to V2. | An error is reported.| No error is reported.| +| A \@ObservedV2 decorated class is transferred from V2 to V1. | An error is reported.| An error is reported.| +| Built-in types such as Array, Map, Set, Date are transferred from V2 to V1. | An error is reported.| No error is reported.| +| \@ObjectLink is initialized by a class that is not decorated by \@Observed. | An error is reported.| No error is reported.| + +@ObservedV2 or @Trace has its own independent observation capability, which can be used in both \@ComponentV2 and \@Component. However, the state management framework does not allow the mixed use of observation capability of V1 and V2. Therefore, the first rule is still enabled. + +## Available APIs +### makeV1Observed + +static makeV1Observed\(source: T): T + +The [makeV1Observed](../reference/apis-arkui/js-apis-StateManagement.md#makev1observed18) API encapsulates an unobservable object into an observable object of state management V1. **makeV1Observed** has the same capability as that of @Observed and its return value can be used to initialize @ObjectLink. + +>**NOTE** +> +>This API is supported since API version 18. + +**Description** +- **makeV1Observed** is used together with **enableV2Compatibility** for V2 -> V1 transfer. +- **makeV1Observed** converts a common class, Array, Map, Set, or Date type to a state variable of V1. Its capability is equivalent to \@Observed. Therefore, the return value can be used to initialize \@ObjectLink. +- If the data received by **makeV1Observed** is already the state variable of V1, **makeV1Observed** returns itself without any change. +- **makeV1Observed** does not execute recursively. It only wraps the first layer into the state variable of V1. + +**Constraints** +- The [collections](../reference/apis-arkts/js-apis-arkts-collections.md) type and [\@Sendable](../arkts-utils/arkts-sendable.md) decorated classes are not supported. +- Non-object types are not supported. +- **undefined** and **null** are not supported. +- The return values of \@ObservedV2 and [makeObserved](../reference/apis-arkui/js-apis-StateManagement.md#makeobserved), and variables of built-in types (such as Array, Map, Set, and Date) decorated by the decorators of V2 are not supported. + + +### enableV2Compatibility + +static enableV2Compatibility\(source: T): T + +[enableV2Compatibility](../reference/apis-arkui/js-apis-StateManagement.md#enablev2compatibility18) enables the observation capability of V2 for the state variable of V1, that is, the state variable of V1 can be observed in \@ComponentV2. + +>**NOTE** +> +>This API is supported since API version 18. + +**Description** +- This API is mainly used in the V1 -> V2 transfer. After the state variable of V1 calls this API and is transferred to \@ComponentV2, the change can be observed in V2 to implement associated data update. +- **enableV2Compatibility** applies only to state variables of V1. The state variable of V1 is a variable decorated by the decorator of V1, such as \@Observed, \@State, \@Prop, \@Link, \@Provide, \@Consume, and \@ObjectLink (\@ObjectLink must be an instance decorated by \@Observed or the return value of **makeV1Observed**). Otherwise, the input parameter itself is returned. +- **enableV2Compatibility** recursively traverses all properties of the class and all subitems of Array, Set, or Map until non-V1 state variable data is found. + +**Constraints** +- Non-object types are not supported. +- **undefined** and **null** are not supported. +- Non-V1 state variable data is not supported. +- The return values of \@ObservedV2 and [makeObserved](../reference/apis-arkui/js-apis-StateManagement.md#makeobserved), and variables of built-in types (such as Array, Map, Set, and Date) decorated by the decorators of V2 are not supported. + +## Mixed Use Paradigm + +Based on the [enableV2Compatibility](../reference/apis-arkui/js-apis-StateManagement.md#enablev2compatibility18) and [makeV1Observed](../reference/apis-arkui/js-apis-StateManagement.md#makev1observed18) APIs, the mixed use paradigm of V1 and V2 is as follows: + +### V1->V2 +- The state variable of V1 is transferred to \@Param of V2. Call **UIUtils.enableV2Compatibility** to enable the state variable of V1 to be observed in \@ComponentV2. For details, see [Common Scenarios](#v1-v2-1). +```ts +import { UIUtils } from '@kit.ArkUI'; + +@Observed +class ObservedClass { +} + +@Entry +@Component +struct CompV1 { + @State observedClass: ObservedClass = new ObservedClass(); + + build() { + Column() { + CompV2({ observedClass: UIUtils.enableV2Compatibility(this.observedClass) }) + } + } +} + +@ComponentV2 +struct CompV2 { + @Param observedClass: ObservedClass = new ObservedClass(); + + build() { + } +} +``` +- The state variables of V1 can be used to observe the first-layer properties. After **UIUtils.enableV2Compatibility** is called to transfer the variables to \@Param, \@Param is able to observe the changes of the first-layer properties. + +The following table lists the observation capability in specific scenarios after **enableV2Compatibility** is called. + +| \@Component (Parent) - > \@ComponentV2 (Child) | Observation Capability| +|------|----| +| Normal variable| No. **enableV2Compatibility** supports only state variables of V1.| +| \@Observed decorated class | The first-layer properties can be observed.| +| Variable decorated by the decorator of V1, whose type is Array, Map, Set, or Date. | API calls can be observed.| +| Variable decorated by the decorator of V1, whose type is class decorated by non-\@Observed. | The first-layer properties can be observed. Note that if the data source is \@ObjectLink, it must be the instance of the \@Observed decorated class or the return value of **makeV1Observed**.| +| Normal array. The array item is the class decorated by \@Observed. | No. The outer array is a non-V1 state variable, so this API does not take effect and the data source itself is returned.| +| Variable decorated by the decorator of V1, whose type is a normal array. The array item is the class decorated by \@Observed. | In \@Component, only the first layer can be observed. To observe the deeper layers, use \@ObjectLink together. You can observe the deeper layers in \@ComponentV2.| +| \@ObservedV2 decorated class | Observable in V1 and V2. The observation capability is derived from the \@ObservedV2 and \@Trace capabilities. **enableV2Compatibility** does not take effect.| +| Variable decorated by the decorator of V1, whose type is a normal array. The array item is the class decorated by \@ObservedV2.| Observable because **enableV2Compatibility** makes the outer array observable in V2. The property observation capability of the class decorated by \@ObservedV2 is derived from \@ObservedV2 and \@Trace, and is irrelevant to **enableV2Compatibility**.| + +### V2->V1 + +For V2 -> V1 transfer, you are advised to use **UIUtils.enableV2Compatibility(UIUtils.makeV1Observed())**. If this object is observable in V1, only **UIUtils.enableV2Compatibility** needs to be called. For details, see [Common Scenarios](#v2-v1-1). + +```ts +import { UIUtils } from '@kit.ArkUI'; + +@Observed +class ObservedClass {} + +@Entry +@ComponentV2 +struct CompV2 { + @Local observedClass: ObservedClass = UIUtils.enableV2Compatibility(new ObservedClass()); + build() { + Column() { + CompV1({ observedClass: this.observedClass }) + } + } +} + +@Component +struct CompV1 { + @ObjectLink observedClass: ObservedClass; + build() {} +} +``` + +The following table lists the specific scenarios. + +| \@ComponentV2 (Parent) -> \@Component (Child) | Observation Capability| +|------|----| +| \@Observed decorated nested class| In \@ComponentV2, you can observe the changes of nested properties.| +| Normal class | Observable. Call **makeV1Observed** to execute **enableV2Compatibility** properly.| +| Array\ or other simple arrays | Observable. **makeV1Observed** needs to be called.
Example: **@Local local : Array\ = UIUtils.enableV2Compatibility(UIUtils.makeV1Observed([1, 2, 3]))**| +| Array\ (The array item is a class decorated by \@Observed.) | Observable. **makeV1Observed** needs to be called.
Example: **@Local local : Array\ = UIUtils.enableV2Compatibility(UIUtils.makeV1Observed([new ObservedClass()]))**| +| Array\\>: two-dimensional array, array item, or other simple types| Observable. **makeV1Observed** needs to be called.
Example: **@Local local : Array>> = UIUtils.enableV2Compatibility(UIUtils.makeV1Observed([UIUtils.makeV1Observed([1, 2, 3])]))**| + + +## Mixed Use Rules +- When complex data is transferred from V1 to V2, call **enableV2Compatibility**; otherwise, data association between V1 and V2 cannot be implemented. It is recommended that **enableV2Compatibility** be called at the construction position of the V2 component. Otherwise, **enableV2Compatibility** needs to be manually called again when a value is assigned to the entire variable. + +```ts +// Recommended. When this.state = new ObservedClass() is called, UIUtils.enableV2Compatibility is not required, simplifying the code. +SubComponentV2({param: UIUtils.enableV2Compatibility(this.state)}) + +// Not recommended. When a value is assigned to the state as a whole, UIUtils.enableV2Compatibility needs to be called again. +// Otherwise, the variable of V1 transferred to SubComponentV2 cannot be observed in V2. +// @State state: ObservedClass = UIUtils.enableV2Compatibility(new ObservedClass()); +// this.state = UIUtils.enableV2Compatibility(new ObservedClass()) +SubComponentV2({param: this.state}) +``` + +- When complex data is transferred from V2 to V1, preferentially declare the state variable data of V1 in V2 and call **UIUtils.enableV2Compatibility**. This is because in state management V1, state variables have the capability of observing the first layer by default, while state management V2 has only the capability of observing itself. If you want to associate data between V1 and V2, you need to call **UIUtils.enableV2Compatibility(UIUtils.makeV1Observed())** to align the observation capabilities of both state managements. + +```ts +// Recommended. +@Local unObservedClass: UnObservedClass = UIUtils.enableV2Compatibility(UIUtils.makeV1Observed(new UnObservedClass())); + +// Recommended. ObservedClass is a class decorated by @Observed. +@Local observedClass: ObservedClass = UIUtils.enableV2Compatibility(new ObservedClass()); +``` +- **UIUtils.enableV2Compatibility(UIUtils.makeV1Observed())** does not change the observation capabilities of V1 and V2. + - In V1, **UIUtils.enableV2Compatibility(UIUtils.makeV1Observed())** is equal to the observation capability of V1, which can observe the value assignment of the data and the first-layer property. If in-depth observation is required, \@ObjectLink should be used together. + - In V2, **UIUtils.enableV2Compatibility(UIUtils.makeV1Observed())** can be used to observe deeper layers, but each layer must be a class decorated by \@Observed or a return value of **makeV1Observed**. +- After **UIUtils.enableV2Compatibility** is called, the observation capability of V2 is enabled for new data by default. However, you need to ensure that the new data is also the class decorated by \@Observed or the return value of **makeV1Observed**. For details about the complete example, see [Common Scenarios](#nested-type). +```ts +let arr: Array = UIUtils.enableV2Compatibility(UIUtils.makeV1Observed(new ArrayItem())); + +arr.push(new ArrayItem()); // The new data is not a state variable of V1. Therefore, the observation capability of V2 is unavailable. +arr.push(UIUtils.makeV1Observed(new ArrayItem())); // The new data is the state variable of V1, which can be observed in V2 by default. +``` +- For built-in types, such as Array, Map, Set, and Date, both V1 and V2 can observe the changes caused by their own value assignment and API calls. Although data refreshes can be implemented in some simple scenarios without calling **UIUtils.enableV2Compatibility**, dual proxies may cause poor performance. Therefore, **UIUtils.enableV2Compatibility(UIUtils.makeV1Observed())** is recommended. For details, see [Common Scenarios](#built-in-type). +- For classes with \@Track decorated properties, the system does not crash when non-\@Track decorated properties are used in \@ComponentV2 but still crashes when they are used in \@Component. For details, see [Common Scenarios](#observed-decorated-class). + +When calling the two APIs to use V1 and V2 together, you can comply with the logic shown in the following figure. + +![mix-usage](./figures/V1V2_mix_usage.png) + + +## Common Scenarios +### Normal JS Object +#### V1->V2 +**Recommended** + +```ts +import { UIUtils } from '@kit.ArkUI'; + +@Observed +class ObservedClass { + name: string = 'Tom'; +} + +@Entry +@Component +struct CompV1 { + @State observedClass: ObservedClass = new ObservedClass(); + + build() { + Column() { + Text(`@State observedClass: ${this.observedClass.name}`) + .onClick(() => { + this.observedClass.name += '!'; // Refresh + }) + // Call UIUtils.enableV2Compatibility to enable the state variable of V1 to be observed in @ComponentV2. + CompV2({ observedClass: UIUtils.enableV2Compatibility(this.observedClass) }) + } + } +} + +@ComponentV2 +struct CompV2 { + @Param observedClass: ObservedClass = new ObservedClass(); + + build() { + // After the observation capability of V2 is enabled for the state variable of V1, the first-layer changes can be observed in V2. + Text(`@Param observedClass: ${this.observedClass.name}`) + .onClick(() => { + this.observedClass.name += '!'; // Refresh + }) + } +} +``` +**Not recommended** + +In the following example, when the state variable of V1 is transferred to V2, the **enableV2Compatibility** API is not called, and the observation capability of V2 is not enabled. Therefore, **observedClass** cannot observe the change of the **name** property in **CompV2**. The observation capabilities of the same state variable in **CompV1** and **CompV2** are different. + +```ts +@Observed +class ObservedClass { + name: string = 'Tom'; +} + +@Entry +@Component +struct CompV1 { + @State observedClass: ObservedClass = new ObservedClass(); + + build() { + Column() { + Text(`@State observedClass: ${this.observedClass.name}`) + .onClick(() => { + this.observedClass.name += '!'; // Refresh + }) + // The enableV2Compatibility API is not called. The state variable of V1 cannot be observed in CompV2. + // The change of name cannot be observed in CompV2. + CompV2({ observedClass: this.observedClass }) + } + } +} + +@ComponentV2 +struct CompV2 { + @Param observedClass: ObservedClass = new ObservedClass(); + + build() { + Text(`@Param observedClass: ${this.observedClass.name}`) + .onClick(() => { + this.observedClass.name += '!'; // Do not refresh. + }) + } +} +``` +#### V2->V1 + +**Recommended** + +During V2->V1 transfer, to align the observation capabilities of V2 and V1, the **makeV1Observed** API needs to be called in V2. In addition, the observation capability of V2 needs to be enabled by calling the **enableV2Compatibility** API. Therefore, the recommended sample code is as follows: + +```ts +import { UIUtils } from '@kit.ArkUI'; + +class ObservedClass { + name: string = 'Tom'; +} + +@Entry +@ComponentV2 +struct CompV2 { + @Local observedClass: ObservedClass = UIUtils.enableV2Compatibility(UIUtils.makeV1Observed(new ObservedClass())); + + build() { + Column() { + // @Local can only observe itself. + // However, UIUtils.makeV1Observed is called to change @Local to the state variable of V1, whose first-layer changes are observable. + // Call UIUtils.enableV2Compatibility to make it observable in V2. + // Currently, you can observe the changes of the first-layer properties. + Text(`@Local observedClass: ${this.observedClass.name}`) + .onClick(() => { + this.observedClass.name += '!'; // Refresh + }) + // @ObjectLink can receive the instance of the @Observed decorated class or the return value of makeV1Observed. + CompV1({ observedClass: this.observedClass }) + } + } +} + +@Component +struct CompV1 { + @ObjectLink observedClass: ObservedClass; + + build() { + // The change of the first layer can be observed in CompV1. + Text(`@ObjectLink observedClass: ${this.observedClass.name}`) + .onClick(() => { + this.observedClass.name += '!'; // Refresh + }) + } +} +``` +**Not recommended** + +The observation capabilities of V1 and V2 are different. If **UIUtils.enableV2Compatibility(UIUtils.makeV1Observed())** is not called to directly transfer data, the data is not updated or the update behavior is inconsistent. + +```ts +class ObservedClass { + name: string = 'Tom'; +} + +@Entry +@ComponentV2 +struct CompV2 { + @Local observedClass: ObservedClass = new ObservedClass(); + + build() { + Column() { + // @Local can only observe itself. Property changes cannot be observed here. + Text(`@Local observedClass: ${this.observedClass.name}`) + .onClick(() => { + this.observedClass.name += '!'; // Do not refresh. + }) + // @ObjectLink cannot receive instances of non-@Observed decorated classes or return values of makeV1Observed. + // The log indicates that the current ObjectLink is assigned an invalid value. + CompV1({ observedClass1: this.observedClass, observedClass2: this.observedClass }) + } + } +} + +@Component +struct CompV1 { + @ObjectLink observedClass1: ObservedClass; + @State observedClass2: ObservedClass = new ObservedClass(); + + build() { + Column() { + // The value of @ObjectLink is invalid and does not respond to the UI re-render. + Text(`@ObjectLink observedClass: ${this.observedClass1.name}`) + .onClick(() => { + this.observedClass1.name += '!'; // Do not refresh. + }) + + // Different from @ObjectLink, @State wraps unobservable objects into observable objects of V1 by default. The changes of itself and attributes can be observed. + Text(`@State observedClass: ${this.observedClass2.name}`) + .onClick(() => { + this.observedClass2.name += '!'; // Refresh + }) + } + } +} +``` +### \@Observed Decorated Class +#### V1->V2 +In the following example: +- **ObservedClass** is the class decorated by \@Observed and enables the observation capability in V2. +- **name** is a @Track decorated property and is observable in both V1 and V2. +- **count** is a non-@Track decorated property and is invalid in both V1 and V2. + - In V1, if a non-@Track decorated property is used on the UI, an error is reported during runtime. + - In V2, no error is reported during runtime when non-@Track decorated properties are used on the UI, but the refresh is not responded. + +```ts +import { UIUtils } from '@kit.ArkUI'; + +@Observed +class ObservedClass { + @Track name: string = 'a'; + count: number = 0; +} + +@Entry +@Component +struct CompV1 { + @State observedClass: ObservedClass = new ObservedClass(); + build() { + Column() { + Text(`name: ${this.observedClass.name}`).onClick(() => { + // Trigger the refresh. + this.observedClass.name += 'a'; + }) + // If a non-@Track decorated variable is used in V1, the system crashes. + // Text(`count: ${this.observedClass.count}`) + + CompV2({ observedClass: UIUtils.enableV2Compatibility(this.observedClass) }) + } + } +} + +@ComponentV2 +struct CompV2 { + @Param observedClass: ObservedClass = new ObservedClass(); + build() { + // The system does not crash when a non-@Track variable is used in V2, but the refresh is not responded as well. + Text(`count: ${this.observedClass.count}`).onClick(() => { + // No refresh is triggered. + this.observedClass.count++; + }) + } +} +``` +#### V2->V1 +- **ObservedClass** is a class decorated by \@Observed. Therefore, when **UIUtils.enableV2Compatibility** is transferred to V1, **UIUtils.makeV1Observed** does not need to be called. +- Only the \@Track decorated variables can be observed in V1 and V2. If a non-\@Track variable is used in V1, an error is reported on the UI. In V2, no error is reported but the variable does not respond to the refresh. +```ts +import { UIUtils } from '@kit.ArkUI'; + +@Observed +class ObservedClass { + @Track name: string = 'a'; + count: number = 0; +} + +@Entry +@ComponentV2 +struct CompV1 { + @Local observedClass: ObservedClass = UIUtils.enableV2Compatibility(new ObservedClass()); + + build() { + Column() { + Text(`name: ${this.observedClass.name}`).onClick(() => { + // Trigger the refresh. + this.observedClass.name += 'a'; + }) + // The system does not crash when a non-@Track variable is used in V2, but the refresh is not triggered as well. + Text(`count: ${this.observedClass.count}`).onClick(() => { + this.observedClass.count++; + }) + + CompV2({ observedClass: this.observedClass }) + } + } +} + +@Component +struct CompV2 { + @ObjectLink observedClass: ObservedClass; + + build() { + Column() { + Text(`count: ${this.observedClass.name}`).onClick(() => { + // Trigger the refresh. + this.observedClass.name += 'a'; + }) + // If a non-@Track decorated variable is used in V1, the system crashes. + // Text(`count: ${this.observedClass.count}`) + } + } +} +``` + +### Built-in Type +The following uses Array as an example. +#### V1->V2 +**Recommended** + +```ts +import { UIUtils } from '@kit.ArkUI'; + +@Entry +@Component +struct ArrayCompV1 { + @State arr: Array = UIUtils.makeV1Observed([1, 2, 3]); + + build() { + Column() { + Text(`V1 ${this.arr[0]}`).onClick(() => { + // Click to trigger the changes of ArrayCompV1 and ArrayCompV2. + this.arr[0]++; + }) + // When the variable is transferred to V2, it is found that the current proxy is wrapped by makeV1Observed and the observation capability of V2 is enabled. + // In ArrayCompV2, Param does not wrap the proxy again to avoid the dual proxy problem. + ArrayCompV2({ arr: UIUtils.enableV2Compatibility(this.arr) }) + } + .height('100%') + .width('100%') + } +} + +@ComponentV2 +struct ArrayCompV2 { + @Param arr: Array = [1, 2, 3]; + + build() { + Column() { + Text(`V2 ${this.arr[0]}`).onClick(() => { + // Click to trigger the changes of ArrayCompV1 and ArrayCompV2. + this.arr[0]++; + }) + } + } +} +``` +**Not recommended** + +In the following example, enableV2Compatibility and makeV1Observed are not called. Therefore, the proxy and refresh in V1 and V2 are inconsistent. +```ts +@Entry +@Component +struct ArrayCompV1 { + @State arr: Array = [1, 2, 3]; + + build() { + Column() { + Text(`V1 ${this.arr[0]}`).onClick(() => { + // V1 proxy, which can trigger the refresh of ArrayCompV1 but cannot trigger the refresh of ArrayCompV2. + this.arr[0]++; + }) + // After being transferred to ArrayCompV2, the variable will be wrapped with a proxy of V2. + ArrayCompV2({ arr: this.arr }) + } + .height('100%') + .width('100%') + } +} + +@ComponentV2 +struct ArrayCompV2 { + @Param arr: Array = [1, 2, 3]; + + build() { + Column() { + Text(`V2 ${this.arr[0]}`).onClick(() => { + // V1 and V2 proxy, which can trigger refresh of ArrayCompV1 or ArrayCompV2. + this.arr[0]++; + }) + } + } +} +``` +#### V2->V1 +**Recommended** + +```ts +import { UIUtils } from '@kit.ArkUI'; + +@Entry +@ComponentV2 +struct ArrayCompV2 { + @Local arr: Array = UIUtils.enableV2Compatibility(UIUtils.makeV1Observed([1, 2, 3])); + + build() { + Column() { + Text(`V2 ${this.arr[0]}`).fontSize(20).onClick(() => { + // Click to trigger changes in V2 and synchronize the change to the @ObjectLink of V1. + this.arr[0]++; + }) + ArrayCompV1({ arr: this.arr }) + } + .height('100%') + .width('100%') + } +} + +@Component +struct ArrayCompV1 { + @ObjectLink arr: Array; + + build() { + Column() { + Text(`V1 ${this.arr[0]}`).fontSize(20).onClick(() => { + // Click to trigger the change of V1 and synchronize the change to V2 in a two-way manner. + this.arr[0]++; + }) + } + } +} + +``` +**Not recommended** + +In the following example, **enableV2Compatibility** and **makeV1Observed** are not called, and \@ObjectLink is initialized illegally so that it cannot observe the property changes. +However, because the state variables of V2 are transferred to \@ObjectLink, the refresh in V2 can be triggered. +```ts +@Entry +@ComponentV2 +struct ArrayCompV2 { + @Local arr: Array = [1, 2, 3]; + + build() { + Column() { + Text(`V2 ${this.arr[0]}`).fontSize(20).onClick(() => { + // Click to trigger changes in V2. + this.arr[0]++; + }) + // The data passed to @ObjectLink is not @Observed or makeV1Observed data + // Invalid operation. @ObjectLink cannot observe property changes. + ArrayCompV1({ arr: this.arr }) + } + .height('100%') + .width('100%') + } +} + +@Component +struct ArrayCompV1 { + @ObjectLink arr: Array; + + build() { + Column() { + Text(`V1 ${this.arr[0]}`).fontSize(20).onClick(() => { + // V2 is refreshed while V1 is not. + this.arr[0]++; + }) + } + } +} +``` +### Two-Dimensional Array +#### V1->V2 + +In the following example: +- **makeV1Observed** is used to change the inner array of the two-dimensional array to the state variables of V1. +- When the state variables of V1 are passed to the child component of V2, **enableV2Compatibility** is called to make them observable in V2 and avoid the dual proxy of V1 and V2. + +```ts +import { UIUtils } from '@kit.ArkUI'; + +@ComponentV2 +struct Item { + @Require @Param itemArr: Array; + + build() { + Row() { + ForEach(this.itemArr, (item: string, index: number) => { + Text(`${index}: ${item}`) + }, (item: string) => item + Math.random()) + + Button('@Param push') + .onClick(() => { + this.itemArr.push('Param'); + }) + } + } +} + +@Entry +@Component +struct IndexPage { + @State arr: Array> = + [UIUtils.makeV1Observed(['apple']), UIUtils.makeV1Observed(['banana']), UIUtils.makeV1Observed(['orange'])]; + + build() { + Column() { + ForEach(this.arr, (itemArr: Array) => { + Item({ itemArr: UIUtils.enableV2Compatibility(itemArr) }) + }, (itemArr: Array) => JSON.stringify(itemArr) + Math.random()) + Divider() + Button('@State push two-dimensional array item') + .onClick(() => { + this.arr[0].push('strawberry'); + }) + + Button('@State push array item') + .onClick(() => { + this.arr.push(UIUtils.makeV1Observed(['pear'])); + }) + + Button('@State change two-dimensional array first item') + .onClick(() => { + this.arr[0][0] = 'APPLE'; + }) + + Button('@State change array first item') + .onClick(() => { + this.arr[0] = UIUtils.makeV1Observed(['watermelon']); + }) + } + } +} +``` + +#### V2->V1 + +In the following example: +- **makeV1Observed** is used to change the inner array of the two-dimensional array to the state variables of V1. **enableV2Compatibility** is called to make them observable in V2 and avoid the dual proxy of V1 and V2. +- In V1, \@ObjectLink is used to receive the inner array of the two-dimensional array. Because the inner array is the return value of **makeV1Observed**, the refresh response is normal when **Button('@ObjectLink push')** is clicked. + +```ts +import { UIUtils } from '@kit.ArkUI'; + +@Component +struct Item { + @ObjectLink itemArr: Array; + + build() { + Row() { + ForEach(this.itemArr, (item: string, index: number) => { + Text(`${index}: ${item}`) + }, (item: string) => item + Math.random()) + + Button('@ObjectLink push') + .onClick(() => { + this.itemArr.push('ObjectLink'); + }) + } + } +} + +@Entry +@ComponentV2 +struct IndexPage { + @Local arr: Array> = + UIUtils.enableV2Compatibility(UIUtils.makeV1Observed([UIUtils.makeV1Observed(['apple']), + UIUtils.makeV1Observed(['banana']), UIUtils.makeV1Observed(['orange'])])); + + build() { + Column() { + ForEach(this.arr, (itemArr: Array) => { + Item({ itemArr: itemArr }) + }, (itemArr: Array) => JSON.stringify(itemArr) + Math.random()) + Divider() + Button('@Local push two-dimensional array item') + .onClick(() => { + this.arr[0].push('strawberry'); + }) + + Button('@Local push array item') + .onClick(() => { + this.arr.push(UIUtils.makeV1Observed(['pear'])); + }) + + Button('@Local change two-dimensional array first item') + .onClick(() => { + this.arr[0][0] = 'APPLE'; + }) + + Button('@Local change array first item') + .onClick(() => { + this.arr[0] = UIUtils.makeV1Observed(['watermelon']); + }) + } + } +} +``` + +### Nested Type +#### V1->V2 +The following shows an example of the nested scenario, +which can be summarized as follows: +- \@State can observe only the first-layer changes. To perform in-depth observation, variables should be transferred to \@ObjectLink. +- The change of the second layer of \@State cannot cause the refresh of the current layer. However, the change can be observed by \@ObjectLink and \@Param and triggers the re-render of the associated components. +- \@ObjectLink and \@Param are referenced by the same object. If their properties are changed, other references are refreshed. +- After **enableV2Compatibility** is enabled, V2 has the in-depth observation capability. +- If **enableV2Compatibility** is not called when transferring the object to V2, **Param** cannot observe the object properties. +```ts +// Not recommended. +NestedClassV2({ outer: this.outer }) +``` +A complete example is as follows: +```ts +import { UIUtils } from '@kit.ArkUI'; + +class ArrayItem { + value: number = 0; + + constructor(value: number) { + this.value = value; + } +} + +class Inner { + innerValue: string = 'inner'; + arr: Array; + + constructor(arr: Array) { + this.arr = arr; + } +} + +class Outer { + @Track outerValue: string = 'out'; + @Track inner: Inner; + + constructor(inner: Inner) { + this.inner = inner; + } +} + +@Entry +@Component +struct NestedClassV1 { + // Ensure that each layer uses the state variable of V1. + @State outer: Outer = + UIUtils.makeV1Observed(new Outer( + UIUtils.makeV1Observed(new Inner(UIUtils.makeV1Observed([ + UIUtils.makeV1Observed(new ArrayItem(1)), + UIUtils.makeV1Observed(new ArrayItem(2)) + ]))) + )); + + build() { + Column() { + Text(`@State outer.outerValue can update ${this.outer.outerValue}`) + .fontSize(20) + .onClick(() => { + // @State can observe the first-layer changes. + // Notify @ObjectLink and @Param of the change. + this.outer.outerValue += '!'; + }) + + Text(`@State outer.inner.innerValue cannot update ${this.outer.inner.innerValue}`) + .fontSize(20) + .onClick(() => { + // @State cannot observe the changes at the second layer. + // However, the change will be observed by @ObjectLink and @Param. + this.outer.inner.innerValue += '!'; + }) + // Transfer inner to @ObjectLink to observe the property change of inner. + NestedClassV1ObjectLink({ inner: this.outer.inner }) + // Pass the data for enabling enableV2Compatibility to V2. + NestedClassV2({ outer: UIUtils.enableV2Compatibility(this.outer) }) + } + .height('100%') + .width('100%') + } +} + +@Component +struct NestedClassV1ObjectLink { + @ObjectLink inner: Inner; + + build() { + Text(`@ObjectLink inner.innerValue can update ${this.inner.innerValue}`) + .fontSize(20) + .onClick(() => { + // Trigger refresh. @ObjectLink and @Param are referenced by the same object and @Param is also refreshed. + this.inner.innerValue += '!'; + }) + } +} + +@ComponentV2 +struct NestedClassV2 { + @Require @Param outer: Outer; + + build() { + Column() { + Text(`@Param outer.outerValue can update ${this.outer.outerValue}`) + .fontSize(20) + .onClick(() => { + // The value changes at the first layer can be observed. + this.outer.outerValue += '!'; + }) + Text(`@Param outer.inner.innerValue can update ${this.outer.inner.innerValue}`) + .fontSize(20) + .onClick(() => { + // Changes on the second layer can be obtained. @Param and @ObjectLink are referenced by the same object, which also triggers a refresh. + this.outer.inner.innerValue += '!'; + }) + + Repeat(this.outer.inner.arr) + .each((item: RepeatItem) => { + Text(`@Param outer.inner.arr index: ${item.index} item: ${item.item.value}`) + }) + + Button('@Param push').onClick(() => { + // The observation capability of V2 has been enabled for outer. For new data, the observation capability of V2 is enabled by default. + this.outer.inner.arr.push(UIUtils.makeV1Observed(new ArrayItem(20))); + }) + + Button('@Param change the last Item').onClick(() => { + // The property change of the last array item can be observed. + this.outer.inner.arr[this.outer.inner.arr.length - 1].value++; + }) + } + } +} +``` + +#### V2->V1 +- In the following example, **outer** in **NestedClassV2** calls **UIUtils.enableV2Compatibility**, and **UIUtils.makeV1Observed** is used in each layer. Therefore, **outer** has the in-depth observation capability in V2. +- In V1, only the changes at the first layer can be observed. Therefore, multiple layers of custom components are required, and each layer uses \@ObjectLink to receive data to implement in-depth observation. + +```ts +import { UIUtils } from '@kit.ArkUI'; + +class ArrayItem { + value: number = 0; + + constructor(value: number) { + this.value = value; + } +} + +class Inner { + innerValue: string = 'inner'; + arr: Array; + + constructor(arr: Array) { + this.arr = arr; + } +} + +class Outer { + @Track outerValue: string = 'out'; + @Track inner: Inner; + + constructor(inner: Inner) { + this.inner = inner; + } +} + +@Entry +@ComponentV2 +struct NestedClassV2 { + // Ensure that each layer uses the state variable of V1. + @Local outer: Outer = UIUtils.enableV2Compatibility( + UIUtils.makeV1Observed(new Outer( + UIUtils.makeV1Observed(new Inner(UIUtils.makeV1Observed([ + UIUtils.makeV1Observed(new ArrayItem(1)), + UIUtils.makeV1Observed(new ArrayItem(2)) + ]))) + ))); + + build() { + Column() { + Text(`@Local outer.outerValue can update ${this.outer.outerValue}`) + .fontSize(20) + .onClick(() => { + // The changes at the first layer can be observed. + this.outer.outerValue += '!'; + }) + + Text(`@Local outer.inner.innerValue can update ${this.outer.inner.innerValue}`) + .fontSize(20) + .onClick(() => { + // The changes at the second layer can be observed. + this.outer.inner.innerValue += '!'; + }) + // Transfer inner to @ObjectLink to observe the property change of inner. + NestedClassV1ObjectLink({ inner: this.outer.inner }) + } + .height('100%') + .width('100%') + } +} + +@Component +struct NestedClassV1ObjectLink { + @ObjectLink inner: Inner; + + build() { + Column() { + Text(`@ObjectLink inner.innerValue can update ${this.inner.innerValue}`) + .fontSize(20) + .onClick(() => { + // Trigger the refresh. + this.inner.innerValue += '!'; + }) + NestedClassV1ObjectLinkArray({ arr: this.inner.arr }) + } + } +} + +@Component +struct NestedClassV1ObjectLinkArray { + @ObjectLink arr: Array; + + build() { + Column() { + ForEach(this.arr, (item: ArrayItem) => { + NestedClassV1ObjectLinkArrayItem({ item: item }) + }, (item: ArrayItem, index: number) => { + return item.value.toString() + index.toString(); + }) + + Button('@ObjectLink push').onClick(() => { + this.arr.push(UIUtils.makeV1Observed(new ArrayItem(20))); + }) + + Button('@ObjectLink change the last Item').onClick(() => { + // Observe the property change of the last array item in NestedClassV1ObjectLinkArrayItem. + this.arr[this.arr.length - 1].value++; + }) + } + } +} + +@Component +struct NestedClassV1ObjectLinkArrayItem { + @ObjectLink item: ArrayItem; + + build() { + Text(`@ObjectLink outer.inner.arr item: ${this.item.value}`) + } +} + +``` + + \ No newline at end of file diff --git a/en/application-dev/quick-start/arkts-watch.md b/en/application-dev/quick-start/arkts-watch.md index ecb811ceecee84e61dfbbd0c1bf722644038a935..13aa9f4ab0588e5f03ed53e40111d016bfb2ca8e 100644 --- a/en/application-dev/quick-start/arkts-watch.md +++ b/en/application-dev/quick-start/arkts-watch.md @@ -16,7 +16,7 @@ Before reading this topic, you are advised to read [\@State](./arkts-state.md) t ## Overview -An application can request to be notified whenever the value of the \@Watch decorated variable changes. The \@Watch callback is called when the value change has occurred. \@Watch uses strict equality (===) to determine whether a value is updated in the ArkUI framework. If **false** is returned, the \@Watch callback is triggered. +An application can request to be notified whenever the value of the \@Watch decorated variable changes. The \@Watch callback is called when the value change has occurred. \@Watch uses strict equality (===) to determine whether a value is updated in the ArkUI framework. If **false** is return, the \@Monitor decorated callback is triggered. ## Decorator Description diff --git a/en/application-dev/quick-start/arkts-wrapBuilder.md b/en/application-dev/quick-start/arkts-wrapBuilder.md index 265f7cad1b6942add29b2dc434c552ad6a5a4a6d..f232d90e3467d55ed4904cba5969bae625d88bb2 100644 --- a/en/application-dev/quick-start/arkts-wrapBuilder.md +++ b/en/application-dev/quick-start/arkts-wrapBuilder.md @@ -2,7 +2,7 @@ When you use multiple global @Builder functions in a struct to implement different UI effects, the code maintenance becomes difficult and the page is not neat. In this case, you can use **wrapBuilder** to encapsulate the global @Builder. -Before reading this topic, you are advised to read [\@Builder](./arkts-builder.md). + Before reading this topic, you are advised to read [\@Builder](./arkts-builder.md). > **NOTE** > @@ -25,7 +25,7 @@ function testBuilder() { In the preceding code, **builderArr** is an array consisting of @Builder methods. When each @Builder method is obtained from **ForEach**, the @Builder method cannot be used in the UI method. -To solve this problem, **wrapBuilder** is introduced as the global @Builder encapsulation function. **wrapBuilder** is a template function that accepts a [global \@Builder decorated function](arkts-builder.md#global-custom-builder-function) as its argument and returns a **WrappedBuilder** object, thereby allowing global \@Builder decorated function to be assigned a value and transferred. + To solve this problem, **wrapBuilder** is introduced as the global @Builder encapsulation function. **wrapBuilder** is a template function that accepts a [global \@Builder decorated function](arkts-builder.md#global-custom-builder-function) as its argument and returns a **WrappedBuilder** object, thereby allowing global \@Builder decorated function to be assigned a value and transferred. ## Available APIs @@ -54,12 +54,16 @@ let builderVar: WrappedBuilder<[string, number]> = wrapBuilder(MyBuilder) let builderArr: WrappedBuilder<[string, number]>[] = [wrapBuilder(MyBuilder)] // An array is acceptable. ``` + + ## Constraints **wrapBuilder** only accepts a [global \@Builder decorated function](arkts-builder.md#global-custom-builder-function) as its argument. Of the **WrappedBuilder** object it returns, the **builder** attribute method can be used only inside the struct. + + ## Assigning a Value to a Variable Using the @Builder Method The **MyBuilder** method decorated by @Builder is used as the parameter of **wrapBuilder**, and **wrapBuilder** is assigned to the **globalBuilder** variable, which solves the problem that the @Builder method cannot be used after being assigned to the variable. @@ -166,11 +170,11 @@ struct Parent{ } ``` -## Incorrect Usage +## FAQs ### wrapBuilder Redefinition Failure -After **builderObj** is initialized and defined through **wrapBuilder(MyBuilderFirst)**, if you assign a new value to **builderObj**, **wrapBuilder(MyBuilderSecond)** does not take effect. Only the first defined **wrapBuilder(MyBuilderFirst)** takes effect. +In the same custom component, the same **wrapBuilder** can be initialized only once. In the example, after **builderObj** is initialized through **wrapBuilder(MyBuilderFirst)**, **wrapBuilder(MyBuilderSecond)** does not take effect when a value is assigned to **builderObj** again. ```ts @Builder @@ -197,6 +201,7 @@ struct Index { aboutToAppear(): void { setTimeout(() => { + // wrapBuilder (MyBuilderSecond) does not take effect. this.builderObj.globalBuilder = wrapBuilder(MyBuilderSecond); },1000) } diff --git a/en/application-dev/quick-start/figures/ForEach-StateVarNoRender.PNG b/en/application-dev/quick-start/figures/ForEach-StateVarNoRender.PNG new file mode 100644 index 0000000000000000000000000000000000000000..43151f21d06d2534db7c0a6ddf5ce57799695367 Binary files /dev/null and b/en/application-dev/quick-start/figures/ForEach-StateVarNoRender.PNG differ diff --git a/zh-cn/application-dev/quick-start/figures/LazyForEach-Refresh-Not-Expected-Repair.gif b/en/application-dev/quick-start/figures/LazyForEach-Refresh-Not-Expected-Repair.gif similarity index 100% rename from zh-cn/application-dev/quick-start/figures/LazyForEach-Refresh-Not-Expected-Repair.gif rename to en/application-dev/quick-start/figures/LazyForEach-Refresh-Not-Expected-Repair.gif diff --git a/zh-cn/application-dev/quick-start/figures/LazyForEach-Refresh-Not-Expected.gif b/en/application-dev/quick-start/figures/LazyForEach-Refresh-Not-Expected.gif similarity index 100% rename from zh-cn/application-dev/quick-start/figures/LazyForEach-Refresh-Not-Expected.gif rename to en/application-dev/quick-start/figures/LazyForEach-Refresh-Not-Expected.gif diff --git a/en/application-dev/quick-start/figures/MVVM_index.gif b/en/application-dev/quick-start/figures/MVVM_index.gif index 085d54af0338485a760c6e08409bb247f9824c80..c3b834f063cd737e5079614477fb6b318e54dbc4 100644 Binary files a/en/application-dev/quick-start/figures/MVVM_index.gif and b/en/application-dev/quick-start/figures/MVVM_index.gif differ diff --git a/en/application-dev/quick-start/figures/Repeat-Slide.png b/en/application-dev/quick-start/figures/Repeat-Slide.png index e8772f03148be4616010202d1adf5db8188b199d..411c83f843062d4ba35778c003a3a8945f2d5c53 100644 Binary files a/en/application-dev/quick-start/figures/Repeat-Slide.png and b/en/application-dev/quick-start/figures/Repeat-Slide.png differ diff --git a/en/application-dev/quick-start/figures/Repeat-Update1.png b/en/application-dev/quick-start/figures/Repeat-Update1.png index 77f4f3b6317960f41812f9646cc37aad38378fcb..1bfb1705462a31306cf4c7d31b385d8359f443fb 100644 Binary files a/en/application-dev/quick-start/figures/Repeat-Update1.png and b/en/application-dev/quick-start/figures/Repeat-Update1.png differ diff --git a/en/application-dev/quick-start/figures/Repeat-Update2.png b/en/application-dev/quick-start/figures/Repeat-Update2.png index 104cc2bde123783e2d24b043f1b148baba3f3197..0946425ba5d5e1261f0a62afeae443b88d54393c 100644 Binary files a/en/application-dev/quick-start/figures/Repeat-Update2.png and b/en/application-dev/quick-start/figures/Repeat-Update2.png differ diff --git a/en/application-dev/quick-start/figures/V1V2_mix_usage.png b/en/application-dev/quick-start/figures/V1V2_mix_usage.png new file mode 100644 index 0000000000000000000000000000000000000000..f86d6f08d61f72dd8850304be18b25b4d483f0fc Binary files /dev/null and b/en/application-dev/quick-start/figures/V1V2_mix_usage.png differ diff --git a/en/application-dev/quick-start/figures/zh-cn_image_22989BBB5490.png b/en/application-dev/quick-start/figures/zh-cn_image_22989BBB5490.png new file mode 100644 index 0000000000000000000000000000000000000000..604b6b71780a8714fabc9df5d6da82a3c6a9927c Binary files /dev/null and b/en/application-dev/quick-start/figures/zh-cn_image_22989BBB5490.png differ diff --git a/en/application-dev/quick-start/har-package.md b/en/application-dev/quick-start/har-package.md index cf345feb33e21a584101ccbabbc7ddeb71a60ba2..703cabd4b958ad81e63f5dddcdd141fe6bee5693 100644 --- a/en/application-dev/quick-start/har-package.md +++ b/en/application-dev/quick-start/har-package.md @@ -10,7 +10,10 @@ A Harmony Archive (HAR) is a static shared package that can contain code, C++ li ## Constraints - An HAR can only be referenced as a dependency of an application module. It cannot be installed or run independently on a device. -- An HAR does not support the declaration of the [ExtensionAbility](../application-models/extensionability-overview.md) component in the configuration file, but supports the [UIAbility](../application-models/uiability-overview.md) component.
**NOTE**
If the [startAbility](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) API is used to start the UIAbility in the HAR, the value of **moduleName** in the API parameter must be the module name of the [HAP](hap-package.md) or [HSP](in-app-hsp.md) that depends on the HAR. +- An HAR does not support the declaration of the [ExtensionAbility](../application-models/extensionability-overview.md) component in the configuration file, but supports the [UIAbility](../application-models/uiability-overview.md) component. +> **NOTE** +> +> If the [startAbility](../reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) API is used to start the UIAbility in the HAR, the value of **moduleName** in the API parameter must be the module name of the [HAP](hap-package.md) or [HSP](in-app-hsp.md) that depends on the HAR. - An HAR does not support the declaration of the [pages](./module-configuration-file.md#pages) tag in the configuration file. Still, it can include pages, which can be redirected through a [named route](../ui/arkts-routing.md#named-route). - An HAR does not support referencing resources in the **AppScope** folder. This is because the content in the **AppScope** folder is not packaged into the HAR during building. - An HAR can depend on other HARs, but does not support cyclic dependency or dependency transfer. @@ -290,9 +293,9 @@ struct Index { ``` ## Building an HAR -HAR can be used as a second-party or third-party library for other applications. To protect code assets, you are advised to [enable code obfuscation](../arkts-utils/source-obfuscation.md). +HAR can be used as a second-party or third-party library for other applications. To protect code assets, you are advised to [enable code obfuscation](../arkts-utils/source-obfuscation-guide.md). -To better protect your source code, enable obfuscation for the HAR so that DevEco Studio compiles, obfuscates, and compresses code during HAR building. +After [code obfuscation](../arkts-utils/source-obfuscation.md) is enabled, DevEco Studio compiles, obfuscates, and compresses code when building HARs to protect code assets. The obfuscation capability is enabled by default for the HAR module. When the compilation module is release, simple code obfuscation is automatically performed for the HAR module of API version 10 or later. **Since DevEco Studio 5.0.3.600, the code obfuscation is disabled by default when a project is created.** You can enable this feature by setting **enable** in the **ruleOptions** field in the **build-profile.json5** file of the HAR module. For details, see [Code Obfuscation](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V13/ide-build-obfuscation-V13). The configuration is as follows: @@ -333,7 +336,7 @@ The obfuscation capability is enabled by default for the HAR module. When the co > >Enable this configuration when using **Sendable** in an HAR. -> **Restrictions** +> **Constraints** > >When depend on TS HAR, the ArkUI component in TS HAR cannot be referenced. diff --git a/en/application-dev/quick-start/in-app-hsp.md b/en/application-dev/quick-start/in-app-hsp.md index e80dd8e1bb5e3b64e33556a6d1549ac525832bdd..cdee2a211d14f084b6cf97127cb498133550b716 100644 --- a/en/application-dev/quick-start/in-app-hsp.md +++ b/en/application-dev/quick-start/in-app-hsp.md @@ -5,7 +5,7 @@ A Harmony Shared Package (HSP) is a dynamic shared package that can contain code > > In-app HSP: a type of HSP that is closely coupled with an application bundle name (**bundleName**) during compilation and can be used only by the specified application. > -> [Integrated HSP](integrated-hsp.md): a type of HSP that is not coupled with any specific application bundle name during the build and release processes and whose bundle name can be automatically replaced by the toolchain with the host application bundle name. +> [Integrated HSP](integrated-hsp.md): a type of HSP that is not coupled with specific application bundle names during building and publishing. The toolchain can automatically replace the bundle name of the integrated HSP with that of the host application and generate a new HSP as the installation package of the host application. The new HSP package also belongs to the in-app HSP. ## Use Scenarios - By storing code and resource files shared by multiple HAPs/HSPs in one place, the HSP significantly improves the reusability and maintainability of the code and resource files. Better yet, because only one copy of the HSP code and resource files is retained during building and packaging, the size of the application package is effectively controlled. @@ -36,13 +36,13 @@ MyApplication │ │ └── main │ │ ├── ets │ │ │ └── pages -│ │ │ └── index.ets -│ │ ├── resources -│ │ └── module.json5 -│ ├── oh-package.json5 -│ ├── index.ets -│ └── build-profile.json5 // Module-level configuration file -└── build-profile.json5 // Project-level configuration file +│ │ │ └── index.ets // Page file of the library module +│ │ ├── resources // Resources of the library module +│ │ └── module.json5 // Configuration file of the library module +│ ├── oh-package.json5 // Module-level configuration file +│ ├── index.ets // Entry file +│ └── build-profile.json5 // Module-level configuration file +└── build-profile.json5 // Project-level configuration file ``` ## Developing an HSP @@ -163,8 +163,6 @@ In the entry point file **index.ets**, declare the APIs to be exposed. export { ResManager } from './src/main/ets/ResManager'; ``` - - ## Using an HSP You can reference APIs in an HSP and implement page redirection in the HSP through page routing. diff --git a/en/application-dev/quick-start/module-configuration-file.md b/en/application-dev/quick-start/module-configuration-file.md index 72da34fdda71bdefa5d7ee1030de8d21534facb7..b76a92774e652f77562154021324751a597201b5 100644 --- a/en/application-dev/quick-start/module-configuration-file.md +++ b/en/application-dev/quick-start/module-configuration-file.md @@ -116,10 +116,10 @@ As shown above, the **module.json5** file contains several tags. | -------- | -------- | -------- | -------- | | name | Name of the module. This name must be unique in the entire application. The value must comply with the following rules:
- Starts with a letter and consists of letters, digits, underscores (_).
- The maximum length is 31 bytes.
This name can be changed during application updates. However, if it is changed, directories related to the module must be migrated. You can use the [file operation API](../reference/apis-core-file-kit/js-apis-file-fs.md#fscopydir10) for migration.| String| No| | type | Type of the module. The options are as follows:
- **entry**: main module of the application.
- **feature**: feature module of the application.
- **har**: static shared module.
- **shared**: dynamic shared module.| String| No| -| srcEntry | Code path of the module. The value is a string with a maximum of 127 bytes.| String| Yes (initial value: left empty)| -| description | Description of the module. The value is a string with a maximum of 255 bytes. It can be a resource reference.| String| Yes (initial value: left empty)| +| srcEntry | Code path of the entry UIAbility or ExtensionAbility of the module. The value must point to the same UIAbility or ExtensionAbility as the **mainElement** field. The value is a string of a maximum of 127 bytes.| String| Yes (initial value: left empty)| +| description | Description of the module, used to describe the module functions. The value is a string of a maximum of 255 bytes. It can be a resource reference.| String| Yes (initial value: left empty)| | process | Process name of the module. The value is a string with a maximum of 31 bytes. If **process** is configured under **HAP**, all UIAbilities, DataShareExtensionAbilities, and ServiceExtensionAbilities of the module will run in the specified process.
**NOTE**
The [device-specific application privileges](../../device-dev/subsystems/subsys-app-privilege-config-guide.md#device-specific-application-privileges) takes effect, but the third-party application configuration does not take effect.| String| Yes (initial value: value of **bundleName** under **app** in the **app.json5** file)| -| mainElement | Name of the entry UIAbility or ExtensionAbility of the module. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| +| mainElement | Name of the entry UIAbility or ExtensionAbility of the module. The value must point to the same UIAbility or ExtensionAbility as the **srcEntry** field. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| | [deviceTypes](#devicetypes) | Types of the devices on which the module can run.
**NOTE**
When there are multiple modules, the configuration of each module can be different, but the required device type must be included to ensure the proper running.| String array| No| | deliveryWithInstall | Whether the HAP of the module is installed together with the application.
- **true**: The HAP of the module is installed together with the application.
- **false**: The HAP of the module is not installed together with the application.| Boolean| No| | installationFree | Whether the module supports the installation-free feature.
- **true**: The module supports the installation-free feature and meets installation-free constraints.
- **false**: The module does not support the installation-free feature.
**NOTE**
If [bundleType](./app-configuration-file.md#tags-in-the-configuration-file) is set to **atomicService**, set this tag to **true**. Otherwise, set this tag to false.| Boolean| No| @@ -138,7 +138,7 @@ As shown above, the **module.json5** file contains several tags. | [proxyData](#proxydata) | List of data proxies provided by the module.| Object array| Yes (initial value: left empty)| | isolationMode | Multi-process configuration of the module. The options are as follows:
- **nonisolationFirst**: The module preferentially runs in a non-independent process.
- **isolationFirst**: The module preferentially runs in an independent process.
- **isolationOnly**: The module runs only in an independent process.
- **nonisolationOnly**: The module runs only in a non-independent process.|String|Yes (initial value: **nonisolationFirst**)| | generateBuildHash |Whether the hash value of the HAP or HSP is generated by the packing tool. The hash value (if any) is used to determine whether the application needs to be updated when the system is updated in OTA mode but the **versionCode** value of the application remains unchanged.
This tag is enabled only when the **generateBuildHash** tag in the [app.json5](./app-configuration-file.md) file is **false**.
**NOTE**
This tag applies only to system applications.|Boolean|Yes (initial value: **false**)| -| compressNativeLibs | During HAP packaging, whether the **libs** libraries are packaged to HAP after being compressed.
- **true**: The **libs** libraries are packaged in the HAP file after being compressed.
- **false**: The **libs** libraries are stored without being compressed.
During application installation, whether the **libs** library needs to be decompressed. (Since API version 16, this field is supported. In earlier versions, the **libs** library is decompressed by default.)
- **true**: The **libs** library is decompressed.
- **false**: The **libs** library is not decompressed.| Boolean| Yes (During HAP packaging, initial value: **false**; during application installation, initial value: **true**)| +| compressNativeLibs | During HAP packaging, whether the **libs** libraries are packaged to HAP after being compressed.
- **true**: The **libs** libraries are packaged in the HAP file after being compressed.
- **false**: The **libs** libraries are stored without being compressed.| Boolean| Yes (During HAP packaging, initial value: **false**;| | libIsolation | Whether to save the .so files of the current HAP to a separate folder. This is intended to avoid .so file conflicts between HAPs.
- **true**: The .so files of the current HAP are stored in a separate folder (named after the module) in the **libs** directory.
- **false**: The .so files of the current HAP are directly stored in the **libs** directory.| Boolean| Yes (initial value: **false**)| | fileContextMenu | Context menu of the current HAP. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| | querySchemes | URL schemes that the current application can query for redirection. This tag is only available for the entry modules. A maximum of 50 URL schemes can be configured, with each containing a maximum of 128 bytes.| String array| Yes (initial value: left empty)| @@ -157,7 +157,7 @@ As shown above, the **module.json5** file contains several tags. | Smart TV| tv | - | | Smart watch| wearable | Watch that provides call features.| | Head unit| car | - | -| 2in1 | 2in1 | Two-in-one device that allows for interactions with a touchscreen, keyboard, and mouse device.| +| PC/2-in-1 device| 2in1 | PC, mainly used for multi-window and multi-task interactions, and keyboard and mouse operations. It fully showcases the device productivity. In the OpenHarmony topics, "2-in-1" indicates PC/2-in-1 device.| | Default device| default | Device that provides full access to system capabilities.| @@ -312,7 +312,7 @@ The **abilities** tag represents the UIAbility configuration of the module, whic | name | Name of the UIAbility. This name must be unique in the entire application. The value is a string with a maximum of 127 bytes.| String| No| | srcEntry | Code path of the entry UIAbility. The value is a string with a maximum of 127 bytes.| String| No| | [launchType](../application-models/uiability-launch-type.md) | Launch type of the UIAbility. The options are as follows:
- **multiton**: A UIAbility instance is created each time the UIAbility is started.
- **singleton**: A UIAbility instance is created only when the UIAbility is started for the first time.
- **specified**: You can determine whether to create a UIAbility instance when the application is running.
- **standard**: original name of **multiton**. The effect is the same as that multition mode.| String| Yes (initial value: **"singleton"**)| -| description | Description of the UIAbility. The value is a string with a maximum of 255 bytes. It must be a resource index to support multiple languages.| String| Yes (initial value: left empty)| +| description | Description of the UIAbility component, used to describe the component functions. The value is a string with a maximum of 255 bytes. It must be a resource index to support multiple languages.| String| Yes (initial value: left empty)| | icon | [Icon](../application-models/application-component-configuration-stage.md#generation-mechanism) of the UIAbility component. The value is the index of the icon resource file.| String| Yes (initial value: left empty)| | label | [Name](../application-models/application-component-configuration-stage.md#generation-mechanism) of the UIAbility component displayed to users. The resource index of the name must be used to support multiple languages. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| | permissions | Permissions required for another application to access the UIAbility.
The value is generally in the reverse domain name notation and contains a maximum of 255 bytes. It is an array of predefined permission names.| String array| Yes (initial value: left empty)| @@ -321,7 +321,7 @@ The **abilities** tag represents the UIAbility configuration of the module, whic | continuable | Whether the UIAbility can be continued on another device.
- **true**: The UIAbility can be continued on another device.
- **false**: The UIAbility cannot be continued on another device.| Boolean| Yes (initial value: **false**)| | [skills](#skills) | A set of [wants](../application-models/want-overview.md) that can be received by the UIAbility or ExtensionAbility.
Configuration rules:
- For HAPs of the entry type, you can configure multiple **skills** attributes with the entry capability for an application. (A **skills** attribute with the entry capability is the one that has **ohos.want.action.home** and **entity.system.home** configured.)
- For HAPs of the feature type, you can configure the **skills** attribute with the entry capability for an application, but not for a service.| Object array| Yes (initial value: left empty)| | backgroundModes | Continuous tasks of the UIAbility.
Continuous tasks are classified into the following types:
- **dataTransfer**: data transfer through the network or peer device, such as download, backup, and share
- **audioPlayback**: audio playback
- **audioRecording**: audio recording
- **location**: location and navigation
- **bluetoothInteraction**: Bluetooth scanning, connection, and transmission (wearables)
- **multiDeviceConnection**: multi-device connection
- **taskKeeping**: computing| String array| Yes (initial value: left empty)| -| [startWindow](#startwindow)| Profile resource of the UIAbility startup page. The value is a string with a maximum of 255 bytes.| String| Yes (initial value: left empty)| +| [startWindow](#startwindow)| Profile resource of the UIAbility startup page. The value is a string with a maximum of 255 bytes. If this field is set, the **startWindowIcon** and **startWindowBackground** fields do not take effect.| String| Yes (initial value: left empty)| | startWindowIcon | Index to the icon file of the UIAbility startup page. The value is a string with a maximum of 255 bytes.| String| No| | startWindowBackground | Index to the background color resource file of the UIAbility startup page. The value is a string with a maximum of 255 bytes.
Example: **$color:red**.| String| No| | removeMissionAfterTerminate | Whether to remove the relevant mission from the mission list after the UIAbility is destroyed.
- **true**: Remove the relevant mission from the mission list after the UIAbility is destroyed.
- **false**: Do not remove the relevant mission from the task mission list after the UIAbility is destroyed.| Boolean| Yes (initial value: **false**)| @@ -376,6 +376,7 @@ Example of the **abilities** structure: "voip", "taskKeeping" ], + "startWindow": "$profile:start_window", "startWindowIcon": "$media:icon", "startWindowBackground": "$color:red", "removeMissionAfterTerminate": true, @@ -425,8 +426,8 @@ The **skills** tag represents the feature set of [wants](../application-models/w | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | -| scheme | Scheme of the URI, such as HTTP, HTTPS, file, and FTP.
**NOTE**
This field is case-insensitive when it is used for implicit Want matching since API 16.| String| Yes when only **type** is set in **uris** (initial value: left empty)| -| host | Host address of the URI. This field is valid only when **scheme** is set. Common methods:
- domain name, for example, **example.com**.
- IP address, for example, **10.10.10.1**.
**NOTE**
This field is case-insensitive when it is used for implicit Want matching since API 16.| String| Yes (initial value: left empty)| +| scheme | Scheme of the URI, such as HTTP, HTTPS, file, and FTP.
**NOTE**
This field is case-insensitive when it is used for implicit Want matching since API version 18.| String| Yes when only **type** is set in **uris** (initial value: left empty)| +| host | Host address of the URI. This field is valid only when **scheme** is set. Common methods:
- domain name, for example, **example.com**.
- IP address, for example, **10.10.10.1**.
**NOTE**
This field is case-insensitive when it is used for implicit Want matching since API version 18.| String| Yes (initial value: left empty)| | port | Port number of the URI. For example, the default HTTP port number is 80, the default HTTPS port number is 443, and the default FTP port number is 21. This field is valid only when both **scheme** and **host** are set.| String| Yes (initial value: left empty)| | path \| pathStartWith \| pathRegex | Path of the URI. **path**, **pathStartWith**, and **pathRegex** represent different matching modes between the paths in the URI and the want. Set any one of them as needed. **path** indicates full matching, **pathStartWith** indicates prefix matching, and **pathRegex** indicates regular expression matching. This field is valid only when both **scheme** and **host** are set.| String| Yes (initial value: left empty)| | type | Data type that matches the want. The value complies with the Multipurpose Internet Mail Extensions (MIME) and [UniformDataType](../reference/apis-arkdata/js-apis-data-uniformTypeDescriptor.md) type specifications. This field can be configured together with **scheme** or be configured separately.| String| Yes (initial value: left empty)| @@ -478,10 +479,10 @@ The **extensionAbilities** tag represents the configuration of ExtensionAbilitie | -------- | -------- | -------- | -------- | | name | Name of the ExtensionAbility. This name must be unique in the entire application. The value is a string with a maximum of 127 bytes.| String| No| | srcEntry | Code path of the ExtensionAbility. The value is a string with a maximum of 127 bytes.| String| No| -| description | Description of the ExtensionAbility. The value is a string with a maximum of 255 bytes. It can be a resource index to support multiple languages.| String| Yes (initial value: left empty)| +| description | Description of the ExtensionAbility component, used to describe the component functions. The value is a string with a maximum of 255 bytes. It can be a resource index to support multiple languages.| String| Yes (initial value: left empty)| | icon | Icon of the ExtensionAbility. The value is the index of the icon resource file. If **ExtensionAbility** is set to **MainElement** of the current module, this field is mandatory.| String| Yes (initial value: left empty)| | label | Name of the ExtensionAbility displayed to users. The value must be a resource index to support multiple languages. It contains a maximum of 255 bytes. If **ExtensionAbility** is set to **MainElement** of the current module, this field is mandatory and its value must be unique in the application.| String| Yes (initial value: left empty)| -| type | Type of the ExtensionAbility. The options are as follows:
- **form**: ExtensionAbility of a widget.
- **workScheduler**: ExtensionAbility of a deferred task.
- **inputMethod**: ExtensionAbility of an input method.
- **service**: service component running in the background.
- **accessibility**: ExtensionAbility of an accessibility feature.
- **fileAccess**: ExtensionAbility for public data access, allowing files and folders to be provided for file management applications to display.
- **dataShare**: ExtensionAbility for data sharing.
- **staticSubscriber**: ExtensionAbility for static broadcast.
- **wallpaper**: ExtensionAbility of the wallpaper.
- **backup**: ExtensionAbility for data backup.
- **window**: ExtensionAbility of a window. This type of ExtensionAbility creates a window during startup for which you can develop the GUI. The GUI you develop is combined with the windows of other applications through the **UIExtensionComponent**.
- **thumbnail**: ExtensionAbility for obtaining file thumbnails. You can provide thumbnails for files of customized file types.
- **preview**: ExtensionAbility for preview. This type of ExtensionAbility can parse the file and display it in a window. You can combine the window with other application windows.
- **print**: ExtensionAbility for the print framework.
- **push**: ExtensionAbility for the push service.
- **driver**: ExtensionAbility for the driver framework.
- **remoteNotification**: ExtensionAbility for remote notifications.
- **remoteLocation**: ExtensionAbility for remote location.
- **voip**: ExtensionAbility for VoIP calls.
- **action**: ExtensionAbility for custom service operations, which provides custom service operation templates based on UIExtension.
- **adsService**: ExtensionAbility for the ad service, which provides the ad service framework.
- **embeddedUI**: embedded UI extension, which allows for UI embedding across processes.
- **insightIntentUI**: APIs that enable applications to be called by Celia intents so as to be displayed in windows.
- **ads**: ExtensionAbility for the ad service, which is used with the AdComponent to display the ad page in other applications. This option is only available for device manufacturers.
- **photoEditor**: ExtensionAbility for the image editing service, which provides an image editing service template based on UIExtension.
- **appAccountAuthorization**: ExtensionAbility for application account authorization extension, which is used to process account authorization requests, for example, account login authorization.
- **autoFill/password**: ExtensionAbility for automatically filling in usernames and passwords.
- **hms/account**: ExtensionAbility for application account management.
- **sysDialog/atomicServicePanel**: ExtensionAbility that provides the basic capability for building an atomic service panel. It is implemented based on UIExtensionAbility.
- **sysDialog/userAuth**: ExtensionAbility for local user authentication.
- **sysDialog/common**: ExtensionAbility for common dialog boxes.
- **sysDialog/power**: ExtensionAbility for the shutdown and restart dialog boxes.
- **sysDialog/print**: ExtensionAbility for the print modals.
- **sysDialog/meetimeCall**: ExtensionAbility for MeeTime calls.
- **sysDialog/meetimeContact**: ExtensionAbility for MeeTime contacts.
- **sysPicker/meetimeMessage**: ExtensionAbility for MeeTime messages.
- **sysPicker/meetimeContact**: ExtensionAbility for the MeeTime contact list.
- **sysPicker/meetimeCallLog**: ExtensionAbility for the MeeTime call history.
- **sysPicker/share**: ExtensionAbility for sharing.
- **sysPicker/mediaControl**: ExtensionAbility for media control.
- **sysPicker/photoPicker**: ExtensionAbility that allows a third-party application to use the corresponding UIExtensionType to open the gallery photo picker.
- **sysPicker/filePicker**: ExtensionAbility for file download dialog boxes.
- **sysPicker/audioPicker**: ExtensionAbility for the audio management dialog box.
- **sysPicker/photoEditor**: ExtensionAbility for the photo editor.
- **sys/commonUI**: non-common ExtensionAbility, which provides embedded display or dialog boxes closely related to service attributes.
- **autoFill/smart**: ExtensionAbility for scenario-specific autofill services.
- **uiService**: ExtensionAbility for pop-up window service, which creates a window during the startup and supports bidirectional communication.
- **statusBarView**: ExtensionAbility for one-step access.
- **recentPhoto**: ExtensionAbility for recommended recent photos.
- **fence**: ExtensionAbility for geofencing.
- **callerInfoQuery**: ExtensionAbility for enterprise contacts.
- **assetAcceleration**: ExtensionAbility for resource pre-download.
- **formEdit**: ExtensionAbility for widget editing.
**NOTE**
For **service**, **adsService**, **sys/commonUI**, **fileAccess**, **sysDialog**, **sysPicker**, **dataShare**, and **uiService** types, this configuration does not take effect in third-party applications but in system applications. | String| No| +| type | Type of the ExtensionAbility. The options are as follows:
- **form**: ExtensionAbility of a widget.
- **workScheduler**: ExtensionAbility of a deferred task.
- **inputMethod**: ExtensionAbility of an input method.
- **service**: service component running in the background.
- **accessibility**: ExtensionAbility of an accessibility feature.
- **fileAccess**: ExtensionAbility for public data access, allowing files and folders to be provided for file management applications to display.
- **dataShare**: ExtensionAbility for data sharing.
- **staticSubscriber**: ExtensionAbility for static broadcast.
- **wallpaper**: ExtensionAbility of the wallpaper.
- **backup**: ExtensionAbility for data backup.
- **window**: ExtensionAbility of a window. This type of ExtensionAbility creates a window during startup for which you can develop the GUI. The GUI you develop is combined with the windows of other applications through the **UIExtensionComponent**.
- **thumbnail**: ExtensionAbility for obtaining file thumbnails. You can provide thumbnails for files of customized file types.
- **preview**: ExtensionAbility for preview. This type of ExtensionAbility can parse the file and display it in a window. You can combine the window with other application windows.
- **print**: ExtensionAbility for the print framework.
- **push**: ExtensionAbility for the push service.
- **driver**: ExtensionAbility for the driver framework.
- **remoteNotification**: ExtensionAbility for remote notifications.
- **remoteLocation**: ExtensionAbility for remote location.
- **voip**: ExtensionAbility for VoIP calls.
- **action**: ExtensionAbility for custom service operations, which provides custom service operation templates based on UIExtension.
- **adsService**: ExtensionAbility for the ad service, which provides the ad service framework.
- **embeddedUI**: embedded UI extension, which allows for UI embedding across processes.
- **insightIntentUI**: APIs that enable applications to be called by Celia intents so as to be displayed in windows.
- **ads**: ExtensionAbility for the ad service, which is used with the AdComponent to display the ad page in other applications. This option is only available for device manufacturers.
- **photoEditor**: ExtensionAbility for the image editing service, which provides an image editing service template based on UIExtension.
- **appAccountAuthorization**: ExtensionAbility for application account authorization extension, which is used to process account authorization requests, for example, account login authorization.
- **autoFill/password**: ExtensionAbility for automatically filling in usernames and passwords.
- **hms/account**: ExtensionAbility for application account management.
- **sysDialog/atomicServicePanel**: ExtensionAbility that provides the basic capability for building an atomic service panel. It is implemented based on UIExtensionAbility.
- **sysDialog/userAuth**: ExtensionAbility for local user authentication.
- **sysDialog/common**: ExtensionAbility for common dialog boxes.
- **sysDialog/power**: ExtensionAbility for the shutdown and restart dialog boxes.
- **sysDialog/print**: ExtensionAbility for the print modals.
- **sysDialog/meetimeCall**: ExtensionAbility for MeeTime calls.
- **sysDialog/meetimeContact**: ExtensionAbility for MeeTime contacts.
- **sysPicker/meetimeMessage**: ExtensionAbility for MeeTime messages.
- **sysPicker/meetimeContact**: ExtensionAbility for the MeeTime contact list.
- **sysPicker/meetimeCallLog**: ExtensionAbility for the MeeTime call history.
- **sysPicker/share**: ExtensionAbility for sharing.
- **sysPicker/mediaControl**: ExtensionAbility for media control.
- **sysPicker/photoPicker**: ExtensionAbility that allows a third-party application to use the corresponding UIExtensionType to open the gallery photo picker.
- **sysPicker/filePicker**: ExtensionAbility for file download dialog boxes.
- **sysPicker/audioPicker**: ExtensionAbility for the audio management dialog box.
- **sysPicker/photoEditor**: ExtensionAbility for the photo editor.
- **sys/commonUI**: non-common ExtensionAbility, which provides embedded display or dialog boxes closely related to service attributes.
- **autoFill/smart**: ExtensionAbility for scenario-specific autofill services.
- **uiService**: ExtensionAbility for pop-up window service, which creates a window during the startup and supports bidirectional communication.
- **statusBarView**: ExtensionAbility for one-step access.
- **recentPhoto**: ExtensionAbility for recommended recent photos.
- **fence**: ExtensionAbility for geofencing.
- **callerInfoQuery**: ExtensionAbility for enterprise contacts.
- **assetAcceleration**: ExtensionAbility for resource pre-download.
- **formEdit**: ExtensionAbility for widget editing.
- **distributed**: ExtensionAbility for distributed extension.
**NOTE**
For **service**, **adsService**, **staticSubscriber**, **window**, **sys/commonUI**, **fileAccess**, **sysDialog**, **sysPicker**, **dataShare**, and **uiService** types, this configuration does not take effect in third-party applications but in system applications. | String| No| | permissions | Permissions required for another application to access the ExtensionAbility.
The value is generally in the reverse domain name notation and contains a maximum of 255 bytes. It is an array of [predefined permission names](../security/AccessToken/app-permissions.md).| String array| Yes (initial value: left empty)| | readPermission | Permission required for reading data in the ExtensionAbility. The value is a string with a maximum of 255 bytes. This field is available only when the type of the ExtensionAbility is set to **dataShare**.| String| Yes (initial value: left empty)| | writePermission | Permission required for writing data to the ExtensionAbility. The value is a string with a maximum of 255 bytes. This field is available only when the type of the ExtensionAbility is set to **dataShare**.| String| Yes (initial value: left empty)| @@ -1136,8 +1137,8 @@ The root node of the file is **fileContextMenu**, which is an object array and i | Name| Description| Data Type| Initial Value Allowed| | -------- | -------- | -------- | -------- | | menuKind | Condition in which the context menu is displayed. The options are as follows:
-: blank area
- 1: file
- 2: folder
- 3: file and folder| Number| No| -| menuRule | Operations that can trigger context menu. The options are as follows:
- single: Single file or folder is selected.
- multi: Multiple files or folders are selected.
- both: Both.| String| No (This attribute is read when **menuKind** is set to **1** or **2**.) | -| fileSupportType | Supported types of files. The context item is displayed when the selected file list contains files of these types.
When the value is set to *, the **fileNotSupportType** field is read.
When the value is left empty, no processing is performed.| String array| No (This attribute is read when **menuKind** is set to **1**.) | +| menuRule | Operations that can trigger context menu. The options are as follows:
- single: Single file or folder is selected.
- multi: Multiple files or folders are selected.
- both: Both.| String| No (This attribute is read when **menuKind** is set to **1** or **2**.)| +| fileSupportType | Supported types of files. The context item is displayed when the selected file list contains files of these types.
When the value is set to *, the **fileNotSupportType** field is read.
When the value is left empty, no processing is performed.| String array| No (This attribute is read when **menuKind** is set to **1**.)| | fileNotSupportType | Types of files not supported. The context item is not displayed when the selected file list contains files of these types.
This attribute is read only when **menuKind** is set to **1** and **fileSupportType** is set to *.| String array| Yes (initial value: left empty)| Example of the **menu.json** file in the **resources/base/profile** directory: @@ -1189,7 +1190,7 @@ After a context menu is registered, the **More** option of the menu, when clicke ## startWindow -This tag points to a profile resource and is used to define the configuration file **start_window.json** of the UIAbility startup page in **resources/base/profile**. +This tag points to a profile resource and is used to define the configuration file **start_window.json** of the UIAbility startup page in **resources/base/profile**. If this field is set, the **startWindowIcon** and **startWindowBackground** fields do not take effect. **Table 29** startWindow configuration diff --git a/en/application-dev/quick-start/properly-use-state-management-to-develope.md b/en/application-dev/quick-start/properly-use-state-management-to-develope.md index a1128d2f4dea62295bd843c741b077128773c9b3..9473ae49da630b45df439287bfff04259805438a 100644 --- a/en/application-dev/quick-start/properly-use-state-management-to-develope.md +++ b/en/application-dev/quick-start/properly-use-state-management-to-develope.md @@ -234,7 +234,7 @@ struct SpecialImage { return 1; } build() { - Image($r('app.media.icon')) // Use app.media.app_icon since API version 12. + Image($r('app.media.icon')) // 'app.media.icon' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed. .width(this.uiStyle.imageWidth) .height(this.uiStyle.imageHeight) .margin({ top: 20 }) @@ -246,7 +246,7 @@ struct SpecialImage { } } @Component -struct CompA { +struct PageChild { @ObjectLink uiStyle: UIStyle // The following function is used to display whether the component is rendered. private isRenderColumn() : number { @@ -272,7 +272,7 @@ struct CompA { }) Stack() { Column() { - Image($r('app.media.icon')) // Use app.media.app_icon since API version 12. + Image($r('app.media.icon')) // 'app.media.icon' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed. .opacity(this.uiStyle.alpha) .scale({ x: this.uiStyle.scaleX, @@ -351,7 +351,7 @@ struct Page { @State uiStyle: UIStyle = new UIStyle(); build() { Stack() { - CompA({ + PageChild({ uiStyle: this.uiStyle }) } @@ -435,7 +435,7 @@ struct SpecialImage { return 1; } build() { - Image($r('app.media.icon')) // Use app.media.app_icon since API version 12. + Image($r('app.media.icon')) // 'app.media.icon' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed. .width(this.needRenderImage.imageWidth) // Use this.needRenderImage.xxx. .height(this.needRenderImage.imageHeight) .margin({top:20}) @@ -447,7 +447,7 @@ struct SpecialImage { } } @Component -struct CompA { +struct PageChild { @ObjectLink uiStyle: UIStyle; @ObjectLink needRenderTranslate: NeedRenderTranslate; // Receive the newly defined instance of the NeedRenderxxx class from its parent component. @ObjectLink needRenderFontSize: NeedRenderFontSize; @@ -481,7 +481,7 @@ struct CompA { }) Stack() { Column() { - Image($r('app.media.icon')) // Use app.media.app_icon since API version 12. + Image($r('app.media.icon')) // 'app.media.icon' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed. .opacity(this.needRenderAlpha.alpha) .scale({ x: this.needRenderScale.scaleX, // Use this.needRenderXxx.xxx. @@ -570,7 +570,7 @@ struct Page { @State uiStyle: UIStyle = new UIStyle(); build() { Stack() { - CompA({ + PageChild({ uiStyle: this.uiStyle, needRenderTranslate: this.uiStyle.needRenderTranslate, // Pass the needRenderxxx class to the child component. needRenderFontSize: this.uiStyle.needRenderFontSize, @@ -629,7 +629,7 @@ struct SpecialImage { return 1; } build() { - Image($r('app.media.icon')) // Use app.media.app_icon since API version 12. + Image($r('app.media.icon')) // 'app.media.icon' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed. .width(this.uiStyle.imageWidth) .height(this.uiStyle.imageHeight) .margin({ top: 20 }) @@ -641,7 +641,7 @@ struct SpecialImage { } } @Component -struct CompA { +struct PageChild { @ObjectLink uiStyle: UIStyle // The following function is used to display whether the component is rendered. private isRenderColumn() : number { @@ -667,7 +667,7 @@ struct CompA { }) Stack() { Column() { - Image($r('app.media.icon')) // Use app.media.app_icon since API version 12. + Image($r('app.media.icon')) // 'app.media.icon' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed. .opacity(this.uiStyle.alpha) .scale({ x: this.uiStyle.scaleX, @@ -746,7 +746,7 @@ struct Page { @State uiStyle: UIStyle = new UIStyle(); build() { Stack() { - CompA({ + PageChild({ uiStyle: this.uiStyle }) } @@ -1185,7 +1185,8 @@ struct MyComponent { aboutToAppear() { for (let i = 0; i <= 9; i++) { - this.data.pushData(new StringData(`Click to add ${i}`, $r('app.media.icon'))); // Use app.media.app_icon since API version 12. + // 'app.media.icon' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed. + this.data.pushData(new StringData(`Click to add ${i}`, $r('app.media.icon'))); } } @@ -1322,7 +1323,8 @@ struct MyComponent { aboutToAppear() { for (let i = 0; i <= 9; i++) { - this.data.pushData(new StringData(`Click to add ${i}`, $r('app.media.icon'))); // Use app.media.app_icon since API version 12. + // 'app.media.icon' is only an example. Replace it with the actual one in use. Otherwise, the imageSource instance fails to be created, and subsequent operations cannot be performed. + this.data.pushData(new StringData(`Click to add ${i}`, $r('app.media.icon'))); } } @@ -1371,10 +1373,10 @@ Frequently seen in applications, the combination of object arrays and [ForEach]( ```typescript @Observed -class StyleList extends Array { +class StyleList extends Array { }; @Observed -class TextStyle { +class TextStyles { fontSize: number; constructor(fontSize: number) { @@ -1387,7 +1389,7 @@ struct Page { @State styleList: StyleList = new StyleList(); aboutToAppear() { for (let i = 15; i < 50; i++) - this.styleList.push(new TextStyle(i)); + this.styleList.push(new TextStyles(i)); } build() { Column() { @@ -1400,7 +1402,7 @@ struct Page { console.log("change font size"); }) List() { - ForEach(this.styleList, (item: TextStyle) => { + ForEach(this.styleList, (item: TextStyles) => { ListItem() { Text("Hello World") .fontSize(item.fontSize) @@ -1420,10 +1422,10 @@ The items generated in **ForEach** are constants. This means that their value ch ```typescript @Observed -class StyleList extends Array { +class StyleList extends Array { }; @Observed -class TextStyle { +class TextStyles { fontSize: number; constructor(fontSize: number) { @@ -1432,7 +1434,7 @@ class TextStyle { } @Component struct TextComponent { - @ObjectLink textStyle: TextStyle; + @ObjectLink textStyle: TextStyles; build() { Text("Hello World") .fontSize(this.textStyle.fontSize) @@ -1444,7 +1446,7 @@ struct Page { @State styleList: StyleList = new StyleList(); aboutToAppear() { for (let i = 15; i < 50; i++) - this.styleList.push(new TextStyle(i)); + this.styleList.push(new TextStyles(i)); } build() { Column() { @@ -1457,7 +1459,7 @@ struct Page { console.log("change font size"); }) List() { - ForEach(this.styleList, (item: TextStyle) => { + ForEach(this.styleList, (item: TextStyles) => { ListItem() { TextComponent({ textStyle: item}) } @@ -1475,7 +1477,3 @@ Below you can see how the preceding code snippet works. When @ObjectLink is used to accept the input item, the **textStyle** variable in the **TextComponent** component can be observed. For @ObjectLink, parameters are passed by reference. Therefore, when the value of **fontSize** in **styleList** is changed in the parent component, this update is properly observed and synced to the corresponding list item in **ForEach**, leading to UI re-rendering. This is a practical mode of using state management for UI re-rendering. - - - - diff --git a/en/application-dev/quick-start/resource-categories-and-access.md b/en/application-dev/quick-start/resource-categories-and-access.md index 0ad717e1a159a0597e6ea7b3acfc775d2772d20b..fd82af40bd95565bddde76c1b74ba5daaea62418 100644 --- a/en/application-dev/quick-start/resource-categories-and-access.md +++ b/en/application-dev/quick-start/resource-categories-and-access.md @@ -75,7 +75,7 @@ You can create multiple levels of subdirectories with custom names to store vari #### resfile Directory -You can create multiple levels of subdirectories with custom names to store various resource files.
Resource files in the subdirectories are directly packed into the application without being compiled, and no IDs will be assigned to the resource files. After an application is installed, the **resfile** directory is decompressed to the application sandbox path. You can obtain the path through the [resourceDir](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-context.md#properties) attribute of **Context**. +You can create multiple levels of subdirectories with custom names to store various resource files.
Resource files in the subdirectories are directly packed into the application without being compiled, and no IDs will be assigned to the resource files. After the application is installed, resources in the **resfile** repository are decompressed to the application sandbox path. After the **resfile** directory is obtained through the **Context** attribute [resourceDir](../reference/apis-ability-kit/js-apis-inner-application-context.md#properties), the resources can be accessed through the file path in read-only mode. ### Resource Group Directories @@ -133,14 +133,14 @@ The content of the **float.json** file is as follows: ```json { - "float":[ + "float": [ { - "name":"font_hello", - "value":"28.0fp" + "name": "font_hello", + "value": "28.0fp" }, - { - "name":"font_world", - "value":"20.0fp" + { + "name": "font_world", + "value": "20.0fp" } ] } @@ -150,22 +150,22 @@ The content of the **string.json** file is as follows: ```json { - "string":[ + "string": [ { - "name":"string_hello", - "value":"Hello" + "name": "string_hello", + "value": "Hello" }, - { - "name":"string_world", - "value":"World" + { + "name": "string_world", + "value": "World" }, - { - "name":"message_arrive", - "value":"We will arrive at %1$s." + { + "name": "message_arrive", + "value": "We will arrive at %1$s." }, { - "name":"message_notification", - "value":"Hello, %1$s!,You have %2$d new messages." + "name": "message_notification", + "value": "Hello, %1$s!,You have %2$d new messages." } ] } @@ -175,17 +175,17 @@ The content of the **plural.json** file is as follows: ```json { - "plural":[ + "plural": [ { - "name":"eat_apple", - "value":[ + "name": "eat_apple", + "value": [ { - "quantity":"one", - "value":"%d apple" + "quantity": "one", + "value": "%d apple" }, { - "quantity":"other", - "value":"%d apples" + "quantity": "other", + "value": "%d apples" } ] } @@ -221,15 +221,10 @@ Right-click a directory under **resources** and choose **New** > **XXX Resource ### Function Description -You can use the **attr** attribute to specify whether a string should be translated and the translation status. The **attr** attribute is not involved in resource compilation. +If the string resource referenced by an application needs to support multi-language adaptation, the **attr** attribute can be used to mark the translation scope and status of the string. The **attr** attribute is not involved in resource compilation. If the **attr** attribute is not configured, a string is translated by default. -``` -"attr": { - "translatable": false|true - "priority": "code|translate|LT|customer" -} -``` + **Parameters of attr** | Name | Type | Description | @@ -248,7 +243,7 @@ resources | | |---plural.json ``` ### Example -This example sets the **attr** attribute for strings. +The following shows the **attr** attribute configured in **string**. The **string1** string is marked as not to be translated, and the **string2** string is marked as to be translated and the translation has been verified. ```json { @@ -282,7 +277,7 @@ This example sets the **attr** attribute for strings. > > For details about how to use native APIs to access raw files, see [Raw File Development](../napi/rawfile-guidelines.md). -As described in [Resource Group Directories](#resource-group-directories), you can reference .json resource files, including **color.json**, **string.json**, and **plural.json**.
The usage is as follows: + As described in [Resource Group Directories](#resource-group-directories), you can reference .json resource files, including **color.json**, **string.json**, and **plural.json**.
The usage is as follows: ```ts // Access through $r('app.type.name'). diff --git a/en/application-dev/quick-start/typescript-to-arkts-migration-guide.md b/en/application-dev/quick-start/typescript-to-arkts-migration-guide.md index 3151fdd98286d0e3c557d3763cc943147345b4e3..b04877a534df2b6bfdafd1404c8bc34562a0dcf8 100644 --- a/en/application-dev/quick-start/typescript-to-arkts-migration-guide.md +++ b/en/application-dev/quick-start/typescript-to-arkts-migration-guide.md @@ -3259,16 +3259,19 @@ class C { **Severity: warning** +**Error codes: 10605151** + ArkTS does not allow using `ESObject` type in some cases. The most part of limitations are put in place in order to prevent spread of dynamic objects in -the static codebase. The only scenario where it is permited to use `ESObject` -as type specifier is in local variable declaration. Initialization of variables +the static codebase. +For API version 15 or eariler, the only scenario where it is permited to use `ESObject` as type specifier is in local variable declaration. Initialization of variables with `ESObject` type is also limited. Such variables can only be initialized with values that originate from interop: other `ESObject` typed variables, any, unknown, variables with anonymous type, etc. It is prohibited to initialize `ESObject` typed variable with statically typed value. Varaible of type `ESObject` can only be passed to interop calls and assigned to other variables of type `ESObject`. +Since API version 16, the `ESObject` type prohibits object literal assignment while supporting: type annotations in dynamic imports, property access (using both **.** and **[]** operators), **call** expressions, and **new** expressions. **ArkTS** @@ -3278,20 +3281,20 @@ declare function foo(): any; declare function bar(a: any): number; // main.ets -let e0: ESObject = foo(); // Compile-time error: 'ESObject' typed variable can only be local +let e0: ESObject = foo(); // For API version 15 or eariler, compile-time error: 'ESObject' typed variable can only be local; since API version 16, the ESObject type supports explicit type annotation. function f() { - let e1 = foo(); // Compile-time error: type of e1 is 'any' - let e2: ESObject = 1; // Compile-time error: can't initialize 'ESObject' with not dynamic values - let e3: ESObject = {}; // Compile-time error: can't initialize 'ESObject' with not dynamic values - let e4: ESObject = []; // Compile-time error: can't initialize 'ESObject' with not dynamic values - let e5: ESObject = ""; // Compile-time error: can't initialize 'ESObject' with not dynamic values - e5['prop'] // Compile-time error: can't access dynamic properties of 'ESObject' - e5[1] // Compile-time error: can't access dynamic properties of 'ESObject' - e5.prop // Compile-time error: can't access dynamic properties of 'ESObject' - - let e6: ESObject = foo(); // OK - explicitly annotated as 'ESObject' - let e7 = e6; // OK - initialize 'ESObject' with 'ESObject' + let e1 = foo(); // Compile-time error: type of e1 is 'any'; + let e2: ESObject = 1; // For API version 15 or eariler, compile-time error: Cannot initialize an ESObject with non-dynamic values; since API version 16, the number type is supported. + let e3: ESObject = {}; // For API version 15 or eariler, compile-time error: Cannot initialize an ESObject with non-dynamic values; since API version 16, compile-time error: object literal type is not supported. + let e4: ESObject = []; // For API version 15 or eariler, compile-time error: Cannot initialize an ESObject with non-dynamic values; since API version 16, the array type is supported. + let e5: ESObject = ""; // For API version 15 or eariler, compile-time error: Cannot initialize an ESObject with non-dynamic values; since API version 16, the string type is supported. + e5['prop'] // For API version 15 or eariler, compile-time error: Cannot access dynamic properties of 'ESObject'; since API version 16, property access using square brackets is supported. + e5[1] // For API version 15 or eariler, compile-time error: Cannot access dynamic properties of 'ESObject'; since API version 16, property access using square brackets is supported. + e5.prop // For API version 15 or eariler, compile-time error: Cannot access dynamic properties of 'ESObject'; since API version 16, property access using a dot (.) is supported. + + let e6: ESObject = foo(); // OK - Explicitly annotated as 'ESObject' + let e7 = e6; // OK - Initialize 'ESObject' with 'ESObject' bar(e7) // OK - 'ESObject' is passed to interop call } ``` diff --git a/en/application-dev/reference/apis-ability-kit/Readme-EN.md b/en/application-dev/reference/apis-ability-kit/Readme-EN.md index 7b8ce91bf00dd7be0a9809bb600928da2e58522b..5f1c795ed2c60b8ec4dc3387eb2f764f1d3b73e0 100644 --- a/en/application-dev/reference/apis-ability-kit/Readme-EN.md +++ b/en/application-dev/reference/apis-ability-kit/Readme-EN.md @@ -41,6 +41,7 @@ - [@ohos.app.ability.AbilityConstant (AbilityConstant) (System API)](js-apis-app-ability-abilityConstant-sys.md) - [@ohos.app.ability.application (Application) (System API)](js-apis-app-ability-application-sys.md) - [@ohos.app.ability.AutoFillExtensionAbility (AutoFillExtensionAbility) (System API)](js-apis-app-ability-autoFillExtensionAbility-sys.md) + - [@ohos.app.ability.autoFillManager (autoFillManager) (System API)](js-apis-app-ability-autoFillManager-sys.md) - [@ohos.app.ability.autoStartupManager (autoStartupManager) (System API)](js-apis-app-ability-autoStartupManager-sys.md) - [@ohos.app.ability.common (Context) (System API)](js-apis-app-ability-common-sys.md) - [@ohos.app.ability.dialogSession (dialogSession) (System API)](js-apis-app-ability-dialogSession-sys.md) @@ -55,7 +56,7 @@ - [@ohos.ability.ability (Ability)](js-apis-ability-ability.md) - [@ohos.ability.featureAbility (FeatureAbility)](js-apis-ability-featureAbility.md) - [@ohos.ability.particleAbility (ParticleAbility)](js-apis-ability-particleAbility.md) - - Both Models (Recommended) + - Both Models (Recommended) - [@ohos.abilityAccessCtrl (Ability Access Control)](js-apis-abilityAccessCtrl.md) - [@ohos.ability.screenLockFileManager (Sensitive Data Access Management Under Lock Screen)](js-apis-screenLockFileManager.md) - [@ohos.app.ability.abilityManager (AbilityManager)](js-apis-app-ability-abilityManager.md) @@ -63,6 +64,7 @@ - [@ohos.app.ability.appRecovery (appRecovery)](js-apis-app-ability-appRecovery.md) - [@ohos.app.ability.Configuration (Configuration)](js-apis-app-ability-configuration.md) - [@ohos.app.ability.ConfigurationConstant (ConfigurationConstant)](js-apis-app-ability-configurationConstant.md) + - [@ohos.app.ability.continueManager (continueManager)](js-apis-app-ability-continueManager.md) - [@ohos.app.ability.dataUriUtils (DataUriUtils)](js-apis-app-ability-dataUriUtils.md) - [@ohos.app.ability.dialogRequest (dialogRequest)](js-apis-app-ability-dialogRequest.md) - [@ohos.app.ability.errorManager (ErrorManager)](js-apis-app-ability-errorManager.md) @@ -84,6 +86,7 @@ - [@ohos.bundle.bundleManager (bundleManager)](js-apis-bundleManager.md) - [@ohos.bundle.defaultAppManager (Default Application Management)](js-apis-defaultAppManager.md) + - [@ohos.bundle.launcherBundleManager (launcherBundleManager)](js-apis-launcherBundleManager.md) - [@ohos.bundle.overlay (overlay)](js-apis-overlay.md) - [@ohos.bundle.appControl (appControl Module) (System Interface)](js-apis-appControl-sys.md) @@ -130,7 +133,6 @@ - [ErrorObserver](js-apis-inner-application-errorObserver.md) - [EventHub](js-apis-inner-application-eventHub.md) - [ExtensionContext](js-apis-inner-application-extensionContext.md) - - [GlobalObserver](js-apis-inner-application-GlobalObserver.md) - [LoopObserver](js-apis-inner-application-loopObserver.md) - [ProcessInformation](js-apis-inner-application-processInformation.md) - [ProcessRunningInfo](js-apis-inner-application-processRunningInfo.md) @@ -158,6 +160,7 @@ - [ContinueCallback (System API)](js-apis-inner-application-continueCallback-sys.md) - [ContinueDeviceInfo (System API)](js-apis-inner-application-continueDeviceInfo-sys.md) - [ContinueMissionInfo (System API)](js-apis-inner-application-continueMissionInfo-sys.md) + - [CustomData (System API)](js-apis-inner-application-customData-sys.md) - [ExtensionRunningInfo (System API)](js-apis-inner-application-extensionRunningInfo-sys.md) - [MissionCallbacks (System API)](js-apis-inner-application-missionCallbacks-sys.md) - [MissionDeviceInfo (System API)](js-apis-inner-application-missionDeviceInfo-sys.md) @@ -165,8 +168,11 @@ - [MissionListener (System API)](js-apis-inner-application-missionListener-sys.md) - [MissionParameter (System API)](js-apis-inner-application-missionParameter-sys.md) - [MissionSnapshot (System API)](js-apis-inner-application-missionSnapshot-sys.md) - - [MissionSnapshot (System API)](js-apis-inner-application-pageNodeInfo-sys.md) + - [MultiAppMode (System API)](js-apis-inner-application-multiAppMode-sys.md) - [PageNodeInfo (System API)](js-apis-inner-application-pageNodeInfo-sys.md) + - [RunningAppClone (System API)](js-apis-inner-application-runningAppClone-sys.md) + - [RunningMultiAppInfo (System API)](js-apis-inner-application-runningMultiAppInfo-sys.md) + - [RunningMultiInstanceInfo (System API)](js-apis-inner-application-runningMultiInstanceInfo-sys.md) - [ServiceExtensionContext (System API)](js-apis-inner-application-serviceExtensionContext-sys.md) - [UIServiceExtensionContext (System API)](js-apis-inner-application-uiserviceExtensionContext-sys.md) - [UIServiceHostProxy (System API)](js-apis-inner-application-uiservicehostproxy-sys.md) @@ -175,25 +181,24 @@ - [ViewData (System API)](js-apis-inner-application-viewData-sys.md) - [AutoFillRect (System API)](js-apis-inner-application-autoFillRect-sys.md) - - bundleManager + - bundleManager - [abilityInfo](js-apis-bundleManager-abilityInfo.md) - [applicationInfo](js-apis-bundleManager-applicationInfo.md) - [bundleInfo](js-apis-bundleManager-bundleInfo.md) - [elementName](js-apis-bundleManager-elementName.md) - [extensionAbilityInfo](js-apis-bundleManager-extensionAbilityInfo.md) - [hapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) + - [launcherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo.md) - [metadata](js-apis-bundleManager-metadata.md) - [OverlayModuleInfo](js-apis-bundleManager-overlayModuleInfo.md) - [Skill](js-apis-bundleManager-skill.md) - [ApplicationInfo (System API)](js-apis-bundleManager-ApplicationInfo-sys.md) - [AppProvisionInfo (System API)](js-apis-bundleManager-AppProvisionInfo-sys.md) - - [BundleInfo (System API)](js-apis-bundleManager-BundleInfo-sys.md) - [BundlePackInfo (System API)](js-apis-bundleManager-BundlePackInfo-sys.md) - [BundleResourceInfo (System API)](js-apis-bundleManager-BundleResourceInfo-sys.md) - [BusinessAbilityInfo (System API)](js-apis-bundleManager-businessAbilityInfo-sys.md) - [dispatchInfo (System API)](js-apis-bundleManager-dispatchInfo-sys.md) - - [launcherAbilityInfo (System API)](js-apis-bundleManager-launcherAbilityInfo-sys.md) - [LauncherAbilityResourceInfo (System API)](js-apis-bundleManager-LauncherAbilityResourceInfo-sys.md) - [permissionDef (System API)](js-apis-bundleManager-permissionDef-sys.md) - [recoverableApplicationInfo (System API)](js-apis-bundleManager-recoverableApplicationInfo-sys.md) @@ -201,15 +206,18 @@ - [SharedBundleInfo (System API)](js-apis-bundleManager-sharedBundleInfo-sys.md) - [shortcutInfo (System API)](js-apis-bundleManager-shortcutInfo-sys.md) - - continuation + - continuation - [continuationExtraParams](js-apis-continuation-continuationExtraParams.md) - [continuationResult](js-apis-continuation-continuationResult.md) - - security + - security - [PermissionRequestResult](js-apis-permissionrequestresult.md) - - wantAgent + - wantAgent - [triggerInfo](js-apis-inner-wantAgent-triggerInfo.md) - [wantAgentInfo](js-apis-inner-wantAgent-wantAgentInfo.md) - - APIs No Longer Maintained + + - [TriggerInfo (System API)](js-apis-inner-wantAgent-triggerInfo-sys.md) + + - APIs No Longer Maintained - [@ohos.ability.dataUriUtils (DataUriUtils)](js-apis-ability-dataUriUtils.md) - [@ohos.ability.errorCode (ErrorCode)](js-apis-ability-errorCode.md) - [@ohos.ability.wantConstant (wantConstant)](js-apis-ability-wantConstant.md) @@ -232,7 +240,7 @@ - [@ohos.distributedBundle (Distributed Bundle Management) (System API)](js-apis-Bundle-distributedBundle-sys.md) - [@system.package (Bundle Management)](js-apis-system-package.md) - - bundle + - bundle - [abilityInfo](js-apis-bundle-AbilityInfo.md) - [applicationInfo](js-apis-bundle-ApplicationInfo.md) - [bundleInfo](js-apis-bundle-BundleInfo.md) @@ -249,23 +257,28 @@ - [remoteAbilityInfo (System API)](js-apis-bundle-remoteAbilityInfo-sys.md) - [shortcutInfo (System API)](js-apis-bundle-ShortcutInfo-sys.md) -- C APIs - - Modules +- C APIs + - Modules - [AbilityAccessControl](_ability_access_control.md) + - [AbilityBase](_ability_base.md) - [AbilityRuntime](_ability_runtime.md) - [Bundle](_bundle.md) - [ChildProcess](c-apis-ability-childprocess.md) - - Header Files + - Header Files - [ability_access_control.h](ability__access__control_8h.md) + - [ability_base_common.h](ability__base__common_8h.md) - [ability_runtime_common.h](ability__runtime__common_8h.md) - [application_context.h](application__context_8h.md) - [context_constant.h](context__constant_8h.md) - [native_interface_bundle.h](native__interface__bundle.md) - [native_child_process.h](native__child__process_8h.md) - - Structs + - [start_options.h](start__options_8h.md) + - [want.h](want__8h.md) + - Structs + - [AbilityBase_Element](_ability_base_element.md) - [OH_NativeBundle_ApplicationInfo](_o_h___native_bundle_application_info.md) - [OH_NativeBundle_ElementName](_o_h___native_bundle_element_name.md) -- Error Codes +- Error Codes - [Ability Error Codes](errorcode-ability.md) - [Distributed Scheduler Error Codes](errorcode-DistributedSchedule.md) - [Bundle Error Codes](errorcode-bundle.md) diff --git a/en/application-dev/reference/apis-ability-kit/_ability_access_control.md b/en/application-dev/reference/apis-ability-kit/_ability_access_control.md index 966d0c11ecd07dd8263f85d7a8b2722d23402065..77fe0716e9cb8b4d6ad095260588aef4f7fc89d1 100644 --- a/en/application-dev/reference/apis-ability-kit/_ability_access_control.md +++ b/en/application-dev/reference/apis-ability-kit/_ability_access_control.md @@ -3,7 +3,7 @@ ## Overview -Provides the system capability for implementing process access control. +Provides the system capability for implementing application access control. **Since**: 12 @@ -15,14 +15,14 @@ Provides the system capability for implementing process access control. | Name| Description| | -------- | -------- | -| [ability_access_control.h](ability__access__control_8h.md) | Declares the APIs for implementing process access control. | +| [ability_access_control.h](ability__access__control_8h.md) | Declares the APIs for implementing application access control. | ### Functions | Name| Description| | -------- | -------- | -| bool [OH_AT_CheckSelfPermission](#oh_at_checkselfpermission)(const char \*permission) | Checks whether the specified permission is granted to the application. | +| bool [OH_AT_CheckSelfPermission](#oh_at_checkselfpermission)(const char \*permission) | Checks whether a permission is granted to this application. | ## Function Description @@ -34,8 +34,7 @@ Provides the system capability for implementing process access control. bool OH_AT_CheckSelfPermission(const char* permission) ``` **Description** - -Checks whether the specified permission is granted to the application. +Checks whether a permission is granted to this application. **Since**: 12 @@ -43,7 +42,7 @@ Checks whether the specified permission is granted to the application. | Name| Description| | -------- | -------- | -| permission | Permission to check. For details about the permissions, see the application permission list. | +| permission | Pointer to the permission to check. For details about the permission, see the application permission list. | **Returns** diff --git a/en/application-dev/reference/apis-ability-kit/_ability_base.md b/en/application-dev/reference/apis-ability-kit/_ability_base.md new file mode 100644 index 0000000000000000000000000000000000000000..4a97ead787e288380e8d2887667482e82cadc761 --- /dev/null +++ b/en/application-dev/reference/apis-ability-kit/_ability_base.md @@ -0,0 +1,495 @@ +# AbilityBase + +## Overview + +As the basic definition module of Ability Kit, AbilityBase provides definitions and APIs for [Want](want__8h.md), which can be used to transfer information between application components. + +**System capability**: SystemCapability.Ability.AbilityBase + +**Since**: 15 + +## Summary + + +### Files + +| Name| Description| +| -------- | -------- | +| [ability_base_common.h](ability__base__common_8h.md) | Declares the error codes related to AbilityBase.
**File to include**:
**Library**: libability_base_want.so| +| [want.h](want__8h.md) | Declares the capabilities related to [Want](want__8h.md).
**File to include**:
**Library**: libability_base_want.so| + +### Enums + +| Name | Description | +| ------------------------------------------------------------ | ---------------------- | +| [AbilityBase_ErrorCode](#abilitybase_errorcode) {
ABILITY_BASE_ERROR_CODE_NO_ERROR = 0,
ABILITY_BASE_ERROR_CODE_PARAM_INVALID = 401,
} | Enumerates the AbilityBase error codes.| + +### Structs + +| Name | Description | +| ------------------------------------------------------------ | ---------------------------- | +| [AbilityBase_Element](_ability_base_element.md#abilitybase_element) {
char* bundleName;
char* moduleName;
char* abilityName;
} | Element struct.| +| [AbilityBase_Want](#abilitybase_want) | Want struct.| + +### Functions + +| Name | Description | +| ------------------------------------------------------------ | ---------------------------- | +| [AbilityBase_Want](#abilitybase_want)* [OH_AbilityBase_CreateWant](#oh_abilitybase_createwant)([AbilityBase_Element](_ability_base_element.md#abilitybase_element) element) | Creates Want.| +| [AbilityBase_ErrorCode](#abilitybase_errorcode) [OH_AbilityBase_DestroyWant](#oh_abilitybase_destroywant)([AbilityBase_Want](#abilitybase_want)* want) | Destroys Want. Want cannot be used after being destroyed. Otherwise, undefined behavior may occur.| +| [AbilityBase_ErrorCode](#abilitybase_errorcode) [OH_AbilityBase_SetWantElement](#oh_abilitybase_setwantelement)([AbilityBase_Want](#abilitybase_want)* want, [AbilityBase_Element](_ability_base_element.md#abilitybase_element) element) | Sets the Element struct, which consists of **bundleName**, **moduleName**, and **abilityName** in Want.| +| [AbilityBase_ErrorCode](#abilitybase_errorcode) [OH_AbilityBase_GetWantElement](#oh_abilitybase_getwantelement)([AbilityBase_Want](#abilitybase_want)* want, [AbilityBase_Element](_ability_base_element.md#abilitybase_element)* element) | Obtains the Element struct, which consists of **bundleName**, **moduleName**, and **abilityName** in Want.| +| [AbilityBase_ErrorCode](#abilitybase_errorcode) [OH_AbilityBase_SetWantCharParam](#oh_abilitybase_setwantcharparam)([AbilityBase_Want](#abilitybase_want)* want, const char* key, const char* value) | Sets **Param** in Want. For details about **Param**, see [parameters in Want](js-apis-inner-ability-want.md).| +| [AbilityBase_ErrorCode](#abilitybase_errorcode) [OH_AbilityBase_GetWantCharParam](#oh_abilitybase_getwantcharparam)([AbilityBase_Want](#abilitybase_want)* want, const char* key, char* value, size_t valueSize) | Obtains **Param** set by [OH_AbilityBase_SetWantCharParam](#oh_abilitybase_setwantcharparam) in Want.| +| [AbilityBase_ErrorCode](#abilitybase_errorcode) [OH_AbilityBase_AddWantFd](#oh_abilitybase_addwantfd)([AbilityBase_Want](#abilitybase_want)* want, const char* key, int32_t fd) | Adds a Want file descriptor. The file descriptor can be obtained through [fs.open](../apis-core-file-kit/js-apis-file-fs.md#fsopen).| +| [AbilityBase_ErrorCode](#abilitybase_errorcode) [OH_AbilityBase_GetWantFd](#oh_abilitybase_getwantfd)([AbilityBase_Want](#abilitybase_want)* want, const char* key, int32_t* fd) | Obtains a Want file descriptor.| +| [AbilityBase_ErrorCode](#abilitybase_errorcode) [OH_AbilityBase_SetWantUri](#oh_abilitybase_setwanturi)([AbilityBase_Want](#abilitybase_want)* want, const char* uri) | Sets **uri** in Want. For details about **uri**, see [uri in Want](js-apis-app-ability-want.md).| +| [AbilityBase_ErrorCode](#abilitybase_errorcode) [OH_AbilityBase_GetWantUri](#oh_abilitybase_getwanturi)([AbilityBase_Want](#abilitybase_want)* want, char* uri, size_t uriSize) | Obtains **uri** set in Want. For details about **uri**, see [uri in Want](js-apis-app-ability-want.md).| +| [AbilityBase_ErrorCode](#abilitybase_errorcode) [OH_AbilityBase_SetWantInt32Param](#oh_abilitybase_setwantint32param)([AbilityBase_Want](#abilitybase_want)* want, const char* key, int32_t value) | Sets a value of the int32_t type in Want.| +| [AbilityBase_ErrorCode](#abilitybase_errorcode) [OH_AbilityBase_GetWantInt32Param](#oh_abilitybase_getwantint32param)([AbilityBase_Want](#abilitybase_want)* want, const char* key, int32_t* value) | Obtains a value of the int32_t type set in Want.| +| [AbilityBase_ErrorCode](#abilitybase_errorcode) [OH_AbilityBase_SetWantBoolParam](#oh_abilitybase_setwantboolparam)([AbilityBase_Want](#abilitybase_want)* want, const char* key, bool value) | Sets a value of the bool type in Want.| +| [AbilityBase_ErrorCode](#abilitybase_errorcode) [OH_AbilityBase_GetWantBoolParam](#oh_abilitybase_getwantboolparam)([AbilityBase_Want](#abilitybase_want)* want, const char* key, bool* value) | Obtains a value of the bool type set in Want.| +| [AbilityBase_ErrorCode](#abilitybase_errorcode) [OH_AbilityBase_SetWantDoubleParam](#oh_abilitybase_setwantdoubleparam)([AbilityBase_Want](#abilitybase_want)* want, const char* key, double value) | Sets a value of the double type in Want.| +| [AbilityBase_ErrorCode](#abilitybase_errorcode) [OH_AbilityBase_GetWantDoubleParam](#oh_abilitybase_getwantdoubleparam)([AbilityBase_Want](#abilitybase_want)* want, const char* key, double* value) | Obtains a value of the double type set in Want.| + + + +## Enum Description + +### AbilityBase_ErrorCode + +``` +enum AbilityBase_ErrorCode +``` + +**Description** + +Enumerates the AbilityBase error codes. + +**Since**: 15 + +| Value | Description | +| --------------------------------------------- | -------------- | +| ABILITY_BASE_ERROR_CODE_NO_ERROR | Operation successful. | +| ABILITY_BASE_ERROR_CODE_PARAM_INVALID | Invalid parameter. | + + +## Struct Description + +### AbilityBase_Want + +``` +AbilityBase_Want +``` + +**Description** + +Want struct. + +**Since**: 15 + + +## Function Description + + +### OH_AbilityBase_CreateWant + +``` +AbilityBase_Want* OH_AbilityBase_CreateWant(AbilityBase_Element element) +``` +**Description** + +Creates Want. + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| element | Element struct.| + +**Returns** + +Returns **AbilityBase_Want**, which is a Want struct. + + +### OH_AbilityBase_DestroyWant + +``` +AbilityBase_ErrorCode OH_AbilityBase_DestroyWant(AbilityBase_Want* want) +``` +**Description** + +Destroys Want. Want cannot be used after being destroyed. Otherwise, undefined behavior may occur. + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| want | Pointer to Want.| + +**Returns** + +Returns **ABILITY_BASE_ERROR_CODE_NO_ERROR** if Want is destroyed. + +Returns **ABILITY_BASE_ERROR_CODE_PARAM_INVALID** if **element** is invalid. + +### OH_AbilityBase_SetWantElement + +``` +AbilityBase_ErrorCode OH_AbilityBase_SetWantElement(AbilityBase_Want* want, AbilityBase_Element element) +``` +**Description** + +Sets the Element struct, which consists of **bundleName**, **moduleName**, and **abilityName** in Want. + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| want | Pointer to Want.| +| element | Element struct.| + +**Returns** + +Returns **ABILITY_BASE_ERROR_CODE_NO_ERROR** if the setting is successful. + +Returns **ABILITY_BASE_ERROR_CODE_PARAM_INVALID** if **want** is set to a null pointer or **element** is invalid. + +### OH_AbilityBase_GetWantElement + +``` +AbilityBase_ErrorCode OH_AbilityBase_GetWantElement(AbilityBase_Want* want, AbilityBase_Element* element) +``` +**Description** + +Obtains the Element struct, which consists of **bundleName**, **moduleName**, and **abilityName** in Want. + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| want | Pointer to Want.| +| element | Pointer to the Element struct.| + +**Returns** + +Returns **ABILITY_BASE_ERROR_CODE_NO_ERROR** if the element struct is obtained. + +Returns **ABILITY_BASE_ERROR_CODE_PARAM_INVALID** if **want** is set to a null pointer or **element** is invalid. + +### OH_AbilityBase_SetWantCharParam + +``` +AbilityBase_ErrorCode OH_AbilityBase_SetWantCharParam(AbilityBase_Want* want, const char* key, const char* value) +``` +**Description** + +Sets **Param** in Want. For details about **Param**, see [parameters in Want](js-apis-inner-ability-want.md). + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| want | Pointer to Want.| +| key | Pointer to a key in Want.| +| value | Pointer to the value of the key in Want.| + +**Returns** + +Returns **ABILITY_BASE_ERROR_CODE_NO_ERROR** if the setting is successful. + +Returns **ABILITY_BASE_ERROR_CODE_PARAM_INVALID** if **want** is a null pointer or invalid. + +### OH_AbilityBase_GetWantCharParam + +``` +AbilityBase_ErrorCode OH_AbilityBase_GetWantCharParam(AbilityBase_Want* want, const char* key, char* value, size_t valueSize) +``` +**Description** + +Obtains **Param** set by [OH_AbilityBase_SetWantCharParam](#oh_abilitybase_setwantcharparam) in Want. + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| want | Pointer to Want.| +| key | Pointer to a key in Want.| +| value | Pointer to the value of the key in Want.| +| valueSize | Length of the value string. If **valueSize** is less than the actual value length, the **ABILITY_BASE_ERROR_CODE_PARAM_INVALID** error is reported.| + +**Returns** + +Returns **ABILITY_BASE_ERROR_CODE_NO_ERROR** if the param struct is obtained. + +Returns **ABILITY_BASE_ERROR_CODE_PARAM_INVALID** if **want** is a null pointer or invalid. + +### OH_AbilityBase_AddWantFd + +``` +AbilityBase_ErrorCode OH_AbilityBase_AddWantFd(AbilityBase_Want* want, const char* key, int32_t fd) +``` +**Description** + +Adds a Want file descriptor. The file descriptor can be obtained through [fs.open](../apis-core-file-kit/js-apis-file-fs.md#fsopen). + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| want | Pointer to Want.| +| key | Pointer to a key in Want.| +| fd | File descriptor, which is obtained by calling [fs.open](../apis-core-file-kit/js-apis-file-fs.md#fsopen).| + +**Returns** + +Returns **ABILITY_BASE_ERROR_CODE_NO_ERROR** if the Want file descriptor is added. + +Returns **ABILITY_BASE_ERROR_CODE_PARAM_INVALID** if **want** is a null pointer or invalid. + +### OH_AbilityBase_GetWantFd + +``` +AbilityBase_ErrorCode OH_AbilityBase_GetWantFd(AbilityBase_Want* want, const char* key, int32_t* fd) +``` +**Description** + +Obtains a Want file descriptor. + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| want | Pointer to Want.| +| key | Pointer to a key in Want.| +| fd | Pointer to the file descriptor.| + +**Returns** + +Returns **ABILITY_BASE_ERROR_CODE_NO_ERROR** if the Want file descriptor is obtained. + +Returns **ABILITY_BASE_ERROR_CODE_PARAM_INVALID** if **want** is a null pointer or invalid. + +### OH_AbilityBase_SetWantUri + +``` +AbilityBase_ErrorCode OH_AbilityBase_SetWantUri(AbilityBase_Want* want, const char* uri) +``` + +**Description** + +Sets **uri** in Want. For details about **uri**, see [uri in Want](js-apis-app-ability-want.md). + +**Valid since**: 18 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| want | Pointer to Want.| +| uri | Pointer to a URI. If a URI is specified in Want, Want will match the specified URI information. For details, see [uri in Want](js-apis-app-ability-want.md).| + +**Returns** + +Returns **ABILITY_BASE_ERROR_CODE_NO_ERROR** if the setting is successful. + +Returns **ABILITY_BASE_ERROR_CODE_PARAM_INVALID** if **want** is a null pointer or invalid. + +### OH_AbilityBase_GetWantUri + +``` +AbilityBase_ErrorCode OH_AbilityBase_GetWantUri(AbilityBase_Want* want, char* uri, size_t uriSize) +``` + +**Description** + +Obtains **uri** set in Want. For details about **uri**, see [uri in Want](js-apis-app-ability-want.md). + +**Valid since**: 18 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| want | Pointer to Want.| +| uri | Pointer to a URI. If a URI is specified in Want, Want will match the specified URI information. For details, see [uri in Want](js-apis-app-ability-want.md).| +| uriSize | Length of the URI string. If **uriSize** is less than the actual URI length, the **ABILITY_BASE_ERROR_CODE_PARAM_INVALID** error is reported.| + +**Returns** + +Returns **ABILITY_BASE_ERROR_CODE_NO_ERROR** if the URI string in Want is successfully obtained. + +Returns **ABILITY_BASE_ERROR_CODE_PARAM_INVALID** if **want** is a null pointer or invalid. + +### OH_AbilityBase_SetWantInt32Param + +``` +AbilityBase_ErrorCode OH_AbilityBase_SetWantInt32Param(AbilityBase_Want* want, const char* key, int32_t value) +``` + +**Description** + +Sets a value of the int32_t type in Want. + +**Valid since**: 18 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| want | Pointer to Want.| +| key | Pointer to the key in Want.| +| value | Value of the int32_t type of the key.| + +**Returns** + +Returns **ABILITY_BASE_ERROR_CODE_NO_ERROR** if the setting is successful. + +Returns **ABILITY_BASE_ERROR_CODE_PARAM_INVALID** if **want** is a null pointer or invalid. + +### OH_AbilityBase_GetWantInt32Param + +``` +AbilityBase_ErrorCode OH_AbilityBase_GetWantInt32Param(AbilityBase_Want* want, const char* key, int32_t* value) +``` + +**Description** + +Obtains a value of the int32_t type set in Want. + +**Valid since**: 18 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| want | Pointer to Want.| +| key | Pointer to the key in Want.| +| value | Pointer to the value of the int32_t type of the key.| + +**Returns** + +Returns **ABILITY_BASE_ERROR_CODE_NO_ERROR** if the value of the int32_t type is successfully obtained. + +Returns **ABILITY_BASE_ERROR_CODE_PARAM_INVALID** if **want** is a null pointer or invalid. + + +### OH_AbilityBase_SetWantBoolParam + +``` +AbilityBase_ErrorCode OH_AbilityBase_SetWantBoolParam(AbilityBase_Want* want, const char* key, bool value) +``` + +**Description** + +Sets a value of the bool type in Want. + +**Valid since**: 18 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| want | Pointer to Want.| +| key | Pointer to the key in Want.| +| value | Value of the bool type of the key.| + +**Returns** + +Returns **ABILITY_BASE_ERROR_CODE_NO_ERROR** if the setting is successful. + +Returns **ABILITY_BASE_ERROR_CODE_PARAM_INVALID** if **want** is a null pointer or invalid. + +### OH_AbilityBase_GetWantBoolParam + +``` +AbilityBase_ErrorCode OH_AbilityBase_GetWantBoolParam(AbilityBase_Want* want, const char* key, bool* value) +``` + +**Description** + +Obtains a value of the bool type set in Want. + +**Valid since**: 18 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| want | Pointer to Want.| +| key | Pointer to the key in Want.| +| value | Pointer to the value of the bool type of the key.| + +**Returns** + +Returns **ABILITY_BASE_ERROR_CODE_NO_ERROR** if the value of the bool type is successfully obtained. + +Returns **ABILITY_BASE_ERROR_CODE_PARAM_INVALID** if **want** is a null pointer or invalid. + +### OH_AbilityBase_SetWantDoubleParam + +``` +AbilityBase_ErrorCode OH_AbilityBase_SetWantDoubleParam(AbilityBase_Want* want, const char* key, double value) +``` + +**Description** + +Sets a value of the double type in Want. + +**Valid since**: 18 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| want | Pointer to Want.| +| key | Pointer to the key in Want.| +| value | Value of the double type of the key.| + +**Returns** + +Returns **ABILITY_BASE_ERROR_CODE_NO_ERROR** if the setting is successful. + +Returns **ABILITY_BASE_ERROR_CODE_PARAM_INVALID** if **want** is a null pointer or invalid. + +### OH_AbilityBase_GetWantDoubleParam + +``` +AbilityBase_ErrorCode OH_AbilityBase_GetWantDoubleParam(AbilityBase_Want* want, const char* key, double* value) +``` + +**Description** + +Obtains a value of the double type set in Want. + +**Valid since**: 18 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| want | Pointer to Want.| +| key | Pointer to the key in Want.| +| value | Pointer to the value of the double type of the key.| + +**Returns** + +Returns **ABILITY_BASE_ERROR_CODE_NO_ERROR** if the value of the double type is successfully obtained. + +Returns **ABILITY_BASE_ERROR_CODE_PARAM_INVALID** if **want** is a null pointer or invalid. diff --git a/en/application-dev/reference/apis-ability-kit/_ability_base_element.md b/en/application-dev/reference/apis-ability-kit/_ability_base_element.md new file mode 100644 index 0000000000000000000000000000000000000000..4ff485fefb2033039a3bffe56113207fdaac9e9c --- /dev/null +++ b/en/application-dev/reference/apis-ability-kit/_ability_base_element.md @@ -0,0 +1,67 @@ +# AbilityBase_Element + + +## Overview + +The Element struct consists of **bundleName**, **moduleName**, and **abilityName** in [Want](want__8h.md). + +**Since**: 15 + +**Related module**: [AbilityBase](_ability_base.md) + + +## Summary + + +### Member Variables + +| Name| Description| +| -------- | -------- | +| [bundleName](#bundlename) | Bundle name.| +| [moduleName](#modulename) | Module name.| +| [abilityName](#abilityname) | Ability name.| + + +## Member Variable Description + + +### bundleName + + +``` +char* AbilityBase_Element::bundleName +``` + +**Description** + +Bundle name. + +**Since**: 15 + + +### moduleName + + +``` +char* AbilityBase_Element::moduleName +``` + +**Description** + +Module name. + +**Since**: 15 + + +### abilityName + + +``` +char* AbilityBase_Element::abilityName +``` + +**Description** + +Ability name. + +**Since**: 15 diff --git a/en/application-dev/reference/apis-ability-kit/_ability_runtime.md b/en/application-dev/reference/apis-ability-kit/_ability_runtime.md index 50df86351bcabbe9c1e009cfbecd65fc7d754e68..239ff3a2f2536416da31675e58df8442a5aa04e4 100644 --- a/en/application-dev/reference/apis-ability-kit/_ability_runtime.md +++ b/en/application-dev/reference/apis-ability-kit/_ability_runtime.md @@ -19,14 +19,17 @@ The AbilityRuntime module provides capabilities related to the ability framework | -------- | -------- | | [ability_runtime_common.h](ability__runtime__common_8h.md) | Declares the error codes of the ability framework.
**File to include**:
**Library**: libability_runtime.so| | [application_context.h](application__context_8h.md) | Declares the context capability at the application level.
**File to include**:
**Library**: libability_runtime.so| -| [context_constant.h](context__constant_8h.md) | Declares context-related enums.
**File to include**:
**Library**: libability_runtime.so| +| [context_constant.h](context__constant_8h.md) | Declares the context-related enums.
**File to include**:
**Library**: libability_runtime.so| +| [start_options.h](start__options_8h.md) | Declares the StartOptions struct and related functions.
**File to include**:
**Library**: libability_runtime.so| ### Enums | Name | Description | | ------------------------------------------------------------ | ---------------------- | -| [AbilityRuntime_ErrorCode](#abilityruntime_errorcode) {
ABILITY_RUNTIME_ERROR_CODE_NO_ERROR = 0,
ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID = 401,
ABILITY_RUNTIME_ERROR_CODE_CONTEXT_NOT_EXIST = 16000011,
} | Enumerates the error codes used by the ability framework.| +| [AbilityRuntime_ErrorCode](#abilityruntime_errorcode) {
ABILITY_RUNTIME_ERROR_CODE_NO_ERROR = 0,
ABILITY_RUNTIME_ERROR_CODE_PERMISSION_DENIED = 201,
ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID = 401,
ABILITY_RUNTIME_ERROR_CODE_NOT_SUPPORTED = 801,
ABILITY_RUNTIME_ERROR_CODE_NO_SUCH_ABILITY = 16000001,
ABILITY_RUNTIME_ERROR_CODE_INCORRECT_ABILITY_TYPE = 16000002,
ABILITY_RUNTIME_ERROR_CODE_CROWDTEST_EXPIRED = 16000008,
ABILITY_RUNTIME_ERROR_CODE_WUKONG_MODE = 16000009,
ABILITY_RUNTIME_ERROR_CODE_CONTEXT_NOT_EXIST = 16000011,
ABILITY_RUNTIME_ERROR_CODE_CONTROLLED = 16000012,
ABILITY_RUNTIME_ERROR_CODE_EDM_CONTROLLED = 16000013,
ABILITY_RUNTIME_ERROR_CODE_CROSS_APP = 16000018,
ABILITY_RUNTIME_ERROR_CODE_INTERNAL = 16000050,
ABILITY_RUNTIME_ERROR_CODE_NOT_TOP_ABILITY = 16000053,
ABILITY_RUNTIME_ERROR_VISIBILITY_SETTING_DISABLED = 16000067,
ABILITY_RUNTIME_ERROR_CODE_MULTI_APP_NOT_SUPPORTED = 16000072,
ABILITY_RUNTIME_ERROR_CODE_INVALID_APP_INSTANCE_KEY = 16000076,
ABILITY_RUNTIME_ERROR_CODE_UPPER_LIMIT_REACHED = 16000077,
ABILITY_RUNTIME_ERROR_MULTI_INSTANCE_NOT_SUPPORTED = 16000078,
ABILITY_RUNTIME_ERROR_CODE_APP_INSTANCE_KEY_NOT_SUPPORTED = 16000079
} | Enumerates the error codes used by the ability framework.| | [AbilityRuntime_AreaMode](#abilityruntime_areamode) {
ABILITY_RUNTIME_AREA_MODE_EL1 = 0,
ABILITY_RUNTIME_AREA_MODE_EL2 = 1,
ABILITY_RUNTIME_AREA_MODE_EL3 = 2,
ABILITY_RUNTIME_AREA_MODE_EL4 = 3,
ABILITY_RUNTIME_AREA_MODE_EL5 = 4
} | Enumerates the data encryption levels. | +| [AbilityRuntime_WindowMode](#abilityruntime_supportedwindowmode) {
ABILITY_RUNTIME_WINDOW_MODE_UNDEFINED = 0,
ABILITY_RUNTIME_WINDOW_MODE_FULL_SCREEN = 1
} | Enumerates the window modes in which an ability can be displayed at startup. | +| [AbilityRuntime_SupportedWindowMode](#abilityruntime_supportedwindowmode) {
ABILITY_RUNTIME_SUPPORTED_WINDOW_MODE_FULL_SCREEN = 0,
ABILITY_RUNTIME_SUPPORTED_WINDOW_MODE_SPLIT = 1,
ABILITY_RUNTIME_SUPPORTED_WINDOW_MODE_FLOATING = 2
} | Enumerates the window modes supported by an ability when it is started. | ### Functions @@ -42,6 +45,52 @@ The AbilityRuntime module provides capabilities related to the ability framework | [AbilityRuntime_ErrorCode](#abilityruntime_errorcode) [OH_AbilityRuntime_ApplicationContextGetBundleCodeDir](#oh_abilityruntime_applicationcontextgetbundlecodedir)(char* buffer, const int32_t bufferSize, int32_t* writeLength) | Obtains the application-level installation file directory.| | [AbilityRuntime_ErrorCode](#abilityruntime_errorcode) [OH_AbilityRuntime_ApplicationContextGetDistributedFilesDir](#oh_abilityruntime_applicationcontextgetdistributedfilesdir)(char* buffer, const int32_t bufferSize, int32_t* writeLength) | Obtains the application-level distributed file directory.| | [AbilityRuntime_ErrorCode](#abilityruntime_errorcode) [OH_AbilityRuntime_ApplicationContextGetCloudFileDir](#oh_abilityruntime_applicationcontextgetcloudfiledir)(char* buffer, const int32_t bufferSize, int32_t* writeLength) | Obtains the application-level cloud file directory.| +| [AbilityRuntime_ErrorCode](#abilityruntime_errorcode) [OH_AbilityRuntime_StartSelfUIAbility](#oh_abilityruntime_startselfuiability)([AbilityBase_Want](_ability_base.md#abilitybase_want) *want) | Starts the UIAbility of the current application.| +| [AbilityRuntime_StartOptions*](#abilityruntime_startoptions) [OH_AbilityRuntime_CreateStartOptions](#oh_abilityruntime_createstartoptions)(void) | Creates the StartOptions struct required for starting the UIAbility of the current application.| +| [AbilityRuntime_ErrorCode](#abilityruntime_errorcode) [OH_AbilityRuntime_DestroyStartOptions](#oh_abilityruntime_destroystartoptions)([AbilityRuntime_StartOptions](#abilityruntime_startoptions) **startOptions) | Destroys a StartOptions struct.| +| [AbilityRuntime_ErrorCode](#abilityruntime_errorcode) [OH_AbilityRuntime_SetStartOptionsWindowMode](#oh_abilityruntime_setstartoptionswindowmode)([AbilityRuntime_StartOptions](#abilityruntime_startoptions) *startOptions, [AbilityRuntime_WindowMode](#abilityruntime_windowmode) windowMode) | Sets the window mode for starting an ability.| +| [AbilityRuntime_ErrorCode](#abilityruntime_errorcode) [OH_AbilityRuntime_GetStartOptionsWindowMode](#oh_abilityruntime_getstartoptionswindowmode)([AbilityRuntime_StartOptions](#abilityruntime_startoptions) *startOptions, [AbilityRuntime_WindowMode](#abilityruntime_windowmode) &windowMode) | Obtains the window mode for starting an ability.| +| [AbilityRuntime_ErrorCode](#abilityruntime_errorcode) [OH_AbilityRuntime_SetStartOptionsDisplayId](#oh_abilityruntime_setstartoptionsdisplayid)([AbilityRuntime_StartOptions](#abilityruntime_startoptions) *startOptions, int32_t displayId) | Sets the ID of the display where the window is launched when the ability is started.| +| [AbilityRuntime_ErrorCode](#abilityruntime_errorcode) [OH_AbilityRuntime_GetStartOptionsDisplayId](#oh_abilityruntime_getstartoptionsdisplayid)([AbilityRuntime_StartOptions](#abilityruntime_startoptions) *startOptions, int32_t &displayId) | Obtains the ID of the display where the window is launched when the ability is started.| +| [AbilityRuntime_ErrorCode](#abilityruntime_errorcode) [OH_AbilityRuntime_SetStartOptionsWithAnimation](#oh_abilityruntime_setstartoptionswithanimation)([AbilityRuntime_StartOptions](#abilityruntime_startoptions) *startOptions, bool withAnimation) | Sets whether to use animation effects when an ability is started.| +| [AbilityRuntime_ErrorCode](#abilityruntime_errorcode) [OH_AbilityRuntime_GetStartOptionsWithAnimation](#oh_abilityruntime_getstartoptionswithanimation)([AbilityRuntime_StartOptions](#abilityruntime_startoptions) *startOptions, bool &withAnimation) | Checks whether animation effects are used when an ability is started.| +| [AbilityRuntime_ErrorCode](#abilityruntime_errorcode) [OH_AbilityRuntime_SetStartOptionsWindowLeft](#oh_abilityruntime_setstartoptionswindowleft)([AbilityRuntime_StartOptions](#abilityruntime_startoptions) *startOptions, int32_t windowLeft) | Sets the left position of the window when the ability is started, in px.| +| [AbilityRuntime_ErrorCode](#abilityruntime_errorcode) [OH_AbilityRuntime_GetStartOptionsWindowLeft](#oh_abilityruntime_getstartoptionswindowleft)([AbilityRuntime_StartOptions](#abilityruntime_startoptions) *startOptions, int32_t &windowLeft) | Obtains the left position of the window when the ability is started, in px.| +| [AbilityRuntime_ErrorCode](#abilityruntime_errorcode) [OH_AbilityRuntime_SetStartOptionsWindowTop](#oh_abilityruntime_setstartoptionswindowtop)([AbilityRuntime_StartOptions](#abilityruntime_startoptions) *startOptions, int32_t windowTop) | Sets the top position of the window when the ability is started, in px.| +| [AbilityRuntime_ErrorCode](#abilityruntime_errorcode) [OH_AbilityRuntime_GetStartOptionsWindowTop](#oh_abilityruntime_getstartoptionswindowtop)([AbilityRuntime_StartOptions](#abilityruntime_startoptions) *startOptions, int32_t &windowTop) | Obtains the top position of the window when the ability is started, in px.| +| [AbilityRuntime_ErrorCode](#abilityruntime_errorcode) [OH_AbilityRuntime_SetStartOptionsWindowHeight](#oh_abilityruntime_setstartoptionswindowheight)([AbilityRuntime_StartOptions](#abilityruntime_startoptions) *startOptions, int32_t windowHeight) | Sets the height of the window when the ability is started, in px.| +| [AbilityRuntime_ErrorCode](#abilityruntime_errorcode) [OH_AbilityRuntime_GetStartOptionsWindowHeight](#oh_abilityruntime_getstartoptionswindowheight)([AbilityRuntime_StartOptions](#abilityruntime_startoptions) *startOptions, int32_t &windowHeight) | Obtains the height of the window when the ability is started, in px.| +| [AbilityRuntime_ErrorCode](#abilityruntime_errorcode) [OH_AbilityRuntime_SetStartOptionsWindowWidth](#oh_abilityruntime_setstartoptionswindowwidth)([AbilityRuntime_StartOptions](#abilityruntime_startoptions) *startOptions, int32_t windowWidth) | Sets the width of the window when the ability is started, in px.| +| [AbilityRuntime_ErrorCode](#abilityruntime_errorcode) [OH_AbilityRuntime_GetStartOptionsWindowWidth](#oh_abilityruntime_getstartoptionswindowwidth)([AbilityRuntime_StartOptions](#abilityruntime_startoptions) *startOptions, int32_t &windowWidth) | Obtains the width of the window when the ability is started, in px.| +| [AbilityRuntime_ErrorCode](#abilityruntime_errorcode) [OH_AbilityRuntime_SetStartOptionsStartWindowIcon](#oh_abilityruntime_setstartoptionsstartwindowicon)([AbilityRuntime_StartOptions](#abilityruntime_startoptions) *startOptions, [OH_PixelmapNative](../apis-image-kit/_image___native_module.md#oh_pixelmapnative) *startWindowIcon) | Sets the startup icon of the window when the ability is started.| +| [AbilityRuntime_ErrorCode](#abilityruntime_errorcode) [OH_AbilityRuntime_GetStartOptionsStartWindowIcon](#oh_abilityruntime_getstartoptionsstartwindowicon)([AbilityRuntime_StartOptions](#abilityruntime_startoptions) *startOptions, [OH_PixelmapNative](../apis-image-kit/_image___native_module.md#oh_pixelmapnative) **startWindowIcon) | Obtains the startup icon of the window when the ability is started.| +| [AbilityRuntime_ErrorCode](#abilityruntime_errorcode) [OH_AbilityRuntime_SetStartOptionsStartWindowBackgroundColor](#oh_abilityruntime_setstartoptionsstartwindowbackgroundcolor)([AbilityRuntime_StartOptions](#abilityruntime_startoptions) *startOptions, const char *startWindowBackgroundColor) | Sets the background color of the window when the ability is started.| +| [AbilityRuntime_ErrorCode](#abilityruntime_errorcode) [OH_AbilityRuntime_GetStartOptionsStartWindowBackgroundColor](#oh_abilityruntime_getstartoptionsstartwindowbackgroundcolor)([AbilityRuntime_StartOptions](#abilityruntime_startoptions) *startOptions, char **startWindowBackgroundColor, size_t &size) | Obtains the background color of the window when the ability is started.| +| [AbilityRuntime_ErrorCode](#abilityruntime_errorcode) [OH_AbilityRuntime_SetStartOptionsSupportedWindowModes](#oh_abilityruntime_setstartoptionssupportedwindowmodes)([AbilityRuntime_StartOptions](#abilityruntime_startoptions) *startOptions, [AbilityRuntime_SupportedWindowMode](#abilityruntime_supportedwindowmode) *supportedWindowModes, size_t size) | Sets the window modes supported by the ability when it is started.| +| [AbilityRuntime_ErrorCode](#abilityruntime_errorcode) [OH_AbilityRuntime_GetStartOptionsSupportedWindowModes](#oh_abilityruntime_getstartoptionssupportedwindowmodes)([AbilityRuntime_StartOptions](#abilityruntime_startoptions) *startOptions, [AbilityRuntime_SupportedWindowMode](#abilityruntime_supportedwindowmode) **supportedWindowModes, size_t &size) | Obtains the window modes supported by the ability when it is started.| +| [AbilityRuntime_ErrorCode](#abilityruntime_errorcode) [OH_AbilityRuntime_SetStartOptionsMinWindowWidth](#oh_abilityruntime_setstartoptionsminwindowwidth)([AbilityRuntime_StartOptions](#abilityruntime_startoptions) *startOptions, int32_t minWindowWidth) | Sets the minimum window width for starting the ability, in vp.| +| [AbilityRuntime_ErrorCode](#abilityruntime_errorcode) [OH_AbilityRuntime_GetStartOptionsMinWindowWidth](#oh_abilityruntime_getstartoptionsminwindowwidth)([AbilityRuntime_StartOptions](#abilityruntime_startoptions) *startOptions, int32_t &minWindowWidth) | Obtains the minimum window width for starting the ability, in vp.| +| [AbilityRuntime_ErrorCode](#abilityruntime_errorcode) [OH_AbilityRuntime_SetStartOptionsMaxWindowWidth](#oh_abilityruntime_setstartoptionsmaxwindowwidth)([AbilityRuntime_StartOptions](#abilityruntime_startoptions) *startOptions, int32_t maxWindowWidth) | Sets the maximum window width for starting the ability, in vp.| +| [AbilityRuntime_ErrorCode](#abilityruntime_errorcode) [OH_AbilityRuntime_GetStartOptionsMaxWindowWidth](#oh_abilityruntime_getstartoptionsmaxwindowwidth)([AbilityRuntime_StartOptions](#abilityruntime_startoptions) *startOptions, int32_t &maxWindowWidth) | Obtains the maximum window width for starting the ability, in vp.| +| [AbilityRuntime_ErrorCode](#abilityruntime_errorcode) [OH_AbilityRuntime_SetStartOptionsMinWindowHeight](#oh_abilityruntime_setstartoptionsminwindowheight)([AbilityRuntime_StartOptions](#abilityruntime_startoptions) *startOptions, int32_t minWindowHeight) | Sets the minimum window height for starting the ability, in vp.| +| [AbilityRuntime_ErrorCode](#abilityruntime_errorcode) [OH_AbilityRuntime_GetStartOptionsMinWindowHeight](#oh_abilityruntime_getstartoptionsminwindowheight)([AbilityRuntime_StartOptions](#abilityruntime_startoptions) *startOptions, int32_t &minWindowHeight) | Obtains the minimum window height for starting the ability, in vp.| +| [AbilityRuntime_ErrorCode](#abilityruntime_errorcode) [OH_AbilityRuntime_SetStartOptionsMaxWindowHeight](#oh_abilityruntime_setstartoptionsmaxwindowheight)([AbilityRuntime_StartOptions](#abilityruntime_startoptions) *startOptions, int32_t maxWindowHeig) | Sets the maximum window height for starting the ability, in vp.| +| [AbilityRuntime_ErrorCode](#abilityruntime_errorcode) [OH_AbilityRuntime_GetStartOptionsMaxWindowHeight](#oh_abilityruntime_getstartoptionsmaxwindowheight)([AbilityRuntime_StartOptions](#abilityruntime_startoptions) *startOptions, int32_t &maxWindowHeight) | Obtains the maximum window height for starting the ability, in vp.| +| [AbilityRuntime_ErrorCode](#abilityruntime_errorcode) [OH_AbilityRuntime_StartSelfUIAbilityWithStartOptions](#oh_abilityruntime_startselfuiabilitywithstartoptions)([AbilityBase_Want](_ability_base.md#abilitybase_want) *want, [AbilityRuntime_StartOptions](#abilityruntime_startoptions) *options) | Starts the UIAbility of the current application.| + +## Structs + +### AbilityRuntime_StartOptions + +``` +AbilityRuntime_StartOptions +``` + +**Description** + +StartOptions struct. + +**Since**: 17 ## Enum Description @@ -60,8 +109,25 @@ Enumerates the error codes used by the ability framework. | Value | Description | | --------------------------------------------- | -------------- | | ABILITY_RUNTIME_ERROR_CODE_NO_ERROR | Operation successful. | -| ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID ARAM | Invalid parameter. | +| ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID | Invalid parameter. | | ABILITY_RUNTIME_ERROR_CODE_CONTEXT_NOT_EXIST | The context does not exist.| +| ABILITY_RUNTIME_ERROR_CODE_PERMISSION_DENIED | Permission verification failed.
**Since**: 15| +| ABILITY_RUNTIME_ERROR_CODE_NOT_SUPPORTED | The device type is not supported.
**Since**: 15| +| ABILITY_RUNTIME_ERROR_CODE_NO_SUCH_ABILITY | The specified ability name does not exist.
**Since**: 15| +| ABILITY_RUNTIME_ERROR_CODE_INCORRECT_ABILITY_TYPE | The ability type is incorrect.
**Since**: 15| +| ABILITY_RUNTIME_ERROR_CODE_CROWDTEST_EXPIRED | The crowdtesting application expires.
**Since**: 15| +| ABILITY_RUNTIME_ERROR_CODE_WUKONG_MODE | An ability cannot be started or stopped in Wukong mode.
**Since**: 15| +| ABILITY_RUNTIME_ERROR_CODE_CONTROLLED | The application is under control.
**Since**: 15| +| ABILITY_RUNTIME_ERROR_CODE_EDM_CONTROLLED | The application is under control by EDM.
**Since**: 15| +| ABILITY_RUNTIME_ERROR_CODE_CROSS_APP | Redirection to third-party applications is not allowed in API versions later than 11.
**Since**: 15| +| ABILITY_RUNTIME_ERROR_CODE_INTERNAL | Internal error.
**Since**: 15| +| ABILITY_RUNTIME_ERROR_CODE_NOT_TOP_ABILITY | The application is not on top.
**Since**: 15| +| ABILITY_RUNTIME_ERROR_VISIBILITY_SETTING_DISABLED | The window visibility cannot be set when the application is started.
**Since**: 17| +| ABILITY_RUNTIME_ERROR_CODE_MULTI_APP_NOT_SUPPORTED | The application does not support clone or multi-instance mode.
**Since**: 17| +| ABILITY_RUNTIME_ERROR_CODE_INVALID_APP_INSTANCE_KEY | The instance key is invalid.
**Since**: 17| +| ABILITY_RUNTIME_ERROR_CODE_UPPER_LIMIT_REACHED | The number of instances has reached the upper limit.
**Since**: 17| +| ABILITY_RUNTIME_ERROR_MULTI_INSTANCE_NOT_SUPPORTED | The application does not support multi-instance mode.
**Since**: 17| +| ABILITY_RUNTIME_ERROR_CODE_APP_INSTANCE_KEY_NOT_SUPPORTED | Setting **instanceKey** is not supported.
**Since**: 17| ### AbilityRuntime_AreaMode @@ -83,6 +149,41 @@ Enumerates the data encryption levels. | ABILITY_RUNTIME_AREA_MODE_EL4 | For files that are related to user security information and do not need to be read, written, or created when the screen is locked, the application can place them in EL4.| | ABILITY_RUNTIME_AREA_MODE_EL5 | By default, sensitive user privacy files cannot be read or written on the lock screen. If such files need to be read or written on the lock screen, you can call [Access](js-apis-screenLockFileManager.md#screenlockfilemanageracquireaccess) to apply for reading or writing files before the screen is locked or create new files that can be read and written after the screen is locked. It is more appropriate to place these files in EL5.| +### AbilityRuntime_WindowMode + +``` +enum AbilityRuntime_WindowMode +``` + +**Description** + +Enumerates the window modes in which an ability can be displayed at startup. + +**Since**: 17 + +| Value | Description | +| ----------------------------- | ------------------------------------------------------------ | +| ABILITY_RUNTIME_WINDOW_MODE_UNDEFINED | Undefined window mode.| +| ABILITY_RUNTIME_WINDOW_MODE_FULL_SCREEN | Full-screen mode. This mode takes effect only on 2-in-1 devices.| + +### AbilityRuntime_SupportedWindowMode + +``` +enum AbilityRuntime_SupportedWindowMode +``` + +**Description** + +Enumerates the window modes supported by an ability when it is started. The supported window mode specifies whether to display the maximize, minimize, or split-screen button when the UIAbility is launched in an application. If this enum is not set, the value of **supportWindowMode** configured under [abilities](../../quick-start/module-configuration-file.md#abilities) in the [module.json5 file](../../quick-start/module-configuration-file.md) corresponding to the UIAbility is used by default. + +**Since**: 17 + +| Value | Description | +| ----------------------------- | ------------------------------------------------------------ | +| ABILITY_RUNTIME_SUPPORTED_WINDOW_MODE_FULL_SCREEN | A window in full-screen mode is supported.| +| ABILITY_RUNTIME_SUPPORTED_WINDOW_MODE_SPLIT | A window in split-screen mode is supported. Generally, **ABILITY_RUNTIME_SUPPORTED_WINDOW_MODE_FULL_SCREEN** or **ABILITY_RUNTIME_SUPPORTED_WINDOW_MODE_FLOATING** must be used together. You are not advised to configure only **ABILITY_RUNTIME_SUPPORTED_WINDOW_MODE_SPLIT**. If only **ABILITY_RUNTIME_SUPPORTED_WINDOW_MODE_SPLIT** is configured, the window on 2-in-1 devices is in floating window mode by default and can transition to the split-screen mode. | +| ABILITY_RUNTIME_SUPPORTED_WINDOW_MODE_FLOATING | A floating window is supported.| + ## Function Description @@ -177,7 +278,7 @@ AbilityRuntime_ErrorCode OH_AbilityRuntime_ApplicationContextGetTempDir(char* bu Obtains the application-level temporary file directory. -**Valid since**: 16 +**Since**: 16 **Parameters** @@ -205,7 +306,7 @@ AbilityRuntime_ErrorCode OH_AbilityRuntime_ApplicationContextGetFilesDir(char* b Obtains the application-level common file directory. -**Valid since**: 16 +**Since**: 16 **Parameters** @@ -233,7 +334,7 @@ AbilityRuntime_ErrorCode OH_AbilityRuntime_ApplicationContextGetDatabaseDir(char Obtains the application-level database file directory. -**Valid since**: 16 +**Since**: 16 **Parameters** @@ -261,7 +362,7 @@ AbilityRuntime_ErrorCode OH_AbilityRuntime_ApplicationContextGetPreferencesDir(c Obtains the application-level preferences file directory. -**Valid since**: 16 +**Since**: 16 **Parameters** @@ -289,7 +390,7 @@ AbilityRuntime_ErrorCode OH_AbilityRuntime_ApplicationContextGetBundleCodeDir(ch Obtains the application-level installation file directory. -**Valid since**: 16 +**Since**: 16 **Parameters** @@ -317,7 +418,7 @@ AbilityRuntime_ErrorCode OH_AbilityRuntime_ApplicationContextGetDistributedFiles Obtains the application-level distributed file directory. -**Valid since**: 16 +**Since**: 16 **Parameters** @@ -345,7 +446,7 @@ AbilityRuntime_ErrorCode OH_AbilityRuntime_ApplicationContextGetCloudFileDir(cha Obtains the application-level cloud file directory. -**Valid since**: 16 +**Since**: 16 **Parameters** @@ -362,3 +463,1660 @@ Returns **ABILITY_RUNTIME_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID** if the passed-in value of **buffer** or **writeLength** is null or the buffer size is less than the size of the string to be written. Returns **ABILITY_RUNTIME_ERROR_CODE_CONTEXT_NOT_EXIST** if the context of the current environment does not exist. For example, the application-level context does not exist in the [child process](c-apis-ability-childprocess.md) created by the application. + +### OH_AbilityRuntime_StartSelfUIAbility + +``` +AbilityRuntime_ErrorCode OH_AbilityRuntime_StartSelfUIAbility(AbilityBase_Want *want) +``` + +**Description** + +Starts the UIAbility of the current application. + +> **NOTE** +> +> This function is valid only for 2-in-1 devices. + +**Required permissions**: ohos.permission.NDK_START_SELF_UI_ABILITY + +**Since**: 15 + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| want | Pointer to the Want information required for starting the UIAbility. | + +**Returns** + +Returns **ABILITY_RUNTIME_ERROR_CODE_NO_ERROR** if the API call is successful. + +Returns **ABILITY_RUNTIME_ERROR_CODE_PERMISSION_DENIED** if permission verification failed. + +Returns **ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID** if the Want information is empty, or if the bundleName or abilityName in the Want information is empty. + +Returns **ABILITY_RUNTIME_ERROR_CODE_NOT_SUPPORTED** if the device type is not supported. + +Returns **ABILITY_RUNTIME_ERROR_CODE_NO_SUCH_ABILITY** if the specified ability name does not exist. + +Returns **ABILITY_RUNTIME_ERROR_CODE_INCORRECT_ABILITY_TYPE** if the ability type is incorrect. + +Returns **ABILITY_RUNTIME_ERROR_CODE_CROWDTEST_EXPIRED** if the crowdtesting application expires. + +Returns **ABILITY_RUNTIME_ERROR_CODE_WUKONG_MODE** if the ability is started or stopped in Wukong mode. + +Returns **ABILITY_RUNTIME_ERROR_CODE_CONTROLLED** if the application is under control. + +Returns **ABILITY_RUNTIME_ERROR_CODE_EDM_CONTROLLED** if the application is under control by EDM. + +Returns **ABILITY_RUNTIME_ERROR_CODE_CROSS_APP** for an attempt to redirection to third-party applications in API versions later than 11. + +Returns **ABILITY_RUNTIME_ERROR_CODE_INTERNAL** if an internal error occurs. + +Returns **ABILITY_RUNTIME_ERROR_CODE_NOT_TOP_ABILITY** if the application is not a top one. + +Returns **ABILITY_RUNTIME_ERROR_CODE_UPPER_LIMIT_REACHED** if the number of instances has reached the upper limit. + +Returns **ABILITY_RUNTIME_ERROR_CODE_APP_INSTANCE_KEY_NOT_SUPPORTED** if **APP_INSTANCE_KEY** cannot be set. + +**Example** +```cpp +#include +#include + +void startSelfUIAbilityTest() +{ + AbilityBase_Element element; + element.abilityName = const_cast("EntryAbility"); + element.bundleName = const_cast("com.exampl.myapplication"); + element.moduleName = const_cast("entry"); + AbilityBase_Want* want = OH_AbilityBase_CreateWant(element); + + AbilityRuntime_ErrorCode err = OH_AbilityRuntime_StartSelfUIAbility(want); + if (err != ABILITY_RUNTIME_ERROR_CODE_NO_ERROR) { + // Record error logs and other service processing. + return; + } + // Destroy the Want to prevent memory leakage. + OH_AbilityBase_DestroyWant(want); +} +``` + +### OH_AbilityRuntime_CreateStartOptions + +``` +AbilityRuntime_StartOptions* OH_AbilityRuntime_CreateStartOptions(void) +``` + +**Description** + +Creates the StartOptions struct required for starting the UIAbility of the current application. + +**Since**: 17 + +**Returns** + +Returns the pointer to **AbilityRuntime_StartOptions**, which is the StartOptions struct. + +**Example** +```cpp +#include + +void createStartOptionsTest() +{ + AbilityRuntime_StartOptions* options = OH_AbilityRuntime_CreateStartOptions(); + if (options == nullptr) { + // Record error logs and other service processing. + return; + } + + // Destroy options to prevent memory leakage. + OH_AbilityRuntime_DestroyStartOptions(&options); +} +``` + +### OH_AbilityRuntime_DestroyStartOptions + +``` +AbilityRuntime_ErrorCode OH_AbilityRuntime_DestroyStartOptions(AbilityRuntime_StartOptions **startOptions) +``` + +**Description** + +Destroys a StartOptions struct. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| startOptions | Double pointer to the StartOptions struct. | + +**Since**: 17 + +**Returns** + +Returns **ABILITY_RUNTIME_ERROR_CODE_NO_ERROR** if the struct is destroyed successfully. + +Returns **ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID** if **startOptions** is null. + +**Example** +```cpp +#include + +void destroyStartOptionsTest() +{ + AbilityRuntime_StartOptions* options = OH_AbilityRuntime_CreateStartOptions(); + if (options == nullptr) { + // Record error logs and other service processing. + return; + } + + // Destroy options to prevent memory leakage. + OH_AbilityRuntime_DestroyStartOptions(&options); +} +``` + +### OH_AbilityRuntime_SetStartOptionsWindowMode + +``` +AbilityRuntime_ErrorCode OH_AbilityRuntime_SetStartOptionsWindowMode(AbilityRuntime_StartOptions *startOptions, + AbilityRuntime_WindowMode windowMode); +``` + +**Description** + +Sets the window mode for starting an ability. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| startOptions | Pointer to the StartOptions struct. | +| windowMode | Window mode. | + +**Since**: 17 + +**Returns** + +Returns **ABILITY_RUNTIME_ERROR_CODE_NO_ERROR** if the setting is successful. + +Returns **ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID** if **startOptions** is null or **WindowMode** is invalid. + +**Example** +```cpp +#include + +void demo() +{ + AbilityRuntime_StartOptions* options = OH_AbilityRuntime_CreateStartOptions(); + if (options == nullptr) { + // Record error logs and other service processing. + return; + } + + AbilityRuntime_ErrorCode err = OH_AbilityRuntime_SetStartOptionsWindowMode(options, + ABILITY_RUNTIME_WINDOW_MODE_FULL_SCREEN); + if (err != ABILITY_RUNTIME_ERROR_CODE_NO_ERROR) { + // Record error logs and other service processing. + } + // Destroy options to prevent memory leakage. + OH_AbilityRuntime_DestroyStartOptions(&options); +} +``` + +### OH_AbilityRuntime_GetStartOptionsWindowMode + +``` +AbilityRuntime_ErrorCode OH_AbilityRuntime_GetStartOptionsWindowMode(AbilityRuntime_StartOptions *startOptions, + AbilityRuntime_WindowMode &windowMode); +``` + +**Description** + +Obtains the window mode for starting an ability. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| startOptions | Pointer to the StartOptions struct. | +| windowMode | Window mode. | + +**Since**: 17 + +**Returns** + +Returns **ABILITY_RUNTIME_ERROR_CODE_NO_ERROR** if the information is obtained successfully. + +Returns **ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID** if **startOptions** is null. + +**Example** +```cpp +#include + +void demo() +{ + AbilityRuntime_StartOptions* options = OH_AbilityRuntime_CreateStartOptions(); + if (options == nullptr) { + // Record error logs and other service processing. + return; + } + + AbilityRuntime_WindowMode windowMode = ABILITY_RUNTIME_WINDOW_MODE_UNDEFINED; + AbilityRuntime_ErrorCode err = OH_AbilityRuntime_GetStartOptionsWindowMode(options, windowMode); + if (err != ABILITY_RUNTIME_ERROR_CODE_NO_ERROR) { + // Record error logs and other service processing. + } + // Destroy options to prevent memory leakage. + OH_AbilityRuntime_DestroyStartOptions(&options); +} +``` + +### OH_AbilityRuntime_SetStartOptionsDisplayId + +``` +AbilityRuntime_ErrorCode OH_AbilityRuntime_SetStartOptionsDisplayId(AbilityRuntime_StartOptions *startOptions, int32_t displayId); +``` + +**Description** + +Sets the ID of the display where the window is launched when the ability is started. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| startOptions | Pointer to the StartOptions struct. | +| displayId | Display ID. | + +**Since**: 17 + +**Returns** + +Returns **ABILITY_RUNTIME_ERROR_CODE_NO_ERROR** if the setting is successful. + +Returns **ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID** if **startOptions** is null. + +**Example** +```cpp +#include + +void demo() +{ + AbilityRuntime_StartOptions* options = OH_AbilityRuntime_CreateStartOptions(); + if (options == nullptr) { + // Record error logs and other service processing. + return; + } + + AbilityRuntime_ErrorCode err = OH_AbilityRuntime_SetStartOptionsDisplayId(options, 1); + if (err != ABILITY_RUNTIME_ERROR_CODE_NO_ERROR) { + // Record error logs and other service processing. + } + // Destroy options to prevent memory leakage. + OH_AbilityRuntime_DestroyStartOptions(&options); +} +``` + +### OH_AbilityRuntime_GetStartOptionsDisplayId + +``` +AbilityRuntime_ErrorCode OH_AbilityRuntime_GetStartOptionsDisplayId(AbilityRuntime_StartOptions *startOptions, int32_t &displayId); +``` + +**Description** + +Obtains the ID of the display where the window is launched when the ability is started. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| startOptions | Pointer to the StartOptions struct. | +| displayId | Display ID. | + +**Since**: 17 + +**Returns** + +Returns **ABILITY_RUNTIME_ERROR_CODE_NO_ERROR** if the information is obtained successfully. + +Returns **ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID** if **startOptions** is null. + +**Example** +```cpp +#include + +void demo() +{ + AbilityRuntime_StartOptions* options = OH_AbilityRuntime_CreateStartOptions(); + if (options == nullptr) { + // Record error logs and other service processing. + return; + } + + int32_t displayId = 0; + AbilityRuntime_ErrorCode err = OH_AbilityRuntime_GetStartOptionsDisplayId(options, displayId); + if (err != ABILITY_RUNTIME_ERROR_CODE_NO_ERROR) { + // Record error logs and other service processing. + } + // Destroy options to prevent memory leakage. + OH_AbilityRuntime_DestroyStartOptions(&options); +} +``` + +### OH_AbilityRuntime_SetStartOptionsWithAnimation + +``` +AbilityRuntime_ErrorCode OH_AbilityRuntime_SetStartOptionsWithAnimation(AbilityRuntime_StartOptions *startOptions, bool withAnimation); +``` + +**Description** + +Sets whether to use animation effects when an ability is started. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| startOptions | Pointer to the StartOptions struct. | +| withAnimation | Whether to use animation effects. | + +**Since**: 17 + +**Returns** + +Returns **ABILITY_RUNTIME_ERROR_CODE_NO_ERROR** if the setting is successful. + +Returns **ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID** if **startOptions** is null. + +**Example** +```cpp +#include + +void demo() +{ + AbilityRuntime_StartOptions* options = OH_AbilityRuntime_CreateStartOptions(); + if (options == nullptr) { + // Record error logs and other service processing. + return; + } + + AbilityRuntime_ErrorCode err = OH_AbilityRuntime_SetStartOptionsWithAnimation(options, true); + if (err != ABILITY_RUNTIME_ERROR_CODE_NO_ERROR) { + // Record error logs and other service processing. + } + // Destroy options to prevent memory leakage. + OH_AbilityRuntime_DestroyStartOptions(&options); +} +``` + +### OH_AbilityRuntime_GetStartOptionsWithAnimation + +``` +AbilityRuntime_ErrorCode OH_AbilityRuntime_GetStartOptionsWithAnimation(AbilityRuntime_StartOptions *startOptions, bool &withAnimation); +``` + +**Description** + +Checks whether animation effects are used when an ability is started. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| startOptions | Pointer to the StartOptions struct. | +| withAnimation | Whether animation effects are used. | + +**Since**: 17 + +**Returns** + +Returns **ABILITY_RUNTIME_ERROR_CODE_NO_ERROR** if the information is obtained successfully. + +Returns **ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID** if **startOptions** is null. + +**Example** +```cpp +#include + +void demo() +{ + AbilityRuntime_StartOptions* options = OH_AbilityRuntime_CreateStartOptions(); + if (options == nullptr) { + // Record error logs and other service processing. + return; + } + + bool withAnimation = false; + AbilityRuntime_ErrorCode err = OH_AbilityRuntime_GetStartOptionsWithAnimation(options, withAnimation); + if (err != ABILITY_RUNTIME_ERROR_CODE_NO_ERROR) { + // Record error logs and other service processing. + } + // Destroy options to prevent memory leakage. + OH_AbilityRuntime_DestroyStartOptions(&options); +} +``` + +### OH_AbilityRuntime_SetStartOptionsWindowLeft + +``` +AbilityRuntime_ErrorCode OH_AbilityRuntime_SetStartOptionsWindowLeft(AbilityRuntime_StartOptions *startOptions, int32_t windowLeft); +``` + +**Description** + +Sets the left position of the window when the ability is started, in px. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| startOptions | Pointer to the StartOptions struct. | +| windowLeft | Left position of the window, in px. | + +**Since**: 17 + +**Returns** + +Returns **ABILITY_RUNTIME_ERROR_CODE_NO_ERROR** if the setting is successful. + +Returns **ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID** if **startOptions** is null. + +**Example** +```cpp +#include + +void demo() +{ + AbilityRuntime_StartOptions* options = OH_AbilityRuntime_CreateStartOptions(); + if (options == nullptr) { + // Record error logs and other service processing. + return; + } + + AbilityRuntime_ErrorCode err = OH_AbilityRuntime_SetStartOptionsWindowLeft(options, 200); + if (err != ABILITY_RUNTIME_ERROR_CODE_NO_ERROR) { + // Record error logs and other service processing. + } + // Destroy options to prevent memory leakage. + OH_AbilityRuntime_DestroyStartOptions(&options); +} +``` + +### OH_AbilityRuntime_GetStartOptionsWindowLeft + +``` +AbilityRuntime_ErrorCode OH_AbilityRuntime_GetStartOptionsWindowLeft(AbilityRuntime_StartOptions *startOptions, int32_t &windowLeft); +``` + +**Description** + +Obtains the left position of the window when the ability is started, in px. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| startOptions | Pointer to the StartOptions struct. | +| windowLeft | Left position of the window, in px. | + +**Since**: 17 + +**Returns** + +Returns **ABILITY_RUNTIME_ERROR_CODE_NO_ERROR** if the information is obtained successfully. + +Returns **ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID** if **startOptions** is null. + +**Example** +```cpp +#include + +void demo() +{ + AbilityRuntime_StartOptions* options = OH_AbilityRuntime_CreateStartOptions(); + if (options == nullptr) { + // Record error logs and other service processing. + return; + } + + int32_t windowLeft = 0; + AbilityRuntime_ErrorCode err = OH_AbilityRuntime_GetStartOptionsWindowLeft(options, windowLeft); + if (err != ABILITY_RUNTIME_ERROR_CODE_NO_ERROR) { + // Record error logs and other service processing. + } + // Destroy options to prevent memory leakage. + OH_AbilityRuntime_DestroyStartOptions(&options); +} +``` + +### OH_AbilityRuntime_SetStartOptionsWindowTop + +``` +AbilityRuntime_ErrorCode OH_AbilityRuntime_SetStartOptionsWindowTop(AbilityRuntime_StartOptions *startOptions, int32_t windowTop); +``` + +**Description** + +Sets the top position of the window when the ability is started, in px. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| startOptions | Pointer to the StartOptions struct. | +| windowTop | Top position of the window, in px. | + +**Since**: 17 + +**Returns** + +Returns **ABILITY_RUNTIME_ERROR_CODE_NO_ERROR** if the setting is successful. + +Returns **ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID** if **startOptions** is null. + +**Example** +```cpp +#include + +void demo() +{ + AbilityRuntime_StartOptions* options = OH_AbilityRuntime_CreateStartOptions(); + if (options == nullptr) { + // Record error logs and other service processing. + return; + } + + AbilityRuntime_ErrorCode err = OH_AbilityRuntime_SetStartOptionsWindowTop(options, 500); + if (err != ABILITY_RUNTIME_ERROR_CODE_NO_ERROR) { + // Record error logs and other service processing. + } + // Destroy options to prevent memory leakage. + OH_AbilityRuntime_DestroyStartOptions(&options); +} +``` + +### OH_AbilityRuntime_GetStartOptionsWindowTop + +``` +AbilityRuntime_ErrorCode OH_AbilityRuntime_GetStartOptionsWindowTop(AbilityRuntime_StartOptions *startOptions, int32_t &windowTop); +``` + +**Description** + +Obtains the top position of the window when the ability is started, in px. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| startOptions | Pointer to the StartOptions struct. | +| windowTop | Top position of the window, in px. | + +**Since**: 17 + +**Returns** + +Returns **ABILITY_RUNTIME_ERROR_CODE_NO_ERROR** if the information is obtained successfully. + +Returns **ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID** if **startOptions** is null. + +**Example** +```cpp +#include + +void demo() +{ + AbilityRuntime_StartOptions* options = OH_AbilityRuntime_CreateStartOptions(); + if (options == nullptr) { + // Record error logs and other service processing. + return; + } + + int32_t windowTop = 0; + AbilityRuntime_ErrorCode err = OH_AbilityRuntime_GetStartOptionsWindowTop(options, windowTop); + if (err != ABILITY_RUNTIME_ERROR_CODE_NO_ERROR) { + // Record error logs and other service processing. + } + // Destroy options to prevent memory leakage. + OH_AbilityRuntime_DestroyStartOptions(&options); +} +``` + +### OH_AbilityRuntime_SetStartOptionsWindowHeight + +``` +AbilityRuntime_ErrorCode OH_AbilityRuntime_SetStartOptionsWindowHeight(AbilityRuntime_StartOptions *startOptions, int32_t windowHeight); +``` + +**Description** + +Sets the height of the window when the ability is started, in px. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| startOptions | Pointer to the StartOptions struct. | +| windowHeight | Window height, in px. | + +**Since**: 17 + +**Returns** + +Returns **ABILITY_RUNTIME_ERROR_CODE_NO_ERROR** if the setting is successful. + +Returns **ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID** if **startOptions** is null. + +**Example** +```cpp +#include + +void demo() +{ + AbilityRuntime_StartOptions* options = OH_AbilityRuntime_CreateStartOptions(); + if (options == nullptr) { + // Record error logs and other service processing. + return; + } + + AbilityRuntime_ErrorCode err = OH_AbilityRuntime_SetStartOptionsWindowHeight(options, 500); + if (err != ABILITY_RUNTIME_ERROR_CODE_NO_ERROR) { + // Record error logs and other service processing. + } + // Destroy options to prevent memory leakage. + OH_AbilityRuntime_DestroyStartOptions(&options); +} +``` + +### OH_AbilityRuntime_GetStartOptionsWindowHeight + +``` +AbilityRuntime_ErrorCode OH_AbilityRuntime_GetStartOptionsWindowHeight(AbilityRuntime_StartOptions *startOptions, int32_t &windowHeight); +``` + +**Description** + +Obtains the height of the window when the ability is started, in px. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| startOptions | Pointer to the StartOptions struct. | +| windowHeight | Window height, in px. | + +**Since**: 17 + +**Returns** + +Returns **ABILITY_RUNTIME_ERROR_CODE_NO_ERROR** if the information is obtained successfully. + +Returns **ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID** if **startOptions** is null. + +**Example** +```cpp +#include + +void demo() +{ + AbilityRuntime_StartOptions* options = OH_AbilityRuntime_CreateStartOptions(); + if (options == nullptr) { + // Record error logs and other service processing. + return; + } + + int32_t windowHeight = 0; + AbilityRuntime_ErrorCode err = OH_AbilityRuntime_GetStartOptionsWindowHeight(options, windowHeight); + if (err != ABILITY_RUNTIME_ERROR_CODE_NO_ERROR) { + // Record error logs and other service processing. + } + // Destroy options to prevent memory leakage. + OH_AbilityRuntime_DestroyStartOptions(&options); +} +``` + +### OH_AbilityRuntime_SetStartOptionsWindowWidth + +``` +AbilityRuntime_ErrorCode OH_AbilityRuntime_SetStartOptionsWindowWidth(AbilityRuntime_StartOptions *startOptions, int32_t windowWidth); +``` + +**Description** + +Sets the width of the window when the ability is started, in px. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| startOptions | Pointer to the StartOptions struct. | +| windowWidth | Window width, in px. | + +**Since**: 17 + +**Returns** + +Returns **ABILITY_RUNTIME_ERROR_CODE_NO_ERROR** if the setting is successful. + +Returns **ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID** if **startOptions** is null. + +**Example** +```cpp +#include + +void demo() +{ + AbilityRuntime_StartOptions* options = OH_AbilityRuntime_CreateStartOptions(); + if (options == nullptr) { + // Record error logs and other service processing. + return; + } + + AbilityRuntime_ErrorCode err = OH_AbilityRuntime_SetStartOptionsWindowWidth(options, 500); + if (err != ABILITY_RUNTIME_ERROR_CODE_NO_ERROR) { + // Record error logs and other service processing. + } + // Destroy options to prevent memory leakage. + OH_AbilityRuntime_DestroyStartOptions(&options); +} +``` + +### OH_AbilityRuntime_GetStartOptionsWindowWidth + +``` +AbilityRuntime_ErrorCode OH_AbilityRuntime_GetStartOptionsWindowWidth(AbilityRuntime_StartOptions *startOptions, int32_t &windowWidth); +``` + +**Description** + +Obtains the width of the window when the ability is started, in px. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| startOptions | Pointer to the StartOptions struct. | +| windowWidth | Window width, in px. | + +**Since**: 17 + +**Returns** + +Returns **ABILITY_RUNTIME_ERROR_CODE_NO_ERROR** if the information is obtained successfully. + +Returns **ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID** if **startOptions** is null. + +**Example** +```cpp +#include + +void demo() +{ + AbilityRuntime_StartOptions* options = OH_AbilityRuntime_CreateStartOptions(); + if (options == nullptr) { + // Record error logs and other service processing. + return; + } + + int32_t windowWidth = 0; + AbilityRuntime_ErrorCode err = OH_AbilityRuntime_GetStartOptionsWindowWidth(options, windowWidth); + if (err != ABILITY_RUNTIME_ERROR_CODE_NO_ERROR) { + // Record error logs and other service processing. + } + // Destroy options to prevent memory leakage. + OH_AbilityRuntime_DestroyStartOptions(&options); +} +``` + +### OH_AbilityRuntime_SetStartOptionsStartWindowIcon + +``` +AbilityRuntime_ErrorCode OH_AbilityRuntime_SetStartOptionsStartWindowIcon(AbilityRuntime_StartOptions *startOptions, OH_PixelmapNative *startWindowIcon) +``` + +**Description** + +Sets the startup icon of the window when the ability is started. The maximum size of an image used as the startup icon is 600 MB. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| startOptions | Pointer to the StartOptions struct. | +| startWindowIcon | Startup icon. | + +**Since**: 17 + +**Returns** + +Returns **ABILITY_RUNTIME_ERROR_CODE_NO_ERROR** if the setting is successful. + +Returns **ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID** if **startOptions** or **OH_PixelmapNative** is null. + +**Example** +```cpp +#include + +void demo() +{ + uint8_t data[96]; + size_t dataSize = 96; + for (int i = 0; i < dataSize; i++) { + data[i] = i + 1; + } + + // Create a parameter structure instance and set parameters. + OH_Pixelmap_InitializationOptions *createOpts = nullptr; + OH_PixelmapInitializationOptions_Create(&createOpts); + OH_PixelmapInitializationOptions_SetWidth(createOpts, 6); + OH_PixelmapInitializationOptions_SetHeight(createOpts, 4); + OH_PixelmapInitializationOptions_SetPixelFormat(createOpts, PIXEL_FORMAT_RGBA_8888); + OH_PixelmapInitializationOptions_SetAlphaType(createOpts, PIXELMAP_ALPHA_TYPE_UNKNOWN); + + // Create a Pixelmap instance. + OH_PixelmapNative *startWindowIcon = nullptr; + Image_ErrorCode errCode = OH_PixelmapNative_CreatePixelmap(data, dataSize, createOpts, &startWindowIcon); + if (errCode != IMAGE_SUCCESS) { + // Record error logs and other service processing. + + // Destroy createOpts to prevent memory leakage. + OH_PixelmapInitializationOptions_Release(createOpts); + return; + } + + AbilityRuntime_StartOptions* options = OH_AbilityRuntime_CreateStartOptions(); + if (options == nullptr) { + // Record error logs and other service processing. + + // Destroy createOpts to prevent memory leakage. + OH_PixelmapInitializationOptions_Release(createOpts); + + // Destroy startWindowIcon to prevent memory leakage. + OH_PixelmapNative_Release(startWindowIcon); + return; + } + + AbilityRuntime_ErrorCode err = OH_AbilityRuntime_SetStartOptionsStartWindowIcon(options, startWindowIcon); + if (err != ABILITY_RUNTIME_ERROR_CODE_NO_ERROR) { + // Record error logs and other service processing. + } + // Destroy createOpts to prevent memory leakage. + OH_PixelmapInitializationOptions_Release(createOpts); + + // Destroy startWindowIcon to prevent memory leakage. + OH_PixelmapNative_Release(startWindowIcon); + + // Destroy options to prevent memory leakage. + OH_AbilityRuntime_DestroyStartOptions(&options); +} +``` + +### OH_AbilityRuntime_GetStartOptionsStartWindowIcon + +``` +AbilityRuntime_ErrorCode OH_AbilityRuntime_GetStartOptionsStartWindowIcon(AbilityRuntime_StartOptions *startOptions, + OH_PixelmapNative **startWindowIcon) +``` + +**Description** + +Obtains the startup icon of the window when the ability is started. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| startOptions | Pointer to the StartOptions struct. | +| startWindowIcon | Startup icon. | + +**Since**: 17 + +**Returns** + +Returns **ABILITY_RUNTIME_ERROR_CODE_NO_ERROR** if the information is obtained successfully. + +Returns **ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID** if **startOptions** is null or **OH_PixelmapNative** is not set to a null pointer. + +**Example** +```cpp +#include + +void demo() +{ + AbilityRuntime_StartOptions* options = OH_AbilityRuntime_CreateStartOptions(); + if (options == nullptr) { + // Record error logs and other service processing. + return; + } + + OH_PixelmapNative *startWindowIcon = nullptr; + AbilityRuntime_ErrorCode err = OH_AbilityRuntime_GetStartOptionsStartWindowIcon(options, &startWindowIcon); + if (err != ABILITY_RUNTIME_ERROR_CODE_NO_ERROR) { + // Record error logs and other service processing. + } + + // Destroy startWindowIcon to prevent memory leakage. + OH_PixelmapNative_Release(startWindowIcon); + + // Destroy options to prevent memory leakage. + OH_AbilityRuntime_DestroyStartOptions(&options); +} +``` + +### OH_AbilityRuntime_SetStartOptionsStartWindowBackgroundColor + +``` +AbilityRuntime_ErrorCode OH_AbilityRuntime_SetStartOptionsStartWindowBackgroundColor(AbilityRuntime_StartOptions *startOptions, const char *startWindowBackgroundColor) +``` + +**Description** + +Sets the background color of the window when the ability is started. Background color of the window. If this function is not called, the value of **startWindowBackground** configured under [abilities](../../quick-start/module-configuration-file.md#abilities) in the [module.json5 file](../../quick-start/module-configuration-file.md) corresponding to the UIAbility is used by default. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| startOptions | Pointer to the StartOptions struct. | +| startWindowBackgroundColor | Background color of the window. | + +**Since**: 17 + +**Returns** + +Returns **ABILITY_RUNTIME_ERROR_CODE_NO_ERROR** if the setting is successful. + +Returns **ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID** if **startOptions** or **StartWindowBackgroundColor** is null. + +**Example** +```cpp +#include + +void demo() +{ + AbilityRuntime_StartOptions* options = OH_AbilityRuntime_CreateStartOptions(); + if (options == nullptr) { + // Record error logs and other service processing. + return; + } + + AbilityRuntime_ErrorCode err = OH_AbilityRuntime_SetStartOptionsStartWindowBackgroundColor(options, "#00000000"); + if (err != ABILITY_RUNTIME_ERROR_CODE_NO_ERROR) { + // Record error logs and other service processing. + } + + // Destroy options to prevent memory leakage. + OH_AbilityRuntime_DestroyStartOptions(&options); +} +``` + +### OH_AbilityRuntime_GetStartOptionsStartWindowBackgroundColor + +``` +AbilityRuntime_ErrorCode OH_AbilityRuntime_GetStartOptionsStartWindowBackgroundColor(AbilityRuntime_StartOptions *startOptions, char **startWindowBackgroundColor, size_t &size) +``` + +**Description** + +Obtains the background color of the window when the ability is started. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| startOptions | Pointer to the StartOptions struct. | +| startWindowBackgroundColor | Background color of the window. | +| size | Size of the background color. | + +**Since**: 17 + +**Returns** + +Returns **ABILITY_RUNTIME_ERROR_CODE_NO_ERROR** if the information is obtained successfully. + +Returns **ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID** if **startOptions** is null or **StartWindowBackgroundColor** is not set to a null pointer. + +Returns **ABILITY_RUNTIME_ERROR_CODE_INTERNAL** if an internal error that cannot be rectified, such as internal malloc error or string copy function error, occurs. + +**Example** +```cpp +#include + +#include + +void demo() +{ + AbilityRuntime_StartOptions* options = OH_AbilityRuntime_CreateStartOptions(); + if (options == nullptr) { + // Record error logs and other service processing. + return; + } + + char *startWindowBackgroundColor = nullptr; + size_t size = 0; + AbilityRuntime_ErrorCode err = OH_AbilityRuntime_GetStartOptionsStartWindowBackgroundColor(options, + &startWindowBackgroundColor, size); + if (err != ABILITY_RUNTIME_ERROR_CODE_NO_ERROR) { + // Record error logs and other service processing. + } + + if (startWindowBackgroundColor != nullptr) { + // Destroy startWindowBackgroundColor to prevent memory leakage. + free(startWindowBackgroundColor); + startWindowBackgroundColor = nullptr; + } + + // Destroy options to prevent memory leakage. + OH_AbilityRuntime_DestroyStartOptions(&options); +} +``` + +### OH_AbilityRuntime_SetStartOptionsSupportedWindowModes + +``` +AbilityRuntime_ErrorCode OH_AbilityRuntime_SetStartOptionsSupportedWindowModes(AbilityRuntime_StartOptions *startOptions, + AbilityRuntime_SupportedWindowMode *supportedWindowModes, size_t size) +``` + +**Description** + +Sets the window modes supported by the ability when it is started. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| startOptions | Pointer to the StartOptions struct. | +| supportedWindowModes | Window modes supported. | +| size | Size of the window modes supported. | + +**Since**: 17 + +**Returns** + +Returns **ABILITY_RUNTIME_ERROR_CODE_NO_ERROR** if the setting is successful. + +Returns **ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID** if **startOptions** or **SupportedWindowModes** is null, or **Size** is **0**. + +**Example** +```cpp +#include + +void demo() +{ + AbilityRuntime_StartOptions* options = OH_AbilityRuntime_CreateStartOptions(); + if (options == nullptr) { + // Record error logs and other service processing. + return; + } + + size_t supportedWindowModesSize = 3; + AbilityRuntime_SupportedWindowMode supportedWindowModes[3] = { + ABILITY_RUNTIME_SUPPORTED_WINDOW_MODE_FULL_SCREEN, + ABILITY_RUNTIME_SUPPORTED_WINDOW_MODE_SPLIT, + ABILITY_RUNTIME_SUPPORTED_WINDOW_MODE_FLOATING, + }; + AbilityRuntime_ErrorCode err = OH_AbilityRuntime_SetStartOptionsSupportedWindowModes(options, + supportedWindowModes, supportedWindowModesSize); + if (err != ABILITY_RUNTIME_ERROR_CODE_NO_ERROR) { + // Record error logs and other service processing. + } + + // Destroy options to prevent memory leakage. + OH_AbilityRuntime_DestroyStartOptions(&options); +} +``` + +### OH_AbilityRuntime_GetStartOptionsSupportedWindowModes + +``` +AbilityRuntime_ErrorCode OH_AbilityRuntime_GetStartOptionsSupportedWindowModes(AbilityRuntime_StartOptions *startOptions, + AbilityRuntime_SupportedWindowMode **supportedWindowModes, size_t &size) +``` + +**Description** + +Obtains the window modes supported by the ability when it is started. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| startOptions | Pointer to the StartOptions struct. | +| supportedWindowModes | Window modes supported. | +| size | Size of the window modes supported. | + +**Since**: 17 + +**Returns** + +Returns **ABILITY_RUNTIME_ERROR_CODE_NO_ERROR** if the information is obtained successfully. + +Returns **ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID** if **startOptions** is null or **SupportWindowMode** is not set to a null pointer. + +Returns **ABILITY_RUNTIME_ERROR_CODE_INTERNAL** if an internal error that cannot be rectified, such as internal malloc error, occurs. + +**Example** +```cpp +#include + +#include + +void demo() +{ + AbilityRuntime_StartOptions* options = OH_AbilityRuntime_CreateStartOptions(); + if (options == nullptr) { + // Record error logs and other service processing. + return; + } + + AbilityRuntime_SupportedWindowMode *supportedWindowModes = nullptr; + size_t size = 0; + AbilityRuntime_ErrorCode err = OH_AbilityRuntime_GetStartOptionsSupportedWindowModes(options, + &supportedWindowModes, size); + if (err != ABILITY_RUNTIME_ERROR_CODE_NO_ERROR) { + // Record error logs and other service processing. + } + + if (supportedWindowModes != nullptr) { + // Destroy supportedWindowModes to prevent memory leakage. + free(supportedWindowModes); + } + + // Destroy options to prevent memory leakage. + OH_AbilityRuntime_DestroyStartOptions(&options); +} +``` + +### OH_AbilityRuntime_SetStartOptionsMinWindowWidth + +``` +AbilityRuntime_ErrorCode OH_AbilityRuntime_SetStartOptionsMinWindowWidth(AbilityRuntime_StartOptions *startOptions, + int32_t minWindowWidth) +``` + +**Description** + +Sets the minimum window width for starting the ability, in vp. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| startOptions | Pointer to the StartOptions struct. | +| minWindowWidth | Minimum window width, in vp. | + +**Since**: 17 + +**Returns** + +Returns **ABILITY_RUNTIME_ERROR_CODE_NO_ERROR** if the setting is successful. + +Returns **ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID** if **startOptions** is null. + +**Example** +```cpp +#include + +void demo() +{ + AbilityRuntime_StartOptions* options = OH_AbilityRuntime_CreateStartOptions(); + if (options == nullptr) { + // Record error logs and other service processing. + return; + } + + AbilityRuntime_ErrorCode err = OH_AbilityRuntime_SetStartOptionsMinWindowWidth(options, 100); + if (err != ABILITY_RUNTIME_ERROR_CODE_NO_ERROR) { + // Record error logs and other service processing. + } + + // Destroy options to prevent memory leakage. + OH_AbilityRuntime_DestroyStartOptions(&options); +} +``` + +### OH_AbilityRuntime_GetStartOptionsMinWindowWidth + +``` +AbilityRuntime_ErrorCode OH_AbilityRuntime_GetStartOptionsMinWindowWidth(AbilityRuntime_StartOptions *startOptions, + int32_t &minWindowWidth) +``` + +**Description** + +Obtains the minimum window width for starting the ability, in vp. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| startOptions | Pointer to the StartOptions struct. | +| minWindowWidth | Minimum window width, in vp. | + +**Since**: 17 + +**Returns** + +Returns **ABILITY_RUNTIME_ERROR_CODE_NO_ERROR** if the information is obtained successfully. + +Returns **ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID** if **startOptions** is null. + +**Example** +```cpp +#include + +void demo() +{ + AbilityRuntime_StartOptions* options = OH_AbilityRuntime_CreateStartOptions(); + if (options == nullptr) { + // Record error logs and other service processing. + return; + } + + int32_t minWindowWidth = 0; + AbilityRuntime_ErrorCode err = OH_AbilityRuntime_GetStartOptionsMinWindowWidth(options, minWindowWidth); + if (err != ABILITY_RUNTIME_ERROR_CODE_NO_ERROR) { + // Record error logs and other service processing. + } + + // Destroy options to prevent memory leakage. + OH_AbilityRuntime_DestroyStartOptions(&options); +} +``` + +### OH_AbilityRuntime_SetStartOptionsMaxWindowWidth + +``` +AbilityRuntime_ErrorCode OH_AbilityRuntime_SetStartOptionsMaxWindowWidth(AbilityRuntime_StartOptions *startOptions, + int32_t maxWindowWidth) +``` + +**Description** + +Sets the maximum window width for starting the ability, in vp. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| startOptions | Pointer to the StartOptions struct. | +| maxWindowWidth | Maximum window width, in vp. | + +**Since**: 17 + +**Returns** + +Returns **ABILITY_RUNTIME_ERROR_CODE_NO_ERROR** if the setting is successful. + +Returns **ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID** if **startOptions** is null. + +**Example** +```cpp +#include + +void demo() +{ + AbilityRuntime_StartOptions* options = OH_AbilityRuntime_CreateStartOptions(); + if (options == nullptr) { + // Record error logs and other service processing. + return; + } + + AbilityRuntime_ErrorCode err = OH_AbilityRuntime_SetStartOptionsMaxWindowWidth(options, 100); + if (err != ABILITY_RUNTIME_ERROR_CODE_NO_ERROR) { + // Record error logs and other service processing. + } + + // Destroy options to prevent memory leakage. + OH_AbilityRuntime_DestroyStartOptions(&options); +} +``` + +### OH_AbilityRuntime_GetStartOptionsMaxWindowWidth + +``` +AbilityRuntime_ErrorCode OH_AbilityRuntime_GetStartOptionsMaxWindowWidth(AbilityRuntime_StartOptions *startOptions, + int32_t &maxWindowWidth) +``` + +**Description** + +Obtains the maximum window width for starting the ability, in vp. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| startOptions | Pointer to the StartOptions struct. | +| maxWindowWidth | Maximum window width, in vp. | + +**Since**: 17 + +**Returns** + +Returns **ABILITY_RUNTIME_ERROR_CODE_NO_ERROR** if the information is obtained successfully. + +Returns **ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID** if **startOptions** is null. + +**Example** +```cpp +#include + +void demo() +{ + AbilityRuntime_StartOptions* options = OH_AbilityRuntime_CreateStartOptions(); + if (options == nullptr) { + // Record error logs and other service processing. + return; + } + + int32_t maxWindowWidth = 0; + AbilityRuntime_ErrorCode err = OH_AbilityRuntime_GetStartOptionsMaxWindowWidth(options, maxWindowWidth); + if (err != ABILITY_RUNTIME_ERROR_CODE_NO_ERROR) { + // Record error logs and other service processing. + } + + // Destroy options to prevent memory leakage. + OH_AbilityRuntime_DestroyStartOptions(&options); +} +``` + +### OH_AbilityRuntime_SetStartOptionsMinWindowHeight + +``` +AbilityRuntime_ErrorCode OH_AbilityRuntime_SetStartOptionsMinWindowHeight(AbilityRuntime_StartOptions *startOptions, + int32_t minWindowHeight) +``` + +**Description** + +Sets the minimum window height for starting the ability, in vp. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| startOptions | Pointer to the StartOptions struct. | +| minWindowHeight | Minimum window height, in vp. | + +**Since**: 17 + +**Returns** + +Returns **ABILITY_RUNTIME_ERROR_CODE_NO_ERROR** if the setting is successful. + +Returns **ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID** if **startOptions** is null. + +**Example** +```cpp +#include + +void demo() +{ + AbilityRuntime_StartOptions* options = OH_AbilityRuntime_CreateStartOptions(); + if (options == nullptr) { + // Record error logs and other service processing. + return; + } + + AbilityRuntime_ErrorCode err = OH_AbilityRuntime_SetStartOptionsMinWindowHeight(options, 100); + if (err != ABILITY_RUNTIME_ERROR_CODE_NO_ERROR) { + // Record error logs and other service processing. + } + + // Destroy options to prevent memory leakage. + OH_AbilityRuntime_DestroyStartOptions(&options); +} +``` + +### OH_AbilityRuntime_GetStartOptionsMinWindowHeight + +``` +AbilityRuntime_ErrorCode OH_AbilityRuntime_GetStartOptionsMinWindowHeight(AbilityRuntime_StartOptions *startOptions, + int32_t &minWindowHeight) +``` + +**Description** + +Obtains the minimum window height for starting the ability, in vp. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| startOptions | Pointer to the StartOptions struct. | +| minWindowHeight | Minimum window height, in vp. | + +**Since**: 17 + +**Returns** + +Returns **ABILITY_RUNTIME_ERROR_CODE_NO_ERROR** if the information is obtained successfully. + +Returns **ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID** if **startOptions** is null. + +**Example** +```cpp +#include + +void demo() +{ + AbilityRuntime_StartOptions* options = OH_AbilityRuntime_CreateStartOptions(); + if (options == nullptr) { + // Record error logs and other service processing. + return; + } + + int32_t minWindowHeight = 0; + AbilityRuntime_ErrorCode err = OH_AbilityRuntime_GetStartOptionsMinWindowHeight(options, minWindowHeight); + if (err != ABILITY_RUNTIME_ERROR_CODE_NO_ERROR) { + // Record error logs and other service processing. + } + + // Destroy options to prevent memory leakage. + OH_AbilityRuntime_DestroyStartOptions(&options); +} +``` + +### OH_AbilityRuntime_SetStartOptionsMaxWindowHeight + +``` +AbilityRuntime_ErrorCode OH_AbilityRuntime_SetStartOptionsMaxWindowHeight(AbilityRuntime_StartOptions *startOptions, + int32_t maxWindowHeight) +``` + +**Description** + +Sets the maximum window height for starting the ability, in vp. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| startOptions | Pointer to the StartOptions struct. | +| maxWindowHeight | Maximum window height, in vp. | + +**Since**: 17 + +**Returns** + +Returns **ABILITY_RUNTIME_ERROR_CODE_NO_ERROR** if the setting is successful. + +Returns **ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID** if **startOptions** is null. + +**Example** +```cpp +#include + +void demo() +{ + AbilityRuntime_StartOptions* options = OH_AbilityRuntime_CreateStartOptions(); + if (options == nullptr) { + // Record error logs and other service processing. + return; + } + + AbilityRuntime_ErrorCode err = OH_AbilityRuntime_SetStartOptionsMaxWindowHeight(options, 100); + if (err != ABILITY_RUNTIME_ERROR_CODE_NO_ERROR) { + // Record error logs and other service processing. + } + + // Destroy options to prevent memory leakage. + OH_AbilityRuntime_DestroyStartOptions(&options); +} +``` + +### OH_AbilityRuntime_GetStartOptionsMaxWindowHeight + +``` +AbilityRuntime_ErrorCode OH_AbilityRuntime_GetStartOptionsMaxWindowHeight(AbilityRuntime_StartOptions *startOptions, + int32_t &maxWindowHeight) +``` + +**Description** + +Obtains the maximum window height for starting the ability, in vp. + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| startOptions | Pointer to the StartOptions struct. | +| maxWindowHeight | Maximum window height, in vp. | + +**Since**: 17 + +**Returns** + +Returns **ABILITY_RUNTIME_ERROR_CODE_NO_ERROR** if the information is obtained successfully. + +Returns **ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID** if **startOptions** is null. + +**Example** +```cpp +#include + +void demo() +{ + AbilityRuntime_StartOptions* options = OH_AbilityRuntime_CreateStartOptions(); + if (options == nullptr) { + // Record error logs and other service processing. + return; + } + + int32_t maxWindowHeight = 0; + AbilityRuntime_ErrorCode err = OH_AbilityRuntime_GetStartOptionsMaxWindowHeight(options, maxWindowHeight); + if (err != ABILITY_RUNTIME_ERROR_CODE_NO_ERROR) { + // Record error logs and other service processing. + } + + // Destroy options to prevent memory leakage. + OH_AbilityRuntime_DestroyStartOptions(&options); +} +``` + +### OH_AbilityRuntime_StartSelfUIAbilityWithStartOptions + +``` +AbilityRuntime_ErrorCode OH_AbilityRuntime_StartSelfUIAbilityWithStartOptions(AbilityBase_Want *want, AbilityRuntime_StartOptions *options) +``` + +**Description** + +Starts the UIAbility of the current application. + +> **NOTE** +> +> This function is valid only for 2-in-1 devices. + +**Required permissions**: ohos.permission.NDK_START_SELF_UI_ABILITY + +**Since**: 17 + +**Parameters** + +| Name | Description | +| ----------- | ------------------------------------------------------------ | +| want | Pointer to the Want information required for starting the UIAbility. | +| options | Pointer to the StartOptions required for starting the UIAbility. | + +**Returns** + +Returns **ABILITY_RUNTIME_ERROR_CODE_NO_ERROR** if the operation is successful. + +Returns **ABILITY_RUNTIME_ERROR_CODE_PERMISSION_DENIED** if permission verification failed. + +Returns **ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID** if the Want or StartOptions information is empty, or if the bundleName or abilityName in the Want information is empty. + +Returns **ABILITY_RUNTIME_ERROR_CODE_NOT_SUPPORTED** if the device type is not supported. + +Returns **ABILITY_RUNTIME_ERROR_CODE_NO_SUCH_ABILITY** if the specified ability name does not exist. + +Returns **ABILITY_RUNTIME_ERROR_CODE_INCORRECT_ABILITY_TYPE** if the ability type is incorrect. + +Returns **ABILITY_RUNTIME_ERROR_CODE_CROWDTEST_EXPIRED** if the crowdtesting application expires. + +Returns **ABILITY_RUNTIME_ERROR_CODE_WUKONG_MODE** if the ability is started or stopped in Wukong mode. + +Returns **ABILITY_RUNTIME_ERROR_CODE_CONTROLLED** if the application is under control. + +Returns **ABILITY_RUNTIME_ERROR_CODE_EDM_CONTROLLED** if the application is under control by EDM. + +Returns **ABILITY_RUNTIME_ERROR_CODE_CROSS_APP** if it is forbidden to start other applications. + +Returns **ABILITY_RUNTIME_ERROR_CODE_INTERNAL** if an internal error occurs. + +Returns **ABILITY_RUNTIME_ERROR_CODE_NOT_TOP_ABILITY** if the application is not a top ability. + +Returns **ABILITY_RUNTIME_ERROR_VISIBILITY_SETTING_DISABLED** if it is forbidden to set the application visibility. + +Returns **ABILITY_RUNTIME_ERROR_CODE_MULTI_APP_NOT_SUPPORTED** if the application does not support clone and multi-instance mode. + +Returns **ABILITY_RUNTIME_ERROR_CODE_INVALID_APP_INSTANCE_KEY** if the multi-instance key is invalid. + +Returns **ABILITY_RUNTIME_ERROR_CODE_UPPER_LIMIT_REACHED** if the number of instances has reached the upper limit. + +Returns **ABILITY_RUNTIME_ERROR_MULTI_INSTANCE_NOT_SUPPORTED** if the application does not support multi-instance mode. + +Returns **ABILITY_RUNTIME_ERROR_CODE_APP_INSTANCE_KEY_NOT_SUPPORTED** if APP_INSTANCE_KEY cannot be assigned a value. + +**Example** +```cpp +#include +#include + +void demo() +{ + AbilityBase_Element element; + element.abilityName = const_cast("EntryAbility"); + element.bundleName = const_cast("com.exampl.myapplication"); + element.moduleName = const_cast("entry"); + AbilityBase_Want* want = OH_AbilityBase_CreateWant(element); + if (want == nullptr) { + // Record error logs and other service processing. + return; + } + + AbilityRuntime_StartOptions* options = OH_AbilityRuntime_CreateStartOptions(); + if (options == nullptr) { + // Record error logs and other service processing. + + // Destroy the Want to prevent memory leakage. + OH_AbilityBase_DestroyWant(want); + return; + } + AbilityRuntime_ErrorCode err = OH_AbilityRuntime_StartSelfUIAbilityWithStartOptions(want, options); + if (err != ABILITY_RUNTIME_ERROR_CODE_NO_ERROR) { + // Record error logs and other service processing. + } + // Destroy the Want to prevent memory leakage. + OH_AbilityBase_DestroyWant(want); + + // Destroy options to prevent memory leakage. + OH_AbilityRuntime_DestroyStartOptions(&options); +} +``` diff --git a/en/application-dev/reference/apis-ability-kit/_bundle.md b/en/application-dev/reference/apis-ability-kit/_bundle.md index 6f62b40638b0e2d29c3138bfce492c739facd14a..f0ec1da05ab82c8ffc0ef78fba8d9af50de6f10a 100644 --- a/en/application-dev/reference/apis-ability-kit/_bundle.md +++ b/en/application-dev/reference/apis-ability-kit/_bundle.md @@ -83,7 +83,7 @@ char* OH_NativeBundle_GetAppIdentifier() **Description** -Obtains the appIdentifier information about the current application. appIdentifier is the unique ID of the application, which is allocated by the cloud. This ID does not change along the application lifecycle, including version updates, certificate changes, public and private key changes, and application transfers. +Obtains the appIdentifier information about the current application. appIdentifier is the unique ID of the application. It is a random string allocated by AppGallery Connect during the creation of the application. This ID does not change along the application lifecycle, including version updates, certificate changes, public and private key changes, and application transfers. **Since**: 11 @@ -115,7 +115,7 @@ char* OH_NativeBundle_GetCompatibleDeviceType() **Description** -Obtains the compatible device type of the application. +Obtains the compatible device type of the current application. It helps you optimize the layout and font size when distributing mobile applications to tablets or 2-in-1 devices. **Since**: 14 diff --git a/en/application-dev/reference/apis-ability-kit/ability__access__control_8h.md b/en/application-dev/reference/apis-ability-kit/ability__access__control_8h.md index 0c21897d147a26106d5769af7791dc4310aef3da..17a43df8932a3a1bba02c634a6718ef1e5de1c29 100644 --- a/en/application-dev/reference/apis-ability-kit/ability__access__control_8h.md +++ b/en/application-dev/reference/apis-ability-kit/ability__access__control_8h.md @@ -3,7 +3,7 @@ ## Overview -Declares the APIs for implementing process access control. +Declares the APIs for implementing application access control. **Library**: ability_access_control.so @@ -23,4 +23,4 @@ Declares the APIs for implementing process access control. | Name| Description| | -------- | -------- | -| bool [OH_AT_CheckSelfPermission](_ability_access_control.md#oh_at_checkselfpermission) (const char \*permission) | Checks whether the specified permission is granted to the application. | +| bool [OH_AT_CheckSelfPermission](_ability_access_control.md#oh_at_checkselfpermission) (const char \*permission) | Checks whether a permission is granted to this application. | diff --git a/en/application-dev/reference/apis-ability-kit/ability__base__common_8h.md b/en/application-dev/reference/apis-ability-kit/ability__base__common_8h.md new file mode 100644 index 0000000000000000000000000000000000000000..0304df641c45b86fa2eef8bd14147d5fcbb81a04 --- /dev/null +++ b/en/application-dev/reference/apis-ability-kit/ability__base__common_8h.md @@ -0,0 +1,32 @@ +# ability_base_common.h + + +## Overview + +The **ability_base_common.h** file describes the error codes defined by AbilityBase. + +**File to include**: + +**Library**: libability_base_want.so + +**System capability**: SystemCapability.Ability.AbilityBase + +**Since**: 15 + +**Related module**: [AbilityBase](_ability_base.md) + + +## Summary + +### Files + +| Name | Description | +| ---------------------------------------------------------- | ------------------------------------------------------------ | +| [ability_base_common.h](ability__base__common_8h.md) | Declares the error codes related to AbilityBase.
**File to include**:
**Library**: libability_base_want.so| + + +### Enums + +| Name | Description | +| ------------------------------------------------------------ | ---------------------- | +| [AbilityBase_ErrorCode](_ability_base.md#AbilityBase_ErrorCode) {
ABILITY_BASE_ERROR_CODE_NO_ERROR = 0,
ABILITY_BASE_ERROR_CODE_PARAM_INVALID = 401,
}| Enumerates the AbilityBase error codes.| diff --git a/en/application-dev/reference/apis-ability-kit/ability__runtime__common_8h.md b/en/application-dev/reference/apis-ability-kit/ability__runtime__common_8h.md index af9787e5158331544328cf82d0c3722420f862a3..4da0a4e5bed114d025fad4395172f421ad98512d 100644 --- a/en/application-dev/reference/apis-ability-kit/ability__runtime__common_8h.md +++ b/en/application-dev/reference/apis-ability-kit/ability__runtime__common_8h.md @@ -27,4 +27,4 @@ The **ability_runtime_common.h** file declares the error codes of the ability fr | Name | Description | | ------------------------------------------------------------ | ---------------------- | -| [AbilityRuntime_ErrorCode](_ability_runtime.md#abilityruntime_errorcode) {
ABILITY_RUNTIME_ERROR_CODE_NO_ERROR = 0,
ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID = 401,
ABILITY_RUNTIME_ERROR_CODE_CONTEXT_NOT_EXIST = 16000011,
} | Enumerates the error codes used by the ability framework.| +| [AbilityRuntime_ErrorCode](_ability_runtime.md#abilityruntime_errorcode) {
ABILITY_RUNTIME_ERROR_CODE_NO_ERROR = 0,
ABILITY_RUNTIME_ERROR_CODE_PERMISSION_DENIED = 201,
ABILITY_RUNTIME_ERROR_CODE_PARAM_INVALID = 401,
ABILITY_RUNTIME_ERROR_CODE_NOT_SUPPORTED = 801,
ABILITY_RUNTIME_ERROR_CODE_NO_SUCH_ABILITY = 16000001,
ABILITY_RUNTIME_ERROR_CODE_INCORRECT_ABILITY_TYPE = 16000002,
ABILITY_RUNTIME_ERROR_CODE_CROWDTEST_EXPIRED = 16000008,
ABILITY_RUNTIME_ERROR_CODE_WUKONG_MODE = 16000009,
ABILITY_RUNTIME_ERROR_CODE_CONTEXT_NOT_EXIST = 16000011,
ABILITY_RUNTIME_ERROR_CODE_CONTROLLED = 16000012,
ABILITY_RUNTIME_ERROR_CODE_EDM_CONTROLLED = 16000013,
ABILITY_RUNTIME_ERROR_CODE_CROSS_APP = 16000018,
ABILITY_RUNTIME_ERROR_CODE_INTERNAL = 16000050,
ABILITY_RUNTIME_ERROR_CODE_NOT_TOP_ABILITY = 16000053,
ABILITY_RUNTIME_ERROR_VISIBILITY_SETTING_DISABLED = 16000067,
ABILITY_RUNTIME_ERROR_CODE_MULTI_APP_NOT_SUPPORTED = 16000072,
ABILITY_RUNTIME_ERROR_CODE_INVALID_APP_INSTANCE_KEY = 16000076,
ABILITY_RUNTIME_ERROR_CODE_UPPER_LIMIT_REACHED = 16000077,
ABILITY_RUNTIME_ERROR_MULTI_INSTANCE_NOT_SUPPORTED = 16000078,
ABILITY_RUNTIME_ERROR_CODE_APP_INSTANCE_KEY_NOT_SUPPORTED = 16000079
} | Enumerates the error codes used by the ability framework.| diff --git a/en/application-dev/reference/apis-ability-kit/application__context_8h.md b/en/application-dev/reference/apis-ability-kit/application__context_8h.md index c3e6aaa4ba0c2ff0a55fb238e1e07722880f4de5..ef1384c22c346918a07b6b47309fd708384ef21e 100644 --- a/en/application-dev/reference/apis-ability-kit/application__context_8h.md +++ b/en/application-dev/reference/apis-ability-kit/application__context_8h.md @@ -36,3 +36,5 @@ The **application_context.h** file declares the context capability at the applic | [AbilityRuntime_ErrorCode](_ability_runtime.md#abilityruntime_errorcode) [OH_AbilityRuntime_ApplicationContextGetBundleCodeDir](_ability_runtime.md#oh_abilityruntime_applicationcontextgetbundlecodedir)(char* buffer, const int32_t bufferSize, int32_t* writeLength) | Obtains the application-level installation file directory. | | [AbilityRuntime_ErrorCode](_ability_runtime.md#abilityruntime_errorcode) [OH_AbilityRuntime_ApplicationContextGetDistributedFilesDir](_ability_runtime.md#oh_abilityruntime_applicationcontextgetdistributedfilesdir)(char* buffer, const int32_t bufferSize, int32_t* writeLength) | Obtains the application-level distributed file directory.| | [AbilityRuntime_ErrorCode](_ability_runtime.md#abilityruntime_errorcode) [OH_AbilityRuntime_ApplicationContextGetCloudFileDir](_ability_runtime.md#oh_abilityruntime_applicationcontextgetcloudfiledir)(char* buffer, const int32_t bufferSize, int32_t* writeLength) | Obtains the application-level cloud file directory. | +| [AbilityRuntime_ErrorCode](_ability_runtime.md#abilityruntime_errorcode) [OH_AbilityRuntime_StartSelfUIAbility](_ability_runtime.md#oh_abilityruntime_startselfuiability)([AbilityBase_Want](_ability_base.md#abilitybase_want) *want) | Starts the UIAbility of the current application. | +| [AbilityRuntime_ErrorCode](_ability_runtime.md#abilityruntime_errorcode) [OH_AbilityRuntime_StartSelfUIAbilityWithStartOptions](_ability_runtime.md#oh_abilityruntime_startselfuiabilitywithstartoptions)([AbilityBase_Want](_ability_base.md#abilitybase_want) *want, [AbilityRuntime_StartOptions](_ability_runtime.md#abilityruntime_startoptions) *options) | Starts the UIAbility of the current application. | diff --git a/en/application-dev/reference/apis-ability-kit/c-apis-ability-childprocess.md b/en/application-dev/reference/apis-ability-kit/c-apis-ability-childprocess.md index 2056e44af4aaf3ef8b501b9a483e1fcc20b57163..cc81565f86713ec35e3fae5c931628f767a6ee4a 100644 --- a/en/application-dev/reference/apis-ability-kit/c-apis-ability-childprocess.md +++ b/en/application-dev/reference/apis-ability-kit/c-apis-ability-childprocess.md @@ -47,7 +47,9 @@ The created child process does not support the UI or the calling of context-rela > **NOTE** > -> Currently, only 2-in-1 devices are supported, and only one native child process can be started for a process. +> This function is valid only for 2-in-1 devices. +> +> Since API version 15, a single process supports a maximum of 50 native child processes. In API version 14 and earlier versions, a single process supports only one native child process. ## Type Description ### OH_Ability_OnNativeChildProcessStarted @@ -183,7 +185,7 @@ Enumerates the error codes used by the native child process module. | NCP_ERR_INVALID_PARAM | Invalid parameter. | | NCP_ERR_NOT_SUPPORTED | Creating a native child process is not supported. | | NCP_ERR_INTERNAL | Internal error. | -| NCP_ERR_BUSY | A new child process cannot be created during the startup of another native child process. You can try again after the child process is started.| +| NCP_ERR_BUSY | A new child process cannot be created during the startup of another native child process. You can try again after the child process is started. This function is deprecated since API version 15.| | NCP_ERR_TIMEOUT | Starting the native child process times out. | | NCP_ERR_SERVICE_ERROR | Server error. | | NCP_ERR_MULTI_PROCESS_DISABLED | The multi-process mode is disabled. A child process cannot be started. | @@ -214,7 +216,7 @@ Enumerates the isolation modes of a child process. ### OH_Ability_CreateNativeChildProcess ``` -int OH_Ability_CreateNativeChildProcess (const char *libName, OH_Ability_OnNativeChildProcessStarted onProcessStarted ) +int OH_Ability_CreateNativeChildProcess (const char *libName, OH_Ability_OnNativeChildProcessStarted onProcessStarted) ``` **Description** @@ -246,7 +248,9 @@ The processing logic sequence is shown in the following pseudocode: > **NOTE** > -> Currently, only 2-in-1 devices are supported, and only one native child process can be started for a process. +> This function is valid only for 2-in-1 devices. +> +> Since API version 15, a single process supports a maximum of 50 native child processes. In API version 14 and earlier versions, a single process supports only one native child process. **Since**: 12 @@ -295,3 +299,23 @@ The specified dynamic library must implement and export the entry parameters of **Returns** Returns **NCP_NO_ERROR** if the operation is successful; returns an error code defined in [Ability_NativeChildProcess_ErrCode](#ability_nativechildprocess_errcode) otherwise. + +### OH_Ability_GetCurrentChildProcessArgs + +``` +NativeChildProcess_Args* OH_Ability_GetCurrentChildProcessArgs(); +``` + +**Description** + +Used by a child process, after being started by calling [OH_Ability_StartNativeChildProcess](#oh_ability_startnativechildprocess), to obtain the startup parameter [NativeChildProcess_Args](#nativechildprocess_args) from any .so file or child thread. + +> **NOTE** +> +> This function is valid only for 2-in-1 devices and tablets. + +**Since**: 16 + +**Returns** + +Returns the pointer to a [NativeChildProcess_Args](#nativechildprocess_args) object if the operation is successful; returns a null pointer otherwise. diff --git a/en/application-dev/reference/apis-ability-kit/context__constant_8h.md b/en/application-dev/reference/apis-ability-kit/context__constant_8h.md index dc88add0a72321cbdf05be9b70c7bd0e0d136990..2dd6fdedcc8ab50c771b14a25f0ba9d9f21c61d0 100644 --- a/en/application-dev/reference/apis-ability-kit/context__constant_8h.md +++ b/en/application-dev/reference/apis-ability-kit/context__constant_8h.md @@ -28,3 +28,5 @@ The **context_constant.h** file declares context-related enums. | Name | Description | | ------------------------------------------------------------ | ------------------ | | [AbilityRuntime_AreaMode](_ability_runtime.md#abilityruntime_areamode) {
ABILITY_RUNTIME_AREA_MODE_EL1 = 0,
ABILITY_RUNTIME_AREA_MODE_EL2 = 1,
ABILITY_RUNTIME_AREA_MODE_EL3 = 2,
ABILITY_RUNTIME_AREA_MODE_EL4 = 3,
ABILITY_RUNTIME_AREA_MODE_EL5 = 4
} | Enumerates the data encryption levels.| +| [AbilityRuntime_WindowMode](_ability_runtime.md#abilityruntime_windowmode) {
ABILITY_RUNTIME_WINDOW_MODE_UNDEFINED = 0,
ABILITY_RUNTIME_WINDOW_MODE_FULL_SCREEN = 1
} | Enumerates the window modes in which an ability can be displayed at startup. | +| [AbilityRuntime_SupportedWindowMode](_ability_runtime.md#abilityruntime_supportedwindowmode) {
ABILITY_RUNTIME_SUPPORTED_WINDOW_MODE_FULL_SCREEN = 0,
ABILITY_RUNTIME_SUPPORTED_WINDOW_MODE_SPLIT = 1,
ABILITY_RUNTIME_SUPPORTED_WINDOW_MODE_FLOATING = 2
} | Enumerates the window modes supported by an ability when it is started. | diff --git a/en/application-dev/reference/apis-ability-kit/errorcode-DistributedSchedule.md b/en/application-dev/reference/apis-ability-kit/errorcode-DistributedSchedule.md index d5b6e7d8f81234d4e67e2390ffcd1b59cc1a0274..f57a6616f7bf57aac18af4be92169f3de2bc34f8 100644 --- a/en/application-dev/reference/apis-ability-kit/errorcode-DistributedSchedule.md +++ b/en/application-dev/reference/apis-ability-kit/errorcode-DistributedSchedule.md @@ -51,7 +51,7 @@ The number of token registration times has reached the upper limit. **Description** -This error code is reported when the number of times that the **continuationManager.registerContinuation** API is called has reached the upper limit. +This error code is reported when the number of times that the **continuationManager.registerContinuation** API is called has reached the upper limit (600). **Possible Causes** diff --git a/en/application-dev/reference/apis-ability-kit/errorcode-ability.md b/en/application-dev/reference/apis-ability-kit/errorcode-ability.md index fec414da7424d6c2131fc6f70f10c4e6c492e74a..b9d22d1e5cdcd9fe4bd8072c5d1d93c473b893ee 100644 --- a/en/application-dev/reference/apis-ability-kit/errorcode-ability.md +++ b/en/application-dev/reference/apis-ability-kit/errorcode-ability.md @@ -713,11 +713,11 @@ This error code is reported when the application does not support clones. **Possible Causes** -An application that does not support clones calls **getCurrentAppCloneIndex()**. +This error code is reported when the [getCurrentAppCloneIndex](./js-apis-inner-application-applicationContext.md#applicationcontextgetcurrentappcloneindex12) API is called while the [multiAppMode](../../quick-start/app-configuration-file.md#multiappmode) field in the **app.json5** file is not set to **appClone** (meaning that the application does not support app clone mode). **Solution** -Avoid calling **getCurrentAppCloneIndex()** in applications that do not support clones. +Configure the **multiAppMode** field in the **app.json5** file by referring to [Creating an Application Multi-Instance](../../quick-start/multiInstance.md). After app clone mode is enabled, call the [getCurrentAppCloneIndex](./js-apis-inner-application-applicationContext.md#applicationcontextgetcurrentappcloneindex12) API. ## 16000072 Multi-app Mode Is Not Supported @@ -1007,11 +1007,14 @@ This error code is reported when the **wantAgent** object passed in the API is i **Possible Causes** -The **wantAgent** object is invalid. +1. The **wantAgent** object is invalid. +2. A third-party application attempts to set the ability of another application. +3. An internal communication error occurs. **Solution** -Pass a valid **wantAgent** object in the API. +1. Ensure that the **wantAgent** object passed in the API exists. +2. Check whether the caller is a third-party application. Third-party applications cannot set the abilities of other applications. ## 16000152 wantAgent Object Does Not Exist @@ -1564,6 +1567,7 @@ This error code is reported when the size of the image exceeds 50 MB. 1. Limit the size of the edited image to less than 50 MB. 2. Verify the image size in advance. + ## 16300007 Download and Installation Task Information of the Atomic Service Does Not Exist **Error Message** @@ -1581,3 +1585,75 @@ The value of **bundleName**, **moduleName**, **abilityName**, or **startTime** i **Solution** Pass in correct values for **bundleName**, **moduleName**, **abilityName**, and **startTime**. + +## 28800001 Startup Task or Dependency Not Found + +**Error Message** + +Startup task or its dependency not found. + +**Description** + +This error code is reported if the startup task or its dependency is not found during task startup. + +**Possible Causes** + +The startup task or dependency is not correctly configured. + +**Solution** + +Check whether the AppStartup configuration file is correctly compiled, and ensure that all configured startup tasks are implemented. + +## 28800002 Circular Dependencies Between Startup Tasks + +**Error Message** + +The startup tasks have circular dependencies. + +**Description** + +This error code is reported if circular dependencies are detected between startup tasks during startup task loading. + +**Possible Causes** + +There are circular dependencies between startup tasks. + +**Solution** + +Check the AppStartup configuration file, and ensure that no circular dependency exists between startup tasks. + +## 28800003 Error Occurs During Task Startup + +**Error Message** + +An error occurred while running the startup tasks. + +**Description** + +This error code is reported when an error occurs during task startup. + +**Possible Causes** + +The code logic for starting the task is incorrect, or no exception handling is available. + +**Solution** + +Check whether the startup task has logic errors, and ensure that each startup task contains the exception handling logic. + +## 28800004 Executing the Startup Task Times Out + +**Error Message** + +Running startup tasks timeout. + +**Description** + +This error code is reported if the execution time of a task exceeds the timeout interval (10000 ms by default). + +**Possible Causes** + +The startup task contains a large number of time-consuming operations, or the configured timeout interval is too short. + +**Solution** + +Adjust the timeout interval as required. For details about how to set the timeout interval, see [Setting Startup Parameters](../../application-models/app-startup.md#setting-startup-parameters). diff --git a/en/application-dev/reference/apis-ability-kit/errorcode-access-token.md b/en/application-dev/reference/apis-ability-kit/errorcode-access-token.md index 0ad6d46b4e8a3fa57baf3b65c2375442d051157e..fd757d494c75d3abbd7939a26bcaf2f165e7cbf7 100644 --- a/en/application-dev/reference/apis-ability-kit/errorcode-access-token.md +++ b/en/application-dev/reference/apis-ability-kit/errorcode-access-token.md @@ -12,19 +12,18 @@ Invalid Parameter. Error message: ${messageInfo}. **Possible Causes** -This error code is reported when the parameter verification fails. The possible causes are as follows: -- The value of **tokenId** is **0**. -- The permission name is empty or exceeds 256 characters. -- The **flag** value in the permission authorization or revocation request is invalid. -- The parameters specified for registering a listener are incorrect. -- The specified context does not belong to the current application. -- The requested permissions do not belong to the same permission group. -- The requested permissions include permissions that are not declared by the application. -- The type of the requested global switch is invalid. +1. The value of **tokenId** is **0**. +2. The permission name is empty or exceeds 256 characters. +3. The **flag** value in the permission authorization or revocation request is invalid. +4. The parameters specified for registering a listener are incorrect. +5. The specified context does not belong to the current application. +6. The requested permissions do not belong to the same permission group. +7. The requested permissions include permissions that are not declared by the application. +8. The type of the requested global switch is invalid. **Solution** -Correct invalid parameter values. +Check and set input parameters correctly. ## 12100002 TokenId Not Exist @@ -35,12 +34,12 @@ TokenId does not exist. **Possible Causes** -- The specified **tokenId** does not exist. -- The process of the specified **tokenId** is not an application process. +1. The specified **tokenId** does not exist. +2. The process of the specified **tokenId** is not an application process. **Solution** -Set **tokenId** correctly. +Check and set input parameters correctly. ## 12100003 Permission Not Exist @@ -51,13 +50,13 @@ Permission does not exist. **Possible Causes** -- The specified **permissionName** does not exist. -- The specified **permissionName** does not match the **tokenId** in the permission authorization or revocation scenario. -- The specified **permissionName** is not a sensitive permission that requires user authorization. +1. The specified **permissionName** does not exist. +2. The specified **permissionName** does not match the **tokenId** in the permission authorization or revocation scenario. +3. The specified **permissionName** is not a sensitive permission that requires user authorization. **Solution** -Set **permissionName** correctly. For details, see [Permissions for All Applications](../../security/AccessToken/permissions-for-all.md). +Check and set input parameters correctly. For details about the permissions, see [Application Permissions](../../security/AccessToken/app-permissions.md). ## 12100004 Listener APIs Not Used in Pairs @@ -68,13 +67,13 @@ The API is not used in pair with others. **Possible Causes** -1. One of the APIs that need to be used in pairs is repeatedly called. -2. One of the APIs that need to be used in pairs is independently called. +1. One of the listener APIs that must be used in pairs is repeatedly called. +2. One of the listener APIs that must be used in pairs is independently called. **Solution** -1. For the APIs that need to be used in pairs, for example, **on()** and **off()**, check whether **on()** with the same parameters is called again before **off()** is called. -2. For the APIs that need to be used in pairs, for example, **on()** and **off()**, check whether **off()** is called before **on()**. +1. For the APIs that must be used in pairs, for example, **on()** and **off()**, check whether **on()** with the same parameters is called again before **off()** is called. +2. For the APIs that must be used in pairs, for example, **on()** and **off()**, check whether **off()** is called before **on()**. ## 12100005 Listener Overflows diff --git a/en/application-dev/reference/apis-ability-kit/errorcode-bundle.md b/en/application-dev/reference/apis-ability-kit/errorcode-bundle.md index 6467d6e32bd7c870d61081365f0e7778f5c75cd5..74d01b4111c64e82d4cb96c8df58ea9c34fbab49 100644 --- a/en/application-dev/reference/apis-ability-kit/errorcode-bundle.md +++ b/en/application-dev/reference/apis-ability-kit/errorcode-bundle.md @@ -1107,11 +1107,11 @@ The app does not support the creation of an appClone instance. **Description** -An **AppClone** instance cannot be created for an application that is not in **appClone** mode. +An AppClone instance cannot be created for an application that is not in appClone mode. **Possible Causes** -The multi-app mode is set to another mode other than **appClone**. +The multi-app mode is set to another mode other than appClone. **Solution** @@ -1207,7 +1207,7 @@ Check whether **appIdentifier** is an empty string. **Error Message** -The specified bundleName of want is not the same with caller. +The specified bundleName of want is not the same with caller. **Description** @@ -1221,6 +1221,203 @@ When setting an uninstallation disposed rule, the bundle name specified in **wan Change the value of **bundleName** in **want** to be the same as that of the caller. +## 17700076 Failed to Install the HAP or HSP Because the Distribution Type in the Signature File Restricts Installation +**Error Message** + +Failed to install the HAP or HSP because the app distribution type is not allowed. + +**Description** + +The distribution type in the signature file restricts installation, leading to a failure in installing the HAP or HSP. + +**Possible Causes** + +The distribution type specified in the signature file restricts installation on the current device. + +**Solution** + +Change the distribution type of the signature file. + + +## 17700077 Application Installation Fails but Preinstallation Is Successful + +**Error Message** + +Failed to install the HAP and restore to preinstalled bundle. + +**Description** + +If the preinstalled application corresponding to the specified application has been uninstalled, the system first attempts to reinstall the preinstalled application. If the preinstalled application is successfully reinstalled but the specified application fails to install afterward, this error code is reported. + +**Possible Causes** + +The version number of the application to be installed is earlier than or the same as the version number of the preinstalled application. + +**Solution** +1. Ensure that the version number of the specified application is later than that of the preinstalled application. +2. Reinstall the specified application. + + + +## 17700080 Invalid Source Paths + +**Error Message** + +The source paths are invalid. + +**Description** + +The source paths are invalid. + +**Possible Causes** +1. The source path array is empty. +2. A source path includes the special sequence **../**. +3. None of the paths can be resolved to the intended location. + +**Solution** + +Pass in a valid path that does not include the special sequence **../**. + +## 17700081 Invalid Destination Path + +**Error Message** + +The destination path is invalid. + +**Description** + +The destination path is invalid. + +**Possible Causes** +1. The destination path is empty. +2. The destination path includes the special sequence **../**. +3. The destination path cannot be resolved to the intended location. + +**Solution** + +Pass in a valid path that does not include the special sequence **../**. + +## 17700082 User Authentication Failed + +**Error Message** + +User authentication failed. + +**Description** + +User authentication fails. + +**Possible Causes** +1. The current system does not support user authentication. +2. The current user has not enabled user authentication. +3. User authentication information is incorrect or the user cancels authentication. + +**Solution** +1. Check whether the current system supports user authentication. If not, the API cannot be used. +2. Ensure that user authentication is enabled for the current user. +3. Have the user re-enter accurate authentication details to ensure successful authentication. + +## 17700083 User Authentication Times Out + +**Error Message** + +Waiting for user authentication timeout. + +**Description** + +Waiting for user authentication times out. + +**Possible Causes** + +The user authentication process exceeds the 5-minute waiting period. + +**Solution** + +Ensure that the user completes the authentication process within the allowed time. + +## 17700084 No Read Permissions for Source Paths + +**Error Message** + +There are inaccessible path in the source paths. + +**Description** + +Some paths in the source path array lack read permissions. + +**Possible Causes** + +Read permissions are not enabled for some source paths. + +**Solution** + +Provide a valid path with read permissions enabled. + +## 17700085 No Write Permissions for the Destination Path + +**Error Message** + +The destination path cannot be accessed. + +**Description** + +The destination path cannot be accessed. + +**Possible Causes** + +Write permissions are not enabled for the destination path. + +**Solution** + +Provide a valid path with write permissions enabled. + +## 17700086 System Error + +**Error Message** + +System error occurred during copy execution. + +**Description** + +A system error occurred during the copy operation. + +**Possible Causes** + +Errors related to file operations occurs, such as insufficient space at the destination or the removal of files from the source path. + +**Solution** +1. Ensure that the destination path has sufficient space. +2. Ensure the files in the source path are still present. + + +## 17700101 Bundle Manager Service Abnormal +**Error Message** + +Bundle manager service is excepted. + +**Description** + +The Bundle Manager service is abnormal. + +**Possible Causes** + +An unknown system exception occurs. + +**Solution** +1. Restart the phone and try again. + +2. If the request still fails after the preceding steps are performed for three to five times, check whether a crash file containing **foundation** exists in the **/data/log/faultlog/faultlogger/** directory of the device. +``` +hdc shell +cd /data/log/faultlog/faultlogger/ +ls -ls +``` +3. Export the crash file and log file and submit them to [online tickets](https://developer.huawei.com/consumer/en/support/feedback/#/) for help. +``` +hdc file recv /data/log/faultlog/faultlogger/ +hdc file recv /data/log/hilog/ +``` + ## 17700201 .abc File Verification Failure **Error Message** diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-Bundle-BundleStatusCallback-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-Bundle-BundleStatusCallback-sys.md index 6afff940abc01792b542d6974aacd68b5c3c6dd9..6604ba9b52835eb3a657732bf432c45eea38bdeb 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-Bundle-BundleStatusCallback-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-Bundle-BundleStatusCallback-sys.md @@ -1,6 +1,6 @@ # BundleStatusCallback (System API) -The **BundleStatusCallback** module provides callbacks for bundle status changes. The changes can be obtained through [innerBundleManager.on](js-apis-Bundle-InnerBundleManager-sys.md). +The BundleStatusCallback module provides callbacks for bundle status changes. The changes can be obtained through [innerBundleManager.on](js-apis-Bundle-InnerBundleManager-sys.md#innerbundlemanagerondeprecated). > **NOTE** > diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-Bundle-InnerBundleManager-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-Bundle-InnerBundleManager-sys.md index 8cdafe52a48b2a24951ef82c43a1e0b50308fa9a..13811a42505bd2f8de8934f4d2e4b10001bc989a 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-Bundle-InnerBundleManager-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-Bundle-InnerBundleManager-sys.md @@ -1,6 +1,6 @@ # @ohos.bundle.innerBundleManager (innerBundleManager) (System API) -The **innerBundleManager** module provides APIs for the **Home Screen** application. +The innerBundleManager module provides APIs for the Home Screen application. > **NOTE** > @@ -25,7 +25,10 @@ SystemCapability.BundleManager.BundleFramework getLauncherAbilityInfos(bundleName: string, userId: number, callback: AsyncCallback<Array<LauncherAbilityInfo>>) : void -Obtains the launcher ability information based on a given bundle name. This API uses an asynchronous callback to return the result. +Obtains an array of the launcher ability information based on a given bundle name. This API uses an asynchronous callback to return the result. + +> **NOTE** +> > This API is deprecated since API version 9. You are advised to use [launcherBundleManager.getLauncherAbilityInfo](js-apis-launcherBundleManager-sys.md#launcherbundlemanagergetlauncherabilityinfo9) instead. **Required permissions** @@ -53,7 +56,10 @@ This is a system API. getLauncherAbilityInfos(bundleName: string, userId: number) : Promise<Array<LauncherAbilityInfo>> -Obtains the launcher ability information based on a given bundle name. This API uses a promise to return the result. +Obtains an array of the launcher ability information based on a given bundle name. This API uses a promise to return the result. + +> **NOTE** +> > This API is deprecated since API version 9. You are advised to use [launcherBundleManager.getLauncherAbilityInfo](js-apis-launcherBundleManager-sys.md#launcherbundlemanagergetlauncherabilityinfo9) instead. **Required permissions** @@ -86,6 +92,9 @@ This is a system API. on(type:"BundleStatusChange", bundleStatusCallback : BundleStatusCallback, callback: AsyncCallback<string>) : void Registers a callback to receive bundle status changes. This API uses an asynchronous callback to return the result. + +> **NOTE** +> > This API is deprecated since API version 9. You are advised to use [bundleMonitor.on](js-apis-bundleMonitor-sys.md#bundlemonitoron) instead. **Required permissions** @@ -113,6 +122,9 @@ This is a system API. on(type:"BundleStatusChange", bundleStatusCallback : BundleStatusCallback) : Promise<string> Registers a callback to receive bundle status changes. This API uses a promise to return the result. + +> **NOTE** +> > This API is deprecated since API version 9. You are advised to use [bundleMonitor.on](js-apis-bundleMonitor-sys.md#bundlemonitoron) instead. **Required permissions** @@ -145,6 +157,9 @@ This is a system API. off(type:"BundleStatusChange", callback: AsyncCallback<string>) : void Deregisters the callback that receives bundle status changes. This API uses an asynchronous callback to return the result. + +> **NOTE** +> > This API is deprecated since API version 9. You are advised to use [bundleMonitor.off](js-apis-bundleMonitor-sys.md#bundlemonitoroff) instead. **Required permissions** @@ -171,6 +186,9 @@ This is a system API. off(type:"BundleStatusChange") : Promise<string> Deregisters the callback that receives bundle status changes. This API uses a promise to return the result. + +> **NOTE** +> > This API is deprecated since API version 9. You are advised to use [bundleMonitor.off](js-apis-bundleMonitor-sys.md#bundlemonitoroff) instead. **Required permissions** @@ -202,6 +220,9 @@ This is a system API. getAllLauncherAbilityInfos(userId: number, callback: AsyncCallback<Array<LauncherAbilityInfo>>) : void Obtains the information about all launcher abilities. This API uses an asynchronous callback to return the result. + +> **NOTE** +> > This API is deprecated since API version 9. You are advised to use [launcherBundleManager.getAllLauncherAbilityInfo](js-apis-launcherBundleManager-sys.md#launcherbundlemanagergetalllauncherabilityinfo9) instead. **Required permissions** @@ -228,6 +249,9 @@ This is a system API. getAllLauncherAbilityInfos(userId: number) : Promise<Array<LauncherAbilityInfo>> Obtains the information about all launcher abilities. This API uses a promise to return the result. + +> **NOTE** +> > This API is deprecated since API version 9. You are advised to use [launcherBundleManager.getAllLauncherAbilityInfo](js-apis-launcherBundleManager-sys.md#launcherbundlemanagergetalllauncherabilityinfo9) instead. **Required permissions** @@ -258,7 +282,10 @@ This is a system API. getShortcutInfos(bundleName :string, callback: AsyncCallback<Array<ShortcutInfo>>) : void -Obtains the shortcut information based on a given bundle name. This API uses an asynchronous callback to return the result. +Obtains an array of the shortcut information based on a given bundle name. This API uses an asynchronous callback to return the result. + +> **NOTE** +> > This API is deprecated since API version 9. You are advised to use [launcherBundleManager.getShortcutInfo](js-apis-launcherBundleManager-sys.md#launcherbundlemanagergetshortcutinfo9) instead. **Required permissions** @@ -284,7 +311,10 @@ This is a system API. getShortcutInfos(bundleName : string) : Promise<Array<ShortcutInfo>> -Obtains the shortcut information based on a given bundle name. This API uses a promise to return the result. +Obtains an array of the shortcut information based on a given bundle name. This API uses a promise to return the result. + +> **NOTE** +> > This API is deprecated since API version 9. You are advised to use [launcherBundleManager.getShortcutInfo](js-apis-launcherBundleManager-sys.md#launcherbundlemanagergetshortcutinfo9) instead. **Required permissions** diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-Bundle-distributedBundle-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-Bundle-distributedBundle-sys.md index 4b2cb85bd4842f7b28c4e082b9dbe36d7756006f..5e16c12e64b62aaaa74263ab08a2b68d45449fbb 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-Bundle-distributedBundle-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-Bundle-distributedBundle-sys.md @@ -1,6 +1,6 @@ # @ohos.distributedBundle (Distributed Bundle Management) (System API) -The **distributedBundle** module manages distributed bundles. +The distributedBundle module manages distributed bundles. > **NOTE** > @@ -22,7 +22,7 @@ SystemCapability.BundleManager.DistributedBundleFramework | Permission | APL | Description | | ------------------------------------------ | ------------ | ------------------ | -| ohos.permission.GET_BUNDLE_INFO_PRIVILEGED | system_basic | Permission to query information about all applications. | +| ohos.permission.GET_BUNDLE_INFO_PRIVILEGED | system_basic | Permission to query information about all applications.| For details about the APL, see [Basic Concepts in the Permission Mechanism](../../security/AccessToken/app-permission-mgmt-overview.md#basic-concepts-in-the-permission-mechanism). @@ -32,7 +32,7 @@ For details about the APL, see [Basic Concepts in the Permission Mechanism](../. getRemoteAbilityInfo(elementName: ElementName, callback: AsyncCallback<RemoteAbilityInfo>): void -Obtains information about the remote ability that matches the given element name. This API uses an asynchronous callback to return the result. +Obtains the information about the remote ability that matches the given element name. This API uses an asynchronous callback to return the result. **Required permissions** @@ -48,10 +48,10 @@ This is a system API. **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ----------- | ------------------------------------------------------------ | ---- | -------------------------------------------------- | | elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | **ElementName**. | -| callback | AsyncCallback<[RemoteAbilityInfo](js-apis-bundle-remoteAbilityInfo-sys.md)> | Yes | Callback used to return the remote ability information. | +| callback | AsyncCallback<[RemoteAbilityInfo](js-apis-bundle-remoteAbilityInfo-sys.md)> | Yes | Callback used to return the remote ability information.| @@ -61,7 +61,7 @@ This is a system API. getRemoteAbilityInfo(elementName: ElementName): Promise<RemoteAbilityInfo> -Obtains information about the remote ability that matches the given element name. This API uses a promise to return the result. +Obtains the information about the remote ability that matches the given element name. This API uses a promise to return the result. **Required permissions** @@ -77,15 +77,15 @@ This is a system API. **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ----------- | -------------------------------------------- | ---- | ----------------------- | -| elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | **ElementName**. | +| elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | **ElementName**.| **Return value** | Type | Description | | ------------------------------------------------------------ | --------------------------------- | -| Promise\<[RemoteAbilityInfo](js-apis-bundle-remoteAbilityInfo-sys.md)> | Promise used to return the remote ability information. | +| Promise\<[RemoteAbilityInfo](js-apis-bundle-remoteAbilityInfo-sys.md)> | Promise used to return the remote ability information.| ## distributedBundle.getRemoteAbilityInfosdeprecated @@ -93,7 +93,7 @@ This is a system API. getRemoteAbilityInfos(elementNames: Array<ElementName>, callback: AsyncCallback<Array<RemoteAbilityInfo>>): void -Obtains information about remote abilities that match the given element names. This API uses an asynchronous callback to return the result. +Obtains the information about remote abilities that match the given element names. This API uses an asynchronous callback to return the result. **Required permissions** @@ -109,10 +109,10 @@ This is a system API. **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ------------ | ------------------------------------------------------------ | ---- | -------------------------------------------------- | | elementNames | Array<[ElementName](js-apis-bundle-ElementName.md)> | Yes | **ElementName** array, whose maximum length is 10. | -| callback | AsyncCallback< Array<[RemoteAbilityInfo](js-apis-bundle-remoteAbilityInfo-sys.md)>> | Yes | Callback used to return an array of the remote ability information. | +| callback | AsyncCallback< Array<[RemoteAbilityInfo](js-apis-bundle-remoteAbilityInfo-sys.md)>> | Yes | Callback used to return an array of the remote ability information.| @@ -122,7 +122,7 @@ This is a system API. getRemoteAbilityInfos(elementNames: Array<ElementName>): Promise<Array<RemoteAbilityInfo>> -Obtains information about remote abilities that match the given element names. This API uses a promise to return the result. +Obtains the information about remote abilities that match the given element names. This API uses a promise to return the result. **Required permissions** @@ -138,12 +138,12 @@ This is a system API. **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ------------ | --------------------------------------------------- | ---- | ----------------------- | -| elementNames | Array<[ElementName](js-apis-bundle-ElementName.md)> | Yes | **ElementName** array, whose maximum length is 10. | +| elementNames | Array<[ElementName](js-apis-bundle-ElementName.md)> | Yes | **ElementName** array, whose maximum length is 10.| **Return value** | Type | Description | | ------------------------------------------------------------ | --------------------------------- | -| Promise\> | Promise used to return the remote ability information. | +| Promise\> | Promise used to return an array of the remote ability information.| diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-Bundle.md b/en/application-dev/reference/apis-ability-kit/js-apis-Bundle.md index c53bd7a354376943f128cd728ee929a4d4ca632f..494f88f634c2675216369c3606139fc544a739fe 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-Bundle.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-Bundle.md @@ -826,7 +826,7 @@ bundle.getAbilityLabel(bundleName, abilityName, (err, data) => { isAbilityEnabled(info: AbilityInfo): Promise\ -Checks whether the ability that matches a given **AbilityInfo** object is enabled. This API uses a promise to return the result. +Checks whether the ability that matches a given AbilityInfo object is enabled. This API uses a promise to return the result. **System capability** @@ -868,7 +868,7 @@ bundle.getAbilityInfo(bundleName, abilityName).then((abilityInfo) => { isAbilityEnabled(info : AbilityInfo, callback : AsyncCallback\): void -Checks whether the ability that matches a given **AbilityInfo** object is enabled. This API uses an asynchronous callback to return the result. +Checks whether the ability that matches a given AbilityInfo object is enabled. This API uses an asynchronous callback to return the result. **System capability** @@ -1135,7 +1135,7 @@ bundle.queryAbilityByWant(want, bundleFlags, (err, data) => { getLaunchWantForBundle(bundleName: string): Promise\ -Obtains the **Want** object that launches the specified application. This API uses a promise to return the result. +Obtains the Want object that launches the specified application. This API uses a promise to return the result. **Required permissions** @@ -1178,7 +1178,7 @@ bundle.getLaunchWantForBundle(bundleName) getLaunchWantForBundle(bundleName: string, callback: AsyncCallback\): void -Obtains the **Want** object that launches the specified application. This API uses an asynchronous callback to return the result. +Obtains the Want object that launches the specified application. This API uses an asynchronous callback to return the result. **Required permissions** @@ -1293,7 +1293,7 @@ bundle.getNameForUid(uid, (err, data) => { getAbilityIcon(bundleName: string, abilityName: string): Promise\ -Obtains the [pixel map](../apis-image-kit/js-apis-image.md) of the icon corresponding to a given bundle name and ability name. This API uses a promise to return the result. +Obtains the [PixelMap](../apis-image-kit/js-apis-image.md) of the icon corresponding to a given bundle name and ability name. This API uses a promise to return the result. No permission is required for obtaining the caller's own information. @@ -1340,7 +1340,7 @@ bundle.getAbilityIcon(bundleName, abilityName) getAbilityIcon(bundleName: string, abilityName: string, callback: AsyncCallback\): void -Obtains the [pixel map](../apis-image-kit/js-apis-image.md) of the icon corresponding to a given bundle name and ability name. This API uses an asynchronous callback to return the result. +Obtains the [PixelMap](../apis-image-kit/js-apis-image.md) of the icon corresponding to a given bundle name and ability name. This API uses an asynchronous callback to return the result. No permission is required for obtaining the caller's own information. @@ -1394,7 +1394,7 @@ bundle.getAbilityIcon(bundleName, abilityName, (err, data) => { | STATUS_INSTALL_FAILURE_INCOMPATIBLE | 6 | Installation incompatibility. (A downgrade occurs or the signature information is incorrect.)| | STATUS_UNINSTALL_FAILURE | 7 | Uninstallation failed. (The application to be uninstalled is not found.) | | STATUS_UNINSTALL_FAILURE_BLOCKED | 8 | Uninstallation aborted. (This error code is not in use.) | -| STATUS_UNINSTALL_FAILURE_ABORTED | 9 | Uninstallation aborted. (Invalid parameters.) | +| STATUS_UNINSTALL_FAILURE_ABORTED | 9 | Uninstallation aborted. (Invalid parameters.) | | STATUS_UNINSTALL_FAILURE_CONFLICT | 10 | Uninstallation conflict. (Failed to uninstall a system application or end the application process.)| | STATUS_INSTALL_FAILURE_DOWNLOAD_TIMEOUT | 0x0B | Installation failed. (Download timed out.) | | STATUS_INSTALL_FAILURE_DOWNLOAD_FAILED | 0x0C | Installation failed. (Download failed.) | @@ -1507,7 +1507,7 @@ Enumerates the color modes of applications and widgets. | Name | Value | Description | | ---------- | ---- | -------- | -| AUTO_MODE | -1 | Automatic mode.| +| AUTO_MODE | -1 | Auto mode.| | DARK_MODE | 0 | Dark mode.| | LIGHT_MODE | 1 | Light mode.| diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-ability-ability.md b/en/application-dev/reference/apis-ability-kit/js-apis-ability-ability.md index 956a632aada8ddae1dfba753c5ebd732b07c6359..a704dc9740a5cc1d3be2986a1a71c52f0145bd7e 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-ability-ability.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-ability-ability.md @@ -12,19 +12,108 @@ The **Ability** module provides all level-2 module APIs for developers to export import { ability } from '@kit.AbilityKit'; ``` -## Properties - -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore - -| Name| Type| Read Only| Optional| Description | -| ---- | ---- | --- | ---- | --------- | -| DataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | No| No| Level-2 module **DataAbilityHelper**.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
**Model restriction**: This API can be used only in the FA model.| -| PacMap | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap) | No| No| Level-2 module **PacMap**.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel| -| DataAbilityOperation | [DataAbilityOperation](js-apis-inner-ability-dataAbilityOperation.md) | No| No| Level-2 module **DataAbilityOperation**.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
**Model restriction**: This API can be used only in the FA model.| -| DataAbilityResult | [DataAbilityResult](js-apis-inner-ability-dataAbilityResult.md) | No| No| Level-2 module **DataAbilityResult**.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
**Model restriction**: This API can be used only in the FA model.| -| AbilityResult | [AbilityResult](js-apis-inner-ability-abilityResult.md) | No| No| Level-2 module **AbilityResult**.
**System capability**: SystemCapability.Ability.AbilityBase
**Model restriction**: This API can be used only in the FA model.| -| ConnectOptions | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | No| No| Level-2 module **ConnectOptions**.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Model restriction**: This API can be used only in the FA model.| -| StartAbilityParameter | [StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | No| No| Level-2 module **StartAbilityParameter**.
**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
**Model restriction**: This API can be used only in the FA model.| +## DataAbilityHelper + +type DataAbilityHelper = _DataAbilityHelper + +Defines the level-2 module DataAbilityHelper. + +**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel + +**Model restriction**: This API can be used only in the FA model. + +| Type| Description| +| --- | --- | +| [_DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | Level-2 module DataAbilityHelper.| + + +## PacMap + +type PacMap = _PacMap + +Defines the level-2 module PacMap. + +**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel + +| Type| Description| +| --- | --- | +| [_PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap) | Level-2 module DataAbilityHelper.| + + +## DataAbilityOperation + +type DataAbilityOperation = _DataAbilityOperation + +Defines the level-2 module DataAbilityOperation. + +**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel + +**Model restriction**: This API can be used only in the FA model. + +| Type| Description| +| --- | --- | +| [_DataAbilityOperation](js-apis-inner-ability-dataAbilityOperation.md) | Level-2 module DataAbilityOperation.| + + +## DataAbilityResult + +type DataAbilityResult = _DataAbilityResult + +Defines the level-2 module DataAbilityResult. + +**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel + +**Model restriction**: This API can be used only in the FA model. + +| Type| Description| +| --- | --- | +| [_DataAbilityResult](js-apis-inner-ability-dataAbilityResult.md) | Level-2 module DataAbilityResult.| + + +## AbilityResult + +type AbilityResult = _AbilityResult + +Defines the level-2 module AbilityResult. + +**System capability**: SystemCapability.Ability.AbilityBase + +**Model restriction**: This API can be used only in the FA model. + +| Type| Description| +| --- | --- | +| [_AbilityResult](js-apis-inner-ability-abilityResult.md) | Level-2 module AbilityResult.| + + +## ConnectOptions + +type ConnectOptions = _ConnectOptions + +Defines the level-2 module ConnectOptions. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Model restriction**: This API can be used only in the FA model. + +| Type| Description| +| --- | --- | +| [_ConnectOptions](js-apis-inner-ability-connectOptions.md) | Level-2 module ConnectOptions.| + + +## StartAbilityParameter + +type StartAbilityParameter = _StartAbilityParameter + +Defines the level-2 module StartAbilityParameter. + +**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel + +**Model restriction**: This API can be used only in the FA model. + +| Type| Description| +| --- | --- | +| [_StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | Level-2 module StartAbilityParameter.| + **Example** ```ts diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-ability-featureAbility.md b/en/application-dev/reference/apis-ability-kit/js-apis-ability-featureAbility.md index ec90caec04226b00b551b0be3d8a4abf5e5f5897..4eeff15a70948f444b2408ad2692e2b7f318d0ee 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-ability-featureAbility.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-ability-featureAbility.md @@ -907,3 +907,45 @@ Enumerates the operation types of a DataAbility. The DataAbility can use an enum | TYPE_UPDATE | 2 | Update operation.| | TYPE_DELETE | 3 | Deletion operation.| | TYPE_ASSERT | 4 | Assert operation.| + +## Context9+ + +type Context = _Context + +Defines the Context module. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Model restriction**: This API can be used only in the FA model. + +| Type| Description| +| --- | --- | +| [_Context](js-apis-inner-app-context.md) | Context module.| + +## AppVersionInfo9+ + +type AppVersionInfo = _AppVersionInfo + +Defines an **AppVersionInfo** object. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Model restriction**: This API can be used only in the FA model. + +| Type| Description| +| --- | --- | +| [_AppVersionInfo](js-apis-inner-app-appVersionInfo.md) | **AppVersionInfo** object.| + +## ProcessInfo9+ + +type ProcessInfo = _ProcessInfo + +Defines a **ProcessInfo** object. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Model restriction**: This API can be used only in the FA model. + +| Type| Description| +| --- | --- | +| [_ProcessInfo](js-apis-inner-app-processInfo.md) | **ProcessInfo** object.| diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-ability-wantConstant-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-ability-wantConstant-sys.md index b040bca298b2580cdf1ef82c9545ae23b112e18a..104e6998b071f14c5d7191f222400951c07f168f 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-ability-wantConstant-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-ability-wantConstant-sys.md @@ -1,6 +1,6 @@ # @ohos.ability.wantConstant (wantConstant) (System API) -The **wantConstant** module provides the actions, entities, and flags used in **Want** objects. +The wantConstant module provides the actions, entities, and flags used in **Want** objects. > **NOTE** > @@ -20,8 +20,10 @@ import wantConstant from '@ohos.ability.wantConstant'; **System capability**: SystemCapability.Ability.AbilityBase +**System API**: This is a system API. + | Name | Value | Description | | ------------------------------------ | ---------- | ------------------------------------------------------------ | -| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Grants the permission to make the URI persistent.
**System API**: This is a system API and cannot be called by third-party applications. | -| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Grants the permission to verify URIs by prefix matching.
**System API**: This is a system API and cannot be called by third-party applications.| -| FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | Indicates that ability continuation is reversible.
**System API**: This is a system API and cannot be called by third-party applications. | +| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Grants the permission to make the URI persistent. | +| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Grants the permission to verify URIs by prefix matching.| +| FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | Indicates that ability continuation is reversible. | diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-ability-wantConstant.md b/en/application-dev/reference/apis-ability-kit/js-apis-ability-wantConstant.md index 9f482ab52c304e05f0e38c979a35f31b56fa8d6a..be4468e27a7c33bfa0e5f2cc9c3cd1632e61edec 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-ability-wantConstant.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-ability-wantConstant.md @@ -21,7 +21,7 @@ Enumerates the action constants of the **Want** object. **action** specifies the | Name | Value | Description | | ------------ | ------------------ | ---------------------- | | ACTION_HOME | ohos.want.action.home | Action of returning to the home page. | -| ACTION_DIAL | ohos.want.action.dial | Action of launching the numeric keypad. | +| ACTION_DIAL | ohos.want.action.dial | Action of launching the numeric keypad. | | ACTION_SEARCH | ohos.want.action.search | Action of launching the search function. | | ACTION_WIRELESS_SETTINGS | ohos.settings.wireless | Action of launching the UI that provides wireless network settings, for example, Wi-Fi options. | | ACTION_MANAGE_APPLICATIONS_SETTINGS | ohos.settings.manage.applications | Action of launching the UI for managing installed applications. | @@ -84,4 +84,3 @@ Enumerates the entity constants of the **Want** object. **entity** specifies add | FLAG_ABILITY_CLEAR_MISSION | 0x00008000 | Clears other operation missions. This flag can be set for **Want** passed in [startAbility](js-apis-ability-featureAbility.md#startability). It must be used together with **FLAG_ABILITY_NEW_MISSION**.| | FLAG_ABILITY_NEW_MISSION | 0x10000000 | Creates a mission on the history mission stack. | | FLAG_ABILITY_MISSION_TOP | 0x20000000 | Reuses an ability instance if it is on the top of an existing mission stack; creates an ability instance otherwise.| -| FLAG_ABILITY_ON_COLLABORATE16+ | 0x00002000 | In multi-device collaboration scenario, the caller application must initiate a request through the DMS, with this flag included in the **Flags** field, in order to invoke the lifecycle callback [onCollaborate(wantParam)](js-apis-app-ability-uiAbility.md#uiabilityoncollaborate) of the target application.| diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-abilityAccessCtrl-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-abilityAccessCtrl-sys.md index 3809467363da0c1bd54eafa7e49c3513c4331e86..043b72e4de0a1a60abba5c83d30a343daa3473ab 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-abilityAccessCtrl-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-abilityAccessCtrl-sys.md @@ -33,8 +33,8 @@ Grants a user_grant permission to an application. This API uses a promise to ret | Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | Yes | Application token ID, which is the value of **accessTokenId** in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| -| permissionName | Permissions | Yes | Permission to grant. For details about the permissions, see [Permissions for All Applications](../../security/AccessToken/permissions-for-all.md).| +| tokenID | number | Yes | Identifier of the target application, which is the value of **accessTokenId** contained in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| +| permissionName | Permissions | Yes | Permission to grant. For details, see [Application Permissions](../../security/AccessToken/app-permissions.md).| | permissionFlags | number | Yes | Permission flag.
- **1**: A dialog box for user authorization will be displayed the next time if the user denies authorization for the permission.
- **2**: No dialog box will be displayed the next time if the user denies authorization for the permission. The permission must be granted by the user in **Settings**.
- **64**: The permission is granted to the user only this time. The authorization is revoked after the application switches to the background or exits.| **Return value** @@ -90,10 +90,10 @@ Grants a user_grant permission to an application. This API uses an asynchronous | Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | Yes | Application token ID, which is the value of **accessTokenId** in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| -| permissionName | Permissions | Yes | Permission to grant. For details about the permissions, see [Permissions for All Applications](../../security/AccessToken/permissions-for-all.md).| +| tokenID | number | Yes | Identifier of the target application, which is the value of **accessTokenId** contained in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| +| permissionName | Permissions | Yes | Permission to grant. For details, see [Application Permissions](../../security/AccessToken/app-permissions.md).| | permissionFlags | number | Yes | Permission flag.
- **1**: A dialog box for user authorization will be displayed the next time if the user denies authorization for the permission.
- **2**: No dialog box will be displayed the next time if the user denies authorization for the permission. The permission must be granted by the user in **Settings**.
- **64**: The permission is granted to the user only this time. The authorization is revoked after the application switches to the background or exits.| -| callback | AsyncCallback<void> | Yes| Grants a user_grant permission to an application. If the permission is granted, **err** is **undefined**. Otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the permission is granted, **err** is **undefined**. Otherwise, **err** is an error object.| **Error codes** @@ -144,8 +144,8 @@ Revokes a user_grant permission from an application. This API uses a promise to | Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | Yes | Application token ID, which is the value of **accessTokenId** in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| -| permissionName | Permissions | Yes | Permission to revoke. For details about the permissions, see [Permissions for All Applications](../../security/AccessToken/permissions-for-all.md).| +| tokenID | number | Yes | Identifier of the target application, which is the value of **accessTokenId** contained in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| +| permissionName | Permissions | Yes | Permission to revoke. For details, see [Application Permissions](../../security/AccessToken/app-permissions.md).| | permissionFlags | number | Yes | Permission flag.
- **1**: A dialog box for user authorization will be displayed the next time if the user denies authorization for the permission.
- **2**: No dialog box will be displayed the next time if the user denies authorization for the permission. The permission must be granted by the user in **Settings**.
- **64**: The permission is granted to the user only this time. The authorization is revoked after the application switches to the background or exits.| **Return value** @@ -201,10 +201,10 @@ Revokes a user_grant permission from an application. This API uses an asynchrono | Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | Yes | Application token ID, which is the value of **accessTokenId** in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| -| permissionName | Permissions | Yes | Permission to revoke. For details about the permissions, see [Permissions for All Applications](../../security/AccessToken/permissions-for-all.md).| +| tokenID | number | Yes | Identifier of the target application, which is the value of **accessTokenId** contained in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| +| permissionName | Permissions | Yes | Permission to revoke. For details, see [Application Permissions](../../security/AccessToken/app-permissions.md).| | permissionFlags | number | Yes | Permission flag.
- **1**: A dialog box for user authorization will be displayed the next time if the user denies authorization for the permission.
- **2**: No dialog box will be displayed the next time if the user denies authorization for the permission. The permission must be granted by the user in **Settings**.
- **64**: The permission is granted to the user only this time. The authorization is revoked after the application switches to the background or exits.| -| callback | AsyncCallback<void> | Yes| Callback invoked to return the result. If the permission is revoked, **err** is **undefined**. Otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the permission is successfully revoked, **err** is **undefined**. Otherwise, **err** is an error object.| **Error codes** @@ -255,14 +255,14 @@ Obtains the flag of the specified permission of an application. This API uses a | Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | Yes | Application token ID, which is the value of **accessTokenId** in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| -| permissionName | Permissions | Yes | Permission whose flag is to be obtained. For details about the permissions, see [Permissions for All Applications](../../security/AccessToken/permissions-for-all.md).| +| tokenID | number | Yes | Identifier of the target application, which is the value of **accessTokenId** contained in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| +| permissionName | Permissions | Yes | Permission whose flag is to be obtained. For details, see [Application Permissions](../../security/AccessToken/app-permissions.md).| **Return value** | Type | Description | | :------------ | :---------------------------------- | -| Promise<number> | Promise used to return the result.| +| Promise<number> | Promise used to return the flag obtained.| **Error codes** @@ -310,7 +310,7 @@ Sets the toggle state of a permission. This API uses a promise to return the res | Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| permissionName | Permissions | Yes | Permission to be set with the toggle state. For details about the permissions, see [Permissions for All Applications](../../security/AccessToken/permissions-for-all.md).| +| permissionName | Permissions | Yes | Permission to be set with the toggle state. For details, see [Application Permissions](../../security/AccessToken/app-permissions.md).| | status | [PermissionRequestToggleStatus](#permissionrequesttogglestatus12) | Yes | Toggle state to set. | **Return value** @@ -364,7 +364,7 @@ Obtains the toggle state of a permission. This API uses a promise to return the | Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| permissionName | Permissions | Yes | Permission whose toggle state is to be obtained. For details about the permissions, see [Permissions for All Applications](../../security/AccessToken/permissions-for-all.md).| +| permissionName | Permissions | Yes | Permission whose toggle state is to be obtained. For details, see [Application Permissions](../../security/AccessToken/app-permissions.md).| **Return value** @@ -453,14 +453,14 @@ Obtains the status of the specified permissions. This API uses a promise to retu | Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | Yes | Application token ID, which is the value of **accessTokenId** in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| -| permissionList | Array<Permissions> | Yes | Permissions whose status is to be obtained. For details about the permissions, see [Permissions for All Applications](../../security/AccessToken/permissions-for-all.md).| +| tokenID | number | Yes | Identifier of the target application, which is the value of **accessTokenId** contained in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| +| permissionList | Array<Permissions> | Yes | Permissions whose status is to be obtained. For details, see [Application Permissions](../../security/AccessToken/app-permissions.md).| **Return value** | Type | Description | | :------------ | :---------------------------------- | -| Promise<Array<[PermissionStatus](#permissionstatus12)>> | Promise used to return the permission status obtained.| +| Promise<Array<[PermissionStatus](#permissionstatus12)>> | Promise used to return the permission statuses obtained.| **Error codes** @@ -494,7 +494,7 @@ atManager.getPermissionsStatus(tokenID, ['ohos.permission.CAMERA']).then((data: on(type: 'permissionStateChange', tokenIDList: Array<number>, permissionList: Array<Permissions>, callback: Callback<PermissionStateChangeInfo>): void -Subscribes to permission state changes of the specified applications and permissions. +Subscribes to changes in the state of specified permissions for the given applications. Multiple callbacks can be registered for the specified **tokenIDList** and **permissionList**. @@ -510,10 +510,10 @@ If **tokenIDList** and **permissionList** have common values with the **tokenIDL | Name | Type | Mandatory| Description | | ------------------ | --------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is **'permissionStateChange'**, which indicates the permission grant state changes. | -| tokenIDList | Array<number> | Yes | List of application token IDs. If this parameter is left empty, this API subscribes to the permission grant state changes of all applications.| -| permissionList | Array<Permissions> | Yes | List of permissions to be subscribed to. If this parameter is left empty, this API subscribes to state changes of all permissions. For details about the permissions, see [Permissions for All Applications](../../security/AccessToken/permissions-for-all.md).| -| callback | Callback<[PermissionStateChangeInfo](#permissionstatechangeinfo9)> | Yes| Callback invoked to return the permission grant state change.| +| type | string | Yes | Event type. The value is **'permissionStateChange'**, which indicates the permission state changes. | +| tokenIDList | Array<number> | Yes | List of application token IDs. If this parameter is not specified, this API will subscribe to the permission state changes of all applications. | +| permissionList | Array<Permissions> | Yes | List of target permissions. If this parameter is not specified, this API will subscribe to state changes of all permissions. For details about the permissions, see [Application Permissions](../../security/AccessToken/app-permissions.md). | +| callback | Callback<[PermissionStateChangeInfo](js-apis-abilityAccessCtrl.md#permissionstatechangeinfo18)> | Yes| Callback invoked to return the permission state change. | **Error codes** @@ -552,9 +552,9 @@ try { off(type: 'permissionStateChange', tokenIDList: Array<number>, permissionList: Array<Permissions>, callback?: Callback<PermissionStateChangeInfo>): void -Unsubscribes from permission grant state changes of the specified applications and permissions. This API uses a callback to return the result. +Unsubscribes from changes in the state of specified permissions for the given applications. This API uses an asynchronous callback to return the result. -If no callback is passed in **atManager.off**, all callbacks for **tokenIDList** and **permissionList** will be unregistered. +If **callback** is not specified, this API will unregister all callbacks for **tokenIDList** and **permissionList**. **System API**: This is a system API. @@ -566,10 +566,10 @@ If no callback is passed in **atManager.off**, all callbacks for **tokenIDList** | Name | Type | Mandatory| Description | | ------------------ | --------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is **'permissionStateChange'**, which indicates the permission grant state changes. | -| tokenIDList | Array<number> | Yes | List of application token IDs. The value must be the same as that passed in **on()**. If this parameter is left empty, this API unsubscribes from the permission grant state changes of all applications.| -| permissionList | Array<Permissions> | Yes | List of permissions. The value must be the same as that of **on()**. If this parameter is left empty, this API unsubscribes from state changes of all permissions. For details about the permissions, see [Permissions for All Applications](../../security/AccessToken/permissions-for-all.md).| -| callback | Callback<[PermissionStateChangeInfo](#permissionstatechangeinfo9)> | No| Callback for the permission grant state change.| +| type | string | Yes | Event type. The value is **'permissionStateChange'**, which indicates the permission state changes. | +| tokenIDList | Array<number> | Yes | List of application token IDs. The value must be the same as that in **on()**. If this parameter is not specified, this API will unsubscribe from the permission state changes of all applications. | +| permissionList | Array<Permissions> | Yes | List of target permissions. The value must be the same as that in **on()**. If this parameter is not specified, this API will unsubscribe from state changes for all permissions. For details about the permissions, see [Application Permissions](../../security/AccessToken/app-permissions.md).| +| callback | Callback<[PermissionStateChangeInfo](js-apis-abilityAccessCtrl.md#permissionstatechangeinfo18)> | No| Callback to unregister.| **Error codes** @@ -601,43 +601,65 @@ try { } ``` -### PermissionStateChangeType9+ +### requestPermissionOnApplicationSetting18+ -Enumerates the operations that trigger permission grant state changes. +requestPermissionOnApplicationSetting(tokenID: number): Promise<void> + +Starts the permission settings page for an application. This API uses a promise to return the result. **System API**: This is a system API. +**Model restriction**: This API can be used only in the stage model. + **System capability**: SystemCapability.Security.AccessToken -| Name | Value| Description | -| ----------------------- | ------ | ----------------- | -| PERMISSION_REVOKED_OPER | 0 | Operation to revoke the permission.| -| PERMISSION_GRANTED_OPER | 1 | Operation to grant the permission.| +**Parameters** -### PermissionRequestToggleStatus12+ +| Name | Type | Mandatory| Description | +| --------- | ------------------- | ---- | ------------------------------------------------------------ | +| tokenID | number | Yes | Identifier of the target application, which is the value of **accessTokenId** contained in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| -Enumerates the permission toggle states. +**Return value** -**System capability**: SystemCapability.Security.AccessToken +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<void> | Promise that returns no value.| -| Name | Value| Description | -| ------------------ | ----- | ----------- | -| CLOSED | 0 | The permission request toggle is disabled.| -| OPEN | 1 | The permission request toggle is enabled.| +**Error codes** + +For details about the error codes, see [Access Control Error Codes](errorcode-access-token.md). + +| ID| Error Message| +| -------- | -------- | +| 202 | Not System App. Interface caller is not a system app. | +| 12100002 | The specified tokenID does not exist. | +| 12100007 | The service is abnormal. | -### PermissionStateChangeInfo9+ +**Example** -Defines detailed information about the permission grant state change. +```ts +import { abilityAccessCtrl } from '@kit.AbilityKit'; +import { BusinessError } from '@kit.BasicServicesKit'; -**System API**: This is a system API. +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); +let tokenID: number = 0; // System applications can obtain the token ID using bundleManager.getApplicationInfo. +atManager.requestPermissionOnApplicationSetting(tokenID).then(() => { + console.log('requestPermissionOnApplicationSetting success'); +}).catch((err: BusinessError) => { + console.error(`requestPermissionOnApplicationSetting fail, err->${JSON.stringify(err)}`); +}); +``` + +### PermissionRequestToggleStatus12+ + +Enumerates the permission toggle states. **System capability**: SystemCapability.Security.AccessToken -| Name | Type | Read Only| Mandatory| Description | -| -------------- | ------------------------- | ---- | ---- | ------------------ | -| change | [PermissionStateChangeType](#permissionstatechangetype9) | Yes | Yes | Operation that triggers the permission grant state change. | -| tokenID | number | Yes | Yes | Application token ID, which is the value of **accessTokenId** in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| -| permissionName | Permissions | Yes | Yes | Permission whose grant state changes. For details about the permissions, see [Permissions for All Applications](../../security/AccessToken/permissions-for-all.md).| +| Name | Value| Description | +| ------------------ | ----- | ----------- | +| CLOSED | 0 | The permission is toggled off. | +| OPEN | 1 | The permission is toggled on. | ### PermissionStatus12+ diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-abilityAccessCtrl.md b/en/application-dev/reference/apis-ability-kit/js-apis-abilityAccessCtrl.md index 4474fe3c08d29503e99097217cb1b608f741200f..687c8f73ebb3dc31fb1c213f93c192244e9d01b3 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-abilityAccessCtrl.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-abilityAccessCtrl.md @@ -15,7 +15,7 @@ import { abilityAccessCtrl } from '@kit.AbilityKit' createAtManager(): AtManager -Creates an **AtManager** instance, which is used for application access control. +Creates an **AtManager** instance for application access control. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -52,8 +52,8 @@ Checks whether a permission is granted to an application. This API uses a promis | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------ | -| tokenID | number | Yes | Application token ID, which is the value of **accessTokenId** in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| -| permissionName | Permissions | Yes | Permission to check. For details about the permissions, see [Permissions for All Applications](../../security/AccessToken/permissions-for-all.md).| +| tokenID | number | Yes | Identifier of the target application, which is the value of **accessTokenId** contained in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| +| permissionName | Permissions | Yes | Permission to check. For details about the permission, see [Application Permissions](../../security/AccessToken/app-permissions.md).| **Return value** @@ -85,11 +85,13 @@ atManager.checkAccessToken(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS }); ``` -### verifyAccessTokenSync9+ +### checkAccessTokenSync10+ -verifyAccessTokenSync(tokenID: number, permissionName: Permissions): GrantStatus +checkAccessTokenSync(tokenID: number, permissionName: Permissions): GrantStatus -Verifies whether a permission is granted to an application. This API returns the result synchronously. +Checks whether a permission is granted to an application. This API returns the result synchronously. + +**Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.Security.AccessToken @@ -97,8 +99,8 @@ Verifies whether a permission is granted to an application. This API returns the | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------ | -| tokenID | number | Yes | Application token ID, which is the value of **accessTokenId** in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| -| permissionName | Permissions | Yes | Permission to verify. For details about the permissions, see [Permissions for All Applications](../../security/AccessToken/permissions-for-all.md).| +| tokenID | number | Yes | Identifier of the target application, which is the value of **accessTokenId** contained in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| +| permissionName | Permissions | Yes | Permission to check. For details about the permission, see [Application Permissions](../../security/AccessToken/app-permissions.md).| **Return value** @@ -118,57 +120,107 @@ For details about the error codes, see [Access Control Error Codes](errorcode-ac **Example** ```ts -import { abilityAccessCtrl } from '@kit.AbilityKit'; +import { abilityAccessCtrl, Permissions } from '@kit.AbilityKit'; let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); let tokenID: number = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a third-party application. +let permissionName: Permissions = 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS'; +let data: abilityAccessCtrl.GrantStatus = atManager.checkAccessTokenSync(tokenID, permissionName); +console.log(`data->${JSON.stringify(data)}`); +``` + +### on18+ + +on(type: 'selfPermissionStateChange', permissionList: Array<Permissions>, callback: Callback<PermissionStateChangeInfo>): void + +Subscribes to changes in the state of the specified permissions for this application. + +Multiple callbacks can be registered for the same permission list. + +The same callback cannot be registered for overlapping permission lists. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Security.AccessToken + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------------ | --------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is **'selfPermissionStateChange'**, which indicates the changes in the permission states specific to this application alone. | +| permissionList | Array<Permissions> | Yes | List of target permissions. If this parameter is not specified, this API will subscribe to state changes of all permissions for this application. For details about the permissions, see [Application Permissions](../../security/AccessToken/app-permissions.md).| +| callback | Callback<[PermissionStateChangeInfo](#permissionstatechangeinfo18)> | Yes| Callback used to return the permission state change.| + +**Error codes** + +For details about the error codes, see [Access Control Error Codes](errorcode-access-token.md). + +| ID| Error Message| +| -------- | -------- | +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | +| 12100001 | Invalid parameter. The permissionName exceeds 256 characters. | +| 12100004 | The API is used repeatedly with the same input. | +| 12100005 | The registration time has exceeded the limitation. | +| 12100007 | The service is abnormal. | + +**Example** + +```ts +import { abilityAccessCtrl, Permissions } from '@kit.AbilityKit'; + +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); +let permissionList: Array = ['ohos.permission.APPROXIMATELY_LOCATION']; try { - let data: abilityAccessCtrl.GrantStatus = atManager.verifyAccessTokenSync(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS'); - console.log(`data->${JSON.stringify(data)}`); + atManager.on('selfPermissionStateChange', permissionList, (data: abilityAccessCtrl.PermissionStateChangeInfo) => { + console.log('receive permission state change, data:' + JSON.stringify(data)); + }); } catch(err) { - console.error(`catch err->${JSON.stringify(err)}`); + console.error(`catch err->${JSON.stringify(err)}`); } ``` +### off18+ -### verifyAccessToken9+ +off(type: 'selfPermissionStateChange', permissionList: Array<Permissions>, callback?: Callback<PermissionStateChangeInfo>): void -verifyAccessToken(tokenID: number, permissionName: Permissions): Promise<GrantStatus> +Unsubscribes from changes in the state of the specified permissions for this application. -Verifies whether a permission is granted to an application. This API uses a promise to return the result. +If **callback** is not specified, this API will unregister all callbacks for **permissionList**. -> **NOTE** -> -> You are advised to use [checkAccessToken](#checkaccesstoken9). +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.Security.AccessToken **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------- | ---- | ------------------------------------------ | -| tokenID | number | Yes | Application token ID, which is the value of **accessTokenId** in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| -| permissionName | Permissions | Yes | Permission to verify. For details about the permissions, see [Permissions for All Applications](../../security/AccessToken/permissions-for-all.md).| +| Name | Type | Mandatory| Description | +| ------------------ | --------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is **'selfPermissionStateChange'**, which indicates the changes in the permission states specific to this application alone. | +| permissionList | Array<Permissions> | Yes | List of target permissions. The value must be the same as that in **on()**. If this parameter is not specified, this API will unsubscribe from state changes for all permissions. For details about the permissions, see [Application Permissions](../../security/AccessToken/app-permissions.md).| +| callback | Callback<[PermissionStateChangeInfo](#permissionstatechangeinfo18)> | No| Callback to unregister.| -**Return value** +**Error codes** -| Type | Description | -| :------------ | :---------------------------------- | -| Promise<[GrantStatus](#grantstatus)> | Promise used to return the permission grant state.| +For details about the error codes, see [Access Control Error Codes](errorcode-access-token.md). + +| ID| Error Message| +| -------- | -------- | +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | +| 12100001 | Invalid parameter. The permissionNames in the list are all invalid. | +| 12100004 | The API is not used in pair with 'on'. | +| 12100007 | The service is abnormal. | **Example** ```ts import { abilityAccessCtrl, Permissions } from '@kit.AbilityKit'; -import { BusinessError } from '@kit.BasicServicesKit'; let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); -let tokenID: number = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a third-party application. -let permissionName: Permissions = 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS'; -atManager.verifyAccessToken(tokenID, permissionName).then((data: abilityAccessCtrl.GrantStatus) => { - console.log(`promise: data->${JSON.stringify(data)}`); -}).catch((err: BusinessError) => { - console.error(`verifyAccessToken fail, err->${JSON.stringify(err)}`); -}); +let permissionList: Array = ['ohos.permission.APPROXIMATELY_LOCATION']; +try { + atManager.off('selfPermissionStateChange', permissionList); +} catch(err) { + console.error(`catch err->${JSON.stringify(err)}`); +} ``` ### requestPermissionsFromUser9+ @@ -194,7 +246,7 @@ If the user rejects to grant the permission, the authorization dialog box cannot | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | context | [Context](js-apis-inner-application-context.md) | Yes| Context of the UIAbility that requests the permission.| -| permissionList | Array<Permissions> | Yes| Permissions to request. For details about the permissions, see [Permissions for All Applications](../../security/AccessToken/permissions-for-all.md).| +| permissionList | Array<Permissions> | Yes| Permissions to request. For details about the permissions, see [Application Permissions](../../security/AccessToken/app-permissions.md).| | requestCallback | AsyncCallback<[PermissionRequestResult](js-apis-permissionrequestresult.md)> | Yes| Callback used to return the result.| **Error codes** @@ -252,7 +304,7 @@ If the user rejects to grant the permission, the authorization dialog box cannot | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | context | [Context](js-apis-inner-application-context.md) | Yes| Context of the UIAbility that requests the permission.| -| permissionList | Array<Permissions> | Yes| Permissions to request. For details about the permissions, see [Permissions for All Applications](../../security/AccessToken/permissions-for-all.md).| +| permissionList | Array<Permissions> | Yes| Permissions to request. For details about the permissions, see [Application Permissions](../../security/AccessToken/app-permissions.md).| **Return value** @@ -290,103 +342,6 @@ atManager.requestPermissionsFromUser(context, ['ohos.permission.CAMERA']).then(( }); ``` -### verifyAccessToken(deprecated) - -verifyAccessToken(tokenID: number, permissionName: string): Promise<GrantStatus> - -Verifies whether a permission is granted to an application. This API uses a promise to return the result. - -> **NOTE** -> -> This API is no longer maintained since API version 9. Use [checkAccessToken](#checkaccesstoken9) instead. - -**System capability**: SystemCapability.Security.AccessToken - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------- | ---- | ------------------------------------------ | -| tokenID | number | Yes | Application token ID, which is the value of **accessTokenId** in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| -| permissionName | string | Yes | Permission to verify. For details about the permissions, see [Permissions for All Applications](../../security/AccessToken/permissions-for-all.md).| - -**Return value** - -| Type | Description | -| :------------ | :---------------------------------- | -| Promise<[GrantStatus](#grantstatus)> | Promise used to return the permission grant state.| - -**Example** - -```ts -import { abilityAccessCtrl } from '@kit.AbilityKit'; -import { BusinessError } from '@kit.BasicServicesKit'; - -let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); -let tokenID: number = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a third-party application. -atManager.verifyAccessToken(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS').then((data: abilityAccessCtrl.GrantStatus) => { - console.log(`promise: data->${JSON.stringify(data)}`); -}).catch((err: BusinessError) => { - console.error(`verifyAccessToken fail, err->${JSON.stringify(err)}`); -}); -``` - -### checkAccessTokenSync10+ - -checkAccessTokenSync(tokenID: number, permissionName: Permissions): GrantStatus - -Checks whether a permission is granted to an application. This API returns the result synchronously. - -**Atomic service API**: This API can be used in atomic services since API version 11. - -**System capability**: SystemCapability.Security.AccessToken - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------- | ---- | ------------------------------------------ | -| tokenID | number | Yes | Application token ID, which is the value of **accessTokenId** in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| -| permissionName | Permissions | Yes | Permission to check. For details about the permissions, see [Permissions for All Applications](../../security/AccessToken/permissions-for-all.md).| - -**Return value** - -| Type | Description | -| :------------ | :---------------------------------- | -| [GrantStatus](#grantstatus) | Permission grant state.| - -**Error codes** - -For details about the error codes, see [Access Control Error Codes](errorcode-access-token.md). - -| ID| Error Message| -| -------- | -------- | -| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | -| 12100001 | Invalid parameter. The tokenID is 0, or the permissionName exceeds 256 characters. | - -**Example** - -```ts -import { abilityAccessCtrl, Permissions } from '@kit.AbilityKit'; - -let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); -let tokenID: number = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a third-party application. -let permissionName: Permissions = 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS'; -let data: abilityAccessCtrl.GrantStatus = atManager.checkAccessTokenSync(tokenID, permissionName); -console.log(`data->${JSON.stringify(data)}`); -``` - -### GrantStatus - -Enumerates the permission grant states. - -**Atomic service API**: This API can be used in atomic services since API version 11. - -**System capability**: SystemCapability.Security.AccessToken - -| Name | Value| Description | -| ------------------ | ----- | ----------- | -| PERMISSION_DENIED | -1 | The permission is not granted.| -| PERMISSION_GRANTED | 0 | The permission is granted.| - ### requestPermissionOnSetting12+ requestPermissionOnSetting(context: Context, permissionList: Array<Permissions>): Promise<Array<GrantStatus>> @@ -416,7 +371,7 @@ Before calling this API, the application must have called [requestPermissionsFro | Type | Description | | :------------ | :---------------------------------- | -| Promise<Array<[GrantStatus](#grantstatus)>> | Promise used to return the permission grant state.| +| Promise<Array<[GrantStatus](#grantstatus)>> | Promise used to return the authorization result.| **Error codes** @@ -504,7 +459,146 @@ atManager.requestGlobalSwitch(context, abilityAccessCtrl.SwitchType.CAMERA).then }); ``` -### SwitchType12+ +### verifyAccessTokenSync9+ + +verifyAccessTokenSync(tokenID: number, permissionName: Permissions): GrantStatus + +Verifies whether a permission is granted to an application. This API returns the result synchronously. + +**System capability**: SystemCapability.Security.AccessToken + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------- | ---- | ------------------------------------------ | +| tokenID | number | Yes | Identifier of the target application, which is the value of **accessTokenId** contained in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| +| permissionName | Permissions | Yes | Permission to verify. For details about the permission, see [Application Permissions](../../security/AccessToken/app-permissions.md).| + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| [GrantStatus](#grantstatus) | Permission grant state.| + +**Error codes** + +For details about the error codes, see [Access Control Error Codes](errorcode-access-token.md). + +| ID| Error Message| +| -------- | -------- | +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | +| 12100001 | Invalid parameter. The tokenID is 0, or the permissionName exceeds 256 characters. | + +**Example** + +```ts +import { abilityAccessCtrl } from '@kit.AbilityKit'; + +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); +let tokenID: number = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a third-party application. +try { + let data: abilityAccessCtrl.GrantStatus = atManager.verifyAccessTokenSync(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS'); + console.log(`data->${JSON.stringify(data)}`); +} catch(err) { + console.error(`catch err->${JSON.stringify(err)}`); +} +``` + +### verifyAccessToken9+ + +verifyAccessToken(tokenID: number, permissionName: Permissions): Promise<GrantStatus> + +Verifies whether a permission is granted to an application. This API uses a promise to return the result. + +> **NOTE** +> +> You are advised to use [checkAccessToken](#checkaccesstoken9). + +**System capability**: SystemCapability.Security.AccessToken + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------- | ---- | ------------------------------------------ | +| tokenID | number | Yes | Identifier of the target application, which is the value of **accessTokenId** contained in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| +| permissionName | Permissions | Yes | Permission to verify. For details about the permission, see [Application Permissions](../../security/AccessToken/app-permissions.md).| + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<[GrantStatus](#grantstatus)> | Promise used to return the authorization result.| + +**Example** + +```ts +import { abilityAccessCtrl, Permissions } from '@kit.AbilityKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); +let tokenID: number = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a third-party application. +let permissionName: Permissions = 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS'; +atManager.verifyAccessToken(tokenID, permissionName).then((data: abilityAccessCtrl.GrantStatus) => { + console.log(`promise: data->${JSON.stringify(data)}`); +}).catch((err: BusinessError) => { + console.error(`verifyAccessToken fail, err->${JSON.stringify(err)}`); +}); +``` + +### verifyAccessToken(deprecated) + +verifyAccessToken(tokenID: number, permissionName: string): Promise<GrantStatus> + +Verifies whether a permission is granted to an application. This API uses a promise to return the result. + +> **NOTE** +> +> This API is no longer maintained since API version 9. Use [checkAccessToken](#checkaccesstoken9) instead. + +**System capability**: SystemCapability.Security.AccessToken + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------- | ---- | ------------------------------------------ | +| tokenID | number | Yes | Identifier of the target application, which is the value of **accessTokenId** contained in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| +| permissionName | string | Yes | Permission to verify. For details about the permission, see [Application Permissions](../../security/AccessToken/app-permissions.md).| + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<[GrantStatus](#grantstatus)> | Promise used to return the authorization result.| + +**Example** + +```ts +import { abilityAccessCtrl } from '@kit.AbilityKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); +let tokenID: number = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a third-party application. +atManager.verifyAccessToken(tokenID, 'ohos.permission.GRANT_SENSITIVE_PERMISSIONS').then((data: abilityAccessCtrl.GrantStatus) => { + console.log(`promise: data->${JSON.stringify(data)}`); +}).catch((err: BusinessError) => { + console.error(`verifyAccessToken fail, err->${JSON.stringify(err)}`); +}); +``` + +## GrantStatus + +Enumerates the permission grant states. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.Security.AccessToken + +| Name | Value| Description | +| ------------------ | ----- | ----------- | +| PERMISSION_DENIED | -1 | The permission is not granted.| +| PERMISSION_GRANTED | 0 | The permission is granted.| + +## SwitchType12+ Enumerates the global switch types. @@ -517,3 +611,62 @@ Enumerates the global switch types. | CAMERA | 0 | Global switch of the camera.| | MICROPHONE | 1 | Global switch of the microphone.| | LOCATION | 2 | Global switch of the location service.| + +## PermissionStateChangeType18+ + +Enumerates the operations that trigger permission state changes. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Security.AccessToken + +| Name | Value| Description | +| ----------------------- | ------ | ----------------- | +| PERMISSION_REVOKED_OPER | 0 | Operation to revoke a permission.| +| PERMISSION_GRANTED_OPER | 1 | Operation to grant a permission.| + +## PermissionStateChangeInfo18+ + +Represents the permission state change details. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Security.AccessToken + +| Name | Type | Read Only| Optional| Description | +| -------------- | ------------------------- | ---- | ---- | ------------------ | +| change | [PermissionStateChangeType](#permissionstatechangetype18) | Yes | No | Operation that triggers the permission state change. | +| tokenID | number | Yes | No | Identifier of the target application, which is the value of **accessTokenId** contained in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| +| permissionName | Permissions | Yes | No | Permissions whose authorization state changes. For details about the permissions, see [Application Permissions](../../security/AccessToken/app-permissions.md).| + +## PermissionRequestResult10+ + +type PermissionRequestResult = _PermissionRequestResult + +Represents the permission request result. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**Model restriction**: This API can be used only in the stage model. + +**System capability**: SystemCapability.Security.AccessToken + +| Type| Description| +| -------- | -------- | +| [_PermissionRequestResult](js-apis-permissionrequestresult.md) | Permission request result object.| + +## Context10+ + +type Context = _Context + +Represents the context for the ability or application. It allows access to application-specific resources. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**Model restriction**: This API can be used only in the stage model. + +**System capability**: SystemCapability.Security.AccessToken + +| Type| Description| +| -------- | -------- | +| [_Context](js-apis-inner-application-context.md) | Context for an ability or application to access to application-specific resources.| diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-abilityConstant-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-abilityConstant-sys.md index bd845954820991cbc5b8bc9146a839afadf87f72..a1c4a071720f17a35ab0eaaae2f9120692e0cf77 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-abilityConstant-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-abilityConstant-sys.md @@ -1,6 +1,6 @@ # @ohos.app.ability.AbilityConstant (AbilityConstant) (System API) -The **AbilityConstant** module defines the enums of the window types in the UIAbility. +The AbilityConstant module defines the enums of the window types in the UIAbility. > **NOTE** > @@ -16,7 +16,7 @@ The **AbilityConstant** module defines the enums of the window types in the UIAb import { AbilityConstant } from '@kit.AbilityKit'; ``` -## WindowMode +## WindowMode12+ Enumerates the window modes in which an ability can be displayed at startup. It can be used in **startAbility()** to specify the window mode when the ability is started. diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-abilityConstant.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-abilityConstant.md index 30ecfb61d1a8551dcfa360567b6d6f9efce96dee..ea7499e122596a200a53e7620e9b0dbacce91413 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-abilityConstant.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-abilityConstant.md @@ -23,9 +23,10 @@ Defines the parameters for starting an ability. The parameter values are automat | Name| Type| Read-only| Optional| Description| | -------- | -------- | -------- | -------- | -------- | | launchReason | [LaunchReason](#launchreason)| No| No| Ability launch reason, which is an enumerated type.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| launchReasonMessage16+ | string | No| Yes| Detailed message that describes the ability launch reason.
**Atomic service API**: This API can be used in atomic services since API version 16.| +| launchReasonMessage18+ | string | No| Yes| Detailed message that describes the ability launch reason.
**Atomic service API**: This API can be used in atomic services since API version 18.| | lastExitReason | [LastExitReason](#lastexitreason) | No| No| Reason for the last exit, which is an enumerated type.
**Atomic service API**: This API can be used in atomic services since API version 11.| | lastExitMessage12+ | string | No| No| Reason for the last exit.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| lastExitDetailInfo18+ | [LastExitDetailInfo](#lastexitdetailinfo18) | No| Yes| Detailed information about the last exit.
**Atomic service API**: This API can be used in atomic services since API version 18.| ## LaunchReason @@ -74,8 +75,10 @@ Enumerates the reasons for the last exit. You can use it together with the value | JS_ERROR10+ | 4 | The ability exits due to a JS_ERROR fault triggered when an application has a JS syntax error that is not captured by developers.
**Atomic service API**: This API can be used in atomic services since API version 11.| | APP_FREEZE10+ | 5 | The ability exits because watchdog detects that the application is frozen.
**Atomic service API**: This API can be used in atomic services since API version 11.| | PERFORMANCE_CONTROL10+ | 6 | The ability exits due to system performance problems, for example, insufficient device memory.
**Atomic service API**: This API can be used in atomic services since API version 11.
**NOTE**: This API will be deprecated. You are advised to use **RESOURCE_CONTROL** instead.| -| RESOURCE_CONTROL10+ | 7 | The ability exits due to improper use of system resources. The specific error cause can be obtained through [LaunchParam.lastExitMessage](#launchparam). The possible causes are as follows:
- **CPU Highload**: The CPU load is high.
- **CPU_EXT Highload**: A fast CPU load detection is carried out.
- **IO Manage Control**: An I/O management and control operation is carried out.
-** App Memory Deterioration**: The application memory usage exceeds the threshold.
- **Temperature Control**: The temperature is too high or too low.
- **Memory Pressure**: The system is low on memory, triggering ability exiting in ascending order of priority.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| RESOURCE_CONTROL10+ | 7 | The ability exits due to improper use of system resources. The specific error cause can be obtained through [LaunchParam.lastExitMessage](#launchparam). The possible causes are as follows:
- **CPU Highload**: The CPU load is high.
- **CPU_EXT Highload**: A fast CPU load detection is carried out.
- **IO Manage Control**: An I/O management and control operation is carried out.
- **App Memory Deterioration**: The application memory usage exceeds the threshold.
- **Temperature Control**: The temperature is too high or too low.
- **Memory Pressure**: The system is low on memory, triggering ability exiting in ascending order of priority.
**Atomic service API**: This API can be used in atomic services since API version 11.| | UPGRADE10+ | 8 | The ability exits due to an update.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| USER_REQUEST18+ | 9 | The ability exits because of an action in the multitasking center, for example, when users swipe up or hit the one-click clean button in the multitasking view.
**Atomic service API**: This API can be used in atomic services since API version 18.| +| SIGNAL18+ | 10 | The ability exits because it receives a kill signal from the system.
**Atomic service API**: This API can be used in atomic services since API version 18.| **Example** @@ -94,6 +97,47 @@ class MyAbility extends UIAbility { } ``` +## LastExitDetailInfo18+ + +Describes the detailed information about the last exit. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name| Type| Read-only| Optional| Description| +| -------- | -------- | -------- | -------- | -------- | +| pid | number | No| No| ID of the process where the ability is running when it exits last time.| +| processName | string | No| No| Name of the process.| +| uid | number | No| No| UID of the application.| +| exitSubReason | number | No| No| Specific reason for the last exit of the ability.| +| exitMsg | string | No| No| Reason why the process was killed.| +| rss | number | No| No| RSS value of the process.| +| pss | number | No| No| PSS value of the process.| +| timestamp | number | No| No| Exact time when the ability last exits.| + +**Example** + +```ts +import { UIAbility, Want, AbilityConstant } from '@kit.AbilityKit'; + +class MyAbility extends UIAbility { + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { + if (launchParam.lastExitDetailInfo) { + console.log('pid: ' + launchParam.lastExitDetailInfo.pid + + '\n processName: ' + launchParam.lastExitDetailInfo.processName + + '\n uid: ' + launchParam.lastExitDetailInfo.uid + + '\n exitSubReason: ' + launchParam.lastExitDetailInfo.exitSubReason + + '\n exitMsg: ' + launchParam.lastExitDetailInfo.exitMsg + + '\n rss: ' + launchParam.lastExitDetailInfo.rss + + '\n pss: ' + launchParam.lastExitDetailInfo.pss + + '\n timestamp: ' + launchParam.lastExitDetailInfo.timestamp + ); + } + } +} +``` + ## OnContinueResult Enumerates the ability continuation results. You can use it together with [onContinue(wantParam)](js-apis-app-ability-uiAbility.md#uiabilityoncontinue) of the UIAbility to complete different operations. @@ -271,9 +315,9 @@ class MyAbility extends UIAbility { } ``` -## CollaborateResult16+ +## CollaborateResult18+ -Enumerates the collaboration request results. This enum is used in multi-device collaboration scenarios to specify whether the target application accepts the collaboration request from the caller application. It is used in [onCollaborate(wantParam)](js-apis-app-ability-uiAbility.md#uiabilityoncollaborate) of the UIAbility. +Enumerates the collaboration request results. This enum is used in multi-device collaboration scenarios to specify whether the target application accepts the collaboration request from the caller application. It is used in [onCollaborate(wantParam)](js-apis-app-ability-uiAbility.md#uiabilityoncollaborate18) of the UIAbility. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -293,3 +337,29 @@ class MyAbility extends UIAbility { } } ``` + +## PrepareTermination15+ + +Enumerates the actions triggered when an application is closed by the user. It must be used together with [onPrepareTermination](js-apis-app-ability-abilityStage.md#abilitystageonpreparetermination15) or [onPrepareTerminationAsync](js-apis-app-ability-abilityStage.md#abilitystageonprepareterminationasync15) of [AbilityStage](js-apis-app-ability-abilityStage.md). + +**Atomic service API**: This API can be used in atomic services since API version 15. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name| Value| Description| +| ------------- | --------- | ----------- | +| TERMINATE_IMMEDIATELY | 0 | Executes the termination action immediately. This is the default behavior.| +| CANCEL | 1 | Cancels the termination action.| + +**Example** + +```ts +import { AbilityConstant, AbilityStage } from '@kit.AbilityKit'; + +class MyAbilityStage extends AbilityStage { + onPrepareTermination(): AbilityConstant.PrepareTermination { + console.info('MyAbilityStage.onPrepareTermination is called'); + return AbilityConstant.PrepareTermination.CANCEL; + } +} +``` diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-abilityLifecycleCallback.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-abilityLifecycleCallback.md index cf6abaad00ba610be3c31559af3f805ac37f7a2c..7770032f44e074d7a37cf7fafadc332de6e5133f 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-abilityLifecycleCallback.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-abilityLifecycleCallback.md @@ -18,7 +18,7 @@ import { AbilityLifecycleCallback } from '@kit.AbilityKit'; onAbilityCreate(ability: UIAbility): void -Called when an ability is created. +Called when the ability is created. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -122,7 +122,7 @@ See [Usage of AbilityLifecycleCallback](#usage-of-abilitylifecyclecallback). onAbilityDestroy(ability: UIAbility): void -Called when an ability is destroyed. +Called when the ability is destroyed. **Atomic service API**: This API can be used in atomic services since API version 11. diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-abilityManager-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-abilityManager-sys.md index 71acb2828f7a00396b6393cec2980d749b09a25c..0be5d007542088f8026d0d185ca3e1b0a0a5c05a 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-abilityManager-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-abilityManager-sys.md @@ -630,7 +630,7 @@ Registers an observer to listen for ability start or exit events. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. It is fixed at **'abilityForegroundState'**.| -| observer | [AbilityForegroundStateObserver](js-apis-inner-application-abilityForegroundStateObserver-sys) | Yes| Observer used to listen for ability start or exit events.| +| observer | [AbilityForegroundStateObserver](js-apis-inner-application-abilityForegroundStateObserver-sys.md) | Yes| Observer used to listen for ability start or exit events.| **Error codes** @@ -680,7 +680,7 @@ Unregisters the observer used to listen for ability start or exit events. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. It is fixed at **'abilityForegroundState'**.| -| observer | [AbilityForegroundStateObserver](js-apis-inner-application-abilityForegroundStateObserver-sys) | No| Observer used to listen for ability start or exit events. If this parameter is not set, all observers associated with the specified event are deregistered. If this parameter is set, only the specified observer is deregistered.| +| observer | [AbilityForegroundStateObserver](js-apis-inner-application-abilityForegroundStateObserver-sys.md) | No| Observer used to listen for ability start or exit events. If this parameter is not set, all observers associated with the specified event are deregistered. If this parameter is set, only the specified observer is deregistered.| **Error codes** @@ -868,7 +868,7 @@ export default class UiExtAbility extends UIExtensionAbility { } ``` -## abilityManager.isEmbeddedOpenAllowed12 +## abilityManager.isEmbeddedOpenAllowed12+ isEmbeddedOpenAllowed(context: Context, appId: string): Promise\ @@ -979,3 +979,72 @@ try { console.error(`setResidentProcessEnabled failed, code is ${code}, message is ${message}`); } ``` + +## AtomicServiceStartupRule18+ + +Describes the rule for launching an embedded atomic service. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name| Type| Read-Only| Optional| Description| +| -------- | ---------| ---- | ---- | --------- | +| isOpenAllowed | boolean | Yes | No | Whether launching the atomic service is allowed.| +| isEmbeddedAllowed | boolean | Yes | No | Whether launching the embedded atomic service is allowed. | + +## abilityManager.queryAtomicServiceStartupRule18+ + +queryAtomicServiceStartupRule(context: Context, appId: string): Promise\ + +Obtains the rule for launching an [EmbeddableUIAbility](js-apis-app-ability-embeddableUIAbility.md) in embedded mode. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------- | -------- | -------- | -------- | +| context | [Context](js-apis-inner-application-context.md) | Yes| Context of the caller.
**Note**: Currently, only [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) is supported.| +| appId | string | Yes| Unique ID of the application, which is allocated by the cloud.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\<[AtomicServiceStartupRule](#atomicservicestartuprule18)> | Promise used to return the rule for launching the embedded atomic service.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). + +| ID| Error Message| +| ------- | -------- | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | +| 801 | Capability not support. | +| 16000050 | Internal error. | + +**Example** + +```ts +import { abilityManager, UIAbility } from '@kit.AbilityKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +export default class EntryAbility extends UIAbility { + onForeground() { + let appId: string = '6918661953712445909'; + try { + abilityManager.queryAtomicServiceStartupRule(this.context, appId).then((data: abilityManager.AtomicServiceStartupRule) => { + console.info(`queryAtomicServiceStartupRule data: ${JSON.stringify(data)}`); + }).catch((err: BusinessError) => { + console.error(`queryAtomicServiceStartupRule failed, code is ${err.code}, message is ${err.message}`); + }); + } catch (err) { + // Process input parameter errors. + console.error(`param is invalid, code is ${err.code}, message is ${err.message}`); + } + } +} +``` diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-abilityManager.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-abilityManager.md index 7522f50da9bdb0fabba869c70d71c6b9dbf63084..987ad05fe604fee4f8ccc4f6a3109346381be670 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-abilityManager.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-abilityManager.md @@ -29,7 +29,7 @@ Enumerates the ability states. This enum can be used together with [AbilityRunni | BACKGROUNDING | 12 | The ability is in the state of being switched to the background. | -## getAbilityRunningInfos +## abilityManager.getAbilityRunningInfos getAbilityRunningInfos(): Promise\> @@ -47,7 +47,7 @@ Obtains the UIAbility running information. This API uses a promise to return the **Error codes** -For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). +For details about the error codes, see [Ability Error Codes](errorcode-ability.md). | ID| Error Message| | ------- | -------- | @@ -60,14 +60,16 @@ import { abilityManager } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; try { - abilityManager.getAbilityRunningInfos().then((data: Array) => { - console.log(`getAbilityRunningInfos success, data: ${JSON.stringify(data)}`); - }).catch((err: BusinessError) => { - console.error(`getAbilityRunningInfos fail, err: ${JSON.stringify(err)}`); - }); -} catch (paramError) { - let code: number = (paramError as BusinessError).code; - let message: string = (paramError as BusinessError).message; - console.error(`error.code: ${code}, error.message: ${message}`); + abilityManager.getAbilityRunningInfos() + .then((data: abilityManager.AbilityRunningInfo[]) => { + console.log(`getAbilityRunningInfos success, data: ${JSON.stringify(data)}`); + }) + .catch((error: BusinessError) => { + console.error(`getAbilityRunningInfos fail, error code: ${JSON.stringify(error.code)}, error msg: ${JSON.stringify(error.message)}`); + }) +} catch (e) { + let code = (e as BusinessError).code; + let msg = (e as BusinessError).message; + console.error(`getAbilityRunningInfos fail, error code: ${JSON.stringify(code)}, error msg: ${JSON.stringify(msg)}`); } ``` diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-abilityStage.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-abilityStage.md index 04f688ccde59717c92e4409eb5e780f3b799b5d7..572ed6538daf8c3b57c836466a1c672cd1a9666d 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-abilityStage.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-abilityStage.md @@ -16,11 +16,21 @@ import { AbilityStage } from '@kit.AbilityKit'; ``` +## Properties + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name| Type| Read-Only| Optional| Description| +| -------- | -------- | -------- | -------- | -------- | +| context | [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) | No| No| Context of an AbilityStage.| + ## AbilityStage.onCreate onCreate(): void -Called when the application is created. +Called when the application is created. This API returns the result synchronously and does not support asynchronous callbacks. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -43,7 +53,7 @@ class MyAbilityStage extends AbilityStage { onAcceptWant(want: Want): string -Called when a specified ability is started. +Called when a specified ability is started. This API returns the result synchronously and does not support asynchronous callbacks. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -78,7 +88,7 @@ class MyAbilityStage extends AbilityStage { onNewProcessRequest(want: Want): string -Called when the UIAbility is started in the specified process. +Called when the UIAbility is started in the specified process. This API returns the result synchronously and does not support asynchronous callbacks. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -112,7 +122,7 @@ class MyAbilityStage extends AbilityStage { onConfigurationUpdate(newConfig: Configuration): void -Called when the global configuration is updated. +Called when the global configuration is updated. This API returns the result synchronously and does not support asynchronous callbacks. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -140,7 +150,7 @@ class MyAbilityStage extends AbilityStage { onMemoryLevel(level: AbilityConstant.MemoryLevel): void -Called when the system has decided to adjust the memory level. For example, this API can be used when there is not enough memory to run as many background processes as possible. +Called when the system has decided to adjust the memory level. For example, this API can be used when there is not enough memory to run as many background processes as possible. This API returns the result synchronously and does not support asynchronous callbacks. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -194,7 +204,7 @@ export default class MyAbilityStage extends AbilityStage { onDestroy(): void -Called when the application is destroyed. This API is called during the normal lifecycle. If the application exits abnormally or is terminated, this API is not called. +Called when the application is destroyed. This API is called during the normal lifecycle. If the application exits abnormally or is terminated, this API is not called. This API returns the result synchronously and does not support asynchronous callbacks. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -211,3 +221,81 @@ class MyAbilityStage extends AbilityStage { } } ``` + +## AbilityStage.onPrepareTermination15+ + +onPrepareTermination(): AbilityConstant.PrepareTermination + +Called when the application is closed by the user, allowing the user to choose between immediate termination or cancellation. This API returns the result synchronously and does not support asynchronous callbacks. + +Currently, this API takes effect only on 2-in-1 devices. + +> **NOTE** +> +> - This API is called only when the application exits normally. It is not called if the application is forcibly closed. +> +> - This API is not executed when [AbilityStage.onPrepareTerminationAsync](#abilitystageonprepareterminationasync15) is implemented. + +**Required permissions**: ohos.permission.PREPARE_APP_TERMINATE + +**Atomic service API**: This API can be used in atomic services since API version 15. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type| Description| +| -------- | -------- | +| [AbilityConstant.PrepareTermination](js-apis-app-ability-abilityConstant.md#preparetermination15) | The user's choice.| + +**Example** + +```ts +import { AbilityConstant, AbilityStage } from '@kit.AbilityKit'; + +class MyAbilityStage extends AbilityStage { + onPrepareTermination(): AbilityConstant.PrepareTermination { + console.info('MyAbilityStage.onPrepareTermination is called'); + return AbilityConstant.PrepareTermination.CANCEL; + } +} +``` + +## AbilityStage.onPrepareTerminationAsync15+ + +onPrepareTerminationAsync(): Promise\ + +Called when the application is closed by the user, allowing the user to choose between immediate termination or cancellation. This API uses a promise to return the result. Currently, this API takes effect only on 2-in-1 devices. + +> **NOTE** +> +> - This API is called only when the application exits normally. It is not called if the application is forcibly closed. +> +> - If an asynchronous callback crashes, it will be handled as a timeout. If the application does not respond within 10 seconds, it will be terminated forcibly. + +**Required permissions**: ohos.permission.PREPARE_APP_TERMINATE + +**Atomic service API**: This API can be used in atomic services since API version 15. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\<[AbilityConstant.PrepareTermination](js-apis-app-ability-abilityConstant.md#preparetermination15)> | Promise used to return the user's choice.| + +**Example** + +```ts +import { AbilityConstant, AbilityStage } from '@kit.AbilityKit'; + +class MyAbilityStage extends AbilityStage { + async onPrepareTerminationAsync(): Promise { + await new Promise((res, rej) => { + setTimeout(res, 3000); // Execute the operation after 3 seconds. + }); + return AbilityConstant.PrepareTermination.CANCEL; + } +} +``` diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-actionExtensionAbility.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-actionExtensionAbility.md index c7f681511ed8e700252cdddf80c5191e9cc4d4aa..d49fbcfbc9fd4d95c08b4c04b29c462ad61ef731 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-actionExtensionAbility.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-actionExtensionAbility.md @@ -123,7 +123,7 @@ See [Creating an ActionExtensionAbility](#creating-an-actionextensionability). To manually create an ActionExtensionAbility in the DevEco Studio project, perform the following steps: -1. In the **ets** directory of a module in the project, right-click and choose **New > Directory** to create a directory named **ActionExtAbility**. +1. In the **ets** directory of a module in the project, right-click and choose **New > Directory** to create a directory named **actionextability**. 2. In the **actionextability** directory, right-click and choose **New > ArkTS File** to create a file named **ActionExtAbility.ets**. @@ -176,7 +176,7 @@ To manually create an ActionExtensionAbility in the DevEco Studio project, perfo ```json { "module": { - ... + // ... "extensionAbilities": [ { "name": "ActionExtAbility", diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-appManager-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-appManager-sys.md index d7e611d0f9e223b97784e1d19cb6ad1210f8a79b..9506b39bcc484c1702407ec4298ee6df0fab7673 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-appManager-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-appManager-sys.md @@ -1,6 +1,6 @@ # @ohos.app.ability.appManager (appManager) (System API) -The **appManager** module implements application management. You can use the APIs of this module to query whether the application is undergoing a stability test, whether the application is running on a RAM constrained device, the memory size of the application, and information about the running process. +The appManager module implements application management. You can use the APIs of this module to query whether the application is undergoing a stability test, whether the application is running on a RAM constrained device, the memory size of the application, and information about the running process. > **NOTE** > @@ -273,97 +273,6 @@ try { } ``` -## appManager.off('applicationState') - -off(type: 'applicationState', observerId: number, callback: AsyncCallback\): void - -Deregisters the application state observer. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the API to call. It is fixed at **'applicationState'**.| -| observerId | number | Yes| Digital code of the observer.| -| callback | AsyncCallback\ | Yes| Callback used to return the API call result. You can perform error handling or custom processing in this callback.| - -**Error codes** - -For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). - -| ID| Error Message| -| ------- | -------- | -| 201 | Permission denied. | -| 202 | Not System App. Interface caller is not a system app. | -| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | -| 16000050 | Internal error. | - -**Example** - -```ts -import { appManager } from '@kit.AbilityKit'; -import { BusinessError } from '@kit.BasicServicesKit'; - -let observerId = 0; - -let applicationStateObserver: appManager.ApplicationStateObserver = { - onForegroundApplicationChanged(appStateData) { - console.log(`[appManager] onForegroundApplicationChanged: ${JSON.stringify(appStateData)}`); - }, - onAbilityStateChanged(abilityStateData) { - console.log(`[appManager] onAbilityStateChanged: ${JSON.stringify(abilityStateData)}`); - }, - onProcessCreated(processData) { - console.log(`[appManager] onProcessCreated: ${JSON.stringify(processData)}`); - }, - onProcessDied(processData) { - console.log(`[appManager] onProcessDied: ${JSON.stringify(processData)}`); - }, - onProcessStateChanged(processData) { - console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`); - }, - onAppStarted(appStateData) { - console.log(`[appManager] onAppStarted: ${JSON.stringify(appStateData)}`); - }, - onAppStopped(appStateData) { - console.log(`[appManager] onAppStopped: ${JSON.stringify(appStateData)}`); - } -}; -let bundleNameList = ['bundleName1', 'bundleName2']; - -try { - observerId = appManager.on('applicationState', applicationStateObserver, bundleNameList); - console.log(`[appManager] observerCode: ${observerId}`); -} catch (paramError) { - let code = (paramError as BusinessError).code; - let message = (paramError as BusinessError).message; - console.error(`[appManager] error: ${code}, ${message} `); -} - -// 2. Deregister the application state observer. -function unregisterApplicationStateObserverCallback(err: BusinessError) { - if (err) { - console.error(`unregisterApplicationStateObserverCallback fail, err: ${JSON.stringify(err)}`); - } else { - console.log('unregisterApplicationStateObserverCallback success.'); - } -} - -try { - appManager.off('applicationState', observerId, unregisterApplicationStateObserverCallback); -} catch (paramError) { - let code = (paramError as BusinessError).code; - let message = (paramError as BusinessError).message; - console.error(`[appManager] error: ${code}, ${message}`); -} -``` - ## appManager.off('appForegroundState')11+ off(type: 'appForegroundState', observer?: AppForegroundStateObserver): void @@ -1598,7 +1507,7 @@ try { } ``` -## appManager.terminateMission12+ +## appManager.terminateMission13+ terminateMission(missionId: number): Promise\ diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-appManager.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-appManager.md index b2a379870e531f44a3131b4e5b8eb38ff2abe8d9..3b30bff816e6b0609418bb63ce89e0845424773b 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-appManager.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-appManager.md @@ -1,6 +1,6 @@ # @ohos.app.ability.appManager (appManager) -The **appManager** module implements application management. You can use the APIs of this module to query whether the application is undergoing a stability test, whether the application is running on a RAM constrained device, the memory size of the application, and information about the running process. +The appManager module implements application management. You can use the APIs of this module to query whether the application is undergoing a stability test, whether the application is running on a RAM constrained device, the memory size of the application, and information about the running process. > **NOTE** > @@ -262,11 +262,12 @@ appManager.getAppMemorySize((err, data) => { getRunningProcessInformation(): Promise\> -Obtains information about the running processes. This API uses a promise to return the result. +Obtains information about the running processes of this application. This API uses a promise to return the result. > **NOTE** > -> In versions earlier than API version 11, this API requires the **ohos.permission.GET_RUNNING_INFO** permission, which is available only for system applications. Since API version 11, no permission is required for calling this API. +> - In versions earlier than API version 11, this API requires the **ohos.permission.GET_RUNNING_INFO** permission, which is available only for system applications. +> - Since API version 11, this API is used only to obtain the process information of the caller. No permission is required. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -303,11 +304,12 @@ appManager.getRunningProcessInformation().then((data) => { getRunningProcessInformation(callback: AsyncCallback\>): void -Obtains information about the running processes. This API uses an asynchronous callback to return the result. +Obtains information about the running processes of this application. This API uses an asynchronous callback to return the result. > **NOTE** > -> In versions earlier than API version 11, this API requires the **ohos.permission.GET_RUNNING_INFO** permission, which is available only for system applications. Since API version 11, no permission is required for calling this API. +> - In versions earlier than API version 11, this API requires the **ohos.permission.GET_RUNNING_INFO** permission, which is available only for system applications. +> - Since API version 11, this API is used only to obtain the process information of the caller. No permission is required. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -495,7 +497,7 @@ try { off(type: 'applicationState', observerId: number): Promise\ -Deregisters the application state observer. +Deregisters the application state observer. This API uses a promise to return the result. **Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER @@ -580,13 +582,100 @@ try { } ``` +## appManager.off('applicationState')15+ + +off(type: 'applicationState', observerId: number, callback: AsyncCallback\): void + +Deregisters the application state observer. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the API to call. It is fixed at **'applicationState'**.| +| observerId | number | Yes| Digital code of the observer.| +| callback | AsyncCallback\ | Yes| Callback used to return the result. If the application state observer is deregistered, **err** is undefined; otherwise, **error** is an error object.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). + +| ID| Error Message| +| ------- | -------- | +| 201 | Permission denied. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | +| 16000050 | Internal error. | + +**Example** + +```ts +import { appManager } from '@kit.AbilityKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +let observerId = 0; + +// 1. Register an application state observer. +let applicationStateObserver: appManager.ApplicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log(`[appManager] onForegroundApplicationChanged: ${JSON.stringify(appStateData)}`); + }, + onAbilityStateChanged(abilityStateData) { + console.log(`[appManager] onAbilityStateChanged: ${JSON.stringify(abilityStateData)}`); + }, + onProcessCreated(processData) { + console.log(`[appManager] onProcessCreated: ${JSON.stringify(processData)}`); + }, + onProcessDied(processData) { + console.log(`[appManager] onProcessDied: ${JSON.stringify(processData)}`); + }, + onProcessStateChanged(processData) { + console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`); + }, + onAppStarted(appStateData) { + console.log(`[appManager] onAppStarted: ${JSON.stringify(appStateData)}`); + }, + onAppStopped(appStateData) { + console.log(`[appManager] onAppStopped: ${JSON.stringify(appStateData)}`); + } +}; +let bundleNameList = ['bundleName1', 'bundleName2']; + +try { + observerId = appManager.on('applicationState', applicationStateObserver, bundleNameList); +} catch (paramError) { + let code = (paramError as BusinessError).code; + let message = (paramError as BusinessError).message; + console.error(`[appManager] error: ${code}, ${message}`); +} + +// 2. Deregister the application state observer. +try { + function offCallback((err: BusinessError) => { + if (err) { + console.error(`appmanager.off failed, code: ${err.code}, msg: ${err.message}`); + } else { + console.info(`appmanager.off success.`); + } + }) + appManager.off('applicationState', observerId, offCallback); +} catch (paramError) { + let code = (paramError as BusinessError).code; + let message = (paramError as BusinessError).message; + console.error(`[appManager] error: ${code}, ${message}`); +} +``` + ## appManager.killProcessesByBundleName14+ killProcessesByBundleName(bundleName: string, clearPageStack: boolean, appIndex?: number): Promise\ Kills a process by bundle name. This API uses an asynchronous callback to return the result. This API uses a promise to return the result. -**Required permissions**: ohos.permission.CLEAN_BACKGROUND_PROCESSES +**Required permissions**: ohos.permission.KILL_APP_PROCESSES or ohos.permission.CLEAN_BACKGROUND_PROCESSES **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -611,7 +700,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message| | ------- | -------- | | 201 | Permission denied. | -| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | +| 401 | If the input parameter is not valid parameter. | | 16000050 | Internal error. | **Example** @@ -666,7 +755,7 @@ Checks whether an application is running. This API uses a promise to return the | ID| Error Message| | ------- | -------- | -| 201 | The application does not have permission to call the interface. | +| 201 | Permission denied. | | 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3.Parameter verification failed. | | 16000050 | Internal error. | | 16000073 | The app clone index is invalid. | @@ -689,3 +778,29 @@ try { hilog.error(0x0000, 'testTag', `isAppRunning error, code: ${err.code}, msg:${err.message}`); } ``` + +## ApplicationStateObserver14+ + +type ApplicationStateObserver = _ApplicationStateObserver.default + +Defines the ApplicationStateObserver module. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Type| Description| +| --- | --- | +| [_ApplicationStateObserver.default](js-apis-inner-application-applicationStateObserver.md) | ApplicationStateObserver module.| + +## ProcessInformation + +type ProcessInformation = _ProcessInformation + +Defines the ProcessInformation module. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Type| Description| +| --- | --- | +| [_ProcessInformation](js-apis-inner-application-processInformation.md) | ProcessInformation module.| diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-appRecovery.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-appRecovery.md index 5af4cc936040d09dc0c54d106e1aaa2adcf65852..66a4b9aa5fe40ec491428799c7a02de43a025f06 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-appRecovery.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-appRecovery.md @@ -1,6 +1,6 @@ # @ohos.app.ability.appRecovery (appRecovery) -The **appRecovery** module provides APIs for recovering faulty applications. +The appRecovery module provides APIs for recovering faulty applications. > **NOTE** > @@ -237,7 +237,7 @@ import { appRecovery, Want } from '@kit.AbilityKit'; @Component struct Index { build() { - Button ("Start to Recover Ability") + Button("Start to Recover Ability") .fontSize(40) .fontWeight(FontWeight.Bold) .onClick(()=> { diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-application-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-application-sys.md index 5cca70f76e1ca1ef12c499cfe042bf0c7e59eb1e..cf86caf19e9b4768be8aa976f99d5379c02b83e0 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-application-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-application-sys.md @@ -19,7 +19,7 @@ Creates the context for a module. > **NOTE** > -> Since API version 16, the context can obtain the [process name](js-apis-inner-application-context.md#properties) of the current application. The **processName** property in the context created by **createModuleContext** is the same as the **processName** property in the input parameter **Context**. The values of other properties are obtained based on the input parameters **Context**, **bundleName**, and **moduleName**. +> Since API version 18, the context can obtain the [process name](js-apis-inner-application-context.md#properties) of the current application. The **processName** property in the context created by **createModuleContext** is the same as the **processName** property in the input parameter **Context**. The values of other properties are obtained based on the input parameters **Context**, **bundleName**, and **moduleName**. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -54,7 +54,7 @@ For details about the error codes, see [Ability Error Codes](errorcode-ability.m **Example** ```ts -import { UIAbility, application} from '@kit.AbilityKit'; +import { UIAbility, application, common } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; export default class EntryAbility extends UIAbility { @@ -82,7 +82,7 @@ Creates the context for an application. > **NOTE** > -> Since API version 16, the context can obtain the [process name](js-apis-inner-application-context.md#properties) of the current application. The **processName** property in the context created by **createBundleContext** is the same as the **processName** property in the input parameter **Context**. The values of other properties are obtained based on the input parameters **Context**, **bundleName**, and **moduleName**. +> Since API version 18, the context can obtain the [process name](js-apis-inner-application-context.md#properties) of the current application. The **processName** property in the context created by **createBundleContext** is the same as the **processName** property in the input parameter **Context**. The values of other properties are obtained based on the input parameters **Context**, **bundleName**, and **moduleName**. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -117,7 +117,7 @@ For details about the error codes, see [Ability Error Codes](errorcode-ability.m **Example** ```ts -import { UIAbility, application} from '@kit.AbilityKit'; +import { UIAbility, application, common } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; export default class EntryAbility extends UIAbility { diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-applicationStateChangeCallback.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-applicationStateChangeCallback.md index d895e11c59c95805b267b6fb272d4b4b3d47a562..6deab716460195dbb633debf91adc4ce7a2d365d 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-applicationStateChangeCallback.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-applicationStateChangeCallback.md @@ -1,6 +1,6 @@ # @ohos.app.ability.ApplicationStateChangeCallback (ApplicationStateChangeCallback) -The **ApplicationStateChangeCallback** module provides callbacks for the application context to listen for application foreground/background state changes. +The ApplicationStateChangeCallback module provides callbacks for the application context to listen for application foreground/background state changes. > **NOTE** > diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-autoFillManager-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-autoFillManager-sys.md new file mode 100644 index 0000000000000000000000000000000000000000..8889ea3ceb2a59504e97e82c708b618a04ed768d --- /dev/null +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-autoFillManager-sys.md @@ -0,0 +1,211 @@ +# @ohos.app.ability.autoFillManager (autoFillManager) (System API) + +The autoFillManager module provides APIs for saving accounts and passwords. + +Unlike the system's auto-save feature that triggers during page transitions, this feature requires manual activation by the user. For example, the user must input their account and password on a website and click the **Save** button to initiate the saving process. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 11. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> The APIs of this module can be used only in the stage model. +> +> This topic describes only system APIs provided by the module. For details about its public APIs, see [@ohos.app.ability.autoFillManager (autoFillManager)](js-apis-app-ability-autoFillManager.md). + +## Modules to Import + +```ts +import { autoFillManager } from '@kit.AbilityKit'; +``` + +## ViewData + +type ViewData = _ViewData.default + +Defines the view data used for auto-fill. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Model restriction**: This API can be used only in the stage model. + +| Type| Description| +| --- | --- | +| [_ViewData.default](js-apis-inner-application-viewData-sys.md) | View data used for auto-fill.| + +## PageNodeInfo + +type PageNodeInfo = _PageNodeInfo.default + +Defines the page node information used for auto-fill. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Model restriction**: This API can be used only in the stage model. + +| Type| Description| +| --- | --- | +| [_PageNodeInfo.default](js-apis-inner-application-pageNodeInfo-sys.md) | Page node information used for auto-fill.| + +## FillRequest + +type FillRequest = _AutoFillRequest.FillRequest + +Defines the information about an auto-fill request. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Model restriction**: This API can be used only in the stage model. + +| Type| Description| +| --- | --- | +| [_AutoFillRequest.FillRequest](js-apis-inner-application-autoFillRequest-sys.md#fillrequest) | Information about an auto-fill request.| + +## SaveRequest + +type SaveRequest = _AutoFillRequest.SaveRequest + +Defines the information about an auto-save request. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Model restriction**: This API can be used only in the stage model. + +| Type| Description| +| --- | --- | +| [_AutoFillRequest.SaveRequest](js-apis-inner-application-autoFillRequest-sys.md#saverequest) | Information about an auto-save request.| + +## UpdateRequest12+ + +type UpdateRequest = _AutoFillRequest.UpdateRequest + +Defines the information about an auto-update request. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Model restriction**: This API can be used only in the stage model. + +| Type| Description| +| --- | --- | +| [_AutoFillRequest.UpdateRequest](js-apis-inner-application-autoFillRequest-sys.md#updaterequest12) | Information about an auto-update request.| + +## FillResponse + +type FillResponse = _AutoFillRequest.FillResponse + +Defines the information about the response to an auto-fill request. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Model restriction**: This API can be used only in the stage model. + +| Type| Description| +| --- | --- | +| [_AutoFillRequest.FillResponse](js-apis-inner-application-autoFillRequest-sys.md#fillresponse) | Information about the response to an auto-fill request.| + +## FillRequestCallback + +type FillRequestCallback = _AutoFillRequest.FillRequestCallback + +Defines the callback for an auto-fill request, which is used to automatically fill in or generate a password. The callback can be used to notify the client of the success or failure of the request. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Model restriction**: This API can be used only in the stage model. + +| Type| Description| +| --- | --- | +| [_AutoFillRequest.FillRequestCallback](js-apis-inner-application-autoFillRequest-sys.md#fillrequestcallback) | Callback for an auto-fill request, which is used to automatically fill in or generate a password. The callback can be used to notify the client of the success or failure of the request.| + +## SaveRequestCallback + +type SaveRequestCallback = _AutoFillRequest.SaveRequestCallback + +Defines the callback for an automatic or a manual saving request. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Model restriction**: This API can be used only in the stage model. + +| Type| Description| +| --- | --- | +| [_AutoFillRequest.SaveRequestCallback](js-apis-inner-application-autoFillRequest-sys.md#saverequestcallback) | Callback for an automatic or a manual saving request.| + +## CustomData13+ + +type CustomData = _CustomData.default + +Defines the custom data. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Model restriction**: This API can be used only in the stage model. + +| Type| Description| +| --- | --- | +| [_CustomData.default](js-apis-inner-application-customData-sys.md) | Custom data.| + +## AutoFillRect12+ + +type AutoFillRect = _AutoFillRect.default + +Defines the rectangle used for auto-fill. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Model restriction**: This API can be used only in the stage model. + +| Type| Description| +| --- | --- | +| [_AutoFillRect.default](js-apis-inner-application-autoFillRect-sys.md) | Rectangle used for auto-fill.| + +## AutoFillPopupConfig12+ + +type AutoFillPopupConfig = _AutoFillPopupConfig.default + +Defines the size and position information of an auto-fill pop-up. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Model restriction**: This API can be used only in the stage model. + +| Type| Description| +| --- | --- | +| [_AutoFillPopupConfig.default](js-apis-inner-application-autoFillPopupConfig-sys.md) | Size and position information of the auto-fill pop-up.| + +## PopupSize12+ + +type PopupSize = _AutoFillPopupConfig.PopupSize + +Defines the width and height of an auto-fill pop-up. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Model restriction**: This API can be used only in the stage model. + +| Type| Description| +| --- | --- | +| [_AutoFillPopupConfig.PopupSize](js-apis-inner-application-autoFillPopupConfig-sys.md#popupsize) | Width and height of the auto-fill pop-up.| diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-autoFillManager.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-autoFillManager.md index 36d741b04d4a9d0ed8105f957ce551eab325051b..226ba1b965b808c8964acffb66f6bd2a1e193bdb 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-autoFillManager.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-autoFillManager.md @@ -2,6 +2,8 @@ The autoFillManager module provides APIs for saving accounts and passwords. +Unlike the system's auto-save feature that triggers during page transitions, this feature requires manual activation by the user. For example, the user must input their account and password on a website and click the **Save** button to initiate the saving process. + > **NOTE** > > The initial APIs of this module are supported since API version 11. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -79,9 +81,9 @@ struct Index { > **NOTE** > -> In the example, the UiContext obtained from the AppStorage is obtained from the **OnWindowStageCreate** lifecycle of the EntryAbility (ability that starts the page) and stored in the AppStorage. For details, see [requestAutoSave](#requestautosave). +> In the example, the UiContext obtained from the AppStorage is obtained from the **OnWindowStageCreate** lifecycle of the EntryAbility (ability that starts the page) and stored in the AppStorage. For details, see [requestAutoSave](#autofillmanagerrequestautosave). -## requestAutoSave +## autoFillManager.requestAutoSave requestAutoSave(context: UIContext, callback?: AutoSaveCallback): void diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-autoStartupManager-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-autoStartupManager-sys.md index f7eb275b88005713a4c89caed2d16dbdf81235b2..f0d5bf9280e58cadffed2910b5b2752b9e4ddf05 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-autoStartupManager-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-autoStartupManager-sys.md @@ -1,6 +1,6 @@ # @ohos.app.ability.autoStartupManager (autoStartupManager) (System API) -The **autoStartupManager** module provides APIs for listening for auto-startup status changes of application components and setting application components to automatically start upon system boot. +The autoStartupManager module provides APIs for listening for auto-startup status changes of application components and setting application components to automatically start upon system boot. > **NOTE** > diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-childProcessManager.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-childProcessManager.md index 8144a46a70d0ba1a8d4cb7d5984782273081f82e..079a17947db666a7071be6822bd03d60c58f5a3c 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-childProcessManager.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-childProcessManager.md @@ -1,6 +1,6 @@ # @ohos.app.ability.childProcessManager (childProcessManager) -The **childProcessManager** module provides the child process management capability. Currently, it provides APIs to start a child process and is valid only for 2-in-1 devices and tables. +The childProcessManager module provides the child process management capability. Currently, it provides APIs to start a child process and is valid only for 2-in-1 devices and tablets. The created child process does not support the UI or the calling of context-related APIs. @@ -41,16 +41,16 @@ A PID is returned once the child process is created. However, this does not mean **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| srcEntry | string | Yes| Path of the source file of the child process relative to the root directory **src/main**. The source file can be stored only in the module of the entry type. For example, if the source file of a child process is **src/main/ets/process/DemoProcess.ets** in the entry module, then **srcEntry** is **./ets/process/DemoProcess.ets**.
In addition, ensure that the source file of the child process is referenced by other files to prevent it from being optimized by the build tool. (For details, see the sample code below.)| -| startMode | [StartMode](#startmode) | Yes| Start mode of the child process.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | srcEntry | string | Yes| Path of the source file of the child process relative to the root directory **src/main**. The source file can be stored only in the module of the entry type. For example, if the source file of a child process is **src/main/ets/process/DemoProcess.ets** in the entry module, then **srcEntry** is **./ets/process/DemoProcess.ets**.
In addition, ensure that the source file of the child process is referenced by other files to prevent it from being optimized by the build tool. (For details, see the sample code below.)| + | startMode | [StartMode](#startmode) | Yes| Start mode of the child process.| **Return value** -| Type| Description| -| -------- | -------- | -| Promise<number> | Promise used to return the PID of the child process.| + | Type| Description| + | -------- | -------- | + | Promise<number> | Promise used to return the PID of the child process.| **Error codes** @@ -110,11 +110,11 @@ A PID is returned once the child process is created. However, this does not mean **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| srcEntry | string | Yes| Path of the source file of the child process relative to the root directory **src/main**. The source file can be stored only in the module of the entry type. For example, if the source file of a child process is **src/main/ets/process/DemoProcess.ets** in the entry module, then **srcEntry** is **./ets/process/DemoProcess.ets**.
In addition, ensure that the source file of the child process is referenced by other files to prevent it from being optimized by the build tool. (For details, see the sample code below.)| -| startMode | [StartMode](#startmode) | Yes| Start mode of the child process.| -| callback | AsyncCallback<number> | Yes| Callback used to return the result. If the subprocess is started, **err** is **undefined** and **data** is the PID of the child process. Otherwise, **data** is an error object.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | srcEntry | string | Yes| Path of the source file of the child process relative to the root directory **src/main**. The source file can be stored only in the module of the entry type. For example, if the source file of a child process is **src/main/ets/process/DemoProcess.ets** in the entry module, then **srcEntry** is **./ets/process/DemoProcess.ets**.
In addition, ensure that the source file of the child process is referenced by other files to prevent it from being optimized by the build tool. (For details, see the sample code below.)| + | startMode | [StartMode](#startmode) | Yes| Start mode of the child process.| + | callback | AsyncCallback<number> | Yes| Callback used to return the result. If the subprocess is started, **err** is **undefined** and **data** is the PID of the child process. Otherwise, **data** is an error object.| **Error codes** @@ -177,17 +177,17 @@ The child process supports parameter transfer and asynchronous ArkTS API calls ( **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| srcEntry | string | Yes| Path of the source file of the child process relative to the root directory **src/main**. The source file cannot be stored in the module of the HAR type. The value consists of a module name, a slash (/), and a file path. For example, if the child process file is **src/main/ets/process/DemoProcess.ets** in module1, then **srcEntry** is **module1/./ets/process/DemoProcess.ets**.
In addition, ensure that the source file of the child process is referenced by other files to prevent it from being optimized by the build tool. (For details, see the sample code below.)| -| args | [ChildProcessArgs](js-apis-app-ability-childProcessArgs.md) | Yes| Parameters transferred to the child process.| -| options | [ChildProcessOptions](js-apis-app-ability-childProcessOptions.md) | No| Startup configuration of the child process.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | srcEntry | string | Yes| Path of the source file of the child process relative to the root directory **src/main**. The source file cannot be stored in the module of the HAR type. The value consists of a module name, a slash (/), and a file path. For example, if the child process file is **src/main/ets/process/DemoProcess.ets** in module1, then **srcEntry** is **module1/./ets/process/DemoProcess.ets**.
In addition, ensure that the source file of the child process is referenced by other files to prevent it from being optimized by the build tool. (For details, see the sample code below.)| + | args | [ChildProcessArgs](js-apis-app-ability-childProcessArgs.md) | Yes| Parameters transferred to the child process.| + | options | [ChildProcessOptions](js-apis-app-ability-childProcessOptions.md) | No| Startup configuration of the child process.| **Return value** -| Type| Description| -| -------- | -------- | -| Promise<number> | Promise used to return the PID of the child process.| + | Type| Description| + | -------- | -------- | + | Promise<number> | Promise used to return the PID of the child process.| **Error codes** @@ -263,7 +263,7 @@ startNativeChildProcess(entryPoint: string, args: ChildProcessArgs, options?: Ch Starts a native child process, loads the specified dynamic library file, and calls the entry function. This API uses a promise to return the result. -The child process does not inherit the resources of the main process. A PID is returned once the child process is created. However, this does not mean that the entry function is successfully called, which depends on the execution result of the entry function of the child process. This API cannot be called by a child process to create its child process. It cannot be called to create a child process in an ArkTS basic runtime environment. +The child process does not inherit the resources of the parent process. A PID is returned once the child process is created. However, this does not mean that the entry function is successfully called, which depends on the execution result of the entry function of the child process. This API cannot be called by a child process to create its child process. It cannot be called to create a child process in an ArkTS basic runtime environment. After the entry function is executed, the child process is automatically destroyed. After the main process is destroyed, the child processes are also destroyed. @@ -271,17 +271,17 @@ After the entry function is executed, the child process is automatically destroy **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| entryPoint | string | Yes| The symbol and entry function of the dynamic link library called in the child process are separated by a colon (:), for example, **libentry.so:Main**.| -| args | [ChildProcessArgs](js-apis-app-ability-childProcessArgs.md) | Yes| Parameters transferred to the child process.| -| options | [ChildProcessOptions](js-apis-app-ability-childProcessOptions.md) | No| Startup configuration of the child process.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | entryPoint | string | Yes| The symbol and entry function of the dynamic link library called in the child process are separated by a colon (:), for example, **libentry.so:Main**.| + | args | [ChildProcessArgs](js-apis-app-ability-childProcessArgs.md) | Yes| Parameters transferred to the child process.| + | options | [ChildProcessOptions](js-apis-app-ability-childProcessOptions.md) | No| Startup configuration of the child process.| **Return value** -| Type| Description| -| -------- | -------- | -| Promise<number> | Promise used to return the PID of the child process.| + | Type| Description| + | -------- | -------- | + | Promise<number> | Promise used to return the PID of the child process.| **Error codes** @@ -290,7 +290,7 @@ After the entry function is executed, the child process is automatically destroy | ID| Error Message| | ------- | -------- | | 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3.Parameter verification failed. | -| 801 | Capability not supported. Capability not supported. Failed to call the API due to limited device capabilities. | +| 801 | Capability not supported. Failed to call the API due to limited device capabilities. | | 16000050 | Internal error. | | 16000061 | Operation not supported. The API cannot be called in a child process. | | 16000062 | The number of child processes exceeds the upper limit. | @@ -358,5 +358,3 @@ try { console.error(`startChildProcess error, errorCode: ${err.code}, errorMsg:${err.message}`); } ``` - - \ No newline at end of file diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-common.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-common.md index d07836e4282aa448679269bad13c770af9d61f2a..e63894467cbb81a3a49e501fc062e6b74ea1eb35 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-common.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-common.md @@ -11,28 +11,285 @@ You can use this module to reference the ability public module class. ```ts import { common } from '@kit.AbilityKit'; ``` -## Properties - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name| Type| Read Only| Optional| Description | -| ---- | ---- | ---- | ---- | ---------- | -| UIAbilityContext | [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) | No | No | Level-2 module **UIAbilityContext**.
**Atomic service API**: This API can be used in atomic services since API version 11.
**Model restriction**: This API can be used only in the stage model. | -| AbilityStageContext | [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) | No | No | Level-2 module **AbilityStageContext**.
**Atomic service API**: This API can be used in atomic services since API version 11.
**Model restriction**: This API can be used only in the stage model.| -| ApplicationContext | [ApplicationContext](js-apis-inner-application-applicationContext.md) | No | No | Level-2 module **ApplicationContext**.
**Atomic service API**: This API can be used in atomic services since API version 11.
**Model restriction**: This API can be used only in the stage model.| -| BaseContext | [BaseContext](js-apis-inner-application-baseContext.md) | No | No | Level-2 module **BaseContext**.
**Atomic service API**: This API can be used in atomic services since API version 11.
**Model restriction**: This API can be used only in the stage model.| -| Context | [Context](js-apis-inner-application-context.md) | No | No | Level-2 module **Context**.
**Atomic service API**: This API can be used in atomic services since API version 11.
**Model restriction**: This API can be used only in the stage model.| -| ExtensionContext | [ExtensionContext](js-apis-inner-application-extensionContext.md) | No | No | Level-2 module **ExtensionContext**.
**Atomic service API**: This API can be used in atomic services since API version 11.
**Model restriction**: This API can be used only in the stage model.| -| FormExtensionContext | [FormExtensionContext](../apis-form-kit/js-apis-inner-application-formExtensionContext.md) | No | No | Level-2 module **FormExtensionContext**.
**Atomic service API**: This API can be used in atomic services since API version 11.
**Model restriction**: This API can be used only in the stage model.| -| VpnExtensionContext11+ | VpnExtensionContext | No | No | Level-2 module **VpnExtensionContext**.
**Model restriction**: This API can be used only in the stage model.| -| EventHub | [EventHub](js-apis-inner-application-eventHub.md) | No | No | Level-2 module **EventHub**.
**Atomic service API**: This API can be used in atomic services since API version 11.
**Model restriction**: This API can be used only in the stage model.| -| PacMap | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap) | No | No | Level-2 module **PacMap**.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| AbilityResult | [AbilityResult](js-apis-inner-ability-abilityResult.md) | No | No | Level-2 module **AbilityResult**.
**Atomic service API**: This API can be used in atomic services since API version 11.
**Model restriction**: This API can be used only in the stage model.| -| AbilityStartCallback11+ | [AbilityStartCallback](js-apis-inner-application-abilityStartCallback.md) | No | No | Level-2 module **AbilityStartCallback**.
**Atomic service API**: This API can be used in atomic services since API version 11.
**Model restriction**: This API can be used only in the stage model.| -| ConnectOptions | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | No | No | Level-2 module **ConnectOptions**.
**Model restriction**: This API can be used only in the stage model.| -| EmbeddableUIAbilityContext12+ | [EmbeddableUIAbilityContext](js-apis-inner-application-EmbeddableUIAbilityContext.md) | No | No | Level-2 module **EmbeddableUIAbilityContext**.
**Atomic service API**: This API can be used in atomic services since API version 12.
**Model restriction**: This API can be used only in the stage model.| -| UIServiceProxy 13+ | [UIServiceProxy ](js-apis-inner-application-uiserviceproxy.md) | No | No | Level-2 module **UIServiceProxy**.
**Atomic service API**: This API can be used in atomic services since API version 13.
**Model restriction**: This API can be used only in the stage model.| -| UIServiceExtensionConnectCallback 13+ | [UIServiceExtensionConnectCallback](js-apis-inner-application-uiServiceExtensionconnectcallback.md) | No | No | Level-2 module **UIServiceExtensionConnectCallback**.
**Atomic service API**: This API can be used in atomic services since API version 13.
**Model restriction**: This API can be used only in the stage model.| + +## UIAbilityContext + +type UIAbilityContext = _UIAbilityContext.default + +Defines the level-2 module UIAbilityContext. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Model restriction**: This API can be used only in the stage model. + +| Type| Description| +| --- | --- | +| [_UIAbilityContext.default](js-apis-inner-application-uiAbilityContext.md) | Level-2 module UIAbilityContext.| + +## AbilityStageContext + +type AbilityStageContext = _AbilityStageContext.default + +Defines the level-2 module AbilityStageContext. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Model restriction**: This API can be used only in the stage model. + +| Type| Description| +| --- | --- | +| [_AbilityStageContext.default](js-apis-inner-application-abilityStageContext.md) | Level-2 module AbilityStageContext.| + +## ApplicationContext + +type ApplicationContext = _ApplicationContext.default + +Defines the level-2 module ApplicationContext. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Model restriction**: This API can be used only in the stage model. + +| Type| Description| +| --- | --- | +| [_ApplicationContext.default](js-apis-inner-application-applicationContext.md) | Level-2 module ApplicationContext.| + +## BaseContext + +type BaseContext = _BaseContext.default + +Defines the level-2 module BaseContext. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Model restriction**: This API can be used only in the stage model. + +| Type| Description| +| --- | --- | +| [_BaseContext.default](js-apis-inner-application-baseContext.md) | Level-2 module BaseContext.| + +## Context + +type Context = _Context.default + +Defines the level-2 module Context. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Model restriction**: This API can be used only in the stage model. + +| Type| Description| +| --- | --- | +| [_Context.default](js-apis-inner-application-context.md) | Level-2 module Context.| + +## ExtensionContext + +type ExtensionContext = _ExtensionContext.default + +Defines the level-2 module ExtensionContext. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Model restriction**: This API can be used only in the stage model. + +| Type| Description| +| --- | --- | +| [_ExtensionContext.default](js-apis-inner-application-extensionContext.md) | Level-2 module ExtensionContext.| + +## FormExtensionContext + +type FormExtensionContext = _FormExtensionContext.default + +Defines the level-2 module FormExtensionContext. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Model restriction**: This API can be used only in the stage model. + +| Type| Description| +| --- | --- | +| [_FormExtensionContext.default](../apis-form-kit/js-apis-inner-application-formExtensionContext.md) | Level-2 module FormExtensionContext.| + +## VpnExtensionContext11+ + +type VpnExtensionContext = _VpnExtensionContext.default + +Defines the level-2 module VpnExtensionContext. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Model restriction**: This API can be used only in the stage model. + +| Type| Description| +| --- | --- | +| [_VpnExtensionContext.default](../apis-network-kit/js-apis-inner-application-VpnExtensionContext.md) | Level-2 module VpnExtensionContext.| + +## EventHub + +type EventHub = _EventHub.default + +Defines the level-2 module EventHub. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Model restriction**: This API can be used only in the stage model. + +| Type| Description| +| --- | --- | +| [_EventHub.default](js-apis-inner-application-eventHub.md) | Level-2 module EventHub.| + +## PacMap + +type PacMap = _PacMap + +Defines the level-2 module PacMap. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Type| Description| +| --- | --- | +| [_PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap) | Level-2 module PacMap.| + +## AbilityResult + +type AbilityResult = _AbilityResult + +Defines the level-2 module AbilityResult. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Model restriction**: This API can be used only in the stage model. + +| Type| Description| +| --- | --- | +| [_AbilityResult](js-apis-inner-ability-abilityResult.md) | Level-2 module AbilityResult.| + +## AbilityStartCallback11+ + +type AbilityStartCallback = _AbilityStartCallback + +Defines the level-2 module AbilityStartCallback. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Model restriction**: This API can be used only in the stage model. + +| Type| Description| +| --- | --- | +| [_AbilityStartCallback](js-apis-inner-application-abilityStartCallback.md) | Level-2 module AbilityStartCallback.| + +## ConnectOptions + +type ConnectOptions = _ConnectOptions + +Defines the level-2 module ConnectOptions. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Model restriction**: This API can be used only in the stage model. + +| Type| Description| +| --- | --- | +| [_ConnectOptions](js-apis-inner-ability-connectOptions.md) | Level-2 module ConnectOptions.| + +## UIExtensionContext10+ + +type UIExtensionContext = _UIExtensionContext.default + +Defines the level-2 module UIExtensionContext. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Model restriction**: This API can be used only in the stage model. + +| Type| Description| +| --- | --- | +| [_UIExtensionContext.default](js-apis-inner-application-uiExtensionContext.md) | Level-2 module UIExtensionContext.| + +## EmbeddableUIAbilityContext12+ + +type EmbeddableUIAbilityContext = _EmbeddableUIAbilityContext.default + +Defines the level-2 module EmbeddableUIAbilityContext. + +**Atomic service API**: This API can be used in atomic services since API version 12. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Model restriction**: This API can be used only in the stage model. + +| Type| Description| +| --- | --- | +| [_EmbeddableUIAbilityContext.default](js-apis-inner-application-EmbeddableUIAbilityContext.md) | Level-2 module EmbeddableUIAbilityContext.| + +## PhotoEditorExtensionContext12+ + +type PhotoEditorExtensionContext = _PhotoEditorExtensionContext.default + +Defines the level-2 module PhotoEditorExtensionContext. + +**System capability**: SystemCapability.Ability.AppExtension.PhotoEditorExtension + +**Model restriction**: This API can be used only in the stage model. + +| Type| Description| +| --- | --- | +| [_PhotoEditorExtensionContext.default](js-apis-app-ability-photoEditorExtensionContext.md) | Level-2 module PhotoEditorExtensionContext.| + +## UIServiceProxy14+ + +type UIServiceProxy = _UIServiceProxy.default + +Defines the level-2 module UIServiceProxy. + +**Atomic service API**: This API can be used in atomic services since API version 14. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Model restriction**: This API can be used only in the stage model. + +| Type| Description| +| --- | --- | +| [_UIServiceProxy.default](js-apis-inner-application-uiserviceproxy.md) | Level-2 module UIServiceProxy.| + +## UIServiceExtensionConnectCallback14+ + +type UIServiceExtensionConnectCallback = _UIServiceExtensionConnectCallback.default + +Defines the level-2 module UIServiceExtensionConnectCallback. + +**Atomic service API**: This API can be used in atomic services since API version 14. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Model restriction**: This API can be used only in the stage model. + +| Type| Description| +| --- | --- | +| [_UIServiceExtensionConnectCallback.default](js-apis-inner-application-uiServiceExtensionconnectcallback.md) | Level-2 module UIServiceExtensionConnectCallback.| + **Example** @@ -44,6 +301,7 @@ let abilityStageContext: common.AbilityStageContext; let applicationContext: common.ApplicationContext; let baseContext: common.BaseContext; let context: common.Context; +let uiExtensionContext: common.UIExtensionContext; let extensionContext: common.ExtensionContext; let formExtensionContext: common.FormExtensionContext; let vpnExtensionContext: common.VpnExtensionContext; @@ -53,6 +311,7 @@ let abilityResult: common.AbilityResult; let abilityStartCallback: common.AbilityStartCallback; let connectOptions: common.ConnectOptions; let embeddableUIAbilityContext: common.EmbeddableUIAbilityContext; +let photoEditorExtensionContext: common.PhotoEditorExtensionContext; let uiServiceProxy : common.UIServiceProxy; let uiServiceExtensionConnectCallback : common.UIServiceExtensionConnectCallback; ``` diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-configuration.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-configuration.md index c1dacc600e882d16bbf6dac9a69385965dc5b4d6..0846e100b01bf4685da52734b32e73582e4fe78e 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-configuration.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-configuration.md @@ -1,6 +1,6 @@ # @ohos.app.ability.Configuration (Configuration) -The **Configuration** module defines environment change information. **Configuration** is an interface definition and is used only for field declaration. +The Configuration module defines environment change information. **Configuration** is an interface definition and is used only for field declaration. > **NOTE** > @@ -24,7 +24,7 @@ import { Configuration } from '@kit.AbilityKit'; | screenDensity | [ConfigurationConstant.ScreenDensity](js-apis-app-ability-configurationConstant.md#screendensity) | No| Yes| Pixel density of the screen. The options are as follows:
- **SCREEN_DENSITY_NOT_SET**: The pixel density is not set.
- **SCREEN_DENSITY_SDPI**: 120.
- **SCREEN_DENSITY_MDPI**: 160.
- **SCREEN_DENSITY_LDPI**: 240.
- **SCREEN_DENSITY_XLDPI**: 320.
- **SCREEN_DENSITY_XXLDPI**: 480.
- **SCREEN_DENSITY_XXXLDPI**: 640.
**Atomic service API**: This API can be used in atomic services since API version 11.| | displayId | number | No| Yes| ID of the display where the application is located.
**Atomic service API**: This API can be used in atomic services since API version 11.| | hasPointerDevice | boolean | No| Yes| Whether a pointer device, such as a keyboard, mouse, or touchpad, is connected.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| fontId14+ | number | No| Yes| Unique ID of the current system font.
**Atomic service API**: This API can be used in atomic services since API version 14.| +| fontId14+ | string | No| Yes| Unique ID of the current system font.
**Atomic service API**: This API can be used in atomic services since API version 14.| | fontSizeScale12+ | number | No| Yes| Font size scale ratio. The value is a non-negative number. The default value is **1**.
**Atomic service API**: This API can be used in atomic services since API version 12.| | fontWeightScale12+ | number | No| Yes| Font weight scale ratio. The value is a non-negative number. The default value is **1**.
**Atomic service API**: This API can be used in atomic services since API version 12.| | mcc12+ | string | No | Yes| Mobile network code (MNC).
**Atomic service API**: This API can be used in atomic services since API version 12.| diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-contextConstant.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-contextConstant.md index 742ddddb930597f1d01cf78fa13562f3419409a8..26bdeaa723662d54221c3db8a74b52f28c4742dd 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-contextConstant.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-contextConstant.md @@ -31,7 +31,7 @@ Enumerates the data encryption levels. ## ProcessMode12+ -Enumerates the process modes. It takes effect only on tablets. +Enumerates the process modes. It takes effect only on 2-in-1 devices and tablets. As a property of [StartOptions](js-apis-app-ability-startOptions.md), **ProcessMode** takes effect only in [UIAbilityContext.startAbility](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability-1) and is used to specify the process mode of the target ability. @@ -83,7 +83,7 @@ As a property of [StartOptions](js-apis-app-ability-startOptions.md), **ProcessM ## StartupVisibility12+ -Enumerates the visibility statuses of an ability after it is started. It takes effect only on tablets. +Enumerates the visibility statuses of an ability after it is started. It takes effect only on 2-in-1 devices and tablets. As a property of [StartOptions](js-apis-app-ability-startOptions.md), **StartupVisibility** takes effect only in [UIAbilityContext.startAbility](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability-1) and specifies the visibility of the target ability after it is started. diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-continueManager.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-continueManager.md new file mode 100644 index 0000000000000000000000000000000000000000..932adb8c01b3e0d1f43385fa69e7bcd156b6ca29 --- /dev/null +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-continueManager.md @@ -0,0 +1,167 @@ +# @ohos.app.ability.continueManager (continueManager) + +The continueManager module provides capabilities for managing cross-device application migration. For example, it allows you to obtain the result of quickly launching the target application during the cross-device migration process. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 18. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```ts +import { continueManager } from '@kit.AbilityKit'; +``` + +## continueManager.on + +on(type: 'prepareContinue', context: Context, callback: AsyncCallback<ContinueResultInfo>): void + +Registers a callback to obtain the quick start result when an application is launched quickly. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> The quick start feature allows the application to start concurrently while the user triggers migration and waits for the migration data to return, reducing wait time. To enable the quick start feature, add the suffix **_ContinueQuickStart** to the **continueType** value in the [module.json5 file](../../quick-start/module-configuration-file.md) of the source application. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**Parameters** + + | Name| Type | Mandatory| Description | + | -------- |-------------------------------------------------------------------------------------------------| -------- |------------------------------------------| + | type | string | Yes| The value is fixed at **prepareContinue**. | + | context | [Context](../apis-ability-kit/js-apis-inner-application-baseContext.md) | Yes| Context of the ability. | + | callback | AsyncCallback<[ContinueResultInfo](js-apis-app-ability-continueManager.md#continueresultinfo)> | Yes| Callback used to return the result. If obtaining the quick start result is successful, **err** is undefined, and **ContinueResultInfo** is the obtained quick startup result. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Distributed Scheduler Error Codes](errorcode-DistributedSchedule.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | +| 16300501 | the system ability work abnormally. | + +**Example** + + ```ts +import { AbilityConstant, UIAbility, Want, continueManager } from '@kit.AbilityKit'; +import { hilog } from '@kit.PerformanceAnalysisKit'; + +const TAG: string = '[MigrationAbility]'; +const DOMAIN_NUMBER: number = 0xFF00; + +export default class MigrationAbility extends UIAbility { + storage : LocalStorage = new LocalStorage(); + + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { + hilog.info(DOMAIN_NUMBER, TAG, '%{public}s', 'Ability onCreate'); + + // 1. Quick start is configured. Trigger the lifecycle callback when the application is launched immediately. + if (launchParam.launchReason === AbilityConstant.LaunchReason.PREPARE_CONTINUATION) { + // Register the callback to obtain the quick start result. + try { + continueManager.on("prepareContinue", this.context, (err, continueResultInfo) => { + if (err.code != 0) { + console.error('register failed, cause: ' + JSON.stringify(err)); + return; + } + console.info('register finished, ' + JSON.stringify(continueResultInfo)); + }); + } catch (e) { + console.error('register failed, cause: ' + JSON.stringify(e)); + } + // If the application data to migrate is large, add a loading screen here (for example, displaying "loading" on the screen). + // Handle issues related to custom redirection and timing. + // ... + } + } +} + ``` + +## continueManager.off + +off(type: 'prepareContinue', context: Context, callback: AsyncCallback<ContinueResultInfo>): void + +Unregisters the callback used to obtain the quick start result when an application is launched quickly. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> The quick start feature allows the application to start concurrently while the user triggers migration and waits for the migration data to return, reducing wait time. To enable the quick start feature, add the suffix **_ContinueQuickStart** to the **continueType** value in the [module.json5 file](../../quick-start/module-configuration-file.md) of the source application. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**Parameters** + +| Name| Type | Mandatory| Description | + | -------- |------------------------------------| -------- |--------------------------------------| +| type | string | Yes| The value is fixed at **prepareContinue**. | +| context | [Context](../apis-ability-kit/js-apis-inner-application-baseContext.md) | Yes| Context of the ability. | +| callback | AsyncCallback<[ContinueResultInfo](js-apis-app-ability-continueManager.md#continueresultinfo)> | Yes| Callback used to return the result. If the callback is unregistered, **err** is undefined, and **ContinueResultInfo** is the callback unregistration result. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Distributed Scheduler Error Codes](errorcode-DistributedSchedule.md). + +| ID | Error Message| +|----------| -------------------------------- | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | +| 16300501 | the system ability work abnormally. | + +**Example** + + ```ts +import { AbilityConstant, UIAbility, Want, continueManager } from '@kit.AbilityKit'; +import { hilog } from '@kit.PerformanceAnalysisKit'; + +const TAG: string = '[MigrationAbility]'; +const DOMAIN_NUMBER: number = 0xFF00; + +export default class MigrationAbility extends UIAbility { + storage : LocalStorage = new LocalStorage(); + + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { + hilog.info(DOMAIN_NUMBER, TAG, '%{public}s', 'Ability onCreate'); + + // 1. Quick start is configured. Trigger the lifecycle callback when the application is launched immediately. + if (launchParam.launchReason === AbilityConstant.LaunchReason.PREPARE_CONTINUATION) { + // Unregister the callback used to obtain the quick start result. + try { + continueManager.off("prepareContinue", this.context, (err, continueResultInfo) => { + if (err.code != 0) { + console.error('unregister failed, cause: ' + JSON.stringify(err)); + return; + } + console.info('unregister finished, ' + JSON.stringify(continueResultInfo)); + }); + } catch (e) { + console.error('unregister failed, cause: ' + JSON.stringify(e)); + } + // If the application data to migrate is large, add a loading screen here (for example, displaying "loading" on the screen). + // Handle issues related to custom redirection and timing. + // ... + } + } +} + ``` + +## ContinueResultInfo + +Describes the quick start result returned by the callback. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +| Name| Type | Read-Only| Optional| Description | +| -------- |-------------------------------------------------------------------------------|----|----|----------| +| resultState | [ContinueStateCode](js-apis-app-ability-continueManager.md#continuestatecode) | Yes | No | Status code of the operation result.| +| resultInfo | string | No | Yes | Description of the operation result.| + +## ContinueStateCode + +Enumerates the status codes of the quick start result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +| Name| Value | Description | +| -------- |----|-------| +| SUCCESS | 0 | Operation succeeded.| +| SYSTEM_ERROR | Others| Operation failed.| diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-environmentCallback.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-environmentCallback.md index 8ccc5b9b3190343bc3aae25ade09d3d77fcf01c9..a275dbbae3bb177470f51c5804cfc7743eea53f2 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-environmentCallback.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-environmentCallback.md @@ -1,6 +1,6 @@ # @ohos.app.ability.EnvironmentCallback (EnvironmentCallback) -The **EnvironmentCallback** module provides APIs for the application context to listen for system environment changes. +The EnvironmentCallback module provides APIs for the application context to listen for system environment changes. > **NOTE** > diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-errorManager.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-errorManager.md index 3a6e37902492d1e461f10c2a27583dc9ce28f8c2..0c321546948d99624a21b57414ef0057431fcae1 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-errorManager.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-errorManager.md @@ -78,13 +78,13 @@ try { } ``` -## errorManager.on('globalErrorOccurred')16+ +## errorManager.on('globalErrorOccurred')18+ on(type: 'globalErrorOccurred', observer: GlobalObserver): void Registers a global error observer with any thread in the process to capture exceptions in other child threads (such as TaskPool threads). When the application breaks down, the process does not exit. You are advised to add the synchronous exit operation after the callback function is executed. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -93,13 +93,7 @@ Registers a global error observer with any thread in the process to capture exce | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. It is fixed at **'globalErrorOccurred'**.| -| observer | [GlobalObserver](js-apis-inner-application-GlobalObserver.md) | Yes| Customized callback function for exception handling.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| void | No value is returned.| +| observer | [GlobalObserver](#globalobserver18) | Yes| Customized callback function for exception handling.| **Error codes** @@ -108,7 +102,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message| | ------- | -------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3. Parameter verification failed. | -| 16000003 | The specified ID does not exist. | +| 16200001 | If the caller is invalid. | **Example** @@ -133,13 +127,13 @@ try { } ``` -## errorManager.off('globalErrorOccurred')16+ +## errorManager.off('globalErrorOccurred')18+ off(type: 'globalErrorOccurred', observer?: GlobalObserver): void Unregisters a global error observer. After the deregistration, global listening cannot be implemented. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -148,13 +142,7 @@ Unregisters a global error observer. After the deregistration, global listening | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. It is fixed at **'globalErrorOccurred'**.| -| observer | [GlobalObserver](js-apis-inner-application-GlobalObserver.md) | Yes| Callback registered by the **on** API.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| void | No value is returned.| +| observer | [GlobalObserver](#globalobserver18) | No| Callback registered by the **on** API.| **Error codes** @@ -163,7 +151,8 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message| | ------- | -------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameter types; 3. Parameter verification failed. | -| 16000003 | The specified ID does not exist. | +| 16200001 | If the caller is invalid. | +| 16300004 | If the observer does not exist | **Example** @@ -333,13 +322,13 @@ let observer: errorManager.LoopObserver = { errorManager.on("loopObserver", 1, observer); ``` -## errorManager.on('globalUnhandledRejectionDetected')16+ +## errorManager.on('globalUnhandledRejectionDetected')18+ on(type: 'globalUnhandledRejectionDetected', observer: GlobalObserver): void Registers a rejected promise observer with any thread in the process. After the registration, a rejected promise that is not captured in the current thread of the application can be captured. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -348,7 +337,7 @@ Registers a rejected promise observer with any thread in the process. After the | Name | Type | Mandatory| Description | |-----------------------|-------------------------------------------------------------| -------- |------------------------------------------| | type | string | Yes| Event type. It is fixed at **'globalUnhandledRejectionDetected'**, indicating an observer for the promise rejection.| -| observer | [GlobalObserver](js-apis-inner-application-GlobalObserver.md) | Yes| Callback to register. | +| observer | [GlobalObserver](#globalobserver18) | Yes| Callback to register. | **Error codes** @@ -431,6 +420,46 @@ let promise1 = new Promise(() => {}).then(() => { throw new Error("uncaught error"); }); ``` +## errorManager.on('freeze')18+ + +on(type: 'freeze', observer: FreezeObserver): void + +Registers an observer for the main thread freeze event of the application. This API can be called only in the main thread. A new observer will overwrite the previous one. + +> **NOTE** +> +> If the callback function runs for more than 1 second, the [AppRecovery](./js-apis-app-ability-appRecovery.md) feature may not work. The execution duration can be calculated by parsing the time difference between **begin** and **Freeze callback execution completed** in HiLogs. If the execution duration exceeds 1 second, you can optimize the callback logic by using methods such as asynchronous processing, reducing operations that block other tasks, and optimizing the data structures to reduce the execution duration. +> + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. It is fixed at **'freeze'**, indicating an observer for the freeze event of the main thread.| +| observer | [FreezeObserver](#freezeobserver18) | Yes| Observer to register.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| ------- | -------- | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | + +**Example** + +```ts +import { errorManager } from '@kit.AbilityKit'; + +function freezeCallback() { + console.log("freezecallback"); +} +errorManager.on("freeze", freezeCallback); +``` ## errorManager.off('loopObserver')12+ @@ -465,13 +494,13 @@ import { errorManager } from '@kit.AbilityKit'; errorManager.off("loopObserver"); ``` -## errorManager.off('globalUnhandledRejectionDetected')16+ +## errorManager.off('globalUnhandledRejectionDetected')18+ off(type: 'globalUnhandledRejectionDetected', observer?: GlobalObserver): void Unregisters a rejected promise observer. After the deregistration, promise exceptions in the process cannot be listened for. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -480,7 +509,7 @@ Unregisters a rejected promise observer. After the deregistration, promise excep | Name | Type | Mandatory| Description | |-----------------------|---------------------------------|----|----------------------------------------------| | type | string | Yes | Event type. It is fixed at **'globalUnhandledRejectionDetected'**, indicating an observer for the promise rejection.| -| observer | [GlobalObserver](js-apis-inner-application-GlobalObserver.md) | Yes | Callback registered by the **on** API. | +| observer | [GlobalObserver](#globalobserver18) | No | Callback registered by the **on** API. | **Error codes** @@ -492,8 +521,6 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 16200001 | If the caller is invalid. | | 16300004 | If the observer does not exist. | -For details about the error codes, see [Ability Error Codes](errorcode-ability.md). - **Example** ```ts @@ -547,8 +574,6 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 16200001 | If the caller is invalid. | | 16300004 | If the observer does not exist. | -For details about the error codes, see [Ability Error Codes](errorcode-ability.md). - **Example** ```ts @@ -597,6 +622,72 @@ let promise1 = new Promise(() => {}).then(() => { errorManager.off("unhandledRejection", observer); ``` +## errorManager.off('freeze')18+ + +off(type: 'freeze', observer?: FreezeObserver): void + +Unregisters an observer for the main thread freeze event of the application. This API can be called only in the main thread. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. It is fixed at **'freeze'**, indicating an observer for the freeze event of the main thread.| +| observer | [FreezeObserver](#freezeobserver18) | No| Observer to unregister. If this parameter is not specified, the subscriptions to the specified event with all the callbacks are canceled.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). + +| ID| Error Message| +| ------- | -------- | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.| +| 16300004 | If the observer does not exist. | + +**Example** + +```ts +import { errorManager } from '@kit.AbilityKit'; + +function freezeCallback() { + console.log("freezecallback"); +} +errorManager.on("freeze", freezeCallback); +errorManager.off("freeze", freezeCallback); +``` + +## ErrorObserver + +type ErrorObserver = _ErrorObserver.default + +Defines the ErrorObserver module. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Type| Description| +| --- | --- | +| [_ErrorObserver.default](js-apis-inner-application-errorObserver.md) | ErrorObserver module.| + +## LoopObserver12+ + +type LoopObserver = _LoopObserver + +Defines the LoopObserver module. + +**Atomic service API**: This API can be used in atomic services since API version 12. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Type| Description| +| --- | --- | +| [_LoopObserver](js-apis-inner-application-loopObserver.md) | LoopObserver module.| + ## UnhandledRejectionObserver12+ type UnhandledRejectionObserver = (reason: Error | any, promise: Promise\) => void @@ -613,3 +704,58 @@ Defines an observer to capture the cause of a rejected promise. |--------|---------------|---| -------- | | reason | Error \| any | Yes| Generally, the value is of the **Error** type, indicating the reason for rejection.| | promise | Promise\ | Yes| Rejected promise.| + +## FreezeObserver18+ + +type FreezeObserver = () => void + +Defines an observer for the main thread freeze event of the application. It is used by the application to customize freeze information. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +## GlobalObserver18+ + +type GlobalObserver = (reason: GlobalError) => void + +Defines an exception observer, which can be used as the input parameter of [errorManager.on('globalErrorOccurred')](#errormanageronglobalerroroccurred18) and [errorManager.on('globalUnhandledRejectionDetected')](#errormanageronglobalunhandledrejectiondetected18) to listen for event processing events of the main thread of the current application. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description| +|--------| ------------- | ---- | --- | +| reason | [GlobalError](#globalerror18) | Yes | Object related to the exception event name, message, error stack information, exception thread name, and exception thread type.| + + +## GlobalError18+ + +Describes the object related to the exception event name, message, error stack information, exception thread name, and exception thread type. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Type | Read Only | Optional | Description | +| ---- | ----- | ---- | ----- | ------ | +| instanceName | string | No| No| Name of a VM instance.| +| instanceType | [InstanceType](#instancetype18) | No| No| Type of the VM instance.| + +## InstanceType18+ + +Enumerates the VM instance types. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value | Description | +| ---- | --- | ------ | +| MAIN | 0 | Main VM instance.| +| WORKER | 1 | Worker VM instance.| +| TASKPOOL | 2 | TaskPool VM instance.| +| CUSTOM | 3 | VM instance created from the local code using [napi_create_ark_runtime](../native-lib/napi.md#napi_create_ark_runtime).| diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-insightIntent.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-insightIntent.md index d001509491309b3702b56c0bcc9db7292d7428d9..1bb5321eae3a7b6d9a94f3d524f427f4419287cc 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-insightIntent.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-insightIntent.md @@ -30,13 +30,11 @@ Enumerates the InsightIntent call execution modes. Defines the InsightIntent call execution result. -**Atomic service API**: This API can be used in atomic services since API version 11. - **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name| Type| Read-only| Optional| Description| | -------- | -------- | -------- | -------- | -------- | -| code | number | No| No| Error code returned.| -| result | Record | No| Yes| Execution result returned.| -| uris16+ | Array<string> | No| Yes| List of URIs authorized by the InsightIntent executor to the InsightIntent caller during the call.| -| flags16+ | number | No| Yes| [Flags](js-apis-app-ability-wantConstant.md#flags) of the URIs authorized by the InsightIntent executor to the InsightIntent caller during the call.
**NOTE**
This parameter supports only **FLAG_AUTH_READ_URI_PERMISSION** and **FLAG_AUTH_WRITE_URI_PERMISSION**.| +| code | number | No| No| Error code returned.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| result | Record | No| Yes| Execution result returned.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| uris18+ | Array<string> | No| Yes| List of URIs authorized by the InsightIntent executor to the InsightIntent caller during the call.
**Atomic service API**: This API can be used in atomic services since API version 18.| +| flags18+ | number | No| Yes| [Flags](js-apis-app-ability-wantConstant.md#flags) of the URIs authorized by the InsightIntent executor to the InsightIntent caller during the call.
**Atomic service API**: This API can be used in atomic services since API version 18.
**NOTE**
This parameter supports only **FLAG_AUTH_READ_URI_PERMISSION**, **FLAG_AUTH_WRITE_URI_PERMISSION**, and FLAG_AUTH_READ_URI_PERMISSION\|FLAG_AUTH_WRITE_URI_PERMISSION.| diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-insightIntentContext.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-insightIntentContext.md index 069c62b1dfc40b075a468b07d78eab2bb3601b00..ec8699286a7d5ec01fd4a42795d2df86c947272d 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-insightIntentContext.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-insightIntentContext.md @@ -53,7 +53,6 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 16000053 | The ability is not on the top of the UI. | | 16000055 | Installation-free timed out. | | 16000061 | Operation not supported. | -| 16000082 | The UIAbility is being started. | | 16200001 | The caller has been released. | For details about the error codes, see [Ability Error Codes](errorcode-ability.md). @@ -140,7 +139,6 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 16000053 | The ability is not on the top of the UI. | | 16000055 | Installation-free timed out. | | 16000061 | Operation not supported. | -| 16000082 | The UIAbility is being started. | | 16200001 | The caller has been released. | For details about the error codes, see [Ability Error Codes](errorcode-ability.md). diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-insightIntentDriver-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-insightIntentDriver-sys.md index 398e6cffb5531013f51f3300f9706b2f7e8cc97a..78bc6cbe5af354f8af4c545e8564242cf59a2b18 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-insightIntentDriver-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-insightIntentDriver-sys.md @@ -22,7 +22,7 @@ Defines the parameter used to execute an InsightIntent call. **Model restriction**: This API can be used only in the stage model. -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -35,8 +35,8 @@ Defines the parameter used to execute an InsightIntent call. | insightIntentParam | string | Yes| InsightIntent call parameter.| | executeMode | [insightIntent.ExecuteMode](js-apis-app-ability-insightIntent.md#executemode) | Yes| InsightIntent call execution mode.| | displayId12+ | number | No| Physical screen ID specified during InsightIntent call. The value must be an integer. This parameter is valid only when **executeMode** is set to **UI_ABILITY_FOREGROUND**.| -| uris16+ | Array<string> | No| List of URIs authorized by the InsightIntent caller to the InsightIntent executor during the call.| -| flags16+ | number | No| [Flags](js-apis-app-ability-wantConstant.md#flags) of the URIs authorized by the InsightIntent caller to the InsightIntent executor during the call.
**NOTE**
This parameter supports only **FLAG_AUTH_READ_URI_PERMISSION** and **FLAG_AUTH_WRITE_URI_PERMISSION**.| +| uris18+ | Array<string> | No| List of URIs authorized by the InsightIntent caller to the InsightIntent executor during the call.| +| flags18+ | number | No| [Flags](js-apis-app-ability-wantConstant.md#flags) of the URIs authorized by the InsightIntent caller to the InsightIntent executor during the call.
**NOTE**
This parameter supports only **FLAG_AUTH_READ_URI_PERMISSION**, **FLAG_AUTH_WRITE_URI_PERMISSION**, and FLAG_AUTH_READ_URI_PERMISSION\||FLAG_AUTH_WRITE_URI_PERMISSION.| ## insightIntentDriver.execute @@ -50,7 +50,7 @@ When [ExecuteMode](js-apis-app-ability-insightIntent.md#executemode) of the Insi **Model restriction**: This API can be used only in the stage model. -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Required permissions**: ohos.permission.EXECUTE_INSIGHT_INTENT @@ -133,7 +133,7 @@ When [ExecuteMode](js-apis-app-ability-insightIntent.md#executemode) of the Insi **Model restriction**: This API can be used only in the stage model. -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Required permissions**: ohos.permission.EXECUTE_INSIGHT_INTENT diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-insightIntentExecutor.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-insightIntentExecutor.md index 4bc039b8fef09ea3dda4c526bbd4dc7289262991..9049ff00d4e75ae91460b8e4b30ad811d18d9cfa 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-insightIntentExecutor.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-insightIntentExecutor.md @@ -1,6 +1,6 @@ # @ohos.app.ability.InsightIntentExecutor (Base Class for InsightIntent Call Execution) -The **InsightIntentExecutor** module provides the base class for InsightIntent call execution. Through this base class, you can access the InsightIntent framework on the device side. You need to implement the service logic to respond to InsightIntent calls. To access the InsightIntent framework, you need to declare the InsightIntent name and InsightIntent access mode in the InsightIntent configuration file. The system calls the InsightIntent based on the user interaction and InsightIntent configuration file and triggers the corresponding InsightIntent call execution callback. +The InsightIntentExecutor module provides the base class for InsightIntent call execution. Through this base class, you can access the InsightIntent framework on the device side. You need to implement the service logic to respond to InsightIntent calls. To access the InsightIntent framework, you need to declare the InsightIntent name and InsightIntent access mode in the InsightIntent configuration file. The system calls the InsightIntent based on the user interaction and InsightIntent configuration file and triggers the corresponding InsightIntent call execution callback. > **NOTE** > diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-missionManager-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-missionManager-sys.md index d89d79737ce8ea794736331b65b846ff01fc03f7..8e12584d8aca251b961eff8d030e012110674941 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-missionManager-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-missionManager-sys.md @@ -28,7 +28,7 @@ Registers a listener to observe the mission status. **System capability**: SystemCapability.Ability.AbilityRuntime.Mission -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -130,7 +130,7 @@ Deregisters a mission status listener. **System capability**: SystemCapability.Ability.AbilityRuntime.Mission -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -228,7 +228,7 @@ Deregisters a mission status listener. This API uses a promise to return the res **System capability**: SystemCapability.Ability.AbilityRuntime.Mission -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -330,7 +330,7 @@ Obtains the information about a given mission. This API uses an asynchronous cal **System capability**: SystemCapability.Ability.AbilityRuntime.Mission -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -396,7 +396,7 @@ Obtains the information about a given mission. This API uses a promise to return **System capability**: SystemCapability.Ability.AbilityRuntime.Mission -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -451,7 +451,7 @@ Obtains information about all missions. This API uses an asynchronous callback t **System capability**: SystemCapability.Ability.AbilityRuntime.Mission -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -504,7 +504,7 @@ Obtains information about all missions. This API uses a promise to return the re **System capability**: SystemCapability.Ability.AbilityRuntime.Mission -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -557,7 +557,7 @@ Obtains the snapshot of a given mission. This API uses an asynchronous callback **System capability**: SystemCapability.Ability.AbilityRuntime.Mission -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -608,7 +608,7 @@ Obtains the snapshot of a given mission. This API uses a promise to return the r **System capability**: SystemCapability.Ability.AbilityRuntime.Mission -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -662,7 +662,7 @@ Obtains the low-resolution snapshot of a given mission. This API uses an asynchr **System capability**: SystemCapability.Ability.AbilityRuntime.Mission -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -713,7 +713,7 @@ Obtains the low-resolution snapshot of a given mission. This API uses a promise **System capability**: SystemCapability.Ability.AbilityRuntime.Mission -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -769,7 +769,7 @@ Locks a given mission. This API uses an asynchronous callback to return the resu **System capability**: SystemCapability.Ability.AbilityRuntime.Mission -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -821,7 +821,7 @@ Locks a given mission. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Mission -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -875,7 +875,7 @@ Unlocks a given mission. This API uses an asynchronous callback to return the re **System capability**: SystemCapability.Ability.AbilityRuntime.Mission -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -926,7 +926,7 @@ Unlocks a given mission. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Mission -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -981,7 +981,7 @@ Clears a given mission, regardless of whether it is locked. This API uses an asy **System capability**: SystemCapability.Ability.AbilityRuntime.Mission -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -1033,7 +1033,7 @@ Clears a given mission, regardless of whether it is locked. This API uses a prom **System capability**: SystemCapability.Ability.AbilityRuntime.Mission -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -1087,7 +1087,7 @@ Clears all unlocked missions. This API uses an asynchronous callback to return t **System capability**: SystemCapability.Ability.AbilityRuntime.Mission -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -1135,7 +1135,7 @@ Clears all unlocked missions. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Mission -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Return value** @@ -1180,7 +1180,7 @@ Switches a given mission to the foreground. This API uses an asynchronous callba **System capability**: SystemCapability.Ability.AbilityRuntime.Mission -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -1232,7 +1232,7 @@ Switches a given mission to the foreground, with the startup parameters for the **System capability**: SystemCapability.Ability.AbilityRuntime.Mission -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -1285,7 +1285,7 @@ Switches a given mission to the foreground, with the startup parameters for the **System capability**: SystemCapability.Ability.AbilityRuntime.Mission -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-photoEditorExtensionAbility.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-photoEditorExtensionAbility.md index c4093a805c32ca8ab9acf16fc853e1036a4e98bb..1ead0703fcae441f5324b4ef699ecbe965e021e6 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-photoEditorExtensionAbility.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-photoEditorExtensionAbility.md @@ -1,5 +1,5 @@ # @ohos.app.ability.PhotoEditorExtensionAbility (Image Editing) -The PhotoEditorExtensionAbility, which inherits from the ExtensionAbility, enables your application to provide an image editing page for applications that do not have the image editing capability. After an application uses **startAbilityByType** to start a vertical domain panel with available image editing applications that have implemented the PhotoEditorExtensionAbility, the user can select one of the applications on the panel to display an image editing page. +The PhotoEditorExtensionAbility, which inherits from the [ExtensionAbility](js-apis-app-ability-extensionAbility.md), enables your application to provide an image editing page for applications that do not have the image editing capability. After an application uses [startAbilityByType](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to start a vertical domain panel with available image editing applications that have implemented the PhotoEditorExtensionAbility, the user can select one of the applications on the panel to display an image editing page. > **NOTE** > > The initial APIs of this module are supported since API version 12. Newly added APIs will be marked with a superscript to indicate their earliest API version. diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-photoEditorExtensionContext.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-photoEditorExtensionContext.md index 282b189bdeac9ad53ed4e93f75d6a1e2012aadc9..3d24bec8d2513f0893991387c4b3736ea5a5dfa2 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-photoEditorExtensionContext.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-photoEditorExtensionContext.md @@ -50,6 +50,7 @@ import { common, UIExtensionContentSession, Want } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { fileIo } from '@kit.CoreFileKit'; import { image } from '@kit.ImageKit'; +import { BusinessError } from '@kit.BasicServicesKit'; const TAG = '[ExamplePhotoEditorAbility]'; diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-quickFixManager-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-quickFixManager-sys.md index 03266e10d6c537fd12046d50ef700e858cff6171..83c81bcf189da2cab7666a801aacc132df9a7ee9 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-quickFixManager-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-quickFixManager-sys.md @@ -19,7 +19,7 @@ Defines the quick fix information at the HAP file level. **System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. | Name | Type | Read-only| Mandatory| Description | | ----------- | -------------------- | ---- | ---- | ------------------------------------------------------------ | @@ -33,7 +33,7 @@ Defines the quick fix information at the application level. **System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. | Name | Type | Read-only| Mandatory| Description | | ----------- | -------------------- | ---- | ---- | ------------------------------------------------------------ | @@ -54,7 +54,7 @@ Applies a quick fix patch. This API uses an asynchronous callback to return the **System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -110,7 +110,7 @@ Applies a quick fix patch. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -167,7 +167,7 @@ Obtains the quick fix information of the application. This API uses an asynchron **System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -218,7 +218,7 @@ Obtains the quick fix information of the application. This API uses a promise to **System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -272,7 +272,7 @@ Revokes quick fix. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -317,7 +317,7 @@ Revokes quick fix. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-serviceExtensionAbility-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-serviceExtensionAbility-sys.md index 206b7591f41681f41a0a1965a11872e79cbbd1a6..bf0195d1e6f5548bbb695cc68321ff366d04f552 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-serviceExtensionAbility-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-serviceExtensionAbility-sys.md @@ -24,7 +24,7 @@ None. **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | @@ -39,7 +39,7 @@ Called to initialize the service logic when a ServiceExtensionAbility is being c **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -68,7 +68,7 @@ Called to clear resources when this ServiceExtensionAbility is being destroyed. **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Example** @@ -91,7 +91,7 @@ Called following **onCreate()** when a ServiceExtensionAbility is started by cal **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -121,7 +121,7 @@ Called following **onCreate()** when a ServiceExtensionAbility is started by cal **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -190,7 +190,7 @@ Called when a client is disconnected from this ServiceExtensionAbility. **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -231,7 +231,7 @@ Called when a new client attempts to connect to this ServiceExtensionAbility aft **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -259,7 +259,7 @@ Called when the configuration of this ServiceExtensionAbility is updated. **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -287,7 +287,7 @@ Dumps the client information. **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-startOptions-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-startOptions-sys.md index 4aab1f91e7d0c3f3d5ae72266ac4bd7c0086c738..99fc16b4c941d58a00e3acb45b2d5bace8176f4a 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-startOptions-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-startOptions-sys.md @@ -20,10 +20,11 @@ import { StartOptions } from '@kit.AbilityKit'; **System capability**: SystemCapability.Ability.AbilityRuntime.Core +**System API**: This is a system API. + | Name| Type| Read-only| Optional| Description| | -------- | -------- | -------- | -------- | -------- | -| [windowMode](js-apis-app-ability-abilityConstant-sys.md#windowmode) | number | No| Yes| Window mode.
**System API**: This is a system API and cannot be called by third-party applications.| -| windowFocused12+ | boolean | No| Yes| Whether the window has focus. The default value is **true**, indicating that the window has focus.
**Constraints**:
This property takes effect only on tablets and 2-in-1 devices.
This property takes effect only in [UIAbilityContext.startAbility](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability-1).| +| windowFocused12+ | boolean | No| Yes| Whether the window has focus. The default value is **true**, indicating that the window has focus.
**Constraints**:
1. This property takes effect only on 2-in-1 devices and tablets.
2. This property takes effect only in [UIAbilityContext.startAbility](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability-1).| **Example** diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-startOptions.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-startOptions.md index 63eae5546102bb96bfbe0264fe04b4f40f7a0405..b34cb606d4428b1402877828a05d13cb6d517120 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-startOptions.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-startOptions.md @@ -22,17 +22,21 @@ import { StartOptions } from '@kit.AbilityKit'; | -------- | -------- | -------- | -------- | -------- | | windowMode12+ | number | No| Yes| Window mode when the ability is started. For details, see [WindowMode](./js-apis-app-ability-abilityConstant.md#windowmode12).| | displayId | number | No| Yes| Display ID mode. The default value is **0**, indicating the current display.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| withAnimation11+ | boolean | No| Yes| Whether the ability has the animation effect.| -| windowLeft11+ | number | No| Yes| Left position of the window.| -| windowTop11+ | number | No| Yes| Top position of the window.| -| windowWidth11+ | number | No| Yes| Width of the window.| -| windowHeight11+ | number | No| Yes| Height of the window.| -| processMode12+ | [contextConstant.ProcessMode](js-apis-app-ability-contextConstant.md#processmode12) | No| Yes| Process mode.
**Constraints**:
1. This property takes effect only on tablets.
2. This property takes effect only in [UIAbilityContext.startAbility](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability-1).
3. **processMode** and **startupVisibility** must be set in pair.| -| startupVisibility12+ | [contextConstant.StartupVisibility](js-apis-app-ability-contextConstant.md#startupvisibility12) | Yes| No| Visibility of the ability after it is started.
**Constraints**:
1. This property takes effect only on tablets.
2. This property takes effect only in [UIAbilityContext.startAbility](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability-1).
3. **processMode** and **startupVisibility** must be set in pair.| -| startWindowIcon14+ | [image.PixelMap](../../reference/apis-image-kit/js-apis-image.md#pixelmap7) | No| Yes| Icon displayed on the launch page when the UIAbility is started in an application. If this property is not set, the value of **startWindowIcon** in the **module.json5** file is used by default.
**Constraints**:
1. This property takes effect only on tablets and 2-in-1 devices.
2. This property takes effect only in [UIAbilityContext.startAbility](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability-1).
3. The maximum size of an image is 600 MB.| -| startWindowBackgroundColor14+ | string | No| Yes| Background color of the launch page when the UIAbility is launched in an application. If this property is not set, the value of **startWindowBackground** in the **module.json5** file is used by default.
**Constraints**:
1. This property takes effect only on tablets and 2-in-1 devices.
2. This property takes effect only in [UIAbilityContext.startAbility](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability-1).| -| supportWindowModes14+ | Array\<[bundleManager.SupportWindowMode](./js-apis-bundleManager.md#supportwindowmode)> | No| Yes| Whether to display the maximize, minimize, or split-screen button when the UIAbility is launched in an application. If this property is not set, the value of **supportWindowMode** in the **module.json5** file is used by default.
**Constraints**:
This property takes effect only on tablets and 2-in-1 devices.| - +| withAnimation11+ | boolean | No| Yes| Whether animation effects are used when the ability is started. The value **true** means that animation effects are used, and **false** means the opposite.
**Constraints**:
1. This property takes effect only on 2-in-1 devices and tablets.
2. The caller and target must be the same application.| +| windowLeft11+ | number | No| Yes| Position of the left edge of the window, in px.| +| windowTop11+ | number | No| Yes| Position of the top edge of the window, in px.| +| windowWidth11+ | number | No| Yes| Window width, in px.| +| windowHeight11+ | number | No| Yes| Window height, in px.| +| processMode12+ | [contextConstant.ProcessMode](js-apis-app-ability-contextConstant.md#processmode12) | No| Yes| Process mode.
**Constraints**:
1. This property takes effect only on 2-in-1 devices and tablets.
2. This property takes effect only in [UIAbilityContext.startAbility](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability-1).
3. **processMode** and **startupVisibility** must be set in pair.| +| startupVisibility12+ | [contextConstant.StartupVisibility](js-apis-app-ability-contextConstant.md#startupvisibility12) | Yes| No| Visibility of the ability after it is started.
**Constraints**:
1. This property takes effect only on 2-in-1 devices and tablets.
2. This property takes effect only in [UIAbilityContext.startAbility](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability-1).
3. **processMode** and **startupVisibility** must be set in pair.| +| startWindowIcon14+ | [image.PixelMap](../../reference/apis-image-kit/js-apis-image.md#pixelmap7) | No| Yes| Icon displayed on the launch page when the UIAbility is started in an application. If this property is not set, the value of **startWindowIcon** in the **module.json5** file is used by default.
**Constraints**:
1. This property takes effect only on 2-in-1 devices and tablets.
2. This property takes effect only in [UIAbilityContext.startAbility](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability-1).
3. The maximum size of an image is 600 MB.| +| startWindowBackgroundColor14+ | string | No| Yes| Background color of the launch page when the UIAbility is launched in an application. If this property is not set, the value of **startWindowBackground** in the **module.json5** file is used by default.
**Constraints**:
1. This property takes effect only on 2-in-1 devices and tablets.
2. This property takes effect only in [UIAbilityContext.startAbility](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability-1).| +| supportWindowModes14+ | Array\<[bundleManager.SupportWindowMode](./js-apis-bundleManager.md#supportwindowmode)> | No| Yes| Whether to display the maximize, minimize, or split-screen button when the UIAbility is launched in an application. If this property is not set, the value of **supportWindowMode** configured under [abilities](../../quick-start/module-configuration-file.md#abilities) in the [module.json5 file](../../quick-start/module-configuration-file.md) corresponding to the UIAbility is used by default.
- **FULL_SCREEN**: full-screen mode.
- **FLOATING**: floating window mode.
- **SPLIT**: split-screen mode. Generally, **FULL_SCREEN** or **FLOATING** must be used together. You are not advised to configure only **SPLIT**. If only **SPLIT** is configured, the window on 2-in-1 devices is in floating window mode by default and can transition to the split-screen mode, and the window on tablets is in full-screen mode by default and can transition to the split-screen mode.
**Constraints**:
This property takes effect only on 2-in-1 devices and tablets.| +| minWindowWidth18+ | number | No| Yes| Minimum width of the window, in vp.
**Constraints**:
This property takes effect only on 2-in-1 devices.| +| minWindowHeight18+ | number | No| Yes| Minimum height of the window, in vp.
**Constraints**:
This property takes effect only on 2-in-1 devices.| +| maxWindowWidth18+ | number | No| Yes| Maximum width of the window, in vp.
**Constraints**:
This property takes effect only on 2-in-1 devices.| +| maxWindowHeight18+ | number | No| Yes| Maximum height of the window, in vp.
**Constraints**:
This property takes effect only on 2-in-1 devices.| + **Example** ```ts @@ -65,7 +69,11 @@ import { StartOptions } from '@kit.AbilityKit'; bundleManager.SupportWindowMode.FULL_SCREEN, bundleManager.SupportWindowMode.SPLIT, bundleManager.SupportWindowMode.FLOATING - ] + ], + minWindowWidth: 320, + minWindowHeight: 240, + maxWindowWidth: 2560, + maxWindowHeight: 2560 }; try { diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-uiAbility.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-uiAbility.md index 32da9b0439197882a04210f492d934439c9a3d4d..d95b9f269d16703c44b1b87abe228f87857f665a 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-uiAbility.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-uiAbility.md @@ -27,7 +27,7 @@ import { UIAbility } from '@kit.AbilityKit'; | -------- | -------- | -------- | -------- | -------- | | context | [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) | No| No| Context of the UIAbility.
**Atomic service API**: This API can be used in atomic services since API version 11.| | launchWant | [Want](js-apis-app-ability-want.md) | No| No| Parameters for starting the UIAbility.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| lastRequestWant | [Want](js-apis-app-ability-want.md) | No| No| Parameters carried in the last request.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| lastRequestWant | [Want](js-apis-app-ability-want.md) | No| No| Latest Want received through [onCreate](#uiabilityoncreate) or [onNewWant](#uiabilityonnewwant) when the UIAbility is started for multiple times.
**Atomic service API**: This API can be used in atomic services since API version 11.| | callee | [Callee](#callee) | No| No| Object that invokes the stub service.| ## UIAbility.onCreate @@ -214,11 +214,80 @@ class MyUIAbility extends UIAbility { } ``` + +## UIAbility.onWillForeground18+ + +onWillForeground(): void + +Triggered just before the application transitions to the foreground. It is called before [onForeground](#uiabilityonforeground). It can be used to capture the moment when the application starts to transition to the foreground. When paired with [onDidForeground](#uiabilityondidforeground18), it can also measure the duration from the application's initial foreground entry to its full transition into the foreground state. + +This API returns the result synchronously and does not support asynchronous callback. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Example** + +```ts +import { UIAbility } from '@kit.AbilityKit'; +import { hiAppEvent, hilog } from '@kit.PerformanceAnalysisKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +export default class EntryAbility extends UIAbility { + // ... + + onWillForeground(): void { + // Start to log the event that the application starts moving to the foreground. + let eventParams: Record = { 'xxxx': 100 }; + let eventInfo: hiAppEvent.AppEventInfo = { + // Define the event domain. + domain: "lifecycle", + // Define the event name. + name: "onwillforeground", + // Define the event type. + eventType: hiAppEvent.EventType.BEHAVIOR, + // Define the event parameters. + params: eventParams, + }; + hiAppEvent.write(eventInfo).then(() => { + hilog.info(0x0000, 'testTag', `HiAppEvent success to write event`) + }).catch((err: BusinessError) => { + hilog.error(0x0000, 'testTag', `HiAppEvent err.code: ${err.code}, err.message: ${err.message}`) + }); + } + // ... + + onDidForeground(): void { + // Start to log the event that the application fully transitions to the foreground. + let eventParams: Record = { 'xxxx': 100 }; + let eventInfo: hiAppEvent.AppEventInfo = { + // Define the event domain. + domain: "lifecycle", + // Define the event name. + name: "ondidforeground", + // Define the event type. + eventType: hiAppEvent.EventType.BEHAVIOR, + // Define the event parameters. + params: eventParams, + }; + hiAppEvent.write(eventInfo).then(() => { + hilog.info(0x0000, 'testTag', `HiAppEvent success to write event`) + }).catch((err: BusinessError) => { + hilog.error(0x0000, 'testTag', `HiAppEvent err.code: ${err.code}, err.message: ${err.message}`) + }); + } +} +``` + + ## UIAbility.onForeground onForeground(): void -Called when this UIAbility is switched from the background to the foreground. This API returns the result synchronously and does not support asynchronous callback. +Triggered when the application transitions from the background to the foreground. It is called between [onWillForeground](#uiabilityonwillbackground18) and [onDidForeground](#uiabilityondidforeground18). It can be used to request system resources required, for example, requesting location services when the application transitions to the foreground. + +This API returns the result synchronously and does not support asynchronous callback. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -237,11 +306,73 @@ class MyUIAbility extends UIAbility { ``` +## UIAbility.onDidForeground18+ + +onDidForeground(): void + +Triggered after the application has transitioned to the foreground. It is called after [onForeground](#uiabilityonforeground). It can be used to capture the moment when the application fully transitions to the foreground. When paired with [onWillForeground](#uiabilityonwillforeground18), it can also measure the duration from the application's initial foreground entry to its full transition into the foreground state. + +This API returns the result synchronously and does not support asynchronous callback. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Example** + +For details, see [onWillForeground](#uiabilityonwillforeground18). + + +## UIAbility.onWillBackground18+ + +onWillBackground(): void + +Triggered just when the application transitions to the background. It is called before [onBackground](#uiabilityonbackground). It can be used to log various types of data, such as faults, statistics, security information, and user behavior that occur during application running. + +This API returns the result synchronously and does not support asynchronous callback. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Example** + +```ts +import { UIAbility } from '@kit.AbilityKit'; +import { hiAppEvent, hilog } from '@kit.PerformanceAnalysisKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +class MyUIAbility extends UIAbility { + onWillBackground(): void { + let eventParams: Record = { + "int_data": 100, + "str_data": "strValue", + }; + // Record the application fault information. + hiAppEvent.write({ + domain: "test_domain", + name: "test_event", + eventType: hiAppEvent.EventType.FAULT, + params: eventParams, + }, (err: BusinessError) => { + if (err) { + hilog.error(0x0000, 'hiAppEvent', `code: ${err.code}, message: ${err.message}`); + return; + } + hilog.info(0x0000, 'hiAppEvent', `success to write event`); + }); + } +} +``` + + ## UIAbility.onBackground onBackground(): void -Called when this UIAbility is switched from the foreground to the background. This API returns the result synchronously and does not support asynchronous callback. +Triggered when the application transitions from the foreground to the background. It is called between [onWillBackground](#uiabilityonwillbackground18) and [onDidBackground](#uiabilityondidbackground18). It can be used to release resources when the UI is no longer visible, for example, stopping location services. + +This API returns the result synchronously and does not support asynchronous callback. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -260,6 +391,51 @@ class MyUIAbility extends UIAbility { ``` +## UIAbility.onDidBackground18+ + +onDidBackground(): void + +Triggered after the application has transitioned to the background. It is called after [onBackground](#uiabilityonbackground). It can be used to release resources after the application has entered the background, for example, stopping audio playback. + +This API returns the result synchronously and does not support asynchronous callback. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Example** + +```ts +import { UIAbility } from '@kit.AbilityKit'; +import { hiAppEvent, hilog } from '@kit.PerformanceAnalysisKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +class MyUIAbility extends UIAbility { + static audioRenderer: audio.AudioRenderer; + // ... + onForeground(): void { + // Request an AudioRenderer in the foreground to play Pulse Code Modulation (PCM) audio data. + audio.createAudioRenderer(audioRendererOptions).then((data) => { + EntryAbility.audioRenderer = data; + console.info('AudioRenderer Created : Success : Stream Type: SUCCESS'); + }).catch((err: BusinessError) => { + console.error(`AudioRenderer Created : ERROR : ${err}`); + }); + } + + onDidBackground() { + // Release the AudioRenderer after transitioning to the background. + audioRenderer.release((err: BusinessError) => { + if (err) { + console.error('AudioRenderer release failed'); + } else { + console.info('AudioRenderer released.'); + } + }); + } +} +``` + ## UIAbility.onContinue onContinue(wantParam: Record<string, Object>): AbilityConstant.OnContinueResult | Promise<AbilityConstant.OnContinueResult> @@ -394,7 +570,7 @@ class MyUIAbility extends UIAbility { onSaveState(reason: AbilityConstant.StateType, wantParam: Record<string, Object>): AbilityConstant.OnSaveResult -Called when the framework automatically saves the UIAbility state in the case of an application fault. This API is used together with [appRecovery](js-apis-app-ability-appRecovery.md). If automatic state saving is enabled, **onSaveState** is called to save the state of this UIAbility. +Called when the framework automatically saves the UIAbility state in the case of an application fault. This API is used together with [appRecovery](js-apis-app-ability-appRecovery.md). When an application is faulty, the framework calls **onSaveState** to save the status of the UIAbility if auto-save is enabled. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -460,7 +636,13 @@ class MyUIAbility extends UIAbility { onPrepareToTerminate(): boolean -Called when this UIAbility is about to terminate in case that the system parameter **persist.sys.prepare_terminate** is set to **true**. You can define an operation in this callback to determine whether to continue terminating the UIAbility. If a confirmation from the user is required, you can define a pre-termination operation in the callback and use it together with [terminateSelf](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself), for example, displaying a dialog box to ask the user whether to terminate the UIAbility. The UIAbility termination process is canceled when **persist.sys.prepare_terminate** is set to **true**. +Called when this UIAbility is about to terminate. It allows for additional actions to be performed before the UIAbility is officially terminated. For example, you can prompt the user to confirm whether they want to terminate the UIAbility. If the user confirms, you can call [terminateSelf](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself) to terminate it. + +Currently, this API takes effect only on 2-in-1 devices. + +> **NOTE** +> +> Since API version 15, this callback is not executed when [UIAbility.onPrepareToTerminateAsync](#uiabilityonpreparetoterminateasync15) is implemented. When [AbilityStage.onPrepareTerminationAsync](js-apis-app-ability-abilityStage.md#abilitystageonprepareterminationasync15) or [AbilityStage.onPrepareTermination](js-apis-app-ability-abilityStage.md#abilitystageonpreparetermination15) is implemented, this callback is not executed if the user right-clicks the dock bar or system tray to close the UIAbility. **Required permissions**: ohos.permission.PREPARE_APP_TERMINATE @@ -472,7 +654,7 @@ Called when this UIAbility is about to terminate in case that the system paramet | Type| Description| | -- | -- | -| boolean | Whether to terminate the UIAbility. The value **true** means that the termination process is canceled and the UIAbility is not terminated. The value **false** means to continue terminating the UIAbility.| +| boolean | Whether to terminate the UIAbility. The value **true** means that the termination process is canceled. The value **false** means to continue terminating the UIAbility.| **Example** @@ -507,6 +689,47 @@ export default class EntryAbility extends UIAbility { } ``` +## UIAbility.onPrepareToTerminateAsync15+ + +onPrepareToTerminateAsync(): Promise\ + +Called when this UIAbility is about to terminate. It allows for additional actions to be performed before the UIAbility is officially terminated. This API uses a promise to return the result. For example, you can prompt the user to confirm whether they want to terminate the UIAbility. If the user confirms, you can call [terminateSelf](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself) to terminate it. + +Currently, this API takes effect only on 2-in-1 devices. + +> **NOTE** +> +> - When [AbilityStage.onPrepareTerminationAsync](js-apis-app-ability-abilityStage.md#abilitystageonprepareterminationasync15) or [AbilityStage.onPrepareTermination](js-apis-app-ability-abilityStage.md#abilitystageonpreparetermination15) is implemented, this callback is not executed if the user right-clicks the dock bar or system tray to close the UIAbility. +> +> - If an asynchronous callback crashes, it will be handled as a timeout. If the UIAbility does not respond within 10 seconds, it will be terminated forcibly. + +**Required permissions**: ohos.permission.PREPARE_APP_TERMINATE + +**Atomic service API**: This API can be used in atomic services since API version 15. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Return value** + +| Type| Description| +| -- | -- | +| Promise\ | Promise used to return the result. The value **true** means that the termination process is canceled. The value **false** means to continue terminating the UIAbility.| + +**Example** + +```ts +import { UIAbility } from '@kit.AbilityKit'; + +export default class EntryAbility extends UIAbility { + async onPrepareToTerminateAsync(): Promise { + await new Promise((res, rej) => { + setTimeout (res, 2000); // Execute the operation 2 seconds later. + }); + return true; // The pre-termination operation is defined. The value true means that the UIAbility termination process is canceled. + } +} +``` + ## UIAbility.onBackPressed10+ onBackPressed(): boolean @@ -538,7 +761,7 @@ export default class EntryAbility extends UIAbility { } ``` -## UIAbility.onCollaborate16+ +## UIAbility.onCollaborate18+ onCollaborate(wantParam: Record<string, Object>): AbilityConstant.CollaborateResult @@ -547,7 +770,7 @@ Callback invoked to return the collaboration result in multi-device collaboratio **NOTE** - This callback does not support ability launch in specified mode. - When you use methods such as **startAbility()** to start an application, you must include **FLAG_ABILITY_ON_COLLABORATE** in [Flags](js-apis-ability-wantConstant.md#flags) in the Want object. -- This callback must be called before **onForeground** or **onBackground** in a cold startup and before **onNewWant** in a hot startup. +- During a cold start, this callback must be invoked before [onForeground](#uiabilityonforeground) or after [onBackground](#uiabilityonbackground). During a hot start, this callback must be invoked before [onNewWant](#uiabilityonnewwant). **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore @@ -562,7 +785,7 @@ Callback invoked to return the collaboration result in multi-device collaboratio | Name | Value | Description | | -------- | ---- | ---------- | -| [AbilityConstant.CollaborateResult](js-apis-app-ability-abilityConstant.md#collaborateresult) | Collaborator result, that is, whether the target application accepts the collaboration request.| +| [AbilityConstant.CollaborateResult](js-apis-app-ability-abilityConstant.md#collaborateresult18) | Collaborator result, that is, whether the target application accepts the collaboration request.| **Example** @@ -972,7 +1195,7 @@ export default class MainUIAbility extends UIAbility { off(type: 'release', callback: OnReleaseCallback): void -Deregisters a callback that is invoked when the stub on the target UIAbility is disconnected. This capability is reserved. This API uses an asynchronous callback to return the result. +Unregisters a callback that is invoked when the stub on the target UIAbility is disconnected. This capability is reserved. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore @@ -1028,7 +1251,7 @@ export default class MainUIAbility extends UIAbility { off(type: 'release'): void -Deregisters a callback that is invoked when the stub on the target UIAbility is disconnected. This capability is reserved. +Unregisters a callback that is invoked when the stub on the target UIAbility is disconnected. This capability is reserved. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore @@ -1159,7 +1382,7 @@ export default class MainUIAbility extends UIAbility { off(method: string): void -Deregisters a caller notification callback, which is invoked when the target UIAbility registers a function. +Unregisters a caller notification callback, which is invoked when the target UIAbility registers a function. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore @@ -1213,7 +1436,7 @@ Defines the callback that is invoked when the stub on the target UIAbility is di | Name| Type| Mandatory| Description| | --- | ----- | --- | -------- | | msg | string | Yes| Message used for disconnection.| - + ## OnRemoteStateChangeCallback10+ ### (msg: string) @@ -1229,7 +1452,7 @@ Defines the callback that is invoked when the remote UIAbility state changes in | Name| Type| Mandatory| Description| | --- | ----- | --- | -------- | | msg | string | Yes| Message used for disconnection.| - + ## CalleeCallback ### (indata: rpc.MessageSequence) diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-uiExtensionContentSession-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-uiExtensionContentSession-sys.md index 7141f9384d3d71d10ca5a60ba9bf837ff98d8107..fa4f938d1b2a1de5743496f28d151b89d13591cb 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-uiExtensionContentSession-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-uiExtensionContentSession-sys.md @@ -64,7 +64,11 @@ struct Index { 'message': 'test' }; - this.session?.sendData(data); + try { + this.session?.sendData(data); + } catch (err) { + console.log('sendData err:' + JSON.stringify(err)); + } }) } .height('100%') @@ -688,9 +692,18 @@ export default class UIExtAbility extends UIExtensionAbility { onSessionCreate(want: Want, session: UIExtensionContentSession): void { let storage: LocalStorage = new LocalStorage(); storage.setOrCreate('session', session); - session.loadContent('pages/Extension', storage); - session.setWindowBackgroundColor('#00FF00'); + try { + session.loadContent('pages/Extension', storage); + } catch (err) { + console.log('loadContent err:' + JSON.stringify(err)); + } + + try { + session.setWindowBackgroundColor('#00FF00'); + } catch (err) { + console.log('setWindowBackgroundColor err:' + JSON.stringify(err)); + } } // ... @@ -981,7 +994,11 @@ export default class UIExtAbility extends UIExtensionAbility { }; let storage: LocalStorage = new LocalStorage(data); - session.loadContent('pages/extension', storage); + try { + session.loadContent('pages/Extension', storage); + } catch (err) { + console.log('loadContent err:' + JSON.stringify(err)); + } } onSessionDestroy(session: UIExtensionContentSession) { diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-uiExtensionContentSession.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-uiExtensionContentSession.md index df73c51f70b41f08a0a5eb9419ca910f41752321..a568bf2234ae1bd0f93116d3e99fed50160ee2b4 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-uiExtensionContentSession.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-uiExtensionContentSession.md @@ -56,7 +56,7 @@ export default class UIExtAbility extends UIExtensionAbility { } ``` -## UIExtensionContentSession.loadContentByName16+ +## UIExtensionContentSession.loadContentByName18+ loadContentByName(name: string, storage?: LocalStorage): void diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-uiServiceExtensionAbility-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-uiServiceExtensionAbility-sys.md index 7bd2fb83054f98f6bb1f4ea18b0e9a1076204b02..51d990a68b88868735cb626aea8c399ffba2f938 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-uiServiceExtensionAbility-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-uiServiceExtensionAbility-sys.md @@ -5,7 +5,7 @@ UIServiceExtensionAbility, inherited from [ExtensionAbility](js-apis-app-ability > **NOTE** > -> The initial APIs of this module are supported since API version 13. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The initial APIs of this module are supported since API version 14. Newly added APIs will be marked with a superscript to indicate their earliest API version. > > The APIs of this module can be used only in the stage model. > @@ -65,7 +65,7 @@ class UIServiceExt extends UIServiceExtensionAbility { onRequest(want: Want, startId: number): void -Called to request to start a [UIServiceExtensionAbility](js-apis-app-ability-uiServiceExtensionAbility-sys.md). If the UIServiceExtensionAbility is started by calling [startAbility](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) or [startUIServiceExtensionAbility](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartuiserviceextensionability13), this callback will be invoked after [onCreate](#uiserviceextensionabilityoncreate). The value of **startId** is incremented for each UIServiceExtensionAbility that is started. +Called to request to start a [UIServiceExtensionAbility](js-apis-app-ability-uiServiceExtensionAbility-sys.md). If the UIServiceExtensionAbility is started by calling [startAbility](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) or [startUIServiceExtensionAbility](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartuiserviceextensionability14), this callback will be invoked after [onCreate](#uiserviceextensionabilityoncreate). The value of **startId** is incremented for each UIServiceExtensionAbility that is started. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -76,7 +76,7 @@ Called to request to start a [UIServiceExtensionAbility](js-apis-app-ability-uiS | Name| Type| Read Only| Optional| Description| | -------- | -------- | -------- | -------- | -------- | | want | [Want](js-apis-app-ability-want.md) | Yes| No| [Want](js-apis-app-ability-want.md) information about the [UIServiceExtensionAbility](js-apis-app-ability-uiServiceExtensionAbility-sys.md), including the ability name and bundle name.| -| startId | number | Yes| |Number of UIServiceExtensionAbility start times. The initial value is **1**, and the value is automatically incremented for each UIServiceExtensionAbility started.| +| startId | number | Yes| Number of UIServiceExtensionAbility start times. The initial value is **1**, and the value is automatically incremented for each UIServiceExtensionAbility started.| **Example** @@ -95,7 +95,7 @@ class UIServiceExt extends UIServiceExtensionAbility { onConnect(want: Want, proxy: UIServiceHostProxy): void -Called when the connection to a [UIServiceExtensionAbility](js-apis-app-ability-uiServiceExtensionAbility-sys.md) is established. If the UIServiceExtensionAbility is started by calling [connectUIServiceExtensionAbility()](js-apis-inner-application-uiExtensionContext.md#uiextensioncontextconnectuiserviceextensionability13), this callback will be invoked after [onCreate()](#uiserviceextensionabilityoncreate). This callback receives a [UIServiceHostProxy](js-apis-inner-application-uiservicehostproxy-sys.md) object for communication between the client and server. +Called when the connection to a [UIServiceExtensionAbility](js-apis-app-ability-uiServiceExtensionAbility-sys.md) is established. If the UIServiceExtensionAbility is started by calling [connectUIServiceExtensionAbility()](js-apis-inner-application-uiExtensionContext.md#uiextensioncontextconnectuiserviceextensionability14), this callback will be invoked after [onCreate()](#uiserviceextensionabilityoncreate). This callback receives a [UIServiceHostProxy](js-apis-inner-application-uiservicehostproxy-sys.md) object for communication between the client and server. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -166,7 +166,7 @@ Called when a window will be created for the [UIServiceExtensionAbility](js-apis | Name| Type| Read Only| Optional| Description| | -------- | -------- | -------- | -------- | -------- | -| config |[window.ExtensionWindowConfig](../apis-arkui/js-apis-window-sys.md#extensionwindowconfig12)| Yes| No| Window configuration information.| +| config |[window.ExtensionWindowConfig](../apis-arkui/js-apis-window-sys.md#extensionwindowconfig14)| Yes| No| Window configuration information.| **Example** diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-want.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-want.md index abeecdd7af558848bc09061c3bb292b395d1dc96..2f07629f17d74a8b6cd2889f4b141965ad822d8b 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-want.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-want.md @@ -22,14 +22,15 @@ import { Want } from '@kit.AbilityKit'; | ----------- | -------------------- | ---- | ------------------------------------------------------------ | | deviceId | string | No | ID of the device running the ability. If this field is unspecified, the local device is used. | | bundleName | string | No | Bundle name of the ability.| -| moduleName | string | No| Name of the module to which the ability belongs.| +| moduleName | string | No| Name of the module to which the ability belongs.
**NOTE**
If the ability belongs to a [HAR](../../quick-start/har-package.md) module, **moduleName** must be set to the name of the [HAP](../../quick-start/hap-package.md) or [HSP](../../quick-start/in-app-hsp.md) module that depends on this HAR.| | abilityName | string | No | Name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability. The value of **abilityName** must be unique in an application.| | action | string | No | Action to take, such as viewing and sharing application details. In implicit Want, you can define this field and use it together with **uri** or **parameters** to specify the operation to be performed on the data. For details about the definition and matching rules of implicit Want, see [Matching Rules of Explicit Want and Implicit Want](../../application-models/explicit-implicit-want-mappings.md). | | entities | Array\ | No| Additional category information (such as browser and video player) of the ability. It is a supplement to the **action** field for implicit Want. and is used to filter ability types.| | uri | string | No| Data carried. This field is used together with **type** to specify the data type. If **uri** is specified in a Want, the Want will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.| | type | string | No| MIME type, that is, the type of the file to open, for example, **'text/xml'** and **'image/*'**. For details about the MIME type definition, see https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com.| -| parameters | Record\ | No | List of parameters in the **Want** object.
1. The values of the following keys are assigned by the system. Manual settings do not take effect, since the system automatically changes the values to the actual values during data transfer.
- **ohos.aafwk.param.callerPid**: PID of the caller. The value is a string.
- **ohos.aafwk.param.callerBundleName**: bundle name of the caller. The value is a string.
- **ohos.aafwk.param.callerAbilityName**: ability name of the caller. The value is a string.
- **ohos.aafwk.param.callerNativeName**: process name of the caller when the native method is called. The value is a string.
- **ohos.aafwk.param.callerAppId**: appId of the caller. The value is a string.
- **ohos.aafwk.param.callerAppIdentifier**: appIdentifier of the caller. The value is a string.
- **ohos.aafwk.param.callerToken**: token of the caller. The value is a string.
- **ohos.aafwk.param.callerUid**: UID in [BundleInfo](js-apis-bundleManager-bundleInfo.md#bundleinfo-1), that is, the application's UID in the bundle information. The value is a number.
- **ohos.param.callerAppCloneIndex**: clone index of the caller. The value is of the numeric type.
- **component.startup.newRules**: enabled status of the new control rule. The value is of the Boolean type.
- **moduleName**: module name of the caller. The value is a string.
- **ability.params.backToOtherMissionStack**: support for redirection back across mission stacks. The value is of the Boolean type.
- **ohos.ability.params.abilityRecoveryRestart**: support for ability restart upon fault recovery. The value is of the Boolean type.
- **ohos.extra.param.key.contentTitle**: title that can be shared by the atomic service. The value is a string.
- **ohos.extra.param.key.shareAbstract**: content that can be shared by the atomic service. The value is a string.
- **ohos.extra.param.key.shareUrl**: URL of the content that can be shared by the atomic service. The value is a string.
- **ohos.extra.param.key.supportContinuePageStack**: support for migration of page stack information during cross-device migration. The value is of the Boolean type. The default value is **true**, indicating that page stack information is automatically migrated.
- **ohos.extra.param.key.supportContinueSourceExit**: support for application exit on the source device during cross-device migration. The value is of the Boolean type. The default value is **true**, indicating that the application on the source device automatically exits.
- **ohos.extra.param.key.showMode**: mode to show the atomic service startup. The value is an enumerated value of [wantConstant.ShowMode](js-apis-app-ability-wantConstant.md#showmode12).
- **ohos.dlp.params.sandbox**: available only for DLP files. This key is involved only in system applications.
- **ohos.dlp.params.bundleName**: bundle name of DLP. The value is a string. This key is involved only in system applications.
- **ohos.dlp.params.moduleName**: module name of DLP. The value is a string. This key is involved only in system applications.
- **ohos.dlp.params.abilityName**: ability name of DLP. The value is a string. This key is involved only in system applications.
- **ohos.dlp.params.index**: DLP index. The value is a number. This key is involved only in system applications.
- **ohos.ability.params.asssertFaultSessionId**: session ID of the fault assertion. The value is a string. This key is involved only in system applications.

2. The following keys are defined by the system, and their values need to be manually assigned.
- **ability.params.stream**: File URIs to be authorized to the target ability. The value is a file URI array of the string type.
- **ohos.extra.param.key.appCloneIndex**: index of the application clone.

3. In addition to the foregoing cases, applications may further agree on the key-value pairs to transfer.

**NOTE**
For details about the constants of **Params** in **want**, see [wantConstant](js-apis-app-ability-wantConstant.md).
Note that a maximum of 200 KB data that can be transferred by using **WantParams**. If the data volume exceeds 200 KB, transfer data in [WriteRawDataBuffer](../apis-ipc-kit/js-apis-rpc.md#writerawdatabuffer11) or [uri](../apis-arkts/js-apis-uri.md) mode.
The values of **parameters** must be of the following basic data types: String, Number, Boolean, Object, undefined, and null. Functions in an object cannot be transferred. | -| [flags](js-apis-ability-wantConstant.md#flags) | number | No| How the **Want** object will be handled. By default, a number is passed in.
For example, **wantConstant.Flags.FLAG_ABILITY_CONTINUATION** specifies whether to start the ability in cross-device migration scenarios.| +| parameters | Record\ | No | List of parameters in the **Want** object.
1. The values of the following keys are assigned by the system. Manual settings do not take effect, since the system automatically changes the values to the actual values during data transfer.
- **ohos.aafwk.param.callerPid**: PID of the caller. The value is a string.
- **ohos.aafwk.param.callerBundleName**: bundle name of the caller. The value is a string.
- **ohos.aafwk.param.callerAbilityName**: ability name of the caller. The value is a string.
- **ohos.aafwk.param.callerNativeName**: process name of the caller when the native method is called. The value is a string.
- **ohos.aafwk.param.callerAppId**: appId of the caller. The value is a string.
- **ohos.aafwk.param.callerAppIdentifier**: appIdentifier of the caller. The value is a string.
- **ohos.aafwk.param.callerToken**: token of the caller. The value is a string.
- **ohos.aafwk.param.callerUid**: UID in [BundleInfo](js-apis-bundleManager-bundleInfo.md#bundleinfo-1), that is, the application's UID in the bundle information. The value is a number.
- **ohos.param.callerAppCloneIndex**: clone index of the caller. The value is of the numeric type.
- **component.startup.newRules**: enabled status of the new control rule. The value is of the Boolean type.
- **moduleName**: module name of the caller. The value is a string.
- **ability.params.backToOtherMissionStack**: support for redirection back across mission stacks. The value is of the Boolean type.
- **ohos.ability.params.abilityRecoveryRestart**: support for ability restart upon fault recovery. The value is of the Boolean type.
- **ohos.extra.param.key.contentTitle**: title that can be shared by the atomic service. The value is a string.
- **ohos.extra.param.key.shareAbstract**: content that can be shared by the atomic service. The value is a string.
- **ohos.extra.param.key.shareUrl**: URL of the content that can be shared by the atomic service. The value is a string.
- **ohos.extra.param.key.supportContinuePageStack**: support for migration of page stack information during cross-device migration. The value is of the Boolean type. The default value is **true**, indicating that page stack information is automatically migrated.
- **ohos.extra.param.key.supportContinueSourceExit**: support for application exit on the source device during cross-device migration. The value is of the Boolean type. The default value is **true**, indicating that the application on the source device automatically exits.
- **ohos.extra.param.key.showMode**: mode to show the atomic service startup. The value is an enumerated value of [wantConstant.ShowMode](js-apis-app-ability-wantConstant.md#showmode12).
- **ohos.dlp.params.sandbox**: available only for DLP files. This key is involved only in system applications.
- **ohos.dlp.params.bundleName**: bundle name of DLP. The value is a string. This key is involved only in system applications.
- **ohos.dlp.params.moduleName**: module name of DLP. The value is a string. This key is involved only in system applications.
- **ohos.dlp.params.abilityName**: ability name of DLP. The value is a string. This key is involved only in system applications.
- **ohos.dlp.params.index**: DLP index. The value is a number. This key is involved only in system applications.
- **ohos.ability.params.asssertFaultSessionId**: session ID of the fault assertion. The value is a string. This key is involved only in system applications.

2. The following keys are defined by the system, and their values need to be manually assigned.
- **ability.params.stream**: File URIs to be authorized to the target ability. The value is a file URI array of the string type.
- **ohos.extra.param.key.appCloneIndex**: index of the application clone.

3. In addition to the foregoing cases, applications may further agree on the key-value pairs to transfer.

**NOTE**
For details about the constants of **Params** in **want**, see [wantConstant](js-apis-app-ability-wantConstant.md).
Note that a maximum of 200 KB data that can be transferred by using **WantParams**. If the data volume exceeds 200 KB, transfer data in [WriteRawDataBuffer](../apis-ipc-kit/js-apis-rpc.md#writerawdatabuffer11) or [uri](../apis-arkts/js-apis-uri.md) mode.
The values of **parameters** must be of the following basic data types: String, Number, Boolean, Object, undefined, and null. Functions in an object cannot be transferred.| +| [flags](js-apis-app-ability-wantConstant.md#flags) | number | No| How the **Want** object will be handled. By default, a number is passed in.
For example, **wantConstant.Flags.FLAG_ABILITY_CONTINUATION** specifies whether to start the ability in cross-device migration scenarios.| +| fds15+ | Record\ | No| Want file descriptor (FD), which is used to identify the Want file opened. You can obtain the FD from [fs.open](../apis-core-file-kit/js-apis-file-fs.md#fsopen). When the FD is no longer needed, you must call [fs.close](../apis-core-file-kit/js-apis-file-fs.md#fsclose) to destroy the FD in a timely manner to prevent FD leakage.
**Atomic service API**: This API can be used in atomic services since API version 15.| **Example** @@ -44,7 +45,7 @@ import { Want } from '@kit.AbilityKit'; deviceId: '', // An empty deviceId indicates the local device. bundleName: 'com.example.myapplication', abilityName: 'FuncAbility', - moduleName: 'entry', // moduleName is optional. + moduleName: 'entry' // moduleName is optional. }; context.startAbility(want, (err: BusinessError) => { @@ -203,55 +204,56 @@ import { Want } from '@kit.AbilityKit'; - **parameter** usage: **parameter** carries custom parameters. It is transferred by UIAbilityA to UIAbilityB and obtained from UIAbilityB. - ```ts - // (1) UIAbilityA calls startAbility to start UIAbilityB. - import { common, Want } from '@kit.AbilityKit'; - import { BusinessError } from '@kit.BasicServicesKit'; + ```ts + // (1) UIAbilityA calls startAbility to start UIAbilityB. + import { common, Want } from '@kit.AbilityKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + let context = getContext(this) as common.UIAbilityContext; // UIAbilityContext + let want: Want = { + bundleName: 'com.example.myapplication', + abilityName: 'UIAbilityB', + parameters: { + developerParameters: 'parameters', + }, + }; - let context = getContext(this) as common.UIAbilityContext; // UIAbilityContext - let want: Want = { - bundleName: 'com.example.myapplication', - abilityName: 'UIAbilityB', - parameters: { - developerParameters: 'parameters', - }, - }; - - context.startAbility(want, (err: BusinessError) => { - if (err.code) { - console.error(`Failed to startAbility. Code: ${err.code}, message: ${err.message}`); - } - }); - ``` - - ```ts - // (2) If the UIAbilityB instance is started for the first time, it enters the onCreate lifecycle. - import { UIAbility, Want, AbilityConstant } from '@kit.AbilityKit'; - - class UIAbilityB extends UIAbility { - onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { - console.log(`onCreate, want parameters: ${want.parameters?.developerParameters}`); - } - } - ``` + context.startAbility(want, (err: BusinessError) => { + if (err.code) { + console.error(`Failed to startAbility. Code: ${err.code}, message: ${err.message}`); + } + }); + ``` + + ```ts + // (2) If the UIAbilityB instance is started for the first time, it enters the onCreate lifecycle. + import { UIAbility, Want, AbilityConstant } from '@kit.AbilityKit'; + + class UIAbilityB extends UIAbility { + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { + console.log(`onCreate, want parameters: ${want.parameters?.developerParameters}`); + } + } + ``` + - Usage of the keys of [wantConstant](js-apis-app-ability-wantConstant.md) in **parameter**. - ```ts - import { common, Want, wantConstant } from '@kit.AbilityKit'; - import { BusinessError } from '@kit.BasicServicesKit'; - - let context = getContext(this) as common.UIAbilityContext; // UIAbilityContext - let want: Want = { - bundleName: 'com.example.myapplication', - abilityName: 'FuncAbility', - parameters: { - [wantConstant.Params.CONTENT_TITLE_KEY]: 'contentTitle', - }, - }; - - context.startAbility(want, (err: BusinessError) => { - if (err.code) { - console.error(`Failed to startAbility. Code: ${err.code}, message: ${err.message}`); - } - }); - ``` + ```ts + import { common, Want, wantConstant } from '@kit.AbilityKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + let context = getContext(this) as common.UIAbilityContext; // UIAbilityContext + let want: Want = { + bundleName: 'com.example.myapplication', + abilityName: 'FuncAbility', + parameters: { + [wantConstant.Params.CONTENT_TITLE_KEY]: 'contentTitle', + }, + }; + + context.startAbility(want, (err: BusinessError) => { + if (err.code) { + console.error(`Failed to startAbility. Code: ${err.code}, message: ${err.message}`); + } + }); + ``` diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-wantAgent-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-wantAgent-sys.md index c323f131430cc3e66ed4479ff60cb046e13204f2..9eb4e6fc01ee3449aee68e04dd7d3c470acf8c9a 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-wantAgent-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-wantAgent-sys.md @@ -22,7 +22,7 @@ Obtains the Want in a **WantAgent** object. This API uses an asynchronous callba **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -73,7 +73,7 @@ let wantAgentInfo: wantAgent.WantAgentInfo = { } } as Want ], - operationType: wantAgent.OperationType.START_ABILITIES, + actionType: wantAgent.OperationType.START_ABILITIES, requestCode: 0, wantAgentFlags:[wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] }; @@ -81,29 +81,33 @@ let wantAgentInfo: wantAgent.WantAgentInfo = { // getWantAgent callback function getWantAgentCallback(err: BusinessError, data: _WantAgent) { if (err) { - console.info(`getWantAgent failed, code: ${JSON.stringify(err.code)}, message: ${JSON.stringify(err.message)}`); + console.info(`getWantAgent failed, code: ${err.code}, message: ${err.message}`); } else { wantAgentData = data; } // getWant callback let getWantCallback = (err: BusinessError, data: Want) => { if(err) { - console.error(`getWant failed! ${err.code} ${err.message}`); + console.error(`getWant failed, code: ${err.code}, messgae: ${err.message}.`); } else { - console.info(`getWant ok! ${JSON.stringify(data)}`); + console.info(`getWant success, data: ${JSON.stringify(data)}.`); } } try { wantAgent.getWant(wantAgentData, getWantCallback); } catch(err) { - console.error(`getWant failed! ${err.code} ${err.message}`); + let code = (err as BusinessError).code; + let msg = (err as BusinessError).message; + console.error(`getWant failed, code: ${code}, message: ${msg}.`); } } try { wantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); } catch(err) { - console.error(`getWantAgent failed! ${err.code} ${err.message}`); + let code = (err as BusinessError).code; + let msg = (err as BusinessError).message; + console.error(`getWantAgent failed, code: ${code}, message: ${msg}.`); } ``` @@ -117,7 +121,7 @@ Obtains the Want in a **WantAgent** object. This API uses a promise to return th **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -175,7 +179,7 @@ let wantAgentInfo: wantAgent.WantAgentInfo = { } } as Want ], - operationType: wantAgent.OperationType.START_ABILITIES, + actionType: wantAgent.OperationType.START_ABILITIES, requestCode: 0, wantAgentFlags:[wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] }; @@ -183,27 +187,115 @@ let wantAgentInfo: wantAgent.WantAgentInfo = { // getWantAgent callback function getWantAgentCallback(err: BusinessError, data: _WantAgent) { if (err) { - console.info(`getWantAgent failed, code: ${JSON.stringify(err.code)}, message: ${JSON.stringify(err.message)}`); + console.info(`getWantAgent failed, code: ${err.code}, message: ${err.message}`); } else { wantAgentData = data; } try { - wantAgent.getUid(wantAgentData).then((data)=>{ - console.info(`getUid ok! ${JSON.stringify(data)}`); + wantAgent.getWant(wantAgentData).then((data)=>{ + console.info(`getWant success, data: ${JSON.stringify(data)}`); }).catch((err: BusinessError)=>{ - console.error(`getUid failed! ${err.code} ${err.message}`); + console.error(`getWant failed, code: ${err.code}, messgae: ${err.message}.`); }); } catch(err){ - console.error(`getUid failed! ${err.code} ${err.message}`); + let code = (err as BusinessError).code; + let msg = (err as BusinessError).message; + console.error(`getWant failed, code: ${code}, messgae: ${msg}.`); } } try { wantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); } catch(err) { - console.error(`getWantAgent failed! ${err.code} ${err.message}}`); + let code = (err as BusinessError).code; + let msg = (err as BusinessError).message; + console.error(`getWantAgent failed, code: ${code}, messgae: ${msg}.`); } ``` + +## WantAgent.setWantAgentMultithreading18+ + +setWantAgentMultithreading(isMultithreadingSupported: boolean) : void + +Enables or disables the WantAgent multithreading feature. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | --------------------- | ---- | ------------------------------- | +| isMultithreadingSupported | boolean | Yes |Whether to enable the multithreading feature. The value **true** means to enable multithreading, and **false** means the opposite. | + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID | Error Message | +|-----------|--------------------| +| 202 | Not system app. Interface caller is not a system app. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | + +**Example** + +```ts +import { wantAgent, WantAgent as _WantAgent, Want } from '@kit.AbilityKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +// Define a wantAgent object. +let wantAgentData: _WantAgent; +// Define a WantAgentInfo object. +let wantAgentInfo: wantAgent.WantAgentInfo = { + wants: [ + { + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', + mykey4: [false, true, false], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], + mykey6: true, + } + } as Want + ], + actionType: wantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +}; + +// Define a getWantAgent callback. +function getWantAgentCallback(err: BusinessError, data: _WantAgent) { + if (err) { + console.info(`Failed to call getWantAgentCallback. Code is ${err.code}. Message is ${err.message}.`); + } else { + wantAgentData = data; + } + + try { + wantAgent.setWantAgentMultithreading(true); + } catch (err) { + console.error(`Failed to set wantAgentMultithreading. Code is ${err.code}. Message is ${err.message}.`); + } +} + +try { + wantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); +} catch (err) { + console.error(`Failed to get wantAgent. Code is ${err.code}. Message is ${err.message}.`); +} +``` + ## OperationType Enumerates the operation types of the **WantAgent** objects. diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-wantAgent.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-wantAgent.md index 30340c8b62a7e0dadc499920d1ae0e67362efdcc..f6f940b058a02ed122375c75b87533e57d7752c6 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-wantAgent.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-wantAgent.md @@ -809,29 +809,33 @@ let wantAgentInfo: wantAgent.WantAgentInfo = { // getWantAgent callback function getWantAgentCallback(err: BusinessError, data: WantAgent) { if (err) { - console.info(`getWantAgent failed, code: ${JSON.stringify(err.code)}, message: ${JSON.stringify(err.message)}`); + console.info(`getWantAgent failed, code: ${err.code}, message: ${err.message}`); } else { wantAgentData = data; } // trigger callback let triggerCallback = (err: BusinessError, data: wantAgent.CompleteData) => { if (err) { - console.error(`getUid failed! ${err.code} ${err.message}`); + console.error(`trigger failed, code: ${err.code}, message: ${err.message}`); } else { - console.info(`getUid ok! ${JSON.stringify(data)}`); + console.info(`trigger success, data: ${JSON.stringify(data)}`); } } try { wantAgent.trigger(wantAgentData, triggerInfo, triggerCallback); } catch (err) { - console.error(`getUid failed! ${err.code} ${err.message}`); + let code = (err as BusinessError).code; + let msg = (err as BusinessError).message; + console.error(`trigger failed, code: ${code}, message: ${msg}.`); } } try { wantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); } catch (err) { - console.error(`getWantAgent failed! ${(err as BusinessError).code} ${(err as BusinessError).message}`); + let code = (err as BusinessError).code; + let msg = (err as BusinessError).message; + console.error(`getWantAgent failed, code: ${code}, message: ${msg}.`); } ``` @@ -1268,6 +1272,48 @@ Describes the data returned by the operation of proactive triggering a WantAgent | -------- | -------- | -------- | -------- | -------- | | info | WantAgent | No| No | WantAgent object that is triggered. | | want | [Want](js-apis-app-ability-want.md#properties) | No| No | Existing Want that is triggered. | -| finalCode | number | No| No | Execution result of the triggering operation.
- In ability startup scenarios (where [OperationType](#operationtype) is set to **1**, **2**, or **3**), **finalCode** is **0** for a successful execution. For details about the value of **finalCode** returned in the case of execution failures, see [Ability Error Codes](errorcode-ability.md).
- In common event publish scenarios (where [OperationType](#operationtype) is set to **4**), **finalCode** is **0** for a successful execution. For details about the value of **finalCode** returned in the case of execution failures, see [Event Error Codes](../apis-basic-services-kit/errorcode-CommonEventService.md).| +| finalCode | number | No| No | Request code that triggers the WantAgent object.| | finalData | string | No| No | Final data collected by the common event. | | extraInfo | Record\ | No|Yes | Extra information. | + +## TriggerInfo + +type TriggerInfo = _TriggerInfo + +Defines the TriggerInfo object. + +**Atomic service API**: This API can be used in atomic services since API version 12. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Type| Description| +| --- | --- | +| [_TriggerInfo](js-apis-inner-wantAgent-triggerInfo.md) | TriggerInfo object.| + +## WantAgentInfo + +type WantAgentInfo = _WantAgentInfo + +Defines the WantAgentInfo object. + +**Atomic service API**: This API can be used in atomic services since API version 12. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Type| Description| +| --- | --- | +| [_WantAgentInfo](js-apis-inner-wantAgent-wantAgentInfo.md) | WantAgentInfo object.| + +## WantAgent + +type WantAgent = object + +Target WantAgent object. + +**Atomic service API**: This API can be used in atomic services since API version 12. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Type| Description| +| --- | --- | +| object | Target WantAgent object.| diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-wantConstant-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-wantConstant-sys.md index c48a7181abb14703fc82098983382b4479989d68..634c54511559c483b59db911d77084ff0e763bd3 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-wantConstant-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-wantConstant-sys.md @@ -22,9 +22,9 @@ Defines **Params** (specifying the action that can be performed) in the Want. | Name | Value | Description | | ----------------------- | ---------------------------------- | ------------------------------------------------------------------------------ | -| DLP_PARAMS_SANDBOX | ohos.dlp.params.sandbox | Action of obtaining the sandbox flag.
**System API**: This is a system API and cannot be called by third-party applications.| -| DLP_PARAMS_BUNDLE_NAME | ohos.dlp.params.bundleName | Action of obtaining the DLP bundle name.
**System API**: This is a system API and cannot be called by third-party applications.| -| DLP_PARAMS_MODULE_NAME | ohos.dlp.params.moduleName | Action of obtaining the DLP module name.
**System API**: This is a system API and cannot be called by third-party applications.| -| DLP_PARAMS_ABILITY_NAME | ohos.dlp.params.abilityName | Action of obtaining the DLP ability name.
**System API**: This is a system API and cannot be called by third-party applications.| -| DLP_PARAMS_INDEX | ohos.dlp.params.index | Action of obtaining the DLP index.
**System API**: This is a system API and cannot be called by third-party applications.| -| ASSERT_FAULT_SESSION_ID12+ | ohos.ability.params.asssertFaultSessionId | Session ID of the AssertFault.
**System API**: This is a system API and cannot be called by third-party applications.| +| DLP_PARAMS_SANDBOX | ohos.dlp.params.sandbox | Action of obtaining the sandbox flag.
**System API**: This is a system API.| +| DLP_PARAMS_BUNDLE_NAME | ohos.dlp.params.bundleName | Action of obtaining the DLP bundle name.
**System API**: This is a system API.| +| DLP_PARAMS_MODULE_NAME | ohos.dlp.params.moduleName | Action of obtaining the DLP module name.
**System API**: This is a system API.| +| DLP_PARAMS_ABILITY_NAME | ohos.dlp.params.abilityName | Action of obtaining the DLP ability name.
**System API**: This is a system API.| +| DLP_PARAMS_INDEX | ohos.dlp.params.index | Action of obtaining the DLP index.
**System API**: This is a system API.| +| ASSERT_FAULT_SESSION_ID12+ | ohos.ability.params.asssertFaultSessionId | Session ID of the AssertFault.
**System API**: This is a system API.| diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-wantConstant.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-wantConstant.md index ac69d07ca6b3b81be0780345b9f2c8628987d92a..a84e2e2f02cdbb528c5f88794de4d8796414a594 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-wantConstant.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-ability-wantConstant.md @@ -31,10 +31,15 @@ Defines **Params** (specifying the action that can be performed) in the Want. | PARAMS_STREAM12+ | ability.params.stream | File URIs to be authorized to the target ability. The value must be an array of file URIs of the string type. For details about how to obtain the file URI, see [fileUri](../apis-core-file-kit/js-apis-file-fileuri.md#fileurigeturifrompath).
**Atomic service API**: This API can be used in atomic services since API version 12.| | APP_CLONE_INDEX_KEY12+ | ohos.extra.param.key.appCloneIndex | Index of an application clone.
**Atomic service API**: This API can be used in atomic services since API version 12.| | CALLER_REQUEST_CODE12+ | ohos.extra.param.key.callerRequestCode | Request code that uniquely identifies the caller of [startAbilityForResult](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartabilityforresult) or [openLink](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextopenlink12). When either of the APIs is called to start an ability, the target ability returns the result to the caller based on the request code.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| PAGE_PATH12+ | ohos.param.atomicservice.pagePath | Path of page parameters.
**Atomic service API**: This API can be used in atomic services since API version 12. | +| ROUTER_NAME12+ | ohos.param.atomicservice.routerName | Name of the page router.
**Atomic service API**: This API can be used in atomic services since API version 12. | +| PAGE_SOURCE_FILE12+ | ohos.param.atomicservice.pageSourceFile | Source file of the page.
**Atomic service API**: This API can be used in atomic services since API version 12. | +| BUILD_FUNCTION12+ | ohos.param.atomicservice.buildFunction | Build function.
**Atomic service API**: This API can be used in atomic services since API version 12. | +| SUB_PACKAGE_NAME12+ | ohos.param.atomicservice.subpackageName | Name of a subpackage.
**Atomic service API**: This API can be used in atomic services since API version 12. | | APP_INSTANCE_KEY14+ | ohos.extra.param.key.appInstance | Specific application instance.| | CREATE_APP_INSTANCE_KEY14+ | ohos.extra.param.key.createAppInstance | Action of creating an application instance.| | CALLER_APP_CLONE_INDEX14+ | ohos.param.callerAppCloneIndex | Clone index of the caller.| -| LAUNCH_REASON_MESSAGE16+ | ohos.params.launchReasonMessage | Reason for starting the ability when the caller starts the target ability. The caller must be a system application and must request the ohos.permission.SET_LAUNCH_REASON_MESSAGE permission.
**Atomic service API**: This API can be used in atomic services since API version 16.| +| LAUNCH_REASON_MESSAGE18+ | ohos.params.launchReasonMessage | Reason for starting the ability when the caller starts the target ability. The caller must be a system application and must request the ohos.permission.SET_LAUNCH_REASON_MESSAGE permission. Currently, the value can only be **ReasonMessage_SystemShare**.
**Atomic service API**: This API can be used in atomic services since API version 18.| ## Flags @@ -46,9 +51,11 @@ Defines **Params** (specifying the action that can be performed) in the Want. | ------------------------------------ | ---------- | ------------------------------------------------------------ | | FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | Grant the permission to read the URI.
**Atomic service API**: This API can be used in atomic services since API version 11. | | FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Grant the permission to write data to the URI.
**Atomic service API**: This API can be used in atomic services since API version 11. | -| FLAG_AUTH_PERSISTABLE_URI_PERMISSION12+ | 0x00000040 | Make the URI persistent. It takes effect only on tablets.| +| FLAG_AUTH_PERSISTABLE_URI_PERMISSION12+ | 0x00000040 | Make the URI persistent. It takes effect only on 2-in-1 devices and tablets.| | FLAG_INSTALL_ON_DEMAND | 0x00000800 | Install the ability if it has not been installed.
**Atomic service API**: This API can be used in atomic services since API version 11. | | FLAG_START_WITHOUT_TIPS11+ | 0x40000000 | Do not display any tips if the ability implicitly started does not match any application. | +| FLAG_ABILITY_ON_COLLABORATE18+ | 0x00002000 | In multi-device collaboration scenario, the caller application must initiate a request through the DMS, with this flag included in the **Flags** field, in order to invoke the lifecycle callback [onCollaborate(wantParam)](js-apis-app-ability-uiAbility.md#uiabilityoncollaborate18) of the target application.| + ## ShowMode12+ Enumerates the modes used to show the atomic service startup. diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-appstartup-startupConfigEntry.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-appstartup-startupConfigEntry.md index 04b286ae267ba4f9747739aaec89eb73686dfcaf..a2926078d8676705cc715abe34815564d2da288f 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-appstartup-startupConfigEntry.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-appstartup-startupConfigEntry.md @@ -25,9 +25,9 @@ Called during application startup to configure AppStartup. **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| StartupConfig | AppStartup configuration. | +| StartupConfig | AppStartup configuration.| **Example** diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-appstartup-startupListener.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-appstartup-startupListener.md index 1fa556bc97d2070d4e2eff8a41cf3f19774139f1..e46d0119c1e23d2c424ed37aca45e4ea8476c7ff 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-appstartup-startupListener.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-appstartup-startupListener.md @@ -25,9 +25,9 @@ Called when all startup tasks are complete. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| error | [BusinessError](../apis-basic-services-kit/js-apis-base.md#businesserror) | Yes | Error message. | +| error | [BusinessError](../apis-basic-services-kit/js-apis-base.md#businesserror) | Yes| Error message.| **Example** diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-appstartup-startupManager.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-appstartup-startupManager.md index dc41fc60c4b25a688631612192df9bea26efad61..3bdc9afd3074ad5cfabf80ace7ed2d8d7403f53b 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-appstartup-startupManager.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-appstartup-startupManager.md @@ -1,11 +1,13 @@ # @ohos.app.appstartup.startupManager -The startupManager module provides APIs for AppStartup to manage startup tasks. It can be called only in the main thread. +The startupManager module provides APIs to manage startup tasks in AppStartup. It can be called only in the main thread. > **NOTE** > > The initial APIs of this module are supported since API version 12. Newly added APIs will be marked with a superscript to indicate their earliest API version. > +> This module supports .so file preloading since API version 18. +> > The APIs of this module can be used only in the stage model. ## Modules to Import @@ -17,28 +19,28 @@ import { startupManager } from '@kit.AbilityKit'; ## startupManager.run run(startupTasks: Array\, config?: StartupConfig): Promise\ -Runs AppStartup. +Runs startup tasks or loads .so files. **System capability**: SystemCapability.Ability.AppStartup **Parameters** - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | startupTasks | Array\ | Yes | Array of class names of the [StartupTask](js-apis-app-appstartup-startupTask.md) API implemented by the startup tasks to be executed. | - | config | [StartupConfig](./js-apis-app-appstartup-startupConfig.md) | No | Timeout for starting AppStartup and startup task listener. | + | startupTasks | Array\ | Yes| Array of class names of the [StartupTask](js-apis-app-appstartup-startupTask.md) API implemented by the startup task and names of .so files to be preloaded.| + | config | [StartupConfig](./js-apis-app-appstartup-startupConfig.md) | No| Configuration for the AppStartup timeout and startup task listener.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise\ | Promise that returns no value. | +| Promise\ | Promise that returns no value.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). - | ID | Error Message | + | ID| Error Message| | ------- | -------------------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | | 16000050 | Internal error. | @@ -57,7 +59,7 @@ import { BusinessError } from '@kit.BasicServicesKit'; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); - let startParams = ['StartupTask_001']; + let startParams = ["StartupTask_001", "libentry_001"]; try { // Manually call the run method. startupManager.run(startParams).then(() => { @@ -84,6 +86,8 @@ removeAllStartupTaskResults(): void Removes all startup task results. +If there are preloading tasks for .so files, the corresponding .so files is set to the unloaded state. However, .so files that have already been loaded in the cache will not be removed. + **System capability**: SystemCapability.Ability.AppStartup **Example** @@ -96,7 +100,7 @@ import { hilog } from '@kit.PerformanceAnalysisKit'; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); - startupManager.run(['StartupTask_001']).then(() => { + startupManager.run(["StartupTask_001", "libentry_001"]).then(() => { console.info("StartupTask_001 init successful"); }) } @@ -121,27 +125,27 @@ export default class EntryAbility extends UIAbility { getStartupTaskResult(startupTask: string): Object -Obtains the result of a startup task. +Obtains the execution result of a startup task or .so file preloading task. **System capability**: SystemCapability.Ability.AppStartup **Parameters** - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | startupTask | string | Yes | Class name of the [StartupTask](js-apis-app-appstartup-startupTask.md) API implemented by the startup task. All the startup tasks must implement the [StartupTask](js-apis-app-appstartup-startupTask.md) API. | + | startupTask | string | Yes| Class name of the [StartupTask](js-apis-app-appstartup-startupTask.md) API implemented by the startup task or .so file name. All the startup tasks must implement the [StartupTask](js-apis-app-appstartup-startupTask.md) API.| **Return value** - | Type | Description | + | Type| Description| | -------- | -------- | - | Object | Result of the startup task. | + | Object | Execution result of the startup task if a startup task name is passed.
undefined if a .so file name is passed.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). - | ID | Error Message | + | ID| Error Message| | ------- | -------------------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | @@ -155,14 +159,14 @@ import { hilog } from '@kit.PerformanceAnalysisKit'; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); - startupManager.run(['StartupTask_001']).then(() => { + startupManager.run(["StartupTask_001"]).then(() => { console.info("StartupTask_001 init successful"); }) } onWindowStageCreate(windowStage: window.WindowStage) { hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); - let result = startupManager.getStartupTaskResult('StartupTask_001'); // Manually obtain the startup task result. + let result = startupManager.getStartupTaskResult("StartupTask_001"); // Manually obtain the startup task result. console.info("getStartupTaskResult result = " + result); windowStage.loadContent('pages/Index', (err, data) => { if (err.code) { @@ -180,27 +184,27 @@ export default class EntryAbility extends UIAbility { isStartupTaskInitialized(startupTask: string): boolean -Checks whether a startup task is initialized. +Checks whether a startup task or .so file preloading task is initialized. **System capability**: SystemCapability.Ability.AppStartup **Parameters** - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | startupTask | string | Yes | Class name of the [StartupTask](js-apis-app-appstartup-startupTask.md) API implemented by the startup task. | + | startupTask | string | Yes| Class name of the [StartupTask](js-apis-app-appstartup-startupTask.md) API implemented by the startup task or .so file name.| **Return value** - | Type | Description | + | Type| Description| | -------- | -------- | - | boolean | **true**: The startup task is initialized.
**false**: The startup task is not initialized. | + | boolean | Check result. The value **true** means that the task is initialized, and **false** means the opposite.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). - | ID | Error Message | + | ID| Error Message| | ------- | -------------------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | @@ -214,19 +218,25 @@ import { hilog } from '@kit.PerformanceAnalysisKit'; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); - startupManager.run(['StartupTask_001']).then(() => { + startupManager.run(["StartupTask_001", "libentry_001"]).then(() => { console.info("StartupTask_001 init successful"); }) } onWindowStageCreate(windowStage: window.WindowStage) { hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); - let result = startupManager.isStartupTaskInitialized('StartupTask_001'); - if (result) { + let result1 = startupManager.isStartupTaskInitialized('StartupTask_001'); + let result2 = startupManager.isStartupTaskInitialized('libentry_001'); + if (result1) { console.info("StartupTask_001 init successful"); } else { console.info("StartupTask_001 uninitialized"); } + if (result2) { + console.info("libentry_001 init successful"); + } else { + console.info("libentry_001 uninitialized"); + } windowStage.loadContent('pages/Index', (err, data) => { if (err.code) { @@ -243,21 +253,25 @@ export default class EntryAbility extends UIAbility { removeStartupTaskResult(startupTask: string): void -Removes the initialization result of a startup task. +Removes the initialization result of a startup task or .so file preloading task. + +- If a startup task name is passed, the initialization result of that startup task is removed. + +- If a .so file is passed, the .so file is set to the unloaded state, but the loaded .so file in the cache is not removed. **System capability**: SystemCapability.Ability.AppStartup **Parameters** - | Name | Type | Mandatory | Description | + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | startupTask | string | Yes | Class name of the [StartupTask](js-apis-app-appstartup-startupTask.md) API implemented by the startup task. | + | startupTask | string | Yes| Class name of the [StartupTask](js-apis-app-appstartup-startupTask.md) API implemented by the startup task or .so file name.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). - | ID | Error Message | + | ID| Error Message| | ------- | -------------------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | @@ -271,14 +285,15 @@ import { hilog } from '@kit.PerformanceAnalysisKit'; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); - startupManager.run(['StartupTask_001']).then(() => { + startupManager.run(["StartupTask_001", "libentry_001"]).then(() => { console.info("StartupTask_001 init successful"); }) } onWindowStageCreate(windowStage: window.WindowStage) { hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); - startupManager.removeStartupTaskResult('StartupTask_001'); + startupManager.removeStartupTaskResult("StartupTask_001"); + startupManager.removeStartupTaskResult("libentry_001"); windowStage.loadContent('pages/Index', (err, data) => { if (err.code) { diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-app-appstartup-startupTask.md b/en/application-dev/reference/apis-ability-kit/js-apis-app-appstartup-startupTask.md index 1f4d2209a8bdb38dd09230c4b9e873db105fd9a3..60e115db506147f69119af282f54ff524d1de9d2 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-app-appstartup-startupTask.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-app-appstartup-startupTask.md @@ -24,10 +24,10 @@ Called when the dependent startup task is complete. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| dependency | string | Yes | Name of the dependent startup task. | -| result | Object | Yes | Execution result of the dependent startup task. | +| dependency | string | Yes| Name of the dependent startup task.| +| result | Object | Yes| Execution result of the dependent startup task.| **Example** @@ -64,15 +64,15 @@ Initializes this startup task. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| context | [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) | Yes | Context of the ability stage. | +| context | [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) | Yes| Context of the ability stage.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise\ | Promise used to return the execution result. | +| Promise\ | Promise used to return the execution result.| **Example** @@ -89,7 +89,7 @@ export default class StartupTask_001 extends StartupTask { hilog.info(0x0000, 'testTag', 'StartupTask_001 init.'); // ... - return 'StartupTask_001'; + return "StartupTask_001"; } onDependencyCompleted(dependence: string, result: Object): void { diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-appControl-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-appControl-sys.md index d3a5a64dbf88e3f1491fee6ebbb3bdbd8f477eea..abbadcb483ea4ceb132da7d5f18cf4ebec632019 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-appControl-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-appControl-sys.md @@ -460,52 +460,6 @@ try { ## appControl.deleteDisposedStatusSync10+ -deleteDisposedStatusSync(appId: string) : void - -Deletes the disposed status for an application. This API returns the result synchronously. If the operation is successful, **null** is returned. If the operation fails, an error message is returned. - -**System API**: This is a system API. - -**Required permissions**: ohos.permission.MANAGE_DISPOSED_APP_STATUS - -**System capability**: SystemCapability.BundleManager.BundleFramework.AppControl - -**Parameters** - -| Name | Type | Mandatory | Description | -| ----------- | ------ | ---- | --------------------------------------- | -| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | - -**Error codes** - -For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). - -| ID| Error Message | -| ------ | -------------------------------------- | -| 201 | Permission denied. | -| 202 | Permission denied, non-system app called system api. | -| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.| -| 801 | Capability not supported. | -| 17700005 | The specified app ID is an empty string. | - -**Example** - -```ts -import appControl from '@ohos.bundle.appControl'; -import { BusinessError } from '@ohos.base'; - -let appId: string = "com.example.myapplication_xxxxx"; - -try { - appControl.deleteDisposedStatusSync(appId); -} catch (error) { - let message = (error as BusinessError).message; - console.error('deleteDisposedStatusSync failed ' + message); -} -``` - -## appControl.deleteDisposedStatusSync12+ - deleteDisposedStatusSync(appId: string, appIndex:? number) : void Deletes the disposed status for an application or an application clone. This API returns the result synchronously. If the operation is successful, **null** is returned. If the operation fails, an error message is returned. @@ -521,7 +475,7 @@ Deletes the disposed status for an application or an application clone. This API | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | --------------------------------------- | | appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | -| appIndex | number | No | Index of the application clone.
If this parameter is set to **0**, the API is used to delete the disposed status of the application. | +| appIndex12+ | number | No | Index of the application clone. The default value is **0**.
The value **0** means to delete the disposed status of the main application. A value greater than 0 means to delete the disposed status of the application clone. | **Error codes** @@ -581,60 +535,6 @@ try { ## appControl.getDisposedRule11+ -getDisposedRule(appId: string): DisposedRule - -Obtains the disposed rule of an application. - -**System API**: This is a system API. - -**Required permissions**: ohos.permission.MANAGE_DISPOSED_APP_STATUS - -**System capability**: SystemCapability.BundleManager.BundleFramework.AppControl - -**Parameters** - -| Name | Type | Mandatory | Description | -| ----------- | ------ | ---- | --------------------------------------- | -| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | - -**Return value** - -| Type | Description | -| ------------------------- | ------------------ | -| [DisposedRule](#disposedrule11) | Disposed rule of the application.| - -**Error codes** - -For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). - -| ID| Error Message | -| ------ | -------------------------------------- | -| 201 | Permission denied. | -| 202 | Permission denied, non-system app called system api. | -| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.| -| 801 | Capability not supported. | -| 17700005 | The specified app ID is an empty string. | - -**Example** - -```ts -import appControl from '@ohos.bundle.appControl'; -import { BusinessError } from '@ohos.base'; -import Want from '@ohos.app.ability.Want'; - -let appId = "com.example.myapplication_xxxxx"; - -try { - let data = appControl.getDisposedRule(appId); - console.info('getDisposedRule successfully. Data: ' + JSON.stringify(data)); -} catch (error) { - let message = (error as BusinessError).message; - console.error('getDisposedRule failed ' + message); -} -``` - -## appControl.getDisposedRule12+ - getDisposedRule(appId: string, appIndex:? number): DisposedRule Obtains the disposed rule of an application or an application clone. @@ -650,7 +550,7 @@ Obtains the disposed rule of an application or an application clone. | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | --------------------------------------- | | appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | -| appIndex | number | No | Index of the application clone.
If this parameter is set to **0**, the API is used to obtain the disposed rule of an application, rather than an application clone. | +| appIndex12+ | number | No | Index of the application clone. The default value is **0**.
The value **0** means to obtain the disposed rule of the main application. A value greater than 0 means to obtain the disposed rule of the application clone. | **Return value** @@ -691,75 +591,6 @@ try { ## appControl.setDisposedRule11+ -setDisposedRule(appId: string, rule: DisposedRule): void - -Sets a disposed rule for an application. - -**System API**: This is a system API. - -**Required permissions**: ohos.permission.MANAGE_DISPOSED_APP_STATUS - -**System capability**: SystemCapability.BundleManager.BundleFramework.AppControl - -**Parameters** - -| Name | Type | Mandatory | Description | -| ----------- | ------ | ---- | --------------------------------------- | -| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | -| rule | [DisposedRule](#disposedrule11) | Yes| Disposed rule to set.| - -**Error codes** - -For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). - -| ID| Error Message | -| ------ | -------------------------------------- | -| 201 | Permission denied. | -| 202 | Permission denied, non-system app called system api. | -| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.| -| 801 | Capability not supported. | -| 17700005 | The specified app ID is an empty string. | - -**Example** - -```ts -import appControl from '@ohos.bundle.appControl'; -import { BusinessError } from '@ohos.base'; -import Want from '@ohos.app.ability.Want'; -import bundleManager from '@ohos.bundle.bundleManager'; - -let appId = "com.example.myapplication_xxxxx"; -let want: Want = { - bundleName: "com.example.myapplication", - moduleName: "entry", - abilityName: "EntryAbility" -}; -let elementName: bundleManager.ElementName = { - bundleName: "com.example.myapplication", - moduleName: "entry", - abilityName: "EntryAbility" -}; -let rule: appControl.DisposedRule = { - want: want, - componentType: appControl.ComponentType.UI_ABILITY, - disposedType: appControl.DisposedType.BLOCK_APPLICATION, - controlType: appControl.ControlType.ALLOWED_LIST, - elementList: [ - elementName - ], - priority: 100 -}; - -try { - appControl.setDisposedRule(appId, rule); -} catch (error) { - let message = (error as BusinessError).message; - console.error('setDisposedRule failed ' + message); -} -``` - -## appControl.setDisposedRule12+ - setDisposedRule(appId: string, rule: DisposedRule, appIndex:? number): void Sets the disposed rule for an application or an application clone. @@ -776,7 +607,7 @@ Sets the disposed rule for an application or an application clone. | ----------- | ------ | ---- | --------------------------------------- | | appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | | rule | [DisposedRule](#disposedrule11) | Yes| Disposed rule to set.| -| appIndex | number | No | Index of the application clone.
If this parameter is set to **0**, the API is used to set the disposed rule for an application, rather than an application clone. | +| appIndex12+ | number | No | Index of the application clone. The default value is **0**.
The value **0** means to set the disposed rule for the main application. A value greater than 0 means to set the disposed rule for the application clone. | **Error codes** @@ -847,7 +678,7 @@ Sets an uninstallation disposed rule for an application or an application clone. | ----------- | ------ | ---- | --------------------------------------- | | appIdentifier | string | Yes | appIdentifier of the target application.
If the application does not have an appIdentifier, use its appId instead. **appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | | rule | [UninstallDisposedRule](#uninstalldisposedrule15) | Yes| Uninstallation disposed rule.| -| appIndex | number | No | Index of the application clone.
When this parameter is set to **0**, an uninstallation disposed rule is set for an application, rather than an application clone. | +| appIndex | number | No | Index of the application clone. The default value is **0**.
The value **0** means to set the uninstallation disposed rule for the main application. A value greater than 0 means to set the uninstallation disposed rule for the application clone. | **Error codes** @@ -907,7 +738,7 @@ Obtains the uninstallation disposed rule of an application or an application clo | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | --------------------------------------- | | appIdentifier | string | Yes | appIdentifier of the target application.
If the application does not have an appIdentifier, use its appId instead. **appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | -| appIndex | number | No | Index of the application clone.
When this parameter is set to **0**, the uninstallation disposed rule of an application, rather than an application clone, is obtained. | +| appIndex | number | No | Index of the application clone. The default value is **0**.
The value **0** means to obtain the uninstallation disposed rule of the main application. A value greater than 0 means to obtain the uninstallation disposed rule of the application clone. | **Return value** @@ -962,7 +793,7 @@ Deletes an uninstallation disposed rule for an application or an application clo | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | --------------------------------------- | | appIdentifier | string | Yes | appIdentifier of the target application.
If the application does not have an appIdentifier, use its appId instead. **appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | -| appIndex | number | No | Index of the application clone.
When this parameter is set to **0**, the uninstallation disposed rule of an application, rather than an application clone, is deleted. | +| appIndex | number | No | Index of the application clone. The default value is **0**.
The value **0** means to delete the uninstallation disposed rule of the main application. A value greater than 0 means to delete the uninstallation disposed rule of the application clone. | **Error codes** diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-appDomainVerify-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-appDomainVerify-sys.md index 15aed611819e87d3a04bc9b1c36271488bcec194..5a1788db41b22c4fb8e53702317a2261701999e7 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-appDomainVerify-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-appDomainVerify-sys.md @@ -46,7 +46,7 @@ Queries the list of domain names associated with an application based on its bun **Error codes** -For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Application Domain Name Verification Error Codes](errorcode-appDomainVerify.md.md). +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Application Domain Name Verification Error Codes](errorcode-appDomainVerify.md). | ID| Error Message | | -------- | ----------------------------------------- | @@ -94,7 +94,7 @@ Obtains the list of bundle names associated with a domain name. **Error codes** -For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Application Domain Name Verification Error Codes](errorcode-appDomainVerify.md.md). +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Application Domain Name Verification Error Codes](errorcode-appDomainVerify.md). | ID| Error Message | | -------- | ----------------------------------------- | diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-application-appManager-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-application-appManager-sys.md index 66464c1e997760f5d268c1fc136273b40e413390..c2ac63d86026d07858a42847a098ae986b842f02 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-application-appManager-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-application-appManager-sys.md @@ -6,7 +6,7 @@ The **appManager** module implements application management. You can use the API > > The APIs of this module are supported since API version 8 and deprecated since API version 9. You are advised to use [@ohos.app.ability.appManager](js-apis-app-ability-appManager.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. > -> This topic describes only system APIs provided by the module. For details about its public APIs, see [@ohos.application.appManager (appManager)](js-apis-app-ability-wantConstant.md). +> This topic describes only system APIs provided by the module. For details about its public APIs, see [@ohos.application.appManager (appManager)](js-apis-application-appManager.md). ## Modules to Import diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-application-configurationConstant.md b/en/application-dev/reference/apis-ability-kit/js-apis-application-configurationConstant.md index 80d03871e4db58dbeccc2ada39f5e0ecba779a02..d1346ca823d968d8aec1a730c1b75b5902c5c87a 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-application-configurationConstant.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-application-configurationConstant.md @@ -1,6 +1,6 @@ # @ohos.application.ConfigurationConstant (ConfigurationConstant) -The **ConfigurationConstant** module provides the enumerated values of the environment configuration information. +The ConfigurationConstant module provides the enumerated values of the environment configuration information. > **NOTE** > diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-application-want.md b/en/application-dev/reference/apis-ability-kit/js-apis-application-want.md index 81a1face17a085fc6e4ee4e990187dacf0376edc..2712417a2d7d5051744812302eff8d5cbdc5f7bc 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-application-want.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-application-want.md @@ -1,6 +1,6 @@ # @ohos.application.Want (Want) -Want is a carrier for information transfer between objects (application components). Want can be used as a parameter of **startAbility()** to specify a startup target and information that needs to be carried during startup, for example, **bundleName** and **abilityName**, which respectively indicate the bundle name of the target ability and the ability name in the bundle. When ability A needs to start ability B and transfer some data to ability B, it can use Want a carrier to transfer the data. +Want is a carrier for information transfer between objects (application components). Want can be used as a parameter of **startAbility** to specify a startup target and information that needs to be carried during startup, for example, **bundleName** and **abilityName**, which respectively indicate the bundle name of the target ability and the ability name in the bundle. When ability A needs to start ability B and transfer some data to ability B, it can use Want a carrier to transfer the data. > **NOTE** > @@ -21,7 +21,7 @@ import Want from '@ohos.application.Want'; | deviceId | string | No | ID of the device running the ability. If this field is unspecified, the local device is used. | | bundleName | string | No | Bundle name.| | abilityName | string | No | Name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability. The value of **abilityName** must be unique in an application.| -| uri | string | No | URI information to match. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.| +| uri | string | No | URI information to match. If **Uri** is specified in a Want object, the Want object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.| | type | string | No | MIME type, that is, the type of the file to open, for example, **'text/xml'** and **'image/*'**. For details about the MIME type definition, see https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com. | | flags | number | No | How the **Want** object will be handled. By default, numbers are passed in. For details, see [flags](js-apis-ability-wantConstant.md#flags).| | action | string | No | Action to take, such as viewing and sharing application details. In implicit **Want**, you can define this property and use it together with **uri** or **parameters** to specify the operation to be performed on the data. For details, see [action](js-apis-ability-wantConstant.md#action). For details about the definition and matching rules of implicit Want, see [Matching Rules of Explicit Want and Implicit Want](../../application-models/explicit-implicit-want-mappings.md). | diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-bundle-AbilityInfo.md b/en/application-dev/reference/apis-ability-kit/js-apis-bundle-AbilityInfo.md index ea2875cdbf6dce0d255da164dd969f67996ae8b1..cdfa655529bca37ec324c6a0ceedb078e43f06aa 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-bundle-AbilityInfo.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-bundle-AbilityInfo.md @@ -22,11 +22,11 @@ The **AbilityInfo** module provides information about an ability. Unless otherwi | descriptionId | number | Yes | No | ID of the ability description. | | iconId | number | Yes | No | ID of the ability icon. | | moduleName | string | Yes | No | Name of the HAP file to which the ability belongs. | -| process | string | Yes | No | Process in which the ability runs. If this parameter is not set, the bundle name is used. | +| process | string | Yes | No | Process name of the ability. | | targetAbility | string | Yes | No | Target ability that the ability alias points to.
**Model restriction**: This API can be used only in the FA model.| | backgroundModes | number | Yes | No | Background service mode of the ability.
**Model restriction**: This API can be used only in the FA model. | -| isVisible | boolean | Yes | No | Whether the ability can be called by other bundles. | -| formEnabled | boolean | Yes | No | Whether the ability provides the service widget capability.
**Model restriction**: This API can be used only in the FA model.| +| isVisible | boolean | Yes | No | Whether the ability can be called by other applications. The value **true** means that the ability can be called by other applications, and **false** means the opposite. | +| formEnabled | boolean | Yes | No | Whether the ability provides the service widget capability. The value **true** means that the ability provides the service widget capability, and **false** means the opposite.
**Model restriction**: This API can be used only in the FA model.| | type | bundle.AbilityType | Yes | No | Ability type.
**Model restriction**: This API can be used only in the FA model. | | orientation | [bundle.DisplayOrientation](js-apis-Bundle.md#displayorientationdeprecated) | Yes | No | Ability display orientation. | | launchMode | [bundle.LaunchMode](js-apis-Bundle.md#launchmodedeprecated) | Yes | No | Ability launch mode. | @@ -40,4 +40,4 @@ The **AbilityInfo** module provides information about an ability. Unless otherwi | labelId | number | Yes | No | ID of the ability label. | | subType | bundle.AbilitySubType | Yes | No | Subtype of the template that can be used by the ability.
**Model restriction**: This API can be used only in the FA model.| | metaData8+ | Array\<[CustomizeData](js-apis-bundle-CustomizeData.md)> | Yes | No | Metadata of the ability.
The value is obtained by passing in GET_ABILITY_INFO_WITH_METADATA to [bundle.getAbilityInfo](js-apis-Bundle.md#bundlegetabilityinfodeprecated).| -| enabled8+ | boolean | Yes | No | Whether the ability is enabled. | +| enabled8+ | boolean | Yes | No | Whether the ability is enabled. The value **true** means that the ability is enabled, and **false** means the opposite. | diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-bundle-ApplicationInfo.md b/en/application-dev/reference/apis-ability-kit/js-apis-bundle-ApplicationInfo.md index aeb5e1be79f10fddb52b7ffc21e1aaccc506076f..de44b1f4d648276cb4037d6988c0b9c8607afe64 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-bundle-ApplicationInfo.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-bundle-ApplicationInfo.md @@ -17,13 +17,13 @@ The **ApplicationInfo** module provides application information. Unless otherwis | name | string | Yes | No | Application name. | | description | string | Yes | No | Application description. | | descriptionId | number | Yes | No | ID of the application description. | -| systemApp | boolean | Yes | No | Whether the application is a system application. The default value is **false**. | -| enabled | boolean | Yes | No | Whether the application is enabled. The default value is **true**. | +| systemApp | boolean | Yes | No | Whether the application is a system application. The value **true** means that the application is a system application, and **false** means the opposite. | +| enabled | boolean | Yes | No | Whether the application is enabled. The value **true** means that the application is enabled, and **false** means the opposite. | | label | string | Yes | No | Application label. | | labelId | string | Yes | No | ID of the application label. | | icon | string | Yes | No | Application icon. | | iconId | string | Yes | No | ID of the application icon. | -| process | string | Yes | No | Process in which the application runs. If this parameter is not set, the bundle name is used. | +| process | string | Yes | No | Process name. | | supportedModes | number | Yes | No | Modes supported by the application. Currently, only the **drive** mode is defined. This attribute applies only to telematics devices.| | moduleSourceDirs | Array\ | Yes | No | Relative paths for storing application resources. Do not access resource files using concatenated paths. Use [@ohos.resourceManager](../apis-localization-kit/js-apis-resource-manager.md) instead. | | permissions | Array\ | Yes | No | Permissions required for accessing the application.
The value is obtained by passing in GET_APPLICATION_INFO_WITH_PERMISSION to [bundle.getApplicationInfo](js-apis-Bundle.md#bundlegetapplicationinfodeprecated).| @@ -31,7 +31,7 @@ The **ApplicationInfo** module provides application information. Unless otherwis | entryDir | string | Yes | No | Path for storing application files. Do not access resource files using concatenated paths. Use [@ohos.resourceManager](../apis-localization-kit/js-apis-resource-manager.md) instead. | | codePath8+ | string | Yes | No | Installation directory of the application. Do not access resource files using concatenated paths. Use [@ohos.resourceManager](../apis-localization-kit/js-apis-resource-manager.md) instead. | | metaData8+ | Map\> | Yes | No | Custom metadata of the application.
The value is obtained by passing in GET_APPLICATION_INFO_WITH_METADATA to [bundle.getApplicationInfo](js-apis-Bundle.md#bundlegetapplicationinfodeprecated).| -| removable8+ | boolean | Yes | No | Whether the application is removable. | +| removable8+ | boolean | Yes | No | Whether the application is removable. The value **true** means that the application is removable, and **false** means the opposite. | | accessTokenId8+ | number | Yes | No | Access token ID of the application. | | uid8+ | number | Yes | No | UID of the application. | | entityType | string | Yes | No | Type of the application, for example, gaming, social networking, movies, and news.| diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-bundle-BundleInfo.md b/en/application-dev/reference/apis-ability-kit/js-apis-bundle-BundleInfo.md index 0ecafcb1011edec7925431f6512ca268fd49644a..048b2e35a2f520c05bb8641515c977ffbc493937 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-bundle-BundleInfo.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-bundle-BundleInfo.md @@ -29,13 +29,13 @@ The **BundleInfo** module defines the bundle information, which can be obtained | versionName | string | Yes | No | Version description of the bundle. | | compatibleVersion | number | Yes | No | Earliest SDK version required for running the bundle. | | targetVersion | number | Yes | No | Latest SDK version required for running the bundle. | -| isCompressNativeLibs | boolean | Yes | No | Whether to compress the native library of the bundle. The default value is **true**. | +| isCompressNativeLibs | boolean | Yes | No | Whether the native libraries in the bundle are compressed. The value **true** means that the native libraries are compressed, and **false** means the opposite. | | hapModuleInfos | Array\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Yes | No | Module configuration information. | | entryModuleName | string | Yes | No | Name of the entry module. | | cpuAbi | string | Yes | No | CPU and ABI information of the bundle. | | isSilentInstallation | string | Yes | No | Whether the application can be installed in silent mode. | | minCompatibleVersionCode | number | Yes | No | Earliest version compatible with the bundle in the distributed scenario. | -| entryInstallationFree | boolean | Yes | No | Whether installation-free is supported for the entry module. | +| entryInstallationFree | boolean | Yes | No | Whether installation-free is supported for the entry module. The value **true** means that installation-free is supported, and **false** means the opposite. | | reqPermissionStates8+ | Array\ | Yes | No | Permission grant state. The value **0** means that the request is successful, and **-1** means the opposite. | @@ -58,7 +58,7 @@ Provides the detailed information of the permissions to request from the system. ## UsedScene(deprecated) -> This API is deprecated since API version 9. You are advised to use [UsedScene](js-apis-bundleManager-bundleInfo.md) instead. +> This API is deprecated since API version 9. You are advised to use [UsedScene](js-apis-bundleManager-bundleInfo.md#usedscene) instead. Describes the application scenario and timing for using the permission. diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-bundle-BundleInstaller-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-bundle-BundleInstaller-sys.md index 202db1b5d2eb727f9c933c42894817dda4861202..b132e019a5211d84e400b87e6724a67cdcde55ce 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-bundle-BundleInstaller-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-bundle-BundleInstaller-sys.md @@ -1,6 +1,6 @@ # BundleInstaller (System API) -The **BundleInstaller** module provides APIs for you to install, uninstall, and recover bundles on devices. +The BundleInstaller module provides APIs for you to install, uninstall, and recover bundles on devices. > **NOTE** > @@ -177,8 +177,8 @@ Describes the parameters required for bundle installation, recovery, or uninstal | Name | Type | Read-Only| Optional| Description | | ----------- | ------- | ---- | ---- | ------------------ | | userId | number | No | No | User ID. The default value is the user ID of the caller.| -| installFlag | number | No | No | Installation flag.
**1** (default): overwrite installation.
**16**: installation-free.| -| isKeepData | boolean | No | No | Whether data is kept. The default value is **false**.| +| installFlag | number | No | No | Installation flag.
The value can be:
**1** (default): overwrite installation.
**16**: installation-free.| +| isKeepData | boolean | No | No | Whether to retain the bundle data when the application is uninstalled. The default value is **false**. The value **true** means to retain the bundle data when the application is uninstalled, and **false** means the opposite.| ## InstallStatus(deprecated) @@ -191,7 +191,7 @@ Describes the bundle installation or uninstall status. | Name | Type | Read-Only| Optional| Description | | ------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | | status | bundle.[InstallErrorCode](js-apis-Bundle.md#installerrorcode) | No | No | Installation or uninstall error code. The value must be defined in [InstallErrorCode](js-apis-Bundle.md#installerrorcode).| -| statusMessage | string | No | No | Installation or uninstall status message.
**SUCCESS**: install_succeed
**STATUS_INSTALL_FAILURE**: Installation failed (no installation file exists).
**STATUS_INSTALL_FAILURE_ABORTED**: Installation aborted.
**STATUS_INSTALL_FAILURE_INVALID**: Invalid installation parameter.
**STATUS_INSTALL_FAILURE_CONFLICT**: Installation conflict. (The basic information of the application to update is inconsistent with that of the existing application.)
**STATUS_INSTALL_FAILURE_STORAGE**: Failed to store the bundle information.
**STATUS_INSTALL_FAILURE_INCOMPATIBLE**: Installation incompatibility. (A downgrade occurs or the signature information is incorrect.)
**STATUS_UNINSTALL_FAILURE**: Uninstall failed. (The application to be uninstalled is not found.)
**STATUS_UNINSTALL_FAILURE_ABORTED**: Uninstall aborted. (This error code is not in use.)
**STATUS_UNINSTALL_FAILURE_ABORTED**: Uninstall conflict. (Failed to uninstall a system application or end the application process.)
**STATUS_INSTALL_FAILURE_DOWNLOAD_TIMEOUT**: Installation failed. (Download timed out.)
**STATUS_INSTALL_FAILURE_DOWNLOAD_FAILED**: Installation failed. (Download failed.)
**STATUS_RECOVER_FAILURE_INVALID**: Failed to restore the pre-installed application.
**STATUS_ABILITY_NOT_FOUND**: Ability not found.
**STATUS_BMS_SERVICE_ERROR**: BMS service error.
**STATUS_FAILED_NO_SPACE_LEFT**: Insufficient device space.
**STATUS_GRANT_REQUEST_PERMISSIONS_FAILED**: Application authorization failed.
**STATUS_INSTALL_PERMISSION_DENIED**: No installation permission.
**STATUS_UNINSTALL_PERMISSION_DENIED**: No uninstall permission. | +| statusMessage | string | No | No | Installation or uninstall status message.
**SUCCESS**: Installation succeeded.
**STATUS_INSTALL_FAILURE**: Installation failed (no installation file exists).
**STATUS_INSTALL_FAILURE_ABORTED**: Installation aborted.
**STATUS_INSTALL_FAILURE_INVALID**: Invalid installation parameter.
**STATUS_INSTALL_FAILURE_CONFLICT**: Installation conflict. (The basic information of the application to update is inconsistent with that of the existing application.)
**STATUS_INSTALL_FAILURE_STORAGE**: Failed to store the bundle information.
**STATUS_INSTALL_FAILURE_INCOMPATIBLE**: Installation incompatibility. (A downgrade occurs or the signature information is incorrect.)
**STATUS_UNINSTALL_FAILURE**: Uninstall failed. (The application to be uninstalled is not found.)
**STATUS_UNINSTALL_FAILURE_ABORTED**: Uninstall aborted. (This error code is not in use.)
**STATUS_UNINSTALL_FAILURE_ABORTED**: Uninstall conflict. (Failed to uninstall a system application or end the application process.)
**STATUS_INSTALL_FAILURE_DOWNLOAD_TIMEOUT**: Installation failed. (Download timed out.)
**STATUS_INSTALL_FAILURE_DOWNLOAD_FAILED**: Installation failed. (Download failed.)
**STATUS_RECOVER_FAILURE_INVALID**: Failed to restore the pre-installed application.
**STATUS_ABILITY_NOT_FOUND**: Ability not found.
**STATUS_BMS_SERVICE_ERROR**: BMS service error.
**STATUS_FAILED_NO_SPACE_LEFT**: Insufficient device space.
**STATUS_GRANT_REQUEST_PERMISSIONS_FAILED**: Application authorization failed.
**STATUS_INSTALL_PERMISSION_DENIED**: No installation permission.
**STATUS_UNINSTALL_PERMISSION_DENIED**: No uninstall permission.| ## Obtaining the Sandbox Path For the FA model, the sandbox path of a bundle can be obtained using the APIs in [Context](js-apis-inner-app-context.md). For the stage model, the sandbox path can be obtained using the property in [Context](js-apis-inner-application-uiAbilityContext-sys.md#abilitycontext). The following describes how to obtain the sandbox path. diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-bundle-HapModuleInfo.md b/en/application-dev/reference/apis-ability-kit/js-apis-bundle-HapModuleInfo.md index b9b0ad82a18ea73c75d8b97b34320c55aa0caebc..3765551e37eebe3bd22418b8d7d5ad33c3453b30 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-bundle-HapModuleInfo.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-bundle-HapModuleInfo.md @@ -28,4 +28,4 @@ The **HapModuleInfo** module provides information about an HAP module. Unless ot | abilityInfo | Array\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | No | Ability information. | | moduleName | string | Yes | No | Module name. | | mainAbilityName | string | Yes | No | Name of the main ability. | -| installationFree | boolean | Yes | No | Whether installation-free is supported. | +| installationFree | boolean | Yes | No | Whether installation-free is supported. The value **true** means that installation-free is supported, and **false** means the opposite. | diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-bundle-LauncherAbilityInfo-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-bundle-LauncherAbilityInfo-sys.md index a65db2c84df6a4b3e71afb699d00746f62a86a16..25a10eda75286bb4190023f4099515427f8a82c2 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-bundle-LauncherAbilityInfo-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-bundle-LauncherAbilityInfo-sys.md @@ -1,6 +1,6 @@ # LauncherAbilityInfo (System API) -The **LauncherAbilityInfo** module provides information about the launcher ability, which is obtained through [innerBundleManager.getLauncherAbilityInfos](js-apis-Bundle-InnerBundleManager-sys.md). +The LauncherAbilityInfo module provides information about the launcher ability, which is obtained through [innerBundleManager.getLauncherAbilityInfos](js-apis-Bundle-InnerBundleManager-sys.md#innerbundlemanagergetlauncherabilityinfosdeprecated). > **NOTE** > @@ -10,7 +10,7 @@ The **LauncherAbilityInfo** module provides information about the launcher abili ## LauncherAbilityInfo(deprecated) -> This API is deprecated since API version 9. You are advised to use [bundleManager-LauncherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo-sys.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleManager-LauncherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo.md) instead. **System capability**: SystemCapability.BundleManager.BundleFramework diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-bundle-ModuleInfo.md b/en/application-dev/reference/apis-ability-kit/js-apis-bundle-ModuleInfo.md index 6fa25be4e74e95ccfe0e893b60a6115add9d76df..0ca50eb6660ed868a1a0dbb9dab8af53e34fccf7 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-bundle-ModuleInfo.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-bundle-ModuleInfo.md @@ -1,6 +1,6 @@ # ModuleInfo -The **ModuleInfo** module provides module information of an application. +The ModuleInfo module provides module information of an application. > **NOTE** > diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-bundle-ShortcutInfo-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-bundle-ShortcutInfo-sys.md index 73fd6a108c1fe147436a06ae6292d3c27b91c6e5..3f711526f1748f5dc5ab04663aea32c750246372 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-bundle-ShortcutInfo-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-bundle-ShortcutInfo-sys.md @@ -10,7 +10,7 @@ The shortcutInfo module defines shortcut information configured in the configura ## ShortcutWant(deprecated) -> This API is deprecated since API version 9. You are advised to use [bundleManager-ShortcutWant](js-apis-bundleManager-shortcutInfo-sys.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleManager-ShortcutWant](js-apis-bundleManager-shortcutInfo-sys.md#shortcutwant) instead. **System capability**: SystemCapability.BundleManager.BundleFramework diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-bundle-ShortcutInfo.md b/en/application-dev/reference/apis-ability-kit/js-apis-bundle-ShortcutInfo.md index cac6f4651b4eac5f4c61baa040f9526b729e1b25..66e1ad1bedc03839f9af0eb6f694d4b53e526157 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-bundle-ShortcutInfo.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-bundle-ShortcutInfo.md @@ -21,6 +21,6 @@ The shortcutInfo module defines shortcut information configured in the configura | labelId8+ | number | Yes | No | Name ID of the shortcut. | | disableMessage | string | Yes | No | Message displayed when the shortcut is disabled. | | wants | Array<[ShortcutWant](js-apis-bundle-ShortcutInfo-sys.md#shortcutwantdeprecated)> | Yes | No | Want list for the shortcut. | -| isStatic | boolean | Yes | Yes | Whether the shortcut is static. | -| isHomeShortcut | boolean | Yes | Yes | Whether the shortcut is a home shortcut.| -| isEnabled | boolean | Yes | Yes | Whether the shortcut is enabled. | +| isStatic | boolean | Yes | No | Whether the shortcut is static. The value **true** means that the shortcut is static, and **false** means the opposite. | +| isHomeShortcut | boolean | Yes | No | Whether the shortcut is a home shortcut. The value **true** means that the shortcut is a home shortcut, and **false** means the opposite.| +| isEnabled | boolean | Yes | No | Whether the shortcut is enabled. The value **true** means that the shortcut is enabled., and **false** means the opposite. | diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-bundle-remoteAbilityInfo-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-bundle-remoteAbilityInfo-sys.md index d97d8bd738b385e8dcb8eaa5c41e47f402ba1fb5..fbdfcc0601d052ba682d8c65a3f0cce66ce2d8ba 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-bundle-remoteAbilityInfo-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-bundle-remoteAbilityInfo-sys.md @@ -1,6 +1,6 @@ # RemoteAbilityInfo (System API) -The **RemoteAbilityInfo** module provides information about a remote ability. +The RemoteAbilityInfo module provides information about a remote ability. > **NOTE** > diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-AppProvisionInfo-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-AppProvisionInfo-sys.md index 7f62f063a564cb574ddfd69b86e80182d9061e9a..819bd4350a9048e9d6b6a4df5ce9138a991899ac 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-AppProvisionInfo-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-AppProvisionInfo-sys.md @@ -1,6 +1,6 @@ # AppProvisionInfo (System API) -The **AppProvisionInfo** module provides information in the [HarmonyAppProvision configuration file](../../security/app-provision-structure.md). The information can be obtained through [getAppProvisionInfo](js-apis-bundleManager.md#bundlemanagergetappprovisioninfo10). +The **AppProvisionInfo** module provides information in the [HarmonyAppProvision configuration file](../../security/app-provision-structure.md). The information can be obtained through [getAppProvisionInfo](./js-apis-bundleManager-sys.md#bundlemanagergetappprovisioninfo10). > **NOTE** > @@ -20,13 +20,13 @@ The **AppProvisionInfo** module provides information in the [HarmonyAppProvision | versionName | string | Yes | No | Version name of the configuration file. | | uuid | string | Yes | No | UUID in the configuration file.| | type | string | Yes | No | Type of the configuration file, which can be **debug** or **release**.| -| appDistributionType | string | Yes | No | Distribution type in the configuration file, which can be **app_gallery**, **enterprise**, **os_integration**, or **crowdtesting**.| +| appDistributionType | string | Yes | No | [Distribution type](../../security/app-provision-structure.md) in the configuration file.| | validity | [Validity](#validity) | Yes | No | Validity period in the configuration file.| | developerId | string | Yes | No | Developer ID in the configuration file.| | certificate | string | Yes | No | Certificate public key in the configuration file.| | apl | string | Yes | No | APL in the configuration file, which can be **normal**, **system_basic**, or **system_core**.| | issuer | string | Yes | No | Issuer name in the configuration file.| -|appIdentifier11+| string | Yes | No | Unique ID of the application, which is allocated by the cloud. This ID does not change along the application lifecycle, including version updates, certificate changes, public and private key changes, and application transfers. | +|appIdentifier11+| string | Yes | No | Unique ID of the application. It is a random string allocated by AppGallery Connect during the creation of the application. This ID does not change along the application lifecycle, including version updates, certificate changes, public and private key changes, and application transfers. | | organization12+ | string | Yes | No | Organization of the application.| ## Validity diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-ApplicationInfo-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-ApplicationInfo-sys.md index 46d903ee32890ce83faabe30d88718c1d37d8c3d..3897fe0ca725c587d2409b49050d163e8e16a6dc 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-ApplicationInfo-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-ApplicationInfo-sys.md @@ -28,6 +28,6 @@ The ApplicationInfo module defines the application information. A third-party ap | Name | Type | Read-Only| Optional| Description | | --------- | -------------- | ---- | ---- | --------------------------- | | bundleName | string | Yes | No | Bundle name of the application. | -| moduleName | string | Yes | No | Module name of the application. By default, the name of the entry module is returned. If the entry module does not exist, the name of the feature module is returned. | +| moduleName | string | Yes | No | Module name of the application. The value is **moduleName** configured for the entry module. If the entry module does not exist, the value is **moduleName** configured for the feature module. | | iconId | number | Yes | No | Icon ID of the application. | | labelId | number | Yes | No | Label ID of the application. | diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-BundlePackInfo-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-BundlePackInfo-sys.md index 0324a60bd97ebf2fbf6dd277ff0ce380d0272ab6..53f643a2c1b7684de84cdad9ecf982442e306a63 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-BundlePackInfo-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-BundlePackInfo-sys.md @@ -14,7 +14,6 @@ The **BundlePackInfo** module provides information in the **pack.info** file. Th **System capability**: SystemCapability.BundleManager.BundleFramework.FreeInstall - | Name | Type | Read-Only| Optional| Description | | -------- | --------------------------------------- | ---- | ---- | ------------------------- | | packages | Array\<[PackageConfig](#packageconfig)> | Yes | No | Package configuration information in the **pack.info** file. | @@ -31,7 +30,7 @@ The **BundlePackInfo** module provides information in the **pack.info** file. Th | deviceTypes | Array\ | Yes | No | Device types supported by the bundle. | | name | string | Yes | No | Bundle name. | | moduleType | string | Yes | No | Module type of the bundle. | -| deliveryWithInstall | boolean | Yes | No | Whether the HAP file will be installed when the user installs the bundle. The value **true** means that the HAP file will be automatically installed when the user installs the bundle, and **false** means the opposite.| +| deliveryWithInstall | boolean | Yes | No | Whether the installation should occur during user-initiated installation. The value **true** means that the installation should occur during user-initiated installation, and **false** means the opposite.| ## PackageSummary @@ -78,7 +77,7 @@ The **BundlePackInfo** module provides information in the **pack.info** file. Th | Name | Type | Read-Only| Optional| Description | | ------------------- | ------- | ---- | ---- | ------------------------------------------------------------ | -| deliveryWithInstall | boolean | Yes | No | Whether the HAP file will be installed when the user installs the bundle. The value **true** means that the HAP file will be automatically installed when the user installs the bundle, and **false** means the opposite.| +| deliveryWithInstall | boolean | Yes | No | Whether the installation should occur during user-initiated installation. The value **true** means that the installation should occur during user-initiated installation, and **false** means the opposite.| | installationFree | boolean | Yes | No | Whether the HAP file supports the installation-free feature. The value **true** means that the HAP file supports the installation-free feature and meets installation-free constraints, and **false** means the opposite.| | moduleName | string | Yes | No | Module name. | | moduleType | string | Yes | No | Module type. | @@ -93,7 +92,7 @@ The **BundlePackInfo** module provides information in the **pack.info** file. Th | ------- | ------------------------------------------- | ---- | ---- | ------------------------------------------------------------ | | name | string | Yes | No | Name of the ability. The name must be unique in the bundle. | | label | string | Yes | No | Name of the ability displayed to users. The value is a resource index to names in multiple languages.| -| exported | boolean | Yes | No | Whether the ability can be called by other bundles. The value **true** means that the ability can be called by other bundles, and **false** means the opposite.| +| exported | boolean | Yes | No | Whether the ability can be invoked by other applications. The value **true** means that it can be invoked by other applications, and the value **false** means the opposite.| | forms | Array\<[AbilityFormInfo](#abilityforminfo)> | Yes | No | Widget information. | ## ExtensionAbility diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-abilityInfo.md b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-abilityInfo.md index d1b3dc035bc30472bb7acdca4ce3fa7bcde0adb5..1fbbaf9b85674132ee602068299f51a3cfc8e703 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-abilityInfo.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-abilityInfo.md @@ -1,6 +1,6 @@ # AbilityInfo -The **AbilityInfo** module defines the ability information. A third-party application can obtain its own ability information through [bundleManager.getBundleInfoForSelf](js-apis-bundleManager.md#bundlemanagergetbundleinfoforself), with **GET_BUNDLE_INFO_WITH_HAP_MODULE** and **GET_BUNDLE_INFO_WITH_ABILITY** passed in to [bundleFlags](js-apis-bundleManager.md#bundleflag). +The AbilityInfo module defines the ability information. A third-party application can obtain its own ability information through [bundleManager.getBundleInfoForSelf](js-apis-bundleManager.md#bundlemanagergetbundleinfoforself), with **GET_BUNDLE_INFO_WITH_HAP_MODULE** and **GET_BUNDLE_INFO_WITH_ABILITY** passed in to [bundleFlags](js-apis-bundleManager.md#bundleflag). > **NOTE** > @@ -21,8 +21,8 @@ The **AbilityInfo** module defines the ability information. A third-party applic | descriptionId | number | Yes | No | ID of the ability description.
**Atomic service API**: This API can be used in atomic services since API version 11.| | icon | string | Yes | No | Resource descriptor of the ability icon. Example: **"icon": "$media:icon"**.
**Atomic service API**: This API can be used in atomic services since API version 11.| | iconId | number | Yes | No | ID of the ability icon.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| process | string | Yes | No | Process in which the ability runs. If this parameter is not set, the bundle name is used.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| exported | boolean | Yes | No | Whether the ability can be called by other bundles.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| process | string | Yes | No | Process name of the ability.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| exported | boolean | Yes | No | Whether the ability can be called by other applications. The value **true** means that the ability can be called by other applications, and **false** means the opposite.
**Atomic service API**: This API can be used in atomic services since API version 11.| | type | [bundleManager.AbilityType](js-apis-bundleManager.md#abilitytype) | Yes | No | Ability type.
**Model restriction**: This API can be used only in the FA model.| | orientation | [bundleManager.DisplayOrientation](js-apis-bundleManager.md#displayorientation) | Yes | No | Ability display orientation.
**Atomic service API**: This API can be used in atomic services since API version 11.| | launchType | [bundleManager.LaunchType](js-apis-bundleManager.md#launchtype) | Yes | No | Ability launch mode.
**Atomic service API**: This API can be used in atomic services since API version 11.| @@ -33,10 +33,10 @@ The **AbilityInfo** module defines the ability information. A third-party applic | deviceTypes | Array\ | Yes | No | Device types supported by the ability.
**Atomic service API**: This API can be used in atomic services since API version 11.| | applicationInfo | [ApplicationInfo](js-apis-bundleManager-applicationInfo.md) | Yes | No | Application information. The information can be obtained by passing in **GET_BUNDLE_INFO_WITH_HAP_MODULE**, **GET_BUNDLE_INFO_WITH_ABILITY**, and **GET_BUNDLE_INFO_WITH_APPLICATION** to the **bundleFlags** parameter of [getBundleInfoForSelf](js-apis-bundleManager.md#bundlemanagergetbundleinfoforself).
**Atomic service API**: This API can be used in atomic services since API version 11.| | metadata | Array\<[Metadata](js-apis-bundleManager-metadata.md)> | Yes | No | Metadata of the ability. The information can be obtained by passing in **GET_BUNDLE_INFO_WITH_HAP_MODULE**, **GET_BUNDLE_INFO_WITH_ABILITY**, and **GET_BUNDLE_INFO_WITH_METADATA** to the **bundleFlags** parameter of [getBundleInfoForSelf](js-apis-bundleManager.md#bundlemanagergetbundleinfoforself).
**Atomic service API**: This API can be used in atomic services since API version 11.| -| enabled | boolean | Yes | No | Whether the ability is enabled.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| enabled | boolean | Yes | No | Whether the ability is enabled. The value **true** means that the ability is enabled, and **false** means the opposite.
**Atomic service API**: This API can be used in atomic services since API version 11.| | supportWindowModes | Array\<[bundleManager.SupportWindowMode](js-apis-bundleManager.md#supportwindowmode)> | Yes | No | Window modes supported by the ability.
**Atomic service API**: This API can be used in atomic services since API version 11.| | windowSize|[WindowSize](#windowsize) | Yes | No | Window size.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| excludeFromDock12+ | boolean | Yes | No | Whether the ability can hide icons in the dock area.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| excludeFromDock12+ | boolean | Yes | No | Whether the ability icon can be hidden in the dock area. The value **true** means that the ability icon can be hidden in the dock area, and **false** means the opposite.
**Atomic service API**: This API can be used in atomic services since API version 12.| | skills12+ | Array\<[Skill](js-apis-bundleManager-skill.md)> | Yes | No | Skills of the ability.
**Atomic service API**: This API can be used in atomic services since API version 12. | | appIndex12+ | number | Yes | No | Index of an application clone. It takes effect only for cloned applications.| | orientationId14+ | number | Yes | No | Resource ID of the ability display mode. If **orientationId** is not set to **0**, the current display mode is customized, and **orientationId** must be used to obtain the corresponding resource from the resource manager module.
**Atomic service API**: This API can be used in atomic services since API version 14.| diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-applicationInfo.md b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-applicationInfo.md index 64f46ee69e4b1c1da494319137ff598a5577a13f..f92ddcc67782be69b2a3e4dfbce8f997156f8fcf 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-applicationInfo.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-applicationInfo.md @@ -15,17 +15,17 @@ The **ApplicationInfo** module defines the application information. A third-part | name | string | Yes | No | Application name.
**Atomic service API**: This API can be used in atomic services since API version 11. | | description | string | Yes | No | Description of the application, for example, "description": $string: mainability_description". For details, see the description of the **descriptionResource** field below.
**Atomic service API**: This API can be used in atomic services since API version 11.| | descriptionId | number | Yes | No | ID of the application description.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| enabled | boolean | Yes | No | Whether the application is enabled. The default value is **true**.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| enabled | boolean | Yes | No | Whether the application is enabled. The value **true** means that the application is enabled, and **false** means the opposite.
**Atomic service API**: This API can be used in atomic services since API version 11.| | label | string | Yes | No | Application name, for example, "label": "$string: mainability_description". For details, see the description of the **labelResource** field below.
**Atomic service API**: This API can be used in atomic services since API version 11.| | labelId | number | Yes | No | ID of the application label.
**Atomic service API**: This API can be used in atomic services since API version 11.| | icon | string | Yes | No | Application icon, for example, "icon": "$media:icon". For details, see the description of the **iconResource** field below.
**Atomic service API**: This API can be used in atomic services since API version 11.| | iconId | number | Yes | No | ID of the application icon.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| process | string | Yes | No | Process in which the application runs. If this parameter is not set, the bundle name is used.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| process | string | Yes | No | Process name.
**Atomic service API**: This API can be used in atomic services since API version 11.| | permissions | Array\ | Yes | No | Permissions required for accessing the application. The permissions can be obtained by passing in **GET_BUNDLE_INFO_WITH_APPLICATION** and **GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION** to the **bundleFlags** parameter of [getBundleInfoForSelf](js-apis-bundleManager.md#bundlemanagergetbundleinfoforself).
**Atomic service API**: This API can be used in atomic services since API version 11.| | codePath | string | Yes | No | Installation directory of the application.
**Atomic service API**: This API can be used in atomic services since API version 11.| | metadata(deprecated) | Map\> | Yes | No | Metadata of the application. The information can be obtained by passing in **GET_BUNDLE_INFO_WITH_APPLICATION** and **GET_BUNDLE_INFO_WITH_METADATA** to the **bundleFlags** parameter of [getBundleInfoForSelf](js-apis-bundleManager.md#bundlemanagergetbundleinfoforself). **NOTE**
This field is deprecated since API version 10. You are advised to use **metadataArray** instead.| | metadataArray10+ | Array\<[ModuleMetadata](#modulemetadata10)> | Yes | No | Metadata of the application. The information can be obtained by passing in **GET_BUNDLE_INFO_WITH_APPLICATION** and **GET_BUNDLE_INFO_WITH_METADATA** to the **bundleFlags** parameter of [getBundleInfoForSelf](js-apis-bundleManager.md#bundlemanagergetbundleinfoforself).
**Atomic service API**: This API can be used in atomic services since API version 11.| -| removable | boolean | Yes | No | Whether the application is removable.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| removable | boolean | Yes | No | Whether the application is removable. The value **true** means that the application is removable, and **false** means the opposite.
**Atomic service API**: This API can be used in atomic services since API version 11.| | accessTokenId | number | Yes | No | Access token ID of the application.
**Atomic service API**: This API can be used in atomic services since API version 11.| | uid | number | Yes | No | UID of the application.
**Atomic service API**: This API can be used in atomic services since API version 11.| | iconResource | [Resource](../apis-localization-kit/js-apis-resource-manager.md#resource9) | Yes| No| Resource information of the application icon. The resource information obtained contains the bundle name, module name, and ID of the resource. You can call [getMediaContent](../apis-localization-kit/js-apis-resource-manager.md#getmediacontent9) to obtain the resource details.
**Atomic service API**: This API can be used in atomic services since API version 11.| @@ -33,14 +33,14 @@ The **ApplicationInfo** module defines the application information. A third-part | descriptionResource | [Resource](../apis-localization-kit/js-apis-resource-manager.md#resource9) | Yes| No| Resource information of the application description. The resource information obtained contains the bundle name, module name, and ID of the resource. You can call [getMediaContent](../apis-localization-kit/js-apis-resource-manager.md#getmediacontent9) to obtain the resource details.
**Atomic service API**: This API can be used in atomic services since API version 11.| | appDistributionType | string | Yes | No | Distribution type of the application signing certificate. The options are **app_gallery**, **enterprise**, **os_integration**, and **crowdtesting**.
**Atomic service API**: This API can be used in atomic services since API version 11.| | appProvisionType | string | Yes | No | Type of the application signing certificate file. The options are **debug** and **release**.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| systemApp | boolean | Yes | No | Whether the application is a system application.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| systemApp | boolean | Yes | No | Whether the application is a system application. The value **true** means that the application is a system application, and **false** means the opposite.
**Atomic service API**: This API can be used in atomic services since API version 11.| | bundleType |[bundleManager.BundleType](js-apis-bundleManager.md#bundletype) | Yes | No | Bundle type, which can be **APP** (application) or **ATOMIC_SERVICE** (atomic service).
**Atomic service API**: This API can be used in atomic services since API version 11.| -| debug10+ | boolean | Yes | No | Whether the application is in debugging mode. The default value is **false**.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| dataUnclearable11+ | boolean | Yes | No | Whether the application data is unclearable. The value **true** means that the application data is unclearable, and **false** means the opposite. The default value is **false**.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| debug10+ | boolean | Yes | No | Whether the application is running in debug mode. The value **true** means that the application is running in debug mode, and **false** means the opposite.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| dataUnclearable11+ | boolean | Yes | No | Whether the application data is unclearable. The value **true** means that the application data is unclearable, and **false** means the opposite.
**Atomic service API**: This API can be used in atomic services since API version 11.| | nativeLibraryPath12+ | string | Yes | No | Local library file path of the application. | | multiAppMode12+ | [MultiAppMode](#multiappmode12) | Yes | No | Multi-app mode.| | appIndex12+ | number | Yes | No | Index of an application clone. It takes effect only for cloned applications.| -| installSource12+ | string | Yes | No | Installation source of the application. **pre-installed** indicates that the application is pre-installed. A value in the form of a bundle name indicates that the application is installed by an application with the given bundle name. **unknown** indicates that the installation source is unknown.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| installSource12+ | string | Yes | No | Installation source of the application. The options are as follows:
- **pre-installed**: The application is a preset application installed at initial device startup.
- **ota**: The application is a preset application added during system upgrade.
- **recovery**: The preset application is uninstalled and then restored.
- Bundle name of an application: The application is installed from the specified bundle name.
- **unknown**: The installation source is unknown.
**Atomic service API**: This API can be used in atomic services since API version 12.| | releaseType12+ | string | Yes | No | Release type of the SDK used for application packing. Currently, the SDK release types include Canary, Beta, and Release. Each of the Canary and Beta releases can be distinguished by a sequential number, such as Canary1, Canary2, Beta1, and Beta2. You can compare the SDK release type on which application packaging depends and the OS release type (specified by [deviceInfo.distributionOSReleaseType](../apis-basic-services-kit/js-apis-device-info.md)) to determine the compatibility.
**Atomic service API**: This API can be used in atomic services since API version 12.| | cloudFileSyncEnabled12+ | boolean | Yes | No | Whether device-cloud file synchronization is enabled for the application. The value **true** means that device-cloud file synchronization is enabled, and **false** means the opposite.
**Atomic service API**: This API can be used in atomic services since API version 12.| diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-bundleInfo.md b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-bundleInfo.md index b19cbc8618ce6f9d499ca1745a033f92534a5b26..4f5bc7833dd3423dbb2a2ff525cee06502d64f11 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-bundleInfo.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-bundleInfo.md @@ -27,6 +27,7 @@ The **BundleInfo** module defines the bundle information. A third-party applicat | updateTime | number | Yes | No | Time when the bundle was updated.
**Atomic service API**: This API can be used in atomic services since API version 11.| | routerMap12+ | Array\<[RouterItem](js-apis-bundleManager-hapModuleInfo.md#routeritem12)> | Yes | No | Router table of the application. The table is obtained by deduplicating and combining the **routerMap** information under **hapModulesInfo** based on the **name** field in **RouterItem**. The information can be obtained by passing in **GET_BUNDLE_INFO_WITH_HAP_MODULE** and **GET_BUNDLE_INFO_WITH_ROUTER_MAP** to the **bundleFlags** parameter of [getBundleInfoForSelf](js-apis-bundleManager.md#bundlemanagergetbundleinfoforself).
**Atomic service API**: This API can be used in atomic services since API version 12.| | appIndex12+ | number | Yes | No | Index of an application clone. It takes effect only for cloned applications.| +| firstInstallTime18+ | number | Yes | Yes | Time when the application is installed on the current device for the first time.
**Atomic service API**: This API can be used in atomic services since API version 18.| ## ReqPermissionDetail @@ -61,19 +62,28 @@ Describes the use scenario and timing for using the permission. | Name | Type | Read-Only| Optional| Description | | --------- | -------------- | ---- | ---- | --------------------------- | | abilities | Array\ | No | No | Abilities that use the permission. | -| when | string | No | No | Time when the permission is used. | +| when | string | No | No | Time when the permission is used. The value can be **inuse** or **always**. | ## SignatureInfo Describes the signature information of the bundle. -**Atomic service API**: This API can be used in atomic services since API version 11. +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +| Name | Type | Read-Only| Optional| Description | +| --------- | -------------- | ---- | ---- | --------------------------- | +| appId | string | Yes | No | Application ID.
**Atomic service API**: This API can be used in atomic services since API version 11. | +|fingerprint| string | Yes | No | Fingerprint information of the bundle. This field changes when the used signing certificate changes.
**Atomic service API**: This API can be used in atomic services since API version 11. | +|appIdentifier11+| string | Yes | No | Unique ID of the application. It is a random string allocated by AppGallery Connect during the creation of the application. This ID does not change along the application lifecycle, including version updates, certificate changes, public and private key changes, and application transfers.
**Atomic service API**: This API can be used in atomic services since API version 11. | +|certificate14+| string | Yes | Yes | Public key of the application certificate.
**Atomic service API**: This API can be used in atomic services since API version 14. | + +## AppCloneIdentity14+ + +Describes the identity information of an application clone. **System capability**: SystemCapability.BundleManager.BundleFramework.Core | Name | Type | Read-Only| Optional| Description | | --------- | -------------- | ---- | ---- | --------------------------- | -| appId | string | Yes | No | Application ID. | -|fingerprint| string | Yes | No | Fingerprint information of the bundle. This field changes when the used signing certificate changes. | -|appIdentifier11+| string | Yes | No | Unique ID of the application, which is allocated by the cloud. This ID does not change along the application lifecycle, including version updates, certificate changes, public and private key changes, and application transfers. | -|certificate14+| string | Yes | Yes | Public key of the application certificate. | +| bundleName | string | Yes | No | Bundle name of the application. | +| appIndex | number | Yes | No | Index of the application clone.| diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-businessAbilityInfo-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-businessAbilityInfo-sys.md index 7948534ded60fed5d4773b89a64841f40bf0be59..3ae3388b6ce34658a78e69041c984d0c7f2c3878 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-businessAbilityInfo-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-businessAbilityInfo-sys.md @@ -1,6 +1,6 @@ # BusinessAbilityInfo (System API) -The **BusinessAbilityInfo** module provides basic information about a business ability. +The BusinessAbilityInfo module provides basic information about a business ability. > **NOTE** > diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-extensionAbilityInfo.md b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-extensionAbilityInfo.md index 2e4608657ad7f3ccd66ee1b2e1b8c6e270542d54..0be886b4e7a835b5c7bce1d4d19f4ccd531e76ca 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-extensionAbilityInfo.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-extensionAbilityInfo.md @@ -1,6 +1,6 @@ # ExtensionAbilityInfo -The **ExtensionAbilityInfo** module defines the ExtensionAbility information. A third-party application can obtain its own ExtensionAbility information through [bundleManager.getBundleInfoForSelf](js-apis-bundleManager.md#bundlemanagergetbundleinfoforself), with **GET_BUNDLE_INFO_WITH_HAP_MODULE** and **GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY** passed in to [bundleFlags](js-apis-bundleManager.md#bundleflag). +The ExtensionAbilityInfo module defines the ExtensionAbility information. A third-party application can obtain its own ExtensionAbility information through [bundleManager.getBundleInfoForSelf](js-apis-bundleManager.md#bundlemanagergetbundleinfoforself), with **GET_BUNDLE_INFO_WITH_HAP_MODULE** and **GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY** passed in to [bundleFlags](js-apis-bundleManager.md#bundleflag). > **NOTE** > @@ -20,14 +20,14 @@ The **ExtensionAbilityInfo** module defines the ExtensionAbility information. A | labelId | number | Yes | No | ID of the ExtensionAbility label. | | descriptionId | number | Yes | No | ID of the ExtensionAbility description. | | iconId | number | Yes | No | ID of the ExtensionAbility icon. | -| exported | boolean | Yes | No | Whether the ExtensionAbility can be called by other bundles. | +| exported | boolean | Yes | No | Whether the ExtensionAbility can be called by other applications. The value **true** means that the ExtensionAbility can be called by other applications, and **false** means the opposite. | | extensionAbilityType | [ExtensionAbilityType](js-apis-bundleManager.md#extensionabilitytype) | Yes | No | Type of the ExtensionAbility. | | permissions | Array\ | Yes | No | Permissions required for other bundles to call the ExtensionAbility.| | applicationInfo | [ApplicationInfo](js-apis-bundleManager-applicationInfo.md) | Yes | No | Application information. The information can be obtained by passing in **GET_BUNDLE_INFO_WITH_HAP_MODULE**, **GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY**, and **GET_BUNDLE_INFO_WITH_APPLICATION** to the **bundleFlags** parameter of [getBundleInfoForSelf](js-apis-bundleManager.md#bundlemanagergetbundleinfoforself).| | metadata | Array\<[Metadata](js-apis-bundleManager-metadata.md)> | Yes | No | Metadata of the ExtensionAbility. The information can be obtained by passing in **GET_BUNDLE_INFO_WITH_HAP_MODULE**, **GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY**, and **GET_BUNDLE_INFO_WITH_METADATA** to the **bundleFlags** parameter of [getBundleInfoForSelf](js-apis-bundleManager.md#bundlemanagergetbundleinfoforself).| -| enabled | boolean | Yes | No | Whether the ExtensionAbility is enabled. | +| enabled | boolean | Yes | No | Whether the ExtensionAbility is enabled. The value **true** means that the ExtensionAbility is enabled, and **false** means the opposite. | | readPermission | string | Yes | No | Permission required for reading data from the ExtensionAbility. | | writePermission | string | Yes | No | Permission required for writing data to the ExtensionAbility. | -| extensionAbilityTypeName11 | string | Yes | No | Type of the ExtensionAbility. | +| extensionAbilityTypeName11+ | string | Yes | No | Type of the ExtensionAbility. | | skills12+ | Array\<[Skill](js-apis-bundleManager-skill.md)> | Yes | No | Skills of the ExtensionAbility. | | appIndex12+ | number | Yes | No | Index of an application clone. It takes effect only for cloned applications.| diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-hapModuleInfo.md b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-hapModuleInfo.md index 7ddf3d749122c18fef8083cab70a5ff55e162955..85d5cecf4b0a6b7ec51c9ee553ba5b6fc0e3ce23 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-hapModuleInfo.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-hapModuleInfo.md @@ -24,7 +24,7 @@ The **HapModuleInfo** module defines the HAP module information. A third-party a | extensionAbilitiesInfo | Array\<[ExtensionAbilityInfo](js-apis-bundleManager-extensionAbilityInfo.md)> | Yes | No | ExtensionAbility information. The information can be obtained by passing in **GET_BUNDLE_INFO_WITH_HAP_MODULE** and **GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY** to the **bundleFlags** parameter of [getBundleInfoForSelf](js-apis-bundleManager.md#bundlemanagergetbundleinfoforself).
**Atomic service API**: This API can be used in atomic services since API version 11.| | metadata | Array\<[Metadata](js-apis-bundleManager-metadata.md)> | Yes | No | Metadata of the ability. The information can be obtained by passing in **GET_BUNDLE_INFO_WITH_HAP_MODULE** and **GET_BUNDLE_INFO_WITH_METADATA** to the **bundleFlags** parameter of [getBundleInfoForSelf](js-apis-bundleManager.md#bundlemanagergetbundleinfoforself).
**Atomic service API**: This API can be used in atomic services since API version 11.| | deviceTypes | Array\ | Yes | No | Types of devices where the module can run.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| installationFree | boolean | Yes | No | Whether installation-free is supported.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| installationFree | boolean | Yes | No | Whether installation-free is supported for the module. The value **true** means that installation-free is supported, and **false** means the opposite.
**Atomic service API**: This API can be used in atomic services since API version 11.| | hashValue | string | Yes | No | Hash value of the module.
**Atomic service API**: This API can be used in atomic services since API version 11.| | type | [bundleManager.ModuleType](js-apis-bundleManager.md#moduletype) | Yes | No | Type of the module.
**Atomic service API**: This API can be used in atomic services since API version 11.| | preloads | Array\<[PreloadItem](#preloaditem)> | Yes | No | Preloaded modules in the atomic service.
**Atomic service API**: This API can be used in atomic services since API version 11.| diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-launcherAbilityInfo-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-launcherAbilityInfo-sys.md index 307094e7a13abcc7e5decc34d9c66f1d39121885..e4773943ca45cde60cd007e0a9fb7f6f51568f39 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-launcherAbilityInfo-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-launcherAbilityInfo-sys.md @@ -1,11 +1,11 @@ # LauncherAbilityInfo (System API) -The **LauncherAbilityInfo** module defines the ability information of the home screen application. The information can be obtained through [bundleManager.getLauncherAbilityInfo](js-apis-launcherBundleManager-sys.md#launcherbundlemanagergetlauncherabilityinfo9). +The LauncherAbilityInfo module defines the ability information of the home screen application. The information can be obtained through [bundleManager.getLauncherAbilityInfo](js-apis-launcherBundleManager-sys.md#launcherbundlemanagergetlauncherabilityinfo9). > **NOTE** > > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> +> > The APIs provided by this module are system APIs. ## LauncherAbilityInfo diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-launcherAbilityInfo.md b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-launcherAbilityInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..40018a398960d14cca2cf57683dda44c4e94e423 --- /dev/null +++ b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-launcherAbilityInfo.md @@ -0,0 +1,20 @@ +# LauncherAbilityInfo + +The LauncherAbilityInfo module describes the ability information of the launcher application. The information can be obtained by calling [getLauncherAbilityInfoSync](js-apis-launcherBundleManager.md#launcherbundlemanagergetlauncherabilityinfosync18) or [getLauncherAbilityInfo](js-apis-launcherBundleManager-sys.md#launcherbundlemanagergetlauncherabilityinfo9). + +> **NOTE** +> +> The initial APIs of this module are supported since API version 18. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## LauncherAbilityInfo + +**System capability**: SystemCapability.BundleManager.BundleFramework.Launcher + +| Name | Type | Read Only| Optional| Description | +| --------------- | ----------------------------------------------------------- | ---- | ---- | ------------------------------------ | +| applicationInfo | [ApplicationInfo](js-apis-bundleManager-applicationInfo.md) | Yes | No | Application information of the launcher ability.| +| elementName | [ElementName](js-apis-bundleManager-elementName.md) | Yes | No | Element name of the launcher ability. | +| labelId | number | Yes | No | Label ID of the launcher ability. | +| iconId | number | Yes | No | Icon ID of the launcher ability. | +| userId | number | Yes | No | User ID of the launcher ability. | +| installTime | number | Yes | No | Time when the launcher ability was installed. | diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-metadata.md b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-metadata.md index 3e5dd239d8ac3ee9deed8258dee6d87eab842aad..c49684ed5125416f3a1ea3d97be10890e92bfca3 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-metadata.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-metadata.md @@ -18,4 +18,4 @@ The **Metadata** module provides the configuration about the module, UIAbility, | name | string | No | No | Metadata name.| | value | string | No | No | Metadata value. | | resource | string | No | No | Metadata resource.| -| valueId16+ | number | Yes | Yes | ID of the metadata value. If **valueId** is not set to **0**, the current metadata value is customized, and **valueId** must be used to obtain the corresponding value from the resource manager module. If **valueId** is set to **0**, the current metadata value is a fixed string.| +| valueId18+ | number | Yes | Yes | ID of the metadata value. If **valueId** is not set to **0**, the current metadata value is customized, and **valueId** must be used to obtain the corresponding value from the resource manager module. If **valueId** is set to **0**, the current metadata value is a fixed string.| diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-overlayModuleInfo.md b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-overlayModuleInfo.md index 86af09b3e0c6ef7f5a467f90fe67ff4ff6b23f09..d8b1924ecd3720c32004d42231c610c93bf1139f 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-overlayModuleInfo.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-overlayModuleInfo.md @@ -1,6 +1,6 @@ # OverlayModuleInfo -The **OverlayModuleInfo** module provides information about a module with the overlay feature. A third-party application can obtain such information through [overlay.getOverlayModuleInfo](js-apis-overlay.md#overlaygetoverlaymoduleinfo). +The OverlayModuleInfo module provides information about a module with the overlay feature. A third-party application can obtain such information through [overlay.getOverlayModuleInfo](js-apis-overlay.md#overlaygetoverlaymoduleinfo). > **NOTE** > diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-permissionDef-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-permissionDef-sys.md index 9a45cae293b3345df72a2fb2b1a45f8338f1ca64..535212d2af3455c2300268ef5be885bd1b2eab00 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-permissionDef-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-permissionDef-sys.md @@ -1,6 +1,6 @@ # PermissionDef (System API) -The **PermissionDef** module provides permission details defined in the configuration file. The information can be obtained using [bundleManager.getPermissionDef](js-apis-bundleManager-sys.md#bundlemanagergetpermissiondef). +The PermissionDef module provides permission details defined in the configuration file. The information can be obtained using [bundleManager.getPermissionDef](js-apis-bundleManager-sys.md#bundlemanagergetpermissiondef). > **NOTE** > @@ -11,8 +11,8 @@ The **PermissionDef** module provides permission details defined in the configur ## **PermissionDef** **System capability**: SystemCapability.BundleManager.BundleFramework.Core - -**System API**: This is a system API and cannot be called by third-party applications. + +**System API**: This is a system API. | Name | Type | Read-Only| Optional| Description | | -------------- | ------ | ---- | ---- | -------------- | diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-recoverableApplicationInfo-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-recoverableApplicationInfo-sys.md index d23a92a75080e5f1000c58d01cbbaefbc553ebba..eb956a3fe7656c3e93aff8be3e12b81ef626a4a6 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-recoverableApplicationInfo-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-recoverableApplicationInfo-sys.md @@ -1,6 +1,6 @@ # RecoverableApplicationInfo (System API) -The **RecoverableApplicationInfo** module defines the information about a preinstalled application that can be restored after being uninstalled. The information can be obtained through [bundleManager.getRecoverableApplicationInfo](js-apis-bundleManager.md). +The RecoverableApplicationInfo module defines the information about a preinstalled application that can be restored after being uninstalled. The information can be obtained through [bundleManager.getRecoverableApplicationInfo](./js-apis-bundleManager-sys.md#bundlemanagergetrecoverableapplicationinfo11). > **NOTE** > @@ -22,6 +22,6 @@ Defines the information about a preinstalled application that can be restored af | moduleName | string | Yes | No | Module name.| | labelId | number | Yes | No | ID of the module label. | | iconId | number | Yes | No | ID of the module icon. | -| systemApp | boolean | Yes | No | Whether the application is a system application.| -| bundleType |[BundleType](js-apis-bundleManager.md#bundletype) | Yes | No | Bundle type, which can be **APP** (application) or **ATOMIC_SERVICE** (atomic service). | -| codePaths | Array\ | Yes | No | Installation directory of the application. | +| systemApp12+ | boolean | Yes | No | Whether the application is a system application. The value **true** means that the application is a system application, and **false** means the opposite. | +| bundleType12+ |[BundleType](js-apis-bundleManager.md#bundletype) | Yes | No | Bundle type, which can be **APP** (application) or **ATOMIC_SERVICE** (atomic service). | +| codePaths12+ | Array\ | Yes | No | Installation directory of the application. | diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-remoteAbilityInfo-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-remoteAbilityInfo-sys.md index 57ff2c9c17a7e8a2442936aa3a6ec71268ee2469..05800e68f1a4cab4144e25705b1da891a9550518 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-remoteAbilityInfo-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-remoteAbilityInfo-sys.md @@ -10,9 +10,9 @@ The **RemoteAbilityInfo** module provides information about a remote ability, wh ## RemoteAbilityInfo -**System capability**: SystemCapability.BundleManager.DistributedBundleFramework + **System capability**: SystemCapability.BundleManager.DistributedBundleFramework -**System API**: This is a system API. + **System API**: This is a system API. | Name | Type | Read-Only| Optional| Description | | ----------- | -------------------------------------------- | ---- | ---- | ----------------------- | diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-shortcutInfo-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-shortcutInfo-sys.md index 70060dedb2847cb247d0de848c53a7c7fce2bbc6..c91111ec0280490f490122f579b69a985f89abe1 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-shortcutInfo-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-shortcutInfo-sys.md @@ -1,12 +1,12 @@ # ShortcutInfo (System API) -The **ShortcutInfo** module defines shortcut information configured in the configuration file. The information can be obtained through [getShortcutInfo](js-apis-launcherBundleManager-sys.md#launcherbundlemanagergetshortcutinfo9). +The ShortcutInfo module defines shortcut information configured in the configuration file. The information can be obtained through [getShortcutInfo](js-apis-launcherBundleManager-sys.md#launcherbundlemanagergetshortcutinfo9). > **NOTE** > > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > -> For the FA model, the shortcut information is configured in the [config.json](../../quick-start/module-structure.md) file. For details about the shortcut information in the stage model, see [shortcuts](../../quick-start/module-configuration-file.md#shortcuts). +> For the FA model, the shortcut information is configured in the [config.json](../../quick-start/module-structure.md#internal-structure-of-the-shortcuts-attribute) file. For details about the shortcut information in the stage model, see [shortcuts](../../quick-start/module-configuration-file.md#shortcuts). > > The APIs provided by this module are system APIs. @@ -27,7 +27,7 @@ The **ShortcutInfo** module defines shortcut information configured in the confi **System capability**: SystemCapability.BundleManager.BundleFramework.Launcher - **System API**: This is a system API. +**System API**: This is a system API. | Name | Type | Read-Only| Optional| Description | | ----------------------- | ------------------------------------------ | ---- | ---- | ---------------------------- | diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-skill.md b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-skill.md index 3c564c58fef879e5d5c6b77311229f98725d6921..93ef12449619b18224b46f8855ce81b160df30f0 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-skill.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-skill.md @@ -22,7 +22,7 @@ import { bundleManager } from '@kit.AbilityKit'; | actions | Array\ | Yes | No | Actions received by the skill.| | entities | Array\ | Yes | No | Entities received by the skill. | | uris | Array\ | Yes | No | URIs that match Want.| -| domainVerify | boolean | Yes | No | DomainVerify value received by the skill. This parameter exists only in **AbilityInfo**.| +| domainVerify | boolean | Yes | No | DomainVerify value received by the skill. This parameter exists only in **AbilityInfo** and specifies whether domain name verification is enabled. The value **true** means that domain name verification is enabled, and **false** means the opposite.| ## SkillUri diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-sys.md index 4373ef104917b388f9ef828f7fe87a5ad01892f8..b04e95e7bb07219e3de16744bc5f218e87742774 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager-sys.md @@ -1,6 +1,6 @@ # @ohos.bundle.bundleManager (bundleManager) (System API) -The bundleManager module provides APIs for obtaining application information, including [BundleInfo](js-apis-bundleManager-BundleInfo-sys.md), [ApplicationInfo](js-apis-bundleManager-ApplicationInfo-sys.md), [AbilityInfo](js-apis-bundleManager-abilityInfo.md), and [ExtensionAbility](js-apis-bundleManager-extensionAbilityInfo.md). +The bundleManager module provides APIs for obtaining application information, including [BundleInfo](js-apis-bundleManager-bundleInfo.md), [ApplicationInfo](js-apis-bundleManager-ApplicationInfo-sys.md), [AbilityInfo](js-apis-bundleManager-abilityInfo.md), and [ExtensionAbility](js-apis-bundleManager-extensionAbilityInfo.md). > **NOTE** > @@ -26,9 +26,7 @@ import { bundleManager } from '@kit.AbilityKit'; For details about the APL, see [Basic Concepts in the Permission Mechanism](../../security/AccessToken/app-permission-mgmt-overview.md#basic-concepts-in-the-permission-mechanism). -## Enums - -### BundleFlag +## BundleFlag Enumerates the bundle flags, which indicate the type of bundle information to obtain. @@ -52,13 +50,13 @@ Enumerates the bundle flags, which indicate the type of bundle information to ob | GET_BUNDLE_INFO_OF_ANY_USER12+ | 0x00002000 | Used to obtain the bundle information of an application installed by any user. It must be used together with **GET_BUNDLE_INFO_WITH_APPLICATION**. It is valid only in the [getBundleInfo](#bundlemanagergetbundleinfo14) and [getAllBundleInfo](#bundlemanagergetallbundleinfo) APIs.
**System API**: This enumerated value can be used in system APIs since API version 12.| | GET_BUNDLE_INFO_EXCLUDE_CLONE12+ | 0x00004000 | Used to obtain the bundle information of a main application (excluding its clones). It is valid only in the [getAllBundleInfo](#bundlemanagergetallbundleinfo) API.| -### ApplicationFlag +## ApplicationFlag Enumerates the application flags, which indicate the type of application information to obtain. - **System capability**: SystemCapability.BundleManager.BundleFramework.Core +**System capability**: SystemCapability.BundleManager.BundleFramework.Core - **System API**: This is a system API. +**System API**: This is a system API. | Name | Value | Description | | ------------------------------------ | ---------- | ------------------------------------------------------------ | @@ -67,13 +65,13 @@ Enumerates the application flags, which indicate the type of application informa | GET_APPLICATION_INFO_WITH_METADATA | 0x00000002 | Used to obtain the application information with metadata. | | GET_APPLICATION_INFO_WITH_DISABLE | 0x00000004 | Used to obtain the application information of disabled bundles. | -### AbilityFlag +## AbilityFlag Enumerates the ability flags, which indicate the type of ability information to obtain. - **System capability**: SystemCapability.BundleManager.BundleFramework.Core +**System capability**: SystemCapability.BundleManager.BundleFramework.Core - **System API**: This is a system API. +**System API**: This is a system API. | Name | Value | Description | | --------------------------------- | ---------- | ------------------------------------------------------------ | @@ -86,13 +84,13 @@ Enumerates the ability flags, which indicate the type of ability information to | GET_ABILITY_INFO_WITH_APP_LINKING12+ | 0x00000040 | Used to obtain the ability information filtered by domain name verification. | | GET_ABILITY_INFO_WITH_SKILL12+ | 0x00000080 | Used to obtain the ability information with skills. | -### ExtensionAbilityFlag +## ExtensionAbilityFlag Enumerates the ExtensionAbility flags, which indicate the type of ExtensionAbility information to obtain. - **System capability**: SystemCapability.BundleManager.BundleFramework.Core +**System capability**: SystemCapability.BundleManager.BundleFramework.Core - **System API**: This is a system API. +**System API**: This is a system API. | Name | Value | Description | | ------------------------------------------- | ---------- | ------------------------------------------------------------ | @@ -102,25 +100,25 @@ Enumerates the ExtensionAbility flags, which indicate the type of ExtensionAbili | GET_EXTENSION_ABILITY_INFO_WITH_METADATA | 0x00000004 | Used to obtain the ExtensionAbility information with metadata. | | GET_EXTENSION_ABILITY_INFO_WITH_SKILL12+ | 0x00000010 | Used to obtain the ExtensionAbility information with skills. | -### ProfileType11+ +## ProfileType11+ Enumerates the types of profiles (also called application files). - **System capability**: SystemCapability.BundleManager.BundleFramework.Core +**System capability**: SystemCapability.BundleManager.BundleFramework.Core - **System API**: This is a system API. +**System API**: This is a system API. | Name | Value | Description | | -------------- | ---- | --------------- | | INTENT_PROFILE | 1 | Profile of the InsightIntent framework. | -### AppDistributionType12+ +## AppDistributionType12+ -Enumerates the application distribution types. +Enumerates the application [distribution types](../../security/app-provision-structure.md). - **System capability**: SystemCapability.BundleManager.BundleFramework.Core +**System capability**: SystemCapability.BundleManager.BundleFramework.Core - **System API**: This is a system API. +**System API**: This is a system API. | Name | Value | Description | | ----------------- | ---- | --------------- | @@ -128,11 +126,11 @@ Enumerates the application distribution types. | ENTERPRISE | 2 | Enterprise application that can be installed on personal devices. | | ENTERPRISE_NORMAL | 3 | Common enterprise application that can be installed on enterprise devices only through an enterprise mobile device management (MDM) application. The applications of this type do not require device management privileges. | | ENTERPRISE_MDM | 4 | Enterprise MDM application that can be installed only on enterprise devices. The applications of this type must have device management privileges, such as remote locking devices and installing common enterprise applications on devices. | -| OS_INTEGRATION | 5 | Preset system application. | +| OS_INTEGRATION | 5 | Preinstalled system application. | | CROWDTESTING | 6 | Crowdtesting application. | | NONE | 7 | Other. | -### ApplicationInfoFlag12+ +## ApplicationInfoFlag12+ Enumerates the application information flag, which describes the status between an application and user. **System capability**: SystemCapability.BundleManager.BundleFramework.Core @@ -141,11 +139,12 @@ Enumerates the application information flag, which describes the status between | Name| Value| Description| |----------------|---|---| -| FLAG_INSTALLED| 0x00000001 | Status between the application and user. The value **1** means that the application is installed by the specified user, and **0** means the opposite.| +| FLAG_INSTALLED| 0x00000001 | The application is installed for the specified user.| +| FLAG_OTHER_INSTALLED15+| 0x00000010 | The application is installed for users other than the specified user.| +| FLAG_PREINSTALLED_APP15+| 0x00000020 | The application is a preinstalled application.| +| FLAG_PREINSTALLED_APP_UPDATE15+| 0x00000040 | The preinstalled application is updated.| -## APIs - -### bundleManager.getBundleInfo14+ +## bundleManager.getBundleInfo14+ getBundleInfo(bundleName: string, bundleFlags: number, userId: number, callback: AsyncCallback\): void @@ -226,7 +225,7 @@ try { } ``` -### bundleManager.getBundleInfo14+ +## bundleManager.getBundleInfo14+ getBundleInfo(bundleName: string, bundleFlags: number, callback: AsyncCallback\): void @@ -281,7 +280,7 @@ try { } ``` -### bundleManager.getBundleInfo14+ +## bundleManager.getBundleInfo14+ getBundleInfo(bundleName: string, bundleFlags: number, userId?: number): Promise\ @@ -362,7 +361,7 @@ try { ``` -### bundleManager.getApplicationInfo +## bundleManager.getApplicationInfo getApplicationInfo(bundleName: string, appFlags: number, userId: number, callback: AsyncCallback\): void @@ -422,7 +421,7 @@ try { } ``` -### bundleManager.getApplicationInfo +## bundleManager.getApplicationInfo getApplicationInfo(bundleName: string, appFlags: number, callback: AsyncCallback\): void @@ -479,7 +478,7 @@ try { } ``` -### bundleManager.getApplicationInfo +## bundleManager.getApplicationInfo getApplicationInfo(bundleName: string, appFlags: number, userId?: number): Promise\ @@ -542,11 +541,11 @@ try { } ``` -### bundleManager.getAllBundleInfo +## bundleManager.getAllBundleInfo getAllBundleInfo(bundleFlags: number, userId: number, callback: AsyncCallback>): void -Obtains the information about all bundles based on the given bundle flags and user ID. This API uses an asynchronous callback to return the result. +Obtains all the bundle information in the system based on the given bundle flags and user ID. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -596,11 +595,11 @@ try { } ``` -### bundleManager.getAllBundleInfo +## bundleManager.getAllBundleInfo getAllBundleInfo(bundleFlags: number, callback: AsyncCallback>): void -Obtains the information about all bundles based on the given bundle flags. This API uses an asynchronous callback to return the result. +Obtains all the bundle information in the system based on the given bundle flags. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -647,11 +646,11 @@ try { } ``` -### bundleManager.getAllBundleInfo +## bundleManager.getAllBundleInfo getAllBundleInfo(bundleFlags: number, userId?: number): Promise> -Obtains the information about all bundles based on the given bundle flags and user ID. This API uses a promise to return the result. +Obtains all the bundle information in the system based on the given bundle flags and user ID. This API uses a promise to return the result. **System API**: This is a system API. @@ -703,11 +702,11 @@ try { } ``` -### bundleManager.getAllApplicationInfo +## bundleManager.getAllApplicationInfo getAllApplicationInfo(appFlags: number, userId: number, callback: AsyncCallback>): void -Obtains the information about all applications based on the given application flags and user ID. This API uses an asynchronous callback to return the result. +Obtains all the application information in the system based on the given application flags and user ID. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -757,11 +756,11 @@ try { } ``` -### bundleManager.getAllApplicationInfo +## bundleManager.getAllApplicationInfo getAllApplicationInfo(appFlags: number, callback: AsyncCallback>): void -Obtains the information about all applications based on the given application flags. This API uses an asynchronous callback to return the result. +Obtains all the application information in the system based on the given application flags. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -808,11 +807,11 @@ try { } ``` -### bundleManager.getAllApplicationInfo +## bundleManager.getAllApplicationInfo getAllApplicationInfo(appFlags: number, userId?: number): Promise> -Obtains the information about all applications based on the given application flags and user ID. This API uses a promise to return the result. +Obtains all the application information in the system based on the given application flags and user ID. This API uses a promise to return the result. **System API**: This is a system API. @@ -865,11 +864,11 @@ try { ``` -### bundleManager.queryAbilityInfo +## bundleManager.queryAbilityInfo queryAbilityInfo(want: Want, abilityFlags: number, userId: number, callback: AsyncCallback>): void -Obtains an array of ability information based on the given want, ability flags, and user ID. This API uses an asynchronous callback to return the result. +Obtains the ability information based on the given Want, ability flags, and user ID. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -929,11 +928,11 @@ try { } ``` -### bundleManager.queryAbilityInfo +## bundleManager.queryAbilityInfo queryAbilityInfo(want: Want, abilityFlags: number, callback: AsyncCallback>): void -Obtains an array of ability information based on the given want and ability flags. This API uses an asynchronous callback to return the result. +Obtains the ability information based on the given Want and ability flags. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -990,11 +989,11 @@ try { } ``` -### bundleManager.queryAbilityInfo +## bundleManager.queryAbilityInfo queryAbilityInfo(want: Want, abilityFlags: number, userId?: number): Promise> -Obtains the ability information based on the given want, ability flags, and user ID. This API uses a promise to return the result. +Obtains the ability information based on the given Want, ability flags, and user ID. This API uses a promise to return the result. **System API**: This is a system API. @@ -1080,7 +1079,7 @@ try { } ``` -### bundleManager.queryAbilityInfoSync10+ +## bundleManager.queryAbilityInfoSync10+ queryAbilityInfoSync(want: Want, abilityFlags: number, userId?: number): Array\ @@ -1165,11 +1164,11 @@ try { } ``` -### bundleManager.queryAbilityInfo12+ +## bundleManager.queryAbilityInfo12+ queryAbilityInfo(wants: Array\, abilityFlags: number, userId?: number): Promise> -Obtains the ability information based on the given want list, ability flags, and user ID. +Obtains the ability information based on the given Want list, ability flags, and user ID. This API uses a promise to return the result. **System API**: This is a system API. @@ -1236,11 +1235,11 @@ let wants: Array = [ want, want1 ]; } ``` -### bundleManager.queryExtensionAbilityInfo +## bundleManager.queryExtensionAbilityInfo queryExtensionAbilityInfo(want: Want, extensionAbilityType: ExtensionAbilityType, extensionAbilityFlags: number, userId: number, callback: AsyncCallback>): void -Obtains the ExtensionAbility information based on the given want, ExtensionAbility type, ExtensionAbility flags, and user ID. This API uses an asynchronous callback to return the result. +Obtains the ExtensionAbility information based on the given Want, ExtensionAbility type, ExtensionAbility flags, and user ID. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -1301,11 +1300,11 @@ try { } ``` -### bundleManager.queryExtensionAbilityInfo +## bundleManager.queryExtensionAbilityInfo queryExtensionAbilityInfo(want: Want, extensionAbilityType: ExtensionAbilityType, extensionAbilityFlags: number, callback: AsyncCallback>): void -Obtains the ExtensionAbility information based on the given want, ExtensionAbility type, and ExtensionAbility flags. This API uses an asynchronous callback to return the result. +Obtains the ExtensionAbility information based on the given Want, ExtensionAbility type, and ExtensionAbility flags. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -1363,11 +1362,11 @@ try { } ``` -### bundleManager.queryExtensionAbilityInfo +## bundleManager.queryExtensionAbilityInfo queryExtensionAbilityInfo(want: Want, extensionAbilityType: ExtensionAbilityType, extensionAbilityFlags: number, userId?: number): Promise> -Obtains the ExtensionAbility information based on the given want, ExtensionAbility type, ExtensionAbility flags, and user ID. This API uses a promise to return the result. +Obtains the ExtensionAbility information based on the given Want, ExtensionAbility type, ExtensionAbility flags, and user ID. This API uses a promise to return the result. **System API**: This is a system API. @@ -1456,7 +1455,7 @@ try { } ``` -### bundleManager.queryExtensionAbilityInfoSync10+ +## bundleManager.queryExtensionAbilityInfoSync10+ queryExtensionAbilityInfoSync(want: Want, extensionAbilityType: ExtensionAbilityType, extensionAbilityFlags: number, userId?: number): Array\ @@ -1543,7 +1542,7 @@ try { } ``` -### bundleManager.getBundleNameByUid14+ +## bundleManager.getBundleNameByUid14+ getBundleNameByUid(uid: number, callback: AsyncCallback\): void @@ -1591,7 +1590,7 @@ try { } ``` -### bundleManager.getBundleNameByUid14+ +## bundleManager.getBundleNameByUid14+ getBundleNameByUid(uid: number): Promise\ @@ -1642,7 +1641,7 @@ try { } ``` -### bundleManager.getBundleNameByUidSync14+ +## bundleManager.getBundleNameByUidSync14+ getBundleNameByUidSync(uid: number): string @@ -1690,7 +1689,7 @@ try { } ``` -### bundleManager.getBundleArchiveInfo +## bundleManager.getBundleArchiveInfo getBundleArchiveInfo(hapFilePath: string, bundleFlags: number, callback: AsyncCallback\): void @@ -1744,7 +1743,7 @@ try { } ``` -### bundleManager.getBundleArchiveInfo +## bundleManager.getBundleArchiveInfo getBundleArchiveInfo(hapFilePath: string, bundleFlags: number): Promise\ @@ -1801,7 +1800,7 @@ try { } ``` -### bundleManager.getBundleArchiveInfoSync10+ +## bundleManager.getBundleArchiveInfoSync10+ getBundleArchiveInfoSync(hapFilePath: string, bundleFlags: number): BundleInfo @@ -1855,11 +1854,105 @@ try { } ``` -### bundleManager.cleanBundleCacheFiles +## bundleManager.getAllBundleCacheSize15+ + +getAllBundleCacheSize(): Promise\ + +Obtains the global cache size. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------- | +| Promise\ | Promise used to return the size of the global cache, in bytes.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). + +| ID| Error Message | +| -------- | ---------------------------------------------------------- | +| 201 | Permission denied. | +| 202 | Permission denied, non-system app called system api. | + +**Example** + +```ts +import { bundleManager } from '@kit.AbilityKit'; +import { BusinessError } from '@kit.BasicServicesKit'; +import { hilog } from '@kit.PerformanceAnalysisKit'; + +try { + bundleManager.getAllBundleCacheSize().then((data) => { + hilog.info(0x0000, 'testTag','getAllBundleCacheSize successful. Data: ' + JSON.stringify(data)); + }).catch((err: BusinessError) => { + hilog.error(0x0000, 'testTag', 'getAllBundleCacheSize failed: %{public}s', err.message); + }); +} catch (err) { + let message = (err as BusinessError).message; + hilog.error(0x0000, 'testTag', 'getAllBundleCacheSize failed: %{public}s', message); +} +``` + +## bundleManager.cleanAllBundleCache15+ + +cleanAllBundleCache(): Promise\ + +Clears the global cache. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.REMOVE_CACHE_FILES + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------- | +| Promise\ | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). + +| ID| Error Message | +| -------- | ---------------------------------------------------------- | +| 201 | Permission denied. | +| 202 | Permission denied, non-system app called system api. | + +**Example** + +```ts +import { bundleManager } from '@kit.AbilityKit'; +import { BusinessError } from '@kit.BasicServicesKit'; +import { hilog } from '@kit.PerformanceAnalysisKit'; + +try { + bundleManager.cleanAllBundleCache().then((data) => { + hilog.info(0x0000, 'testTag','cleanAllBundleCache successful.'); + }).catch((err: BusinessError) => { + hilog.error(0x0000, 'testTag', 'cleanAllBundleCache failed: %{public}s', err.message); + }); +} catch (err) { + let message = (err as BusinessError).message; + hilog.error(0x0000, 'testTag', 'cleanAllBundleCache failed: %{public}s', message); +} +``` + +## bundleManager.cleanBundleCacheFiles cleanBundleCacheFiles(bundleName: string, callback: AsyncCallback\): void -Clears the cache files based on the given bundle name. This API uses an asynchronous callback to return the result. +Clears the bundle cache based on the given bundle name. This API uses an asynchronous callback to return the result. + +No permission is required when the caller clears its own cache. **System API**: This is a system API. @@ -1908,11 +2001,13 @@ try { } ``` -### bundleManager.cleanBundleCacheFiles +## bundleManager.cleanBundleCacheFiles cleanBundleCacheFiles(bundleName: string): Promise\ -Clears the cache files based on the given bundle name. This API uses a promise to return the result. +Clears the bundle cache based on the given bundle name. This API uses a promise to return the result. + +No permission is required when the caller clears its own cache. **System API**: This is a system API. @@ -1964,7 +2059,68 @@ try { } ``` -### bundleManager.setApplicationEnabled +## bundleManager.cleanBundleCacheFiles15+ + +cleanBundleCacheFiles(bundleName: string, appIndex: number): Promise\ + +Clears the bundle cache based on the given bundle name and application index. This API uses a promise to return the result. + +No permission is required when the caller clears its own cache. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.REMOVE_CACHE_FILES + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------ | ---- | ------------------------------------------ | +| bundleName | string | Yes | Bundle name.| +| appIndex | number | Yes | Index of the application clone.
The value **0** means to clear the cache of the main application. A value greater than 0 means to clear the cache data of the application clone.| + +**Return value** + +| Type | Description | +| -------------- | ------------------------------------------------------------ | +| Promise\ | Promise that returns no value. If clearing the cache files fails, an error object is thrown.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). + +| ID| Error Message | +| -------- | ---------------------------------------------------------- | +| 201 | Permission denied. | +| 202 | Permission denied, non-system app called system api. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.| +| 17700001 | The specified bundleName is not found. | +| 17700030 | The specified bundle does not support clearing of cache files. | +| 17700061 | AppIndex is not in the valid range. | + +**Example** + +```ts +import { bundleManager } from '@kit.AbilityKit'; +import { BusinessError } from '@kit.BasicServicesKit'; +import { hilog } from '@kit.PerformanceAnalysisKit'; +let bundleName = "com.ohos.myapplication"; +let appIndex = 1; + +try { + bundleManager.cleanBundleCacheFiles(bundleName, appIndex).then(() => { + hilog.info(0x0000, 'testTag', 'cleanBundleCacheFiles successfully.'); + }).catch((err: BusinessError) => { + hilog.error(0x0000, 'testTag', 'cleanBundleCacheFiles failed: %{public}s', err.message); + }); +} catch (err) { + let message = (err as BusinessError).message; + hilog.error(0x0000, 'testTag', 'cleanBundleCacheFiles failed: %{public}s', message); +} +``` + +## bundleManager.setApplicationEnabled setApplicationEnabled(bundleName: string, isEnabled: boolean, callback: AsyncCallback\): void @@ -2017,7 +2173,7 @@ try { } ``` -### bundleManager.setApplicationEnabled +## bundleManager.setApplicationEnabled setApplicationEnabled(bundleName: string, isEnabled: boolean): Promise\ @@ -2073,7 +2229,7 @@ try { } ``` -### bundleManager.setApplicationEnabled12+ +## bundleManager.setApplicationEnabled12+ setApplicationEnabled(bundleName: string, appIndex: number, isEnabled: boolean): Promise\ @@ -2090,8 +2246,8 @@ Enables or disables an application or an application clone. This API uses a prom | Name | Type | Mandatory| Description | | ---------- | ------- | ---- | ------------------------------------- | | bundleName | string | Yes | Bundle name. | -| appIndex | number | Yes | Index of the application clone.
If this parameter is set to **0**, the API is used to enable or disable an application, rather than an application clone. | -| isEnabled | boolean | Yes | Whether to enable the application or the application clone. The value **true** means to enable it, and **false** means to disable it.| +| appIndex | number | Yes | Index of the application clone.
The value **0** means to enable or disable the main application. A value greater than 0 means to enable or disable the application clone. | +| isEnabled | boolean | Yes | Whether to enable the application or application clone. The value **true** means to enable it, and **false** means to disable it.| **Return value** @@ -2131,7 +2287,7 @@ try { } ``` -### bundleManager.setApplicationEnabledSync10+ +## bundleManager.setApplicationEnabledSync10+ setApplicationEnabledSync(bundleName: string, isEnabled: boolean): void @@ -2178,7 +2334,7 @@ try { } ``` -### bundleManager.setAbilityEnabled +## bundleManager.setAbilityEnabled setAbilityEnabled(info: AbilityInfo, isEnabled: boolean, callback: AsyncCallback\): void @@ -2245,7 +2401,7 @@ try { } ``` -### bundleManager.setAbilityEnabled +## bundleManager.setAbilityEnabled setAbilityEnabled(info: AbilityInfo, isEnabled: boolean): Promise\ @@ -2315,7 +2471,7 @@ try { } ``` -### bundleManager.setAbilityEnabled12+ +## bundleManager.setAbilityEnabled12+ setAbilityEnabled(info: AbilityInfo, appIndex: number, isEnabled: boolean): Promise\ @@ -2332,7 +2488,7 @@ Enables or disables an ability of an application or an application clone. This A | Name | Type | Mandatory| Description | | -------- | ----------- | ---- | ------------------------------------- | | info | [AbilityInfo](js-apis-bundleManager-abilityInfo.md) | Yes | Information about the target ability. | -| appIndex | number | Yes | Index of the application clone.
If this parameter is set to **0**, the API is used to enable or disable the ability of an application, rather than an application clone. | +| appIndex | number | Yes | Index of the application clone.
The value **0** means to enable or disable the ability of the main application. A value greater than 0 means to enable or disable the ability of the application clone. | | isEnabled| boolean | Yes | Whether to enable the ability. The value **true** means to enable it, and **false** means to disable it.| **Return value** @@ -2387,7 +2543,7 @@ try { } ``` -### bundleManager.setAbilityEnabledSync10+ +## bundleManager.setAbilityEnabledSync10+ setAbilityEnabledSync(info: AbilityInfo, isEnabled: boolean): void @@ -2453,7 +2609,7 @@ try { } ``` -### bundleManager.isApplicationEnabled +## bundleManager.isApplicationEnabled isApplicationEnabled(bundleName: string, callback: AsyncCallback\): void @@ -2502,7 +2658,7 @@ try { } ``` -### bundleManager.isApplicationEnabled +## bundleManager.isApplicationEnabled isApplicationEnabled(bundleName: string): Promise\ @@ -2554,7 +2710,7 @@ try { } ``` -### bundleManager.isApplicationEnabled12+ +## bundleManager.isApplicationEnabled12+ isApplicationEnabled(bundleName: string, appIndex: number): Promise\ @@ -2569,7 +2725,7 @@ Checks whether an application or an application clone is enabled. This API uses | Name | Type | Mandatory| Description | | ---------- | ------ | ---- | -------------------------- | | bundleName | string | Yes | Bundle name. | -| appIndex | number | Yes | Index of the application clone.
If this parameter is set to **0**, the API is used to obtain the enabled status of an application, rather than an application clone. | +| appIndex | number | Yes | Index of the application clone.
The value **0** means to obtain the enabled status of the main application. A value greater than 0 means to obtain the enabled status of the application clone. | **Return value** @@ -2608,7 +2764,7 @@ try { } ``` -### bundleManager.isApplicationEnabledSync10+ +## bundleManager.isApplicationEnabledSync10+ isApplicationEnabledSync(bundleName: string): boolean @@ -2657,7 +2813,7 @@ try { } ``` -### bundleManager.isAbilityEnabled +## bundleManager.isAbilityEnabled isAbilityEnabled(info: AbilityInfo, callback: AsyncCallback\): void @@ -2720,7 +2876,7 @@ try { } ``` -### bundleManager.isAbilityEnabled +## bundleManager.isAbilityEnabled isAbilityEnabled(info: AbilityInfo): Promise\ @@ -2786,7 +2942,7 @@ try { } ``` -### bundleManager.isAbilityEnabled12+ +## bundleManager.isAbilityEnabled12+ isAbilityEnabled(info: AbilityInfo, appIndex: number): Promise\ @@ -2801,7 +2957,7 @@ Checks whether an ability of an application or an application clone is enabled. | Name| Type | Mandatory| Description | | ---- | ----------- | ---- | --------------------------- | | info | [AbilityInfo](js-apis-bundleManager-abilityInfo.md) | Yes | Information about the target ability.| -| appIndex | number | Yes | Index of the application clone.
If this parameter is set to **0**, the API is used to obtain the enabled status of the ability of an application, rather than an application clone. | +| appIndex | number | Yes | Index of the application clone.
The value **0** means to obtain the enabled status of the ability of the main application. A value greater than 0 means to obtain the enabled status of the ability of the application clone. | **Return value** @@ -2854,7 +3010,7 @@ try { } ``` -### bundleManager.isAbilityEnabledSync10+ +## bundleManager.isAbilityEnabledSync10+ isAbilityEnabledSync(info: AbilityInfo): boolean @@ -2922,7 +3078,7 @@ try { } ``` -### bundleManager.getLaunchWantForBundle +## bundleManager.getLaunchWantForBundle getLaunchWantForBundle(bundleName: string, userId: number, callback: AsyncCallback\): void @@ -2978,7 +3134,7 @@ try { } ``` -### bundleManager.getLaunchWantForBundle +## bundleManager.getLaunchWantForBundle getLaunchWantForBundle(bundleName: string, callback: AsyncCallback\): void @@ -3031,7 +3187,7 @@ try { } ``` -### bundleManager.getLaunchWantForBundle +## bundleManager.getLaunchWantForBundle getLaunchWantForBundle(bundleName: string, userId?: number): Promise\ @@ -3091,7 +3247,7 @@ try { ``` -### bundleManager.getLaunchWantForBundleSync10+ +## bundleManager.getLaunchWantForBundleSync10+ getLaunchWantForBundleSync(bundleName: string, userId?: number): Want @@ -3165,11 +3321,11 @@ try { } ``` -### bundleManager.getPermissionDef +## bundleManager.getPermissionDef getPermissionDef(permissionName: string, callback: AsyncCallback\): void -Obtains the **PermissionDef** struct based on the given permission name. This API uses an asynchronous callback to return the result. +Obtains the PermissionDef struct based on the given permission name. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -3216,11 +3372,11 @@ try { } ``` -### bundleManager.getPermissionDef +## bundleManager.getPermissionDef getPermissionDef(permissionName: string): Promise\ -Obtains the **PermissionDef** struct based on the given permission name. This API uses a promise to return the result. +Obtains the PermissionDef struct based on the given permission name. This API uses a promise to return the result. **System API**: This is a system API. @@ -3270,7 +3426,7 @@ try { } ``` -### bundleManager.getPermissionDefSync10+ +## bundleManager.getPermissionDefSync10+ getPermissionDefSync(permissionName: string): PermissionDef; @@ -3321,11 +3477,11 @@ try { } ``` -### bundleManager.getAbilityLabel +## bundleManager.getAbilityLabel getAbilityLabel(bundleName: string, moduleName: string, abilityName: string, callback: AsyncCallback\): void -Obtains the ability label based on the given bundle name, module name, and ability name. This API uses an asynchronous callback to return the result. +Obtains the label based on the given bundle name, module name, and ability name. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -3382,11 +3538,11 @@ try { } ``` -### bundleManager.getAbilityLabel +## bundleManager.getAbilityLabel getAbilityLabel(bundleName: string, moduleName: string, abilityName: string): Promise\ -Obtains the ability label based on the given bundle name, module name, and ability name. This API uses a promise to return the result. +Obtains the label based on the given bundle name, module name, and ability name. This API uses a promise to return the result. **System API**: This is a system API. @@ -3446,7 +3602,7 @@ try { } ``` -### bundleManager.getAbilityLabelSync10+ +## bundleManager.getAbilityLabelSync10+ getAbilityLabelSync(bundleName: string, moduleName: string, abilityName: string): string @@ -3507,7 +3663,7 @@ try { } ``` -### bundleManager.getApplicationInfoSync +## bundleManager.getApplicationInfoSync getApplicationInfoSync(bundleName: string, applicationFlags: number, userId: number) : ApplicationInfo @@ -3565,7 +3721,7 @@ try { } ``` -### bundleManager.getApplicationInfoSync +## bundleManager.getApplicationInfoSync getApplicationInfoSync(bundleName: string, applicationFlags: number) : ApplicationInfo @@ -3620,7 +3776,7 @@ try { } ``` -### bundleManager.getBundleInfoSync14+ +## bundleManager.getBundleInfoSync14+ getBundleInfoSync(bundleName: string, bundleFlags: number, userId: number): BundleInfo @@ -3677,7 +3833,7 @@ try { } ``` -### bundleManager.getBundleInfoSync14+ +## bundleManager.getBundleInfoSync14+ getBundleInfoSync(bundleName: string, bundleFlags: number): BundleInfo @@ -3730,7 +3886,7 @@ try { } ``` -### bundleManager.getSharedBundleInfo10+ +## bundleManager.getSharedBundleInfo10+ getSharedBundleInfo(bundleName: string, moduleName: string, callback: AsyncCallback\\>): void @@ -3785,7 +3941,7 @@ try { } ``` -### bundleManager.getSharedBundleInfo10+ +## bundleManager.getSharedBundleInfo10+ getSharedBundleInfo(bundleName: string, moduleName: string): Promise\\> @@ -3843,11 +3999,11 @@ try { } ``` -### bundleManager.getAllSharedBundleInfo10+ +## bundleManager.getAllSharedBundleInfo10+ getAllSharedBundleInfo(callback: AsyncCallback\\>): void -Obtains the information about all shared bundles. This API uses an asynchronous callback to return the result. +Obtains all the shared bundle information. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -3891,11 +4047,11 @@ try { } ``` -### bundleManager.getAllSharedBundleInfo10+ +## bundleManager.getAllSharedBundleInfo10+ getAllSharedBundleInfo(): Promise\\> -Obtains the information about all shared bundles. This API uses a promise to return the result. +Obtains all the shared bundle information. This API uses a promise to return the result. **System API**: This is a system API. @@ -3937,7 +4093,7 @@ try { } ``` -### bundleManager.getAppProvisionInfo10+ +## bundleManager.getAppProvisionInfo10+ getAppProvisionInfo(bundleName: string, callback: AsyncCallback\): void @@ -3989,7 +4145,7 @@ try { } ``` -### bundleManager.getAppProvisionInfo10+ +## bundleManager.getAppProvisionInfo10+ getAppProvisionInfo(bundleName: string, userId: number, callback: AsyncCallback\): void @@ -4045,7 +4201,7 @@ try { } ``` -### bundleManager.getAppProvisionInfo10+ +## bundleManager.getAppProvisionInfo10+ getAppProvisionInfo(bundleName: string, userId?: number): Promise\ @@ -4115,7 +4271,7 @@ try { } ``` -### bundleManager.getAppProvisionInfoSync10+ +## bundleManager.getAppProvisionInfoSync10+ getAppProvisionInfoSync(bundleName: string, userId?: number): AppProvisionInfo @@ -4179,10 +4335,10 @@ try { } ``` -### bundleManager.getSpecifiedDistributionType10+ +## bundleManager.getSpecifiedDistributionType10+ getSpecifiedDistributionType(bundleName: string): string -Obtains the distribution type of a bundle in synchronous mode. The return value is the **specifiedDistributionType** field value in [InstallParam](./js-apis-installer-sys.md#installparam) passed when **install** is called. +Obtains the [distribution type](../../security/app-provision-structure.md) of a bundle in synchronous mode. The return value is the **specifiedDistributionType** field value in [InstallParam](./js-apis-installer-sys.md#installparam) passed when **install** is called. **System API**: This is a system API. @@ -4200,7 +4356,7 @@ Obtains the distribution type of a bundle in synchronous mode. The return value | Type | Description | | ------------- | -------------------------------------- | -| string | Distribution type of the bundle.| +| string | [Distribution type](../../security/app-provision-structure.md) of the bundle.| **Error codes** @@ -4229,7 +4385,7 @@ try { ``` -### bundleManager.getAdditionalInfo10+ +## bundleManager.getAdditionalInfo10+ getAdditionalInfo(bundleName: string): string @@ -4280,7 +4436,7 @@ try { } ``` -### bundleManager.queryExtensionAbilityInfoSync11+ +## bundleManager.queryExtensionAbilityInfoSync11+ queryExtensionAbilityInfoSync(want: Want, extensionAbilityType: string, extensionAbilityFlags: number, userId?: number): Array\ @@ -4370,7 +4526,7 @@ try { } ``` -### bundleManager.getJsonProfile12+ +## bundleManager.getJsonProfile11+ getJsonProfile(profileType: ProfileType, bundleName: string, moduleName?: string, userId?: number): string @@ -4391,7 +4547,7 @@ No permission is required for obtaining the caller's own profile. | profileType | [ProfileType](#profiletype11) | Yes | Type of the profile. | | bundleName | string | Yes | Bundle name of the application. | | moduleName | string | No | Module name of the application. If this parameter is not passed in, the entry module is used. | -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| userId12+ | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | **Return value** @@ -4434,7 +4590,7 @@ try { } ``` -### bundleManager.getRecoverableApplicationInfo11+ +## bundleManager.getRecoverableApplicationInfo11+ getRecoverableApplicationInfo(callback: AsyncCallback\\>): void @@ -4482,7 +4638,7 @@ try { } ``` -### bundleManager.getRecoverableApplicationInfo11+ +## bundleManager.getRecoverableApplicationInfo11+ getRecoverableApplicationInfo(): Promise\\> @@ -4528,7 +4684,7 @@ try { } ``` -### bundleManager.setAdditionalInfo11+ +## bundleManager.setAdditionalInfo11+ setAdditionalInfo(bundleName: string, additionalInfo: string): void @@ -4578,7 +4734,7 @@ try { } ``` -### bundleManager.getAllPreinstalledApplicationInfo12+ +## bundleManager.getAllPreinstalledApplicationInfo12+ getAllPreinstalledApplicationInfo(): Promise\\> @@ -4609,17 +4765,19 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts import { bundleManager } from '@kit.AbilityKit'; -import { Base } from '@ohos.base'; - -bundleManager.getAllPreinstalledApplicationInfo().then((data: Array) => { - console.info("GetAllPreinstalledApplicationInfo success, data is :" + JSON.stringify(data)); +import { BusinessError } from '@kit.BasicServicesKit'; +import { hilog } from '@kit.PerformanceAnalysisKit'; -}).catch((err: Base.BusinessError) => { - console.error("GetAllPreinstalledApplicationInfo success errCode is :" + JSON.stringify(err.code)); -}); +try { + let data = bundleManager.getAllPreinstalledApplicationInfo(); + hilog.info(0x0000, 'testTag', 'getAllPreinstalledApplicationInfo success, Data: %{public}s', JSON.stringify(data)); +} catch (err) { + let message = (err as BusinessError).message; + hilog.error(0x0000, 'testTag', 'getAllPreinstalledApplicationInfo failed: %{public}s', message); +} ``` -### bundleManager.queryExtensionAbilityInfoSync11+ +## bundleManager.queryExtensionAbilityInfoSync11+ queryExtensionAbilityInfoSync(extensionAbilityType: string, extensionAbilityFlags: number, userId?: number): Array\ @@ -4696,7 +4854,7 @@ try { } ``` -### bundleManager.getAllBundleInfoByDeveloperId12+ +## bundleManager.getAllBundleInfoByDeveloperId12+ getAllBundleInfoByDeveloperId(developerId: string): Array\ @@ -4749,11 +4907,11 @@ try { } ``` -### bundleManager.getDeveloperIds12+ +## bundleManager.getDeveloperIds12+ getDeveloperIds(appDistributionType?: number): Array\ -Obtains all the developer IDs of the current user based on the given application distribution type. +Obtains all the developer IDs of the current user based on the given application [distribution type](#appdistributiontype12). **System API**: This is a system API. @@ -4765,7 +4923,7 @@ Obtains all the developer IDs of the current user based on the given application | Name | Type | Mandatory| Description | | --------------------- | ---------| ---- | --------------------- | -| appDistributionType | [number](#appdistributiontype12) | No | Application distribution type. If this parameter is not specified, a list of developer IDs of all applications is returned. | +| [appDistributionType](#appdistributiontype12) | number | No | Application distribution type. If this parameter is not specified, a list of developer IDs of all applications is returned. | **Return value** @@ -4801,7 +4959,7 @@ try { } ``` -### bundleManager.switchUninstallState12+ +## bundleManager.switchUninstallState12+ switchUninstallState(bundleName: string, state: boolean): void @@ -4847,7 +5005,7 @@ try { } ``` -### bundleManager.getExtResource12+ +## bundleManager.getExtResource12+ getExtResource(bundleName: string): Promise\>; @@ -4905,7 +5063,7 @@ try { } ``` -### bundleManager.enableDynamicIcon12+ +## bundleManager.enableDynamicIcon12+ enableDynamicIcon(bundleName: string, moduleName: string): Promise\; @@ -4964,7 +5122,7 @@ try { } ``` -### bundleManager.disableDynamicIcon12+ +## bundleManager.disableDynamicIcon12+ disableDynamicIcon(bundleName: string): Promise\; @@ -5020,7 +5178,7 @@ try { } ``` -### bundleManager.getDynamicIcon12+ +## bundleManager.getDynamicIcon12+ getDynamicIcon(bundleName: string): Promise\; @@ -5076,11 +5234,11 @@ try { } ``` -### bundleManager.getAppCloneIdentity14+ +## bundleManager.getAppCloneIdentity14+ getAppCloneIdentity(uid: number): Promise\; -Obtains the bundle name and app index of an application clone based on the given UID. This API uses a promise to return the result. +Obtains the bundle name and application index of an application clone based on the given UID. This API uses a promise to return the result. **Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -5128,7 +5286,7 @@ try { } ``` -### bundleManager.getAppCloneBundleInfo12+ +## bundleManager.getAppCloneBundleInfo12+ getAppCloneBundleInfo(bundleName: string, appIndex: number, bundleFlags: number, userId?: number): Promise\; @@ -5145,7 +5303,7 @@ Obtains the bundle information of an application or an application clone based o | Name | Type | Mandatory| Description | | ---------- | ------ | ---- | ---------------------------| | bundleName | number | Yes | Bundle name. | -| appIndex | number | Yes | Index of the application clone.
If this parameter is set to **0**, the API is used to obtain the bundle information of an application, rather than an application clone. | +| appIndex | number | Yes | Index of the application clone.
The value **0** means to obtain the bundle information of the main application. A value greater than 0 means to obtain the bundle information of the application clone. | | [bundleFlags](js-apis-bundleManager.md#bundleflag) | number | Yes | Type of the bundle information to obtain. | | userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | @@ -5191,7 +5349,7 @@ try { } ``` -### bundleManager.getAllAppCloneBundleInfo12+ +## bundleManager.getAllAppCloneBundleInfo12+ getAllAppCloneBundleInfo(bundleName: string, bundleFlags: number, userId?: number): Promise\>; @@ -5253,7 +5411,7 @@ try { hilog.error(0x0000, 'testTag', 'getAllAppCloneBundleInfo failed. Cause: %{public}s', message); } ``` -### bundleManager.verifyAbc11+ +## bundleManager.verifyAbc11+ verifyAbc(abcPaths: Array\, deleteOriginalFiles: boolean, callback: AsyncCallback\): void @@ -5307,7 +5465,74 @@ try { } ``` -### bundleManager.verifyAbc11+ +## bundleManager.migrateData18+ + +migrateData(sourcePaths: Array<string>, destinationPath: string): Promise<void> + +Migrates files from the source path to the destination path. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.MIGRATE_DATA + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | -------------------------------------------------------- | +| sourcePaths | Array<string> | Yes| Array of source paths. The value can be a single file path such as **/example1/test.txt** or a directory path such as **/example2/test**.| +| destinationPath | string | Yes| Destination path. Only one directory path is supported, for example, **/example2/test**.| + +**Return value** + +| Type | Description | +| ---------- | -------------------- | +| Promise\ | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). + +| ID| Error Message | +| -------- | ------------------------------------- | +| 201 | Permission denied. | +| 202 | Permission denied, non-system app called system api. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 17700080 | The source paths are invalid. | +| 17700081 | The destination path is invalid. | +| 17700082 | User authentication failed. | +| 17700083 | Waiting for user authentication timeout. | +| 17700084 | There are inaccessible path in the source paths. | +| 17700085 | The destination path cannot be accessed. | +| 17700086 | System error occurred during copy execution. | + +**Example** + +```ts +import { bundleManager } from '@kit.AbilityKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +try { + // Change the values of source1, source2, and dest to the actual file or directory paths. + let source1: string = "/data/app/el2/100/base/com.example.myapplication/"; + let source2: string = "/data/app/el2/101/base/com.example.myapplication/log.txt"; + let dest: string = "/data/local/tmp"; + let sourcePaths: Array = [source1, source2]; + + bundleManager.migrateData(sourcePaths, dest) + .then(() => { + console.info(`migrateData succeed`); + }) + .catch((err: BusinessError) => { + console.error(`migrateData err : `, JSON.stringify(err)); + }) +} catch(err) { + console.error(`migrateData call err : `, JSON.stringify(err)); +} +``` + +## bundleManager.verifyAbc11+ verifyAbc(abcPaths: Array\, deleteOriginalFiles: boolean): Promise\ @@ -5364,7 +5589,7 @@ try { } ``` -### bundleManager.deleteAbc11+ +## bundleManager.deleteAbc11+ deleteAbc(abcPath: string): Promise\ diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager.md b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager.md index fabf81359b5caa591c3831025123ef5f47af8cec..41d03462a725c5a409d848be5d9249364021c931 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-bundleManager.md @@ -12,9 +12,15 @@ The bundleManager module provides APIs for obtaining application information, in import { bundleManager } from '@kit.AbilityKit'; ``` -## Enums +## Required Permissions -### BundleFlag +| Permission | APL | Description | +| ------------------------------------------ | ------------ | ------------------| +| ohos.permission.GET_BUNDLE_INFO_PRIVILEGED | system_basic | Permission to obtain basic information and other sensitive information about a bundle.| + +For details about the APL, see [Basic Concepts in the Permission Mechanism](../../security/AccessToken/app-permission-mgmt-overview.md#basic-concepts-in-the-permission-mechanism). + +## BundleFlag Enumerates the bundle flags, which indicate the type of bundle information to obtain. @@ -35,7 +41,7 @@ Enumerates the bundle flags, which indicate the type of bundle information to ob | GET_BUNDLE_INFO_WITH_ROUTER_MAP12+ | 0x00000200 | Used to obtain the bundle information with the router map. It must be used together with **GET_BUNDLE_INFO_WITH_HAP_MODULE**.
**Atomic service API**: This API can be used in atomic services since API version 12.| | GET_BUNDLE_INFO_WITH_SKILL12+ | 0x00000800 | Used to obtain the bundle information with the skills. It must be used together with **GET_BUNDLE_INFO_WITH_HAP_MODULE**, **GET_BUNDLE_INFO_WITH_ABILITY**, and **GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY**.
**Atomic service API**: This API can be used in atomic services since API version 12.| -### ExtensionAbilityType +## ExtensionAbilityType Enumerates the types of ExtensionAbilities. @@ -46,29 +52,31 @@ Enumerates the types of ExtensionAbilities. | FORM | 0 | [FormExtensionAbility](../apis-form-kit/js-apis-app-form-formExtensionAbility.md): provides APIs for widget development.
**Atomic service API**: This API can be used in atomic services since API version 11.| | WORK_SCHEDULER | 1 | [WorkSchedulerExtensionAbility](../apis-backgroundtasks-kit/js-apis-WorkSchedulerExtensionAbility.md): enables applications to execute non-real-time tasks when the system is idle.| | INPUT_METHOD | 2 | [InputMethodExtensionAbility](../apis-ime-kit/js-apis-inputmethod-extension-ability.md): provides APIs for developing input method applications.| -| SERVICE | 3 | [ServiceExtensionAbility](js-apis-app-ability-serviceExtensionAbility-sys.md): enables applications to run in the background and provide services.| +| SERVICE | 3 | [ServiceExtensionAbility](js-apis-app-ability-serviceExtensionAbility-sys.md): enables applications to run in the background and provide services.| | ACCESSIBILITY | 4 | [AccessibilityExtensionAbility](../apis-accessibility-kit/js-apis-application-accessibilityExtensionAbility.md): provides accessibility for access to and operations on the UI.| -| DATA_SHARE | 5 | [DataShareExtensionAbility ](../apis-arkdata/js-apis-application-dataShareExtensionAbility-sys.md): enables applications to read and write data.| -| FILE_SHARE | 6 | FileShareExtensionAbility: enables file sharing between applications. This ability is reserved and supported only by system applications.| -| STATIC_SUBSCRIBER| 7 | [StaticSubscriberExtensionAbility ](../apis-basic-services-kit/js-apis-application-staticSubscriberExtensionAbility-sys.md): provides APIs for processing static events, such as the startup event.| -| WALLPAPER | 8 | WallpaperExtensionAbility: provides APIs to implement the home screen wallpaper. This ability is reserved and supported only by system applications.| +| DATA_SHARE | 5 | [DataShareExtensionAbility](../apis-arkdata/js-apis-application-dataShareExtensionAbility-sys.md): enables applications to read and write data.| +| FILE_SHARE | 6 | FileShareExtensionAbility: enables file sharing between applications. This ability is reserved and supported only by system applications.| +| STATIC_SUBSCRIBER| 7 | [StaticSubscriberExtensionAbility](../apis-basic-services-kit/js-apis-application-staticSubscriberExtensionAbility-sys.md): provides APIs for processing static events, such as the startup event.| +| WALLPAPER | 8 | WallpaperExtensionAbility: provides APIs to implement the home screen wallpaper. This ability is reserved and supported only by system applications.| | BACKUP | 9 | [BackupExtensionAbility](../apis-core-file-kit/js-apis-application-backupExtensionAbility.md): provides APIs to implement application data backup and restore.| -| WINDOW | 10 | [WindowExtensionAbility](../apis-arkui/js-apis-application-windowExtensionAbility-sys.md): allows system applications to display UIs of other applications.| +| WINDOW | 10 | [WindowExtensionAbility](../apis-arkui/js-apis-application-windowExtensionAbility-sys.md): allows system applications to display UIs of other applications.| | ENTERPRISE_ADMIN | 11 | [EnterpriseAdminExtensionAbility](../apis-mdm-kit/js-apis-EnterpriseAdminExtensionAbility.md): provides APIs for processing enterprise management events, such as application installation events on devices and events indicating too many incorrect screen-lock password attempts.| -| THUMBNAIL | 13 | ThumbnailExtensionAbility: provides thumbnails for files. This ability is reserved and supported only by system applications.| -| PREVIEW | 14 | PreviewExtensionAbility: provides APIs for file preview so that other applications can be embedded and displayed in the current application. This ability is reserved and supported only by system applications.| -| PRINT10+ | 15 | PrintExtensionAbility: provides APIs for printing images. This ability is supported only by system applications.| +| THUMBNAIL | 13 | ThumbnailExtensionAbility: provides thumbnails for files. This ability is reserved and supported only by system applications.| +| PREVIEW | 14 | PreviewExtensionAbility: provides APIs for file preview so that other applications can be embedded and displayed in the current application. This ability is reserved and supported only by system applications.| +| PRINT10+ | 15 | PrintExtensionAbility: provides APIs for printing images. This ability is supported only by system applications.| | SHARE10+ | 16 | [ShareExtensionAbility](js-apis-app-ability-shareExtensionAbility.md): provides sharing service templates based on UIExtensionAbilities.| -| PUSH10+ | 17 | PushExtensionAbility: provides APIs for pushing scenario-specific messages. This ability is reserved and supported only by system applications.| -| DRIVER10+ | 18 | [DriverExtensionAbility](../apis-driverdevelopment-kit/js-apis-app-ability-driverExtensionAbility.md): provides APIs for the peripheral driver. This ability is supported only by system applications.| +| PUSH10+ | 17 | PushExtensionAbility: provides APIs for pushing scenario-specific messages. This ability is reserved and supported only by system applications.| +| DRIVER10+ | 18 | [DriverExtensionAbility](../apis-driverdevelopment-kit/js-apis-app-ability-driverExtensionAbility.md): provides APIs for the peripheral driver. This ability is supported only by system applications.| | ACTION10+ | 19 | [ActionExtensionAbility](js-apis-app-ability-actionExtensionAbility.md): provides custom action service templates based on UIExtensionAbilities.| -| ADS_SERVICE11+ | 20 | AdsServiceExtensionAbility: provides background customized ad services for external systems. This ability is supported only by system applications.| +| ADS_SERVICE11+ | 20 | AdsServiceExtensionAbility: provides background customized ad services for external systems. This ability is supported only by system applications.| | EMBEDDED_UI12+ | 21 | [EmbeddedUIExtensionAbility](js-apis-app-ability-embeddedUIExtensionAbility.md): provides ExtensionAbilities for the embeddable UI across process.| | INSIGHT_INTENT_UI12+ | 22 | **InsightIntentUIExtensionAbility**: provides APIs that enable applications to be called by Celia intents so as to be displayed in windows.| +| ASSET_ACCELERATION18+ | 26 | **AssetAccelerationExtensionAbility**: provides the capability of pre-downloading background resources when the device is idle.| +| DISTRIBUTED18+ | 28 | [DistributedExtensionAbility](../apis-distributedservice-kit/js-apis-distributedExtensionAbility.md): provides DistributedExtensionAbility capabilities and lifecycle callbacks for creation, destruction, and connection of DistributedExtensionAbilities.| | UNSPECIFIED | 255 | No type is specified. It is used together with **queryExtensionAbilityInfo** to query all types of ExtensionAbilities.| -### PermissionGrantState +## PermissionGrantState Enumerates the permission grant states. @@ -81,7 +89,7 @@ Enumerates the permission grant states. | PERMISSION_DENIED| -1 | Permission denied.| | PERMISSION_GRANTED | 0 | Permission granted. | -### SupportWindowMode +## SupportWindowMode Enumerates the window modes supported by the ability. @@ -95,7 +103,7 @@ Enumerates the window modes supported by the ability. | SPLIT | 1 | A window in split-screen mode is supported.| | FLOATING | 2 | A floating window is supported. | -### LaunchType +## LaunchType Enumerates the launch types of the ability. @@ -109,7 +117,7 @@ Enumerates the launch types of the ability. | MULTITON | 1 | The ability can have multiple instances.| | SPECIFIED | 2 | The ability can have one or multiple instances, depending on the internal service of the ability.| -### AbilityType +## AbilityType Enumerates the types of abilities. @@ -123,7 +131,7 @@ Enumerates the types of abilities. | SERVICE | 2 | Ability of the background service type, without the UI. PA developed using the Service template to provide the capability of running tasks in the background. | | DATA | 3 | PA developed using the Data template to provide unified data access for external systems.| -### DisplayOrientation +## DisplayOrientation Enumerates the display orientations of the ability. This property applies only to the ability using the Page template. @@ -147,7 +155,7 @@ Enumerates the display orientations of the ability. This property applies only t | AUTO_ROTATION_UNSPECIFIED12+ |13|Auto rotation controlled by the switch and determined by the system.
**Atomic service API**: This API can be used in atomic services since API version 12.| | FOLLOW_DESKTOP12+ |14|Following the orientation of the home screen.
**Atomic service API**: This API can be used in atomic services since API version 12.| -### CompatiblePolicy10+ +## CompatiblePolicy10+ Defines the version compatibility type of the shared library. @@ -159,7 +167,7 @@ Defines the version compatibility type of the shared library. | ---------------------- | ---- | -------------------------------- | | BACKWARD_COMPATIBILITY | 1 | The shared library is backward compatible.| -### ModuleType +## ModuleType Enumerates the module types. @@ -173,7 +181,7 @@ Enumerates the module types. | FEATURE | 2 | Dynamic feature module of the application.| | SHARED | 3 | Dynamic shared library module of the application. | -### BundleType +## BundleType Enumerates the bundle types. @@ -186,7 +194,7 @@ Enumerates the bundle types. | APP | 0 | The bundle is an application. | | ATOMIC_SERVICE | 1 | The bundle is an atomic service.| -### MultiAppModeType12+ +## MultiAppModeType12+ Enumerates the types of the multi-app mode. **System capability**: SystemCapability.BundleManager.BundleFramework.Core @@ -197,13 +205,11 @@ Enumerates the types of the multi-app mode. | MULTI_INSTANCE | 1 | Multiton mode. A resident process does not support this value. | | APP_CLONE | 2 | App clone mode. | -## APIs - -### bundleManager.getBundleInfoForSelf +## bundleManager.getBundleInfoForSelf getBundleInfoForSelf(bundleFlags: number): Promise\ -Obtains the bundle information of this bundle based on the given bundle flags. This API uses a promise to return the result. +Obtains the bundle information based on the given bundle flags. This API uses a promise to return the result. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -251,11 +257,11 @@ try { } ``` -### bundleManager.getBundleInfoForSelf +## bundleManager.getBundleInfoForSelf getBundleInfoForSelf(bundleFlags: number, callback: AsyncCallback\): void -Obtains the bundle information of this bundle based on the given bundle flags. This API uses an asynchronous callback to return the result. +Obtains the bundle information based on the given bundle flags. This API uses an asynchronous callback to return the result. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -300,11 +306,11 @@ try { } ``` -### bundleManager.getProfileByAbility +## bundleManager.getProfileByAbility getProfileByAbility(moduleName: string, abilityName: string, metadataName: string, callback: AsyncCallback\\>): void -Obtains the JSON string array of the current application's configuration file in the [metadata](../../quick-start/module-configuration-file.md#metadata) based on a given module name, ability name, and metadata name. This API uses an asynchronous callback to return the result. +Obtains the JSON string array of the configuration file based on the given module name, ability name, and metadata name (name configured in [metadata](../../quick-start/module-configuration-file.md#metadata)). This API uses an asynchronous callback to return the result. > **NOTE** > @@ -333,7 +339,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 17700002 | The specified moduleName is not existed. | | 17700003 | The specified abilityName is not existed. | | 17700024 | Failed to get the profile because there is no profile in the HAP. | -| 17700026 | The specified bundle is disabled. | +| 17700026 | The specified bundle is disabled. | | 17700029 | The specified ability is disabled. | **Example** @@ -361,11 +367,11 @@ try { } ``` -### bundleManager.getProfileByAbility +## bundleManager.getProfileByAbility getProfileByAbility(moduleName: string, abilityName: string, metadataName?: string): Promise\\> -Obtains the JSON string array of the current application's configuration file in the [metadata](../../quick-start/module-configuration-file.md#metadata) based on a given module name, ability name, and metadata name. This API uses a promise to return the result. +Obtains the JSON string array of the configuration file based on the given module name, ability name, and metadata name (name configured in [metadata](../../quick-start/module-configuration-file.md#metadata)). This API uses a promise to return the result. > **NOTE** > @@ -399,7 +405,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 17700002 | The specified moduleName is not existed. | | 17700003 | The specified abilityName is not existed. | | 17700024 | Failed to get the profile because there is no profile in the HAP. | -| 17700026 | The specified bundle is disabled. | +| 17700026 | The specified bundle is disabled. | | 17700029 | The specified ability is disabled. | **Example** @@ -413,6 +419,7 @@ let moduleName = 'entry'; let abilityName = 'EntryAbility'; try { + // Obtain the JSON string array of the configuration file based on the module name and ability name. bundleManager.getProfileByAbility(moduleName, abilityName).then((data) => { hilog.info(0x0000, 'testTag', 'getProfileByAbility successfully. Data: %{public}s', JSON.stringify(data)); }).catch((err: BusinessError) => { @@ -434,6 +441,7 @@ let abilityName = 'EntryAbility'; let metadataName = 'ability_metadata'; try { + // Obtain the JSON string array of the configuration file based on the module name, ability name, and metadata name. bundleManager.getProfileByAbility(moduleName, abilityName, metadataName).then((data) => { hilog.info(0x0000, 'testTag', 'getProfileByAbility successfully. Data: %{public}s', JSON.stringify(data)); }).catch((err: BusinessError) => { @@ -445,7 +453,7 @@ try { } ``` -### bundleManager.getProfileByAbilitySync10+ +## bundleManager.getProfileByAbilitySync10+ getProfileByAbilitySync(moduleName: string, abilityName: string, metadataName?: string): Array\ @@ -483,7 +491,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 17700002 | The specified moduleName is not existed. | | 17700003 | The specified abilityName is not existed. | | 17700024 | Failed to get the profile because there is no profile in the HAP. | -| 17700026 | The specified bundle is disabled. | +| 17700026 | The specified bundle is disabled. | | 17700029 | The specified ability is disabled. | **Example** @@ -497,6 +505,7 @@ let moduleName = 'entry'; let abilityName = 'EntryAbility'; try { + // Obtain the JSON string array of the configuration file based on the module name and ability name. let data = bundleManager.getProfileByAbilitySync(moduleName, abilityName); hilog.info(0x0000, 'testTag', 'getProfileByAbilitySync successfully. Data: %{public}s', JSON.stringify(data)); } catch (err) { @@ -515,6 +524,7 @@ let abilityName: string = 'EntryAbility'; let metadataName: string = 'ability_metadata'; try { + // Obtain the JSON string array of the configuration file based on the module name, ability name, and metadata name. let data = bundleManager.getProfileByAbilitySync(moduleName, abilityName, metadataName); hilog.info(0x0000, 'testTag', 'getProfileByAbilitySync successfully. Data: %{public}s', JSON.stringify(data)); } catch (err) { @@ -523,11 +533,11 @@ try { } ``` -### bundleManager.getProfileByExtensionAbility +## bundleManager.getProfileByExtensionAbility getProfileByExtensionAbility(moduleName: string, extensionAbilityName: string, metadataName: string, callback: AsyncCallback\\>): void -Obtains the JSON string array of the current application's configuration file in the [metadata](../../quick-start/module-configuration-file.md#metadata) based on a given module name, ExtensionAbility name, and metadata name. This API uses an asynchronous callback to return the result. +Obtains the JSON string array of the configuration file based on the given module name, ExtensionAbility name, and metadata name (name configured in [metadata](../../quick-start/module-configuration-file.md#metadata)). This API uses an asynchronous callback to return the result. > **NOTE** > @@ -556,7 +566,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 17700002 | The specified moduleName is not existed. | | 17700003 | The specified extensionAbilityName not existed. | | 17700024 | Failed to get the profile because there is no profile in the HAP. | -| 17700026 | The specified bundle is disabled. | +| 17700026 | The specified bundle is disabled. | **Example** @@ -583,7 +593,7 @@ try { } ``` -### bundleManager.getProfileByExtensionAbility +## bundleManager.getProfileByExtensionAbility getProfileByExtensionAbility(moduleName: string, extensionAbilityName: string, metadataName?: string): Promise\\> @@ -621,7 +631,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 17700002 | The specified moduleName is not existed. | | 17700003 | The specified extensionAbilityName not existed. | | 17700024 | Failed to get the profile because there is no profile in the HAP. | -| 17700026 | The specified bundle is disabled. | +| 17700026 | The specified bundle is disabled. | **Example** @@ -657,7 +667,7 @@ try { } ``` -### bundleManager.getProfileByExtensionAbilitySync10+ +## bundleManager.getProfileByExtensionAbilitySync10+ getProfileByExtensionAbilitySync(moduleName: string, extensionAbilityName: string, metadataName?: string): Array\ @@ -695,7 +705,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 17700002 | The specified moduleName is not existed. | | 17700003 | The specified extensionAbilityName not existed. | | 17700024 | Failed to get the profile because there is no profile in the HAP. | -| 17700026 | The specified bundle is disabled. | +| 17700026 | The specified bundle is disabled. | **Example** @@ -725,7 +735,7 @@ try { } ``` -### bundleManager.getBundleInfoForSelfSync10+ +## bundleManager.getBundleInfoForSelfSync10+ getBundleInfoForSelfSync(bundleFlags: number): BundleInfo @@ -773,7 +783,7 @@ try { } ``` -### bundleManager.canOpenLink12+ +## bundleManager.canOpenLink12+ canOpenLink(link: string): boolean @@ -822,7 +832,7 @@ try { } ``` -### bundleManager.getLaunchWant13+ +## bundleManager.getLaunchWant13+ getLaunchWant(): Want @@ -863,7 +873,7 @@ try { } ``` -### bundleManager.getBundleInfo14+ +## bundleManager.getBundleInfo14+ getBundleInfo(bundleName: string, bundleFlags: number, userId: number, callback: AsyncCallback\): void @@ -894,7 +904,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.| | 17700001 | The specified bundleName is not found. | | 17700004 | The specified user ID is not found. | -| 17700026 | The specified bundle is disabled. | +| 17700026 | The specified bundle is disabled. | **Example** @@ -944,7 +954,7 @@ try { } ``` -### bundleManager.getBundleInfo14+ +## bundleManager.getBundleInfo14+ getBundleInfo(bundleName: string, bundleFlags: number, callback: AsyncCallback\): void @@ -973,7 +983,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 201 | Permission denied. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.| | 17700001 | The specified bundleName is not found. | -| 17700026 | The specified bundle is disabled. | +| 17700026 | The specified bundle is disabled. | **Example** @@ -999,7 +1009,7 @@ try { } ``` -### bundleManager.getBundleInfo14+ +## bundleManager.getBundleInfo14+ getBundleInfo(bundleName: string, bundleFlags: number, userId?: number): Promise\ @@ -1035,7 +1045,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.| | 17700001 | The specified bundleName is not found. | | 17700004 | The specified user ID is not found. | -| 17700026 | The specified bundle is disabled. | +| 17700026 | The specified bundle is disabled. | **Example** @@ -1080,7 +1090,7 @@ try { ``` -### bundleManager.getBundleInfoSync14+ +## bundleManager.getBundleInfoSync14+ getBundleInfoSync(bundleName: string, bundleFlags: number, userId: number): BundleInfo @@ -1116,7 +1126,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.| | 17700001 | The specified bundleName is not found. | | 17700004 | The specified user ID is not found. | -| 17700026 | The specified bundle is disabled. | +| 17700026 | The specified bundle is disabled. | **Example** @@ -1137,7 +1147,7 @@ try { } ``` -### bundleManager.getBundleInfoSync14+ +## bundleManager.getBundleInfoSync14+ getBundleInfoSync(bundleName: string, bundleFlags: number): BundleInfo @@ -1171,7 +1181,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 201 | Permission denied. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.| | 17700001 | The specified bundleName is not found. | -| 17700026 | The specified bundle is disabled. | +| 17700026 | The specified bundle is disabled. | **Example** @@ -1190,7 +1200,7 @@ try { } ``` -### bundleManager.getBundleNameByUid14+ +## bundleManager.getBundleNameByUid14+ getBundleNameByUid(uid: number, callback: AsyncCallback\): void @@ -1238,7 +1248,7 @@ try { } ``` -### bundleManager.getBundleNameByUid14+ +## bundleManager.getBundleNameByUid14+ getBundleNameByUid(uid: number): Promise\ @@ -1289,7 +1299,7 @@ try { } ``` -### bundleManager.getBundleNameByUidSync14+ +## bundleManager.getBundleNameByUidSync14+ getBundleNameByUidSync(uid: number): string @@ -1337,7 +1347,7 @@ try { } ``` -### bundleManager.getAppCloneIdentity14+ +## bundleManager.getAppCloneIdentity14+ getAppCloneIdentity(uid: number): Promise\; @@ -1357,7 +1367,7 @@ Obtains the bundle name and app index of an application clone based on the given | Type | Description | | ----------------------------------------------------------- | --------------------------- | -| Promise\ | Promise used to return \.| +| Promise\<[AppCloneIdentity](js-apis-bundleManager-bundleInfo.md#appcloneidentity14)> | Promise used to return \.| **Error codes** @@ -1378,7 +1388,7 @@ import { hilog } from '@kit.PerformanceAnalysisKit'; let uid = 20010005; try { - bundleManager.getAppCloneIdentity(uid).then((res: bundleManager.AppCloneIdentity) => { + bundleManager.getAppCloneIdentity(uid).then((res) => { hilog.info(0x0000, 'testTag', 'getAppCloneIdentity res = %{public}s', JSON.stringify(res)); }).catch((err: BusinessError) => { hilog.error(0x0000, 'testTag', 'getAppCloneIdentity failed. Cause: %{public}s', err.message); @@ -1388,3 +1398,317 @@ try { hilog.error(0x0000, 'testTag', 'getAppCloneIdentity failed. Cause: %{public}s', message); } ``` + +## bundleManager.getSignatureInfo18+ + +getSignatureInfo(uid: number): SignatureInfo + +Obtains the [SignatureInfo](./js-apis-bundleManager-bundleInfo.md#signatureinfo) based on the given UID. + +**Required permissions**: ohos.permission.GET_SIGNATURE_INFO + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ---- | ------ | ---- | ------------------ | +| uid | number | Yes | UID of the application.| + +**Return value** + +| Type | Description | +| ---------------- | --------------------------- | +| [SignatureInfo](./js-apis-bundleManager-bundleInfo.md#signatureinfo) | **SignatureInfo** object.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). + +| ID| Error Message | +| -------- | ---------------------| +| 201 | Permission denied. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.| +| 17700021 | The uid is not found. | + +**Example** + +```ts +import { bundleManager } from '@kit.AbilityKit'; +import { BusinessError } from '@kit.BasicServicesKit'; +import { hilog } from '@kit.PerformanceAnalysisKit'; +let uid = 20010005; // Replace uid with the UID of the corresponding application. +try { + let data = bundleManager.getSignatureInfo(uid); + hilog.info(0x0000, 'testTag', 'getSignatureInfo successfully. Data: %{public}s', JSON.stringify(data)); +} catch (err) { + let message = (err as BusinessError).message; + hilog.error(0x0000, 'testTag', 'getSignatureInfo failed. Cause: %{public}s', message); +} +``` + +## ApplicationInfo + +type ApplicationInfo = _ApplicationInfo + +Defines the application information. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +| Type | Description | +| ------------------------------------------------------------ | -------------- | +| [_ApplicationInfo](js-apis-bundleManager-applicationInfo.md#applicationinfo-1) | Application information.| + +## ModuleMetadata10+ + +type ModuleMetadata = _ModuleMetadata + +Defines the metadata of a module. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +| Type | Description | +| ------------------------------------------------------------ | -------------- | +| [_ModuleMetadata](js-apis-bundleManager-applicationInfo.md#ModuleMetadata10) | Metadata of the module.| + +## Metadata + +type Metadata = _Metadata + +Defines the metadata. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +| Type | Description | +| ------------------------------------------------------------ | -------------- | +| [_Metadata](js-apis-bundleManager-metadata.md#metadata) | Metadata.| + +## BundleInfo + +type BundleInfo = _BundleInfo.BundleInfo + +Defines the bundle information. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +| Type | Description | +| ------------------------------------------------------------ | -------------- | +| [_BundleInfo.BundleInfo](js-apis-bundleManager-bundleInfo.md#bundleinfo) | Bundle information.| + + +## UsedScene + +type UsedScene = _BundleInfo.UsedScene + +Defines the use scenario and timing for using the permission. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +| Type | Description | +| ------------------------------------------------------------ | -------------- | +| [_BundleInfo.UsedScene](js-apis-bundleManager-bundleInfo.md#usedscene) | Use scenario and timing for using the permission.| + +## ReqPermissionDetail + +type ReqPermissionDetail = _BundleInfo.ReqPermissionDetail + +Defines the detailed information of the permissions to request from the system. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +| Type | Description | +| ------------------------------------------------------------ | -------------- | +| [_BundleInfo.ReqPermissionDetail](js-apis-bundleManager-bundleInfo.md#reqpermissiondetail) | Detailed information of the permissions to request from the system.| + +## SignatureInfo + +type SignatureInfo = _BundleInfo.SignatureInfo + +Defines the signature information of the bundle. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +| Type | Description | +| ------------------------------------------------------------ | -------------- | +| [_BundleInfo.SignatureInfo](js-apis-bundleManager-bundleInfo.md#signatureinfo) | Signature information of the bundle.| + +## HapModuleInfo + +type HapModuleInfo = _HapModuleInfo.HapModuleInfo + +Defines the HAP module information. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +| Type | Description | +| ------------------------------------------------------------ | -------------- | +| [_HapModuleInfo.HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md#hapmoduleinfo-1) | HAP module information.| + +## PreloadItem + +type PreloadItem = _HapModuleInfo.PreloadItem + +Defines the preloaded module information in the atomic service. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +| Type | Description | +| ------------------------------------------------------------ | -------------- | +| [_HapModuleInfo.PreloadItem](js-apis-bundleManager-hapModuleInfo.md#preloaditem) | Preloaded module information in the atomic service.| + +## Dependency + +type Dependency = _HapModuleInfo.Dependency + +Defines the information about the dynamic shared libraries on which the module depends. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +| Type | Description | +| ------------------------------------------------------------ | -------------- | +| [_HapModuleInfo.Dependency](js-apis-bundleManager-hapModuleInfo.md#dependency) | Information about the dynamic shared libraries on which the module depends.| + +## RouterItem12+ + +type RouterItem = _HapModuleInfo.RouterItem + +Defines the router table configuration of the module. + +**Atomic service API**: This API can be used in atomic services since API version 12. + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +| Type | Description | +| ------------------------------------------------------------ | -------------- | +| [_HapModuleInfo.RouterItem](js-apis-bundleManager-hapModuleInfo.md#routeritem12) | Router table configuration of the module.| + +## DataItem12+ + +type DataItem = _HapModuleInfo.DataItem + +Defines the user-defined data in the routing table configuration of the module. + +**Atomic service API**: This API can be used in atomic services since API version 12. + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +| Type | Description | +| ------------------------------------------------------------ | -------------- | +| [_HapModuleInfo.DataItem](js-apis-bundleManager-hapModuleInfo.md#dataitem12) | User-defined data in the routing table configuration of the module.| + +## AbilityInfo + +type AbilityInfo = _AbilityInfo.AbilityInfo + +Defines the ability information. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +| Type | Description | +| ------------------------------------------------------------ | -------------- | +| [_AbilityInfo.AbilityInfo](js-apis-bundleManager-abilityInfo.md#abilityinfo-1) |Ability information.| + +## WindowSize + +type WindowSize = _AbilityInfo.WindowSize + +Defines the window size. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +| Type | Description | +| ------------------------------------------------------------ | -------------- | +| [_AbilityInfo.WindowSize](js-apis-bundleManager-abilityInfo.md#windowsize) |Window size.| + + +## ExtensionAbilityInfo + +type ExtensionAbilityInfo = _ExtensionAbilityInfo.ExtensionAbilityInfo + +Defines the ExtensionAbility information. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +| Type | Description | +| ------------------------------------------------------------ | -------------- | +| [_ExtensionAbilityInfo.ExtensionAbilityInfo](js-apis-bundleManager-extensionAbilityInfo.md#extensionabilityinfo-1) |ExtensionAbility information.| + +## ElementName + +type ElementName = _ElementName + +Defines the element name. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +| Type | Description | +| ------------------------------------------------------------ | -------------- | +| [_ElementName](js-apis-bundleManager-elementName.md#elementname-1) |Element name.| + +## Skill12+ + +type Skill = _Skill.Skill + +Defines the skill information. + +**Atomic service API**: This API can be used in atomic services since API version 12. + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +| Type | Description | +| ------------------------------------------------------------ | -------------- | +| [_Skill.Skill](js-apis-bundleManager-skill.md#skill-1) |Skill information.| + +## SkillUrl12+ + +type SkillUrl = _Skill.SkillUri + +Defines the SkillUri information. + +**Atomic service API**: This API can be used in atomic services since API version 12. + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +| Type | Description | +| ------------------------------------------------------------ | -------------- | +| [_Skill.SkillUri](js-apis-bundleManager-skill.md#skilluri) |SkillUri information.| + +## AppCloneIdentity15+ + +type AppCloneIdentity = _BundleInfo.AppCloneIdentity + +Describes the identity information of an application clone. + +**System capability**: SystemCapability.BundleManager.BundleFramework.Core + +| Type | Description | +| ------------------------------------------------------------ | -------------- | +| [_BundleInfo.AppCloneIdentity](js-apis-bundleManager-bundleInfo.md#appcloneidentity14) |Identity information of an application clone.| diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-bundleResourceManager-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-bundleResourceManager-sys.md index ec8a3f9920079231b8d1b92d59046dd5e958b01f..cae1512d595730994d30687e59a945a2da86e873 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-bundleResourceManager-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-bundleResourceManager-sys.md @@ -118,7 +118,7 @@ Obtains the bundle information of the entry ability of an application based on t | Name | Type | Mandatory| Description | | ----------- | ------ | ---- | --------------------- | | bundleName | string | Yes | Bundle name of the application.| -| resourceFlags | [number](#resourceflag) | No | Type of the resource information to obtain.| +| resourceFlags | [number](#resourceflag) | No | Type of the resource information to obtain. The default value is **[ResourceFlag](#resourceflag).GET_RESOURCE_INFO_ALL**.| **Return value** @@ -159,7 +159,7 @@ try { getAllBundleResourceInfo(resourceFlags: [number](#resourceflag), callback: AsyncCallback>): void -Obtains resource information of all applications based on the given resource flags. This API uses an asynchronous callback to return the result. +Obtains the bundle resource information of all applications based on the given resource flags. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -209,7 +209,7 @@ try { getAllBundleResourceInfo(resourceFlags: [number](#resourceflag)): Promise>; -Obtains resource information of all applications based on the given resource flags. This API uses a promise to return the result. +Obtains the bundle resource information of all applications based on the given resource flags. This API uses a promise to return the result. **System API**: This is a system API. @@ -262,7 +262,7 @@ try { getAllLauncherAbilityResourceInfo(resourceFlags: [number](#resourceflag), callback: AsyncCallback>): void -Obtains resource information of the entry abilities of all applications based on the given resource flags. This API uses an asynchronous callback to return the result. +Obtains the resource information of the entry abilities of the current application based on the given resource flags. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -312,7 +312,7 @@ try { getAllLauncherAbilityResourceInfo(resourceFlags: [number](#resourceflag)) : Promise> -Obtains resource information of the entry abilities of all applications based on the given resource flags. This API uses a promise to return the result. +Obtains the resource information of the entry abilities of the current application based on the given resource flags. This API uses a promise to return the result. **System API**: This is a system API. @@ -378,7 +378,7 @@ Obtains the resource information of an application based on the given bundle nam | ----------- | ------ | ---- | --------------------- | | bundleName | string | Yes | Bundle name of the application.| | resourceFlags | [number](#resourceflag) | No | Type of the resource information to obtain.| -| appIndex | number | No | Index of the application clone.| +| appIndex | number | No | Index of the application clone. The default value is **0**.| **Return value** @@ -435,8 +435,8 @@ Obtains the launcher ability resource information of an application based on the | Name | Type | Mandatory| Description | | ----------- | ------ | ---- | --------------------- | | bundleName | string | Yes | Bundle name of the application.| -| resourceFlags | [number](#resourceflag) | No | Type of the resource information to obtain.| -| appIndex | number | No | Index of the application clone.| +| resourceFlags | [number](#resourceflag) | No | Type of the resource information to obtain. The default value is **[ResourceFlag](#resourceflag).GET_RESOURCE_INFO_ALL**.| +| appIndex | number | No | Index of the application clone. The default value is **0**.| **Return value** diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-businessAbilityRouter-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-businessAbilityRouter-sys.md index 059b1e8d3918f9421fc929b29cbd568f4883df20..3cdbb43c94422a7da7638777aacb7ccbb58c0987 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-businessAbilityRouter-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-businessAbilityRouter-sys.md @@ -1,6 +1,6 @@ # @ohos.app.businessAbilityRouter (Business Ability Router) (System API) -The **businessAbilityRouter** module provides APIs for you to query the business ability information of applications installed on the device. It provides a unified template for you to register standard services by type. Based on the information, a system application or third-party application can obtain services that meet certain criteria and select a proper service. The module also provides unified rules to manage redirection between applications and services. It prevents arbitrary switching between the foreground and background and avoids the distribution of third-party applications by means of redirection. +The businessAbilityRouter module provides APIs for you to query the business ability information of applications installed on the device. It provides a unified template for you to register standard services by type. Based on the information, a system application or third-party application can obtain services that meet certain criteria and select a proper service. The module also provides unified rules to manage redirection between applications and services. It prevents arbitrary switching between the foreground and background and avoids the distribution of third-party applications by means of redirection. > **NOTE** > @@ -18,7 +18,7 @@ import businessAbilityRouter from '@ohos.app.businessAbilityRouter'; | Permission | APL | Description | | ------------------------------------------ | ------------ | -------------------- | -| ohos.permission.GET_BUNDLE_INFO_PRIVILEGED | system_basic | Permission to query information about all bundles. | +| ohos.permission.GET_BUNDLE_INFO_PRIVILEGED | system_basic | Permission to query information about all bundles.| For details about the APL, see [Basic Concepts in the Permission Mechanism](../../security/AccessToken/app-permission-mgmt-overview.md#basic-concepts-in-the-permission-mechanism). @@ -32,7 +32,7 @@ Enumerates the types of business abilities. | Name | Value | Description | | ----------- | ---- | ------------------------------------ | -| SHARE | 0 | Business ability of the share type. | +| SHARE | 0 | Business ability of the share type.| | UNSPECIFIED | 255 | Business ability of an unspecified type. | ## BusinessAbilityFilter @@ -43,10 +43,10 @@ Describes the criteria for filtering business abilities. **System API**: This is a system API. -| Name | Type | Read-only | Mandatory | Description | +| Name | Type | Read-only| Mandatory| Description | | ------------ | ------------ | ---- | ---- | -------------------------------------- | | businessType | [BusinessType](#businesstype) | No | Yes | Type of the business ability. | -| mimeType | string | No | No | MIME type supported by the business ability. | +| mimeType | string | No | No | MIME type supported by the business ability.| | uri | string | No | No | URI supported by the business ability. | ## businessAbilityRouter.queryBusinessAbilityInfo @@ -65,14 +65,14 @@ Obtains the business ability information based on the specified filter criteria. | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | --------------------------------------- | -| filter | [BusinessAbilityFilter](#businessabilityfilter) | Yes | Object used to filter the business abilities. | -| callback | AsyncCallback\\> | Yes | Callback used to return the result. If the operation is successful, the business ability information that meets the filter criteria is returned; otherwise, an error object is returned. | +| filter | [BusinessAbilityFilter](#businessabilityfilter) | Yes | Object used to filter the business abilities.| +| callback | AsyncCallback\\> | Yes| Callback used to return the result. If the operation is successful, the business ability information that meets the filter criteria is returned; otherwise, an error object is returned.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message| | ------- | -------- | | 201 | Permission denied. | | 202 | Not System App. Interface caller is not a system app. | @@ -122,13 +122,13 @@ Obtains the business ability information based on the specified filter criteria. | Type | Description | | ------------------------------------------------------------ | ------------------------------------------- | -| Promise\\> | Promise used to return the business ability information that meets the filter criteria. | +| Promise\\> | Promise used to return the business ability information that meets the filter criteria.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message| | ------- | -------- | | 201 | Permission denied. | | 202 | Not System App. Interface caller is not a system app. | diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-continuation-continuationManager.md b/en/application-dev/reference/apis-ability-kit/js-apis-continuation-continuationManager.md index e83ec77850181aeed5b82f15fbc0b7aa1b14639a..fc5b485e12d20deebeeee063fb62929840b15fe3 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-continuation-continuationManager.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-continuation-continuationManager.md @@ -99,9 +99,9 @@ Registers the continuation management service and obtains a token. This API uses **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | options | [ContinuationExtraParams](js-apis-continuation-continuationExtraParams.md) | No| Extra parameters used to filter the list of available devices. This parameter can be null.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| options | [ContinuationExtraParams](js-apis-continuation-continuationExtraParams.md) | No| Extra parameters used to filter the list of available devices. This parameter can be null.| **Return value** @@ -242,9 +242,9 @@ Registers the continuation management service and obtains a token. This API uses **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | options | [ContinuationExtraParams](js-apis-continuation-continuationExtraParams.md) | No| Extra parameters used to filter the list of available devices. This parameter can be null.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| options | [ContinuationExtraParams](js-apis-continuation-continuationExtraParams.md) | No| Extra parameters used to filter the list of available devices. This parameter can be null.| **Return value** @@ -687,10 +687,10 @@ Starts the device selection module to show the list of available devices on the **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | token | number | Yes| Token obtained after the registration of the continuation management service.| - | options | [ContinuationExtraParams](js-apis-continuation-continuationExtraParams.md) | No| Extra parameters used to filter the list of available devices. This parameter can be null.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| token | number | Yes| Token obtained after the registration of the continuation management service.| +| options | [ContinuationExtraParams](js-apis-continuation-continuationExtraParams.md) | No| Extra parameters used to filter the list of available devices. This parameter can be null.| **Return value** @@ -834,10 +834,10 @@ Starts the device selection module to show the list of available devices on the **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | token | number | Yes| Token obtained after the registration of the continuation management service.| - | options | [ContinuationExtraParams](js-apis-continuation-continuationExtraParams.md) | No| Extra parameters used to filter the list of available devices. This parameter can be null.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| token | number | Yes| Token obtained after the registration of the continuation management service.| +| options | [ContinuationExtraParams](js-apis-continuation-continuationExtraParams.md) | No| Extra parameters used to filter the list of available devices. This parameter can be null.| **Return value** @@ -1272,3 +1272,31 @@ Enumerates the continuation modes provided by the device selection module. | -------- | -------- | -------- | | COLLABORATION_SINGLE | 0 | Single-choice mode.| | COLLABORATION_MULTIPLE | 1 | Multi-choice mode.| + +## ContinuationResult10+ + +type ContinuationResult = _ContinuationResult + +Defines the device information returned by the continuation management entry. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.Ability.DistributedAbilityManager + +| Type| Description| +| --- | --- | +| [_ContinuationResult](js-apis-continuation-continuationResult.md) | Device information returned by the continuation management entry.| + +## ContinuationExtraParams10+ + +type ContinuationExtraParams = _ContinuationExtraParams + +Defines the extra parameters required by the device selection module in the continuation management entry. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.Ability.DistributedAbilityManager + +| Type| Description| +| --- | --- | +| [_ContinuationExtraParams](js-apis-continuation-continuationExtraParams.md) | Extra parameters required by the device selection module in the continuation management entry.| diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-defaultAppManager-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-defaultAppManager-sys.md index 3e55ff94f2e99547f58922f742987f9259a1b5e2..8104f78b4fcd019147c3e74cf3a106640feacbcf 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-defaultAppManager-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-defaultAppManager-sys.md @@ -18,7 +18,7 @@ import { defaultAppManager } from '@kit.AbilityKit'; | Permission | APL | Description | | --------------------------------------- | ----------- | ---------------- | -| ohos.permission.GET_DEFAULT_APPLICATION | system_core | Permission related to the default application. | +| ohos.permission.GET_DEFAULT_APPLICATION | system_core | Permission related to the default application.| For details about the APL, see [Basic Concepts in the Permission Mechanism](../../security/AccessToken/app-permission-mgmt-overview.md#basic-concepts-in-the-permission-mechanism). @@ -38,20 +38,20 @@ Obtains the default application based on a system-defined application type, a fi | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | --------------------------------------- | -| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](js-apis-defaultAppManager.md#defaultappmanagerapplicationtype), a file type that complies with the media type format, or a value defined by [UniformDataType](../apis-arkdata/js-apis-data-uniformTypeDescriptor.md). | +| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](js-apis-defaultAppManager.md#applicationtype), a file type that complies with the media type format, or a value defined by [UniformDataType](../apis-arkdata/js-apis-data-uniformTypeDescriptor.md). | | userId | number | No | User ID. The default value is the user ID of the caller. | **Return value** | Type | Description | | ------------------------- | ------------------ | -| Promise\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Promise used to return the default application. | +| Promise\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Promise used to return the default application.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). -| ID | Error Message | +| ID| Error Message | | -------- | ----------------------------------------- | | 201 | Permission denied. | | 202 | Permission denied, non-system app called system api. | @@ -109,7 +109,7 @@ Obtains the default application of a user based on a system-defined application | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | --------------------------------------- | -| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](js-apis-defaultAppManager.md#defaultappmanagerapplicationtype), a file type that complies with the media type format, or a value defined by [UniformDataType](../apis-arkdata/js-apis-data-uniformTypeDescriptor.md). | +| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](js-apis-defaultAppManager.md#applicationtype), a file type that complies with the media type format, or a value defined by [UniformDataType](../apis-arkdata/js-apis-data-uniformTypeDescriptor.md). | | userId | number | Yes | User ID. | | callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the default application. | @@ -117,7 +117,7 @@ Obtains the default application of a user based on a system-defined application For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). -| ID | Error Message | +| ID| Error Message | | -------- | ----------------------------------------- | | 201 | Permission denied. | | 202 | Permission denied, non-system app called system api. | @@ -176,14 +176,14 @@ Obtains the default application based on a system-defined application type, a fi | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | --------------------------------------- | -| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](js-apis-defaultAppManager.md#defaultappmanagerapplicationtype), a file type that complies with the media type format, or a value defined by [UniformDataType](../apis-arkdata/js-apis-data-uniformTypeDescriptor.md). | +| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](js-apis-defaultAppManager.md#applicationtype), a file type that complies with the media type format, or a value defined by [UniformDataType](../apis-arkdata/js-apis-data-uniformTypeDescriptor.md). | | callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the default application. | **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). -| ID | Error Message | +| ID| Error Message | | -------- | ----------------------------------------- | | 201 | Permission denied. | | 202 | Permission denied, non-system app called system api. | @@ -238,9 +238,9 @@ Obtains the default application based on a system-defined application type, a fi **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type | Mandatory| Description | | -------| ------ | ---- | --------------------------------------- | -| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](js-apis-defaultAppManager.md#defaultappmanagerapplicationtype), a file type that complies with the media type format, or a value defined by [UniformDataType](../apis-arkdata/js-apis-data-uniformTypeDescriptor.md).| +| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](js-apis-defaultAppManager.md#applicationtype), a file type that complies with the media type format, or a value defined by [UniformDataType](../apis-arkdata/js-apis-data-uniformTypeDescriptor.md).| | userId | number | No | User ID. The default value is the user ID of the caller. | **Return value** @@ -253,7 +253,7 @@ Obtains the default application based on a system-defined application type, a fi For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). -| ID | Error Message | +| ID| Error Message | | -------- | ----------------------------------------- | | 201 | Permission denied. | | 202 | Permission denied, non-system app called system api. | @@ -307,7 +307,7 @@ Sets the default application based on a system-defined application type, a file | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | --------------------------------------- | -| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](js-apis-defaultAppManager.md#defaultappmanagerapplicationtype), a file type that complies with the media type format, or a value defined by [UniformDataType](../apis-arkdata/js-apis-data-uniformTypeDescriptor.md). | +| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](js-apis-defaultAppManager.md#applicationtype), a file type that complies with the media type format, or a value defined by [UniformDataType](../apis-arkdata/js-apis-data-uniformTypeDescriptor.md). | | elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | Information about the element to be set as the default application. | | userId | number | No | User ID. The default value is the user ID of the caller. | @@ -315,13 +315,13 @@ Sets the default application based on a system-defined application type, a file | Type | Description | | -------------- | ---------------------------------- | -| Promise\ | Promise that returns no value. | +| Promise\ | Promise that returns no value.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------- | | 201 | Permission denied. | | 202 | Permission denied, non-system app called system api. | @@ -396,7 +396,7 @@ Sets the default application for a user based on a system-defined application ty | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | --------------------------------------- | -| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](js-apis-defaultAppManager.md#defaultappmanagerapplicationtype), a file type that complies with the media type format, or a value defined by [UniformDataType](../apis-arkdata/js-apis-data-uniformTypeDescriptor.md). | +| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](js-apis-defaultAppManager.md#applicationtype), a file type that complies with the media type format, or a value defined by [UniformDataType](../apis-arkdata/js-apis-data-uniformTypeDescriptor.md). | | elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | Information about the element to be set as the default application. | | userId | number | Yes | User ID. | | callback | AsyncCallback\ | Yes | Callback used to return the result. | @@ -405,7 +405,7 @@ Sets the default application for a user based on a system-defined application ty For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------- | | 201 | Permission denied. | | 202 | Permission denied, non-system app called system api. | @@ -476,7 +476,7 @@ Sets the default application based on a system-defined application type, a file | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | --------------------------------------- | -| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](js-apis-defaultAppManager.md#defaultappmanagerapplicationtype), a file type that complies with the media type format, or a value defined by [UniformDataType](../apis-arkdata/js-apis-data-uniformTypeDescriptor.md). | +| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](js-apis-defaultAppManager.md#applicationtype), a file type that complies with the media type format, or a value defined by [UniformDataType](../apis-arkdata/js-apis-data-uniformTypeDescriptor.md). | | elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | Information about the element to be set as the default application. | | callback | AsyncCallback\ | Yes | Callback used to return the result. | @@ -484,7 +484,7 @@ Sets the default application based on a system-defined application type, a file For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------- | | 201 | Permission denied. | | 202 | Permission denied, non-system app called system api. | @@ -551,17 +551,17 @@ Sets the default application based on a system-defined application type, a file **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ----------- | ------ | ---- | --------------------------------------- | -| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](js-apis-defaultAppManager.md#defaultappmanagerapplicationtype), a file type that complies with the media type format, or a value defined by [UniformDataType](../apis-arkdata/js-apis-data-uniformTypeDescriptor.md).| -| elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | Information about the element to be set as the default application. | +| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](js-apis-defaultAppManager.md#applicationtype), a file type that complies with the media type format, or a value defined by [UniformDataType](../apis-arkdata/js-apis-data-uniformTypeDescriptor.md).| +| elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes| Information about the element to be set as the default application. | | userId | number | No | User ID. The default value is the user ID of the caller. | **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------- | | 201 | Permission denied. | | 202 | Permission denied, non-system app called system api. | @@ -639,14 +639,14 @@ Resets the default application based on a system-defined application type, a fil | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | --------------------------------------- | -| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](js-apis-defaultAppManager.md#defaultappmanagerapplicationtype), a file type that complies with the media type format, or a value defined by [UniformDataType](../apis-arkdata/js-apis-data-uniformTypeDescriptor.md). | +| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](js-apis-defaultAppManager.md#applicationtype), a file type that complies with the media type format, or a value defined by [UniformDataType](../apis-arkdata/js-apis-data-uniformTypeDescriptor.md). | | userId | number | No | User ID. The default value is the user ID of the caller. | **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). -| ID | Error Message | +| ID| Error Message | | -------- | ----------------------------------- | | 201 | Permission denied. | | 202 | Permission denied, non-system app called system api. | @@ -704,7 +704,7 @@ Resets the default application for a user based on a system-defined application | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | --------------------------------------- | -| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](js-apis-defaultAppManager.md#defaultappmanagerapplicationtype), a file type that complies with the media type format, or a value defined by [UniformDataType](../apis-arkdata/js-apis-data-uniformTypeDescriptor.md). | +| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](js-apis-defaultAppManager.md#applicationtype), a file type that complies with the media type format, or a value defined by [UniformDataType](../apis-arkdata/js-apis-data-uniformTypeDescriptor.md). | | userId | number | Yes | User ID. | | callback | AsyncCallback\ | Yes | Callback used to return the result. | @@ -712,7 +712,7 @@ Resets the default application for a user based on a system-defined application For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). -| ID | Error Message | +| ID| Error Message | | -------- | ----------------------------------- | | 201 | Permission denied. | | 202 | Permission denied, non-system app called system api. | @@ -770,14 +770,14 @@ Resets the default application based on a system-defined application type, a fil | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | --------------------------------------- | -| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](js-apis-defaultAppManager.md#defaultappmanagerapplicationtype), a file type that complies with the media type format, or a value defined by [UniformDataType](../apis-arkdata/js-apis-data-uniformTypeDescriptor.md). | +| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](js-apis-defaultAppManager.md#applicationtype), a file type that complies with the media type format, or a value defined by [UniformDataType](../apis-arkdata/js-apis-data-uniformTypeDescriptor.md). | | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). -| ID | Error Message | +| ID| Error Message | | -------- | ----------------------------------- | | 201 | Permission denied. | | 202 | Permission denied, non-system app called system api. | @@ -831,16 +831,16 @@ Resets the default application based on a system-defined application type, a fil **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | --------------------------------------- | -| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](js-apis-defaultAppManager.md#defaultappmanagerapplicationtype), a file type that complies with the media type format, or a value defined by [UniformDataType](../apis-arkdata/js-apis-data-uniformTypeDescriptor.md).| +| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](js-apis-defaultAppManager.md#applicationtype), a file type that complies with the media type format, or a value defined by [UniformDataType](../apis-arkdata/js-apis-data-uniformTypeDescriptor.md).| | userId | number | No | User ID. The default value is the user ID of the caller. | **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). -| ID | Error Message | +| ID| Error Message | | -------- | ----------------------------------- | | 201 | Permission denied. | | 202 | Permission denied, non-system app called system api. | diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-defaultAppManager.md b/en/application-dev/reference/apis-ability-kit/js-apis-defaultAppManager.md index b7bea970f5eadff40c5bc99e569319151a4a7768..e3f4c62c59fbfedde9d7a5dab52fc0533578bc43 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-defaultAppManager.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-defaultAppManager.md @@ -12,13 +12,13 @@ The **DefaultAppManager** module provides APIs to query whether the current appl import { defaultAppManager } from '@kit.AbilityKit'; ``` -## defaultAppManager.ApplicationType +## ApplicationType Enumerates the default application types. **System capability**: SystemCapability.BundleManager.BundleFramework.DefaultApp -| Name | Value | Description | +| Name | Value| Description | | -------- | -------------------------------------- | -------------------------------------- | | BROWSER | 'Web Browser' | Default browser. | | IMAGE | 'Image Gallery' | Default image viewer. | @@ -42,19 +42,19 @@ Checks whether this application is the default application of a system-defined a | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | --------------------------------------- | -| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmanagerapplicationtype) or [UniformDataType](../apis-arkdata/js-apis-data-uniformTypeDescriptor.md). | +| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#applicationtype) or [UniformDataType](../apis-arkdata/js-apis-data-uniformTypeDescriptor.md). | **Return value** | Type | Description | | ------------------------- | ------------------ | -| Promise\ | Promise used to return the result. If the application is the default application, **true** is returned; otherwise, **false** is returned. | +| Promise\ | Promise used to return the result. If the application is the default application, **true** is returned; otherwise, **false** is returned.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | | 801 | Capability not supported. | @@ -85,14 +85,14 @@ Checks whether this application is the default application of a system-defined a | Name | Type | Mandatory | Description | | ----------- | ------------------------------- | ---- | --------------------------------------- | -| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmanagerapplicationtype) or [UniformDataType](../apis-arkdata/js-apis-data-uniformTypeDescriptor.md). | -| callback | AsyncCallback\ | Yes | Callback used to return the result. If the application is the default application, **true** is returned; otherwise, **false** is returned. | +| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#applicationtype) or [UniformDataType](../apis-arkdata/js-apis-data-uniformTypeDescriptor.md). | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the application is the default application, **true** is returned; otherwise, **false** is returned.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | | 801 | Capability not supported. | @@ -122,21 +122,21 @@ Checks whether this application is the default application of a system-defined a **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type | Mandatory| Description | | -------| ------ | ---- | --------------------------------------- | -| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmanagerapplicationtype) or [UniformDataType](../apis-arkdata/js-apis-data-uniformTypeDescriptor.md). | +| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#applicationtype) or [UniformDataType](../apis-arkdata/js-apis-data-uniformTypeDescriptor.md). | **Return value** | Type | Description | | ------- | -------------------- | -| boolean | Returns **true** if the application is the default application; returns **false** otherwise. | +| boolean | Returns **true** if the application is the default application; returns **false** otherwise.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | | 801 | Capability not supported. | diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-distributedBundleManager-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-distributedBundleManager-sys.md index 6cb13290cb69810d280af37de4d6c14ca76f0877..fa338193390801e5c3079ecd8f6b3904f9e23c7f 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-distributedBundleManager-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-distributedBundleManager-sys.md @@ -22,7 +22,7 @@ SystemCapability.BundleManager.DistributedBundleFramework | Permission | APL | Description | | ------------------------------------------ | ------------ | ------------------ | -| ohos.permission.GET_BUNDLE_INFO_PRIVILEGED | system_basic | Permission to obtain basic information and other sensitive information about a bundle. | +| ohos.permission.GET_BUNDLE_INFO_PRIVILEGED | system_basic | Permission to obtain basic information and other sensitive information about a bundle.| For details about the APL, see [Basic Concepts in the Permission Mechanism](../../security/AccessToken/app-permission-mgmt-overview.md#basic-concepts-in-the-permission-mechanism). @@ -40,16 +40,16 @@ Obtains information about the remote ability that matches the given element name **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | elementName | [ElementName](js-apis-bundleManager-elementName.md) | Yes | Target element name. | -| callback | AsyncCallback<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo-sys.md)> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the **RemoteAbilityInfo** object obtained. Otherwise, **err** is an error object and **data** is **undefined**. | +| callback | AsyncCallback<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo-sys.md)> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the **RemoteAbilityInfo** object obtained. Otherwise, **err** is an error object and **data** is **undefined**.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). -| ID | Error Message | +| ID| Error Message | |----------|--------------------------------------| | 201 | Permission denied. | | 202 | Permission denied, non-system app called system api. | @@ -100,21 +100,21 @@ Obtains information about the remote ability that matches the given element name **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ----------- | -------------------------------------------- | ---- | ----------------------- | -| elementName | [ElementName](js-apis-bundleManager-elementName.md) | Yes | Target element name. | +| elementName | [ElementName](js-apis-bundleManager-elementName.md) | Yes | Target element name.| **Return value** | Type | Description | | ------------------------------------------------------------ | --------------------------------- | -| Promise\<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo-sys.md)> | Promise used to return the result. If the operation is successful, the **RemoteAbilityInfo** object is returned. Otherwise, an error object is returned. | +| Promise\<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo-sys.md)> | Promise used to return the result. If the operation is successful, the **RemoteAbilityInfo** object is returned. Otherwise, an error object is returned.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). -| ID | Error Message | +| ID| Error Message | |----------|-------------------------| | 201 | Permission denied. | | 202 | Permission denied, non-system app called system api. | @@ -163,16 +163,16 @@ Obtains information about the remote abilities that match the given element name **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ------------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | elementNames | Array<[ElementName](js-apis-bundleManager-elementName.md)> | Yes | **ElementName** array, whose maximum length is 10. | -| callback | AsyncCallback\> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the array of **RemoteAbilityInfo** objects obtained. Otherwise, **err** is an error object and **data** is **undefined**. | +| callback | AsyncCallback\> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the array of **RemoteAbilityInfo** objects obtained. Otherwise, **err** is an error object and **data** is **undefined**.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). -| ID | Error Message | +| ID| Error Message | |----------|-------------------------| | 201 | Permission denied. | | 202 | Permission denied, non-system app called system api. | @@ -230,21 +230,21 @@ Obtains information about the remote abilities that match the given element name **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ------------ | --------------------------------------------------- | ---- | ----------------------- | -| elementNames | Array<[ElementName](js-apis-bundleManager-elementName.md)> | Yes | **ElementName** array, whose maximum length is 10. | +| elementNames | Array<[ElementName](js-apis-bundleManager-elementName.md)> | Yes | **ElementName** array, whose maximum length is 10.| **Return value** | Type | Description | | ------------------------------------------------------------ | --------------------------------- | -| Promise\> | Promise used to return the result. If the operation is successful, an array of **RemoteAbilityInfo** objects is returned. Otherwise, an error object is returned. | +| Promise\> | Promise used to return the result. If the operation is successful, an array of **RemoteAbilityInfo** objects is returned. Otherwise, an error object is returned.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). -| ID | Error Message | +| ID| Error Message | |----------|-------------------------| | 201 | Permission denied. | | 202 | Permission denied, non-system app called system api. | @@ -300,17 +300,17 @@ Obtains information about the remote ability that matches the given element name **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ----------- | ------------------------------------------------------------ | ---- | -------------------------------------------------- | | elementName | [ElementName](js-apis-bundleManager-elementName.md) | Yes | Target element name. | -| locale | string |Yes | Target locale. | -| callback | AsyncCallback<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo-sys.md)> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the **RemoteAbilityInfo** object obtained. Otherwise, **err** is an error object and **data** is **undefined**. | +| locale | string |Yes| Target locale.| +| callback | AsyncCallback<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo-sys.md)> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the **RemoteAbilityInfo** object obtained. Otherwise, **err** is an error object and **data** is **undefined**.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). -| ID | Error Message | +| ID| Error Message | |----------|-------------------------| | 201 | Permission denied. | | 202 | Permission denied, non-system app called system api. | @@ -361,22 +361,22 @@ Obtains information about the remote ability that matches the given element name **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ----------- | -------------------------------------------- | ---- | ----------------------- | -| elementName | [ElementName](js-apis-bundleManager-elementName.md) | Yes | Target element name. | -| locale | string |Yes | Target locale. | +| elementName | [ElementName](js-apis-bundleManager-elementName.md) | Yes | Target element name.| +| locale | string |Yes| Target locale.| **Return value** | Type | Description | | ------------------------------------------------------------ | --------------------------------- | -| Promise\<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo-sys.md)> | Promise used to return the result. If the operation is successful, the **RemoteAbilityInfo** object is returned. Otherwise, an error object is returned. | +| Promise\<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo-sys.md)> | Promise used to return the result. If the operation is successful, the **RemoteAbilityInfo** object is returned. Otherwise, an error object is returned.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). -| ID | Error Message | +| ID| Error Message | |----------|-------------------------| | 201 | Permission denied. | | 202 | Permission denied, non-system app called system api. | @@ -425,11 +425,11 @@ Obtains information about the remote abilities that match the given element name **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ------------ | ------------------------------------------------------------ | ---- | -------------------------------------------------- | | elementNames | Array<[ElementName](js-apis-bundleManager-elementName.md)> | Yes | **ElementName** array, whose maximum length is 10. | -| locale | string |Yes | Target locale. | -| callback | AsyncCallback\> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the array of **RemoteAbilityInfo** objects obtained. Otherwise, **err** is an error object and **data** is **undefined**. | +| locale | string |Yes| Target locale.| +| callback | AsyncCallback\> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the array of **RemoteAbilityInfo** objects obtained. Otherwise, **err** is an error object and **data** is **undefined**.| **Error codes** @@ -493,22 +493,22 @@ Obtains information about the remote abilities that match the given element name **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ------------ | --------------------------------------------------- | ---- | ----------------------- | -| elementNames | Array<[ElementName](js-apis-bundleManager-elementName.md)> | Yes | **ElementName** array, whose maximum length is 10. | -| locale | string |Yes | Target locale. | +| elementNames | Array<[ElementName](js-apis-bundleManager-elementName.md)> | Yes | **ElementName** array, whose maximum length is 10.| +| locale | string |Yes| Target locale.| **Return value** | Type | Description | | ------------------------------------------------------------ | --------------------------------- | -| Promise\> | Promise used to return the result. If the operation is successful, an array of **RemoteAbilityInfo** objects is returned. Otherwise, an error object is returned. | +| Promise\> | Promise used to return the result. If the operation is successful, an array of **RemoteAbilityInfo** objects is returned. Otherwise, an error object is returned.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). -| ID | Error Message | +| ID| Error Message | |----------|-------------------------| | 201 | Permission denied. | | 202 | Permission denied, non-system app called system api. | diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-distributedMissionManager-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-distributedMissionManager-sys.md index f123be0958dd327cac7fdd6bfc8ef9e816ef1d58..2f30478d7c8d068ac18d3bc481f222de54f39e9b 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-distributedMissionManager-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-distributedMissionManager-sys.md @@ -698,7 +698,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ } ``` -## distributedMissionManager.on('continueStateChange')10+ +## distributedMissionManager.on('continueStateChange')11+ on(type: 'continueStateChange', callback: Callback<ContinueCallbackInfo>): void @@ -738,7 +738,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ } ``` -## distributedMissionManager.off('continueStateChange')10+ +## distributedMissionManager.off('continueStateChange')11+ off(type: 'continueStateChange', callback?: Callback<ContinueCallbackInfo>): void diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-freeInstall-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-freeInstall-sys.md index 6d502fb7e5a1e3c8eef1218e381b4e33dc09f8a7..a7a90cb27a459c47abf57a9f219647b8fcc50812 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-freeInstall-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-freeInstall-sys.md @@ -18,7 +18,7 @@ import freeInstall from '@ohos.bundle.freeInstall'; | Permission | APL | Description | | ------------------------------------------ | ------------ | ------------------ | -| ohos.permission.GET_BUNDLE_INFO_PRIVILEGED | system_basic | Permission to query information about all applications. | +| ohos.permission.GET_BUNDLE_INFO_PRIVILEGED | system_basic | Permission to query information about all applications.| | ohos.permission.INSTALL_BUNDLE | system_core | Permission to install or uninstall other applications except enterprise applications, including enterprise InHouse, mobile device management (MDM), and Normal applications. | For details about the APL, see [Basic Concepts in the Permission Mechanism](../../security/AccessToken/app-permission-mgmt-overview.md#basic-concepts-in-the-permission-mechanism). @@ -31,8 +31,8 @@ For details about the APL, see [Basic Concepts in the Permission Mechanism](../. | Name | Value | Description | | ---------------- | ---- | ---------------- | | NOT_UPGRADE | 0 | No module needs an upgrade. | -| SINGLE_UPGRADE | 1 | A single module needs an upgrade. | -| RELATION_UPGRADE | 2 | The module that has a relationship with the current one needs an upgrade. | +| SINGLE_UPGRADE | 1 | A single module needs an upgrade.| +| RELATION_UPGRADE | 2 | The module that has a relationship with the current one needs an upgrade.| ## BundlePackFlag @@ -43,7 +43,7 @@ For details about the APL, see [Basic Concepts in the Permission Mechanism](../. | Name | Value | Description | | ------------------ | ---------- | ---------------------------------- | | GET_PACK_INFO_ALL | 0x00000000 | All information in the **pack.info** file. | -| GET_PACKAGES | 0x00000001 | Package information in the **pack.info** file. | +| GET_PACKAGES | 0x00000001 | Package information in the **pack.info** file.| | GET_BUNDLE_SUMMARY | 0x00000002 | Bundle summary information in the **pack.info** file. | | GET_MODULE_SUMMARY | 0x00000004 | Module summary information in the **pack.info** file. | @@ -61,18 +61,18 @@ Sets an upgrade flag for a module. This API uses an asynchronous callback to ret **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ----------- | --------------------------- | ---- | ---------------------------- | | bundleName | string | Yes | Bundle name. | | moduleName | string | Yes | Module name. | | upgradeFlag | [UpgradeFlag](#upgradeflag) | Yes | Upgrade flag, which is for internal use only. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, **err** is **null**; otherwise, **err** is an error object. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, **err** is **null**; otherwise, **err** is an error object.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). -| ID | Error Message | +| ID| Error Message | |----------|---------------------------------------- | | 201 | Permission denied. | | 202 | Permission denied, non-system app called system api. | @@ -115,9 +115,9 @@ Sets an upgrade flag for a module. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ----------- | --------------------------- | ---- | ---------------------- | -| bundleName | string | Yes | Bundle name. | +| bundleName | string | Yes | Bundle name.| | moduleName | string | Yes | Module name. | | upgradeFlag | [UpgradeFlag](#upgradeflag) | Yes | Upgrade flag, which is for internal use only.| @@ -125,13 +125,13 @@ Sets an upgrade flag for a module. This API uses a promise to return the result. | Type | Description | | ------------- | ------------------------------------ | -| Promise\ | Promise that returns no value. | +| Promise\ | Promise that returns no value.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). -| ID | Error Message | +| ID| Error Message | |----------|----------------------------------------| | 201 | Permission denied. | | 202 | Permission denied, non-system app called system api. | @@ -173,17 +173,17 @@ Checks whether a module can be removed. This API uses an asynchronous callback t **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ---------- | ---------------------- | ---- | --------------------------------------------- | | bundleName | string | Yes | Bundle name. | | moduleName | string | Yes | Module name. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. If the module can be removed, **true** is returned; otherwise, **false** is returned. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the module can be removed, **true** is returned; otherwise, **false** is returned.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). -| ID | Error Message | +| ID| Error Message | |----------|----------------------------------------| | 201 | Permission denied. | | 202 | Permission denied, non-system app called system api. | @@ -225,22 +225,22 @@ Checks whether a module can be removed. This API uses a promise to return the re **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ---------- | ------ | ---- | ------------------ | | bundleName | string | Yes | Bundle name. | -| moduleName | string | Yes | Module name. | +| moduleName | string | Yes | Module name.| **Return value** | Type | Description | | ---------------- | ---------------------------- | -| Promise\ | Promise used to return the result. If the module can be removed, **true** is returned; otherwise, **false** is returned. | +| Promise\ | Promise used to return the result. If the module can be removed, **true** is returned; otherwise, **false** is returned.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). -| ID | Error Message | +| ID| Error Message | |----------|----------------------------------------| | 201 | Permission denied. | | 202 | Permission denied, non-system app called system api. | @@ -281,17 +281,17 @@ Obtains **bundlePackInfo** based on **bundleName** and **bundlePackFlag**. This **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | -------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | bundleName | string | Yes | Bundle name. | | bundlePackFlag | [BundlePackFlag](#bundlepackflag) | Yes | Flag of the bundle package. | -| callback | AsyncCallback<[BundlePackInfo](js-apis-bundleManager-BundlePackInfo-sys.md)> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the **BundlePackInfo** object obtained; otherwise, **err** is an error object. | +| callback | AsyncCallback<[BundlePackInfo](js-apis-bundleManager-BundlePackInfo-sys.md)> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the **BundlePackInfo** object obtained; otherwise, **err** is an error object.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). -| ID | Error Message | +| ID| Error Message | |----------|----------------------------------------| | 201 | Permission denied. | | 202 | Permission denied, non-system app called system api. | @@ -331,22 +331,22 @@ Obtains **bundlePackInfo** based on **bundleName** and **bundlePackFlag**. This **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | -------------- | --------------------------------- | ---- | ---------------------- | -| bundleName | string | Yes | Bundle name. | +| bundleName | string | Yes | Bundle name.| | bundlePackFlag | [BundlePackFlag](#bundlepackflag) | Yes | Flag of the bundle package.| **Return value** | Type | Description | | ---------------------------------------------------------- | ----------------------------------- | -| Promise<[BundlePackInfo](js-apis-bundleManager-BundlePackInfo-sys.md)> | Promise used to return the **BundlePackInfo** object obtained. | +| Promise<[BundlePackInfo](js-apis-bundleManager-BundlePackInfo-sys.md)> | Promise used to return the **BundlePackInfo** object obtained.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). -| ID | Error Message | +| ID| Error Message | |----------|----------------------------------------| | 201 | Permission denied. | | 202 | Permission denied, non-system app called system api. | @@ -386,15 +386,15 @@ Obtains the dispatch information. This API uses an asynchronous callback to retu **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| callback | AsyncCallback<[DispatchInfo](js-apis-bundleManager-dispatchInfo-sys.md)> | Yes | Callback used to return the result. If the operation is successful, **err** is **null**, and **data** is the [DispatchInfo](js-apis-bundleManager-dispatchInfo-sys.md) object obtained. otherwise, **err** is an error object. | +| callback | AsyncCallback<[DispatchInfo](js-apis-bundleManager-dispatchInfo-sys.md)> | Yes | Callback used to return the result. If the operation is successful, **err** is **null**, and **data** is the [DispatchInfo](js-apis-bundleManager-dispatchInfo-sys.md) object obtained. otherwise, **err** is an error object.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | |----------|----------------------------------------| | 201 | Permission denied. | | 202 | Permission denied, non-system app called system api. | @@ -433,13 +433,13 @@ Obtains the dispatch information. This API uses a promise to return the result. | Type | Description | | ------------------------------------------------ | ------------------------------------------------------------ | -| Promise<[DispatchInfo](js-apis-bundleManager-dispatchInfo-sys.md)> | Promise used to return the [DispatchInfo](js-apis-bundleManager-dispatchInfo-sys.md) object obtained. | +| Promise<[DispatchInfo](js-apis-bundleManager-dispatchInfo-sys.md)> | Promise used to return the [DispatchInfo](js-apis-bundleManager-dispatchInfo-sys.md) object obtained.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | |----------|----------------------------------------| | 201 | Permission denied. | | 202 | Permission denied, non-system app called system api. | diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-ability-abilityResult.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-ability-abilityResult.md index e1c1576851e085e61af12ab0680fccca4cd92310..ffb40ff8a40fecdfef69bef92c7a1aa16da6db61 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-ability-abilityResult.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-ability-abilityResult.md @@ -1,6 +1,6 @@ # AbilityResult -The **AbilityResult** module defines the result code and data returned when an ability is terminated after being started. +The AbilityResult module defines the result code and data returned when an ability is terminated after being started. In the stage model, you can use [startAbilityForResult](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartabilityforresult) to obtain the **AbilityResult** object returned after the started ability is terminated by calling [terminateSelfWithResult](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult). @@ -30,5 +30,5 @@ import ability from '@ohos.ability.ability'; | Name | Type | Read-only| Optional| Description | | ----------- | -------------------- | ---- | ---- | ------------------------------------------------------------ | -| resultCode | number | No | No | Result code returned after the started ability is terminated. | +| resultCode | number | No | No | Result code returned by the target party to the caller after the ability of the target party is started and then terminated.
- In normal cases, the result code sent by the target party is returned.
- In abnormal cases, the value **-1** is returned. | | want | [Want](js-apis-app-ability-want.md) | No | Yes | Data returned after the started ability is terminated.| diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-ability-connectOptions.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-ability-connectOptions.md index 40c4485a74ba2f62904a3f5b08b388e6e0495e52..1ffd29ffc1ead9fde46d86ed3039ac406e421161 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-ability-connectOptions.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-ability-connectOptions.md @@ -12,7 +12,9 @@ import { common } from '@kit.AbilityKit'; ``` -## onConnect +## ConnectOptions + +### onConnect onConnect(elementName: ElementName, remote: rpc.IRemoteObject): void @@ -24,8 +26,8 @@ Callback invoked when a connection is set up. | Name | Type | Mandatory | Description | | -------- | ---------------------- | ---- | ------------- | -| elementName | [ElementName](js-apis-bundleManager-elementName.md) | Yes | Element name of the ability. | -| remote | [rpc.IRemoteObject](../apis-ipc-kit/js-apis-rpc.md#iremoteobject) | Yes | **IRemoteObject** instance. | +| elementName | [ElementName](js-apis-bundleManager-elementName.md) | Yes | Element name of the ability.| +| remote | [rpc.IRemoteObject](../apis-ipc-kit/js-apis-rpc.md#iremoteobject) | Yes | **IRemoteObject** instance.| **Example** @@ -58,7 +60,7 @@ class EntryAbility extends UIAbility { } ``` -## onDisconnect +### onDisconnect onDisconnect(elementName: ElementName): void @@ -70,7 +72,7 @@ Callback invoked when a connection is interrupted. | Name | Type | Mandatory | Description | | -------- | ---------------------- | ---- | ------------- | -| elementName | [ElementName](js-apis-bundleManager-elementName.md) | Yes | Element name of the ability. | +| elementName | [ElementName](js-apis-bundleManager-elementName.md) | Yes | Element name of the ability.| **Example** @@ -103,7 +105,7 @@ class EntryAbility extends UIAbility { } ``` -## onFailed +### onFailed onFailed(code: number): void @@ -115,7 +117,7 @@ Callback invoked when a connection fails. | Name | Type | Mandatory | Description | | -------- | ---------------------- | ---- | ------------- | -| code | number | Yes | Result code.
The value **0** means that the connection is successful, **-1** means that a parameter is incorrect, and **-2** means that the ability is not found. | +| code | number | Yes | Result code.
The value **0** means that the connection is successful, **-1** means that a parameter is incorrect, and **-2** means that the ability is not found.| **Example** diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-ability-dataAbilityHelper.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-ability-dataAbilityHelper.md index 956cc602666bbd75c78b50f57fe6c00bfa91f696..94ee5e7c610a3a28629b5a93f4eb8b3162894e22 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-ability-dataAbilityHelper.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-ability-dataAbilityHelper.md @@ -548,7 +548,7 @@ DAHelper.notifyChange('dataability:///com.example.DataAbility').then(() => { ## DataAbilityHelper.insert -insert(uri: string, valuesBucket: rdb.ValuesBucket, callback: AsyncCallback\): void +insert(uri: string, valuesBucket: [rdb.ValuesBucket](../apis-arkdata/js-apis-data-rdb.md#valuesbucket), callback: AsyncCallback\): void Inserts a single data record into the database. This API uses an asynchronous callback to return the result. @@ -561,7 +561,7 @@ Inserts a single data record into the database. This API uses an asynchronous ca | Name | Type | Mandatory| Description | | ------------ | ---------------------- | ---- | ------------------------------------------------------ | | uri | string | Yes | URI of the data to insert. | -| valuesBucket | rdb.ValuesBucket | Yes | Data record to insert. If this parameter is **null**, a blank row will be inserted.| +| valuesBucket | [rdb.ValuesBucket](../apis-arkdata/js-apis-data-rdb.md#valuesbucket) | Yes | Data record to insert. If this parameter is **null**, a blank row will be inserted.| | callback | AsyncCallback\ | Yes | Callback used to return the index of the inserted data record. | **Example** @@ -592,7 +592,7 @@ DAHelper.insert('dataability:///com.example.DataAbility', valueBucket, (error, d ## DataAbilityHelper.insert -insert(uri: string, valuesBucket: rdb.ValuesBucket): Promise\ +insert(uri: string, valuesBucket: [rdb.ValuesBucket](../apis-arkdata/js-apis-data-rdb.md#valuesbucket)): Promise\ Inserts a single data record into the database. This API uses a promise to return the result. @@ -605,7 +605,7 @@ Inserts a single data record into the database. This API uses a promise to retur | Name | Type | Mandatory| Description | | ------------ | ---------------- | ---- | ------------------------------------------------------ | | uri | string | Yes | URI of the data to insert. | -| valuesBucket | rdb.ValuesBucket | Yes | Data record to insert. If this parameter is **null**, a blank row will be inserted.| +| valuesBucket | [rdb.ValuesBucket](../apis-arkdata/js-apis-data-rdb.md#valuesbucket) | Yes | Data record to insert. If this parameter is **null**, a blank row will be inserted.| **Return value** @@ -834,7 +834,7 @@ DAHelper.delete('dataability:///com.example.DataAbility', (error, data) => { ## DataAbilityHelper.update -update(uri: string, valuesBucket: rdb.ValuesBucket, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\): void +update(uri: string, valuesBucket: [rdb.ValuesBucket](../apis-arkdata/js-apis-data-rdb.md#valuesbucket), predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\): void Updates data in the database. This API uses an asynchronous callback to return the result. @@ -847,7 +847,7 @@ Updates data in the database. This API uses an asynchronous callback to return t | Name | Type | Mandatory| Description | | ------------ | --------------------------------- | ---- | ------------------------------------------------ | | uri | string | Yes | URI of the data to update. | -| valuesBucket | rdb.ValuesBucket | Yes | New values. | +| valuesBucket | [rdb.ValuesBucket](../apis-arkdata/js-apis-data-rdb.md#valuesbucket) | Yes | New values. | | predicates | dataAbility.DataAbilityPredicates | Yes | Filter criteria. You should define the processing logic when this parameter is **null**.| | callback | AsyncCallback\ | Yes | Callback used to return the number of updated data records. | @@ -881,7 +881,7 @@ DAHelper.update('dataability:///com.example.DataAbility', va, da, (error, data) ## DataAbilityHelper.update -update(uri: string, valuesBucket: rdb.ValuesBucket, predicates?: dataAbility.DataAbilityPredicates): Promise\ +update(uri: string, valuesBucket: [rdb.ValuesBucket](../apis-arkdata/js-apis-data-rdb.md#valuesbucket), predicates?: dataAbility.DataAbilityPredicates): Promise\ Updates data in the database. This API uses a promise to return the result. @@ -894,7 +894,7 @@ Updates data in the database. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ------------ | --------------------------------- | ---- | ------------------------------------------------ | | uri | string | Yes | URI of the data to update. | -| valuesBucket | rdb.ValuesBucket | Yes | New values. | +| valuesBucket | [rdb.ValuesBucket](../apis-arkdata/js-apis-data-rdb.md#valuesbucket) | Yes | New values. | | predicates | dataAbility.DataAbilityPredicates | No | Filter criteria. You should define the processing logic when this parameter is **null**.| **Return value** @@ -929,7 +929,7 @@ DAHelper.update('dataability:///com.example.DataAbility', va, da).then((data) => ## DataAbilityHelper.update -update(uri: string, valuesBucket: rdb.ValuesBucket, callback: AsyncCallback\): void +update(uri: string, valuesBucket: [rdb.ValuesBucket](../apis-arkdata/js-apis-data-rdb.md#valuesbucket), callback: AsyncCallback\): void Uses a custom processing logic to update data records in the database. This API uses an asynchronous callback to return the result. @@ -942,7 +942,7 @@ Uses a custom processing logic to update data records in the database. This API | Name | Type | Mandatory| Description | | ------------ | --------------------------------- | ---- | ------------------------------------------------ | | uri | string | Yes | URI of the data to update. | -| valuesBucket | rdb.ValuesBucket | Yes | New values. | +| valuesBucket | [rdb.ValuesBucket](../apis-arkdata/js-apis-data-rdb.md#valuesbucket) | Yes | New values. | | callback | AsyncCallback\ | Yes | Callback used to return the number of updated data records. | **Example** diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-ability-dataAbilityOperation.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-ability-dataAbilityOperation.md index cc8f18359663e52a13fbf8dad26f7cf38df84df9..82ed3d5e275cf938102d2fc7660217721b96efeb 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-ability-dataAbilityOperation.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-ability-dataAbilityOperation.md @@ -1,10 +1,11 @@ # DataAbilityOperation -The **DataAbilityOperation** module defines the operation on DataAbilities. It can be used as an input parameter of [executeBatch](js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperexecutebatch) to specify the database operation information. +The DataAbilityOperation module defines the operation on DataAbilities. It can be used as an input parameter of [executeBatch](js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperexecutebatch) to specify the database operation information. > **NOTE** > > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> > The APIs of this module can be used only in the FA model. ## Modules to Import diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-ability-dataAbilityResult.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-ability-dataAbilityResult.md index 5b0862756fbeca3a20806e585fad07a05d1b375a..49e21a2e8c9db6746c40c2a15e865c7ff99a68d6 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-ability-dataAbilityResult.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-ability-dataAbilityResult.md @@ -1,10 +1,11 @@ # DataAbilityResult -The **DataAbilityResult** module defines the operation result on DataAbilities. When you call [executeBatch](js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperexecutebatch) to operate the database, the operation result is returned through the **DataAbilityResult** object. +The DataAbilityResult module defines the operation result on DataAbilities. When you call [executeBatch](js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperexecutebatch) to operate the database, the operation result is returned through the **DataAbilityResult** object. > **NOTE** > > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> > The APIs of this module can be used only in the FA model. ## Modules to Import diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-ability-startAbilityParameter.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-ability-startAbilityParameter.md index cbe8279865f9867573050555cb703fc7c0c64d53..b7c0882370049387d894d945ce102d570e7821ad 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-ability-startAbilityParameter.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-ability-startAbilityParameter.md @@ -5,6 +5,7 @@ The **StartAbilityParameter** module defines the parameters for starting an abil > **NOTE** > > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> > The APIs of this module can be used only in the FA model. ## Modules to Import diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-app-context.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-app-context.md index 96af67e0f211baf9f3c6bb079aa15079e51abcf2..61541501b36daa3f2984833019a3642e66fe366a 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-app-context.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-app-context.md @@ -688,7 +688,7 @@ Sets whether to wake up the screen when this feature is restored. This API uses > **NOTE** > -> This API is supported since API version 7 and deprecated since API version 12. Its substitute **window.setWakeUpScreen** is available only to system applications. +> This API is supported since API version 7 and deprecated since API version 12. Its substitute, **window.setWakeUpScreen**, is available only to system applications. **System capability**: SystemCapability.Ability.AbilityRuntime.Core diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-app-processInfo.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-app-processInfo.md index de49ed9d3f56bb8a963e0320db127081ff43b5a3..f5817146e4b80dd986af6d7a93730d03ef2979f9 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-app-processInfo.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-app-processInfo.md @@ -16,10 +16,10 @@ import featureAbility from '@ohos.ability.featureAbility'; **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name | Type | Readable | Writable | Description | +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| pid | number | Yes | No | Process ID. | -| processName | string | Yes | No | Process name. | +| pid | number | Yes| No| Process ID.| +| processName | string | Yes| No| Process name.| **Example** diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-GlobalObserver.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-GlobalObserver.md index 1867b93e2ca939992ae7d046a84d743f57a1b936..c509235456df617fcab0ca3fb29ba45763e8e9b6 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-GlobalObserver.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-GlobalObserver.md @@ -29,7 +29,7 @@ import { errorManager } from '@kit.AbilityKit'; ```ts import { errorManager } from '@kit.AbilityKit'; -function errorFunc(observer: errorManager.GlobalObserver) { +function errorFunc(observer: errorManager.GlobalError) { console.log("result name :" + observer.name); console.log("result message :" + observer.message); console.log("result stack :" + observer.stack); diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-abilityFirstFrameStateObserver-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-abilityFirstFrameStateObserver-sys.md index ca0b5a77e76999e06c00f539fb546b21b5e0e185..d0b7f00883a4bd70b99a0d07375794f654d122f4 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-abilityFirstFrameStateObserver-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-abilityFirstFrameStateObserver-sys.md @@ -21,4 +21,4 @@ import { appManager } from '@kit.AbilityKit'; | Name | Type | Read Only| Mandatory| Description | | ------------------------ | -------------------- | ---- | ---- | ------------------------------------------------------------ | -| onAbilityFirstFrameDrawn | AsyncCallback\ | Yes | No | Callback invoked when the first frame of an ability is rendered. The parameter type passed in is [AbilityFirstFrameStateData](js-apis-inner-application-abilityFirstFrameStateData-sys).| +| onAbilityFirstFrameDrawn | AsyncCallback\ | Yes | No | Callback invoked when the first frame of an ability is rendered. The parameter type passed in is [AbilityFirstFrameStateData](js-apis-inner-application-abilityFirstFrameStateData-sys.md).| diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-abilityForegroundStateObserver-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-abilityForegroundStateObserver-sys.md index 850b635a8e2b09df048ad3de94496217e1b3a308..ba9548815a8cd38fee3f20b519d0f4bdfe0dfe70 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-abilityForegroundStateObserver-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-abilityForegroundStateObserver-sys.md @@ -1,6 +1,6 @@ # AbilityForegroundStateObserver (System API) -The **AbilityForegroundStateObserver** module defines the listener used to listen for ability foreground and background state changes. +The AbilityForegroundStateObserver module defines the listener used to listen for ability foreground and background state changes. > **NOTE** > diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-abilityRunningInfo.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-abilityRunningInfo.md index 0e5ec30fff076fda7bc406a6b84deb5cbc3d45ff..147e91b1f13f76deaa82bb043a69ab3ac84f8f66 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-abilityRunningInfo.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-abilityRunningInfo.md @@ -27,27 +27,28 @@ The ability running information is obtained by calling [getAbilityRunningInfos]( | uid | number | Yes| No| User ID. | | processName | string | Yes| No| Process name. | | startTime | number | Yes| No| Ability start time. | -| abilityState | [AbilityState](js-apis-app-ability-abilityManager.md#abilitystate) | Yes| No| Ability state. | +| abilityState | [abilityManager.AbilityState](js-apis-app-ability-abilityManager.md#abilitystate) | Yes| No| Ability state. | **Example** ```ts import { abilityManager } from '@kit.AbilityKit'; - -abilityManager.getAbilityRunningInfos((error, data) => { - if (error) { - console.error(`getAbilityRunningInfos fail, error: ${JSON.stringify(error)}`); - } else { - console.log(`getAbilityRunningInfos success, data: ${JSON.stringify(data)}`); - for (let i = 0; i < data.length; i++) { - let abilityInfo = data[i]; - console.log(`abilityInfo.ability: ${JSON.stringify(abilityInfo.ability)}`); - console.log(`abilityInfo.pid: ${JSON.stringify(abilityInfo.pid)}`); - console.log(`abilityInfo.uid: ${JSON.stringify(abilityInfo.uid)}`); - console.log(`abilityInfo.processName: ${JSON.stringify(abilityInfo.processName)}`); - console.log(`abilityInfo.startTime: ${JSON.stringify(abilityInfo.startTime)}`); - console.log(`abilityInfo.abilityState: ${JSON.stringify(abilityInfo.abilityState)}`); - } - } -}); +import { BusinessError } from '@kit.BasicServicesKit'; + +try { + abilityManager.getAbilityRunningInfos() + .then((data: abilityManager.AbilityRunningInfo[]) => { + for (let i = 0; i < data.length; i++) { + let abilityInfo = data[i]; + console.info(`getAbilityRunningInfos success, data: ${JSON.stringify(abilityInfo)}`); + } + }) + .catch((error: BusinessError) => { + console.error(`getAbilityRunningInfos fail, error code: ${JSON.stringify(error.code)}, error msg: ${JSON.stringify(error.message)}`); + }) +} catch (e) { + let code = (e as BusinessError).code; + let msg = (e as BusinessError).message; + console.error(`getAbilityRunningInfos fail, error code: ${JSON.stringify(code)}, error msg: ${JSON.stringify(msg)}`); +} ``` diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-abilityStageContext.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-abilityStageContext.md index e13b5216515012f9ebf1b343f7e551615576c38f..54025ee5b45c59b7cf6d2260c014b9959b59a00f 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-abilityStageContext.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-abilityStageContext.md @@ -35,7 +35,7 @@ class MyAbilityStage extends AbilityStage { **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name | Type | Readable | Writable | Description | +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| currentHapModuleInfo | [HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) | Yes | No | **ModuleInfo** object corresponding to the **AbilityStage**. | -| config | [Configuration](js-apis-app-ability-configuration.md) | Yes | No | Configuration for the environment where the application is running. | +| currentHapModuleInfo | [HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) | Yes| No| **ModuleInfo** object corresponding to the **AbilityStage**.| +| config | [Configuration](js-apis-app-ability-configuration.md) | Yes| No| Configuration for the environment where the application is running.| diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-abilityStageMonitor.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-abilityStageMonitor.md index bddb953163b4ea210cfab299a032813ec640f1db..f37640970463b23539af4c471ecea83ab24e90b7 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-abilityStageMonitor.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-abilityStageMonitor.md @@ -1,6 +1,6 @@ # AbilityStageMonitor -The **AbilityStageMonitor** module provides conditions for matching **AbilityStage** instances. The most recently matched **AbilityStage** instance is saved in an **AbilityStageMonitor** instance. +The **AbilityStageMonitor** module provides conditions for matching **AbilityStage** instances. The most recently matched **AbilityStage** instance is saved in an **AbilityStageMonitor** instance. > **NOTE** > @@ -12,10 +12,10 @@ The **AbilityStageMonitor** module provides conditions for matching **AbilitySta **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable| Writable| Description | | ------------------------------------------------------------ | -------- | ---- | ---- | ------------------------------------------------------------ | -| moduleName | string | Yes | Yes | Module name of the **AbilityStage** instance. | -| srcEntrance | string | Yes | Yes | Source path of the **AbilityStage** instance. | +| moduleName | string | Yes | Yes | Module name of the **AbilityStage** instance.| +| srcEntrance | string | Yes | Yes | Source path of the **AbilityStage** instance.| **Example** ```ts diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-abilityStartCallback.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-abilityStartCallback.md index 44ff2accac5d01c003ac5404d094c1517352d08d..9f9311dda19638080cf114348bb899053f9a5282 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-abilityStartCallback.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-abilityStartCallback.md @@ -16,7 +16,9 @@ The AbilityStartCallback module describes the callback invoked to return the UIE import { common } from '@kit.AbilityKit'; ``` -## onError +## AbilityStartCallback + +### onError onError(code: number, name: string, message: string): void @@ -30,9 +32,9 @@ Called when the UIExtensionAbility fails to start. | Name | Type | Mandatory | Description | | -------- | ---------------------- | ---- | ------------- | -| code | number | Yes | Result code returned when the UIExtensionAbility fails to start. | -| name | string | Yes | Name returned when the UIExtensionAbility fails to start. | -| message | string | Yes | Error information returned when the UIExtensionAbility fails to start. | +| code | number | Yes | Result code returned when the UIExtensionAbility fails to start.| +| name | string | Yes | Name returned when the UIExtensionAbility fails to start.| +| message | string | Yes | Error information returned when the UIExtensionAbility fails to start.| **Example** @@ -65,7 +67,7 @@ export default class EntryAbility extends UIAbility { } ``` -## onResult12+ +### onResult12+ onResult?(parameter: AbilityResult): void @@ -79,7 +81,7 @@ Called when the UIExtensionAbility is terminated. | Name | Type | Mandatory | Description | | -------- | ---------------------- | ---- | ------------- | -| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes | Result returned when [terminateSelfWithResult](js-apis-inner-application-uiExtensionContext.md#uiextensioncontextterminateselfwithresult12) is called to terminate the UIExtensionAbility. | +| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes | Result returned when [terminateSelfWithResult](js-apis-inner-application-uiExtensionContext.md#uiextensioncontextterminateselfwithresult12) is called to terminate the UIExtensionAbility.| **Example** diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-abilityStateData.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-abilityStateData.md index df96332aa7ff53af5e90f438f4309d5cd44d2d0a..c380e05f2b2016e55917c679e9067859b9202600 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-abilityStateData.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-abilityStateData.md @@ -23,9 +23,9 @@ import { appManager } from '@kit.AbilityKit'; | abilityName | string | Yes | No | Ability name. | | uid | number | Yes | No | User ID. | | state | number | Yes | No | Ability state.
- In the stage model, the states of a UIAbility are described in [Ability States](#ability-states), and the states of an ExtensionAbility are described in [ExtensionAbility States](#extensionability-states).
- In the FA model, the states of an ability are described in [Ability States](#ability-states). | -| moduleName9+ | string | Yes | No | Name of the HAP file to which the ability belongs. | +| moduleName | string | Yes | No | Name of the HAP file to which the ability belongs. | | abilityType | number | Yes | No | [Ability type](#ability-types), which can be **page** or **service**.| -| isAtomicService12+| boolean | Yes | No | Whether the ability belongs to an atomic service.
**true**: The ability belongs to an atomic service.
**false**: The ability does not belong to an atomic service. | +| isAtomicService | boolean | Yes | No | Whether the ability belongs to an atomic service.
**true**: The ability belongs to an atomic service.
**false**: The ability does not belong to an atomic service. | | appCloneIndex | number | Yes | No | Index of an application clone. | ### Ability States diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-appStateData.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-appStateData.md index 5f7af5976caef3b731b92e84783b8d527f4b27aa..374fbc14c19573ce7c3ebbe87115cb8d14ac1b45 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-appStateData.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-appStateData.md @@ -18,11 +18,11 @@ import { appManager } from '@kit.AbilityKit'; | Name | Type | Mandatory | Description | | ------------------------- | ------ | ---- | --------- | -| bundleName | string | No | Bundle name.| -| uid | number | No | UID of the application. | -| state | number | No | Application state.
**0**: The application is being initialized.
**1**: The application has been initialized and is ready.
**2**: The application is running in the foreground.
**3**: The application is having the focus. (This state is reserved.)
**4**: The application is running in the background.
**5**: The application has exited.| -| isSplitScreenMode | boolean | No| Whether the application is in split-screen mode.
**true**: The application is in split-screen mode.
**false**: The application is not in split-screen mode.| -| isFloatingWindowMode | boolean | No| Whether the application is in floating window mode.
**true**: The application is in floating window mode.
**false**: The application is not in floating window mode.| +| bundleName | string | Yes | Bundle name.| +| uid | number | Yes | UID of the application. | +| state | number | Yes | Application state.
**0**: The application is being initialized.
**1**: The application has been initialized and is ready.
**2**: The application is running in the foreground.
**3**: The application is having the focus. (This state is reserved.)
**4**: The application is running in the background.
**5**: The application has exited.| +| isSplitScreenMode | boolean | Yes| Whether the application is in split-screen mode.
**true**: The application is in split-screen mode.
**false**: The application is not in split-screen mode.| +| isFloatingWindowMode | boolean | Yes| Whether the application is in floating window mode.
**true**: The application is in floating window mode.
**false**: The application is not in floating window mode.| **Example** diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-applicationContext.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-applicationContext.md index e8c4d86ca60b8b236687fe481e0466b8ba5c2ca5..6fc69a50fa695370806cba7f4c44ad24f201999a 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-applicationContext.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-applicationContext.md @@ -1,6 +1,6 @@ # ApplicationContext -The ApplicationContext module, inherited from [Context](js-apis-inner-application-context.md), provides application-level context capabilities, including APIs for registering and deregistering the lifecycle of application components. +The ApplicationContext module, inherited from [Context](js-apis-inner-application-context.md), provides application-level context capabilities, including APIs for registering and unregistering the lifecycle of application components. > **NOTE** > @@ -15,7 +15,7 @@ import { common } from '@kit.AbilityKit'; ## Usage -Before calling any APIs in **ApplicationContext**, obtain an **ApplicationContext** instance through the **context** instance. +Before calling any APIs in **ApplicationContext**, obtain an **ApplicationContext** instance through the **Context** instance. ## ApplicationContext.on('abilityLifecycle') @@ -109,7 +109,7 @@ export default class EntryAbility extends UIAbility { off(type: 'abilityLifecycle', callbackId: number, callback: AsyncCallback\): void -Deregisters the listener that monitors the ability lifecycle of the application. This API uses an asynchronous callback to return the result. It can be called only by the main thread. +Unregisters the listener that monitors the ability lifecycle of the application. This API uses an asynchronous callback to return the result. It can be called only by the main thread. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -120,7 +120,7 @@ Deregisters the listener that monitors the ability lifecycle of the application. | Name | Type | Mandatory| Description | | ------------- | -------- | ---- | -------------------------- | | type | 'abilityLifecycle' | Yes | Event type.| -| callbackId | number | Yes | ID of the listener to deregister.| +| callbackId | number | Yes | ID of the listener to unregister.| | callback | AsyncCallback\ | Yes | Callback used to return the result. If the deregistration is successful, **err** is **undefined**. Otherwise, **err** is an error object. | **Error codes** @@ -162,7 +162,7 @@ export default class EntryAbility extends UIAbility { off(type: 'abilityLifecycle', callbackId: number): Promise\ -Deregisters the listener that monitors the ability lifecycle of the application. This API uses a promise to return the result. It can be called only by the main thread. +Unregisters the listener that monitors the ability lifecycle of the application. This API uses a promise to return the result. It can be called only by the main thread. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -173,7 +173,7 @@ Deregisters the listener that monitors the ability lifecycle of the application. | Name | Type | Mandatory| Description | | ------------- | -------- | ---- | -------------------------- | | type | 'abilityLifecycle' | Yes | Event type.| -| callbackId | number | Yes | ID of the listener to deregister.| +| callbackId | number | Yes | ID of the listener to unregister.| **Return value** @@ -277,7 +277,7 @@ export default class EntryAbility extends UIAbility { off(type: 'environment', callbackId: number, callback: AsyncCallback\): void -Deregisters the listener for system environment changes. This API uses an asynchronous callback to return the result. It can be called only by the main thread. +Unregisters the listener for system environment changes. This API uses an asynchronous callback to return the result. It can be called only by the main thread. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -288,7 +288,7 @@ Deregisters the listener for system environment changes. This API uses an asynch | Name | Type | Mandatory| Description | | ------------- | -------- | ---- | -------------------------- | | type | 'environment' | Yes | Event type.| -| callbackId | number | Yes | ID of the listener to deregister. | +| callbackId | number | Yes | ID of the listener to unregister. | | callback | AsyncCallback\ | Yes | Callback used to return the result. If the deregistration is successful, **err** is **undefined**. Otherwise, **err** is an error object. | **Error codes** @@ -329,7 +329,7 @@ export default class EntryAbility extends UIAbility { off(type: 'environment', callbackId: number): Promise\ -Deregisters the listener for system environment changes. This API uses a promise to return the result. It can be called only by the main thread. +Unregisters the listener for system environment changes. This API uses a promise to return the result. It can be called only by the main thread. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -340,7 +340,7 @@ Deregisters the listener for system environment changes. This API uses a promise | Name | Type | Mandatory| Description | | ------------- | -------- | ---- | -------------------------- | | type | 'environment' | Yes | Event type.| -| callbackId | number | Yes | ID of the listener to deregister. | +| callbackId | number | Yes | ID of the listener to unregister. | **Return value** @@ -436,7 +436,11 @@ export default class MyAbility extends UIAbility { off(type: 'applicationStateChange', callback?: ApplicationStateChangeCallback): void -Deregisters all the listeners for application foreground/background state changes. This API uses an asynchronous callback to return the result. It can be called only by the main thread. +Unregisters the listener for application foreground/background state changes. This API uses an asynchronous callback to return the result. It can be called only by the main thread. + +> **NOTE** +> +> A listener must have been registered by calling [ApplicationContext.on('applicationStateChange')](#applicationcontextonapplicationstatechange10). **Atomic service API**: This API can be used in atomic services since API version 11. @@ -447,7 +451,7 @@ Deregisters all the listeners for application foreground/background state change | Name| Type | Mandatory| Description | | ------ | ------------- | ---- | -------------------- | | type | 'applicationStateChange' | Yes | Event type.| -| callback | [ApplicationStateChangeCallback](js-apis-app-ability-applicationStateChangeCallback.md) | No | Callback used to return the result. You can define a callback for switching from the background to the foreground and a callback for switching from the foreground to the background. | +| callback | [ApplicationStateChangeCallback](js-apis-app-ability-applicationStateChangeCallback.md) | No | Callback used to return the result. The value can be a callback defined by **ApplicationContext.on('applicationStateChange')** or empty.
- If a defined callback is passed in, the listener for that callback is unregistered.
- If no value is passed in, all the listeners for the corresponding event are unregistered. | **Error codes** @@ -459,6 +463,8 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** +Assume that [ApplicationContext.on('applicationStateChange')](#applicationcontextonapplicationstatechange10) is used to register a callback named **applicationStateChangeCallback**. The following example shows how to unregister the corresponding listener. + ```ts import { UIAbility } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; @@ -467,7 +473,9 @@ export default class MyAbility extends UIAbility { onDestroy() { let applicationContext = this.context.getApplicationContext(); try { - applicationContext.off('applicationStateChange'); + // In this example, the callback field is set to applicationStateChangeCallback. + // If no value is passed in for the callback field, all the listeners registered for the application foreground/background state change event are canceled. + applicationContext.off('applicationStateChange', applicationStateChangeCallback); } catch (paramError) { console.error(`error: ${(paramError as BusinessError).code}, ${(paramError as BusinessError).message}`); } @@ -572,7 +580,7 @@ Kills all processes of this application. The application will not go through the > **NOTE** > -> This API is used to forcibly exit an application in abnormal scenarios. To exit an application in the normal state, call [terminateSelf()](./js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself-1). +> This API is used to forcibly exit an application in abnormal scenarios. To exit an application properly, call [terminateSelf()](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself-1). **Atomic service API**: This API can be used in atomic services since API version 11. @@ -614,9 +622,9 @@ Kills all processes of this application. The application will not go through the > **NOTE** > -> This API is used to forcibly exit an application in abnormal scenarios. To exit an application in the normal state, call [terminateSelf()](./js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself-1). +> This API is used to forcibly exit an application in abnormal scenarios. To exit an application properly, call [terminateSelf()](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself-1). -**Atomic service API**: This API can be used in atomic services since API version 11. +**Atomic service API**: This API can be used in atomic services since API version 14. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -638,7 +646,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message| | ------- | -------- | -| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | +| 401 | If the input parameter is not valid parameter. | | 16000011 | The context does not exist. | **Example** @@ -664,7 +672,7 @@ Kills all processes of this application. The application will not go through the > **NOTE** > -> This API is used to forcibly exit an application in abnormal scenarios. To exit an application in the normal state, call [terminateSelf()](./js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself-1). +> This API is used to forcibly exit an application in abnormal scenarios. To exit an application properly, call [terminateSelf()](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself-1). **Atomic service API**: This API can be used in atomic services since API version 11. diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-applicationStateObserver.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-applicationStateObserver.md index 6d7322e7195a27ffee55446a96ecadda9c30452f..c328615ef8dac2b9df629ff26bdfd70143c4946d 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-applicationStateObserver.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-applicationStateObserver.md @@ -12,19 +12,115 @@ The ApplicationStateObserver module defines an observer to listen for applicatio import { appManager } from '@kit.AbilityKit'; ``` -## Properties +## ApplicationStateObserver.onForegroundApplicationChanged + +onForegroundApplicationChanged(appStateData: AppStateData): void + +Called when the foreground or background state of an application changes. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| appStateData | [AppStateData](js-apis-inner-application-appStateData.md) | Yes| Application state data.| + +## ApplicationStateObserver.onAbilityStateChanged + +onAbilityStateChanged(abilityStateData: AbilityStateData): void + +Called when the ability state changes. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| abilityStateData | [AbilityStateData](js-apis-inner-application-abilityStateData.md) | Yes| Ability state data.| + +## ApplicationStateObserver.onProcessCreated + +onProcessCreated(processData: ProcessData): void + +Called when a process is created. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| processData | [ProcessData](js-apis-inner-application-processData.md) | Yes| Process data.| + +## ApplicationStateObserver.onProcessDied + +onProcessDied(processData: ProcessData): void + +Called when a process is destroyed. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| processData | [ProcessData](js-apis-inner-application-processData.md) | Yes| Process data.| + +## ApplicationStateObserver.onProcessStateChanged + +onProcessStateChanged(processData: ProcessData): void + +Called when the process state is changed. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| processData | [ProcessData](js-apis-inner-application-processData.md) | Yes| Process data.| + +## ApplicationStateObserver.onAppStarted + +onAppStarted(appStateData: AppStateData): void + +Called when the first process of the application is created. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| appStateData | [AppStateData](js-apis-inner-application-appStateData.md) | Yes| Application state data.| + +## ApplicationStateObserver.onAppStopped + +onAppStopped(appStateData: AppStateData): void + +Called when the last process of the application is destroyed. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| appStateData | [AppStateData](js-apis-inner-application-appStateData.md) | Yes| Application state data.| + +## ProcessData + +type ProcessData = _ProcessData.default + +Defines the process data. **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name | Type | Readable| Writable| Description | -| -------------------------------- | ---------------------- | ---- | ---- | ------------------ | -| onForegroundApplicationChanged | AsyncCallback\ | Yes | No | Callback invoked when the foreground or background state of an application changes. The parameter type passed in is [AppStateData](js-apis-inner-application-appStateData.md).| -| onAbilityStateChanged | AsyncCallback\ | Yes | No | Callback invoked when the ability state changes. The parameter type passed in is [AbilityStateData](js-apis-inner-application-abilityStateData.md). | -| onProcessCreated | AsyncCallback\ | Yes | No | Callback invoked when a process is created. The parameter type passed in is [ProcessData](js-apis-inner-application-processData.md). | -| onProcessDied | AsyncCallback\ | Yes | No | Callback invoked when a process is destroyed. The parameter type passed in is [ProcessData](js-apis-inner-application-processData.md). | -| onProcessStateChanged | AsyncCallback\ | Yes | No | Callback invoked when the process state is changed. The parameter type passed in is [ProcessData](js-apis-inner-application-processData.md). | -| onAppStarted | AsyncCallback\ | Yes | No | Callback invoked when the first process of the application is created. The parameter type passed in is [AppStateData](js-apis-inner-application-appStateData.md). | -| onAppStopped | AsyncCallback\ | Yes | No | Callback invoked when the last process of the application is destroyed. The parameter type passed in is [AppStateData](js-apis-inner-application-appStateData.md). | +| Type| Description| +| --- | --- | +| [_ProcessData.default](js-apis-inner-application-processData.md) | Process data.| **Example** ```ts diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-autoFillExtensionContext-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-autoFillExtensionContext-sys.md index 4c924c3d5e5b6f7c4efdb710fdff28a6cdcb8529..17ab7710a19b790378f769f4de3a4b020e2c075b 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-autoFillExtensionContext-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-autoFillExtensionContext-sys.md @@ -1,4 +1,4 @@ -# AutoFillExtensionContext (System API) +# AutoFillExtensionContext (System API) The **AutoFillExtensionContext** module, inherited from [ExtensionContext](js-apis-inner-application-extensionContext.md), provides the context environment for the AutoFillExtensionAbility. @@ -22,7 +22,7 @@ class MyAutoFillExtensionAbility extends AutoFillExtensionAbility { } ``` -## AutoFillExtensionContext.reloadInModal12+ +## AutoFillExtensionContext.reloadInModal13+ reloadInModal(customData: CustomData): Promise\ @@ -32,21 +32,21 @@ Starts a modal page. **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ---------- | --------------------------------------------------------- | ---- | ---------------------------- | -| customData | [CustomData](js-apis-inner-application-customData-sys.md) | Yes | Custom information for starting the modal page. | +| customData | [CustomData](js-apis-inner-application-customData-sys.md) | Yes | Custom information for starting the modal page.| **Return value** | Type | Description | | ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value. | +| Promise<void> | Promise that returns no value.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). -| ID | Error Message | +| ID| Error Message | | -------- | ------------------------------------------------------------ | | 202 | Not System App. Interface caller is not a system app. | | 401 | If the input parameter is not valid parameter. | diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-autoFillPopupConfig-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-autoFillPopupConfig-sys.md index 9d4ce38662d0ea03eb98bb4cd898917183eefb06..5026bc2c751e00ba85ddb43d61378dd236610711 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-autoFillPopupConfig-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-autoFillPopupConfig-sys.md @@ -22,9 +22,9 @@ import { autoFillManager } from '@kit.AbilityKit'; **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | --------- | -------------- | ---- | ------------------------------------------ | -| popupSize | [PopupSize](#popupsize) | No | Width and height of the auto-fill pop-up. If this parameter is not set, the width and height are not updated. | +| popupSize | [PopupSize](#popupsize) | No | Width and height of the auto-fill pop-up. If this parameter is not set, the width and height are not updated.| | placement | [PopupPlacement](#popupplacement) | No | Position of the auto-fill pop-up. If this parameter is not set, the position is not updated.| ## PopupSize @@ -35,10 +35,10 @@ Describes the width and height of the auto-fill pop-up. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore -| Name | Type | Mandatory | Description | +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | --------------- | -| width | number | Yes | Width of the auto-fill pop-up. | -| height | number | Yes | Height of the auto-fill pop-up. | +| width | number | Yes | Width of the auto-fill pop-up.| +| height | number | Yes | Height of the auto-fill pop-up.| ## PopupPlacement @@ -50,16 +50,16 @@ Enumerates the positions of an auto-fill pop-up. | Name | Value | Description | | ------------ | --- | --------------------------------- | -| LEFT | 0 |The popup is on the left of the component and aligned with the left center of the component. | -| RIGHT | 1 |The popup is on the right of the component and aligned with the right center of the component. | -| TOP | 2 |The popup is at the top of the component and aligned with the top center of the component. | -| BOTTOM | 3 |The popup is at the bottom of the component and aligned with the bottom center of the component. | -| TOP_LEFT | 4 |The popup is at the top of the component and aligned with the left edge of the component. | -| TOP_RIGHT | 5 |The popup is at the top of the component and aligned with the right edge of the component. | -| BOTTOM_LEFT | 6 |The popup is at the bottom of the component and aligned with the left edge of the component. | -| BOTTOM_RIGHT | 7 |The popup is at the bottom of the component and aligned with the right edge of the component. | -| LEFT_TOP | 8 |The popup is on the left of the component and aligned with the top edge of the component. | -| LEFT_BOTTOM | 9 |The popup is on the left of the component and aligned with the bottom edge of the component. | -| RIGHT_TOP | 10 |The popup is on the right of the component and aligned with the top edge of the component. | -| RIGHT_BOTTOM | 11 |The popup is on the right of the component and aligned with the bottom edge of the component. | +| LEFT | 0 |The popup is on the left of the component and aligned with the left center of the component.| +| RIGHT | 1 |The popup is on the right of the component and aligned with the right center of the component.| +| TOP | 2 |The popup is at the top of the component and aligned with the top center of the component.| +| BOTTOM | 3 |The popup is at the bottom of the component and aligned with the bottom center of the component.| +| TOP_LEFT | 4 |The popup is at the top of the component and aligned with the left edge of the component.| +| TOP_RIGHT | 5 |The popup is at the top of the component and aligned with the right edge of the component.| +| BOTTOM_LEFT | 6 |The popup is at the bottom of the component and aligned with the left edge of the component.| +| BOTTOM_RIGHT | 7 |The popup is at the bottom of the component and aligned with the right edge of the component.| +| LEFT_TOP | 8 |The popup is on the left of the component and aligned with the top edge of the component.| +| LEFT_BOTTOM | 9 |The popup is on the left of the component and aligned with the bottom edge of the component.| +| RIGHT_TOP | 10 |The popup is on the right of the component and aligned with the top edge of the component.| +| RIGHT_BOTTOM | 11 |The popup is on the right of the component and aligned with the bottom edge of the component.| | NONE | 12 |The position is unspecified. | diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-autoFillRect-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-autoFillRect-sys.md index b83a7536ed9bb68ba94cf9b491bda58298c6ad08..67a0e9e83bc69d2ce9e53fddf79189a2b4086b3a 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-autoFillRect-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-autoFillRect-sys.md @@ -1,6 +1,6 @@ # AutoFillRect (System API) -**AutoFillRect** describes the rectangle used for AutoFill. +**AutoFillRect** describes the rectangle used for auto-fill. > **NOTE** > diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-autoFillRequest-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-autoFillRequest-sys.md index 3d46a85b7f9c434df62f22d942b031d280087f45..d68051ed1d7d6bba83611a4ebc68dd5bbfbcf8bd 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-autoFillRequest-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-autoFillRequest-sys.md @@ -24,7 +24,7 @@ Defines the information about an auto-fill request. | ----------- | -------------------- | ---- | ------------------------------------------------------------ | | type | [AutoFillType](js-apis-inner-application-autoFillType-sys.md) | Yes | Type of the element to be automatically filled in. | | viewData | [ViewData](js-apis-inner-application-viewData-sys.md) | Yes | Page data. | -| customData12+ | [CustomData](js-apis-inner-application-customData-sys.md) | Yes | Custom data. | +| customData13+ | [CustomData](js-apis-inner-application-customData-sys.md) | Yes | Custom data. | | isPopup12+ | boolean | Yes | Whether a dialog box is displayed for the auto-fill request.
**true**: A dialog box is displayed
**false**: A modal window is displayed | ## SaveRequest @@ -73,7 +73,7 @@ Called when an auto-fill request is successfully processed. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | ------------------------------ | -| response | [FillResponse](../apis/#fillresponse) | Yes| Information about the response to the auto-fill response.| +| response | [FillResponse](#fillresponse) | Yes| Information about the response to the auto-fill request.| **Error codes** @@ -246,7 +246,7 @@ struct AutoFillPage { } ``` -### FillRequestCallback.onCancel12+ +### FillRequestCallback.onCancel11+ onCancel(fillContent?: string): void diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-autoFillType-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-autoFillType-sys.md index 286798f9ee9be5744120bf9f80988310abddaf29..70851b27a05a357a0a7ef68b5b3d33d4e4149f9f 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-autoFillType-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-autoFillType-sys.md @@ -26,21 +26,33 @@ import { autoFillManager } from '@kit.AbilityKit'; | PASSWORD | 1 | Password. | | USER_NAME | 2 | Username. | | NEW_PASSWORD | 3 | New password. | -| FULL_STREET_ADDRESS12+ | 4 | Detailed address with street information. | -| HOUSE_NUMBER12+ | 5 | House number. | -| DISTRICT_ADDRESS12+ | 6 | District. | -| CITY_ADDRESS12+ | 7 | City. | -| PROVINCE_ADDRESS12+ | 8 | Province. | -| COUNTRY_ADDRESS12+ | 9 | Country/Region. | -| PERSON_FULL_NAME12+ | 10 | Full name. | -| PERSON_LAST_NAME12+ | 11 | Last name. | -| PERSON_FIRST_NAME12+ | 12 | First name. | -| PHONE_NUMBER12+ | 13 | Mobile number. | -| PHONE_COUNTRY_CODE12+ | 14 | Country/Region code. | -| FULL_PHONE_NUMBER12+ | 15 | Mobile number with the country/region code. | -| EMAIL_ADDRESS12+ | 16 | Email address. | -| BANK_CARD_NUMBER12+ | 17 | Bank card number. | -| ID_CARD_NUMBER12+ | 18 | ID card number. | -| NICKNAME12+ | 24 | Nickname. | -| DETAIL_INFO_WITHOUT_STREET12+ | 25 | Detailed address without street information. | -| FORMAT_ADDRESS12+ | 26 | Standard address. | +| FULL_STREET_ADDRESS12+ | 4 | Detailed address with street information.| +| HOUSE_NUMBER12+ | 5 | House number.| +| DISTRICT_ADDRESS12+ | 6 | District.| +| CITY_ADDRESS12+ | 7 | City.| +| PROVINCE_ADDRESS12+ | 8 | Province.| +| COUNTRY_ADDRESS12+ | 9 | Country/Region.| +| PERSON_FULL_NAME12+ | 10 | Full name.| +| PERSON_LAST_NAME12+ | 11 | Last name.| +| PERSON_FIRST_NAME12+ | 12 | First name.| +| PHONE_NUMBER12+ | 13 | Mobile number.| +| PHONE_COUNTRY_CODE12+ | 14 | Country/Region code.| +| FULL_PHONE_NUMBER12+ | 15 | Mobile number with the country/region code.| +| EMAIL_ADDRESS12+ | 16 | Email address.| +| BANK_CARD_NUMBER12+ | 17 | Bank card number.| +| ID_CARD_NUMBER12+ | 18 | ID card number.| +| NICKNAME12+ | 24 | Nickname.| +| DETAIL_INFO_WITHOUT_STREET12+ | 25 | Detailed address without street information.| +| FORMAT_ADDRESS12+ | 26 | Standard address.| +| PASSPORT_NUMBER18+ | 27 | Passport number.| +| VALIDITY18+ | 28 | Validity period of the passport.| +| ISSUE_AT18+ | 29 | Location where the passport was issued.| +| ORGANIZATION18+ | 30 | Invoice title.| +| TAX_ID18+ | 31 | Tax ID.| +| ADDRESS_CITY_AND_STATE18+ | 32 | Location (city and state).| +| FLIGHT_NUMBER18+ | 33 | Flight number.| +| LICENSE_NUMBER18+ | 34 | Driver's license number.| +| LICENSE_FILE_NUMBER18+ | 35 | Driver's license file number.| +| LICENSE_PLATE18+ | 36 | License plate.| +| ENGINE_NUMBER18+ | 37 | Vehicle engine number.| +| LICENSE_CHASSIS_NUMBER18+ | 38 | Chassis number (VIN) of a vehicle.| diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-autoStartupCallback-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-autoStartupCallback-sys.md index 71a2d7d18af8ada5e2d8f7b6e32fb2485fbe033c..704f403161fbb4f77cdd0c9c8624d10b4e42a811 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-autoStartupCallback-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-autoStartupCallback-sys.md @@ -21,9 +21,9 @@ Called when auto-startup is set for an application component. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| info | [AutoStartupInfo](js-apis-inner-application-autoStartupInfo-sys.md) | Yes | Information about the target application component. | +| info | [AutoStartupInfo](js-apis-inner-application-autoStartupInfo-sys.md) | Yes| Information about the target application component.| **Example** @@ -59,9 +59,9 @@ Called when the auto-startup setting of an application component is canceled. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type | Mandatory| Description | | ------ | --------------- | ---- | -------------------- | -| info | [AutoStartupInfo](js-apis-inner-application-autoStartupInfo-sys.md) | Yes | Information about the target application component. | +| info | [AutoStartupInfo](js-apis-inner-application-autoStartupInfo-sys.md) | Yes | Information about the target application component.| **Example** diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-autoStartupInfo-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-autoStartupInfo-sys.md index b9c35d094cc325b40fdd1158fd1c4b85329dd579..37c5addaa8efdd8ebcae1a89502f2155931af1bf 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-autoStartupInfo-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-autoStartupInfo-sys.md @@ -1,4 +1,4 @@ - # AutoStartupInfo (System API) +# AutoStartupInfo (System API) The **AutoStartupInfo** module defines information about the application component that automatically starts upon system boot. @@ -17,10 +17,10 @@ The **AutoStartupInfo** module defines information about the application compone | Name | Type | Mandatory | Description | | ------------------------- | ------ | ---- | --------- | -| bundleName | string | Yes | Bundle name. | -| moduleName | string | No | Module name. | -| abilityName | string | Yes | Ability name. | -| abilityTypeName | string | No | Ability type. | +| bundleName | string | Yes | Bundle name.| +| moduleName | string | No | Module name.| +| abilityName | string | Yes | Ability name.| +| abilityTypeName | string | No| Ability type.| | appCloneIndex | number | No | Index of an application clone. | **Example** diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-baseContext.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-baseContext.md index b0b26fa768008bcf9aabd9c89e103a34de234003..d2639d2a91c4c43925567a14a4af7cae1f3cf9f5 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-baseContext.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-baseContext.md @@ -20,7 +20,7 @@ import { common } from '@kit.AbilityKit'; | Name | Type | Readable | Writable | Description | | -------- | ------ | ---- | ---- | ------- | -| stageMode | boolean | Yes | Yes | Whether the child class **Context** is used for the stage model.
**true**: used for the stage model.
**false**: used for the FA model. | +| stageMode | boolean | Yes | Yes | Whether the child class **Context** is used for the stage model.
**true**: used for the stage model.
**false**: used for the FA model.| **Example** diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-context.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-context.md index 3eccdc0bca55ac8a6babce39df09e0834f403b0d..e7c2edaa4a7a3341d6654f8acfcde20c78cd5737 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-context.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-context.md @@ -23,7 +23,7 @@ import { common } from '@kit.AbilityKit'; | applicationInfo | [ApplicationInfo](js-apis-bundleManager-applicationInfo.md) | No | No | Application information.
**Atomic service API**: This API can be used in atomic services since API version 11.| | cacheDir | string | No | No | Cache directory.
**Atomic service API**: This API can be used in atomic services since API version 11.| | tempDir | string | No | No | Temporary directory.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| resourceDir11+ | string | No | No | Resource directory.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| resourceDir11+ | string | No | No | Resource directory.
**NOTE**: You are required to manually create the **resfile** directory in **\\resource**. The **resfile** directory can be accessed only in read-only mode.
**Atomic service API**: This API can be used in atomic services since API version 11.| | filesDir | string | No | No | File directory.
**Atomic service API**: This API can be used in atomic services since API version 11.| | databaseDir | string | No | No | Database directory.
**Atomic service API**: This API can be used in atomic services since API version 11.| | preferencesDir | string | No | No | Preferences directory.
**Atomic service API**: This API can be used in atomic services since API version 11.| @@ -32,7 +32,7 @@ import { common } from '@kit.AbilityKit'; | cloudFileDir12+ | string | No | No | Cloud file directory.
**Atomic service API**: This API can be used in atomic services since API version 12. | | eventHub | [EventHub](js-apis-inner-application-eventHub.md) | No | No | Event hub that implements event subscription, unsubscription, and triggering.
**Atomic service API**: This API can be used in atomic services since API version 11.| | area | contextConstant.[AreaMode](js-apis-app-ability-contextConstant.md) | No | No | Encryption level of the directory.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| processName16+ | string | No | No| Process name of the current application.
**Atomic service API**: This API can be used in atomic services since API version 16.| +| processName18+ | string | No | No| Process name of the current application.
**Atomic service API**: This API can be used in atomic services since API version 18.| ## Context.createModuleContext(deprecated) @@ -235,13 +235,13 @@ export default class EntryAbility extends UIAbility { } ``` -## Context.createAreaModeContext16+ +## Context.createAreaModeContext18+ createAreaModeContext(areaMode: contextConstant.AreaMode): Context Creates the context for this application based on a data encryption level. This is required when an application needs to store different types of information in different directories. The application can obtain the corresponding directory. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -285,13 +285,13 @@ export default class EntryAbility extends UIAbility { } ``` -## Context.createDisplayContext16+ +## Context.createDisplayContext15+ createDisplayContext(displayId: number): Context Creates the context based on the specified display ID, so as to obtain and use other application contexts with screen information (including [ScreenDensity](../apis-localization-kit/js-apis-resource-manager.md#screendensity) and [Direction](../apis-localization-kit/js-apis-resource-manager.md#direction)). -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 15. **System capability**: SystemCapability.Ability.AbilityRuntime.Core diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-continueCallback-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-continueCallback-sys.md index 137400bf55c16f3d1d9faf356f9103bd620a4abb..21d4bf2d207918e9f82e6a49e3400d4a4d833375 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-continueCallback-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-continueCallback-sys.md @@ -19,9 +19,9 @@ Called when the mission continuation is complete. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| result | number | Yes | Mission continuation result. | +| result | number | Yes| Mission continuation result.| **Example** diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-continueDeviceInfo-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-continueDeviceInfo-sys.md index 12eec4972997048c428de40b783f0e8f59a36b9f..3bc8941ac5fca98133624ab694918f9478a45b66 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-continueDeviceInfo-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-continueDeviceInfo-sys.md @@ -11,7 +11,7 @@ The ContinueDeviceInfo module defines the parameters required for initiating mis **System capability**: SystemCapability.Ability.AbilityRuntime.Mission -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. | Name | Type | Readable | Writable | Description | | -------- | ------ | ---- | ---- | ------- | diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-customData-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-customData-sys.md index 8c42200261fdf400c9c71e7a6f116e0a1c87d880..0ab25f29847d1a36e83a87242532e4b86e37dd5c 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-customData-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-customData-sys.md @@ -4,7 +4,7 @@ When starting a modal page, you can transfer custom data to the autofill service > **NOTE** > -> The initial APIs of this module are supported since API version 12. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The initial APIs of this module are supported since API version 13. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. > The APIs provided by this module are system APIs. @@ -12,6 +12,6 @@ When starting a modal page, you can transfer custom data to the autofill service **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore -| Name | Type | Mandatory | Description | +| Name| Type | Mandatory| Description | | ---- | ---------------------- | ---- | ---------------------------------------------------- | -| data | Record | Yes | Custom data transferred for starting the modal page. The data is of the Record type. | +| data | Record | Yes | Custom data transferred for starting the modal page. The data is of the Record type.| diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-extensionContext.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-extensionContext.md index f62a65fb3e1e61d05a0fdbaa87bb9b72ea482694..31809f7cab6b13a5f044645957afcad05fbf591c 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-extensionContext.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-extensionContext.md @@ -21,11 +21,11 @@ import { common } from '@kit.AbilityKit'; **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name | Type | Readable | Writable | Description | +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| currentHapModuleInfo | [HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) | Yes | No | Information about the HAP file.
(See **api\bundle\hapModuleInfo.d.ts** in the **SDK** directory.) | -| config | [Configuration](js-apis-app-ability-configuration.md) | Yes | No | Module configuration information.
(See **api\@ohos.app.ability.Configuration.d.ts** in the **SDK** directory.) | -| extensionAbilityInfo | [ExtensionAbilityInfo](js-apis-bundleManager-extensionAbilityInfo.md) | Yes | No | Extension ability information.
(See **api\bundle\extensionAbilityInfo.d.ts** in the **SDK** directory.) | +| currentHapModuleInfo | [HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) | Yes| No| Information about the HAP file.
(See **api\bundle\hapModuleInfo.d.ts** in the **SDK** directory.) | +| config | [Configuration](js-apis-app-ability-configuration.md) | Yes| No| Module configuration information.
(See **api\@ohos.app.ability.Configuration.d.ts** in the **SDK** directory.)| +| extensionAbilityInfo | [ExtensionAbilityInfo](js-apis-bundleManager-extensionAbilityInfo.md) | Yes| No| Extension ability information.
(See **api\bundle\extensionAbilityInfo.d.ts** in the **SDK** directory.)| ## When to Use **ExtensionContext** provides information about an Extension ability, module, and HAP file. You can use the information based on service requirements. diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-extensionRunningInfo-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-extensionRunningInfo-sys.md index ec3c81de3c9e48adc4064eafb0193c6523f975cd..d514cd1896d172f82b5405b7382dd3c6a9349a38 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-extensionRunningInfo-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-extensionRunningInfo-sys.md @@ -21,17 +21,17 @@ Import the **abilityManager** module and obtain the ExtensionAbility running inf **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: The following APIs are system APIs and cannot be called by third-party applications. +**System API**: This is a system API. -| Name | Type | Readable | Writable | Description | +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| extension | [ElementName](js-apis-bundleManager-elementName.md) | Yes | No | ExtensionAbility information. | -| pid | number | Yes | No | Process ID. | -| uid | number | Yes | No | UID of the application. | -| processName | string | Yes | No | Process name. | -| startTime | number | Yes | No | Timestamp when the ExtensionAbility is started. | -| clientPackage | Array<String> | Yes | No | Names of all packages in the process. | -| type | [ExtensionAbilityType](js-apis-bundleManager.md#extensionabilitytype) | Yes | No | ExtensionAbility type. | +| extension | [ElementName](js-apis-bundleManager-elementName.md) | Yes| No| ExtensionAbility information.| +| pid | number | Yes| No| Process ID.| +| uid | number | Yes| No| UID of the application.| +| processName | string | Yes| No| Process name.| +| startTime | number | Yes| No| Timestamp when the ExtensionAbility is started.| +| clientPackage | Array<String> | Yes| No| Names of all packages in the process.| +| type | [ExtensionAbilityType](js-apis-bundleManager.md#extensionabilitytype) | Yes| No| ExtensionAbility type.| **Example** ```ts diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-missionCallbacks-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-missionCallbacks-sys.md index cb71efacc5524f6755694b6d26379d07207fa2b4..d9d1af51a20503d6d18f33afe9b83329fb1bbbc5 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-missionCallbacks-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-missionCallbacks-sys.md @@ -21,9 +21,9 @@ import { distributedMissionManager } from '@kit.AbilityKit'; **Parameters** -| Name | Template | Mandatory | Description | +| Name| Template| Mandatory| Description| | -------- | -------- | -------- | -------- | -| deviceId | string | Yes | Device ID in the callback that notifies a mission change.| +| deviceId | string | Yes| Device ID in the callback that notifies a mission change.| **Example** ```ts @@ -57,10 +57,10 @@ distributedMissionManager.registerMissionListener( **Parameters** -| Name | Template | Mandatory | Description | +| Name| Template| Mandatory| Description| | -------- | -------- | -------- | -------- | -| deviceId | string | Yes | Device ID in the callback that notifies a snapshot change. | -| mission | number | Yes | Mission ID in the callback that notifies a snapshot change. | +| deviceId | string | Yes| Device ID in the callback that notifies a snapshot change.| +| mission | number | Yes| Mission ID in the callback that notifies a snapshot change.| **Example** ```ts @@ -94,12 +94,13 @@ distributedMissionManager.registerMissionListener( **Parameters** -| Name | Template | Mandatory | Description | +| Name| Template| Mandatory| Description| | -------- | -------- | -------- | -------- | -| deviceId | string | Yes | Device ID in the callback that notifies disconnection. | -| state | number | Yes | Network status in the callback that notifies disconnection. | +| deviceId | string | Yes| Device ID in the callback that notifies disconnection.| +| state | number | Yes| Network status in the callback that notifies disconnection. The fixed value **0** is returned, indicating network disconnection.| **Example** + ```ts import { distributedMissionManager } from '@kit.AbilityKit'; diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-missionDeviceInfo-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-missionDeviceInfo-sys.md index 5f765a9b9079d213c5e68f08867f52c270fdf5aa..cda48cd8f789b1553ee6f586c7075f9cf3f6dc5b 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-missionDeviceInfo-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-missionDeviceInfo-sys.md @@ -22,4 +22,4 @@ import { distributedMissionManager } from '@kit.AbilityKit'; | Name | Type | Readable | Writable | Description | | -------- | ------ | ---- | ---- | ------- | -| deviceId | string | Yes | Yes | Device ID. | +| deviceId | string | Yes | Yes | Device ID.| diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-missionInfo-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-missionInfo-sys.md index 4813ab822332b85d238d8f3fc4efe58ef894eaf6..6b26184e46523fdbb510d4d15b6ebb3fb26941b2 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-missionInfo-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-missionInfo-sys.md @@ -15,22 +15,22 @@ import { missionManager } from '@kit.AbilityKit'; ## Attributes -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Ability.AbilityRuntime.Mission -| Name | Type | Readable | Writable | Description | +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| missionId | number | Yes | Yes | Mission ID.| -| runningState | number | Yes | Yes | Running state of the mission. | -| lockedState | boolean | Yes | Yes | Locked state of the mission. | -| timestamp | string | Yes | Yes | Latest time when the mission was created or updated. | -| want | [Want](js-apis-app-ability-want.md) | Yes | Yes | Want information of the mission. | -| label | string | Yes | Yes | Label of the mission. | -| iconPath | string | Yes | Yes | Path of the mission icon. | -| continuable | boolean | Yes | Yes | Whether the mission can be continued on another device. | -| abilityState10+ | number | Yes | Yes | Capability status of the mission. | -| unclearable10+ | boolean | Yes | Yes | Whether the mission can be manually deleted. | +| missionId | number | Yes| Yes| Mission ID.| +| runningState | number | Yes| Yes| Running state of the mission.| +| lockedState | boolean | Yes| Yes| Locked state of the mission.| +| timestamp | string | Yes| Yes| Latest time when the mission was created or updated.| +| want | [Want](js-apis-app-ability-want.md) | Yes| Yes| Want information of the mission.| +| label | string | Yes| Yes| Label of the mission.| +| iconPath | string | Yes| Yes| Path of the mission icon.| +| continuable | boolean | Yes| Yes| Whether the mission can be continued on another device.| +| abilityState10+ | number | Yes| Yes| Capability status of the mission.| +| unclearable10+ | boolean | Yes| Yes| Whether the mission can be manually deleted.| **Example** ```ts diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-missionListener-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-missionListener-sys.md index e89e2b3af36eaecaff8353c2d3a607782c05d545..fd596c7520ac1a17d80cb5e5445f756a20bd3228 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-missionListener-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-missionListener-sys.md @@ -15,7 +15,7 @@ import { missionManager } from '@kit.AbilityKit'; ## Attributes -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Ability.AbilityRuntime.Mission diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-processData.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-processData.md index 9ae0f14a5e13cec02a1ddd908c9b92f54d39f43e..6ddbf62d8051876d04b0fceb2b3e64c408de73e5 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-processData.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-processData.md @@ -16,14 +16,14 @@ import { appManager } from '@kit.AbilityKit'; **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name | Type | Read-Only| Mandatory| Description | -| ----------------------- | ---------| ---- | ---- | ------------------------- | -| pid | number | No | Yes | Process ID. | -| bundleName | string | No | Yes | Bundle name of the application. | -| uid | number | No | Yes | UID of the application. | -| isContinuousTask | boolean | No | Yes | Whether the task is a continuous task. The value **true** means that the task is a continuous task, and **false** means the opposite. | -| isKeepAlive | boolean | No | Yes | Whether the process is a resident task. The value **true** means that the process is a resident, and **false** means the opposite. | -| state | number | No | Yes | Application state. The options are as follows:
**0**: newly created.
**1**: ready.
**2**: running in the foreground.
**4**: running in the background.
**5**: terminated. | +| Name | Type | Mandatory| Description | +| ----------------------- | ---------| ---- | ------------------------- | +| pid | number | Yes | Process ID. | +| bundleName | string | Yes | Bundle name of the application. | +| uid | number | Yes | UID of the application. | +| isContinuousTask | boolean | Yes | Whether the task is a continuous task. The value **true** means that the task is a continuous task, and **false** means the opposite. | +| isKeepAlive | boolean | Yes | Whether the process is a resident task. The value **true** means that the process is a resident, and **false** means the opposite. | +| state | number | Yes | Application state. The options are as follows:
**0**: newly created.
**1**: ready.
**2**: running in the foreground.
**4**: running in the background.
**5**: terminated. | **Example** ```ts diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-runningAppClone-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-runningAppClone-sys.md index 5ea05a1fe760ef9b0d8098d68f4a38606568e834..e48ef390d5f30970fcf5ac8d830bbd3209c89d0a 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-runningAppClone-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-runningAppClone-sys.md @@ -1,9 +1,9 @@ - # RunningAppClone (System API) +# RunningAppClone (System API) The RunningAppClone module defines the information of an application clone in the running state. > **NOTE** -> +> > The initial APIs of this module are supported since API version 12. Newly added APIs will be marked with a superscript to indicate their earliest API version. > > The APIs provided by this module are system APIs. diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-serviceExtensionContext-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-serviceExtensionContext-sys.md index 8484001642d7328bdbb7e3d7531292ff1421dd93..6a24e19a469089f9bc51ebc150caa4af50c323aa 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-serviceExtensionContext-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-serviceExtensionContext-sys.md @@ -44,7 +44,7 @@ Starts an ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -126,7 +126,7 @@ Starts an ability. This API uses a promise to return the result. It can be calle **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -217,7 +217,7 @@ Starts an ability with the start options specified. This API uses an asynchronou **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -310,7 +310,7 @@ Starts an ability with the account ID specified. This API uses an asynchronous c **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -402,7 +402,7 @@ Starts an ability with the account ID and start options specified. This API uses **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -499,7 +499,7 @@ Starts an ability with the account ID specified. This API uses a promise to retu **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -594,7 +594,7 @@ Starts a new ServiceExtensionAbility. This API uses an asynchronous callback to **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -665,7 +665,7 @@ Starts a new ServiceExtensionAbility. This API uses a promise to return the resu **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -748,7 +748,7 @@ Starts a new ServiceExtensionAbility with the account ID specified. This API use **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -828,7 +828,7 @@ Starts a new ServiceExtensionAbility with the account ID specified. This API use **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -910,7 +910,7 @@ Starts an ability with the caller information specified. The caller information **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -990,7 +990,7 @@ Starts an ability with the caller information and start options specified. The c **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -1073,7 +1073,7 @@ Starts an ability with the caller information specified. The caller information **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -1160,7 +1160,7 @@ Stops a ServiceExtensionAbility in the same application. This API uses an asynch **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -1227,7 +1227,7 @@ Stops a ServiceExtensionAbility in the same application. This API uses a promise **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -1305,7 +1305,7 @@ Stops a ServiceExtensionAbility in the same application with the account ID spec **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -1380,7 +1380,7 @@ Stops a ServiceExtensionAbility in the same application with the account ID spec **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -1454,7 +1454,7 @@ Terminates this ability. This API uses an asynchronous callback to return the re **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -1505,7 +1505,7 @@ Terminates this ability. This API uses a promise to return the result. It can be **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Return value** @@ -1557,7 +1557,7 @@ Connects this ability to a ServiceExtensionAbility. It can be called only by the **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -1636,6 +1636,8 @@ connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options Connects this ability to a ServiceExtensionAbility of a given account. It can be called only by the main thread. +Currently, this API takes effect only on mobile phones and tablets. + > **NOTE** > > For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). @@ -1645,7 +1647,7 @@ Connects this ability to a ServiceExtensionAbility of a given account. It can be **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -1730,7 +1732,7 @@ Disconnects this ability from a ServiceExtensionAbility and after the successful **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -1790,7 +1792,7 @@ Disconnects this ability from a ServiceExtensionAbility and after the successful **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -1865,7 +1867,7 @@ Observe the following when using this API: **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -1983,7 +1985,7 @@ Starts an ability. If the ability has multiple instances, the latest instance is **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -2060,7 +2062,7 @@ You can use this API to carry start options. It can be called only by the main t **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -2142,7 +2144,7 @@ This API uses a promise to return the result. It can be called only by the main **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -2228,7 +2230,7 @@ Observe the following when using this API: **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -2634,16 +2636,14 @@ export default class ServiceExtAbility extends ServiceExtensionAbility { } ``` -## ServiceExtensionContext.startUIServiceExtensionAbility13+ +## ServiceExtensionContext.startUIServiceExtensionAbility14+ startUIServiceExtensionAbility(want: Want): Promise<void> Starts a new [UIServiceExtensionAbility](js-apis-app-ability-uiServiceExtensionAbility-sys.md). This API uses a promise to return the result. - > **NOTE** > > For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). -> **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -2704,7 +2704,7 @@ export default class MyServiceExtensionAbility extends ServiceExtensionAbility { } ``` -## ServiceExtensionContext.openAtomicService16+ +## ServiceExtensionContext.openAtomicService18+ openAtomicService(appId: string, options?: AtomicServiceOptions): Promise<void> Starts an atomic service based on an application ID. This API uses a promise to return the result. diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext-sys.md index 6915c9346d4c1b31e3b0a95e06fe51a469ca3ed4..d83480a75ec98494d56f65a496b07425a9141032 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext-sys.md @@ -33,7 +33,7 @@ Starts an ability with the account ID specified and returns the result when the **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -127,7 +127,7 @@ Starts an ability with the account ID and start options specified and returns th **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -225,7 +225,7 @@ Starts an ability with the account ID specified and returns the result when the **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -319,7 +319,7 @@ Starts a ServiceExtensionAbility. This API uses an asynchronous callback to retu **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -390,7 +390,7 @@ Starts a ServiceExtensionAbility. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -467,7 +467,7 @@ Starts a ServiceExtensionAbility with the account ID specified. This API uses an **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -547,7 +547,7 @@ Starts a ServiceExtensionAbility with the account ID specified. This API uses a **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -618,7 +618,7 @@ Stops a ServiceExtensionAbility in the same application. This API uses an asynch **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -687,7 +687,7 @@ Stops a ServiceExtensionAbility in the same application. This API uses a promise **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -759,7 +759,7 @@ Stops a ServiceExtensionAbility with the account ID specified in the same applic **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -834,7 +834,7 @@ Stops a ServiceExtensionAbility with the account ID specified in the same applic **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -900,6 +900,8 @@ connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options Connects this ability to a ServiceExtensionAbility, with the account ID specified. This API can be called only by the main thread. +Currently, this API takes effect only on mobile phones and tablets. + > **NOTE** > > For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). @@ -909,7 +911,7 @@ Connects this ability to a ServiceExtensionAbility, with the account ID specifie **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -1000,7 +1002,7 @@ Starts an ability with want and the account ID specified. This API uses an async **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -1094,7 +1096,7 @@ Starts an ability with want, the account ID, and start options specified. This A **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -1192,7 +1194,7 @@ Starts an ability with want, the account ID, and start options specified. This A **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -1281,7 +1283,7 @@ Sets an icon for this ability in the mission. This API uses an asynchronous call **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -1337,7 +1339,7 @@ Sets an icon for this ability in the mission. This API uses a promise to return **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -1405,7 +1407,7 @@ Starts an ability. If the ability has multiple instances, the latest instance is **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -1485,7 +1487,7 @@ Starts an ability with the start options specified. If the ability has multiple **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -1568,7 +1570,7 @@ Starts an ability. If the ability has multiple instances, the latest instance is **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -1656,7 +1658,7 @@ Observe the following when using this API: **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -1751,7 +1753,7 @@ Starts an ability with the caller information specified. The caller information **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -1826,9 +1828,10 @@ Starts an ability with the caller information and start options specified. The c > **NOTE** > > For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -1908,7 +1911,7 @@ Starts an ability with the caller information specified. The caller information **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -2074,6 +2077,7 @@ Before starting the UIExtensionAbility, ensure that the foreground application h > **NOTE** > > For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + **System capability**: SystemCapability.Ability.AbilityRuntime.Core **System API**: This is a system API. diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md index 7c90a2115a88baab4611f1d0d49f249437378354..d99694324bc505fa951536b18d58d22c41daac91 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-uiAbilityContext.md @@ -64,7 +64,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 16000006 | Cross-user operations are not allowed. | | 16000008 | The crowdtesting application expires. | | 16000009 | An ability cannot be started or stopped in Wukong mode. | -| 16000010 | The call with the continuation flag is forbidden. | +| 16000010 | The call with the continuation and prepare continuation flag is forbidden. | | 16000011 | The context does not exist. | | 16000012 | The application is controlled. | | 16000013 | The application is controlled by EDM. | @@ -80,8 +80,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 16000077 | The number of app instances reaches the limit. | | 16000078 | The multi-instance is not supported. | | 16000079 | The APP_INSTANCE_KEY cannot be specified. | -| 16000080 | Creating an instance is not supported. | -| 16000082 | The UIAbility is being started. | +| 16000080 | Creating a new instance is not supported. | | 16200001 | The caller has been released. | **Example** @@ -172,8 +171,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 16000077 | The number of app instances reaches the limit. | | 16000078 | The multi-instance is not supported. | | 16000079 | The APP_INSTANCE_KEY cannot be specified. | -| 16000080 | Creating an instance is not supported. | -| 16000082 | The UIAbility is being started. | +| 16000080 | Creating a new instance is not supported. | | 16200001 | The caller has been released. | **Example** @@ -256,7 +254,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 16000006 | Cross-user operations are not allowed. | | 16000008 | The crowdtesting application expires. | | 16000009 | An ability cannot be started or stopped in Wukong mode. | -| 16000010 | The call with the continuation flag is forbidden. | +| 16000010 | The call with the continuation and prepare continuation flag is forbidden. | | 16000011 | The context does not exist. | | 16000012 | The application is controlled. | | 16000013 | The application is controlled by EDM. | @@ -275,8 +273,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 16000077 | The number of app instances reaches the limit. | | 16000078 | The multi-instance is not supported. | | 16000079 | The APP_INSTANCE_KEY cannot be specified. | -| 16000080 | Creating an instance is not supported. | -| 16000082 | The UIAbility is being started. | +| 16000080 | Creating a new instance is not supported. | | 16200001 | The caller has been released. | **Example** @@ -356,7 +353,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 16000006 | Cross-user operations are not allowed. | | 16000008 | The crowdtesting application expires. | | 16000009 | An ability cannot be started or stopped in Wukong mode. | -| 16000010 | The call with the continuation flag is forbidden. | +| 16000010 | The call with the continuation and prepare continuation flag is forbidden. | | 16000011 | The context does not exist. | | 16000012 | The application is controlled. | | 16000013 | The application is controlled by EDM. | @@ -372,8 +369,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 16000077 | The number of app instances reaches the limit. | | 16000078 | The multi-instance is not supported. | | 16000079 | The APP_INSTANCE_KEY cannot be specified. | -| 16000080 | Creating an instance is not supported. | -| 16000082 | The UIAbility is being started. | +| 16000080 | Creating a new instance is not supported. | | 16200001 | The caller has been released. | **Example** @@ -466,8 +462,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 16000077 | The number of app instances reaches the limit. | | 16000078 | The multi-instance is not supported. | | 16000079 | The APP_INSTANCE_KEY cannot be specified. | -| 16000080 | Creating an instance is not supported. | -| 16000082 | The UIAbility is being started. | +| 16000080 | Creating a new instance is not supported. | | 16200001 | The caller has been released. | **Example** @@ -556,7 +551,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 16000006 | Cross-user operations are not allowed. | | 16000008 | The crowdtesting application expires. | | 16000009 | An ability cannot be started or stopped in Wukong mode. | -| 16000010 | The call with the continuation flag is forbidden. | +| 16000010 | The call with the continuation and prepare continuation flag is forbidden. | | 16000011 | The context does not exist. | | 16000012 | The application is controlled. | | 16000013 | The application is controlled by EDM. | @@ -572,8 +567,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 16000077 | The number of app instances reaches the limit. | | 16000078 | The multi-instance is not supported. | | 16000079 | The APP_INSTANCE_KEY cannot be specified. | -| 16000080 | Creating an instance is not supported. | -| 16000082 | The UIAbility is being started. | +| 16000080 | Creating a new instance is not supported. | | 16200001 | The caller has been released. | **Example** @@ -1098,13 +1092,17 @@ export default class EntryAbility extends UIAbility { startAbilityByCall(want: Want): Promise<Caller> -Starts an ability in the foreground or background in the cross-device scenario and obtains the caller object for communicating with the ability. This API uses a promise to return the result. It can be called only by the main thread. +Starts an ability in the foreground or background and obtains the caller object for communicating with the ability. This API uses a promise to return the result. It can be called only by the main thread. This API cannot be used to start the UIAbility with the launch type set to [specified](../../application-models/uiability-launch-type.md#specified). > **NOTE** > -> For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). +> - For a successful launch in cross-device scenarios, the caller and target must be the same application and have the ohos.permission.DISTRIBUTED_DATASYNC permission. +> +> - For a successful launch in the same device scenario, the caller and target must be different applications and have the ohos.permission.ABILITY_BACKGROUND_COMMUNICATION permission (available only for system applications). +> +> - If the caller is running in the background, the ohos.permission.START_ABILITIES_FROM_BACKGROUND permission is required (available only for system applications). For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -1151,7 +1149,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 16000077 | The number of app instances reaches the limit. | | 16000078 | The multi-instance is not supported. | | 16000079 | The APP_INSTANCE_KEY cannot be specified. | -| 16000080 | Creating an instance is not supported. | +| 16000080 | Creating a new instance is not supported. | **Example** @@ -1236,7 +1234,7 @@ export default class EntryAbility extends UIAbility { setMissionLabel(label: string, callback: AsyncCallback<void>): void -Sets a label for this ability in the mission. This API uses an asynchronous callback to return the result. +Sets a label for this UIAbility in the mission. This API uses an asynchronous callback to return the result. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -1278,7 +1276,7 @@ export default class EntryAbility extends UIAbility { setMissionLabel(label: string): Promise<void> -Sets a label for this ability in the mission. This API uses a promise to return the result. +Sets a label for this UIAbility in the mission. This API uses a promise to return the result. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -1329,7 +1327,7 @@ export default class EntryAbility extends UIAbility { setMissionContinueState(state: AbilityConstant.ContinueState, callback: AsyncCallback<void>): void -Sets the mission continuation state of this ability. This API uses an asynchronous callback to return the result. +Sets the mission continuation state of this UIAbility. This API uses an asynchronous callback to return the result. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -1371,7 +1369,7 @@ export default class EntryAbility extends UIAbility { setMissionContinueState(state: AbilityConstant.ContinueState): Promise<void> -Sets the mission continuation state of this ability. This API uses a promise to return the result. +Sets the mission continuation state of this UIAbility. This API uses a promise to return the result. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -1526,7 +1524,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 16000006 | Cross-user operations are not allowed. | | 16000008 | The crowdtesting application expires. | | 16000009 | An ability cannot be started or stopped in Wukong mode. | -| 16000010 | The call with the continuation flag is forbidden. | +| 16000010 | The call with the continuation and prepare continuation flag is forbidden. | | 16000011 | The context does not exist. | | 16000012 | The application is controlled. | | 16000013 | The application is controlled by EDM. | @@ -1609,7 +1607,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 16000006 | Cross-user operations are not allowed. | | 16000008 | The crowdtesting application expires. | | 16000009 | An ability cannot be started or stopped in Wukong mode. | -| 16000010 | The call with the continuation flag is forbidden. | +| 16000010 | The call with the continuation and prepare continuation flag is forbidden. | | 16000011 | The context does not exist. | | 16000012 | The application is controlled. | | 16000013 | The application is controlled by EDM. | @@ -1655,7 +1653,7 @@ export default class EntryAbility extends UIAbility { reportDrawnCompleted(callback: AsyncCallback\): void -Reports an event indicating that page loading is complete (**loadContent()** is successfully called). This API uses an asynchronous callback to return the result. +Reports an event indicating that page loading is complete (**loadContent** is successfully called). This API uses an asynchronous callback to return the result. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -1908,7 +1906,8 @@ export default class EntryAbility extends UIAbility { }; let options: StartOptions = { displayId: 0, - processMode: contextConstant.ProcessMode.NEW_PROCESS_ATTACH_TO_STATUS_BAR_ITEM + processMode: contextConstant.ProcessMode.NEW_PROCESS_ATTACH_TO_STATUS_BAR_ITEM, + startupVisibility: contextConstant.StartupVisibility.STARTUP_SHOW }; try { @@ -2005,7 +2004,8 @@ export default class EntryAbility extends UIAbility { }; let options: StartOptions = { displayId: 0, - processMode: contextConstant.ProcessMode.NEW_PROCESS_ATTACH_TO_STATUS_BAR_ITEM + processMode: contextConstant.ProcessMode.NEW_PROCESS_ATTACH_TO_STATUS_BAR_ITEM, + startupVisibility: contextConstant.StartupVisibility.STARTUP_HIDE }; try { @@ -2230,7 +2230,6 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 16000019 | No matching ability is found. | | 16200001 | The caller has been released. | | 16000053 | The ability is not on the top of the UI. | -| 16000082 | The UIAbility is being started. | **Example** @@ -2286,7 +2285,7 @@ struct Index { backToCallerAbilityWithResult(abilityResult: AbilityResult, requestCode: string): Promise<void> -Returns the startup result to the caller of [startAbilityForResult](#uiabilitycontextstartabilityforresult) or [openLink](#uiabilitycontextopenlink12). Different from [terminateSelfWithResult](#uiabilitycontextterminateselfwithresult), this API does not destroy the current ability (target ability) when it returns the result. +Returns the startup result to the caller of [startAbilityForResult](#uiabilitycontextstartabilityforresult) or [openLink](#uiabilitycontextopenlink12). Different from [terminateSelfWithResult](#uiabilitycontextterminateselfwithresult), this API does not destroy the current ability (target ability) when it returns the result. This API uses a promise to return the result. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -2431,9 +2430,11 @@ export default class EntryAbility extends UIAbility { ## UIAbilityContext.setRestoreEnabled14+ -setRestoreEnabled(enabled: boolean): Promise\ +setRestoreEnabled(enabled: boolean): void + +Sets whether to enable backup and restore for this UIAbility. -Sets whether to enable backup and restore for this UIAbility. This API uses a promise to return the result. +**Atomic service API**: This API can be used in atomic services since API version 14. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -2443,12 +2444,6 @@ Sets whether to enable backup and restore for this UIAbility. This API uses a pr | -------- | -------- | -------- | -------- | | enabled | boolean | Yes| Whether to enable backup and restore. The value **true** means to enable backup and restore, and **false** means the opposite.| -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<void> | Promise that returns no value.| - **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). @@ -2478,25 +2473,25 @@ export default class EntryAbility extends UIAbility { } ``` -## UIAbilityContext.startUIServiceExtensionAbility13+ +## UIAbilityContext.startUIServiceExtensionAbility14+ startUIServiceExtensionAbility(want: Want): Promise<void> -Starts a UIServiceExtensionAbility. +Starts a UIServiceExtensionAbility. This API uses a promise to return the result. > **NOTE** > > For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). -**Atomic service API**: This API can be used in atomic services since API version 13. +**Atomic service API**: This API can be used in atomic services since API version 14. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** -| Name | Type | Read Only| Optional| Description | -| -------- | --------------------------------------- | ---- | ---- | ------------------------ | -| want | [Want](js-apis-app-ability-want.md) | Yes | No| Want information required for startup.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ------------------------ | +| want | [Want](js-apis-app-ability-want.md) | Yes| Want information required for startup.| **Return value** @@ -2512,16 +2507,16 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | -------- | ----------------------------------------------------------------------------------------------------------- | | 201 | The application does not have permission to call the interface. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | -| 801 | The Ability is not supported. | +| 801 | Capability not supported. | | 16000001 | The specified ability does not exist. | | 16000002 | Incorrect ability type. | | 16000004 | Failed to start the invisible ability. | | 16000005 | The specified process does not have the permission. | -| 16000006 | Cross-user operations are not allowed. | | 16000008 | The crowdtesting application expires. | | 16000011 | The context does not exist. | | 16000012 | The application is controlled. | | 16000013 | The application is controlled by EDM. | +| 16000019 | No matching ability is found. | | 16000050 | Internal error. | | 16200001 | The caller has been released. | @@ -2563,29 +2558,27 @@ struct Index { } ``` -## UIAbilityContext.connectUIServiceExtensionAbility13+ +## UIAbilityContext.connectUIServiceExtensionAbility14+ connectUIServiceExtensionAbility(want: Want, callback: UIServiceExtensionConnectCallback) : Promise<UIServiceProxy> Connects to a UIServiceExtensionAbility. This API uses a promise to return the result. - - > **NOTE** > > For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). > -**Atomic service API**: This API can be used in atomic services since API version 13. +**Atomic service API**: This API can be used in atomic services since API version 14. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** -| Name| Type| Read Only| Optional| Description | -| ------ | ---- | ---- | -------------------- | ---- | -| want |[Want](js-apis-app-ability-want.md) | Yes | No| Want information required for connection.| -| callback | [UIServiceExtensionConnectCallback](js-apis-inner-application-uiServiceExtensionconnectcallback.md) | No| Yes| Callback for connecting to the UIServiceExtensionAbility.| +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ---- | +| want |[Want](js-apis-app-ability-want.md) | Yes | Want information required for connection.| +| callback | [UIServiceExtensionConnectCallback](js-apis-inner-application-uiServiceExtensionconnectcallback.md) | Yes | Callback for connecting to the UIServiceExtensionAbility.| **Return value** @@ -2599,23 +2592,23 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ----------------------------------------------------------------------------------- | -| 201 | The application does not have permission to call the interface. | +| 201 | The application does not have permission to call the interface. | +| 801 | Capability not supported. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 16000001 | The specified ability does not exist. | | 16000002 | Incorrect ability type. | -| 16000004 | Failed to start the invisible ability. | +| 16000004 | Failed to start the invisible ability. | | 16000005 | The specified process does not have the permission. | -| 16000006 | Cross-user operations are not allowed. | | 16000008 | The crowdtesting application expires. | | 16000011 | The context does not exist. | +| 16000013 | The EDM prohibits the application from launching. | | 16000050 | Internal error. | -| 16000053 | The ability is not on the top of the | | 16000055 | Installation-free timed out. | **Example** ```ts -import { common } from '@kit.AbilityKit'; +import { common, Want } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; const TAG: string = '[Extension] '; @@ -2678,28 +2671,26 @@ struct UIServiceExtensionAbility { } ``` -## UIAbilityContext.disconnectUIServiceExtensionAbility13+ +## UIAbilityContext.disconnectUIServiceExtensionAbility14+ disconnectUIServiceExtensionAbility(proxy: UIServiceProxy): Promise<void> -Disconnects from a UIServiceExtensionAbility. - +Disconnects from a UIServiceExtensionAbility. This API uses a promise to return the result. > **NOTE** > > For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). > - -**Atomic service API**: This API can be used in atomic services since API version 13. +**Atomic service API**: This API can be used in atomic services since API version 14. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** -| Name| Type| Read Only| Optional| Description | -| ------ | ---- | ---- | -------------------- | -------------------- | -| proxy | [UIServiceProxy](js-apis-inner-application-uiserviceproxy.md) | Yes |No| Proxy returned after [connectUIServiceExtensionAbility](#uiabilitycontextconnectuiserviceextensionability13) is called.| +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | -------------------- | +| proxy | [UIServiceProxy](js-apis-inner-application-uiserviceproxy.md) | Yes| Proxy returned after [connectUIServiceExtensionAbility](#uiabilitycontextconnectuiserviceextensionability13) is called.| **Return value** @@ -2775,3 +2766,128 @@ struct UIServiceExtensionAbility { } } ``` + +## UIAbilityContext.setAbilityInstanceInfo15+ + +setAbilityInstanceInfo(label: string, icon: image.PixelMap) : Promise<void> + +Sets the icon and label for this UIAbility. The icon and label can be displayed in Recents and the shortcut bar. This API uses a promise to return the result. + + +> **NOTE** +> +> This API is available only for 2-in-1 devices. + +**Required permissions**: ohos.permission.SET_ABILITY_INSTANCE_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------------------------------------------------------- | ---- | -------------------------------------------------- | +| label |string | Yes | Label. The label cannot be an empty string, and can contain a maximum of 1024 bytes. | +| icon | [image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | Yes | Icon. The recommended icon size is 512 px * 512 px. | + +**Return value** + +| Type | Description | +| ------------------- | -------------------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). + +| ID| Error Message | +| -------- | ----------------------------------------------------------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | +| 801 | Capability not supported. | +| 16000011 | The context does not exist. | +| 16000050 | Internal error. | + +**Example** + +```ts +import { UIAbility } from '@kit.AbilityKit'; +import { image } from '@kit.ImageKit'; +import { BusinessError } from '@kit.BasicServicesKit'; +import { window } from '@kit.ArkUI'; + +export default class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage): void { + windowStage.loadContent('pages/Index', async (err, data) => { + if (err.code) { + console.error(`loadContent failed, code is ${err.code}`); + return; + } + + let newLabel: string = 'instance label'; + let color = new ArrayBuffer(0); + let imagePixelMap: image.PixelMap = await image.createPixelMap(color, { + size: { + height: 100, + width: 100 + } + }); + this.context.setAbilityInstanceInfo(newLabel, imagePixelMap) + .then(() => { + console.info('setAbilityInstanceInfo success'); + }).catch((err: BusinessError) => { + console.error(`setAbilityInstanceInfo failed, code is ${err.code}, message is ${err.message}`); + }); + }); + } +} +``` + +## UIAbilityContext.setColorMode18+ + +setColorMode(colorMode: ConfigurationConstant.ColorMode): void + +Sets the color mode for this UIAbility. Before calling this API, ensure that the page corresponding to the UIAbility has been loaded. This API can be called only by the main thread. + +> **NOTE** +> - After this API is called, a new resource manager object is created. If a resource manager was previously cached, it should be updated accordingly. +> - The priority of the color mode is as follows: UIAbility color mode > Application color mode (set via [ApplicationContext.setColorMode](js-apis-inner-application-applicationContext.md)) > System color mode. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------- | ---- | -------------------- | +| colorMode | [ConfigurationConstant.ColorMode](js-apis-app-ability-configurationConstant.md) | Yes | Color mode. The options are as follows:
- **COLOR_MODE_DARK**: dark mode.
- **COLOR_MODE_LIGHT**: light mode.
- **COLOR_MODE_NOT_SET**: not set (following the system or application).| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). + +| ID| Error Message| +| ------- | -------- | +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | +| 16000011 | The context does not exist. | + +**Example** + +```ts +import { UIAbility, ConfigurationConstant } from '@kit.AbilityKit'; +import { hilog } from '@kit.PerformanceAnalysisKit'; +import { window } from '@kit.ArkUI'; + +export default class MyAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + windowStage.loadContent('pages/Index', (err, data) => { + if (err.code) { + hilog.error(0x0000, 'testTag', 'Failed to load the content.'); + return; + } + let uiAbilityContext = this.context; + uiAbilityContext.setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_DARK); + }); + } +} +``` diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-uiExtensionContext-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-uiExtensionContext-sys.md index 329f4ee0f3fe0bf6cd786f14a89dc773c182bc9a..a042a0373b507844b278f2d983210d6b6dfa1e97 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-uiExtensionContext-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-uiExtensionContext-sys.md @@ -83,3 +83,227 @@ export default class UIExtension extends UIExtensionAbility { } } ``` + +## UIExtensionContext.startServiceExtensionAbility18+ + +startServiceExtensionAbility(want: Want): Promise\ + +Starts a ServiceExtensionAbility. This API uses a promise to return the result. + +**Model restriction**: This API can be used only in the stage model. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------ | ------ | ------ | ------ | +| want | [Want](js-apis-app-ability-want.md) | Yes| Want information for starting the ServiceExtensionAbility.| + +**Return value** + +| Type| Description| +| ------ | ------ | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). + +| ID| Error Message| +| ------ | ------ | +| 201 | The application does not have permission to call the interface. | +| 202 | The application is not system-app, can not use system-api. | +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Failed to start the invisible ability. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000011 | The context does not exist. | +| 16000012 | The application is controlled. | +| 16000013 | The application is controlled by EDM. | +| 16000019 | No matching ability is found. | +| 16000050 | Internal error. | +| 16200001 | The caller has been released. | + +**Example** + +```ts +import { UIExtensionAbility, Want } from '@kit.AbilityKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +export default class UIExtAbility extends UIExtensionAbility { + onForeground() { + let want: Want = { + bundleName: 'com.example.myapplication', + moduleName: 'entry', + abilityName: 'ServiceExtensionAbility' + }; + + try { + this.context.startServiceExtensionAbility(want) + .then(() => { + // Carry out normal service processing. + console.info('startServiceExtensionAbility succeed'); + }) + .catch((err: BusinessError) => { + // Process service logic errors. + console.error(`startServiceExtensionAbility failed, code is ${err.code}, message is ${err.message}`); + }); + } catch (err) { + // Process input parameter errors. + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`startServiceExtensionAbility failed, code is ${code}, message is ${message}`); + } + } +} +``` + +## UIExtensionContext.startServiceExtensionAbilityWithAccount18+ + +startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\ + +Starts a ServiceExtensionAbility under a specified system account. This API uses a promise to return the result. + +> **NOTE** +> +> For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). +> +> Permission verification is not required when **accountId** specifies the current user. + +**Model restriction**: This API can be used only in the stage model. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------ | ------ | ------ | ------ | +| want | [Want](js-apis-app-ability-want.md) | Yes| Want information for starting the ServiceExtensionAbility.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](../apis-basic-services-kit/js-apis-osAccount.md#getosaccountcount9).| + +**Return value** + +| Type| Description| +| ------ | ------ | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). + +| ID| Error Message| +| ------ | ------ | +| 201 | The application does not have permission to call the interface. | +| 202 | The application is not system-app, can not use system-api. | +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | +| 16000001 | The specified ability does not exist. | +| 16000002 | Incorrect ability type. | +| 16000004 | Failed to start the invisible ability. | +| 16000005 | The specified process does not have the permission. | +| 16000006 | Cross-user operations are not allowed. | +| 16000008 | The crowdtesting application expires. | +| 16000011 | The context does not exist. | +| 16000012 | The application is controlled. | +| 16000013 | The application is controlled by EDM. | +| 16000019 | No matching ability is found. | +| 16000050 | Internal error. | +| 16200001 | The caller has been released. | + +**Example** + +```ts +import { UIExtensionAbility, Want } from '@kit.AbilityKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +export default class UIExtAbility extends UIExtensionAbility { + onForeground() { + let want: Want = { + bundleName: 'com.example.myapplication', + moduleName: 'entry', + abilityName: 'ServiceExtensionAbility' + }; + let accountId = 100; + + try { + this.context.startServiceExtensionAbilityWithAccount(want, accountId) + .then(() => { + // Carry out normal service processing. + console.info('startServiceExtensionAbilityWithAccount succeed'); + }) + .catch((err: BusinessError) => { + // Process service logic errors. + console.error(`startServiceExtensionAbilityWithAccount failed, code is ${err.code}, message is ${err.message}`); + }); + } catch (err) { + // Process input parameter errors. + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`startServiceExtensionAbilityWithAccount failed, code is ${code}, message is ${message}`); + } + } +} +``` + +## UIExtensionContext.setHostPageOverlayForbidden15+ + +setHostPageOverlayForbidden(isForbidden: boolean) : void + +Sets whether the page started by the [UIExtensionAbility](../apis-ability-kit/js-apis-app-ability-uiExtensionAbility.md) can be overlaid by the page of the user. + +> **NOTE** +> +> For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). +> +> This API must be called before a window is created. You are advised to call it within the [onCreate](../apis-ability-kit/js-apis-app-ability-uiExtensionAbility.md#uiextensionabilityoncreate) lifecycle of the [UIExtensionAbility](../apis-ability-kit/js-apis-app-ability-uiExtensionAbility.md). + +**Model restriction**: This API can be used only in the stage model. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------ | ------ | ------ | ------ | +| isForbidden | boolean | Yes| Whether the page started by the [UIExtensionAbility](../apis-ability-kit/js-apis-app-ability-uiExtensionAbility.md) can be overlaid by the page of the user. The value **true** means that the page can be overlaid, and **false** means the opposite.| + + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| ------ | ------ | +| 202 | The application is not system-app, can not use system-api. | +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | + +**Example** + +```ts +import { UIExtensionAbility } from '@kit.AbilityKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +export default class UIExtAbility extends UIExtensionAbility { + OnCreate() { + try { + this.context.setHostPageOverlayForbidden(true) + } catch (err) { + // Process input parameter errors. + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error(`setHostPageOverlayForbidden failed, code is ${code}, message is ${message}`); + } + } +} +``` diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-uiExtensionContext.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-uiExtensionContext.md index 19068111fdcfa3b2a4bf41bda861228278e308d8..75706d2075cd2be1c2e1acdb8647ee25dc23aa43 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-uiExtensionContext.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-uiExtensionContext.md @@ -48,7 +48,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 16000006 | Cross-user operations are not allowed. | | 16000008 | The crowdtesting application expires. | | 16000009 | An ability cannot be started or stopped in Wukong mode. | -| 16000010 | The call with the continuation flag is forbidden. | +| 16000010 | The call with the continuation and prepare continuation flag is forbidden. | | 16000011 | The context does not exist. | | 16000012 | The application is controlled. | | 16000013 | The application is controlled by EDM. | @@ -66,8 +66,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 16000077 | The number of app instances reaches the limit. | | 16000078 | The multi-instance is not supported. | | 16000079 | The APP_INSTANCE_KEY cannot be specified. | -| 16000080 | Creating an instance is not supported. | -| 16000082 | The UIAbility is being started. | +| 16000080 | Creating a new instance is not supported. | | 16200001 | The caller has been released. | **Example** @@ -155,8 +154,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 16000077 | The number of app instances reaches the limit. | | 16000078 | The multi-instance is not supported. | | 16000079 | The APP_INSTANCE_KEY cannot be specified. | -| 16000080 | Creating an instance is not supported. | -| 16000082 | The UIAbility is being started. | +| 16000080 | Creating a new instance is not supported. | | 16200001 | The caller has been released. | **Example** @@ -236,7 +234,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 16000006 | Cross-user operations are not allowed. | | 16000008 | The crowdtesting application expires. | | 16000009 | An ability cannot be started or stopped in Wukong mode. | -| 16000010 | The call with the continuation flag is forbidden. | +| 16000010 | The call with the continuation and prepare continuation flag is forbidden. | | 16000011 | The context does not exist. | | 16000012 | The application is controlled. | | 16000013 | The application is controlled by EDM. | @@ -254,8 +252,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 16000077 | The number of app instances reaches the limit. | | 16000078 | The multi-instance is not supported. | | 16000079 | The APP_INSTANCE_KEY cannot be specified. | -| 16000080 | Creating an instance is not supported. | -| 16000082 | The UIAbility is being started. | +| 16000080 | Creating a new instance is not supported. | | 16200001 | The caller has been released. | **Example** @@ -331,7 +328,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 16000006 | Cross-user operations are not allowed. | | 16000008 | The crowdtesting application expires. | | 16000009 | An ability cannot be started or stopped in Wukong mode. | -| 16000010 | The call with the continuation flag is forbidden. | +| 16000010 | The call with the continuation and prepare continuation flag is forbidden. | | 16000011 | The context does not exist. | | 16000012 | The application is controlled. | | 16000013 | The application is controlled by EDM. | @@ -349,8 +346,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 16000077 | The number of app instances reaches the limit. | | 16000078 | The multi-instance is not supported. | | 16000079 | The APP_INSTANCE_KEY cannot be specified. | -| 16000080 | Creating an instance is not supported. | -| 16000082 | The UIAbility is being started. | +| 16000080 | Creating a new instance is not supported. | | 16200001 | The caller has been released. | **Example** @@ -440,8 +436,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 16000077 | The number of app instances reaches the limit. | | 16000078 | The multi-instance is not supported. | | 16000079 | The APP_INSTANCE_KEY cannot be specified. | -| 16000080 | Creating an instance is not supported. | -| 16000082 | The UIAbility is being started. | +| 16000080 | Creating a new instance is not supported. | | 16200001 | The caller has been released. | **Example** @@ -525,7 +520,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 16000006 | Cross-user operations are not allowed. | | 16000008 | The crowdtesting application expires. | | 16000009 | An ability cannot be started or stopped in Wukong mode. | -| 16000010 | The call with the continuation flag is forbidden. | +| 16000010 | The call with the continuation and prepare continuation flag is forbidden. | | 16000011 | The context does not exist. | | 16000012 | The application is controlled. | | 16000013 | The application is controlled by EDM. | @@ -543,8 +538,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 16000077 | The number of app instances reaches the limit. | | 16000078 | The multi-instance is not supported. | | 16000079 | The APP_INSTANCE_KEY cannot be specified. | -| 16000080 | Creating an instance is not supported. | -| 16000082 | The UIAbility is being started. | +| 16000080 | Creating a new instance is not supported. | | 16200001 | The caller has been released. | **Example** @@ -1071,6 +1065,7 @@ export default class UIExtAbility extends UIExtensionAbility { ``` ## UIExtensionContext.openAtomicService12+ + openAtomicService(appId: string, options?: AtomicServiceOptions): Promise<AbilityResult> Starts an [EmbeddableUIAbility](js-apis-app-ability-embeddableUIAbility.md) in jump-out mode and returns the result. This API uses a promise to return the result. @@ -1150,6 +1145,7 @@ export default class EntryAbility extends UIExtensionAbility { ``` ## UIExtensionContext.openLink12+ + openLink(link:string, options?: OpenLinkOptions, callback?: AsyncCallback<AbilityResult>): Promise<void> Starts a UIAbility through App Linking. This API uses a promise to return the result. @@ -1197,7 +1193,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 16000006 | Cross-user operations are not allowed. | | 16000008 | The crowdtesting application expires. | | 16000009 | An ability cannot be started or stopped in Wukong mode. | -| 16000010 | The call with the continuation flag is forbidden. | +| 16000010 | The call with the continuation flag is forbidden. | | 16000011 | The context does not exist. | | 16000012 | The application is controlled. | | 16000013 | The application is controlled by EDM. | @@ -1205,7 +1201,6 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 16000069 | The extension cannot start the third party application. | | 16200001 | The caller has been released. | | 16000053 | The ability is not on the top of the UI. | -| 16000082 | The UIAbility is being started. | **Example** @@ -1274,7 +1269,8 @@ export default class UIExtAbility extends UIExtensionAbility { } ``` -## UIExtensionContext.startUIServiceExtensionAbility13+ +## UIExtensionContext.startUIServiceExtensionAbility14+ + startUIServiceExtensionAbility(want: Want): Promise<void> Starts a UIServiceExtensionAbility. @@ -1284,14 +1280,13 @@ Starts a UIServiceExtensionAbility. > For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). > - **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** -| Name | Type |Read Only| Optional| Description | -| -------- | ---------------------------------------------------------------------------- | ---- | ---- |------------------------- | -| want | [Want](js-apis-app-ability-want.md) | Yes| No | Want information for starting the UIServiceExtensionAbility.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------------------------------- | --- |------------------------- | +| want | [Want](js-apis-app-ability-want.md) | Yes| Want information for starting the UIServiceExtensionAbility.| **Return value** @@ -1307,16 +1302,16 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | -------- | ----------------------------------------------------------------------------------------------------------- | | 201 | The application does not have permission to call the interface. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | -| 801 | The Ability is not supported. | +| 801 | Capability not supported. | | 16000001 | The specified ability does not exist. | | 16000002 | Incorrect ability type. | -| 16000004 | Failed to start the invisible ability. | +| 16000004 | Failed to start the invisible ability. | | 16000005 | The specified process does not have the permission. | -| 16000006 | Cross-user operations are not allowed. | | 16000008 | The crowdtesting application expires. | | 16000011 | The context does not exist. | | 16000012 | The application is controlled. | -| 16000013 | The application is controlled by EDM. | +| 16000013 | The EDM prohibits the application from launching. | +| 16000019 | No matching ability is found. | | 16000050 | Internal error. | | 16200001 | The caller has been released. | @@ -1358,7 +1353,8 @@ struct Index { } ``` -## UIExtensionContext.connectUIServiceExtensionAbility13+ +## UIExtensionContext.connectUIServiceExtensionAbility14+ + connectUIServiceExtensionAbility(want: Want, callback: UIServiceExtensionConnectCallback) : Promise<UIServiceProxy> Connects to a UIServiceExtensionAbility. @@ -1368,15 +1364,14 @@ Connects to a UIServiceExtensionAbility. > For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). > - **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** -| Name | Type | Read Only| Optional| Description | -| -------------------- | -------------------------------- | ---- | -------------------- | -------------------- | -| want | Want | Yes | No| Want information used for connection.| -| callback | [UIServiceExtensionConnectCallback](js-apis-inner-application-uiServiceExtensionconnectcallback.md) | Yes|No | Callback for connecting to the UIServiceExtensionAbility. | +| Name | Type | Mandatory| Description | +| -------------------- | -------------------------------- | ---- | -------------------- | +| want | Want | Yes| Want information used for connection.| +| callback | [UIServiceExtensionConnectCallback](js-apis-inner-application-uiServiceExtensionconnectcallback.md) | Yes| Callback for connecting to the UIServiceExtensionAbility. | **Return value** @@ -1392,15 +1387,15 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | -------- | ---------------------------------- | | 201 | The application does not have permission to call the interface. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | -| 16000001 | The specified ability does not | +| 801 | Capability not supported. | +| 16000001 | The specified ability does not exist. | | 16000002 | Incorrect ability type. | -| 16000004 | Failed to start the invisible ability. | +| 16000004 | Failed to start the invisible ability. | | 16000005 | The specified process does not have the permission. | -| 16000006 | Cross-user operations are not allowed. | | 16000008 | The crowdtesting application expires. | | 16000011 | The context does not exist. | +| 16000013 | The EDM prohibits the application from launching. | | 16000050 | Internal error. | -| 16000053 | The ability is not on the top of the UI. | | 16000055 | Installation-free timed out. | **Example** @@ -1448,19 +1443,19 @@ struct Page_UIServiceExtensionAbility { } ``` -## UIExtensionContext.disconnectUIServiceExtensionAbility13+ +## UIExtensionContext.disconnectUIServiceExtensionAbility14+ + disconnectUIServiceExtensionAbility(proxy: UIServiceProxy): Promise<void> Disconnects a UIServiceExtensionAbility. - **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** -| Name | Type | Read Only| Optional| Description | -| -------------------- | -------------------------------- | ---- | -------------------- | -------------------- | -| proxy | [UIServiceProxy](js-apis-inner-application-uiserviceproxy.md) | Yes| No | Proxy used returned by calling [connectUIServiceExtensionAbility](#uiextensioncontextconnectuiserviceextensionability13).| +| Name | Type | Mandatory| Description | +| -------------------- | -------------------------------- | ---- | -------------------- | +| proxy | [UIServiceProxy](js-apis-inner-application-uiserviceproxy.md) | Yes | Proxy used returned by calling [connectUIServiceExtensionAbility](#uiextensioncontextconnectuiserviceextensionability13).| **Return value** @@ -1507,3 +1502,43 @@ struct Page_UIServiceExtensionAbility { } } ``` + +## UIExtensionContext.setColorMode18+ + +setColorMode(colorMode: ConfigurationConstant.ColorMode): void + +Sets the color mode for this UIExtensionAbility. Before calling this API, ensure that the page corresponding to the UIExtensionContext has been loaded. This API can be called only by the main thread. + +> **NOTE** +> - After this API is called, a new resource manager object is created. If a resource manager was previously cached, it should be updated accordingly. +> - The priority of the color mode is as follows: UIExtensionAbility color mode > Application color mode (set via [ApplicationContext.setColorMode](js-apis-inner-application-applicationContext.md)) > System color mode. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------- | ---- | -------------------- | +| colorMode | [ConfigurationConstant.ColorMode](js-apis-app-ability-configurationConstant.md#colormode) | Yes | Color mode. The options are as follows:
- **COLOR_MODE_DARK**: dark mode.
- **COLOR_MODE_LIGHT**: light mode.
- **COLOR_MODE_NOT_SET**: not set (following the system or application).| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). + +| ID| Error Message| +| ------- | -------- | +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | +| 16000011 | The context does not exist. | + +**Example** + +```ts +import { UIExtensionAbility, ConfigurationConstant } from '@kit.AbilityKit'; + +export default class MyAbility extends UIExtensionAbility { + onForeground() { + let uiExtensionContext = this.context; + uiExtensionContext.setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_DARK); + } +} +``` diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-uiServiceExtensionconnectcallback.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-uiServiceExtensionconnectcallback.md index cbbcbd9202dad5a2e7c63d94d1b54d1ab847bab2..c99a350937f42c8e40fe2a7f29f4a098794e83e7 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-uiServiceExtensionconnectcallback.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-uiServiceExtensionconnectcallback.md @@ -5,7 +5,7 @@ UIServiceExtensionConnectCallback provides callbacks for the connection to a UIS > **NOTE** > -> - The initial APIs of this module are supported since API version 13. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The initial APIs of this module are supported since API version 14. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The APIs of this module can be used only in the stage model. > - The APIs of this module must be used in the main thread, but not in sub-threads such as Worker and TaskPool. @@ -26,20 +26,20 @@ Called to receive data when a connection to the UIServiceExtensionAbility is est > For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). > +**Atomic service API**: This API can be used in atomic services since API version 14. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** -| Name| Type | Read Only| Optional| Description | -| ------ | ---------------------- | ---- | ------------ | ------------ | -| data | Record<string, Object> | Yes| No | Data about the UIServiceExtensionAbility connection.| - +| Name| Type | Mandatory| Description | +| ------ | ---------------------- | ---- | ------------ | +| data | Record<string, Object> | Yes| Data about the UIServiceExtensionAbility connection.| **Example** ```ts -import { common } from '@kit.AbilityKit'; +import { common, Want } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; const TAG: string = '[Extension] '; @@ -133,13 +133,10 @@ Called when the connection to the UIServiceExtensionAbility is interrupted. > For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). > +**Atomic service API**: This API can be used in atomic services since API version 14. **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**Parameters** - -N/A - **Example** ```ts import { common } from '@kit.AbilityKit'; diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-uiserviceExtensionContext-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-uiserviceExtensionContext-sys.md index ae1eda389b3976f56cefb5982bc9848b6b432edc..6dd7eec318d67533f7b933914cb54951d8431000 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-uiserviceExtensionContext-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-uiserviceExtensionContext-sys.md @@ -6,7 +6,7 @@ UIServiceExtensionContext provides access to a UIServiceExtensionAbility and API > **NOTE** > -> - The initial APIs of this module are supported since API version 13. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The initial APIs of this module are supported since API version 14. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The APIs of this module can be used only in the stage model. > - The APIs of this module must be used in the main thread, but not in sub-threads such as Worker and TaskPool. > - The APIs provided by this module are system APIs. @@ -34,7 +34,7 @@ class UIServiceExtAbility extends UIServiceExtensionAbility { ``` -## UIServiceExtensionContext.startAbility13+ +## UIServiceExtensionContext.startAbility startAbility(want: Want, options?: StartOptions): Promise<void> @@ -121,7 +121,7 @@ class UIEntryAbility extends UIServiceExtensionAbility { ``` -## UIServiceExtensionContext.terminateSelf13+ +## UIServiceExtensionContext.terminateSelf terminateSelf(): Promise<void> @@ -160,7 +160,7 @@ class UIEntryAbility extends UIServiceExtensionAbility { } ``` -## UIServiceExtensionContext.startAbilityByType13+ +## UIServiceExtensionContext.startAbilityByType startAbilityByType(type: string, wantParam: Record<string, Object>, abilityStartCallback: AbilityStartCallback): Promise<void> @@ -253,7 +253,7 @@ struct SubIndex { } ``` -## UIServiceExtensionContext.connectServiceExtensionAbility13+ +## UIServiceExtensionContext.connectServiceExtensionAbility connectServiceExtensionAbility(want: Want, options: ConnectOptions): number @@ -376,11 +376,11 @@ struct Page_UIServiceExtensionAbility { } ``` -## UIServiceExtensionContext.disconnectServiceExtensionAbility13+ +## UIServiceExtensionContext.disconnectServiceExtensionAbility disconnectServiceExtensionAbility(connectionId: number): Promise<void> -Disconnects from a [UIExtensionAbility](js-apis-app-ability-uiExtensionAbility.md). This API is opposite to [connectServiceExtensionAbility](#uiserviceextensioncontextconnectserviceextensionability13). +Disconnects from a [UIExtensionAbility](js-apis-app-ability-uiExtensionAbility.md). This API is opposite to [connectServiceExtensionAbility](#uiserviceextensioncontextconnectserviceextensionability). **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -391,7 +391,7 @@ Disconnects from a [UIExtensionAbility](js-apis-app-ability-uiExtensionAbility.m | Name | Type | Read Only| Optional| Description | | -------------------- | ------------------------ | ---- | ----------------- | ----------------- | -| connectionId | number | Yes | No| Connection ID returned by [connectServiceExtensionAbility](#uiserviceextensioncontextconnectserviceextensionability13).| +| connectionId | number | Yes | No| Connection ID returned by [connectServiceExtensionAbility](#uiserviceextensioncontextconnectserviceextensionability).| **Return value** diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-uiservicehostproxy-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-uiservicehostproxy-sys.md index e0a2e7be98f427d7a1f412b40f04753317f80cba..07547b86e468cca999f0b8ec2d798653a3d49778 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-uiservicehostproxy-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-uiservicehostproxy-sys.md @@ -5,7 +5,7 @@ UIServiceHostProxy functions as a proxy to send data from the [UIServiceExtensio > **NOTE** > -> - The initial APIs of this module are supported since API version 13. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The initial APIs of this module are supported since API version 14. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The APIs of this module can be used only in the stage model. > - The APIs of this module must be used in the main thread, but not in sub-threads such as Worker and TaskPool. > - The APIs provided by this module are system APIs. @@ -23,7 +23,6 @@ sendData(data: Record\): void Sends data from the [UIServiceExtensionAbility](js-apis-app-ability-uiServiceExtensionAbility-sys.md) server to the client. - **System capability**: SystemCapability.Ability.AbilityRuntime.Core **System API**: This is a system API. @@ -61,7 +60,7 @@ export default class MyUiServiceExtensionAbility extends UIServiceExtensionAbili 'proxyData': 'proxyData' }; try { - // Send data to the UIServiceExtensionAbility client. + // Send data to the UIServiceExtensionAbility server. proxy.sendData(formData); } catch (err) { console.log(TAG + `sendData failed ${JSON.stringify(err.message)}`); diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-uiserviceproxy.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-uiserviceproxy.md index 237eeb439204ec785f5a2ce63d64e2d9abca8ae4..81f80923bb60a3e9d88478371e582c3a45a9a28c 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-uiserviceproxy.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-application-uiserviceproxy.md @@ -5,7 +5,7 @@ UIServiceProxy functions as a proxy to send data from the UIServiceExtensionAbil > **NOTE** > -> - The initial APIs of this module are supported since API version 13. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The initial APIs of this module are supported since API version 14. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The APIs of this module can be used only in the stage model. > - The APIs of this module must be used in the main thread, but not in sub-threads such as Worker and TaskPool. @@ -26,14 +26,15 @@ Sends data to the UIServiceExtensionAbility server. > For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). > +**Atomic service API**: This API can be used in atomic services since API version 14. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** -| Name| Type | Read Only| Optional| Description | -| ------ | ---------------------- | ---- | ------------ | ------------ | -| data | Record\ | Yes| No | Data to be sent to the UIServiceExtensionAbility server.| +| Name| Type | Mandatory| Description | +| ------ | ---------------------- | ---- | ------------ | +| data | Record\ | Yes| Data to be sent to the UIServiceExtensionAbility server.| **Error codes** @@ -47,7 +48,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -import { common } from '@kit.AbilityKit'; +import { common, Want } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; const TAG: string = '[Extension] '; diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-wantAgent-triggerInfo-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-wantAgent-triggerInfo-sys.md index 35d68ab3b5d113a96e85c0fb963ec50715f51aeb..bdaacdd16a3a1451e2e7cecc863f2954b383baed 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-wantAgent-triggerInfo-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-wantAgent-triggerInfo-sys.md @@ -1,6 +1,6 @@ # TriggerInfo (System API) -The **TriggerInfo** module defines the information required for triggering the WantAgent. The information is used as an input parameter of [trigger](js-apis-app-ability-wantAgent.md#wantagenttrigger). +The TriggerInfo module defines the information required for triggering the WantAgent. The information is used as an input parameter of [trigger](js-apis-app-ability-wantAgent.md#wantagenttrigger). > **NOTE** > @@ -20,4 +20,4 @@ import { wantAgent } from '@kit.AbilityKit'; | Name | Type | Mandatory| Description | | ---------- | --- |-------------------- | ----------- | -| startOptions12+|[StartOptions](js-apis-app-ability-startOptions.md) | No | Start options in **wantAgent** used to start an ability..| +| startOptions12+|[StartOptions](js-apis-app-ability-startOptions.md) | No | Start options in **wantAgent** used to start an ability.| diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-inner-wantAgent-wantAgentInfo.md b/en/application-dev/reference/apis-ability-kit/js-apis-inner-wantAgent-wantAgentInfo.md index 5abfbd96517db586f0938ebf96fcdf21c7d8fa5f..95b4b5e66074ebd11377564c02b2ce8d6f334889 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-inner-wantAgent-wantAgentInfo.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-inner-wantAgent-wantAgentInfo.md @@ -9,8 +9,7 @@ The **WantAgentInfo** module defines the information required for triggering a * ## Modules to Import ```ts -import { wantAgent } from '@kit.AbilityKit'; -import wantAgentDeprecated from '@ohos.wantAgent'; +import { wantAgent as abilityWantAgent } from '@kit.AbilityKit'; ``` ## Attributes @@ -22,10 +21,10 @@ import wantAgentDeprecated from '@ohos.wantAgent'; | Name | Type | Mandatory| Description | | -------------- | ------------------------------- | ---- | ---------------------- | | wants | Array\<[Want](js-apis-app-ability-want.md)\> | Yes | Array of all **Want** objects. Currently, only one Want is supported. The array is reserved for future capability expansion. If multiple values are passed in, only the first member in the array is used. | -| operationType(deprecated) | [wantAgentDeprecated.OperationType](js-apis-wantAgent.md#operationtype) | No | Operation type.
This attribute is supported since API version 7 and deprecated since API version 11. You are advised to use actionType11+ instead. | -| actionType11+ | [wantAgent.OperationType](js-apis-app-ability-wantAgent.md#operationtype) | No | Operation type. | +| operationType(deprecated) | [wantAgent.OperationType](js-apis-wantAgent.md#operationtype) | No | Operation type.
This attribute is supported since API version 7 and deprecated since API version 11. You are advised to use actionType11+ instead. | +| actionType11+ | [abilityWantAgent.OperationType](js-apis-app-ability-wantAgent.md#operationtype) | No | Operation type. | | requestCode | number | Yes | Request code defined by the user.| -| wantAgentFlags(deprecated) | Array<[wantAgentDeprecated.WantAgentFlags](js-apis-wantAgent.md#wantagentflags)> | No | Array of flags for using the **WantAgent** object.
This attribute is supported since API version 7 and deprecated since API version 11. You are advised to use actionFlags11+ instead. | -| actionFlags11+ | Array<[wantAgent.WantAgentFlags](js-apis-app-ability-wantAgent.md#wantagentflags)> | No | Array of flags for using the **WantAgent** object. | +| wantAgentFlags(deprecated) | Array<[wantAgent.WantAgentFlags](js-apis-wantAgent.md#wantagentflags)> | No | Array of flags for using the **WantAgent** object.
This attribute is supported since API version 7 and deprecated since API version 11. You are advised to use actionFlags11+ instead. | +| actionFlags11+ | Array<[abilityWantAgent.WantAgentFlags](js-apis-app-ability-wantAgent.md#wantagentflags)> | No | Array of flags for using the **WantAgent** object. | | extraInfo | { [key: string]: any } | No | Extra information. | | extraInfos11+ | Record\ | No | Extra information. You are advised to use this attribute to replace **extraInfo**. When this attribute is set, **extraInfo** does not take effect. | diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-installer-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-installer-sys.md index 5b4b30e733dad4f11508250a425c05a2f82b45fe..da1d2bfd21fe87198805a5a0efd8d39bd13a63c9 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-installer-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-installer-sys.md @@ -1,6 +1,6 @@ # @ohos.bundle.installer (installer) (System API) -The **bundle.installer** module provides APIs for you to install, uninstall, and recover bundles on devices. +The bundle.installer module provides APIs for you to install, uninstall, and recover bundles on devices. > **NOTE** > @@ -216,6 +216,8 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 17700054 | Failed to install the HAP because the HAP requests wrong permissions.| | 17700066 | Failed to install the HAP because installing the native package failed. | | 17700073 | Failed to install the HAP because an application with the same bundle name but different signature information exists on the device. | +| 17700076 | Failed to install the HAP or HSP because the app distribution type is not allowed. | +| 17700077 | Failed to install the HAP and restore to preinstalled bundle. | **Example** @@ -308,6 +310,8 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 17700054 | Failed to install the HAP because the HAP requests wrong permissions.| | 17700066 | Failed to install the HAP because installing the native package failed. | | 17700073 | Failed to install the HAP because an application with the same bundle name but different signature information exists on the device. | +| 17700076 | Failed to install the HAP or HSP because the app distribution type is not allowed. | +| 17700077 | Failed to install the HAP and restore to preinstalled bundle. | **Example** @@ -404,6 +408,8 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 17700054 | Failed to install the HAP because the HAP requests wrong permissions.| | 17700066 | Failed to install the HAP because installing the native package failed. | | 17700073 | Failed to install the HAP because an application with the same bundle name but different signature information exists on the device. | +| 17700076 | Failed to install the HAP or HSP because the app distribution type is not allowed. | +| 17700077 | Failed to install the HAP and restore to preinstalled bundle. | **Example** @@ -833,7 +839,7 @@ try { uninstall(uninstallParam: UninstallParam, callback : AsyncCallback\) : void -Uninstalls a shared bundle. This API uses an asynchronous callback to return the result. +Uninstalls a shared package. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -893,7 +899,7 @@ try { uninstall(uninstallParam: UninstallParam) : Promise\ -Uninstalls a shared bundle. This API uses a promise to return the result. +Uninstalls a shared package. This API uses a promise to return the result. **System API**: This is a system API. @@ -1316,7 +1322,7 @@ try { uninstallUpdates(bundleName: string, installParam?: InstallParam): Promise\; -Uninstalls and updates a pre-installed application and restores it to the initial installation status. This API uses a promise to return the result. +Uninstalls and updates a preinstalled application and restores it to the initial installation status. This API uses a promise to return the result. **System API**: This is a system API. @@ -1681,12 +1687,11 @@ Defines the parameters that need to be specified for bundle installation, uninst | hashParams | Array<[HashParam](#hashparam)> | No| Hash parameters. By default, no value is passed. | | crowdtestDeadline| number | No | End date of crowdtesting. The default value is **-1**, indicating that no end date is specified for crowdtesting.| | sharedBundleDirPaths10+ | Array\ | No|Paths of the shared bundle files. By default, no value is passed.| -| specifiedDistributionType10+ | string | No|Distribution type specified during application installation. By default, no value is passed. The maximum length is 128 bytes. This field is usually specified by the application market of the operating system operator.| +| specifiedDistributionType10+ | string | No|[Distribution type](../../security/app-provision-structure.md) specified during application installation. By default, no value is passed. The maximum length is 128 bytes. This field is usually specified by the application market of the operating system operator.| | additionalInfo10+ | string | No|Additional information during application installation (usually an enterprise application). By default, no value is passed. The maximum length is 3,000 bytes. This field is usually specified by the application market of the operating system operator.| | verifyCodeParamsdeprecated | Array<[VerifyCodeParam](#verifycodeparamdeprecated)> | No| Information about the code signature file. The default value is null. | | pgoParams11+ | Array<[PGOParam](#pgoparam11)> | No| Parameters of the Profile-guided Optimization (PGO) configuration file. The default value is null. | -| parameters15+ | Array<[Parameters](#parameters15)> | No| Extended parameters. The default value is null. | - +| parameters15+ | Array<[Parameters](#parameters15)> | No| Extended parameters, represented as an array of the Parameters type. The default value is empty. The options of **Parameters.key** are as follows:
- **ohos.bms.param.renameInstall**: If the value is **true**, the installation package is moved from the application sandbox to the installation directory using a shared directory. Otherwise, it is copied from the application sandbox to the installation directory using a regular directory.
- **ohos.bms.param.enterpriseForAllUser**: If the value is **true**, the enterprise application is installed for all users.
- **ohos.bms.param.verifyUninstallRule**: If the value is **true**, an uninstallation handling rule is set to block application uninstallation.| ## UninstallParam10+ Defines the parameters required for the uninstall of a shared bundle. diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-launcherBundleManager-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-launcherBundleManager-sys.md index a751883515568d20060ecef33c046cac628f2d6e..7f551b6773dd6248e44df7653ab534951247e20e 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-launcherBundleManager-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-launcherBundleManager-sys.md @@ -1,6 +1,6 @@ # @ohos.bundle.launcherBundleManager (launcherBundleManager) (System API) -The **bundle.launcherBundleManager** module providers APIs for the **Home Screen** application to obtain the [launcher ability information](js-apis-bundleManager-launcherAbilityInfo-sys.md) and [shortcut information](js-apis-bundleManager-shortcutInfo-sys.md). +The bundle.launcherBundleManager module providers APIs for the **Home Screen** application to obtain the [LauncherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo.md) and [ShortcutInfo](js-apis-bundleManager-shortcutInfo-sys.md). > **NOTE** > @@ -17,7 +17,7 @@ import launcherBundleManager from '@ohos.bundle.launcherBundleManager'; ## launcherBundleManager.getLauncherAbilityInfo9+ -getLauncherAbilityInfo(bundleName: string, userId: number, callback: AsyncCallback\\>) : void +getLauncherAbilityInfo(bundleName: string, userId: number, callback: AsyncCallback\\>) : void Obtains the launcher ability information based on the given bundle name and user ID. This API uses an asynchronous callback to return the result. @@ -33,7 +33,7 @@ Obtains the launcher ability information based on the given bundle name and user | ---------- | ------ | ---- | -------------- | | bundleName | string | Yes | Bundle name.| | userId | number | Yes | User ID.| -| callback | AsyncCallback\\> | Yes| Callback used to return the **LauncherAbilityInfo** object obtained.| +| callback | AsyncCallback\\> | Yes| Callback used to return the **LauncherAbilityInfo** object obtained.| **Error codes** @@ -72,7 +72,7 @@ try { ## launcherBundleManager.getLauncherAbilityInfo9+ -getLauncherAbilityInfo(bundleName: string, userId: number) : Promise\\> +getLauncherAbilityInfo(bundleName: string, userId: number) : Promise\\> Obtains the launcher ability information based on the given bundle name and user ID. This API uses a promise to return the result. @@ -93,7 +93,7 @@ Obtains the launcher ability information based on the given bundle name and user | Type | Description | | ----------------------------- | -------------------------------------------------- | -| Promise\\> | Promise used to return the **LauncherAbilityInfo** object obtained.| +| Promise\\> | Promise used to return the **LauncherAbilityInfo** object obtained.| **Error codes** @@ -128,63 +128,9 @@ try { } ``` -## launcherBundleManager.getLauncherAbilityInfoSync10+ - -getLauncherAbilityInfoSync(bundleName: string, userId: number) : Array\<[LauncherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo-sys.md)\> - -Obtains the launcher ability information based on the given bundle name and user ID. This API returns the result synchronously. - -**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED - -**System API**: This is a system API. - -**System capability**: SystemCapability.BundleManager.BundleFramework.Launcher - -**Parameters** - -| Name | Type | Mandatory| Description | -| ---------- | ------ | ---- | -------------- | -| bundleName | string | Yes | Bundle name.| -| userId | number | Yes | User ID.| - -**Return value** - -| Type | Description | -| ----------------------------- | -------------------------------------------------- | -| Array\<[LauncherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo-sys.md)\> | Array of the **LauncherAbilityInfo** objects obtained.| - -**Error codes** - -For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). - -| ID| Error Message | -| -------- | ---------------------------------------- | -| 201 | Permission denied. | -| 202 | Permission denied, non-system app called system api. | -| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.| -| 801 | Capability not support. | -| 17700001 | The specified bundle name is not found. | -| 17700004 | The specified user ID is not found. | - -**Example** - -```ts -import launcherBundleManager from '@ohos.bundle.launcherBundleManager'; -import { BusinessError } from '@ohos.base'; - -try { - let data = launcherBundleManager.getLauncherAbilityInfoSync("com.example.demo", 100); - console.log("data is " + JSON.stringify(data)); -} catch (errData) { - let code = (errData as BusinessError).code; - let message = (errData as BusinessError).message; - console.error(`errData is errCode:${code} message:${message}`); -} -``` - ## launcherBundleManager.getAllLauncherAbilityInfo9+ -getAllLauncherAbilityInfo(userId: number, callback: AsyncCallback\\>) : void +getAllLauncherAbilityInfo(userId: number, callback: AsyncCallback\\>) : void Obtains the launcher ability information of all applications based on the given user ID. This API uses an asynchronous callback to return the result. @@ -199,7 +145,7 @@ Obtains the launcher ability information of all applications based on the given | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------- | | userId | number | Yes | User ID.| -| callback | AsyncCallback\\> | Yes| Callback used to return the array of **LauncherAbilityInfo** objects obtained.| +| callback | AsyncCallback\\> | Yes| Callback used to return the array of **LauncherAbilityInfo** objects obtained.| **Error codes** @@ -236,7 +182,7 @@ try { ``` ## launcherBundleManager.getAllLauncherAbilityInfo9+ -getAllLauncherAbilityInfo(userId: number) : Promise\\> +getAllLauncherAbilityInfo(userId: number) : Promise\\> Obtains the launcher ability information of all applications based on the given user ID. This API uses a promise to return the result. @@ -256,7 +202,7 @@ Obtains the launcher ability information of all applications based on the given | Type | Description | | ----------------------------- | ------------------------------------------------------ | -| Promise\\> | Promise used to return the array of **LauncherAbilityInfo** objects obtained.| +| Promise\\> | Promise used to return the array of **LauncherAbilityInfo** objects obtained.| **Error codes** diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-launcherBundleManager.md b/en/application-dev/reference/apis-ability-kit/js-apis-launcherBundleManager.md new file mode 100644 index 0000000000000000000000000000000000000000..82016ccd51ef0ea456bceb7be19be52ccb5bd6c7 --- /dev/null +++ b/en/application-dev/reference/apis-ability-kit/js-apis-launcherBundleManager.md @@ -0,0 +1,64 @@ +# @ohos.bundle.launcherBundleManager (launcherBundleManager) + +The bundle.launcherBundleManager module providers APIs for the launcher application to obtain the [launcher ability information](js-apis-bundleManager-launcherAbilityInfo.md). + +> **NOTE** +> +> The initial APIs of this module are supported since API version 18. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```ts +import { launcherBundleManager } from '@kit.AbilityKit'; +``` + +## launcherBundleManager.getLauncherAbilityInfoSync18+ + +getLauncherAbilityInfoSync(bundleName: string, userId: number) : Array\<[LauncherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo.md)\> + +Obtains the launcher ability information based on the given bundle name and user ID. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.BundleManager.BundleFramework.Launcher + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------ | ---- | -------------- | +| bundleName | string | Yes | Bundle name.| +| userId | number | Yes | User ID.| + +**Returns** + +| Type | Description | +| ----------------------------- | -------------------------------------------------- | +| Array\<[LauncherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo.md)\> | Array of the **LauncherAbilityInfo** objects obtained.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 201 | Permission denied. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.| +| 801 | Capability not support. | +| 17700001 | The specified bundle name is not found. | +| 17700004 | The specified user ID is not found. | + +**Example** + +```ts +import { launcherBundleManager } from '@kit.AbilityKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +try { + let data = launcherBundleManager.getLauncherAbilityInfoSync("com.example.demo", 100); + console.log("data is " + JSON.stringify(data)); +} catch (errData) { + let code = (errData as BusinessError).code; + let message = (errData as BusinessError).message; + console.error(`errData is errCode:${code} message:${message}`); +} +``` diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-overlay-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-overlay-sys.md index 26f614d6d5554a20a2b647958eb5eae433b7d8b2..28891ece4aa9da9da05a72c970dadebe1b53a05c 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-overlay-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-overlay-sys.md @@ -16,7 +16,7 @@ import { overlay } from '@kit.AbilityKit'; ## overlay.setOverlayEnabledByBundleName -setOverlayEnabledByBundleName(bundleName:string, moduleName:string, isEnabled: boolean): Promise\ +setOverlayEnabledByBundleName(bundleName: string, moduleName: string, isEnabled: boolean): Promise\ Enables or disables a module with the overlay feature in another application. This API uses a promise to return the result. If the operation is successful, the processing result is returned; otherwise, an error message is returned. @@ -32,19 +32,19 @@ Enables or disables a module with the overlay feature in another application. Th | ----------- | ------ | ---- | --------------------------------------- | | bundleName | string | Yes | Bundle name of the application. | | moduleName | string | Yes | Name of the module with the overlay feature. | -| isEnabled | boolean | Yes | Whether to enable the module with the overlay feature. The value **true** means to enable the module, and **false** means to disable the module. | +| isEnabled | boolean | Yes | Whether to enable the module with the overlay feature. The value **true** means to enable the module, and **false** means to disable the module.| **Return value** | Type | Description | | ------------------------- | ------------------ | -| Promise\ | Promise that returns no value. | +| Promise\ | Promise that returns no value.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). -| ID | Error Message | +| ID| Error Message | | ------ | -------------------------------------- | | 201 | Permission denied. | | 202 | Permission denied, non-system app called system api. | @@ -79,7 +79,7 @@ try { ## overlay.setOverlayEnabledByBundleName -setOverlayEnabledByBundleName(bundleName:string, moduleName:string, isEnabled: boolean, callback: AsyncCallback\): void +setOverlayEnabledByBundleName(bundleName: string, moduleName: string, isEnabled: boolean, callback: AsyncCallback\): void Enables or disables a module with the overlay feature in another application. This API uses an asynchronous callback to return the result. If the operation is successful, the processing result is returned; otherwise, an error message is returned. @@ -95,14 +95,14 @@ Enables or disables a module with the overlay feature in another application. Th | ----------- | ------ | ---- | --------------------------------------- | | bundleName | string | Yes | Bundle name of the application. | | moduleName | string | Yes | Name of the module with the overlay feature. | -| isEnabled | boolean | Yes | Whether to enable the module with the overlay feature. The value **true** means to enable the module, and **false** means to disable the module. | +| isEnabled | boolean | Yes | Whether to enable the module with the overlay feature. The value **true** means to enable the module, and **false** means to disable the module.| | callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, **err** is **null**; otherwise, **err** is an error object. | **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). -| ID | Error Message | +| ID| Error Message | | ------ | -------------------------------------- | | 201 | Permission denied. | | 202 | Permission denied, non-system app called system api. | @@ -159,13 +159,13 @@ Obtains the information about a module with the overlay feature in another appli | Type | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| Promise\> | Promise used to return the result, which is an array of [OverlayModuleInfo](js-apis-bundleManager-overlayModuleInfo.md) objects. | +| Promise\> | Promise used to return the result, which is an array of [OverlayModuleInfo](js-apis-bundleManager-overlayModuleInfo.md) objects.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). -| ID | Error Message | +| ID| Error Message | | ------ | -------------------------------------- | | 201 | Permission denied. | | 202 | Permission denied, non-system app called system api. | @@ -219,7 +219,7 @@ Obtains the information about a module with the overlay feature in another appli For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). -| ID | Error Message | +| ID| Error Message | | ------ | -------------------------------------- | | 201 | Permission denied. | | 202 | Permission denied, non-system app called system api. | @@ -275,7 +275,7 @@ Obtains the information about all modules with the overlay feature in another ap For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). -| ID | Error Message | +| ID| Error Message | | ------ | -------------------------------------- | | 201 | Permission denied. | | 202 | Permission denied, non-system app called system api. | @@ -328,13 +328,13 @@ Obtains the information about modules with the overlay feature in another applic | Type | Description | | ------------------------- | ------------------ | -| Promise\> | Promise used to return the result, which is an array of [OverlayModuleInfo](js-apis-bundleManager-overlayModuleInfo.md) objects. | +| Promise\> | Promise used to return the result, which is an array of [OverlayModuleInfo](js-apis-bundleManager-overlayModuleInfo.md) objects.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). -| ID | Error Message | +| ID| Error Message | | ------ | -------------------------------------- | | 201 | Permission denied. | | 202 | Permission denied, non-system app called system api. | @@ -388,7 +388,7 @@ Obtains the information about modules with the overlay feature in another applic For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). -| ID | Error Message | +| ID| Error Message | | ------ | -------------------------------------- | | 201 | Permission denied. | | 202 | Permission denied, non-system app called system api. | @@ -444,7 +444,7 @@ Obtains the information about all modules with the overlay feature in another ap For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Bundle Error Codes](errorcode-bundle.md). -| ID | Error Message | +| ID| Error Message | | ------ | -------------------------------------- | | 201 | Permission denied. | | 202 | Permission denied, non-system app called system api. | diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-overlay.md b/en/application-dev/reference/apis-ability-kit/js-apis-overlay.md index 19902314b1dd4e1b811514fae2286c4adece7903..aafe3d7b5127377726912728bb9d08a9e8e974ad 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-overlay.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-overlay.md @@ -1,10 +1,17 @@ # @ohos.bundle.overlay (overlay) -The **overlay** module provides APIs for installing a [module with the overlay feature](#module-with-the-overlay-feature), querying the [module information](js-apis-bundleManager-overlayModuleInfo.md), and disabling and enabling the module. +The overlay module provides APIs for installing a module with the overlay feature, querying the [module information](js-apis-bundleManager-overlayModuleInfo.md), and disabling and enabling the module. + +A module with the [overlay feature](../../quick-start/resource-categories-and-access.md#overlay-mechanism) generally provides additional resource files for modules without the overlay feature on the device, so that the target modules can use these resource files at runtime to display different colors, labels, themes, and the like. + +If the **module.json5** file of a module contains the **targetModuleName** and **targetPriority fields** during project creation on DevEco Studio, the module is identified as a module with the overlay feature in the installation phase. > **NOTE** > > The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> The overlay feature applies only to the stage model. + ## Modules to Import @@ -68,7 +75,7 @@ try { ## overlay.setOverlayEnabled -setOverlayEnabled(moduleName:string, isEnabled: boolean, callback: AsyncCallback\): void +setOverlayEnabled(moduleName: string, isEnabled: boolean, callback: AsyncCallback\): void Enables or disables a module with the overlay feature in the current application. This API uses an asynchronous callback to return the result. If the operation is successful, **null** is returned; otherwise, an error message is returned. @@ -314,10 +321,14 @@ try { } ``` -## Module with the Overlay Feature +## OverlayModuleInfo -**Concept** -A module with the overlay feature generally provides additional resource files for modules without the overlay feature on the device, so that the target modules can use these resource files at runtime to display different colors, labels, themes, and the like. The overlay feature applies only to the stage model. +type OverlayModuleInfo = _OverlayModuleInfo.OverlayModuleInfo -**How do I identify a module with the overlay feature?** -If the **module.json5** file of a module contains the **targetModuleName** and **targetPriority fields** during project creation on DevEco Studio, the module is identified as a module with the overlay feature in the installation phase. +Defines the information about a module with the overlay feature. + +**System capability**: SystemCapability.BundleManager.BundleFramework.Overlay + +| Type | Description | +| ------------------------------------------------------------ | -------------- | +| [_OverlayModuleInfo.OverlayModuleInfo](js-apis-bundleManager-overlayModuleInfo.md#overlaymoduleinfo-1) |Information about a module with the overlay feature.| diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-permissionrequestresult.md b/en/application-dev/reference/apis-ability-kit/js-apis-permissionrequestresult.md index d47cc526b6412363fce478bd86ed958783c371d2..2a4e0b104e17b0669fab90959c1e2bf27d2955dc 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-permissionrequestresult.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-permissionrequestresult.md @@ -1,6 +1,6 @@ # PermissionRequestResult -The **PermissionRequestResult** module defines the result of a permission request. The result is returned when [requestPermissionsFromUser](js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) is called to request permissions. +The **PermissionRequestResult** module defines the permission request result returned by [requestPermissionsFromUser](js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9). > **NOTE** > @@ -13,9 +13,10 @@ The **PermissionRequestResult** module defines the result of a permission reques | Name| Type| Read Only| Optional| Description| | -------- | -------- | -------- | -------- | -------- | -| permissions | Array<string> | Yes| No| Permissions requested.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| authResults | Array<number> | Yes| No| Result of the permission request.
- **-1**: The permission is not granted. If **dialogShownResults** is **true**, it is the first time that the user requests the permission. If **dialogShownResults** is **false**, the permission has been set and no dialog box is displayed. The user can modify the permission settings in **Settings**.
- **0**: The permission is granted.
- **2**: The permission is not granted due to an invalid request. The possible causes are as follows:
- The permission is not declared in the configuration file.
- The permission name is invalid.
- Conditions for requesting the permission are not met. For details, see [ohos.permission.LOCATION](../../security/AccessToken/permissions-for-all.md#ohospermissionlocation) and [ohos.permission.APPROXIMATELY_LOCATION](../../security/AccessToken/permissions-for-all.md#ohospermissionapproximately_location).
**Atomic service API**: This API can be used in atomic services since API version 11. | -| dialogShownResults12+ | Array<boolean> | Yes| Yes| Whether to display a dialog box.
The value **true** means to display a dialog box; the value **false** means the opposite.
**Atomic service API**: This API can be used in atomic services since API version 12. | +| permissions | Array<string> | Yes| No| Permissions requested.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| authResults | Array<number> | Yes| No| Result of the permission request.
- **-1**: The permission is not granted. If **dialogShownResults** is **true**, it is the first time that the user requests the permission. If **dialogShownResults** is **false**, the permission has been set and no dialog box is displayed. The user can modify the permission settings in **Settings**.
- **0**: The permission is granted.
- **2**: The permission request is invalid. The possible causes are as follows: 1. The permission is not declared in the configuration file. 2. The permission name is invalid. 3. The conditions for requesting the permission are not met. For details, see [ohos.permission.LOCATION](../../security/AccessToken/permissions-for-all-user.md#ohospermissionlocation) and [ohos.permission.APPROXIMATELY_LOCATION](../../security/AccessToken/permissions-for-all-user.md#ohospermissionapproximately_location).
**Atomic service API**: This API can be used in atomic services since API version 11.| +| dialogShownResults12+ | Array<boolean> | Yes| Yes| Whether to display a dialog box.
The value **true** means to display a dialog box; the value **false** means the opposite.
**Atomic service API**: This API can be used in atomic services since API version 12. | +| errorReasons18+ | Array<number> | Yes| Yes| Return value.
- **0**: The request is valid.
- **1**: The permission name is invalid.
- **2**: The permission is not declared in the configuration file.
- **3**: The conditions for requesting the permission are not met. For details, see the permission description in [Permission List](../../security/AccessToken/permissions-for-all-user.md). Currently, only the location permissions are involved.
- **4**: The user does not agree to the privacy statement.
- **5**: This permission cannot be requested via a dialog box.
- **12**: The service is abnormal.
**Atomic service API**: This API can be used in atomic services since API version 18.| ## Usage @@ -38,6 +39,7 @@ try { console.info("data permissions:" + data.permissions); console.info("data authResults:" + data.authResults); console.info("data dialogShownResults:" + data.dialogShownResults); + console.info("data errorReasons:" + data.errorReasons); }).catch((err: BusinessError) => { console.error("data:" + JSON.stringify(err)); }) diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-privacyManager-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-privacyManager-sys.md index 288ba1c0cc8b8b1085892a5838ac1cd86a654a57..3883125f803714b4ab6f79574c33638677903895 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-privacyManager-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-privacyManager-sys.md @@ -19,7 +19,7 @@ import { privacyManager } from '@kit.AbilityKit'; addPermissionUsedRecord(tokenID: number, permissionName: Permissions, successCount: number, failCount: number, options?: AddPermissionUsedRecordOptions): Promise<void> Adds a permission usage record when an application protected by the permission is called by another service or application. This API uses a promise to return the result. -The permission usage record includes the application identity (token ID) of the invoker, name of the permission used, and number of successful and failed accesses to the target application. +The permission usage record includes the application identity (token ID) of the caller, name of the permission used, and number of successful and failed accesses to the target application. **Required permissions**: ohos.permission.PERMISSION_USED_STATS (available only to system applications) @@ -29,7 +29,7 @@ The permission usage record includes the application identity (token ID) of the | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------ | -| tokenID | number | Yes | Application token ID of the caller, which is the value of **accessTokenId** in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| +| tokenID | number | Yes | Token ID of the caller, which is the value of **accessTokenId** in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| | permissionName | Permissions | Yes | Name of the permission.| | successCount | number | Yes | Number of successful accesses.| | failCount | number | Yes | Number of failed accesses.| @@ -84,7 +84,7 @@ privacyManager.addPermissionUsedRecord(tokenID, 'ohos.permission.READ_AUDIO', 1, addPermissionUsedRecord(tokenID: number, permissionName: Permissions, successCount: number, failCount: number, callback: AsyncCallback<void>): void Adds a permission usage record when an application protected by the permission is called by another service or application. This API uses an asynchronous callback to return the result. -The permission usage record includes the application identity (token ID) of the invoker, name of the permission used, and number of successful and failed accesses to the target application. +The permission usage record includes the application identity (token ID) of the caller, name of the permission used, and number of successful and failed accesses to the target application. **Required permissions**: ohos.permission.PERMISSION_USED_STATS (available only to system applications) @@ -94,11 +94,11 @@ The permission usage record includes the application identity (token ID) of the | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------ | -| tokenID | number | Yes | Application token ID of the caller, which is the value of **accessTokenId** in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| -| permissionName | Permissions | Yes | Permission name. For details about the permissions, see [Permissions for All Applications](../../security/AccessToken/permissions-for-all.md).| +| tokenID | number | Yes | Token ID of the caller, which is the value of **accessTokenId** in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| +| permissionName | Permissions | Yes | Permission name. For details, see [Application Permissions](../../security/AccessToken/app-permissions.md).| | successCount | number | Yes | Number of successful accesses.| | failCount | number | Yes | Number of failed accesses.| -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| **Error codes** @@ -207,7 +207,7 @@ Obtains historical permission usage records. This API uses an asynchronous callb | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------ | | request | [PermissionUsedRequest](#permissionusedrequest) | Yes| Request for querying permission usage records.| -| callback | AsyncCallback<[PermissionUsedResponse](#permissionusedresponse)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the permission usage record obtained. Otherwise, **err** is an error object.| +| callback | AsyncCallback<[PermissionUsedResponse](#permissionusedresponse)> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the permission usage record obtained. Otherwise, **err** is an error object.| **Error codes** @@ -250,11 +250,106 @@ privacyManager.getPermissionUsedRecord(request, (err: BusinessError, data: priva }); ``` +## privacyManager.setPermissionUsedRecordToggleStatus18+ + +setPermissionUsedRecordToggleStatus(status: boolean): Promise<void> + +Sets whether to record the permission usage of this user. This API uses a promise to return the result. + +If **status** is **true**, [addPermissionUsedRecord](#privacymanageraddpermissionusedrecord) can be called to add permission usage records. If **status** is set **false**, [addPermissionUsedRecord](#privacymanageraddpermissionusedrecord) does not add permission usage records. Instead, it deletes the historical records of the user. + +**Required permissions**: ohos.permission.PERMISSION_RECORD_TOGGLE (available only to system applications) + +**System capability**: SystemCapability.Security.AccessToken + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ------ | ---- | ------------------------------------ | +| status | boolean | Yes | Setting of the permission usage record switch. The value **true** means the switch is toggled on; the value **false** means the opposite.| + +**Return value** + +| Type | Description | +| ------------- | --------------------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Access Control Error Codes](errorcode-access-token.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission denied. Interface caller does not have permission. | +| 202 | Not System App. Interface caller is not a system app. | +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | +| 12100007 | The service is abnormal. | +| 12100009 | Common inner error. | + +**Example** + +```ts +import { privacyManager } from '@kit.AbilityKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +privacyManager.setPermissionUsedRecordToggleStatus(true).then(() => { + console.log('setPermissionUsedRecordToggleStatus success'); +}).catch((err: BusinessError) => { + console.error(`setPermissionUsedRecordToggleStatus fail, err->${JSON.stringify(err)}`); +}); +``` + +## privacyManager.getPermissionUsedRecordToggleStatus18+ + +getPermissionUsedRecordToggleStatus(): Promise<boolean> + +Obtains the settings of the permission usage record switch for this user. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.PERMISSION_USED_STATS (available only to system applications) + +**System capability**: SystemCapability.Security.AccessToken + +**Return value** + +| Type | Description | +| ------------- | --------------------------------------- | +| Promise<boolean> | Promise used to return the switch settings.| + +**Error codes** + +For details about the error codes, see [Access Control Error Codes](errorcode-access-token.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission denied. Interface caller does not have permission. | +| 202 | Not System App. Interface caller is not a system app. | +| 12100007 | The service is abnormal. | + +**Example** + +```ts +import { privacyManager } from '@kit.AbilityKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +privacyManager.getPermissionUsedRecordToggleStatus().then((res) => { + console.log('getPermissionUsedRecordToggleStatus success'); + if (res == true) { + console.log('get status is TRUE'); + } else { + console.log('get status is FALSE'); + } +}).catch((err: BusinessError) => { + console.error(`getPermissionUsedRecordToggleStatus fail, err->${JSON.stringify(err)}`); +}); +``` + ## privacyManager.startUsingPermission startUsingPermission(tokenID: number, permissionName: Permissions): Promise<void> -Starts to use a permission and flushes the permission usage record. This API is called by a system application, either running in the foreground or background, and uses a promise to return the result. This API uses a promise to return the result. +Starts using a permission. This API is called by a system application to report the permission usage of an application in the foreground and background, allowing the privacy service to respond based on the application lifecycle. This API uses a promise to return the result. + +When an application starts to use a permission, the privacy service notifies the privacy indicator that the application is using the permission. Upon the application's exit, the privacy service notifies the privacy indicator that the application has stopped using the permission and clears the corresponding cache. **Required permissions**: ohos.permission.PERMISSION_USED_STATS (available only to system applications) @@ -264,8 +359,8 @@ Starts to use a permission and flushes the permission usage record. This API is | Name | Type | Mandatory| Description | | -------------- | ------ | ---- | ------------------------------------ | -| tokenID | number | Yes | Application token ID of the caller, which is the value of **accessTokenId** in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| -| permissionName | Permissions | Yes | Permission to use. For details about the permissions, see [Permissions for All Applications](../../security/AccessToken/permissions-for-all.md).| +| tokenID | number | Yes | Token ID of the caller, which is the value of **accessTokenId** in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| +| permissionName | Permissions | Yes | Permission to use. For details, see [Application Permissions](../../security/AccessToken/app-permissions.md).| **Return value** @@ -303,11 +398,97 @@ privacyManager.startUsingPermission(tokenID, 'ohos.permission.READ_AUDIO').then( }); ``` +## privacyManager.startUsingPermission18+ + +startUsingPermission(tokenID: number, permissionName: Permissions, pid?: number, usedType?: PermissionUsedType): Promise<void> + +Starts using a permission. This API is called by a system application to report the permission usage of an application in the foreground and background, allowing the privacy service to respond based on the application lifecycle. This API uses a promise to return the result. + +When an application starts to use a permission, the privacy service notifies the privacy indicator that the application is using the permission. Upon the application's exit, the privacy service notifies the privacy indicator that the application has stopped using the permission and clears the corresponding cache. + +For a multi-process application, you can specify the process ID (PID) of the application when reporting the permission usage. If no PID is specified, the privacy service responds by application. When the application exits, the privacy service notifies the privacy indicator and clears the cache. + +If a PID is specified, the privacy service responds by process. when the process exits, the privacy service notifies the privacy indicator and clears the cache. In this case, the PID must be that of the application corresponding to the token ID. + +**Required permissions**: ohos.permission.PERMISSION_USED_STATS (available only to system applications) + +**System capability**: SystemCapability.Security.AccessToken + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ------ | ---- | ------------------------------------ | +| tokenID | number | Yes | Token ID of the caller, which is the value of **accessTokenId** in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| +| permissionName | Permissions | Yes | Permission to use. For details, see [Permissions for All Applications](../../security/AccessToken/app-permissions.md).| +| pid | number | No | PID of the caller. The default value is **-1**, which indicates that the privacy service does not respond based on the process lifecycle.| +| usedType | [PermissionUsedType](#permissionusedtype12) | No| Sensitive permission access mode. The default value is **NORMAL_TYPE**.| + +**Return value** + +| Type | Description | +| ------------- | --------------------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Access Control Error Codes](errorcode-access-token.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission denied. Interface caller does not have permission. | +| 202 | Not System App. Interface caller is not a system app. | +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | +| 12100001 | Invalid parameter. The tokenID is 0, the permissionName exceeds 256 characters, or the count value is invalid. | +| 12100002 | The specified tokenID does not exist or refer to an application process. | +| 12100003 | The specified permission does not exist or is not an user_grant permission. | +| 12100004 | The API is used repeatedly with the same input. It means the application specified by the tokenID has been using the specified permission. | +| 12100007 | The service is abnormal. | +| 12100008 | Out of memory. | + +**Example** + +```ts +import { privacyManager } from '@kit.AbilityKit'; +import { BusinessError } from '@kit.BasicServicesKit'; +import { rpc } from '@kit.IPCKit' + +let tokenID: number = rpc.IPCSkeleton.getCallingTokenId(); // accessTokenId can also be obtained by using bundleManager.getBundleInfoForSelfSync. +let pid: number = rpc.IPCSkeleton.getCallingPid(); +let usedType: privacyManager.PermissionUsedType = privacyManager.PermissionUsedType.PICKER_TYPE; + +// without pid and usedType +privacyManager.startUsingPermission(tokenID, 'ohos.permission.READ_AUDIO').then(() => { + console.log('startUsingPermission success'); +}).catch((err: BusinessError) => { + console.error(`startUsingPermission fail, err->${JSON.stringify(err)}`); +}); +// with pid +privacyManager.startUsingPermission(tokenID, 'ohos.permission.READ_AUDIO', pid).then(() => { + console.log('startUsingPermission success'); +}).catch((err: BusinessError) => { + console.error(`startUsingPermission fail, err->${JSON.stringify(err)}`); +}); +// with usedType +privacyManager.startUsingPermission(tokenID, 'ohos.permission.READ_AUDIO', -1, usedType).then(() => { + console.log('startUsingPermission success'); +}).catch((err: BusinessError) => { + console.error(`startUsingPermission fail, err->${JSON.stringify(err)}`); +}); +// with pid and usedType +privacyManager.startUsingPermission(tokenID, 'ohos.permission.READ_AUDIO', pid, usedType).then(() => { + console.log('startUsingPermission success'); +}).catch((err: BusinessError) => { + console.error(`startUsingPermission fail, err->${JSON.stringify(err)}`); +}); +``` + ## privacyManager.startUsingPermission startUsingPermission(tokenID: number, permissionName: Permissions, callback: AsyncCallback<void>): void -Starts to use a permission and flushes the permission usage record. This API is called by a system application, either running in the foreground or background, and uses a promise to return the result. This API uses an asynchronous callback to return the result. +Starts using a permission. This API is called by a system application to report the permission usage of an application in the foreground and background, allowing the privacy service to respond based on the application lifecycle. This API uses an asynchronous callback to return the result. + +When an application starts to use a permission, the privacy service notifies the privacy indicator that the application is using the permission. Upon the application's exit, the privacy service notifies the privacy indicator that the application has stopped using the permission and clears the corresponding cache. **Required permissions**: ohos.permission.PERMISSION_USED_STATS (available only to system applications) @@ -317,9 +498,9 @@ Starts to use a permission and flushes the permission usage record. This API is | Name | Type | Mandatory| Description | | -------------- | --------------------- | ---- | ------------------------------------ | -| tokenID | number | Yes | Application token ID of the caller, which is the value of **accessTokenId** in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| -| permissionName | Permissions | Yes | Permission to use. For details about the permissions, see [Permissions for All Applications](../../security/AccessToken/permissions-for-all.md).| -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| +| tokenID | number | Yes | Token ID of the caller, which is the value of **accessTokenId** in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| +| permissionName | Permissions | Yes | Permission to use. For details, see [Application Permissions](../../security/AccessToken/app-permissions.md).| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| **Error codes** @@ -357,7 +538,7 @@ privacyManager.startUsingPermission(tokenID, 'ohos.permission.READ_AUDIO', (err: stopUsingPermission(tokenID: number, permissionName: Permissions): Promise<void> -Stops using a permission. This API is called by a system application and uses a promise to return the result. **startUsingPermission** and **stopUsingPermission** are used in pairs. This API uses a promise to return the result. +Stops using a permission. This API must be called by a system application, and used with **startUsingPermission** in pairs. This API uses a promise to return the result. **Required permissions**: ohos.permission.PERMISSION_USED_STATS (available only to system applications) @@ -367,8 +548,8 @@ Stops using a permission. This API is called by a system application and uses a | Name | Type | Mandatory| Description | | -------------- | ------ | ---- | ------------------------------------ | -| tokenID | number | Yes | Application token ID of the caller, which is the value of **accessTokenId** in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| -| permissionName | Permissions | Yes | Permission to use. For details about the permissions, see [Permissions for All Applications](../../security/AccessToken/permissions-for-all.md).| +| tokenID | number | Yes | Token ID of the caller, which is the value of **accessTokenId** in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| +| permissionName | Permissions | Yes | Permission to stop using. For details, see [Application Permissions](../../security/AccessToken/app-permissions.md).| **Return value** @@ -406,11 +587,78 @@ privacyManager.stopUsingPermission(tokenID, 'ohos.permission.READ_AUDIO').then(( }); ``` +## privacyManager.stopUsingPermission18+ + +stopUsingPermission(tokenID: number, permissionName: Permissions, pid?: number): Promise<void> + +Stops using a permission. This API must be called by a system application, and used with **startUsingPermission** in pairs. This API uses a promise to return the result. + +The value of **pid** must match that used in **startUsingPermission**. + +**Required permissions**: ohos.permission.PERMISSION_USED_STATS (available only to system applications) + +**System capability**: SystemCapability.Security.AccessToken + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ------ | ---- | ------------------------------------ | +| tokenID | number | Yes | Token ID of the caller, which is the value of **accessTokenId** in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| +| permissionName | Permissions | Yes | Permission to stop using. For details, see [Application Permissions](../../security/AccessToken/app-permissions.md).| +| pid | number | No | PID of the application. The value must match that used in **startUsingPermission**. The default value is **-1**.| + +**Return value** + +| Type | Description | +| ------------- | --------------------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Access Control Error Codes](errorcode-access-token.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission denied. Interface caller does not have permission. | +| 202 | Not System App. Interface caller is not a system app. | +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | +| 12100001 | Invalid parameter. The tokenID is 0, the permissionName exceeds 256 characters, or the count value is invalid. | +| 12100002 | The specified tokenID does not exist or refer to an application process. | +| 12100003 | The specified permission does not exist or is not an user_grant permission. | +| 12100004 | The API is not used in pair with 'startUsingPermission'. | +| 12100007 | The service is abnormal. | +| 12100008 | Out of memory. | + +**Example** + +```ts +import { privacyManager } from '@kit.AbilityKit'; +import { BusinessError } from '@kit.BasicServicesKit'; +import { rpc } from '@kit.IPCKit' + +let tokenID: number = rpc.IPCSkeleton.getCallingTokenId(); // accessTokenId can also be obtained by using bundleManager.getBundleInfoForSelfSync. +let pid: number = rpc.IPCSkeleton.getCallingPid(); + +// without pid +privacyManager.stopUsingPermission(tokenID, 'ohos.permission.READ_AUDIO').then(() => { + console.log('stopUsingPermission success'); +}).catch((err: BusinessError) => { + console.error(`stopUsingPermission fail, err->${JSON.stringify(err)}`); +}); + +// with pid +privacyManager.stopUsingPermission(tokenID, 'ohos.permission.READ_AUDIO', pid).then(() => { + console.log('stopUsingPermission success'); +}).catch((err: BusinessError) => { + console.error(`stopUsingPermission fail, err->${JSON.stringify(err)}`); +}); +``` + ## privacyManager.stopUsingPermission stopUsingPermission(tokenID: number, permissionName: Permissions, callback: AsyncCallback<void>): void -Stops using a permission. This API is called by a system application and uses a promise to return the result. **startUsingPermission** and **stopUsingPermission** are used in pairs. This API uses an asynchronous callback to return the result. +Stops using a permission. This API must be called by a system application, and used with **startUsingPermission** in pairs. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.PERMISSION_USED_STATS (available only to system applications) @@ -420,9 +668,9 @@ Stops using a permission. This API is called by a system application and uses a | Name | Type | Mandatory| Description | | -------------- | --------------------- | ---- | ------------------------------------ | -| tokenID | number | Yes | Application token ID of the caller, which is the value of **accessTokenId** in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| -| permissionName | Permissions | Yes | Permission to use. For details about the permissions, see [Permissions for All Applications](../../security/AccessToken/permissions-for-all.md).| -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| +| tokenID | number | Yes | Token ID of the caller, which is the value of **accessTokenId** in [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| +| permissionName | Permissions | Yes | Permission to stop using. For details, see [Application Permissions](../../security/AccessToken/app-permissions.md).| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| **Error codes** @@ -460,11 +708,11 @@ privacyManager.stopUsingPermission(tokenID, 'ohos.permission.READ_AUDIO', (err: on(type: 'activeStateChange', permissionList: Array<Permissions>, callback: Callback<ActiveChangeResponse>): void -Subscribes to the permission usage status changes of the specified permissions. +Subscribes to changes in the permission usage status of the specified permissions. Multiple callbacks can be registered for the same **permissionList**. -The same callback cannot be registered for the **permissionList**s with common values. +The same callback cannot be registered for the **permissionList**s with overlapping values. **Required permissions**: ohos.permission.PERMISSION_USED_STATS (available only to system applications) @@ -475,8 +723,8 @@ The same callback cannot be registered for the **permissionList**s with common v | Name | Type | Mandatory| Description | | ------------------ | --------------------- | ---- | ------------------------------------------------------------ | | type | string | Yes | Event type. The value is **'activeStateChange'**, which indicates the permission usage change. | -| permissionList | Array<Permissions> | Yes | Permissions to be observed. If this parameter is left empty, this API subscribes to usage status changes of all permissions. For details about the permissions, see [Permissions for All Applications](../../security/AccessToken/permissions-for-all.md).| -| callback | Callback<[ActiveChangeResponse](#activechangeresponse)> | Yes| Callback invoked to return a change in the permission usage.| +| permissionList | Array<Permissions> | Yes | List of target permissions. If this parameter is not specified, this API will subscribe to usage changes of all permissions. For details about the permissions, see [Application Permissions](../../security/AccessToken/app-permissions.md).| +| callback | Callback<[ActiveChangeResponse](#activechangeresponse)> | Yes| Callback used to return the permission usage change.| **Error codes** @@ -513,9 +761,9 @@ try { off(type: 'activeStateChange', permissionList: Array<Permissions>, callback?: Callback<ActiveChangeResponse>): void -Unsubscribes from the permission usage status changes of the specified permissions. +Unsubscribes from changes in the permission usage of the specified permissions. -If no callback is passed in **privacyManager.off**, all callbacks of **permissionList** will be unregistered. +If **callback** is not specified, this API will unregister all callbacks for **permissionList**. **Required permissions**: ohos.permission.PERMISSION_USED_STATS (available only to system applications) @@ -526,8 +774,8 @@ If no callback is passed in **privacyManager.off**, all callbacks of **permissio | Name | Type | Mandatory| Description | | ------------------ | --------------------- | ---- | ------------------------------------------------------------ | | type | string | Yes | Event type. The value is **'activeStateChange'**, which indicates the permission usage change. | -| permissionList | Array<Permissions> | Yes | List of permissions. The value must be the same as that of **on()**. If this parameter is left empty, this API unsubscribes from usage status changes of all permissions. For details about the permissions, see [Permissions for All Applications](../../security/AccessToken/permissions-for-all.md).| -| callback | Callback<[ActiveChangeResponse](#activechangeresponse)> | No| Callback for the permission usage change event.| +| permissionList | Array<Permissions> | Yes | List of target permissions. The value must be the same as that in **on()**. If this parameter is not specified, this API will unsubscribe from usage changes for all permissions. For details about the permissions, see [Application Permissions](../../security/AccessToken/app-permissions.md).| +| callback | Callback<[ActiveChangeResponse](#activechangeresponse)> | No| Callback to unregister.| **Error codes** @@ -645,11 +893,11 @@ Represents the request for querying permission usage records. | Name | Type | Mandatory | Description | | -------- | -------------- | ---- | ---------------------------------------- | -| tokenId | number | No | Token ID of the application (invoker).
By default, all applications are queried. | -| isRemote | boolean | No | Whether to query the permission usage records of the remote device.
The default value is **false**, which means the permission usage records of the local device are queried by default.| -| deviceId | string | No | ID of the device hosting the target application.
The default value is the local device ID. | -| bundleName | string | No | Bundle name of the target application.
By default, all applications are queried.| -| permissionNames | Array<Permissions> | No | Permissions to query.
By default, the usage records of all permissions are queried. | +| tokenId | number | No | Token ID of the application (caller).
By default, all applications are queried. | +| isRemote | boolean | No | Whether to query the permission usage records of the remote device.
The default value is **false**, which means the permission usage records of the local device are queried by default.| +| deviceId | string | No | ID of the device hosting the target application.
The default value is the local device ID. | +| bundleName | string | No | Bundle name of the target application.
By default, all applications are queried.| +| permissionNames | Array<Permissions> | No | Permissions to query.
By default, the usage records of all permissions are queried. | | beginTime | number | No | Start time of the query, in ms.
The default value is **0**, which means the start time is not set.| | endTime | number | No | End time of the query, in ms.
The default value is **0**, which means the end time is not set.| | flag | [PermissionUsageFlag](#permissionusageflag) | Yes | Query mode.| @@ -674,8 +922,8 @@ Represents the permission access records of an application. | Name | Type | Readable| Writable| Description | | -------- | -------------- | ---- | ---- | ---------------------------------------- | -| tokenId | number | Yes | No | Token ID of the application (invoker). | -| isRemote | boolean | Yes | No | Whether the token ID belongs to the application on a remote device. The default value is **false**.| +| tokenId | number | Yes | No | Token ID of the application (caller). | +| isRemote | boolean | Yes | No | Whether it is a distributed device. The default value is **false**, which indicates that the device is not a distributed device.| | deviceId | string | Yes | No | ID of the device hosting the target application. | | bundleName | string | Yes | No | Bundle name of the target application.| | permissionRecords | Array<[PermissionUsedRecord](#permissionusedrecord)> | Yes | No | Permission usage records of the target application. | @@ -706,10 +954,10 @@ Represents the details of a single access record. | Name | Type | Readable| Writable| Description | | -------- | -------------- | ---- | ---- | ---------------------------------------- | | status | number | Yes | No | Access status. | -| lockScreenStatus11+ | number | Yes | No | Status of the screen during the access.
- **1**: The screen is not locked when the permission is used.
- **2**: The screen is locked when the permission is used. | +| lockScreenStatus11+ | number | Yes | No | Status of the screen during the access.
- **1**: The screen is not locked when the permission is used.
- **2**: The screen is locked when the permission is used. | | timestamp | number | Yes | No | Access timestamp, in ms.| | accessDuration | number | Yes | No | Access duration, in ms. | -| count11+ | number | Yes| No | Number of successful or failed accesses. +| count11+ | number | Yes| No | Number of successful or failed accesses.| | usedType12+ | [PermissionUsedType](#permissionusedtype12) | Yes| No | Means for using the sensitive permission.| ## PermissionActiveStatus @@ -732,10 +980,12 @@ Defines the detailed permission usage information. | Name | Type | Readable| Writable| Description | | -------------- | ---------------------- | ---- | ---- | --------------------- | -| tokenId | number | Yes | No | Token ID of the application. | -| permissionName | Permissions | Yes | No | Name of the permission.| +| callingTokenId18+ | number | Yes | No | Token ID of the caller. This parameter is invalid when **activeStatus** is **INACTIVE**.| +| tokenId | number | Yes | No | Token ID of the application whose permission usage changes are subscribed to. | +| permissionName | Permissions | Yes | No | Permissions whose usage status changes.| | deviceId | string | Yes | No | Device ID. | | activeStatus | [PermissionActiveStatus](#permissionactivestatus) | Yes | No | Permission usage status. | +| usedType18+ | [PermissionUsedType](#permissionusedtype12) | Yes | No | Sensitive permission access mode. This parameter is invalid when **activeStatus** is **INACTIVE**.| ## PermissionUsedType12+ @@ -757,9 +1007,9 @@ Represents detailed information about the use of a permission. | Name | Type | Readable| Writable| Description | | -------------- | ---------------------- | ---- | ---- | --------------------- | -| tokenId | number | Yes | No | ID of the application that uses the sensitive permission.| +| tokenId | number | Yes | No | Token ID of the application that uses the sensitive permission.| | permissionName | Permissions | Yes | No | Name of the sensitive permission.| -| usedType | [PermissionUsedType](#permissionusedtype12) | Yes| No | Means for using the sensitive permission.| +| usedType | [PermissionUsedType](#permissionusedtype12) | Yes| No | Access mode of the sensitive permission.| ## AddPermissionUsedRecordOptions12+ @@ -769,4 +1019,4 @@ Represents the options for adding a permission usage record. | Name | Type | Readable| Writable| Description | | -------------- | ---------------------- | ---- | ---- | --------------------- | -| usedType | [PermissionUsedType](#permissionusedtype12) | Yes| No | Means for using the sensitive permission.| +| usedType | [PermissionUsedType](#permissionusedtype12) | Yes| No | Access mode of the sensitive permission.| diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-screenLockFileManager-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-screenLockFileManager-sys.md index a270e4c5eaf142e9fe33a7e84469c6602db53429..666fafe49ae5fd666988de298ab4183ed290f36a 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-screenLockFileManager-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-screenLockFileManager-sys.md @@ -1,6 +1,6 @@ # @ohos.ability.screenLockFileManager (Sensitive Data Access Management Under Lock Screen) (System API) -Once the screen is locked, the keys for sensitive data are destroyed, preventing any read or write operations on that data. These keys can be restored only after the screen is unlocked. To facilitate data access on the lock screen, the screenLockFileManager module has been introduced. This module provides APIs to request and revoke the permission to access sensitive data on the lock screen, thereby managing sensitive data access securely. +Once the screen is locked, the keys for sensitive data are destroyed, preventing any read or write operations on that data. These keys can be restored only after the screen is unlocked. To facilitate data access on the lock screen, the screenLockFileManager module has been introduced. This module provides APIs to request and release the permission to access sensitive data on the lock screen, thereby managing sensitive data access securely. > **NOTE** > - The initial APIs of this module are supported since API version 12. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -48,7 +48,7 @@ Requests the permission to access a specified type of sensitive data on the lock | Type | Description | | ----------------------------------------------------------- | ------------------------------------- | -| [AccessStatus](js-apis-screenLockFileManager.md#accessstatus) | Sensitive data access status.| +| [AccessStatus](js-apis-screenLockFileManager.md#accessstatus) | State for requesting access to sensitive data on the lock screen.| **Error codes** @@ -88,7 +88,7 @@ try { releaseAccess(dataType: DataType): ReleaseStatus -Revokes the permission to access a specified type of sensitive data on the lock screen. This API returns the result synchronously. +Releases the permission to access a specified type of sensitive data on the lock screen. This API returns the result synchronously. **System API**: This is a system API. @@ -106,7 +106,7 @@ Revokes the permission to access a specified type of sensitive data on the lock | Type | Description | | ------------------------------------------------------------ | ------------------------------ | -| [ReleaseStatus](js-apis-screenLockFileManager.md#releasestatus) | Type of the operation used to revoke the permission to access sensitive data on the lock screen.| +| [ReleaseStatus](js-apis-screenLockFileManager.md#releasestatus) | State for releasing access permissions to sensitive data on the lock screen.| **Error codes** @@ -126,7 +126,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -// Revoke the permission to access media data on the lock screen. +// Release the permission to access media data on the lock screen. import { screenLockFileManager } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; @@ -141,3 +141,63 @@ try { hilog.error(0x0000, 'testTag', 'releaseAccess failed: %{public}s', message); } ``` + +## screenLockFileManager.queryAppKeyState18+ + +queryAppKeyState(dataType: DataType): KeyStatus + +Obtains the state of access permissions for a specified type of sensitive data on the lock screen. This API returns the result synchronously. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.ACCESS_SCREEN_LOCK_MEDIA_DATA or ohos.permission.ACCESS_SCREEN_LOCK_ALL_DATA + +**System capability**: SystemCapability.Security.ScreenLockFileManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ---------------------------- | +| dataType | [DataType](#datatype) | Yes | Type of sensitive data that is accessible on the lock screen.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ------------------------------ | +| [KeyStatus](js-apis-screenLockFileManager.md#keystatus18) | State of access permissions for sensitive data on the lock screen.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [ohos.screenLockFileManager](errorcode-screenLockFileManager.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 201 | Permission verification failed, usually returned by VerifyAccessToken. | +| 202 | Permission verification failed, application which is not a system application uses system API. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 801 | The specified SystemCapability name was not found. | +| 29300001 | Invalid parameter. | +| 29300002 | The system ability work abnormally. | + +**Example** + +```ts +// Obtain the state of access permissions for media data on the lock screen. +import { screenLockFileManager } from '@kit.AbilityKit'; +import { BusinessError } from '@kit.BasicServicesKit'; +import { hilog } from '@kit.PerformanceAnalysisKit'; + +try { + let keyStatus = screenLockFileManager.queryAppKeyState(screenLockFileManager.DataType.MEDIA_DATA); + if (keyStatus === screenLockFileManager.KeyStatus.KEY_NOT_EXIST) { + hilog.info(0x0000, 'testTag', 'Key does not exist.'); + } else if (keyStatus === screenLockFileManager.KeyStatus.KEY_RELEASED) { + hilog.info(0x0000, 'testTag', 'Key has been released.'); + } else if (keyStatus === screenLockFileManager.KeyStatus.KEY_EXIST) { + hilog.info(0x0000, 'testTag', 'Key exists.'); + } +} catch (err) { + let message = (err as BusinessError).message; + hilog.error(0x0000, 'testTag', 'queryAppKeyState failed: %{public}s', message); +} +``` diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-screenLockFileManager.md b/en/application-dev/reference/apis-ability-kit/js-apis-screenLockFileManager.md index 300d9b9f9705d30e4670a9b1335881a589864578..0ef0f9ae5f6d4dd759f453bb9eb230a4fdcb4620 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-screenLockFileManager.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-screenLockFileManager.md @@ -1,6 +1,6 @@ # @ohos.ability.screenLockFileManager (Sensitive Data Access Management Under Lock Screen) -Once the screen is locked, the keys for sensitive data are destroyed, preventing any read or write operations on that data. These keys can be restored only after the screen is unlocked. To facilitate data access on the lock screen, the screenLockFileManager module has been introduced. This module provides APIs to request and revoke the permission to access sensitive data on the lock screen, thereby managing sensitive data access securely. +Once the screen is locked, the keys for sensitive data are destroyed, preventing any read or write operations on that data. These keys can be restored only after the screen is unlocked. To facilitate data access on the lock screen, the screenLockFileManager module has been introduced. This module provides APIs to request and release the permission to access sensitive data on the lock screen, thereby managing sensitive data access securely. > **NOTE** > @@ -14,26 +14,38 @@ import { screenLockFileManager } from '@kit.AbilityKit'; ## AccessStatus -Enumerates the statuses available for access to sensitive data on the lock screen. +Enumerates the statuses for requesting access to sensitive data on the lock screen. **System capability**: SystemCapability.Security.ScreenLockFileManager | Name | Value | Description | | -------------- | ---- | ------------------------ | -| ACCESS_DENIED | -1 | Denies access to sensitive data on the lock screen.| -| ACCESS_GRANTED | 0 | Allows access to sensitive data on the lock screen. | +| ACCESS_DENIED | -1 | Access to sensitive data on the lock screen is denied.| +| ACCESS_GRANTED | 0 | Access to sensitive data on the lock screen is granted. | ## ReleaseStatus -Enumerates the types of operations used to revoke the permission to access sensitive data on the lock screen. +Enumerates the statuses for releasing access permissions to sensitive data on the lock screen. **System capability**: SystemCapability.Security.ScreenLockFileManager | Name| Value| Description| |-----------------|----|----| -| RELEASE_DENIED | -1 | Revokes the permission that denies access to sensitive data on the lock screen.| -| RELEASE_GRANTED | 0 | Revokes the permission that allows access to sensitive data on the lock screen. | +| RELEASE_DENIED | -1 | Release of access to sensitive data on the lock screen is denied.| +| RELEASE_GRANTED | 0 | Release of access to sensitive data on the lock screen is granted. | + +## KeyStatus18+ + +Enumerates the statuses for access permissions for sensitive data on the lock screen. + + **System capability**: SystemCapability.Security.ScreenLockFileManager + +| Name| Value| Description| +|-----------------|----|----| +| KEY_NOT_EXIST | -2 | The application has not enabled sensitive data protection on the lock screen.| +| KEY_RELEASED | -1 | The access permission for sensitive data on the lock screen has been released.| +| KEY_EXIST | 0 | The application can access sensitive data on the lock screen. | ## screenLockFileManager.acquireAccess @@ -47,7 +59,7 @@ Requests the permission to access sensitive data on the lock screen. This API re | Type | Description | | ----------------------------------------------------------- | ------------------------------------- | -| [AccessStatus](#accessstatus) | Sensitive data access status.| +| [AccessStatus](#accessstatus) | State for requesting access to sensitive data on the lock screen.| **Error codes** @@ -83,7 +95,7 @@ try { releaseAccess(): ReleaseStatus -Revokes the permission to access sensitive data on the lock screen. This API returns the result synchronously. +Releases the permission to access sensitive data on the lock screen. This API returns the result synchronously. **System capability**: SystemCapability.Security.ScreenLockFileManager @@ -91,7 +103,7 @@ Revokes the permission to access sensitive data on the lock screen. This API ret | Type | Description | | ------------------------------- | ------------------------------ | -| [ReleaseStatus](#releasestatus) | Type of the operation used to revoke the permission to access sensitive data on the lock screen.| +| [ReleaseStatus](#releasestatus) | State for releasing access permissions to sensitive data on the lock screen.| **Error codes** @@ -107,7 +119,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -// Revoke the permission to access sensitive data on the lock screen. +// Release the permission to access sensitive data on the lock screen. import { screenLockFileManager } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; @@ -122,3 +134,49 @@ try { hilog.error(0x0000, 'testTag', 'releaseAccess failed: %{public}s', message); } ``` + +## screenLockFileManager.queryAppKeyState18+ + +queryAppKeyState(): KeyStatus + +Obtains the state of access permissions for sensitive data on the lock screen. This API returns the result synchronously. + +**System capability**: SystemCapability.Security.ScreenLockFileManager + +**Return value** + +| Type | Description | +| ------------------------------- | ------------------------------ | +| [KeyStatus](#keystatus18) | State of access permissions for sensitive data on the lock screen.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [ohos.screenLockFileManager](errorcode-screenLockFileManager.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 801 | The specified SystemCapability name was not found. | +| 29300002 | The system ability work abnormally. | + +**Example** + +```ts +// Obtain the state of access permissions for sensitive data on the lock screen. +import { screenLockFileManager } from '@kit.AbilityKit'; +import { BusinessError } from '@kit.BasicServicesKit'; +import { hilog } from '@kit.PerformanceAnalysisKit'; + +try { + let keyStatus = screenLockFileManager.queryAppKeyState(); + if (keyStatus === screenLockFileManager.KeyStatus.KEY_NOT_EXIST) { + hilog.info(0x0000, 'testTag', 'Key does not exist.'); + } else if (keyStatus === screenLockFileManager.KeyStatus.KEY_RELEASED) { + hilog.info(0x0000, 'testTag', 'Key has been released.'); + } else if (keyStatus === screenLockFileManager.KeyStatus.KEY_EXIST) { + hilog.info(0x0000, 'testTag', 'Key exists.'); + } +} catch (err) { + let message = (err as BusinessError).message; + hilog.error(0x0000, 'testTag', 'queryAppKeyState failed: %{public}s', message); +} +``` diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-uripermissionmanager-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-uripermissionmanager-sys.md index 67047f1632f5b6c47b2d8f938e4706a1f13d425c..0185fa8f5c485c81fb6d96e1a7fa11f235887b5b 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-uripermissionmanager-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-uripermissionmanager-sys.md @@ -1,6 +1,6 @@ # @ohos.application.uriPermissionManager (URI Permission Management) (System API) -The **uriPermissionManager** module provides APIs for granting permissions on a file or revoking the granted permission from an application. The file is identified by a uniform resource identifier (URI). +The **uriPermissionManager** module provides capabilities for granting the permission on a file to another application and revoking the granted permissions. The file is identified by a uniform resource identifier (URI). > **NOTE** > @@ -20,10 +20,13 @@ import { uriPermissionManager } from '@kit.AbilityKit'; grantUriPermission(uri: string, flag: wantConstant.Flags, targetBundleName: string, callback: AsyncCallback<number>): void -Grants the URI permission to an application. The permission will be revoked once the application exits. This API uses an asynchronous callback to return the result. +Grants the URI permission to an application. If the call is successful, the application obtains the permission to access the file specified by the URI. Once the application exits, the permission will be automatically revoked. For details about how to access the file based on the URI, see [Sharing an Application File](../../file-management/share-app-file.md). This API uses an asynchronous callback to return the result. -An application can grant its own URIs to another application. If it has the ohos.permission.PROXY_AUTHORIZATION_URI permission, it can also grant the any accessible URI of another application. -**System API**: This is a system API and cannot be called by third-party applications. +> **NOTE** +> +> If an application has the ohos.permission.PROXY_AUTHORIZATION_URI permission, it can grant the accessible URIs of another application. If the application does not have this permission, it can grant only its own URI permissions. + +**System API**: This is a system API. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -33,9 +36,9 @@ An application can grant its own URIs to another application. If it has the ohos | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| uri | string | Yes| URI of the file, for example, **fileshare:///com.samples.filesharetest.FileShare/person/10**.| +| uri | string | Yes| URI of the file. The scheme has a fixed value of **file**. For details, see [FileUri](../apis-core-file-kit/js-apis-file-fileuri.md#constructor10).| | flag | [wantConstant.Flags](js-apis-app-ability-wantConstant.md#flags) | Yes| Read or write permission on the file to grant.| -| targetBundleName | string | Yes| Bundle name of the application, to which the permission is granted.| +| targetBundleName | string | Yes| Bundle name of the target application.| | callback | AsyncCallback<number> | Yes| Callback used to return the result. If the operation is successful, **0** is returned; otherwise, **-1** is returned.| **Error codes** @@ -79,10 +82,13 @@ An application can grant its own URIs to another application. If it has the ohos grantUriPermission(uri: string, flag: wantConstant.Flags, targetBundleName: string): Promise<number> -Grants the URI permission to an application. The permission will be revoked once the application exits. This API uses a promise to return the result. +Grants the URI permission to an application. If the call is successful, the application obtains the permission to access the file specified by the URI. Once the application exits, the permission will be automatically revoked. For details about how to access the file based on the URI, see [Sharing an Application File](../../file-management/share-app-file.md). This API uses a promise to return the result. + +> **NOTE** +> +> If an application has the ohos.permission.PROXY_AUTHORIZATION_URI permission, it can grant the accessible URIs of another application. If the application does not have this permission, it can grant only its own URI permissions. -An application can grant its own URIs to another application. If it has the ohos.permission.PROXY_AUTHORIZATION_URI permission, it can also grant the any accessible URI of another application. -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -92,9 +98,9 @@ An application can grant its own URIs to another application. If it has the ohos | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| uri | string | Yes| URI of the file, for example, **fileshare:///com.samples.filesharetest.FileShare/person/10**.| +| uri | string | Yes| URI of the file. The scheme has a fixed value of **file**. For details, see [FileUri](../apis-core-file-kit/js-apis-file-fileuri.md#constructor10).| | flag | [wantConstant.Flags](js-apis-app-ability-wantConstant.md#flags) | Yes| Read or write permission on the file to grant.| -| targetBundleName | string | Yes| Bundle name of the application, to which the permission is granted.| +| targetBundleName | string | Yes| Bundle name of the target application.| **Return value** @@ -142,14 +148,111 @@ An application can grant its own URIs to another application. If it has the ohos }); ``` +## uriPermissionManager.grantUriPermission14+ + +grantUriPermission(uri: string, flag: wantConstant.Flags, targetBundleName: string, appCloneIndex: number): Promise<void> + +Grants the URI permission to an application. If the call is successful, the application obtains the permission to access the file specified by the URI. Once the application exits, the permission will be automatically revoked. For details about how to access the file based on the URI, see [Sharing an Application File](../../file-management/share-app-file.md). This API uses a promise to return the result. + +> **NOTE** +> +>- If an application has the ohos.permission.PROXY_AUTHORIZATION_URI permission, it can grant the accessible URIs of another application. If the application does not have this permission, it can grant only its own URI permissions. +>- This API can be used to grant URI access permission to a cloned application. You need to specify the application bundle name and index of the cloned application. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Required permissions**: ohos.permission.PROXY_AUTHORIZATION_URI + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| uri | string | Yes| URI of the file. The scheme has a fixed value of **file**. For details, see [FileUri](../apis-core-file-kit/js-apis-file-fileuri.md#constructor10).| +| flag | [wantConstant.Flags](js-apis-app-ability-wantConstant.md#flags) | Yes| Read or write permission on the file to grant.| +| targetBundleName | string | Yes| Bundle name of the target application.| +| appCloneIndex | number | Yes| Index of the cloned application. The value range is [0, 1000]. The value **0** indicates the application itself.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + + For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | Permission denied. | +| 202 | Not System App. Interface caller is not a system app. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.| +| 16000050 | Internal error. | +| 16000058 | Invalid URI flag. | +| 16000059 | Invalid URI type. | +| 16000060 | A sandbox application cannot grant URI permission. | +| 16000081 | Get target application info failed. | + +**Example** + + ```ts + import { AbilityConstant, UIAbility, Want, wantConstant, uriPermissionManager } from '@kit.AbilityKit'; + import { fileUri } from '@kit.CoreFileKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + export default class EntryAbility extends UIAbility { + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { + } + + onForeground(): void { + let targetBundleName: string = 'com.example.demo1'; + let filePath: string = this.context.filesDir + "/test.txt"; + let uri: string = fileUri.getUriFromPath(filePath); + // grant uri permission to main application + try { + let appCloneIndex: number = 0; + uriPermissionManager.grantUriPermission(uri, wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, targetBundleName, + appCloneIndex) + .then(() => { + console.log('grantUriPermission succeeded.'); + }).catch((error: BusinessError) => { + console.error(`grantUriPermission failed. error: ${JSON.stringify(error)}.`); + }); + } catch (error) { + console.error(`grantUriPermission failed. error: ${JSON.stringify(error)}.`); + } + + // grant uri permission to clone application + try { + let appCloneIndex: number = 1; + uriPermissionManager.grantUriPermission(uri, wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, targetBundleName, + appCloneIndex) + .then(() => { + console.log('grantUriPermission succeeded.'); + }).catch((error: BusinessError) => { + console.error(`grantUriPermission failed. error: ${JSON.stringify(error)}.`); + }); + } catch (error) { + console.error(`grantUriPermission failed. error: ${JSON.stringify(error)}.`); + } + } + } + + ``` + ## uriPermissionManager.revokeUriPermission revokeUriPermission(uri: string, targetBundleName: string, callback: AsyncCallback<number>): void Revokes the URI permission from an application. This API uses an asynchronous callback to return the result. -This API can be used to revoke the URI permission of another application obtained by this application or URI permission granted by this application. -**System API**: This is a system API and cannot be called by third-party applications. +> **NOTE** +> +> This API can be used to revoke the URI permission of another application obtained by this application or URI permission granted by this application. + +**System API**: This is a system API. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -157,7 +260,7 @@ This API can be used to revoke the URI permission of another application obtaine | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| uri | string | Yes| URI of the file, for example, **fileshare:///com.samples.filesharetest.FileShare/person/10**.| +| uri | string | Yes| URI of the file. The scheme has a fixed value of **file**. For details, see [FileUri](../apis-core-file-kit/js-apis-file-fileuri.md#constructor10).| | targetBundleName | string | Yes| Bundle name of the application, from which the permission is revoked.| | callback | AsyncCallback<number> | Yes| Callback used to return the result. If the operation is successful, **0** is returned; otherwise, **-1** is returned.| @@ -192,9 +295,11 @@ revokeUriPermission(uri: string, targetBundleName: string): Promise<number> Revokes the URI permission from an application. This API uses a promise to return the result. +> **NOTE** +> +> This API can be used to revoke the URI permission of another application obtained by this application or URI permission granted by this application. -This API can be used to revoke the URI permission of another application obtained by this application or URI permission granted by this application. -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -202,8 +307,8 @@ This API can be used to revoke the URI permission of another application obtaine | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| uri | string | Yes| URI of the file, for example, **fileshare:///com.samples.filesharetest.FileShare/person/10**.| -| targetBundleName | string | Yes| Bundle name of the application, from which the permission is revoked.| +| uri | string | Yes| URI of the file. The scheme has a fixed value of **file**. For details, see [FileUri](../apis-core-file-kit/js-apis-file-fileuri.md#constructor10).| +| targetBundleName | string | Yes| Bundle name of the target application.| **Return value** @@ -239,3 +344,88 @@ This API can be used to revoke the URI permission of another application obtaine console.log('Verification failed.'); }); ``` +## uriPermissionManager.revokeUriPermission14+ + +revokeUriPermission(uri: string, targetBundleName: string, appCloneIndex: number): Promise<void> + +Revokes the URI permission from an application. This API uses a promise to return the result. + +> **NOTE** +> +>- This API can be used to revoke the URI permission of another application obtained by this application or URI permission granted by this application. +>- This API can be used to revoke the URI permissions granted to a cloned application. You need to specify the application bundle name and index of the cloned application. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| uri | string | Yes| URI of the file. The scheme has a fixed value of **file**. For details, see [FileUri](../apis-core-file-kit/js-apis-file-fileuri.md#constructor10).| +| targetBundleName | string | Yes| Bundle name of the target application.| +| appCloneIndex | number | Yes| Index of the cloned application. The value range is [0, 1000]. The value **0** indicates the application itself.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + + For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 202 | Not System App. Interface caller is not a system app. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.| +| 16000050 | Internal error. | +| 16000059 | Invalid URI type. | +| 16000081 | Get target application info failed. | + +**Example** + + ```ts + + import { AbilityConstant, UIAbility, Want, wantConstant, uriPermissionManager } from '@kit.AbilityKit'; + import { fileUri } from '@kit.CoreFileKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + export default class EntryAbility extends UIAbility { + onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { + } + + onForeground(): void { + let targetBundleName: string = 'com.example.demo1'; + let filePath: string = this.context.filesDir + "/test.txt"; + let uri: string = fileUri.getUriFromPath(filePath); + // revoke uri permission of main application + try { + let appCloneIndex: number = 0; + uriPermissionManager.revokeUriPermission(uri, targetBundleName, appCloneIndex) + .then(() => { + console.log('revokeUriPermission succeeded.'); + }).catch((error: BusinessError) => { + console.error(`revokeUriPermission failed. error: ${JSON.stringify(error)}.`); + }); + } catch (error) { + console.error(`revokeUriPermission failed. error: ${JSON.stringify(error)}.`); + } + + // revoke uri permission of clone application + try { + let appCloneIndex: number = 0; + uriPermissionManager.revokeUriPermission(uri, targetBundleName, appCloneIndex) + .then(() => { + console.log('revokeUriPermission succeeded.'); + }).catch((error: BusinessError) => { + console.error(`revokeUriPermission failed. error: ${JSON.stringify(error)}.`); + }); + } catch (error) { + console.error(`revokeUriPermission failed. error: ${JSON.stringify(error)}.`); + } + } + } + ``` diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-wantAgent-sys.md b/en/application-dev/reference/apis-ability-kit/js-apis-wantAgent-sys.md index d583f066dc76519727f67e681b17721d4bca86c7..91d596e15499660caa21f50fd648d18bffcf5cf9 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-wantAgent-sys.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-wantAgent-sys.md @@ -22,7 +22,7 @@ Obtains the Want in a **WantAgent** object. This API uses an asynchronous callba **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -94,7 +94,7 @@ Obtains the Want in a **WantAgent** object. This API uses a promise to return th **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** diff --git a/en/application-dev/reference/apis-ability-kit/js-apis-wantAgent.md b/en/application-dev/reference/apis-ability-kit/js-apis-wantAgent.md index 093a7c8ce7211f8ba6d30fc5066a6baa1ab3fd7f..8ef149b015e86fe57e40e880f0a72bd7b948517f 100644 --- a/en/application-dev/reference/apis-ability-kit/js-apis-wantAgent.md +++ b/en/application-dev/reference/apis-ability-kit/js-apis-wantAgent.md @@ -643,7 +643,7 @@ Checks whether two **WantAgent** objects are equal to determine whether the same | ---------- | ------------------------ | ---- | --------------------------------------- | | agent | WantAgent | Yes | The first **WantAgent** object. | | otherAgent | WantAgent | Yes | **WantAgent** object. | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that the two **WantAgent** objects are equal, and **false** means the opposite.| **Example** @@ -724,7 +724,7 @@ Checks whether two **WantAgent** objects are equal to determine whether the same | Type | Description | | ----------------------------------------------------------- | ------------------------------------------------------------ | -| Promise\ | Promise used to return the result.| +| Promise\ | Promise used to return the result. The value **true** means that the two **WantAgent** objects are equal, and **false** means the opposite.| **Example** @@ -818,3 +818,17 @@ wantAgent.getWantAgent({ | finalCode | number | Yes | Request code that triggers the **WantAgent** object.| | finalData | string | Yes | Final data collected by the common event. | | extraInfo | { [key: string]: any } | No | Extra information. | + +## WantAgent + +type WantAgent = object + +Defines the **WantAgent** object. + +**Atomic service API**: This API can be used in atomic services since API version 12. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Type| Description| +| --- | --- | +| object | **WantAgent** object.| diff --git a/en/application-dev/reference/apis-ability-kit/native__child__process_8h.md b/en/application-dev/reference/apis-ability-kit/native__child__process_8h.md index 3e172834806c17866d2a28dd0776aa315b45cad0..cfcb67c512c77605513470fedf6c4bc4f4ffd47c 100644 --- a/en/application-dev/reference/apis-ability-kit/native__child__process_8h.md +++ b/en/application-dev/reference/apis-ability-kit/native__child__process_8h.md @@ -44,7 +44,8 @@ The **native_child_process.h** file declares the APIs used to create a native ch ### Functions -| Name | Description | -| ------------------------------------------------------------ | ------------------------------------------------------------ | -| int [OH_Ability_CreateNativeChildProcess](c-apis-ability-childprocess.md#oh_ability_createnativechildprocess) (const char \*libName, [OH_Ability_OnNativeChildProcessStarted](c-apis-ability-childprocess.md#oh_ability_onnativechildprocessstarted) onProcessStarted) | Creates a child process, loads the specified dynamic library file, and returns the startup result asynchronously through a callback parameter. The callback notification is an independent thread. When implementing the callback function, pay attention to thread synchronization and do not perform time-consuming operations to avoid long-time blocking.
NOTE
Currently, this function is valid only for 2-in-1 devices, and a process can start only one native child process by using this function. | -| [Ability_NativeChildProcess_ErrCode](c-apis-ability-childprocess.md#ability_nativechildprocess_errcode) [OH_Ability_StartNativeChildProcess](c-apis-ability-childprocess.md#oh_ability_startnativechildprocess)(const char\* entry, [NativeChildProcess_Args](c-apis-ability-childprocess.md#nativechildprocess_args) args, [NativeChildProcess_Options](c-apis-ability-childprocess.md#nativechildprocess_options) options, int32_t *pid) | Starts a child process, loads the specified dynamic library file, and calls the entry function. Arguments can be passed to the child process.
NOTE
Currently, this function is valid only for 2-in-1 devices and tablets. | +| Name | Description | +| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | +| int [OH_Ability_CreateNativeChildProcess](c-apis-ability-childprocess.md#oh_ability_createnativechildprocess) (const char \*libName, [OH_Ability_OnNativeChildProcessStarted](c-apis-ability-childprocess.md#oh_ability_onnativechildprocessstarted) onProcessStarted) | Creates a child process, loads the specified dynamic library file, and returns the startup result asynchronously through a callback parameter. The callback notification is an independent thread. When implementing the callback function, pay attention to thread synchronization and do not perform time-consuming operations to avoid long-time blocking.
NOTE
Currently, this function is valid only for 2-in-1 devices. Since API version 15, a single process supports a maximum of 50 native child processes. In API version 14 and earlier versions, a single process supports only one native child process.| +| [Ability_NativeChildProcess_ErrCode](c-apis-ability-childprocess.md#ability_nativechildprocess_errcode) [OH_Ability_StartNativeChildProcess](c-apis-ability-childprocess.md#oh_ability_startnativechildprocess)(const char\* entry, [NativeChildProcess_Args](c-apis-ability-childprocess.md#nativechildprocess_args) args, [NativeChildProcess_Options](c-apis-ability-childprocess.md#nativechildprocess_options) options, int32_t *pid) | Starts a child process, loads the specified dynamic library file, and calls the entry function. Arguments can be passed to the child process.
NOTE
Currently, this function is valid only for 2-in-1 devices and tablets.| +| [NativeChildProcess_Args](c-apis-ability-childprocess.md#nativechildprocess_args)* [OH_Ability_GetCurrentChildProcessArgs](c-apis-ability-childprocess.md#oh_ability_getcurrentchildprocessargs)() | Used by a child process, after being started by calling [OH_Ability_StartNativeChildProcess](#oh_ability_startnativechildprocess), to obtain the startup parameter [NativeChildProcess_Args](c-apis-ability-childprocess.md#nativechildprocess_args) from any .so file or child thread.
NOTE
Currently, this function is valid only for 2-in-1 devices and tablets.| diff --git a/en/application-dev/reference/apis-ability-kit/start__options_8h.md b/en/application-dev/reference/apis-ability-kit/start__options_8h.md new file mode 100644 index 0000000000000000000000000000000000000000..2cf96f8ff456b9d68f311719b13176f5fca06207 --- /dev/null +++ b/en/application-dev/reference/apis-ability-kit/start__options_8h.md @@ -0,0 +1,65 @@ +# start_options.h + + +## Overview + +The **start_options.h** file declares the StartOptions struct and related functions. + +**File to include**: + +**Library**: libability_runtime.so + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Since**: 17 + +**Related module**: [AbilityRuntime](_ability_runtime.md) + +## Summary + +### Files + +| Name | Description | +| --------------------------------------------------- | ------------------------------------------------------------ | +| [start_options.h](start__options_8h.md) | Declares the StartOptions struct.
**File to include**:
**Library**: libability_runtime.so| + +### Structs + +| Name | Description | +| ------------------------------------------------------------ | ---------------------------- | +| [AbilityRuntime_StartOptions](_ability_runtime.md#abilityruntime_startoptions) | StartOptions struct.| + +### Functions + +| Name | Description | +| ------------------------------------------------------------ | ---------------------------- | +| [AbilityRuntime_StartOptions*](_ability_runtime.md#abilityruntime_startoptions) [OH_AbilityRuntime_CreateStartOptions](_ability_runtime.md#oh_abilityruntime_createstartoptions)(void) | Creates the StartOptions struct required for starting the UIAbility of the current application.| +| [AbilityRuntime_ErrorCode](_ability_runtime.md#abilityruntime_errorcode) [OH_AbilityRuntime_DestroyStartOptions](_ability_runtime.md#oh_abilityruntime_destroystartoptions)([AbilityRuntime_StartOptions](_ability_runtime.md#abilityruntime_startoptions) **startOptions) | Destroys a StartOptions struct.| +| [AbilityRuntime_ErrorCode](_ability_runtime.md#abilityruntime_errorcode) [OH_AbilityRuntime_SetStartOptionsWindowMode](_ability_runtime.md#oh_abilityruntime_setstartoptionswindowmode)([AbilityRuntime_StartOptions](_ability_runtime.md#abilityruntime_startoptions) *startOptions, [AbilityRuntime_WindowMode](_ability_runtime.md#abilityruntime_windowmode) windowMode) | Sets the window mode for starting an ability.| +| [AbilityRuntime_ErrorCode](_ability_runtime.md#abilityruntime_errorcode) [OH_AbilityRuntime_GetStartOptionsWindowMode](_ability_runtime.md#oh_abilityruntime_getstartoptionswindowmode)([AbilityRuntime_StartOptions](_ability_runtime.md#abilityruntime_startoptions) *startOptions, [AbilityRuntime_WindowMode](_ability_runtime.md#abilityruntime_windowmode) &windowMode) | Obtains the window mode for starting an ability.| +| [AbilityRuntime_ErrorCode](_ability_runtime.md#abilityruntime_errorcode) [OH_AbilityRuntime_SetStartOptionsDisplayId](_ability_runtime.md#oh_abilityruntime_setstartoptionsdisplayid)([AbilityRuntime_StartOptions](_ability_runtime.md#abilityruntime_startoptions) *startOptions, int32_t displayId) | Sets the ID of the display where the window is launched when the ability is started.| +| [AbilityRuntime_ErrorCode](_ability_runtime.md#abilityruntime_errorcode) [OH_AbilityRuntime_GetStartOptionsDisplayId](_ability_runtime.md#oh_abilityruntime_getstartoptionsdisplayid)([AbilityRuntime_StartOptions](_ability_runtime.md#abilityruntime_startoptions) *startOptions, int32_t &displayId) | Obtains the ID of the display where the window is launched when the ability is started.| +| [AbilityRuntime_ErrorCode](_ability_runtime.md#abilityruntime_errorcode) [OH_AbilityRuntime_SetStartOptionsWithAnimation](_ability_runtime.md#oh_abilityruntime_setstartoptionswithanimation)([AbilityRuntime_StartOptions](_ability_runtime.md#abilityruntime_startoptions) *startOptions, bool withAnimation) | Sets whether to use animation effects when an ability is started.| +| [AbilityRuntime_ErrorCode](_ability_runtime.md#abilityruntime_errorcode) [OH_AbilityRuntime_GetStartOptionsWithAnimation](_ability_runtime.md#oh_abilityruntime_getstartoptionswithanimation)([AbilityRuntime_StartOptions](_ability_runtime.md#abilityruntime_startoptions) *startOptions, bool &withAnimation) | Checks whether animation effects are used when an ability is started.| +| [AbilityRuntime_ErrorCode](_ability_runtime.md#abilityruntime_errorcode) [OH_AbilityRuntime_SetStartOptionsWindowLeft](_ability_runtime.md#oh_abilityruntime_setstartoptionswindowleft)([AbilityRuntime_StartOptions](_ability_runtime.md#abilityruntime_startoptions) *startOptions, int32_t windowLeft) | Sets the left position of the window when the ability is started, in px.| +| [AbilityRuntime_ErrorCode](_ability_runtime.md#abilityruntime_errorcode) [OH_AbilityRuntime_GetStartOptionsWindowLeft](_ability_runtime.md#oh_abilityruntime_getstartoptionswindowleft)([AbilityRuntime_StartOptions](_ability_runtime.md#abilityruntime_startoptions) *startOptions, int32_t &windowLeft) | Obtains the left position of the window when the ability is started, in px.| +| [AbilityRuntime_ErrorCode](_ability_runtime.md#abilityruntime_errorcode) [OH_AbilityRuntime_SetStartOptionsWindowTop](_ability_runtime.md#oh_abilityruntime_setstartoptionswindowtop)([AbilityRuntime_StartOptions](_ability_runtime.md#abilityruntime_startoptions) *startOptions, int32_t windowTop) | Sets the top position of the window when the ability is started, in px.| +| [AbilityRuntime_ErrorCode](_ability_runtime.md#abilityruntime_errorcode) [OH_AbilityRuntime_GetStartOptionsWindowTop](_ability_runtime.md#oh_abilityruntime_getstartoptionswindowtop)([AbilityRuntime_StartOptions](_ability_runtime.md#abilityruntime_startoptions) *startOptions, int32_t &windowTop) | Obtains the top position of the window when the ability is started, in px.| +| [AbilityRuntime_ErrorCode](_ability_runtime.md#abilityruntime_errorcode) [OH_AbilityRuntime_SetStartOptionsWindowHeight](_ability_runtime.md#oh_abilityruntime_setstartoptionswindowheight)([AbilityRuntime_StartOptions](_ability_runtime.md#abilityruntime_startoptions) *startOptions, int32_t windowHeight) | Sets the height of the window when the ability is started, in px.| +| [AbilityRuntime_ErrorCode](_ability_runtime.md#abilityruntime_errorcode) [OH_AbilityRuntime_GetStartOptionsWindowHeight](_ability_runtime.md#oh_abilityruntime_getstartoptionswindowheight)([AbilityRuntime_StartOptions](_ability_runtime.md#abilityruntime_startoptions) *startOptions, int32_t &windowHeight) | Obtains the height of the window when the ability is started, in px.| +| [AbilityRuntime_ErrorCode](_ability_runtime.md#abilityruntime_errorcode) [OH_AbilityRuntime_SetStartOptionsWindowWidth](_ability_runtime.md#oh_abilityruntime_setstartoptionswindowwidth)([AbilityRuntime_StartOptions](_ability_runtime.md#abilityruntime_startoptions) *startOptions, int32_t windowWidth) | Sets the width of the window when the ability is started, in px.| +| [AbilityRuntime_ErrorCode](_ability_runtime.md#abilityruntime_errorcode) [OH_AbilityRuntime_GetStartOptionsWindowWidth](_ability_runtime.md#oh_abilityruntime_getstartoptionswindowwidth)([AbilityRuntime_StartOptions](_ability_runtime.md#abilityruntime_startoptions) *startOptions, int32_t &windowWidth) | Obtains the width of the window when the ability is started, in px.| +| [AbilityRuntime_ErrorCode](_ability_runtime.md#abilityruntime_errorcode) [OH_AbilityRuntime_SetStartOptionsStartWindowIcon](_ability_runtime.md#oh_abilityruntime_setstartoptionsstartwindowicon)([AbilityRuntime_StartOptions](_ability_runtime.md#abilityruntime_startoptions) *startOptions, [OH_PixelmapNative](../apis-image-kit/_image___native_module.md#oh_pixelmapnative) *startWindowIcon) | Sets the startup icon of the window when the ability is started.| +| [AbilityRuntime_ErrorCode](_ability_runtime.md#abilityruntime_errorcode) [OH_AbilityRuntime_GetStartOptionsStartWindowIcon](_ability_runtime.md#oh_abilityruntime_getstartoptionsstartwindowicon)([AbilityRuntime_StartOptions](_ability_runtime.md#abilityruntime_startoptions) *startOptions, [OH_PixelmapNative](../apis-image-kit/_image___native_module.md#oh_pixelmapnative) **startWindowIcon) | Obtains the startup icon of the window when the ability is started.| +| [AbilityRuntime_ErrorCode](_ability_runtime.md#abilityruntime_errorcode) [OH_AbilityRuntime_SetStartOptionsStartWindowBackgroundColor](_ability_runtime.md#oh_abilityruntime_setstartoptionsstartwindowbackgroundcolor)([AbilityRuntime_StartOptions](_ability_runtime.md#abilityruntime_startoptions) *startOptions, const char *startWindowBackgroundColor) | Sets the background color of the window when the ability is started.| +| [AbilityRuntime_ErrorCode](_ability_runtime.md#abilityruntime_errorcode) [OH_AbilityRuntime_GetStartOptionsStartWindowBackgroundColor](_ability_runtime.md#oh_abilityruntime_getstartoptionsstartwindowbackgroundcolor)([AbilityRuntime_StartOptions](_ability_runtime.md#abilityruntime_startoptions) *startOptions, char **startWindowBackgroundColor, size_t &size) | Obtains the background color of the window when the ability is started.| +| [AbilityRuntime_ErrorCode](_ability_runtime.md#abilityruntime_errorcode) [OH_AbilityRuntime_SetStartOptionsSupportedWindowModes](_ability_runtime.md#oh_abilityruntime_setstartoptionssupportedwindowmodes)([AbilityRuntime_StartOptions](_ability_runtime.md#abilityruntime_startoptions) *startOptions, [AbilityRuntime_SupportedWindowMode](_ability_runtime.md#abilityruntime_supportedwindowmode) *supportedWindowModes, size_t size) | Sets the window modes supported by the ability when it is started.| +| [AbilityRuntime_ErrorCode](_ability_runtime.md#abilityruntime_errorcode) [OH_AbilityRuntime_GetStartOptionsSupportedWindowModes](_ability_runtime.md#oh_abilityruntime_getstartoptionssupportedwindowmodes)([AbilityRuntime_StartOptions](_ability_runtime.md#abilityruntime_startoptions) *startOptions, [AbilityRuntime_SupportedWindowMode](_ability_runtime.md#abilityruntime_supportedwindowmode) **supportedWindowModes, size_t &size) | Obtains the window modes supported by the ability when it is started.| +| [AbilityRuntime_ErrorCode](_ability_runtime.md#abilityruntime_errorcode) [OH_AbilityRuntime_SetStartOptionsMinWindowWidth](_ability_runtime.md#oh_abilityruntime_setstartoptionsminwindowwidth)([AbilityRuntime_StartOptions](_ability_runtime.md#abilityruntime_startoptions) *startOptions, int32_t minWindowWidth) | Sets the minimum window width for starting the ability, in vp.| +| [AbilityRuntime_ErrorCode](_ability_runtime.md#abilityruntime_errorcode) [OH_AbilityRuntime_GetStartOptionsMinWindowWidth](_ability_runtime.md#oh_abilityruntime_getstartoptionsminwindowwidth)([AbilityRuntime_StartOptions](_ability_runtime.md#abilityruntime_startoptions) *startOptions, int32_t &minWindowWidth) | Obtains the minimum window width for starting the ability, in vp.| +| [AbilityRuntime_ErrorCode](_ability_runtime.md#abilityruntime_errorcode) [OH_AbilityRuntime_SetStartOptionsMaxWindowWidth](_ability_runtime.md#oh_abilityruntime_setstartoptionsmaxwindowwidth)([AbilityRuntime_StartOptions](_ability_runtime.md#abilityruntime_startoptions) *startOptions, int32_t maxWindowWidth) | Sets the maximum window width for starting the ability, in vp.| +| [AbilityRuntime_ErrorCode](_ability_runtime.md#abilityruntime_errorcode) [OH_AbilityRuntime_GetStartOptionsMaxWindowWidth](_ability_runtime.md#oh_abilityruntime_getstartoptionsmaxwindowwidth)([AbilityRuntime_StartOptions](_ability_runtime.md#abilityruntime_startoptions) *startOptions, int32_t &maxWindowWidth) | Obtains the maximum window width for starting the ability, in vp.| +| [AbilityRuntime_ErrorCode](_ability_runtime.md#abilityruntime_errorcode) [OH_AbilityRuntime_SetStartOptionsMinWindowHeight](_ability_runtime.md#oh_abilityruntime_setstartoptionsminwindowheight)([AbilityRuntime_StartOptions](_ability_runtime.md#abilityruntime_startoptions) *startOptions, int32_t minWindowHeight) | Sets the minimum window height for starting the ability, in vp.| +| [AbilityRuntime_ErrorCode](_ability_runtime.md#abilityruntime_errorcode) [OH_AbilityRuntime_GetStartOptionsMinWindowHeight](_ability_runtime.md#oh_abilityruntime_getstartoptionsminwindowheight)([AbilityRuntime_StartOptions](_ability_runtime.md#abilityruntime_startoptions) *startOptions, int32_t &minWindowHeight) | Obtains the minimum window height for starting the ability, in vp.| +| [AbilityRuntime_ErrorCode](_ability_runtime.md#abilityruntime_errorcode) [OH_AbilityRuntime_SetStartOptionsMaxWindowHeight](_ability_runtime.md#oh_abilityruntime_setstartoptionsmaxwindowheight)([AbilityRuntime_StartOptions](_ability_runtime.md#abilityruntime_startoptions) *startOptions, int32_t maxWindowHeig) | Sets the maximum window height for starting the ability, in vp.| +| [AbilityRuntime_ErrorCode](_ability_runtime.md#abilityruntime_errorcode) [OH_AbilityRuntime_GetStartOptionsMaxWindowHeight](_ability_runtime.md#oh_abilityruntime_getstartoptionsmaxwindowheight)([AbilityRuntime_StartOptions](_ability_runtime.md#abilityruntime_startoptions) *startOptions, int32_t &maxWindowHeight) | Obtains the maximum window height for starting the ability, in vp.| diff --git a/en/application-dev/reference/apis-ability-kit/want__8h.md b/en/application-dev/reference/apis-ability-kit/want__8h.md new file mode 100644 index 0000000000000000000000000000000000000000..069a8cc6a989baa3e741064350d525706113851c --- /dev/null +++ b/en/application-dev/reference/apis-ability-kit/want__8h.md @@ -0,0 +1,55 @@ +# want.h + + +## Overview + +Want is a carrier for information transfer between objects (application components). Want can be used as a parameter of **startAbility** to specify a startup target and information that needs to be carried during startup, for example, **bundleName** and **abilityName**, which respectively indicate the bundle name of the target ability and the ability name in the bundle. When ability A needs to start ability B and transfer some data to ability B, it can use Want a carrier to transfer the data. + +**File to include**: + +**Library**: libability_base_want.so + +**System capability**: SystemCapability.Ability.AbilityBase + +**Since**: 15 + +**Related module**: [AbilityBase](_ability_base.md) + + +## Summary + +### Files + +| Name | Description | +| --------------------------------------------- | ------------------------------------------------------------ | +| [want.h](want__8h.md) | Declare Want-related capabilities.
**File to include**:
**Library**: libability_base_want.so| + + +### Structs + +| Name | Description | +| ------------------------------------------------------------ | ---------------------------- | +| [AbilityBase_Element](_ability_base_element.md#abilitybase_element) {
char* bundleName;
char* moduleName;
char* abilityName;
} | Element struct.| +| [AbilityBase_Want](_ability_base.md#abilitybase_want) | Want struct.| + + +### Functions + +| Name | Description | +| ------------------------------------------------------------ | ---------------------------- | +| [AbilityBase_Want](_ability_base.md#abilitybase_want)* [OH_AbilityBase_CreateWant](_ability_base.md#oh_abilitybase_createwant)([AbilityBase_Element](_ability_base_element.md#abilitybase_element) element) | Creates Want.| +| [AbilityBase_ErrorCode](_ability_base.md#abilitybase_errorcode) [OH_AbilityBase_DestroyWant](_ability_base.md#oh_abilitybase_destroywant)([AbilityBase_Want](_ability_base.md#abilitybase_want)* want) | Destroys Want. Want cannot be used after being destroyed. Otherwise, undefined behavior may occur.| +| [AbilityBase_ErrorCode](_ability_base.md#abilitybase_errorcode) [OH_AbilityBase_SetWantElement](_ability_base.md#oh_abilitybase_setwantelement)([AbilityBase_Want](_ability_base.md#abilitybase_want)* want, [AbilityBase_Element](_ability_base_element.md#abilitybase_element) element) | Sets the Element struct, which consists of **bundleName**, **moduleName**, and **abilityName** in Want.| +| [AbilityBase_ErrorCode](_ability_base.md#abilitybase_errorcode) [OH_AbilityBase_GetWantElement](_ability_base.md#oh_abilitybase_getwantelement)([AbilityBase_Want](_ability_base.md#abilitybase_want)* want, [AbilityBase_Element](_ability_base_element.md#abilitybase_element)* element) | Obtains the Element struct, which consists of **bundleName**, **moduleName**, and **abilityName** in Want.| +| [AbilityBase_ErrorCode](_ability_base.md#abilitybase_errorcode) [OH_AbilityBase_SetWantCharParam](_ability_base.md#oh_abilitybase_setwantcharparam)([AbilityBase_Want](_ability_base.md#abilitybase_want)* want, const char* key, const char* value) | Sets **Param** in Want. For details about **Param**, see [parameters in Want](js-apis-inner-ability-want.md).| +| [AbilityBase_ErrorCode](_ability_base.md#abilitybase_errorcode) [OH_AbilityBase_GetWantCharParam](_ability_base.md#oh_abilitybase_getwantcharparam)([AbilityBase_Want](_ability_base.md#abilitybase_want)* want, const char* key, char* value, size_t valueSize) | Obtains **Param** set by [OH_AbilityBase_SetWantCharParam](#oh_abilitybase_setwantcharparam) in Want.| +| [AbilityBase_ErrorCode](_ability_base.md#abilitybase_errorcode) [OH_AbilityBase_AddWantFd](_ability_base.md#oh_abilitybase_addwantfd)([AbilityBase_Want](_ability_base.md#abilitybase_want)* want, const char* key, int32_t fd) | Adds a Want file descriptor. The file descriptor can be obtained through [fs.open](../apis-core-file-kit/js-apis-file-fs.md#fsopen).| +| [AbilityBase_ErrorCode](_ability_base.md#abilitybase_errorcode) [OH_AbilityBase_GetWantFd](_ability_base.md#oh_abilitybase_getwantfd)([AbilityBase_Want](_ability_base.md#abilitybase_want)* want, const char* key, int32_t* fd) | Obtains a Want file descriptor.| +| [AbilityBase_ErrorCode](_ability_base.md#abilitybase_errorcode) [OH_AbilityBase_SetWantUri](_ability_base.md#oh_abilitybase_setwanturi)([AbilityBase_Want](#abilitybase_want)* want, const char* uri) | Sets **uri** in Want. For details about **uri**, see [uri in Want](js-apis-app-ability-want.md).| +| [AbilityBase_ErrorCode](_ability_base.md#abilitybase_errorcode) [OH_AbilityBase_GetWantUri](_ability_base.md#oh_abilitybase_getwanturi)([AbilityBase_Want](#abilitybase_want)* want, char* uri, size_t uriSize) | Obtains **uri** set in Want. For details about **uri**, see [uri in Want](js-apis-app-ability-want.md).| +| [AbilityBase_ErrorCode](_ability_base.md#abilitybase_errorcode) [OH_AbilityBase_SetWantInt32Param](_ability_base.md#oh_abilitybase_setwantint32param)([AbilityBase_Want](#abilitybase_want)* want, const char* key, int32_t value) | Sets a value of the int32_t type in Want.| +| [AbilityBase_ErrorCode](_ability_base.md#abilitybase_errorcode) [OH_AbilityBase_GetWantInt32Param](_ability_base.md#oh_abilitybase_getwantint32param)([AbilityBase_Want](#abilitybase_want)* want, const char* key, int32_t* value) | Obtains a value of the int32_t type set in Want.| +| [AbilityBase_ErrorCode](_ability_base.md#abilitybase_errorcode) [OH_AbilityBase_SetWantBoolParam](_ability_base.md#oh_abilitybase_setwantboolparam)([AbilityBase_Want](#abilitybase_want)* want, const char* key, bool value) | Sets a value of the bool type in Want.| +| [AbilityBase_ErrorCode](_ability_base.md#abilitybase_errorcode) [OH_AbilityBase_GetWantBoolParam](_ability_base.md#oh_abilitybase_getwantboolparam)([AbilityBase_Want](#abilitybase_want)* want, const char* key, bool* value) | Obtains a value of the bool type set in Want.| +| [AbilityBase_ErrorCode](_ability_base.md#abilitybase_errorcode) [OH_AbilityBase_SetWantDoubleParam](_ability_base.md#oh_abilitybase_setwantdoubleparam)([AbilityBase_Want](#abilitybase_want)* want, const char* key, double value) | Sets a value of the double type in Want.| +| [AbilityBase_ErrorCode](_ability_base.md#abilitybase_errorcode) [OH_AbilityBase_GetWantDoubleParam](_ability_base.md#oh_abilitybase_getwantdoubleparam)([AbilityBase_Want](#abilitybase_want)* want, const char* key, double* value) | Obtains a value of the double type set in Want.| diff --git a/en/application-dev/reference/apis-accessibility-kit/js-apis-accessibility.md b/en/application-dev/reference/apis-accessibility-kit/js-apis-accessibility.md index 8ac23f8627bec093f6652f9e8f90486f9347d412..043b24f31f8d6a4c69183acd63c6274f0ebed87b 100644 --- a/en/application-dev/reference/apis-accessibility-kit/js-apis-accessibility.md +++ b/en/application-dev/reference/apis-accessibility-kit/js-apis-accessibility.md @@ -362,7 +362,7 @@ Describes a GUI change event. | itemCount | number | No | Total number of records. | | elementId12+ | number | No | Element ID of the component. | | textAnnouncedForAccessibility12+ | string | No | Content for auto-broadcasting. | -| textResourceAnnouncedForAccessibility16+ | Resource | No | Content for auto-broadcasting, which supports resources of the string type. | +| textResourceAnnouncedForAccessibility18+ | Resource | No | Content for auto-broadcasting, which supports resources of the string type. | | customId12+ | string | No | Component ID for auto-focusing. | ### constructor @@ -442,9 +442,9 @@ Enumerates accessibility event types. | 'scroll' | Event of the scroll view. | | 'requestFocusForAccessibility' | Event of the auto-focusing.| | 'announceForAccessibility' | Event of the auto-broadcasting.| -| 'requestFocusForAccessibilityNotInterrupt' | Event of the auto-focusing without interruption.
This event is supported since API version 16.| -| 'announceForAccessibilityNotInterrupt' | Event of the auto-broadcasting without interruption.
This event is supported since API version 16.| -| 'scrolling' | Event indicating that an item is scrolled out of the screen in the scrolling view.
This event is supported since API version 16.| +| 'requestFocusForAccessibilityNotInterrupt' | Event of the auto-focusing without interruption.
This event is supported since API version 18.| +| 'announceForAccessibilityNotInterrupt' | Event of the auto-broadcasting without interruption.
This event is supported since API version 18.| +| 'scrolling' | Event indicating that an item is scrolled out of the screen in the scrolling view.
This event is supported since API version 18.| ## TextMoveUnit @@ -778,7 +778,7 @@ accessibility.on('touchGuideStateChange', (data: boolean) => { }); ``` -## accessibility.on('screenReaderStateChange')16+ +## accessibility.on('screenReaderStateChange')18+ on(type: 'screenReaderStateChange', callback: Callback<boolean>): void @@ -877,7 +877,7 @@ accessibility.off('touchGuideStateChange', (data: boolean) => { }); ``` -## accessibility.off('screenReaderStateChange')16+ +## accessibility.off('screenReaderStateChange')18+ off(type: 'screenReaderStateChange', callback?: Callback<boolean>): void @@ -1095,13 +1095,13 @@ import { accessibility } from '@kit.AccessibilityKit'; let status: boolean = accessibility.isOpenTouchGuideSync(); ``` -## accessibility.isScreenReaderOpenSync16+ +## accessibility.isScreenReaderOpenSync18+ isScreenReaderOpenSync(): boolean Checks whether the screen reader mode is enabled. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.BarrierFree.Accessibility.Vision @@ -1330,7 +1330,7 @@ accessibility.sendAccessibilityEvent(eventInfo, (err: BusinessError) => { }); ``` -**Example of resource-supported auto-broadcasting16+:** +**Example of resource-supported auto-broadcasting18+:** ```ts import { accessibility } from '@kit.AccessibilityKit'; diff --git a/en/application-dev/reference/apis-accessibility-kit/js-apis-application-accessibilityExtensionAbility.md b/en/application-dev/reference/apis-accessibility-kit/js-apis-application-accessibilityExtensionAbility.md index 306e766e12921d5c07aea5dc01ada4f62f89d46f..dfef13b145048f09633059f2a41e1a3fe461361d 100644 --- a/en/application-dev/reference/apis-accessibility-kit/js-apis-application-accessibilityExtensionAbility.md +++ b/en/application-dev/reference/apis-accessibility-kit/js-apis-application-accessibilityExtensionAbility.md @@ -39,7 +39,7 @@ Defines an accessibility event. ## AccessibilityElement10+ -Defines accessibility elements. For details, see [AccessibilityElement](js-apis-inner-application-accessibilityExtensionContext.md#accessibilityelement9). +Indicates an accessibility element. For details, see [AccessibilityElement](js-apis-inner-application-accessibilityExtensionContext.md#accessibilityelement9). **System capability**: SystemCapability.BarrierFree.Accessibility.Core diff --git a/en/application-dev/reference/apis-accessibility-kit/js-apis-inner-application-accessibilityExtensionContext-sys.md b/en/application-dev/reference/apis-accessibility-kit/js-apis-inner-application-accessibilityExtensionContext-sys.md index 6bf49617fe9400d39f3b7071ffd33ffee65ecf04..5652cbff7ba3bf4408403a62b35391f63fa14d12 100644 --- a/en/application-dev/reference/apis-accessibility-kit/js-apis-inner-application-accessibilityExtensionContext-sys.md +++ b/en/application-dev/reference/apis-accessibility-kit/js-apis-inner-application-accessibilityExtensionContext-sys.md @@ -251,7 +251,7 @@ axContext.startAbility(want).then(() => { }); ``` -### getElements16+ +### getElements18+ getElements(windowId: number, elementId?: number): Promise; @@ -297,7 +297,7 @@ axContext.getElements(windowId, elementId).then((data:AccessibilityElement[]) => }); ``` -### getDefaultFocusedElementIds16+ +### getDefaultFocusedElementIds18+ getDefaultFocusedElementIds(windowId: number): Promise; diff --git a/en/application-dev/reference/apis-accessibility-kit/js-apis-inner-application-accessibilityExtensionContext.md b/en/application-dev/reference/apis-accessibility-kit/js-apis-inner-application-accessibilityExtensionContext.md index 2ba1ded3bb1525755b5ab17fd478f4b64f03c3e9..5ad287aee51659630945ecee56a0a3fb3c634b7e 100644 --- a/en/application-dev/reference/apis-accessibility-kit/js-apis-inner-application-accessibilityExtensionContext.md +++ b/en/application-dev/reference/apis-accessibility-kit/js-apis-inner-application-accessibilityExtensionContext.md @@ -28,7 +28,7 @@ Provides attribute names and value types of a node element. **System capability**: SystemCapability.BarrierFree.Accessibility.Core -### Name +### Attributes | Name | Type | Readable | Writable | Description | |----------------------|--------------------------------------------------------------------|-----|-----| ------------------- | @@ -83,10 +83,11 @@ Provides attribute names and value types of a node element. | textType12+ | string | Yes | No | Accessibility text type of an element, which is configured by the **accessibilityTextHint** attribute of the component.| | offset12+ | number | Yes | No | Pixel offset of the content area relative to the top coordinate of a scrollable component, such as **List** and **Grid**.| | hotArea12+ | [Rect](#rect) | Yes | No | Touchable area of an element.| -| customComponentType16+ | string | Yes | No | Custom component type.| -| accessibilityNextFocusId16+ | number | Yes | No | ID of the next component to be focused on. You can use **findElement('elementId')** to obtain the value of this attribute set on the component from the **AccessibilityElementInfo** object.| -| accessibilityPreviousFocusId16+ | number | Yes | No | ID of the previous component to be focused on. You can use **findElement('elementId')** to obtain the value of this attribute set on the component from the **AccessibilityElementInfo** object.| -| extraInfo16+ | string | Yes | No | Extended attribute, which is used to define the attributes that are available only to specific components.| +| customComponentType18+ | string | Yes | No | Custom component type.| +| accessibilityNextFocusId18+ | number | Yes | No | ID of the next component to be focused on. You can use **findElement('elementId')** to obtain the value of this attribute set on the component from the **AccessibilityElementInfo** object.| +| accessibilityPreviousFocusId18+ | number | Yes | No | ID of the previous component to be focused on. You can use **findElement('elementId')** to obtain the value of this attribute set on the component from the **AccessibilityElementInfo** object.| +| extraInfo18+ | string | Yes | No | Extended attributes, which are used to define the attributes of specific components, including:
- **CheckboxGroupSelectedStatus**: selection status of the **CheckboxGroup** component. The options are as follows:
**0**: selected
**1**: partially selected
**2**: not selected
- **Row**: row where an focused item is located in **Grid**.
- **Column**: column where an focused item is located in **Grid**.
- **ListItemIndex**: row where an focused item is located in **List**.
- **SideBarContainerStates**: expansion state of the expandable components (such as **SideBarContainer** and **Select**). The options are as follows:
**0**: collapsed
**1**: expanded
- **ToggleType**: type of the **Toggle** component. The options are as follows:
**0**: checkbox
**1**: switch
**2**: button
- **BindSheet**: state of the **BindSheet** component. The options are as follows:
**0**: high
**1**: middle
**2**: low
- **hasRegisteredHover**: whether the component has registered the **onAccessibilityHover** event callback. The value **1** indicates that the component has registered the event callback; otherwise, this field is not used.
- **direction**: layout direction of the **List** component. The value can be **vertical** or **horizontal**.
- **expandedState**: expanded state of list items in the **List** component. The value can be **expanded** or **collapsed**. | +| accessibilityScrollable18+ | boolean | Yes | No | Whether an element is scrollable for accessibility. This attribute has a higher priority than **scrollable**.
- **true** (default): the element is scrollable.
- **false**: the element is not scrollable.| ## FocusDirection @@ -1032,9 +1033,9 @@ Performs an action based on the specified action name. This API uses a promise t **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory | Description | | ----------- | ---------------------------------------- | ---- |----------------------------------------------------------| -| actionName | string | Yes | Action name. For details, see [Action](./js-apis-accessibility.md#action). +| actionName | string | Yes | Action name. For details, see [Action](./js-apis-accessibility.md#action). | | parameters | object | No | Parameters required for performing the target action. Empty by default. | **Return value** @@ -1129,7 +1130,7 @@ Performs an action based on the specified action name. This API uses an asynchro | Name | Type | Mandatory | Description | | ----------- | ---------------------------------------- | ---- | -------------- | -| actionName | string | Yes | Action name. For details, see [Action](./js-apis-accessibility.md#action). +| actionName | string | Yes | Action name. For details, see [Action](./js-apis-accessibility.md#action). | | callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Error codes** diff --git a/en/application-dev/reference/apis-ads-kit/Readme-EN.md b/en/application-dev/reference/apis-ads-kit/Readme-EN.md index 549d3a21b15eff93ab2fb6f59c243c80ea7f947e..ec640e91c3013f0eb929908e52fff7acd9aae980 100644 --- a/en/application-dev/reference/apis-ads-kit/Readme-EN.md +++ b/en/application-dev/reference/apis-ads-kit/Readme-EN.md @@ -1,16 +1,19 @@ - -# Ads Kit +# Ads Kit -- ArkTS APIs +- ArkTS APIs - [@ohos.advertising (Ads Service Framework)](js-apis-advertising.md) - [@ohos.identifier.oaid (OAID)](js-apis-oaid.md) - [@ohos.advertising.AdsServiceExtensionAbility (ExtensionAbility for Ads](js-apis-adsserviceextensionability.md) + - [@ohos.advertising.AdsServiceExtensionAbility (ExtensionAbility for Ads) (System API)](js-apis-adsserviceextensionability-sys.md) - [@ohos.identifier.oaid (OAID) (System API)](js-apis-oaid-sys.md) -- ArkTS Components + + - Dependent Elements and Definitions + - advertising + - [Advertisement](js-apis-inner-advertising-advertisement.md) +- ArkTS Components - [@ohos.advertising.AdComponent (Non-Full-Screen Ad Component)](js-apis-adcomponent.md) - [@ohos.advertising.AutoAdComponent (Carousel Ad Component)](js-apis-autoadcomponent.md) -- Error Codes +- Error Codes - [Ads Service Framework Error Codes](errorcode-ads.md) - [OAID Error Codes](errorcode-oaid.md) - diff --git a/en/application-dev/reference/apis-ads-kit/errorcode-ads.md b/en/application-dev/reference/apis-ads-kit/errorcode-ads.md index c8b66937d4c644a6376188a8892aef512f2a4928..a42cb793ff4f93527e38898e3b8d4e9314267230 100644 --- a/en/application-dev/reference/apis-ads-kit/errorcode-ads.md +++ b/en/application-dev/reference/apis-ads-kit/errorcode-ads.md @@ -1,11 +1,8 @@ # Ads Service Framework Error Codes - > **NOTE** -> > This topic describes only module-specific error codes. For details about universal error codes, see [Universal Error Codes](../errorcode-universal.md). - ## 21800001 Internal System Error **Error Message** @@ -24,7 +21,6 @@ Failed to connect to the OAID service. Check whether the service is running properly. - ## 21800003 Ad Loading Failure **Error Message** @@ -37,12 +33,17 @@ This error code is reported if loading the ad fails. **Possible Causes** -The network connection is abnormal, or an ad request parameter is incorrect. +1. The network connection is abnormal. + +2. Incorrect ad request parameter. + +3. The server does not have proper ad filling. **Procedure** -Check the network status, and correct the ad request parameters. +1. Check the network status. +2. Check whether the ad request parameters meet the requirements based on the API reference. ## 21800004 Ad Display Failure @@ -62,13 +63,29 @@ The network connection is abnormal. Check the network status. +## 21800005 Ad Data Parsing Failure + +**Error Message** + +Failed to parse the ad response. + +**Description** + +This error code is reported if ad data is failed to be parsed. + +**Possible Causes** + +Key attributes are missing or the structure of the ad response data is incorrect. + +**Procedure** + +Check the ad response data. ## 401 Incorrect Ads Request Parameter **Error Message** -Invalid input parameter. Possible causes:1. Mandatory parameters are left unspecified. -2.Incorrect parameter types. 3.Parameter verification failed +Invalid input parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed **Description** @@ -82,12 +99,11 @@ Ads request parameters fail the verification. Check whether the ads request parameters are correct. - ## 801 Ad Request Failure **Error Message** -Device not support +Device not supported. **Description** diff --git a/en/application-dev/reference/apis-ads-kit/js-apis-adcomponent.md b/en/application-dev/reference/apis-ads-kit/js-apis-adcomponent.md index d186463c4c7b014677c1d6b19866739cf31a71e8..58b259dbe278fbc04504463dcbaa0064bfcc2bd9 100644 --- a/en/application-dev/reference/apis-ads-kit/js-apis-adcomponent.md +++ b/en/application-dev/reference/apis-ads-kit/js-apis-adcomponent.md @@ -1,24 +1,19 @@ # @ohos.advertising.AdComponent (Non-Full-Screen Ad Component) - The AdComponent module provides the capability of displaying non-full-screen ads. - > **NOTE** -> > The initial APIs of this module are supported since API version 11. Newly added APIs will be marked with a superscript to indicate their earliest API version. - ## Modules to Import ```ts import { AdComponent } from '@kit.AdsKit'; ``` - ## AdComponent -AdComponent(ads: Array, displayOptions: advertising.AdDisplayOptions, interactionListener: advertising.AdInteractionListener, adRenderer?:() => void): void +AdComponent(ads: advertising.Advertisement[], displayOptions: advertising.AdDisplayOptions, interactionListener: advertising.AdInteractionListener, @BuilderParam adRenderer?: () => void, @Prop rollPlayState?: number): void Component that displays a non-full-screen ad. @@ -26,13 +21,13 @@ Component that displays a non-full-screen ad. **Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| ads | Array<advertising.[Advertisement](js-apis-advertising.md#advertisement)> | Yes| Array of ad objects.
**Atomic service API**: This API can be used in atomic services since API version 12.| -| displayOptions | advertising.[AdDisplayOptions](js-apis-advertising.md#addisplayoptions) | Yes| Ad display parameters.
**Atomic service API**: This API can be used in atomic services since API version 12.| -| interactionListener | advertising.[AdInteractionListener](js-apis-advertising.md#adinteractionlistener) | Yes| Ad status change callback.
**Atomic service API**: This API can be used in atomic services since API version 12.| -| adRenderer12+ | () => void | No| Ad self-rendering.| +| Name | Type | Mandatory| Description | +|-----------------------------|-----------------------------------------------------------------------------------|----|----------------------------------------------------------| +| ads | advertising.[Advertisement](js-apis-advertising.md#advertisement)[] | Yes | Array of ad objects.
**Atomic service API**: This API can be used in atomic services since API version 12. | +| displayOptions | advertising.[AdDisplayOptions](js-apis-advertising.md#addisplayoptions) | Yes | Ad display parameters.
**Atomic service API**: This API can be used in atomic services since API version 12. | +| interactionListener | advertising.[AdInteractionListener](js-apis-advertising.md#adinteractionlistener) | Yes | Ad status change callback.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| adRenderer12+ | () => void | No | Ad self-rendering. | +| rollPlayState15+ | number | No | Roll ad state. The value **1** means that the roll ad is played, and the value **2** means that the roll ad is paused. Other values are invalid and the previous playback state is not changed. | **Example** @@ -42,32 +37,33 @@ import { hilog } from '@kit.PerformanceAnalysisKit'; @Entry @Component -export struct ShowNonFullScreenAd { +struct Index { // Requested ad content. - private ads: Array = []; + private ads: advertising.Advertisement[] = []; // Ad display parameters. private adDisplayOptions: advertising.AdDisplayOptions = { // Whether to mute the ad. By default, the ad is not muted. mute: false - } + }; build() { Column() { // The AdComponent is used to show a non-full-screen ad. AdComponent({ - ads: this.ads, displayOptions: this.adDisplayOptions, + ads: this.ads, + displayOptions: this.adDisplayOptions, interactionListener: { // Ad status change callback. onStatusChanged: (status: string, ad: advertising.Advertisement, data: string) => { switch (status) { case 'onAdOpen': - hilog.info(0x0000, 'testTag', '%{public}s', 'onAdOpen'); + hilog.info(0x0000, 'testTag', 'onAdOpen'); break; case 'onAdClick': - hilog.info(0x0000, 'testTag', '%{public}s', 'onAdClick'); + hilog.info(0x0000, 'testTag', 'onAdClick'); break; case 'onAdClose': - hilog.info(0x0000, 'testTag', '%{public}s', 'onAdClose'); + hilog.info(0x0000, 'testTag', 'onAdClose'); break; } } @@ -75,7 +71,9 @@ export struct ShowNonFullScreenAd { }) .width('100%') .height('100%') - }.width('100%').height('100%') + } + .width('100%') + .height('100%') } } ``` diff --git a/en/application-dev/reference/apis-ads-kit/js-apis-adsserviceextensionability-sys.md b/en/application-dev/reference/apis-ads-kit/js-apis-adsserviceextensionability-sys.md index bfc968ae051474eddff25390be8ee30929f6d5b7..7916ebb3adb1149263c54449cb500825e1654d45 100644 --- a/en/application-dev/reference/apis-ads-kit/js-apis-adsserviceextensionability-sys.md +++ b/en/application-dev/reference/apis-ads-kit/js-apis-adsserviceextensionability-sys.md @@ -1,25 +1,20 @@ # @ohos.advertising.AdsServiceExtensionAbility (ExtensionAbility for Ads) (System API) - The AdsServiceExtensionAbility module provides ExtensionAbilities for the ads service. Device vendors can implement the service logic of requesting one or multiple ads. - > **NOTE** -> > The initial APIs of this module are supported since API version 11. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs provided by this module are system APIs. - ## Modules to Import ```ts import { AdsServiceExtensionAbility } from '@kit.AdsKit'; ``` - ## AdsServiceExtensionAbility.onLoadAd -onLoadAd(adParam: advertising.AdRequestParams, adOptions: advertising.AdOptions, respCallback: RespCallback); +onLoadAd(adParam: advertising.AdRequestParams, adOptions: advertising.AdOptions, respCallback: RespCallback) Called when the media application starts to load an ad. The device vendor needs to implement the ad request service logic in this API and send the result to the media application through a call back. @@ -27,23 +22,22 @@ Called when the media application starts to load an ad. The device vendor needs **System capability**: SystemCapability.Advertising.Ads -**Since**: 11 - **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| adParam | advertising.[AdRequestParams](js-apis-advertising.md#adrequestparams) | Yes| Ad request parameters.| -| adOptions | advertising.[AdOptions](js-apis-advertising.md#adoptions) | Yes| Ad configuration.| -| respCallback | [RespCallback](js-apis-adsserviceextensionability#adsserviceextensionabilityrespcallback) | Yes| Ad request callback.| +| Name | Type | Mandatory| Description | +|--------------|-----------------------------------------------------------------------|----|---------| +| adParam | advertising.[AdRequestParams](js-apis-advertising.md#adrequestparams) | Yes | Ad request parameters.| +| adOptions | advertising.[AdOptions](js-apis-advertising.md#adoptions) | Yes | Ad configuration. | +| respCallback | [RespCallback](js-apis-adsserviceextensionability.md#respcallback) | Yes | Ad request callback.| **Example** + ```ts import { AdsServiceExtensionAbility, advertising, RespCallback } from '@kit.AdsKit'; export default class AdsExtensionAbility extends AdsServiceExtensionAbility { - onLoadAd(adParam: advertising.AdRequestParams, adOptions: advertising.AdOptions, respCallback: RespCallback) { - const adType: number | undefined = adParam.adType; + onLoadAd(adRequestParams: advertising.AdRequestParams, adOptions: advertising.AdOptions, respCallback: RespCallback) { + const adType: number | undefined = adRequestParams.adType; const ads: Array = []; const rewardVerifyConfig: Map = new Map(); ads.push({ @@ -63,17 +57,16 @@ export default class AdsExtensionAbility extends AdsServiceExtensionAbility { clicked: false }); const slot: string = 'test'; - const resMap: Map> = new Map(); - resMap.set(slot, ads); - respCallback(resMap); + const respData: Map> = new Map(); + respData.set(slot, ads); + respCallback(respData); } } ``` - ## AdsServiceExtensionAbility.onLoadAdWithMultiSlots -onLoadAdWithMultiSlots(adParams: advertising.AdRequestParams[], adOptions: advertising.AdOptions, respCallback: RespCallback); +onLoadAdWithMultiSlots(adParams: advertising.AdRequestParams[], adOptions: advertising.AdOptions, respCallback: RespCallback) Called when the media application starts to load multiple ads. The device vendor needs to implement the ad request service logic in this API and send the result to the media application through a call back. @@ -81,24 +74,23 @@ Called when the media application starts to load multiple ads. The device vendor **System capability**: SystemCapability.Advertising.Ads -**Since**: 11 - **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| adParams | advertising.[AdRequestParams](js-apis-advertising.md#adrequestparams)[] | Yes| Ad request parameters.| -| adOptions | advertising.[AdOptions](js-apis-advertising.md#adoptions) | Yes| Ad configuration.| -| respCallback | [RespCallback](js-apis-adsserviceextensionability#adsserviceextensionabilityrespcallback) | Yes| Ad request callback.| +| Name | Type | Mandatory| Description | +|--------------|-------------------------------------------------------------------------|----|---------| +| adParams | advertising.[AdRequestParams](js-apis-advertising.md#adrequestparams)[] | Yes | Ad request parameters.| +| adOptions | advertising.[AdOptions](js-apis-advertising.md#adoptions) | Yes | Ad configuration. | +| respCallback | [RespCallback](js-apis-adsserviceextensionability.md#respcallback) | Yes | Ad request callback.| **Example** + ```ts import { AdsServiceExtensionAbility, advertising, RespCallback } from '@kit.AdsKit'; export default class AdsExtensionAbility extends AdsServiceExtensionAbility { - onLoadAdWithMultiSlots(adParams: advertising.AdRequestParams[], adOptions: advertising.AdOptions, + onLoadAdWithMultiSlots(adRequestParams: advertising.AdRequestParams[], adOptions: advertising.AdOptions, respCallback: RespCallback) { - const adType1: number = adParams[0].adType as number; + const adType1: number = adRequestParams[0].adType as number; const ads1: Array = []; const rewardVerifyConfig: Map = new Map(); ads1.push({ @@ -118,7 +110,7 @@ export default class AdsExtensionAbility extends AdsServiceExtensionAbility { clicked: false }); const slot1: string = 'test1'; - const adType2: number = adParams[1].adType as number; + const adType2: number = adRequestParams[1].adType as number; const ads2: Array = []; ads2.push({ adType: adType2, @@ -137,10 +129,10 @@ export default class AdsExtensionAbility extends AdsServiceExtensionAbility { clicked: false }); const slot2: string = 'test2'; - const resMap: Map> = new Map(); - resMap.set(slot1, ads1); - resMap.set(slot2, ads2); - respCallback(resMap); + const respData: Map> = new Map(); + respData.set(slot1, ads1); + respData.set(slot2, ads2); + respCallback(respData); } } ``` diff --git a/en/application-dev/reference/apis-ads-kit/js-apis-adsserviceextensionability.md b/en/application-dev/reference/apis-ads-kit/js-apis-adsserviceextensionability.md index 65438c7f75bdb9456b6ad12bb27767535fbece09..74bf7107ba9a7a60b96454a8dbc2d4d36eaa7cd2 100644 --- a/en/application-dev/reference/apis-ads-kit/js-apis-adsserviceextensionability.md +++ b/en/application-dev/reference/apis-ads-kit/js-apis-adsserviceextensionability.md @@ -1,21 +1,17 @@ # @ohos.advertising.AdsServiceExtensionAbility (ExtensionAbility for Ads) - The AdsServiceExtensionAbility module provides ExtensionAbilities for the ads service. Device vendors can implement the callbacks for ads requests. - > **NOTE** -> > The initial APIs of this module are supported since API version 11. Newly added APIs will be marked with a superscript to indicate their earliest API version. - ## Modules to Import ```ts import { RespCallback } from '@kit.AdsKit'; ``` -## AdsServiceExtensionAbility.RespCallback +## RespCallback (respData: Map<string, Array<advertising.Advertisement>>): void; @@ -23,34 +19,31 @@ Ad request callback. **System capability**: SystemCapability.Advertising.Ads -**Since**: 11 - **Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| respData | Map<string, Array<advertising.[Advertisement](js-apis-advertising.md#advertisement)>> | Yes| Data in the ad request callback.| - +| Name | Type | Mandatory| Description | +|----------|---------------------------------------------------------------------------------------------------|----|-----------| +| respData | Map<string, Array<advertising.[Advertisement](js-apis-advertising.md#advertisement)>> | Yes | Data in the ad request callback.| **Example** + ```ts import { advertising, RespCallback } from '@kit.AdsKit'; -function respDemo(respCallback: RespCallback) { - const ads: Array = []; - const rewardVerifyConfig: Map = new Map(); - ads.push({ - adType: 7, - uniqueId: '111111', - rewardVerifyConfig: rewardVerifyConfig, - rewarded: false, - shown: false, - clicked: false - }) - const slot: string = "test"; - const resMap: Map> = new Map(); - resMap.set(slot, ads); - respCallback(resMap); +function setRespCallback(respCallback: RespCallback) { + const ads: Array = []; + const rewardVerifyConfig: Map = new Map(); + ads.push({ + adType: 7, + uniqueId: '111111', + rewardVerifyConfig: rewardVerifyConfig, + rewarded: false, + shown: false, + clicked: false + }) + const slot: string = 'test'; + const respData: Map> = new Map(); + respData.set(slot, ads); + respCallback(respData); } ``` diff --git a/en/application-dev/reference/apis-ads-kit/js-apis-advertising.md b/en/application-dev/reference/apis-ads-kit/js-apis-advertising.md index ca4f83643f5ef6c0c1568ed6000a05bdb71b81a2..b258d28bbdb7232118219441ecc7ecfcfb359c1a 100644 --- a/en/application-dev/reference/apis-ads-kit/js-apis-advertising.md +++ b/en/application-dev/reference/apis-ads-kit/js-apis-advertising.md @@ -1,19 +1,398 @@ # @ohos.advertising (Ads Service Framework) - The advertising module provides APIs for requesting and displaying ads. - > **NOTE** -> > The initial APIs of this module are supported since API version 11. Newly added APIs will be marked with a superscript to indicate their earliest API version. - ## Modules to Import ```ts import { advertising } from '@kit.AdsKit'; ``` + +## advertising.showAd + +showAd(ad: Advertisement, options: AdDisplayOptions, context?: common.UIAbilityContext): void + +Shows a full-screen ad. + +**Atomic service API**: This API can be used in atomic services since API version 12. + +**System capability**: SystemCapability.Advertising.Ads + +**Parameters** + +| Name | Type | Mandatory| Description | +|---------|----------------------------------------------------------------------------------------------|----|-------------------------------------------------------| +| ad | [Advertisement](#advertisement) | Yes | Ad object. | +| options | [AdDisplayOptions](#addisplayoptions) | Yes | Ad display parameters. | +| context | common.[UIAbilityContext](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md) | No | Context of the UIAbility. If this parameter is not set, the value is obtained from @ohos.app.ability.common.| + +**Error codes** + +For details about the following error codes, see [Ads Service Framework Error Codes](errorcode-ads.md). + +| ID | Error Message | +|----------|-----------------------------------------------------------------------------------------| +| 401 | Invalid input parameter. Possible causes: 1. Mandatory parameters are left unspecified. | +| 21800001 | System internal error. | +| 21800004 | Failed to display the ad. | + +**Example** + +```ts +import { common } from '@kit.AbilityKit'; +import { advertising } from '@kit.AdsKit'; +import { hilog } from '@kit.PerformanceAnalysisKit'; + +@Entry +@Component +struct Index { + private context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext; + // Requested ad content. + private ad?: advertising.Advertisement; + // Ad display parameters. + private adDisplayOptions: advertising.AdDisplayOptions = { + // Whether to mute the ad. By default, the ad is not muted. + mute: false + } + + build() { + Column() { + Button('showAd') + .onClick(() => { + try { + // Show the ad. + advertising.showAd(this.ad, this.adDisplayOptions, this.context); + } catch (err) { + hilog.error(0x0000, 'testTag', `Fail to show ad. Code is ${err.code}, message is ${err.message}`); + } + }); + } + .width('100%') + .height('100%') + } +} +``` + +## advertising.getAdRequestBody12+ + +getAdRequestBody(adParams: AdRequestParams[], adOptions: AdOptions): Promise<string> + +Obtains the body of an ad request. This API uses a promise to return the result. (This API is available only for some preset applications.) + +**System capability**: SystemCapability.Advertising.Ads + +**Parameters** + +| Name | Type | Mandatory| Description | +|-----------|---------------------------------------|----|---------------------------------| +| adParams | [AdRequestParams[]](#adrequestparams) | Yes | Ad request parameters.
- The **adid** parameter is optional.| +| adOptions | [AdOptions](#adoptions) | Yes | Ad configuration. | + +**Return value** + +| Type | Description | +|-----------------------|------------------------| +| Promise<string> | Promise used to return the ad data of the string type.| + +**Error codes** + +For details about the following error codes, see [Ads Service Framework Error Codes](errorcode-ads.md). + +| ID | Error Message | +|----------|---------------------------------------------------------------------------------------------------------------------------------------------------------| +| 401 | Invalid input parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | +| 801 | Device not supported. | +| 21800001 | System internal error. | + +**Example** + +```ts +import { advertising } from '@kit.AdsKit'; +import { Prompt } from '@kit.ArkUI'; +import { BusinessError } from '@kit.BasicServicesKit'; +import { hilog } from '@kit.PerformanceAnalysisKit'; + +function getAdRequestBody(): void { + const adRequestParamsArray: advertising.AdRequestParams[] = []; + const adRequestParams: advertising.AdRequestParams = { + adId: 'testu7m3hc4gvm', + adType: 3, + adCount: 2, + adWidth: 100, + adHeight: 100 + }; + adRequestParamsArray.push(adRequestParams); + const adOptions: advertising.AdOptions = { + // Set whether to request only non-personalized ads. 0: to request personalized ads and non-personalized ads; 1: to request only non-personalized ads. If this parameter is left blank, the service logic prevails. + nonPersonalizedAd: 0, + // Specify whether you want your ad content to be treated as COPPA-compliant. The following values are available: -1 (default value): uncertain; 0: no; 1: yes. + tagForChildProtection: -1, + // Specify whether you want the ad request to be processed in a way that meets the GDPR for users in the EEA under the age of consent. The following values are available: -1 (default value): uncertain; 0: no; 1: yes. + tagForUnderAgeOfPromise: -1, + // Maximum ad content rating. **W**: aged 3 and up; **PI**: aged 7 and up, under parental guidance; **J**: teenagers aged 12 and up; **A**: adults aged 16 or 18 and up. + adContentClassification: 'A' + }; + advertising.getAdRequestBody(adRequestParamsArray, adOptions).then((data) => { + hilog.info(0x0000, 'testTag', `Succeeded in getting ad request body. Data is ${JSON.stringify(data)}`); + Prompt.showToast({ + message: data, + duration: 1000 + }); + }).catch((error: BusinessError) => { + hilog.error(0x0000, 'testTag', `Fail to get ad request body. Code is ${error.code}, message is ${error.message}`); + Prompt.showToast({ + message: error.code.toString() + ',' + error.message, + duration: 1000 + }); + }) +} +``` + +## advertising.parseAdResponse12+ + +parseAdResponse(adResponse: string, listener: MultiSlotsAdLoadListener, context: common.UIAbilityContext): void + +Parses and processes the ad response body. (This API is available only for some preset applications.) + +**System capability**: SystemCapability.Advertising.Ads + +**Parameters** + +| Name | Type | Mandatory| Description | +|------------|----------------------------------------------------------------------------------------------|----|------------------| +| adResponse | string | Yes | Ad request parameters. | +| listener | [MultiSlotsAdLoadListener](#multislotsadloadlistener) | Yes | Ad request callback. | +| context | common.[UIAbilityContext](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md) | Yes | UIAbility context.| + +**Error codes** + +For details about the following error codes, see [Ads Service Framework Error Codes](errorcode-ads.md). + +| ID | Error Message | +|----------|---------------------------------------------------------------------------------------------------------------------------------------------------------| +| 401 | Invalid input parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | +| 801 | Device not supported. | +| 21800001 | System internal error. | +| 21800005 | Failed to parse the ad response. | + +**Example** + +For details about how to obtain the context, see [Obtaining the Context of UIAbility](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md). + +```ts +import { common } from '@kit.AbilityKit'; +import { advertising } from '@kit.AdsKit'; +import { hilog } from '@kit.PerformanceAnalysisKit'; + +function parseAdResponse(adResponse: string, context: common.UIAbilityContext): void { + // Listen for the ad parsing callback. + const multiSlotsAdLoaderListener: advertising.MultiSlotsAdLoadListener = { + // Called when ad parsing fails. + onAdLoadFailure: (errorCode: number, errorMsg: string) => { + hilog.error(0x0000, 'testTag', `Fail to load multiSlots ad. Code is ${errorCode}, message is ${errorMsg}`); + }, + // Called when ad parsing is successful. + onAdLoadSuccess: (ads: Map>) => { + hilog.info(0x0000, 'testTag', 'Succeed in loading multiSlots ad'); + // Save the parsed ad content as an array for display. + const returnAds: Array = []; + ads.forEach((adsArray) => returnAds.push(...adsArray)); + } + }; + // Call the API to parse the response body. + hilog.info(0x0000, 'testTag', 'Start to parse ad response'); + advertising.parseAdResponse(adResponse, multiSlotsAdLoaderListener, context); +} +``` + +## advertising.registerWebAdInterface12+ + +registerWebAdInterface(controller: web_webview.WebviewController, context: common.UIAbilityContext): void + +Injects an ad JavaScript object to the **Web** component. (This API is available only for some preset applications.) + +**Atomic service API**: This API can be used in atomic services since API version 12. + +**System capability**: SystemCapability.Advertising.Ads + +**Parameters** + +| Name | Type | Mandatory| Description | +|------------|----------------------------------------------------------------------------------------------|----|------------------| +| controller | web_webview.[WebviewController](../apis-arkweb/js-apis-webview.md#webviewcontroller) | Yes | Controller of the **Web** component. | +| context | common.[UIAbilityContext](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md) | Yes | UIAbility context.| + +**Error codes** + +For details about the following error codes, see [Ads Service Framework Error Codes](errorcode-ads.md). + +| ID | Error Message | +|----------|---------------------------------------------------------------------------------------| +| 401 | Invalid input parameter. Possible causes: 1.Mandatory parameters are left unspecified | +| 21800001 | System internal error. | + +**Example** + +```ts +import { common } from '@kit.AbilityKit'; +import { advertising } from '@kit.AdsKit'; +import { webview } from '@kit.ArkWeb'; +import { hilog } from '@kit.PerformanceAnalysisKit'; + +@Entry +@Component +struct Index { + private webController: webview.WebviewController = new webview.WebviewController(); + private context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext; + + build() { + Column() { + Button('registerWebAdInterface') + .onClick(() => { + try { + advertising.registerWebAdInterface(this.webController, this.context); + } catch (err) { + hilog.error(0x0000, 'testTag', `Fail to register web ad interface. Code is ${err.code}, message is ${err.message}`); + } + }) + + Web({ + src: 'www.example.com', + controller: this.webController + }) + .width("100%") + .height("100%") + } + } +} +``` + +## advertising.registerWebAdInterface16+ + +registerWebAdInterface(controller: web_webview.WebviewController, context: common.UIAbilityContext, needRefresh: boolean): void + +Injects an ad JavaScript object to the **Web** component. (This API is available only for some preset applications.) + +**Atomic service API**: This API can be used in atomic services since API version 16. + +**System capability**: SystemCapability.Advertising.Ads + +**Parameters** + +| Name | Type | Mandatory| Description | +|-------------|----------------------------------------------------------------------------------------------|----|--------------------------------| +| controller | web_webview.[WebviewController](../apis-arkweb/js-apis-webview.md#webviewcontroller) | Yes | Controller of the **Web** component. | +| context | common.[UIAbilityContext](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md) | Yes | UIAbility context. | +| needRefresh | boolean | Yes | Whether a page needs to be refreshed. (The value **true** means that a page needs to be refreshed; the value **false** means the opposite.)| + +**Error codes** + +For details about the following error codes, see [Ads Service Framework Error Codes](errorcode-ads.md). + +| ID | Error Message | +|----------|--------------------------------------------------------------------------------------| +| 401 | Invalid input parameter. Possible causes: Mandatory parameters are left unspecified. | +| 21800001 | operation javascriptRegister error. | + +**Example** + +```ts +import { common } from '@kit.AbilityKit'; +import { advertising } from '@kit.AdsKit'; +import { webview } from '@kit.ArkWeb'; +import { hilog } from '@kit.PerformanceAnalysisKit'; + +@Entry +@Component +struct Index { + private webController: webview.WebviewController = new webview.WebviewController(); + private context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext; + + build() { + Column() { + Button('registerWebAdInterface') + .onClick(() => { + try { + advertising.registerWebAdInterface(this.webController, this.context, true); + } catch (err) { + hilog.error(0x0000, 'testTag', `Fail to register web ad interface. Code is ${err.code}, message is ${err.message}`); + } + }) + + Web({ + src: 'www.example.com', + controller: this.webController + }) + .width("100%") + .height("100%") + } + } +} +``` + +## advertising.deleteWebAdInterface16+ + +deleteWebAdInterface(controller: web_webview.WebviewController, needRefresh: boolean): void + +Deletes the ad JavaScript object injected through **registerWebAdInterface**. (This API is available only to some preset applications.) + +**Atomic service API**: This API can be used in atomic services since API version 16. + +**System capability**: SystemCapability.Advertising.Ads + +**Parameters** + +| Name | Type | Mandatory| Description | +|-------------|--------------------------------------------------------------------------------------|----|--------------------------------| +| controller | web_webview.[WebviewController](../apis-arkweb/js-apis-webview.md#webviewcontroller) | Yes | Controller of the **Web** component. | +| needRefresh | boolean | Yes | Whether a page needs to be refreshed. (The value **true** means that a page needs to be refreshed; the value **false** means the opposite.)| + +**Error codes** + +For details about the following error codes, see [Ads Service Framework Error Codes](errorcode-ads.md). + +| ID | Error Message | +|----------|--------------------------------------------------------------------------------------| +| 401 | Invalid input parameter. Possible causes: Mandatory parameters are left unspecified. | +| 21800001 | operation javascriptRegister error. | + +**Example** + +```ts +import { advertising } from '@kit.AdsKit'; +import { webview } from '@kit.ArkWeb'; +import { hilog } from '@kit.PerformanceAnalysisKit'; + +@Entry +@Component +struct Index { + private webController: webview.WebviewController = new webview.WebviewController(); + + build() { + Column() { + Button('deleteWebAdInterface') + .onClick(() => { + try { + advertising.deleteWebAdInterface(this.webController, true); + } catch (err) { + hilog.error(0x0000, 'testTag', `Fail to delete web ad interface. Code is ${err.code}, message is ${err.message}`); + } + }) + + Web({ + src: 'www.example.com', + controller: this.webController, + }) + .width('100%') + .height('100%') + } + } +} +``` + ## AdLoader Provides the APIs for loading ads. @@ -24,7 +403,7 @@ Provides the APIs for loading ads. ### constructor -constructor(context: common.Context); +constructor(context: common.Context) Constructor. @@ -34,9 +413,9 @@ Constructor. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| context | common.[Context](../apis-ability-kit/js-apis-inner-application-context.md) | Yes| Context of the ability or application.| +| Name | Type | Mandatory| Description | +|---------|----------------------------------------------------------------------------|----|----------------------------| +| context | common.[Context](../apis-ability-kit/js-apis-inner-application-context.md) | Yes | Context of the ability or application.| **Example** @@ -47,11 +426,10 @@ import { advertising } from '@kit.AdsKit'; import { common } from '@kit.AbilityKit'; function createConstructor(context: common.Context): void { - const load: advertising.AdLoader = new advertising.AdLoader(context); + const adLoader: advertising.AdLoader = new advertising.AdLoader(context); } ``` - ### loadAd loadAd(adParam: AdRequestParams, adOptions: AdOptions, listener: AdLoadListener): void @@ -64,73 +442,70 @@ Loads an ad. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| adParam | [AdRequestParams](#adrequestparams) | Yes| Ad request parameters.| -| adOptions | [AdOptions](#adoptions) | Yes| Ad configuration.| -| listener | [AdLoadListener](#adloadlistener) | Yes| Ad request callback.| +| Name | Type | Mandatory| Description | +|-----------|-------------------------------------|----|-----------| +| adParam | [AdRequestParams](#adrequestparams) | Yes | Ad request parameters. | +| adOptions | [AdOptions](#adoptions) | Yes | Ad configuration. | +| listener | [AdLoadListener](#adloadlistener) | Yes | Ad request callback.| **Error codes** For details about the following error codes, see [Ads Service Framework Error Codes](errorcode-ads.md). -| ID| Error Message| -| -------- | -------- | +| ID | Error Message | +|----------|--------------------------------------------------------------------------------------------------------------------------------------------------------| | 401 | Invalid input parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | -| 801 | Device not supported. | -| 21800001 | System internal error. | -| 21800003 | Failed to load the ad request. | - +| 801 | Device not supported. | +| 21800001 | System internal error. | +| 21800003 | Failed to load the ad request. | **Example** For details about how to obtain the context, see [Context](../../application-models/application-context-stage.md#overview). ```ts -import { advertising } from '@kit.AdsKit'; import { common } from '@kit.AbilityKit'; +import { advertising } from '@kit.AdsKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; -function requestAd(context: common.Context): void { - const adRequestParam: advertising.AdRequestParams = { +function loadAd(context: common.Context): void { + const adRequestParams: advertising.AdRequestParams = { // Ad type. adType: 3, // Ad ID. - adId: "testy63txaom86" + adId: 'testy63txaom86' }; const adOptions: advertising.AdOptions = { - // Optional custom parameter, which specifies whether the ad can be downloaded while mobile data is in use. The value 1 means that the ad can be downloaded while mobile data is in use, and 0 means the opposite. + // Optional custom parameter, which specifies whether to allow ad asset download using mobile data. The options are 0 (no) and 1 (yes). If this parameter is not set, the advertiser's setting will be used. allowMobileTraffic: 0, - // Set the maximum ad content rating. The following values are available: w: ages 3+, all audiences; PI: ages 7+, audiences under parental instruction; J: ages 12+, teenagers; A: ages 16+/18+, adults. - adContentClassification: 'A', // Specify whether you want your ad content to be treated as COPPA-compliant. The following values are available: -1 (default value): uncertain; 0: no; 1: yes. tagForChildProtection: -1, // Specify whether you want the ad request to be processed in a way that meets the GDPR for users in the EEA under the age of consent. The following values are available: -1 (default value): uncertain; 0: no; 1: yes. - tagForUnderAgeOfPromise: -1 - } + tagForUnderAgeOfPromise: -1, + // Maximum ad content rating. W: aged 3 and up; PI: aged 7 and up, under parental guidance; J: teenagers aged 12 and up; A: adults aged 16 or 18 and up. + adContentClassification: 'A' + }; // Listener for the ad loading status. const adLoaderListener: advertising.AdLoadListener = { // Called when the ad request fails. onAdLoadFailure: (errorCode: number, errorMsg: string) => { - hilog.error(0x0000, 'testTag', '%{public}s', - `request single ad errorCode is: ${errorCode}, errorMsg is: ${errorMsg}`); + hilog.error(0x0000, 'testTag', `Fail to load ad. Code is ${errorCode}, message is ${errorMsg}`); }, // Called when the ad request is successful. onAdLoadSuccess: (ads: Array) => { - hilog.info(0x0000, 'testTag', '%{public}s', 'succeed in requesting single ad!'); + hilog.info(0x0000, 'testTag', 'Succeed in loading ad'); // Save the requested ad content for display. const returnAds = ads; } }; // Create an AdLoader object. - const load: advertising.AdLoader = new advertising.AdLoader(context); + const adLoader: advertising.AdLoader = new advertising.AdLoader(context); // Load the ad. - hilog.info(0x0000, 'testTag', '%{public}s', 'request single ad!'); - load.loadAd(adRequestParam, adOptions, adLoaderListener); + hilog.info(0x0000, 'testTag', 'Start to load ad'); + adLoader.loadAd(adRequestParams, adOptions, adLoaderListener); } ``` - ### loadAdWithMultiSlots loadAdWithMultiSlots(adParams: AdRequestParams[], adOptions: AdOptions, listener: MultiSlotsAdLoadListener): void @@ -143,188 +518,79 @@ Loads multiple ads. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| adParams | [AdRequestParams](#adrequestparams)[] | Yes| Ad request parameters.| -| adOptions | [AdOptions](#adoptions) | Yes| Ad configuration.| -| listener | [MultiSlotsAdLoadListener](#multislotsadloadlistener) | Yes| Ad request callback.| +| Name | Type | Mandatory| Description | +|-----------|-------------------------------------------------------|----|-----------| +| adParams | [AdRequestParams](#adrequestparams)[] | Yes | Ad request parameters. | +| adOptions | [AdOptions](#adoptions) | Yes | Ad configuration. | +| listener | [MultiSlotsAdLoadListener](#multislotsadloadlistener) | Yes | Ad request callback.| **Error codes** For details about the following error codes, see [Ads Service Framework Error Codes](errorcode-ads.md). -| ID| Error Message| -| -------- | -------- | +| ID | Error Message | +|----------|--------------------------------------------------------------------------------------------------------------------------------------------------------| | 401 | Invalid input parameter. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | -| 801 | Device not supported. | -| 21800001 | System internal error. | -| 21800003 | Failed to load the ad request. | +| 801 | Device not supported. | +| 21800001 | System internal error. | +| 21800003 | Failed to load the ad request. | **Example** For details about how to obtain the context, see [Context](../../application-models/application-context-stage.md#overview). ```ts -import { advertising } from '@kit.AdsKit'; import { common } from '@kit.AbilityKit'; +import { advertising } from '@kit.AdsKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; -function requestMultiAd(context: common.Context): void { - const adRequestParamArray: advertising.AdRequestParams[] = [{ - // Ad type. - adType: 3, - // Ad ID. - adId: "testy63txaom86" - } as advertising.AdRequestParams, +function loadAdWithMultiSlots(context: common.Context): void { + const adRequestParamsArray: advertising.AdRequestParams[] = [ + { + // Ad type. + adType: 3, + // Ad ID. + adId: 'testy63txaom86' + }, { // Ad type. adType: 3, // Ad ID. - adId: "testy63txaom86" - } as advertising.AdRequestParams + adId: 'testy63txaom86' + } ]; const adOptions: advertising.AdOptions = { - // Optional custom parameter, which specifies whether the ad can be downloaded while mobile data is in use. The value 1 means that the ad can be downloaded while mobile data is in use, and 0 means the opposite. + // Optional custom parameter, which specifies whether to allow ad asset download using mobile data. The options are 0 (no) and 1 (yes). If this parameter is not set, the advertiser's setting will be used. allowMobileTraffic: 0, - // Set the maximum ad content rating. The following values are available: w: ages 3+, all audiences; PI: ages 7+, audiences under parental instruction; J: ages 12+, teenagers; A: ages 16+/18+, adults. - adContentClassification: 'A', // Specify whether you want your ad content to be treated as COPPA-compliant. The following values are available: -1 (default value): uncertain; 0: no; 1: yes. tagForChildProtection: -1, // Specify whether you want the ad request to be processed in a way that meets the GDPR for users in the EEA under the age of consent. The following values are available: -1 (default value): uncertain; 0: no; 1: yes. - tagForUnderAgeOfPromise: -1 + tagForUnderAgeOfPromise: -1, + // Maximum ad content rating. W: aged 3 and up; PI: aged 7 and up, under parental guidance; J: teenagers aged 12 and up; A: adults aged 16 or 18 and up. + adContentClassification: 'A' }; // Listener for the ad loading status. const multiSlotsAdLoaderListener: advertising.MultiSlotsAdLoadListener = { // Called when the ad request fails. onAdLoadFailure: (errorCode: number, errorMsg: string) => { - hilog.error(0x0000, 'testTag', '%{public}s', - `request multi ads errorCode is: ${errorCode}, errorMsg is: ${errorMsg}`); + hilog.error(0x0000, 'testTag', `Fail to load multiSlots ad. Code is ${errorCode}, message is ${errorMsg}`); }, // Called when the ad request is successful. onAdLoadSuccess: (ads: Map>) => { - hilog.info(0x0000, 'testTag', '%{public}s', 'succeed in requesting multi ads!'); + hilog.info(0x0000, 'testTag', 'Succeed in loading multiSlots ad'); // Save the requested ad content for display. - let returnAds: Array = []; + const returnAds: Array = []; ads.forEach((adsArray) => returnAds.push(...adsArray)); } }; // Create an AdLoader object. - const load: advertising.AdLoader = new advertising.AdLoader(context); + const adLoader: advertising.AdLoader = new advertising.AdLoader(context); // Load the ad. - hilog.info(0x0000, 'testTag', '%{public}s', 'request multi ads!'); - load.loadAdWithMultiSlots(adRequestParamArray, adOptions, multiSlotsAdLoaderListener); -} -``` - - -## showAd - -showAd(ad: Advertisement, options: AdDisplayOptions, context?: common.UIAbilityContext): void - -Shows a full-screen ad. - -**Atomic service API**: This API can be used in atomic services since API version 12. - -**System capability**: SystemCapability.Advertising.Ads - -**Parameters** - - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| ad | [Advertisement](#advertisement) | Yes| Ad object.| -| options | [AdDisplayOptions](#addisplayoptions) | Yes| Ad display parameters.| -| context | common.[UIAbilityContext](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md) | No| Context of the UIAbility. If this parameter is not set, the value is obtained from @ohos.app.ability.common.| - - -**Error codes** - - -For details about the following error codes, see [Ads Service Framework Error Codes](errorcode-ads.md). - - -| ID| Error Message| -| -------- | -------- | -| 401 | Invalid input parameter. Possible causes: 1. Mandatory parameters are left unspecified.| -| 21800001 | System internal error. | -| 21800004 | Failed to display the ad. | - - -**Example** - -```ts -import { advertising } from '@kit.AdsKit'; -import { hilog } from '@kit.PerformanceAnalysisKit'; -import { common } from '@kit.AbilityKit'; - -@Entry -@Component -export struct ShowAd { - private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext; - // Requested ad content. - private ad?: advertising.Advertisement; - // Ad display parameters. - private adDisplayOptions: advertising.AdDisplayOptions = { - // Whether to mute the ad. By default, the ad is not muted. - mute: false - } - - build() { - Column() { - Button ('Show Ad') - .onClick(() => { - try { - // Show the ad. - advertising.showAd(this.ad, this.adDisplayOptions, this.context); - } catch (err) { - hilog.error(0x0000, 'testTag', '%{public}s', `show ad catch error: ${err.code} ${err.message}`); - } - }); - } - .width('100%') - .height('100%') - } + hilog.info(0x0000, 'testTag', 'Start to load multiSlots ad'); + adLoader.loadAdWithMultiSlots(adRequestParamsArray, adOptions, multiSlotsAdLoaderListener); } ``` - -## AdOptions - -Defines the ad configuration. - -**Atomic service API**: This API can be used in atomic services since API version 12. - -**System capability**: SystemCapability.Advertising.Ads - - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| tagForChildProtection | number | No| Tag for child protection, which specifies whether you want the ad content to be treated as COPPA-compliant.
- **-1** (default value): uncertain. You do not want to specify whether the ad content needs to be treated as COPPA-compliant.
- **0**: No. You do not want the ad content to be treated as COPPA-compliant.
- 1: Yes. You want the ad content to be treated as COPPA-compliant. The default value is **-1**.| -| adContentClassification | string | No| Maximum ad content rating.
- **W**: ages 3+, all audiences.
-** PI**: ages 7+, audiences under parental instruction.
- **J**: ages 12+, teenagers.
- **A**: ages 16+/18+, adults. The default value is "".| -| nonPersonalizedAd | number | No| Whether to request only non-personalized ads.
- **0**: request for personalized and non-personalized ads.
- **1**: request for only non-personalized ads. If this parameter is left blank, the service logic prevails.| -| [key: string] | number \| boolean \| string \| undefined | No| Custom parameters.
- **totalDuration**: The value is of the number type, in seconds. This parameter is mandatory for roll ads and is used to set the total duration of roll ads.
- **placementAdCountDownDesc**: The value is of the string type. This parameter is optional for roll ads and is used to set the countdown description of roll ads. This parameter must be encoded using the **encodeURI()** API. If this parameter is set, the countdown description is displayed. Otherwise, only the countdown is displayed.
- **allowMobileTraffic**: The value is of the number type. This parameter is optional. It specifies whether ads can be downloaded while mobile data is in use. The value **1** means that ads can be downloaded while mobile data is in use, and **0** means the opposite.
- **tagForUnderAgeOfPromise**: The value is of the number type. This parameter is optional. It specifies whether you want the ad request to be processed in a way that meets the GDPR for users in the EEA under the age of consent. The value **-1** means that you do not specify whether the ad request should be processed in a way that meets the GDPR for users in the EEA under the age of consent. The value **0** means that you do not want the ad request to be processed in a way that meets the GDPR for users in the EEA under the age of consent, and **1** means the opposite.| - - -## AdRequestParams - -Defines the ad request parameters. - -**Atomic service API**: This API can be used in atomic services since API version 12. - -**System capability**: SystemCapability.Advertising.Ads - - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| adId | string | Yes| Ad ID| -| adType | number | No| Type of the requested ad.
- **1**: splash ad.
- **3**: native ad.
- **7**: rewarded ad.
- **8**: banner ad.
- **12**: interstitial ad.
- **60**: roll ad.| -| adCount | number | No| Number of ads requested. If this parameter is left blank, the service logic prevails.| -| adWidth | number | No| Ad width. The value must be greater than 0. If this parameter is left blank, the service logic prevails.| -| adHeight | number | No| Ad height. The value must be greater than 0. If this parameter is left blank, the service logic prevails.| -| adSearchKeyword | string | No| Ad keyword. If this parameter is left blank, "" is used by default.| -| [key: string] | number \| boolean \| string \| undefined | No| Custom parameters.| - - ## AdLoadListener Enumerates the callbacks used for the request for loading an ad. @@ -343,15 +609,16 @@ Called when an ad request fails. **System capability**: SystemCapability.Advertising.Ads -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| errorCode | number | Yes| Result code indicating the ad request failure.| -| errorMsg | string | Yes| Error message about the ad request failure.| +**Parameters** +| Name | Type | Mandatory| Description | +|-----------|--------|----|--------------| +| errorCode | number | Yes | Result code indicating the ad request failure. | +| errorMsg | string | Yes | Error message about the ad request failure.| ### onAdLoadSuccess -onAdLoadSuccess(ads: Array<advertising.Advertisement>): void +onAdLoadSuccess(ads: Array<Advertisement>): void Called when an ad request is successful. @@ -359,26 +626,25 @@ Called when an ad request is successful. **System capability**: SystemCapability.Advertising.Ads -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| ads | Array<advertising.[Advertisement](#advertisement)> | Yes| Ad data.| +**Parameters** +| Name| Type | Mandatory| Description | +|-----|----------------------------------------------|----|-------| +| ads | Array<[Advertisement](#advertisement)> | Yes | Ad data.| **Example** ```ts import { advertising } from '@kit.AdsKit'; -let adLoaderListener: advertising.AdLoadListener = { +const adLoaderListener: advertising.AdLoadListener = { onAdLoadFailure: (errorCode: number, errorMsg: string) => { }, onAdLoadSuccess: (ads: Array) => { } } - ``` - ## MultiSlotsAdLoadListener Enumerates the callbacks used for the request for loading multiple ads. @@ -397,15 +663,16 @@ Called when a request for loading multiple ads fails. **System capability**: SystemCapability.Advertising.Ads -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| errorCode | number | Yes| Result code indicating the ad request failure.| -| errorMsg | string | Yes| Error message about the ad request failure.| +**Parameters** +| Name | Type | Mandatory| Description | +|-----------|--------|----|--------------| +| errorCode | number | Yes | Result code indicating the ad request failure. | +| errorMsg | string | Yes | Error message about the ad request failure.| ### onAdLoadSuccess -onAdLoadSuccess(adsMap: Map<string, Array<advertising.Advertisement>>): void +onAdLoadSuccess(adsMap: Map<string, Array<Advertisement>>): void Called when a request for loading multiple ads is successful. @@ -413,17 +680,18 @@ Called when a request for loading multiple ads is successful. **System capability**: SystemCapability.Advertising.Ads -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| adsMap | Map<string, Array<advertising.[Advertisement](#advertisement)>>| Yes| Ad data.| +**Parameters** +| Name | Type | Mandatory| Description | +|--------|-----------------------------------------------------------------|----|-------| +| adsMap | Map<string, Array<[Advertisement](#advertisement)>> | Yes | Ad data.| **Example** ```ts import { advertising } from '@kit.AdsKit'; -let adLoaderListener: advertising.MultiSlotsAdLoadListener = { +const multiSlotsAdLoadListener: advertising.MultiSlotsAdLoadListener = { onAdLoadFailure: (errorCode: number, errorMsg: string) => { }, onAdLoadSuccess: (adsMap: Map>) => { @@ -431,51 +699,8 @@ let adLoaderListener: advertising.MultiSlotsAdLoadListener = { } ``` - -## Advertisement - - -Defines the requested ad content. - -**Atomic service API**: This API can be used in atomic services since API version 12. - -**System capability**: SystemCapability.Advertising.Ads - - -| Name| Type| Read-Only| Mandatory| Description| -| -------- | --------| -------- | -------- | -------- | -| adType | number | No|Yes| Ad type.| -| uniqueId | string | No|Yes| Unique ID of the ad.| -| rewarded | boolean | No|Yes| Whether users get rewarded for watching or clicking the ad.
- **true**: Users get rewarded.
- **false**: Users do not get rewarded.| -| shown | boolean | No|Yes| Whether the ad is shown.
- **true**: The ad is shown.
- **false**: The ad is not shown.| -| clicked | boolean | No|Yes| Whether the ad is clicked.
- **true**: The ad is clicked.
- **false**: The ad is not clicked.| -| rewardVerifyConfig | Map<string, string> | No|Yes| Server verification parameter.
{
customData: "test",
userId: "12345"
} | -| [key: string] | Object | No|Yes| Custom parameters.
- **isFullScreen**: The value is of the Boolean type. This parameter is used for splash ads to specify whether such an ad is in full-screen mode. The value **true** means that the ad is in full-screen mode, and **false** means that the ad is in half-screen mode.| - - -## AdDisplayOptions - - -Defines the ad display parameters. - -**Atomic service API**: This API can be used in atomic services since API version 12. - -**System capability**: SystemCapability.Advertising.Ads - - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| customData | string | No| Custom media data. It is used by the server to notify the media server that a user should be rewarded for interacting with the ad, so as to avoid spoofing. If this parameter is left blank, no notification is sent.| -| userId | string | No| User ID. It is used by the server to notify the media server that a user should be rewarded for interacting with the ad, so as to avoid spoofing. If this parameter is left blank, no notification is sent.| -| useMobileDataReminder | boolean | No| Whether to display a dialog box to notify users when they use mobile data to play videos or download applications.
- **true**: A dialog box is displayed.
- **false**: No dialog box is displayed. This parameter depends on the mobile data dialog box function. Currently, the complete function is not supported, and therefore the default value is not determined.| -| mute | boolean | No| Whether to mute the ad video.
- **true**: The ad video is muted.
- **false**: The ad video is not muted. If this parameter is left blank, the default value **true** is used.| -| audioFocusType | number | No| Type of the scenario where the audio focus is obtained during video playback.
- **0**: The focus is obtained when the video is played in mute or non-mute mode.
- **1**: The focus is not obtained when the video is played in mute mode.
- **2**: The focus is not obtained when the video is played in mute or non-mute mode. Currently, the function on which this API depends is not supported, and therefore the default value is not determined.| -| [key: string] | number \| boolean \| string \| undefined | No| Custom parameters.
- **refreshTime**: The value is of the number type, in ms. The value is in the range [30000, 120000]. This parameter is optional for the AutoAdComponent module and specifies the interval at which the ads rotate. If this parameter is set, ads are rotated at the interval specified by this parameter. Otherwise, ads are not rotated and only the first ad in the ad response is displayed.| - - ## AdInteractionListener - Defines the ad status change callback. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -484,7 +709,7 @@ Defines the ad status change callback. ### onStatusChanged -onStatusChanged(status: string, ad: advertising.[Advertisement](#advertisement), data: string) +onStatusChanged(status: string, ad: Advertisement, data: string) Called when the ad display status changes. @@ -492,221 +717,86 @@ Called when the ad display status changes. **System capability**: SystemCapability.Advertising.Ads -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| status | string | Yes| **status**: ad display status, which can be
**onAdOpen**, **onAdClose**, **onAdClick**, **onVideoPlayBegin**, **onVideoPlayEnd**, **onAdLoad**, **onAdFail**, **onMediaProgress**, **onMediaStart**, **onMediaPause**, **onMediaStop**, **onMediaComplete**, **onMediaError**, **onLandscape**, **onPortrait**, **onAdReward**, **onMediaCountDown**, or **onBackClicked**.| -| ad | advertising.[Advertisement](#advertisement) | Yes| Content of the ad.| -| data | string | Yes| Extended information.| +**Parameters** + +| Name | Type | Mandatory| Description | +|--------|---------------------------------|----|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| status | string | Yes | **status**: ad display status, which can be
**onAdOpen**, **onAdClose**, **onAdClick**, **onVideoPlayBegin**, **onVideoPlayEnd**, **onAdLoad**, **onAdFail**, **onMediaProgress**, **onMediaStart**, **onMediaPause**, **onMediaStop**, **onMediaComplete**, **onMediaError**, **onLandscape**, **onPortrait**, **onAdReward**, **onMediaCountDown**, or **onBackClicked**.| +| ad | [Advertisement](#advertisement) | Yes | Content of the ad. | +| data | string | Yes | Extended information. | **Example** ```ts import { advertising } from '@kit.AdsKit'; -let adInteractionListener: advertising.AdInteractionListener = { +const adInteractionListener: advertising.AdInteractionListener = { onStatusChanged: (status: string, ad: advertising.Advertisement, data: string) => { } } ``` -## getAdRequestBody12+ -getAdRequestBody(adParams: AdRequestParams[], adOptions: AdOptions): Promise<string> - -Obtains the body of an ad request. This API uses a promise to return the result. - -**System capability**: SystemCapability.Advertising.Ads - -**Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| adParams | [AdRequestParams[]](#adrequestparams) | Yes| Ad request parameters.| -| adOptions | [AdOptions](#adoptions) | Yes| Ad configuration.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<string> | Promise used to return the ad data of the string type.| - -**Error codes** - -For details about the following error codes, see [Ads Service Framework Error Codes](errorcode-ads.md). - -| ID| Error Message | -| -------- | -------------------------------- | -| 401 | Invalid input parameter. Possible causes: 1.Mandatory parameters are left unspecified | -| 801 | Device not supported. | -| 21800001 | System internal error. | - -**Example** - -```ts -import { hilog } from '@kit.PerformanceAnalysisKit'; -import { BusinessError } from '@kit.BasicServicesKit'; -import { advertising } from '@kit.AdsKit'; -import { Prompt } from '@kit.ArkUI'; - -function getAdRequestBody(): void { - let adReqParamsListForRequest: Array = []; - const adReqParams: Record = { - 'adId': 'testu7m3hc4gvm', - 'adType': 3, - 'adCount': 2, - 'adWidth': 100, - 'adHeight': 100 - }; - - adReqParamsListForRequest.push(adReqParams as advertising.AdRequestParams); - const adOption: Record = { - // Set the maximum ad content rating. The following values are available: w: ages 3+, all audiences; PI: ages 7+, audiences under parental instruction; J: ages 12+, teenagers; A: ages 16+/18+, adults. - 'adContentClassification': 'A', - // Set whether to request only non-personalized ads. 0: to request personalized ads and non-personalized ads; 1: to request only non-personalized ads. If this parameter is left blank, the service logic prevails. - 'nonPersonalizedAd': 0, - // Specify whether you want your ad content to be treated as COPPA-compliant. The following values are available: -1 (default value): uncertain; 0: no; 1: yes. - 'tagForChildProtection': 1, - // Specify whether you want the ad request to be processed in a way that meets the GDPR for users in the EEA under the age of consent. The following values are available: -1 (default value): uncertain; 0: no; 1: yes. - 'tagForUnderAgeOfPromise': -1 - }; - advertising.getAdRequestBody(adReqParamsListForRequest, adOption as advertising.AdOptions).then((data) => { - hilog.info(0x0000, 'testTag', '%{public}s', `succeeded in getting AdRequestBody by promise: ${data}`); - Prompt.showToast({ - message: data, - duration: 1000 - }); - }).catch((error: BusinessError) => { - hilog.error(0x0000, 'testTag', '%{public}s', - `getAdRequestBody failed, code: ${error.code}, message: ${error.message}`); - Prompt.showToast({ - message: error.code.toString() + ',' + error.message, - duration: 1000 - }); - }) -} -``` - -## parseAdResponse12+ +## AdOptions -parseAdResponse(adResponse: string, listener: MultiSlotsAdLoadListener, context: common.UIAbilityContext): void +Defines the ad configuration. -Parses the body of an ad response. +**Atomic service API**: This API can be used in atomic services since API version 12. **System capability**: SystemCapability.Advertising.Ads -**Parameters** - -| Name| Type | Mandatory| Description | -| ---------- | ------------------------------------------------------------ | ---- | ----------------------- | -| adResponse | string | Yes | Ad request parameters. | -| listener | [MultiSlotsAdLoadListener](#multislotsadloadlistener) | Yes | Ad request callback. | -| context | common.[UIAbilityContext](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md) | Yes | UIAbility context.| - -**Error codes** - -For details about the following error codes, see [Ads Service Framework Error Codes](errorcode-ads.md). - -| ID| Error Message | -| -------- | -------------------------------- | -| 401 | Invalid input parameter. Possible causes: 1.Mandatory parameters are left unspecified | -| 801 | Device not supported. | -| 21800001 | System internal error. | -| 21800005 | Failed to parse the ad response. | - -**Example** - -For details about how to obtain the context, see [Obtaining the Context of UIAbility](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md). - -```ts -import { common } from '@kit.AbilityKit'; -import { advertising } from '@kit.AdsKit'; -import { hilog } from '@kit.PerformanceAnalysisKit'; - -function parseAdResponse(adResponse: string, context: common.UIAbilityContext): void { - // Listen for the ad parsing callback. - const multiSlotsAdLoaderListener: advertising.MultiSlotsAdLoadListener = { - // Called when ad parsing fails. - onAdLoadFailure: (errorCode: number, errorMsg: string) => { - hilog.error(0x0000, 'testTag', '%{public}s', - `request multi ads errorCode is: ${errorCode}, errorMsg is: ${errorMsg}`); - }, - // Called when ad parsing is successful. - onAdLoadSuccess: (ads: Map>) => { - hilog.info(0x0000, 'testTag', '%{public}s', 'succeeded in requesting multi ads!'); - // Save the parsed ad content as an array for display. - let returnAds: Array = []; - ads.forEach((adsArray) => returnAds.push(...adsArray)); - } - }; - // Call the API to parse the response body. - hilog.info(0x0000, 'testTag', '%{public}s', 'parse ad response!'); - advertising.parseAdResponse(adResponse, multiSlotsAdLoaderListener, context); -} -``` - -## registerWebAdInterface12+ +| Name | Type | Read-Only| Optional| Description | +|-------------------------|------------------------------------------|----|----|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| tagForChildProtection | number | No | Yes | Tag for child protection, which specifies whether you want the ad content to be treated as COPPA-compliant.
- **-1** (default value): uncertain. You do not want to specify whether the ad content needs to be treated as COPPA-compliant.
- **0**: No. You do not want the ad content to be treated as COPPA-compliant.
- **1**: Yes. You want the ad content to be treated as COPPA-compliant.
| +| adContentClassification | string | No | Yes | Maximum ad content rating.
- **W**: ages 3+, all audiences.
- **PI**: ages 7+, audiences under parental instruction.
- **J**: ages 12+, teenagers.
- **A**: ages 16+/18+, adults.
If this parameter is left blank, the service logic prevails. | +| nonPersonalizedAd | number | No | Yes | Whether to request only non-personalized ads.
- **0**: request for personalized and non-personalized ads.
- **1**: request for only non-personalized ads.
If this parameter is left blank, the service logic prevails. | +| [key: string] | number \| boolean \| string \| undefined | No | Yes | Custom parameters.
- **totalDuration**: The value is of the number type, in seconds. This parameter is mandatory for roll ads and is used to set the total duration of roll ads.
- **placementAdCountDownDesc**: The value is of the string type. This parameter is optional for roll ads and is used to set the countdown description of roll ads. This parameter must be encoded using the **encodeURI()** API. If this parameter is set, the countdown description is displayed. Otherwise, only the countdown is displayed.
- **allowMobileTraffic**: The value is of the number type. This parameter is optional. It specifies whether ads can be downloaded while mobile data is in use. The options are **0** (no) and **1** (yes). If this parameter is not set, the advertiser's setting will be used.
- **tagForUnderAgeOfPromise**: The value is of the number type. This parameter is optional. It specifies whether you want the ad request to be processed in a way that meets the GDPR for users in the EEA under the age of consent. The value **-1** means that you do not specify whether the ad request should be processed in a way that meets the GDPR for users in the EEA under the age of consent. The value **0** means that you do not want the ad request to be processed in a way that meets the GDPR for users in the EEA under the age of consent, and **1** means the opposite.| -registerWebAdInterface(controller: web_webview.WebviewController, context: common.UIAbilityContext): void +## AdRequestParams -Injects an ad JavaScript object to the **Web** component. +Defines the ad request parameters. **Atomic service API**: This API can be used in atomic services since API version 12. **System capability**: SystemCapability.Advertising.Ads -**Parameters** - +| Name | Type | Read-Only| Optional| Description | +|-----------------|------------------------------------------|----|----|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| adId | string | No | No | Ad ID
- This parameter is optional for **getAdRequestBody**. | +| adType | number | No | Yes | Type of the requested ad.
- **1**: splash ad.
- **3**: native ad.
- **7**: rewarded ad.
- **8**: banner ad.
- **12**: interstitial ad.
- **60**: roll ad.
If this parameter is left blank, the native ad type is used by default. | +| adCount | number | No | Yes | Number of ads requested. If this parameter is left blank, the service logic prevails. | +| adWidth | number | No | Yes | Expected creative width of ads requested, in vp. This parameter is mandatory for banner ads. If this parameter is left blank, the service logic prevails. | +| adHeight | number | No | Yes | Expected creative height of ads requested, in vp. This parameter is mandatory for banner ads. If this parameter is left blank, the service logic prevails. | +| adSearchKeyword | string | No | Yes | Ad keyword. If this parameter is left blank, "" is used by default. | +| [key: string] | number \| boolean \| string \| undefined | No | Yes | Custom parameters.
- **isPreload**: A Boolean value used to distinguish common requests from preload requests when roll ads are requested. The value **true** indicates the preload request; the value **false** (default) indicates the common request. This parameter is valid only for roll ads. For other ad requests, this parameter is not parsed.
- **enableDirectReturnVideoAd**: A custom extended parameter of native ads, whose value is of Boolean type. It indicates whether to directly return the ad without waiting for the download of all ad materials. The value **true** means that the ad is loaded online without waiting for the download of all ad materials; the value **false** means that the ad is loaded from the local cache after the ad materials are downloaded. If this parameter is left blank, the configuration on the cloud prevails. This parameter is valid only for native ads. It is not parsed for other ad requests.
- **oaid**: A string indicates the Open Anonymous Device Identifier (OAID), which is used to precisely push ads. If this parameter is left blank, personalized ads cannot be obtained. Default value: **""**
- **tmax**: A number indicates the maximum timeout (including the network delay) of a transaction. The unit is millisecond.
- **cur**: A string indicates the currency supported by the bidding request. Multiple currencies are separated by commas (,). Currently, the following currencies are supported: **CNY**, **USD**, **EUR**, **GBP**, and **JPY**. If this parameter is left blank, the default value **CNY** is used.
- **bidFloor**: A number indicates the bid price floor of an ad.
- **bidFloorCur**: A string indicates the currency used by the bid price floor of an ad. If **bidFloor** is not empty, then **bidFlorCur** is also not empty. Currently, the following currencies are supported: **CNY**, **USD**, **EUR**, **GBP**, and **JPY**. If this parameter is left blank, the default value **CNY** is used.
- **bpkgName**: A string indicates the package name of the application that is forbidden to be displayed in an ad. Multiple application package names are passed and separated by commas (,).| -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| controller | web_webview.[WebviewController](../apis-arkweb/js-apis-webview.md#webviewcontroller) | Yes| Controller of the **Web** component.| -| context | common.[UIAbilityContext](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md) | Yes| UIAbility context.| - - -**Error codes** +## AdDisplayOptions +Defines the ad display parameters. -For details about the following error codes, see [Ads Service Framework Error Codes](errorcode-ads.md). +**Atomic service API**: This API can be used in atomic services since API version 12. +**System capability**: SystemCapability.Advertising.Ads -| ID| Error Message| -| -------- | -------- | -| 401 | Invalid input parameter. Possible causes: 1.Mandatory parameters are left unspecified | -| 21800001 | System internal error. | +| Name | Type | Read-Only| Optional| Description | +|-----------------------|------------------------------------------|----|----|--------------------------------------------------------------------------------------------------------------------------------------------------------| +| customData | string | No | Yes | Custom media data. It is used by the server to notify the media server that a user should be rewarded for interacting with the ad, so as to avoid spoofing. If this parameter is left blank, no notification is sent. | +| userId | string | No | Yes | User ID. It is used by the server to notify the media server that a user should be rewarded for interacting with the ad, so as to avoid spoofing. If this parameter is left blank, no notification is sent. | +| useMobileDataReminder | boolean | No | Yes | Whether to display a dialog box to notify users when they use mobile data to play videos or download applications.
- **true**: A dialog box is displayed.
- **false**: No dialog box is displayed.
This parameter depends on the mobile data dialog box function. Currently, the complete function is not supported, and therefore the default value is not determined. | +| mute | boolean | No | Yes | Whether to mute the ad video.
- **true**: The ad video is muted.
- **false**: The ad video is not muted.
If this parameter is left blank, the service logic prevails. | +| audioFocusType | number | No | Yes | Type of the scenario where the audio focus is obtained during video playback.
- **0**: The focus is obtained when the video is played in mute or non-mute mode.
- **1**: The focus is not obtained when the video is played in mute mode.
- **2**: The focus is not obtained when the video is played in mute or non-mute mode.
Currently, the function on which this API depends is not supported, and therefore the default value is not determined. | +| [key: string] | number \| boolean \| string \| undefined | No | Yes | Custom parameters.
- **refreshTime**: The value is of the number type, in ms. The value is in the range [30000, 120000]. This parameter is optional for the AutoAdComponent module and specifies the interval at which the ads rotate. If this parameter is set, ads are rotated at the interval specified by this parameter. Otherwise, ads are not rotated and only the first ad in the ad response is displayed.| +## Advertisement -**Example** +type Advertisement = _Advertisement -```ts -import { webview } from '@kit.ArkWeb'; -import { common } from '@kit.AbilityKit'; -import { advertising } from '@kit.AdsKit'; -import { hilog } from '@kit.PerformanceAnalysisKit'; +Defines the requested ad content. -@Entry -@Component -struct Index { - private webController: webview.WebviewController = new webview.WebviewController(); - private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext; +**Atomic service API**: This API can be used in atomic services since API version 12. - build() { - Column() { - Button('Inject Ad Object to Web') - .onClick(() => { - try { - advertising.registerWebAdInterface(this.webController, this.context); - } catch (err) { - hilog.error(0x0000, 'testTag', '%{public}s', - `register web ad interface error: ${err.code}, ${err.message}`); - } - }) +**System capability**: SystemCapability.Advertising.Ads - Web({ - src: 'www.example.com', - controller: this.webController, - }) - .width("100%") - .height("100%") - } - } -} -``` +| Type | Description | +|--------------------------------------------------------------|-------------------| +| [_Advertisement](js-apis-inner-advertising-advertisement.md) | Advertisement object.| diff --git a/en/application-dev/reference/apis-ads-kit/js-apis-autoadcomponent.md b/en/application-dev/reference/apis-ads-kit/js-apis-autoadcomponent.md index cb523ce515f0eb798dc72ce8386e7677c200484d..d4fe231cde9f44eaaeaab7d8a3b838f853612fee 100644 --- a/en/application-dev/reference/apis-ads-kit/js-apis-autoadcomponent.md +++ b/en/application-dev/reference/apis-ads-kit/js-apis-autoadcomponent.md @@ -1,21 +1,17 @@ # @ohos.advertising.AutoAdComponent (Carousel Ad Component) - The AutoAdComponent module provides the capability of displaying carousel ads. - > **NOTE** -> +> > The initial APIs of this module are supported since API version 11. Newly added APIs will be marked with a superscript to indicate their earliest API version. - ## Modules to Import ```ts import { AutoAdComponent } from '@kit.AdsKit'; ``` - ## AutoAdComponent AutoAdComponent(adParam: advertising.AdRequestParams, adOptions: advertising.AdOptions, displayOptions: advertising.AdDisplayOptions, interactionListener: advertising.AdInteractionListener): void @@ -26,31 +22,29 @@ Component used to automatically play ads. **System capability**: SystemCapability.Advertising.Ads - **Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| adParam | advertising.[AdRequestParams](js-apis-advertising.md#adrequestparams) | Yes| Ad request parameters.| -| adOptions | advertising.[AdOptions](js-apis-advertising.md#adoptions) | Yes| Ad configuration.| -| displayOptions | advertising.[AdDisplayOptions](js-apis-advertising.md#addisplayoptions) | Yes| Ad display parameters.| -| interactionListener | advertising.[AdInteractionListener](js-apis-advertising.md#adinteractionlistener) | Yes| Ad status change callback.| - +| Name | Type | Mandatory| Description | +|---------------------|-----------------------------------------------------------------------------------|----|-----------| +| adParam | advertising.[AdRequestParams](js-apis-advertising.md#adrequestparams) | Yes | Ad request parameters. | +| adOptions | advertising.[AdOptions](js-apis-advertising.md#adoptions) | Yes | Ad configuration. | +| displayOptions | advertising.[AdDisplayOptions](js-apis-advertising.md#addisplayoptions) | Yes | Ad display parameters. | +| interactionListener | advertising.[AdInteractionListener](js-apis-advertising.md#adinteractionlistener) | Yes | Ad status change callback.| **Example** + ```ts -import { AutoAdComponent, advertising } from '@kit.AdsKit'; +import { advertising, AutoAdComponent } from '@kit.AdsKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; @Entry @Component -export struct ShowCarouselAd { - private adRequestParam: advertising.AdRequestParams = { +struct Index { + private adRequestParams: advertising.AdRequestParams = { // Ad type. adType: 8, // Ad ID. - adId: "test1" + adId: 'testw6vs28auh3' }; private adOptions: advertising.AdOptions = { // Set the maximum ad content rating. @@ -62,13 +56,13 @@ export struct ShowCarouselAd { mute: false, // Interval at which the carousel items rotate, in ms. The value range is [30000, 120000]. refreshTime: 30000 - } + }; build() { Column() { // The AutoAdComponent is used to show the carousel ad in non-full-screen mode. AutoAdComponent({ - adParam: this.adRequestParam, + adParam: this.adRequestParams, adOptions: this.adOptions, displayOptions: this.adDisplayOptions, interactionListener: { @@ -76,13 +70,13 @@ export struct ShowCarouselAd { onStatusChanged: (status: string, ad: advertising.Advertisement, data: string) => { switch (status) { case 'onAdOpen': - hilog.info(0x0000, 'testTag', '%{public}s', 'onAdOpen'); + hilog.info(0x0000, 'testTag', 'onAdOpen'); break; case 'onAdClick': - hilog.info(0x0000, 'testTag', '%{public}s', 'onAdClick'); + hilog.info(0x0000, 'testTag', 'onAdClick'); break; case 'onAdClose': - hilog.info(0x0000, 'testTag', '%{public}s', 'onAdClose'); + hilog.info(0x0000, 'testTag', 'onAdClose'); break; } } @@ -90,7 +84,9 @@ export struct ShowCarouselAd { }) .width('100%') .height('100%') - }.width('100%').height('100%') + } + .width('100%') + .height('100%') } } ``` diff --git a/en/application-dev/reference/apis-ads-kit/js-apis-inner-advertising-advertisement.md b/en/application-dev/reference/apis-ads-kit/js-apis-inner-advertising-advertisement.md new file mode 100644 index 0000000000000000000000000000000000000000..eb97e21beb3d1304e40f948d46099cf5b2fa8437 --- /dev/null +++ b/en/application-dev/reference/apis-ads-kit/js-apis-inner-advertising-advertisement.md @@ -0,0 +1,28 @@ +# Advertisement + +Advertisement is the ad content requested by [advertising](js-apis-advertising.md#advertisement). + +> **NOTE** +> The initial APIs of this module are supported since API version 11. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```ts +import { advertising } from '@kit.AdsKit'; +``` + +## Attributes + +**Atomic service API**: This API can be used in atomic services since API version 12. + +**System capability**: SystemCapability.Advertising.Ads + +| Name | Type | Read-Only| Optional| Description | +|--------------------|---------------------------|----|----|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| adType | number | No | No | Ad type.
- **1**: splash ad.
- **3**: native ad.
- **7**: rewarded ad.
- **8**: banner ad.
- **12**: interstitial ad.
- **60**: roll ad.
If this parameter is left empty, the native ad is used by default. | +| uniqueId | string | No | No | Unique ID of the ad. | +| rewarded | boolean | No | No | Whether users get rewarded for watching or clicking the ad.
- **true**: Users get rewarded.
- **false**: Users do not get rewarded. | +| shown | boolean | No | No | Whether the ad is shown.
- **true**: The ad is shown.
- **false**: The ad is not shown. | +| clicked | boolean | No | No | Whether the ad is clicked.
- **true**: The ad is clicked.
- **false**: The ad is not clicked. | +| rewardVerifyConfig | Map<string, string> | No | No | Server verification parameter.
{
customData: "test",
userId: "12345"
} | +| [key: string] | Object | No | Yes | Custom parameter.
- **isFullScreen**: The value is of the Boolean type. It specifies whether a splash ad is in full-screen mode. The value **true** means that the ad is in full-screen mode, and **false** means that the ad is in half-screen mode.
- **biddingInfo**: An object containing ad information. It is used to obtain real-time bidding results. **biddingInfo.price**: the Effective Cost Per Mille (eCPM) of an ad. **biddingInfo.cur**: the currency of an ad. **biddingInfo.nurl**: URL used to specify the successful bidding results returned by the media. **biddingInfo.lurl**: URL used to notify other Demand-Side Platforms (DSPs) of the bidding success result when the bidding fails.| diff --git a/en/application-dev/reference/apis-ads-kit/js-apis-oaid-sys.md b/en/application-dev/reference/apis-ads-kit/js-apis-oaid-sys.md index abec22e6fe3d36ba01c913fc93e09542b485dc20..df357bd7002ae9f0eadd62e845cd66daa8ba3763 100644 --- a/en/application-dev/reference/apis-ads-kit/js-apis-oaid-sys.md +++ b/en/application-dev/reference/apis-ads-kit/js-apis-oaid-sys.md @@ -1,21 +1,16 @@ # @ohos.identifier.oaid (OAID) (System API) - The **OAID** module provides APIs for obtaining and resetting Open Anonymous Device Identifiers (OAIDs). - > **NOTE** -> > The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> > To use the APIs for obtaining OAIDs, you must [request the ohos.permission.APP_TRACKING_CONSENT permission](../../security/AccessToken/request-user-authorization.md). > This topic describes only system APIs provided by the module. For details about its public APIs, see [@ohos.identifier.oaid (OAID)](js-apis-oaid.md). - ## Modules to Import -``` -import identifier from '@ohos.identifier.oaid'; +```ts +import { identifier } from '@kit.AdsKit'; ``` ## identifier.resetOAID @@ -32,20 +27,21 @@ Resets an OAID. For details about the following error codes, see [OAID Error Codes](errorcode-oaid.md). -| ID | Error Message | -| -------- | -------- | +| ID | Error Message | +|----------|------------------------------------------------------------------------------| | 202 | Permission verification failed. A non-system application calls a system API. | -| 17300001 | System internal error. | -| 17300002 | Not in the trust list. | +| 17300001 | System internal error. | +| 17300002 | Not in the trust list. | **Example** -``` -import identifier from '@ohos.identifier.oaid'; -import hilog from '@ohos.hilog'; + +```ts +import { identifier } from '@kit.AdsKit'; +import { hilog } from '@kit.PerformanceAnalysisKit'; try { identifier.resetOAID(); } catch (err) { - hilog.error(0x0000, 'testTag', '%{public}s', `reset oaid catch error: ${err.code} ${err.message}`); + hilog.error(0x0000, 'testTag', `Fail to reset OAID. Code is ${err.code}, message is ${err.message}`); } ``` diff --git a/en/application-dev/reference/apis-ads-kit/js-apis-oaid.md b/en/application-dev/reference/apis-ads-kit/js-apis-oaid.md index 7f24fa7b1891e912cd63eff1e60ff8ade0735a6a..098f35ba11f82af4636b7d1b36865484d4c09185 100644 --- a/en/application-dev/reference/apis-ads-kit/js-apis-oaid.md +++ b/en/application-dev/reference/apis-ads-kit/js-apis-oaid.md @@ -1,23 +1,17 @@ # @ohos.identifier.oaid (OAID) - The **OAID** module provides APIs for obtaining Open Anonymous Device Identifiers (OAIDs). - > **NOTE** -> > The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> > To use the APIs for obtaining OAIDs, you must [request the ohos.permission.APP_TRACKING_CONSENT permission](../../security/AccessToken/request-user-authorization.md). - ## Modules to Import -``` +```ts import { identifier } from '@kit.AdsKit'; ``` - ## identifier.getOAID getOAID(): Promise<string> @@ -30,38 +24,33 @@ Obtains an OAID. This API uses a promise to return the result. **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +|-----------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Promise<string> | Promise used to return the OAID.
1. If the application has configured the permission **ohos.permission.APP_TRACKING_CONSENT** and the permission is allowed, the OAID is returned.
2. If the application has configured the permission **ohos.permission.APP_TRACKING_CONSENT** and the permission is disallowed, 00000000-0000-0000-0000-000000000000 is returned.
3. If the application has not configured the permission **ohos.permission.APP_TRACKING_CONSENT**, 00000000-0000-0000-0000-000000000000 is returned.| **Error codes** For details about the following error codes, see [OAID Error Codes](errorcode-oaid.md). -| ID| Error Message| -| -------- | -------- | +| ID | Error Message | +|----------|----------------------------------| | 17300001 | System internal error. | **Example** -``` + +```ts import { identifier } from '@kit.AdsKit'; -import { hilog } from '@kit.PerformanceAnalysisKit'; import { BusinessError } from '@kit.BasicServicesKit'; +import { hilog } from '@kit.PerformanceAnalysisKit'; -try { - identifier.getOAID().then((data) => { - const oaid: string = data; - hilog.info(0x0000, 'testTag', '%{public}s', `succeeded in getting oaid by promise, oaid: ${oaid}`); - }).catch((err: BusinessError) => { - hilog.error(0x0000, 'testTag', '%{public}s', - `get oaid by promise failed, code: ${err.code}, message: ${err.message}`); - }) -} catch (err) { - hilog.error(0x0000, 'testTag', '%{public}s', `get oaid by promise catch error: ${err.code} ${err.message}`); -} +identifier.getOAID().then((data) => { + const oaid: string = data; + hilog.info(0x0000, 'testTag', `Succeed in getting oaid. Oaid is ${oaid}`); +}).catch((err: BusinessError) => { + hilog.error(0x0000, 'testTag', `Fail to get oaid. Code is ${err.code}, message is ${err.message}`); +}) ``` - ## identifier.getOAID getOAID(callback: AsyncCallback<string>): void @@ -74,39 +63,31 @@ Obtains an OAID. This API uses an asynchronous callback to return the result. **Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<string> | Yes| Callback used to return the OAID.
1. If the application has configured the permission **ohos.permission.APP_TRACKING_CONSENT** and the permission is allowed, the OAID is returned.
2. If the application has configured the permission **ohos.permission.APP_TRACKING_CONSENT** and the permission is disallowed, 00000000-0000-0000-0000-000000000000 is returned.
3. If the application has not configured the permission **ohos.permission.APP_TRACKING_CONSENT**, 00000000-0000-0000-0000-000000000000 is returned.| - +| Name | Type | Mandatory| Description | +|----------|-----------------------------|----|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| callback | AsyncCallback<string> | Yes | Callback used to return the OAID.
1. If the application has configured the permission **ohos.permission.APP_TRACKING_CONSENT** and the permission is allowed, the OAID is returned.
2. If the application has configured the permission **ohos.permission.APP_TRACKING_CONSENT** and the permission is disallowed, 00000000-0000-0000-0000-000000000000 is returned.
3. If the application has not configured the permission **ohos.permission.APP_TRACKING_CONSENT**, 00000000-0000-0000-0000-000000000000 is returned.| **Error codes** - For details about the following error codes, see [OAID Error Codes](errorcode-oaid.md). - -| ID| Error Message| -| -------- | -------- | +| ID | Error Message | +|----------|----------------------------------| | 17300001 | System internal error. | - **Example** -``` + +```ts import { identifier } from '@kit.AdsKit'; -import { hilog } from '@kit.PerformanceAnalysisKit'; import { BusinessError } from '@kit.BasicServicesKit'; +import { hilog } from '@kit.PerformanceAnalysisKit'; -try { - identifier.getOAID((err: BusinessError, data: string) => { - if (err.code) { - hilog.error(0x0000, 'testTag', '%{public}s', `get oaid by callback failed, error: ${err.code} ${err.message}`); - } else { - const oaid: string = data; - hilog.info(0x0000, 'testTag', '%{public}s', 'succeed in getting oaid by callback'); - } - }); -} catch (err) { - hilog.error(0x0000, 'testTag', '%{public}s', `get oaid by callback catch error: ${err.code} ${err.message}`); -} +identifier.getOAID((err: BusinessError, data: string) => { + if (err.code) { + hilog.error(0x0000, 'testTag', `Fail to get oaid. Code is ${err.code}, message is ${err.message}`); + } else { + const oaid: string = data; + hilog.info(0x0000, 'testTag', `Succeed in getting oaid. Oaid is ${oaid}`); + } +}); ``` diff --git a/en/application-dev/reference/apis-arkdata/Readme-EN.md b/en/application-dev/reference/apis-arkdata/Readme-EN.md index 0900c247a749a70c0e063b7e1fdca79474f40f7c..5a50f9fed9347e4e960bd2a29c74dbadbd95febc 100644 --- a/en/application-dev/reference/apis-arkdata/Readme-EN.md +++ b/en/application-dev/reference/apis-arkdata/Readme-EN.md @@ -1,6 +1,6 @@ # ArkData (ArkData Management) -- ArkTS APIs +- ArkTS APIs - [@ohos.data.commonType (Common Data Types)](js-apis-data-commonType.md) - [@ohos.data.dataAbility (DataAbility Predicates)](js-apis-data-ability.md) - [@ohos.data.dataSharePredicates (DataShare Predicates)](js-apis-data-dataSharePredicates.md) @@ -14,6 +14,7 @@ - [@ohos.data.uniformDataStruct (Uniform Data Structs)](js-apis-data-uniformDataStruct.md) - [@ohos.data.uniformTypeDescriptor (Uniform Data Definition and Description)](js-apis-data-uniformTypeDescriptor.md) - [@ohos.data.ValuesBucket (Value Bucket)](js-apis-data-valuesBucket.md) + - [@ohos.data.intelligence (ArkData Intelligence Platform)](js-apis-data-intelligence.md) - [@ohos.application.DataShareExtensionAbility (DataShare ExtensionAbility) (System API)](js-apis-application-dataShareExtensionAbility-sys.md) @@ -21,26 +22,28 @@ - [@ohos.data.cloudData (Device-Cloud Service) (System API)](js-apis-data-cloudData-sys.md) - [@ohos.data.cloudExtension (Device-Cloud Sharing Extension) (System API)](js-apis-data-cloudExtension-sys.md) + - [@ohos.data.collaborationEditObject (Collaboration Edit Object) (System API)](js-apis-data-collaborationEditObject-sys.md) - [@ohos.data.dataShare (DataShare) (System API)](js-apis-data-dataShare-sys.md) - [@ohos.data.dataSharePredicates (DataShare Predicates) (System API)](js-apis-data-dataSharePredicates-sys.md) - [@ohos.data.dataShareResultSet (DataShare Result Set) (System API)](js-apis-data-DataShareResultSet-sys.md) - [@ohos.data.distributedKVStore (Distributed KV Store) (System API)](js-apis-distributedKVStore-sys.md) + - [@ohos.data.graphStore (Graph Database) (System API)](js-apis-data-graphStore-sys.md) - [@ohos.data.relationalStore (RDB Store) (System API)](js-apis-data-relationalStore-sys.md) - - APIs No Longer Maintained + - APIs No Longer Maintained - [@ohos.data.distributedData (Distributed Data Management)](js-apis-distributed-data.md) - [@ohos.data.rdb (RDB)](js-apis-data-rdb.md) - [@ohos.data.storage (Lightweight Data Storage)](js-apis-data-storage.md) - [@system.storage (Data Storage)](js-apis-system-storage.md) - data/rdb - [resultSet (Result Set)](js-apis-data-resultset.md) -- C APIs - - Modules +- C APIs + - Modules - [Data](_data.md) - [RDB](_r_d_b.md) - [UDMF](_u_d_m_f.md) - [Preferences](_preferences.md) - - Header Files + - Header Files - [data_asset.h](data__asset_8h.md) - [oh_cursor.h](oh__cursor_8h.md) - [oh_data_value.h](oh__data__value_8h.md) @@ -48,6 +51,7 @@ - [oh_data_values_buckets.h](oh__data__values__buckets_8h.md) - [oh_predicates.h](oh__predicates_8h.md) - [oh_rdb_transaction.h](oh__rdb__transaction_8h.md) + - [oh_rdb_types.h](oh__rdb__types_8h.md) - [oh_value_object.h](oh__value__object_8h.md) - [oh_values_bucket.h](oh__values__bucket_8h.md) - [relational_store_error_code.h](relational__store__error__code_8h.md) @@ -61,7 +65,7 @@ - [oh_preferences_err_code.h](oh__preferences__err__code_8h.md) - [oh_preferences_option.h](oh__preferences__option_8h.md) - [oh_preferences_value.h](oh__preferences__value_8h.md) - - Structs + - Structs - [OH_Cursor](_o_h___cursor.md) - [OH_Predicates](_o_h___predicates.md) - [OH_Rdb_Config](_o_h___rdb___config.md) @@ -78,10 +82,15 @@ - [Rdb_Statistic](_rdb___statistic.md) - [Rdb_SubscribeCallback](union_rdb___subscribe_callback.md) - [Rdb_TableDetails](_rdb___table_details.md) -- Error Codes +- Error Codes + + - [Graph Store Error Codes](errorcode-data-gdb.md) + - [RDB Error Codes](errorcode-data-rdb.md) - [DataShare Error Codes](errorcode-datashare.md) - [Distributed Data Object Error Codes](errorcode-distributed-dataObject.md) - [Distributed KV Store Error Codes](errorcode-distributedKVStore.md) - [User Preferences Error Codes](errorcode-preferences.md) - [UDMF Error Codes](errorcode-udmf.md) + - [AIP Error Codes](errorcode-intelligence.md) + - [Collaboration Edit Object Error Codes](errorcode-collaboration-edit-object.md) diff --git a/en/application-dev/reference/apis-arkdata/_preferences.md b/en/application-dev/reference/apis-arkdata/_preferences.md index 2c17989812d87755818ca8573d56d56f1c1f7c03..e6ae2447db758f29a7ca9b1fe45e7984b9cc0395 100644 --- a/en/application-dev/reference/apis-arkdata/_preferences.md +++ b/en/application-dev/reference/apis-arkdata/_preferences.md @@ -34,6 +34,7 @@ The **Preferences** module provides APIs for key-value (KV) data processing, inc | typedef enum [Preference_ValueType](#preference_valuetype) [Preference_ValueType](#preference_valuetype) | Defines an enum for types of **PreferencesValue**.| | typedef struct [OH_PreferencesPair](#oh_preferencespair) [OH_PreferencesPair](#oh_preferencespair) | Defines a struct for the Preferences data in KV format.| | typedef struct [OH_PreferencesValue](#oh_preferencesvalue) [OH_PreferencesValue](#oh_preferencesvalue) | Defines the struct for a **PreferencesValue** object.| +| typedef enum [Preferences_StorageType](#preferences_storagetype) [Preferences_StorageType](#preferences_storagetype) | Defines an enum for preferences storage types.| ### Enums @@ -42,12 +43,14 @@ The **Preferences** module provides APIs for key-value (KV) data processing, inc | -------- | -------- | | [OH_Preferences_ErrCode](#oh_preferences_errcode-1) {
PREFERENCES_OK = 0, PREFERENCES_ERROR_INVALID_PARAM = 401, PREFERENCES_ERROR_NOT_SUPPORTED = 801, PREFERENCES_ERROR_BASE = 15500000,
PREFERENCES_ERROR_DELETE_FILE = 15500010, PREFERENCES_ERROR_STORAGE = 15500011, PREFERENCES_ERROR_MALLOC = 15500012, PREFERENCES_ERROR_KEY_NOT_FOUND = 15500013,
PREFERENCES_ERROR_GET_DATAOBSMGRCLIENT = 15500019
} | Enumerates the error codes.| | [Preference_ValueType](#preference_valuetype-1) {
PREFERENCE_TYPE_NULL = 0, PREFERENCE_TYPE_INT, PREFERENCE_TYPE_BOOL, PREFERENCE_TYPE_STRING,
PREFERENCE_TYPE_BUTT
} | Enumerates the types of **PreferencesValue**.| - +| [Preferences_StorageType](#preferences_storagetype-1) { PREFERENCES_STORAGE_XML = 0, PREFERENCES_STORAGE_GSKV } | Enumerates the preferences storage types.| ### Functions | Name| Description| | -------- | -------- | +| int [OH_PreferencesOption_SetStorageType](#oh_preferencesoption_setstoragetype) ([OH_PreferencesOption](#oh_preferencesoption) \*option, [Preferences_StorageType](#preferences_storagetype) type) | Sets the storage type for a preferences instance.| +| int [OH_Preferences_IsStorageTypeSupported](#oh_preferences_isstoragetypesupported) ([Preferences_StorageType](#preferences_storagetype) type, bool \*isSupported) | Checks whether the specified storage type is supported.| | [OH_Preferences](#oh_preferences) \* [OH_Preferences_Open](#oh_preferences_open) ([OH_PreferencesOption](#oh_preferencesoption) \*option, int \*errCode) | Opens a **Preferences** instance and creates a pointer to it. If the pointer is no longer required, use [OH_Preferences_Close][OH_Preferences_Close](#oh_preferences_close) to close the instance.| | int [OH_Preferences_Close](#oh_preferences_close) ([OH_Preferences](#oh_preferences) \*preference) | Closes a **Preferences** instance.| | int [OH_Preferences_GetInt](#oh_preferences_getint) ([OH_Preferences](#oh_preferences) \*preference, const char \*key, int \*value) | Obtains an integer corresponding to the specified key in a **Preferences** instance.| @@ -60,7 +63,7 @@ The **Preferences** module provides APIs for key-value (KV) data processing, inc | int [OH_Preferences_Delete](#oh_preferences_delete) ([OH_Preferences](#oh_preferences) \*preference, const char \*key) | Deletes the KV data corresponding to the specified key from a **Preferences** instance.| | int [OH_Preferences_RegisterDataObserver](#oh_preferences_registerdataobserver) ([OH_Preferences](#oh_preferences) \*preference, void \*context, [OH_PreferencesDataObserver](#oh_preferencesdataobserver) observer, const char \*keys[], uint32_t keyCount) | Subscribes to data changes of the specified keys. If the value of the specified key changes, a callback will be invoked after **OH_Preferences_Close ()** is called.| | int [OH_Preferences_UnregisterDataObserver](#oh_preferences_unregisterdataobserver) ([OH_Preferences](#oh_preferences) \*preference, void \*context, [OH_PreferencesDataObserver](#oh_preferencesdataobserver) observer, const char \*keys[], uint32_t keyCount) | Unsubscribes from data changes of the specified keys.| -| [OH_PreferencesOption](#oh_preferencesoption) \* [OH_PreferencesOption_Create](#oh_preferencesoption_create) (void) | Creates an [OH_PreferencesOption](#oh_preferencesoption) instance and a pointer to it. If this pointer is no longer required, use [OH_PreferencesOption_Destroy](#oh_preferencesoption_destroy) to destroy it. Otherwise, memory leaks may occur.| +| [OH_PreferencesOption](#oh_preferencesoption) \* [OH_PreferencesOption_Create](#oh_preferencesoption_create) (void) | Creates an [OH_PreferencesOption](#oh_preferencesoption) instance and a pointer to it.
If this pointer is no longer required, use [OH_PreferencesOption_Destroy](#oh_preferencesoption_destroy) to destroy it. Otherwise, memory leaks may occur.| | int [OH_PreferencesOption_SetFileName](#oh_preferencesoption_setfilename) ([OH_PreferencesOption](#oh_preferencesoption) \*option, const char \*fileName) | Sets the file name for an [OH_PreferencesOption](#oh_preferencesoption) instance.| | int [OH_PreferencesOption_SetBundleName](#oh_preferencesoption_setbundlename) ([OH_PreferencesOption](#oh_preferencesoption) \*option, const char \*bundleName) | Sets the bundle name for an [OH_PreferencesOption](#oh_preferencesoption) instance.| | int [OH_PreferencesOption_SetDataGroupId](#oh_preferencesoption_setdatagroupid) ([OH_PreferencesOption](#oh_preferencesoption) \*option, const char \*dataGroupId) | Sets the application group ID for an [OH_PreferencesOption](#oh_preferencesoption) instance.| @@ -75,6 +78,17 @@ The **Preferences** module provides APIs for key-value (KV) data processing, inc ## Type Description +### Preferences_StorageType + +``` +typedef enum Preferences_StorageType Preferences_StorageType +``` + +**Description** + +Defines an enum for preferences storage types. + +**Since**: 18 ### OH_Preferences @@ -181,6 +195,22 @@ Defines an enum for types of **PreferencesValue**. ## Enum Description +### Preferences_StorageType + +``` +enum Preferences_StorageType +``` + +**Description** + +Enumerates the preferences storage types. + +**Since**: 18 + +| Enumerated Value| Description| +| -------- | -------- | +| PREFERENCES_STORAGE_XML | XML. In this type is used, data operations are performed in the memory and data is persisted after [OH_Preferences_Close](#oh_preferences_close) is called. This type does not multi-processes operations.| +| PREFERENCES_STORAGE_GSKV | CLKV. If this type is used, data operations are flushed on a real-time basis. This type supports multi-process operations.| ### OH_Preferences_ErrCode @@ -231,6 +261,66 @@ Enumerates the types of **PreferencesValue**. ## Function Description +### OH_Preferences_IsStorageTypeSupported() + +``` +int OH_Preferences_IsStorageTypeSupported (Preferences_StorageType type, bool *isSupported ) +``` + +**Description** + +Checks whether the specified storage type is supported. + +**Since**: 18 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| type | Storage type to check.| +| isSupported | Pointer to the check result. The value **true** means the storage type is supported; the value **false** means the opposite.| + +**Returns** + +Returns the operation status code. + +**PREFERENCES_OK** indicates the operation is successful. + +**PREFERENCES_ERROR_INVALID_PARAM** indicates invalid parameters are specified. + + +### OH_PreferencesOption_SetStorageType() + +``` +int OH_PreferencesOption_SetStorageType (OH_PreferencesOption *option, Preferences_StorageType type ) +``` + +**Description** + +Sets the storage type for a preferences instance. + +**Since**: 18 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| option | Pointer to the configuration whose storage type is to set.| +| type | Storage type to set.| + +**Returns** + +Returns the error code. + +**PREFERENCES_OK** indicates the operation is successful. + +**PREFERENCES_ERROR_INVALID_PARAM** indicates invalid parameters are specified. + +**See** + +[OH_PreferencesOption](#oh_preferencesoption). + + ### OH_Preferences_Close() ``` @@ -253,13 +343,13 @@ Closes a **Preferences** instance. Returns [OH_Preferences_ErrCode](#oh_preferences_errcode). -Returns **PREFERENCES_OK** if the operation is successful. +**PREFERENCES_OK** indicates the operation is successful. -Returns **PREFERENCES_ERROR_INVALID_PARAM** if invalid parameters are detected. +**PREFERENCES_ERROR_INVALID_PARAM** indicates invalid parameters are specified. -Returns **PREFERENCES_ERROR_STORAGE** if the storage is abnormal. +**PREFERENCES_ERROR_STORAGE** indicates the storage is abnormal. -Returns **PREFERENCES_ERROR_MALLOC** if memory allocation fails. +**PREFERENCES_ERROR_MALLOC** indicates a failure in memory allocation. **See** @@ -291,13 +381,13 @@ Deletes the KV data corresponding to the specified key from a **Preferences** in Returns the error code. -Returns **PREFERENCES_OK** if the operation is successful. +**PREFERENCES_OK** indicates the operation is successful. -Returns **PREFERENCES_ERROR_INVALID_PARAM** if invalid parameters are detected. +**PREFERENCES_ERROR_INVALID_PARAM** indicates invalid parameters are specified. -Returns **PREFERENCES_ERROR_STORAGE** if the storage is abnormal. +**PREFERENCES_ERROR_STORAGE** indicates the storage is abnormal. -Returns **PREFERENCES_ERROR_MALLOC** if memory allocation fails. +**PREFERENCES_ERROR_MALLOC** indicates a failure in memory allocation. **See** @@ -353,15 +443,15 @@ Obtains a Boolean value corresponding to the specified key in a **Preferences** Returns the error code. -Returns **PREFERENCES_OK** if the operation is successful. +**PREFERENCES_OK** indicates the operation is successful. -Returns **PREFERENCES_ERROR_INVALID_PARAM** if invalid parameters are detected. +**PREFERENCES_ERROR_INVALID_PARAM** indicates invalid parameters are specified. -Returns **PREFERENCES_ERROR_STORAGE** if the storage is abnormal. +**PREFERENCES_ERROR_STORAGE** indicates the storage is abnormal. -Returns **PREFERENCES_ERROR_MALLOC** if memory allocation fails. +**PREFERENCES_ERROR_MALLOC** indicates a failure in memory allocation. -Returns **PREFERENCES_ERROR_KEY_NOT_FOUND** if the specified key does not exist. +**PREFERENCES_ERROR_KEY_NOT_FOUND** indicates that the specified key does not exist. **See** @@ -394,15 +484,15 @@ Obtains an integer corresponding to the specified key in a **Preferences** insta Returns the error code. -Returns **PREFERENCES_OK** if the operation is successful. +**PREFERENCES_OK** indicates the operation is successful. -Returns **PREFERENCES_ERROR_INVALID_PARAM** if invalid parameters are detected. +**PREFERENCES_ERROR_INVALID_PARAM** indicates invalid parameters are specified. -Returns **PREFERENCES_ERROR_STORAGE** if the storage is abnormal. +**PREFERENCES_ERROR_STORAGE** indicates the storage is abnormal. -Returns **PREFERENCES_ERROR_MALLOC** if memory allocation fails. +**PREFERENCES_ERROR_MALLOC** indicates a failure in memory allocation. -Returns **PREFERENCES_ERROR_KEY_NOT_FOUND** if the specified key does not exist. +**PREFERENCES_ERROR_KEY_NOT_FOUND** indicates that the specified key does not exist. **See** @@ -436,15 +526,15 @@ Obtains a string corresponding to the specified key in a **Preferences** instanc Returns the error code. -Returns **PREFERENCES_OK** if the operation is successful. +**PREFERENCES_OK** indicates the operation is successful. -Returns **PREFERENCES_ERROR_INVALID_PARAM** if invalid parameters are detected. +**PREFERENCES_ERROR_INVALID_PARAM** indicates invalid parameters are specified. -Returns **PREFERENCES_ERROR_STORAGE** if the storage is abnormal. +**PREFERENCES_ERROR_STORAGE** indicates the storage is abnormal. -Returns **PREFERENCES_ERROR_MALLOC** if memory allocation fails. +**PREFERENCES_ERROR_MALLOC** indicates a failure in memory allocation. -Returns **PREFERENCES_ERROR_KEY_NOT_FOUND** if the specified key does not exist. +**PREFERENCES_ERROR_KEY_NOT_FOUND** indicates that the specified key does not exist. **See** @@ -511,15 +601,15 @@ Subscribes to data changes of the specified keys. If the value of the specified Returns the error code. -Returns **PREFERENCES_OK** if the operation is successful. +**PREFERENCES_OK** indicates the operation is successful. -Returns **PREFERENCES_ERROR_INVALID_PARAM** if invalid parameters are detected. +**PREFERENCES_ERROR_INVALID_PARAM** indicates invalid parameters are specified. -Returns **PREFERENCES_ERROR_STORAGE** if the storage is abnormal. +**PREFERENCES_ERROR_STORAGE** indicates the storage is abnormal. -Returns **PREFERENCES_ERROR_MALLOC** if memory allocation fails. +**PREFERENCES_ERROR_MALLOC** indicates a failure in memory allocation. -Returns **PREFERENCES_ERROR_GET_DATAOBSMGRCLIENT** if the data change subscription service fails to be obtained. +**PREFERENCES_ERROR_GET_DATAOBSMGRCLIENT** indicates a failure in obtaining the data change subscription service. **See** @@ -554,13 +644,13 @@ Sets a Boolean value based on the specified key in a **Preferences** instance. Returns the error code. -Returns **PREFERENCES_OK** if the operation is successful. +**PREFERENCES_OK** indicates the operation is successful. -Returns **PREFERENCES_ERROR_INVALID_PARAM** if invalid parameters are detected. +**PREFERENCES_ERROR_INVALID_PARAM** indicates invalid parameters are specified. -Returns **PREFERENCES_ERROR_STORAGE** if the storage is abnormal. +**PREFERENCES_ERROR_STORAGE** indicates the storage is abnormal. -Returns **PREFERENCES_ERROR_MALLOC** if memory allocation fails. +**PREFERENCES_ERROR_MALLOC** indicates a failure in memory allocation. **See** @@ -593,13 +683,13 @@ Sets an integer based on the specified key in a **Preferences** instance. Returns the error code. -Returns **PREFERENCES_OK** if the operation is successful. +**PREFERENCES_OK** indicates the operation is successful. -Returns **PREFERENCES_ERROR_INVALID_PARAM** if invalid parameters are detected. +**PREFERENCES_ERROR_INVALID_PARAM** indicates invalid parameters are specified. -Returns **PREFERENCES_ERROR_STORAGE** if the storage is abnormal. +**PREFERENCES_ERROR_STORAGE** indicates the storage is abnormal. -Returns **PREFERENCES_ERROR_MALLOC** if memory allocation fails. +**PREFERENCES_ERROR_MALLOC** indicates a failure in memory allocation. **See** @@ -632,13 +722,13 @@ Sets a string based on the specified key in a **Preferences** instance. Returns the error code. -Returns **PREFERENCES_OK** if the operation is successful. +**PREFERENCES_OK** indicates the operation is successful. -Returns **PREFERENCES_ERROR_INVALID_PARAM** if invalid parameters are detected. +**PREFERENCES_ERROR_INVALID_PARAM** indicates invalid parameters are specified. -Returns **PREFERENCES_ERROR_STORAGE** if the storage is abnormal. +**PREFERENCES_ERROR_STORAGE** indicates the storage is abnormal. -Returns **PREFERENCES_ERROR_MALLOC** if memory allocation fails. +**PREFERENCES_ERROR_MALLOC** indicates a failure in memory allocation. **See** @@ -673,13 +763,13 @@ Unsubscribes from data changes of the specified keys. Returns the error code. -Returns **PREFERENCES_OK** if the operation is successful. +**PREFERENCES_OK** indicates the operation is successful. -Returns **PREFERENCES_ERROR_INVALID_PARAM** if invalid parameters are detected. +**PREFERENCES_ERROR_INVALID_PARAM** indicates invalid parameters are specified. -Returns **PREFERENCES_ERROR_STORAGE** if the storage is abnormal. +**PREFERENCES_ERROR_STORAGE** indicates the storage is abnormal. -Returns **PREFERENCES_ERROR_MALLOC** if memory allocation fails. +**PREFERENCES_ERROR_MALLOC** indicates a failure in memory allocation. **See** @@ -698,7 +788,7 @@ OH_PreferencesOption* OH_PreferencesOption_Create (void ) **Description** -Creates an [OH_PreferencesOption](#oh_preferencesoption) instance and a pointer to it. If this pointer is no longer required, use [OH_PreferencesOption_Destroy](#oh_preferencesoption_destroy) to destroy it. Otherwise, memory leaks may occur. +Creates an [OH_PreferencesOption](#oh_preferencesoption) instance and a pointer to it.
If this pointer is no longer required, use [OH_PreferencesOption_Destroy](#oh_preferencesoption_destroy) to destroy it. Otherwise, memory leaks may occur. **Since**: 13 @@ -731,9 +821,7 @@ Destroys an [OH_PreferencesOption](#oh_preferencesoption) instance. **Returns** -Returns the error code. -Returns **PREFERENCES_OK** if the operation is successful. -Returns **PREFERENCES_ERROR_INVALID_PARAM** if invalid parameters are detected. +Returns the error code.
**PREFERENCES_OK** indicates the operation is successful.
**PREFERENCES_ERROR_INVALID_PARAM** indicates invalid parameters are specified. **See** @@ -765,9 +853,9 @@ Sets the bundle name for an [OH_PreferencesOption](#oh_preferencesoption) instan Returns the error code. -Returns **PREFERENCES_OK** if the operation is successful. +**PREFERENCES_OK** indicates the operation is successful. -Returns **PREFERENCES_ERROR_INVALID_PARAM** if invalid parameters are detected. +**PREFERENCES_ERROR_INVALID_PARAM** indicates invalid parameters are specified. **See** @@ -805,9 +893,9 @@ If the application group ID is an empty string, the **Preferences** instance wil Returns the error code. -Returns **PREFERENCES_OK** if the operation is successful. +**PREFERENCES_OK** indicates the operation is successful. -Returns **PREFERENCES_ERROR_INVALID_PARAM** if invalid parameters are detected. +**PREFERENCES_ERROR_INVALID_PARAM** indicates invalid parameters are specified. **See** @@ -839,9 +927,9 @@ Sets the file name for an [OH_PreferencesOption](#oh_preferencesoption) instance Returns the error code. -Returns **PREFERENCES_OK** if the operation is successful. +**PREFERENCES_OK** indicates the operation is successful. -Returns **PREFERENCES_ERROR_INVALID_PARAM** if invalid parameters are detected. +**PREFERENCES_ERROR_INVALID_PARAM** indicates invalid parameters are specified. **See** @@ -872,6 +960,7 @@ Obtains the key based on the specified index from the KV data. **Returns** Returns the pointer to the key obtained if the operation is successful. + Returns a null pointer if the operation fails or the input parameter is invalid. **See** @@ -900,8 +989,7 @@ Obtains the value based on the specified index from the KV pairs. **Returns** -Returns the pointer to the value obtained if the operation is successful. -Returns a null pointer if the operation fails or the input parameter is invalid. +Returns the pointer to the value obtained if the operation is successful.
Returns a null pointer if the operation fails or the input parameter is invalid. **See** @@ -931,13 +1019,13 @@ Obtains a Boolean value from an [OH_PreferencesValue](#oh_preferencesvalue) inst Returns the error code. -Returns **PREFERENCES_OK** if the operation is successful. +**PREFERENCES_OK** indicates the operation is successful. -Returns **PREFERENCES_ERROR_INVALID_PARAM** if invalid parameters are detected. +**PREFERENCES_ERROR_INVALID_PARAM** indicates invalid parameters are specified. -Returns **PREFERENCES_ERROR_STORAGE** if the storage is abnormal. +**PREFERENCES_ERROR_STORAGE** indicates the storage is abnormal. -Returns **PREFERENCES_ERROR_MALLOC** if memory allocation fails. +**PREFERENCES_ERROR_MALLOC** indicates a failure in memory allocation. **See** @@ -969,13 +1057,13 @@ Obtains an integer from an [OH_PreferencesValue](#oh_preferencesvalue) instance. Returns the error code. -Returns **PREFERENCES_OK** if the operation is successful. +**PREFERENCES_OK** indicates the operation is successful. -Returns **PREFERENCES_ERROR_INVALID_PARAM** if invalid parameters are detected. +**PREFERENCES_ERROR_INVALID_PARAM** indicates invalid parameters are specified. -Returns **PREFERENCES_ERROR_STORAGE** if the storage is abnormal. +**PREFERENCES_ERROR_STORAGE** indicates the storage is abnormal. -Returns **PREFERENCES_ERROR_MALLOC** if memory allocation fails. +**PREFERENCES_ERROR_MALLOC** indicates a failure in memory allocation. **See** @@ -1008,13 +1096,13 @@ Obtains a string from an [OH_PreferencesValue](#oh_preferencesvalue) instance. Returns the error code. -Returns **PREFERENCES_OK** if the operation is successful. +**PREFERENCES_OK** indicates the operation is successful. -Returns **PREFERENCES_ERROR_INVALID_PARAM** if invalid parameters are detected. +**PREFERENCES_ERROR_INVALID_PARAM** indicates invalid parameters are specified. -Returns **PREFERENCES_ERROR_STORAGE** if the storage is abnormal. +**PREFERENCES_ERROR_STORAGE** indicates the storage is abnormal. -Returns **PREFERENCES_ERROR_MALLOC** if memory allocation fails. +**PREFERENCES_ERROR_MALLOC** indicates a failure in memory allocation. **See** diff --git a/en/application-dev/reference/apis-arkdata/_r_d_b.md b/en/application-dev/reference/apis-arkdata/_r_d_b.md index 9978658e70011da7ca9d16d52c5a052fbe595e65..7ffe6300792f885be10e5ab8d8a0cdc002014b06 100644 --- a/en/application-dev/reference/apis-arkdata/_r_d_b.md +++ b/en/application-dev/reference/apis-arkdata/_r_d_b.md @@ -3,7 +3,7 @@ ## Overview -The relational database (RDB) store manages data based on relational models. The RDB store provides a complete mechanism for managing local databases based on the underlying SQLite. It provides a series of methods for performing operations, such as adding, deleting, modifying, and querying data, and supports direct execution of SQL statements to satisfy different needs in complicated scenarios. +The relational database (RDB) store manages data based on relational models. The system provides mechanisms for local database management based on the underlying SQLite. You can use the APIs to perform operations, such as adding, deleting, modifying, and querying data, and directly executing SQL statements to satisfy different needs in complicated scenarios. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -18,14 +18,15 @@ The relational database (RDB) store manages data based on relational models. The | Name| Description| | -------- | -------- | | [oh_cursor.h](oh__cursor_8h.md) | Defines APIs for accessing the result set obtained by querying an RDB store.
**File to include**:
**Library**: libnative_rdb_ndk.z.so
| -| [oh_data_value.h](oh__data__value_8h.md) | Defines APIs and enums related to a single data value.
**File to include**:
**Library**: libnative_rdb_ndk.z.so
| +| [oh_data_value.h](oh__data__value_8h.md) | Defines APIs and enums related to a single data value.
Since API version 18, **OH_ColumnType** is moved from **oh_cursor.h** to this file. This type is supported in versions earlier than API version 18 and can be used in all versions.
**File to include**:
**Library**: libnative_rdb_ndk.z.so
| | [oh_data_values.h](oh__data__values_8h.md) | Defines APIs and enums related to multiple data values.
**File to include**:
**Library**: libnative_rdb_ndk.z.so
| | [oh_data_values_buckets.h](oh__data__values__buckets_8h.md) | Defines structs, APIs, and enums related to stored data values.
**File to include**:
**Library**: libnative_rdb_ndk.z.so
| -| [oh_predicates.h](oh__predicates_8h.md) | Defines the predicates for RDB stores.
**File to include**:
**Library**: libnative_rdb_ndk.z.so
| -| [oh_rdb_transaction.h](oh__rdb__transaction_8h.md) | Defines APIs and enums related to database transactions.
**File to include**:
**Library**: libnative_rdb_ndk.z.so
| +| [oh_predicates.h](oh__predicates_8h.md) | Defines the predicates for RDB store operations.
**File to include**:
**Library**: libnative_rdb_ndk.z.so
| +| [oh_rdb_transaction.h](oh__rdb__transaction_8h.md) | Defines APIs and enums related to transactions.
**File to include**:
**Library**: libnative_rdb_ndk.z.so
| +| [oh_rdb_types.h](oh__rdb__types_8h.md) | Defines types related to data values.
**File to include**:
**Library**: libnative_rdb_ndk.z.so
| | [oh_value_object.h](oh__value__object_8h.md) | Defines the APIs for type conversion.
**File to include**:
**Library**: libnative_rdb_ndk.z.so
| | [oh_values_bucket.h](oh__values__bucket_8h.md) | Defines the types of the key and value in a key-value (KV) pair.
**File to include**:
**Library**: libnative_rdb_ndk.z.so
| -| [relational_store.h](relational__store_8h.md) | Defines APIs for managing an RDB store. The APIs not marked as supporting vector stores support only RDB stores.
**File to include**:
**Library**: libnative_rdb_ndk.z.so
| +| [relational_store.h](relational__store_8h.md) | Provides APIs for managing data in an RDB store. The APIs not marked as supporting vector stores are available only to RDB stores.
**File to include**:
**Library**: libnative_rdb_ndk.z.so
| | [relational_store_error_code.h](relational__store__error__code_8h.md) | Defines the error codes used for RDB stores.
**File to include**:
**Library**: libnative_rdb_ndk.z.so| @@ -35,18 +36,18 @@ The relational database (RDB) store manages data based on relational models. The | -------- | -------- | | [OH_Cursor](_o_h___cursor.md) | Defines a result set.| | [OH_Predicates](_o_h___predicates.md) | Defines a **predicates** object.| -| [OH_VObject](_o_h___v_object.md) | Defines the allowed data field types.| +| [OH_VObject](_o_h___v_object.md) | Defines the allowed data types of the fields.| | [OH_VBucket](_o_h___v_bucket.md) | Defines the types of the key and value in a KV pair.| -| [OH_Rdb_Config](_o_h___rdb___config.md) | Defines the RDB store configuration.| +| [OH_Rdb_Config](_o_h___rdb___config.md) | Defines the configuration of an RDB store.| | [OH_Rdb_Store](_o_h___rdb___store.md) | Defines the RDB store type.| | [Rdb_DistributedConfig](_rdb___distributed_config.md) | Defines the distributed configuration of a table.| -| [Rdb_KeyInfo](_rdb___key_info.md) | Defines the primary key or row number of the row that changes.| +| [Rdb_KeyInfo](_rdb___key_info.md) | Defines the primary key or number of the row changed.| | [Rdb_KeyInfo::Rdb_KeyData](union_rdb___key_info_1_1_rdb___key_data.md) | Defines the changed data.| | [Rdb_ChangeInfo](_rdb___change_info.md) | Defines the details about the device-cloud sync process.| | [Rdb_SubscribeCallback](union_rdb___subscribe_callback.md) | Defines a callback used to return the subscribed event.| | [Rdb_DataObserver](_rdb___data_observer.md) | Defines the data observer.| -| [Rdb_Statistic](_rdb___statistic.md) | Defines the device-cloud sync statistics of a database table.| -| [Rdb_TableDetails](_rdb___table_details.md) | Defines the statistics of device-cloud upload and download tasks of a database table.| +| [Rdb_Statistic](_rdb___statistic.md) | Defines the device-cloud sync statistics of a table.| +| [Rdb_TableDetails](_rdb___table_details.md) | Defines the statistics of device-cloud upload and download tasks of a table.| | [Rdb_ProgressDetails](_rdb___progress_details.md) | Defines the statistics of the overall device-cloud sync (upload and download) tasks of an RDB store.| | [Rdb_ProgressObserver](_rdb___progress_observer.md) | Defines the observer of the device-cloud sync progress.| @@ -64,6 +65,7 @@ The relational database (RDB) store manages data based on relational models. The | Name| Description| | -------- | -------- | +| typedef enum [Rdb_ConflictResolution](#rdb_conflictresolution) [Rdb_ConflictResolution](#rdb_conflictresolution) | Defines an enum for conflict resolution policies.| | typedef struct [OH_Rdb_ConfigV2](#oh_rdb_configv2) [OH_Rdb_ConfigV2](#oh_rdb_configv2) | Defines a struct for the RDB store configuration. Different from [OH_Rdb_Config](_o_h___rdb___config.md), this struct does not expose its member variables externally. Methods are used to configure the properties of this struct. It supports vector stores.| | typedef enum [Rdb_DBType](#rdb_dbtype) [Rdb_DBType](#rdb_dbtype) | Defines an enum for database kernel types.| | typedef enum [Rdb_Tokenizer](#rdb_tokenizer) [Rdb_Tokenizer](#rdb_tokenizer) | Defines an enum for database tokenizer types.| @@ -80,11 +82,11 @@ The relational database (RDB) store manages data based on relational models. The | [OH_VObject](#oh_vobject) | Defines a struct for allowed data field types.| | [OH_VBucket](#oh_vbucket) | Defines a struct for the types of the key and value in a KV pair.| | [OH_Rdb_SecurityLevel](#oh_rdb_securitylevel) | Defines an enum for RDB store security levels.| -| [Rdb_SecurityArea](#rdb_securityarea) | Defines an enum for encryption levels of an RDB store.| +| [Rdb_SecurityArea](#rdb_securityarea) | Defines an enum for encryption levels of database files.| | [Rdb_DistributedType](#rdb_distributedtype) | Defines an enum for distributed types.| | [Rdb_DistributedConfig](#rdb_distributedconfig) | Defines a struct for distributed configuration of a table.| | [Rdb_ChangeType](#rdb_changetype) | Defines an enum for data change types.| -| [Rdb_KeyInfo](#rdb_keyinfo) | Defines a struct for the primary key or row number of the row that changes.| +| [Rdb_KeyInfo](#rdb_keyinfo) | Defines a struct for the primary key or number of the row that changes.| | [Rdb_ChangeInfo](#rdb_changeinfo) | Defines a struct for the details about the device-cloud sync process.| | [Rdb_SubscribeType](#rdb_subscribetype) | Defines an enum for subscription types.| | [Rdb_BriefObserver](#rdb_briefobserver) | Defines a callback used to return the device-cloud data change event.| @@ -94,7 +96,7 @@ The relational database (RDB) store manages data based on relational models. The | [Rdb_SyncMode](#rdb_syncmode) | Defines an enum for RDB store sync modes.| | [Rdb_Statistic](#rdb_statistic) | Defines a struct for the device-cloud sync statistics of a database table.| | [Rdb_TableDetails](#rdb_tabledetails) | Defines a struct for statistics of device-cloud upload and download tasks of a database table.| -| [Rdb_Progress](#rdb_progress) | Defines an enum for device-cloud sync progresses.| +| [Rdb_Progress](#rdb_progress) | Defines an enum for device-cloud sync progress states.| | [Rdb_ProgressCode](#rdb_progresscode) | Defines an enum for device-cloud sync states.| | [Rdb_ProgressDetails](#rdb_progressdetails) | Defines a struct for statistics of the overall device-cloud sync (upload and download) tasks of an RDB store.| | [Rdb_ProgressCallback](#rdb_progresscallback) | Defines a callback used to return the device-cloud sync progress.| @@ -110,7 +112,7 @@ The relational database (RDB) store manages data based on relational models. The | [Rdb_DBType](#rdb_dbtype-1) { RDB_SQLITE = 1, RDB_CAYLEY = 2, DBTYPE_BUTT = 64 } | Enumerates the database kernel types.| | [OH_OrderType](#oh_ordertype-1) { ASC = 0, DESC = 1 } | Enumerates the sorting types.| | [OH_Rdb_SecurityLevel](#oh_rdb_securitylevel-1) { S1 = 1, S2, S3, S4 } | Enumerates the RDB store security levels.| -| [Rdb_SecurityArea](#rdb_securityarea-1) { RDB_SECURITY_AREA_EL1 = 1, RDB_SECURITY_AREA_EL2, RDB_SECURITY_AREA_EL3, RDB_SECURITY_AREA_EL4 } | Enumerates the encryption levels of an RDB store.| +| [Rdb_SecurityArea](#rdb_securityarea-1) { RDB_SECURITY_AREA_EL1 = 1, RDB_SECURITY_AREA_EL2, RDB_SECURITY_AREA_EL3, RDB_SECURITY_AREA_EL4 } | Enumerates the encryption levels of database files.| | [Rdb_DistributedType](#rdb_distributedtype-1) { RDB_DISTRIBUTED_CLOUD } | Enumerates the distributed types.| | [Rdb_ChangeType](#rdb_changetype-1) { RDB_DATA_CHANGE, RDB_ASSET_CHANGE } | Enumerates the data change types.| | [Rdb_SubscribeType](#rdb_subscribetype-1) { RDB_SUBSCRIBE_TYPE_CLOUD, RDB_SUBSCRIBE_TYPE_CLOUD_DETAILS, RDB_SUBSCRIBE_TYPE_LOCAL_DETAILS } | Enumerates the subscription types.| @@ -120,109 +122,112 @@ The relational database (RDB) store manages data based on relational models. The | [OH_ColumnType](#oh_columntype-1) {
TYPE_NULL = 0, TYPE_INT64, TYPE_REAL, TYPE_TEXT,
TYPE_BLOB, TYPE_ASSET, TYPE_ASSETS, TYPE_FLOAT_VECTOR,
TYPE_UNLIMITED_INT
} | Enumerates the column types.| | [OH_RDB_TransType](#oh_rdb_transtype-1) { RDB_TRANS_DEFERRED = 0, RDB_TRANS_IMMEDIATE, RDB_TRANS_EXCLUSIVE, RDB_TRANS_BUTT } | Enumerates the transaction types of an RDB store.| | [Rdb_Tokenizer](#rdb_tokenizer-1) { RDB_NONE_TOKENIZER = 1, RDB_ICU_TOKENIZER = 2, RDB_CUSTOM_TOKENIZER = 3 } | Enumerates the database tokenizer types.| -| [OH_Rdb_ErrCode](#oh_rdb_errcode-1) {
RDB_ERR = -1,
RDB_OK = 0,
E_BASE = 14800000,
RDB_E_NOT_SUPPORTED = 801,
RDB_E_ERROR = E_BASE,
RDB_E_INVALID_ARGS = (E_BASE + 1),
RDB_E_CANNOT_UPDATE_READONLY = (E_BASE + 2),
RDB_E_REMOVE_FILE = (E_BASE + 3),
RDB_E_EMPTY_TABLE_NAME = (E_BASE + 5),
RDB_E_EMPTY_VALUES_BUCKET = (E_BASE + 6),
RDB_E_EXECUTE_IN_STEP_QUERY = (E_BASE + 7),
RDB_E_INVALID_COLUMN_INDEX = (E_BASE + 8),
RDB_E_INVALID_COLUMN_TYPE = (E_BASE + 9),
RDB_E_EMPTY_FILE_NAME = (E_BASE + 10),
RDB_E_INVALID_FILE_PATH = (E_BASE + 11),
RDB_E_TRANSACTION_IN_EXECUTE = (E_BASE + 12),
RDB_E_INVALID_STATEMENT = (E_BASE + 13),
RDB_E_EXECUTE_WRITE_IN_READ_CONNECTION = (E_BASE + 14),
RDB_E_BEGIN_TRANSACTION_IN_READ_CONNECTION = (E_BASE + 15),
RDB_E_NO_TRANSACTION_IN_SESSION = (E_BASE + 16),
RDB_E_MORE_STEP_QUERY_IN_ONE_SESSION = (E_BASE + 17),
RDB_E_NO_ROW_IN_QUERY = (E_BASE + 18),
RDB_E_INVALID_BIND_ARGS_COUNT = (E_BASE + 19),
RDB_E_INVALID_OBJECT_TYPE = (E_BASE + 20),
RDB_E_INVALID_CONFLICT_FLAG = (E_BASE + 21),
RDB_E_HAVING_CLAUSE_NOT_IN_GROUP_BY = (E_BASE + 22), RDB_E_NOT_SUPPORTED_BY_STEP_RESULT_SET = (E_BASE + 23), RDB_E_STEP_RESULT_SET_CROSS_THREADS = (E_BASE + 24),
RDB_E_STEP_RESULT_QUERY_NOT_EXECUTED = (E_BASE + 25),
RDB_E_STEP_RESULT_IS_AFTER_LAST = (E_BASE + 26),
RDB_E_STEP_RESULT_QUERY_EXCEEDED = (E_BASE + 27),
RDB_E_STATEMENT_NOT_PREPARED = (E_BASE + 28),
RDB_E_EXECUTE_RESULT_INCORRECT = (E_BASE + 29),
RDB_E_STEP_RESULT_CLOSED = (E_BASE + 30),
RDB_E_RELATIVE_PATH = (E_BASE + 31),
RDB_E_EMPTY_NEW_ENCRYPT_KEY = (E_BASE + 32),
RDB_E_CHANGE_UNENCRYPTED_TO_ENCRYPTED = (E_BASE + 33),
RDB_E_CHANGE_ENCRYPT_KEY_IN_BUSY = (E_BASE + 34),
RDB_E_STEP_STATEMENT_NOT_INIT = (E_BASE + 35),
RDB_E_NOT_SUPPORTED_ATTACH_IN_WAL_MODE = (E_BASE + 36),
RDB_E_CREATE_FOLDER_FAIL = (E_BASE + 37),
RDB_E_SQLITE_SQL_BUILDER_NORMALIZE_FAIL = (E_BASE + 38),
RDB_E_STORE_SESSION_NOT_GIVE_CONNECTION_TEMPORARILY = (E_BASE + 39),
RDB_E_STORE_SESSION_NO_CURRENT_TRANSACTION = (E_BASE + 40),
RDB_E_NOT_SUPPORT = (E_BASE + 41),
RDB_E_INVALID_PARCEL = (E_BASE + 42),
RDB_E_QUERY_IN_EXECUTE = (E_BASE + 43),
RDB_E_SET_PERSIST_WAL = (E_BASE + 44),
RDB_E_DB_NOT_EXIST = (E_BASE + 45),
RDB_E_ARGS_READ_CON_OVERLOAD = (E_BASE + 46),
RDB_E_WAL_SIZE_OVER_LIMIT = (E_BASE + 47),
RDB_E_CON_OVER_LIMIT = (E_BASE + 48),
RDB_E_ALREADY_CLOSED = (E_BASE + 51),
RDB_E_DATABASE_BUSY = (E_BASE + 52),
RDB_E_NOT_SUPPORT_THE_SQL = (E_BASE + 53),
RDB_E_SQLITE_CORRUPT = (E_BASE + 54),
RDB_E_SQLITE_PERM = (E_BASE + 55),
RDB_E_SQLITE_BUSY = (E_BASE + 56),
RDB_E_SQLITE_LOCKED = (E_BASE + 57),
RDB_E_SQLITE_NOMEM = (E_BASE + 58),
RDB_E_SQLITE_READONLY = (E_BASE + 59),
RDB_E_SQLITE_IOERR = (E_BASE + 60),
RDB_E_SQLITE_FULL = (E_BASE + 61),
RDB_E_SQLITE_CANT_OPEN = (E_BASE + 62),
RDB_E_SQLITE_TOO_BIG = (E_BASE + 63),
RDB_E_SQLITE_MISMATCH = (E_BASE + 64)
} | Enumerates the RDB store error codes.| +| [Rdb_ConflictResolution](#rdb_conflictresolution-1) {
RDB_CONFLICT_NONE = 1, RDB_CONFLICT_ROLLBACK, RDB_CONFLICT_ABORT, RDB_CONFLICT_FAIL,
RDB_CONFLICT_IGNORE, RDB_CONFLICT_REPLACE
} | Enumerates the conflict resolution policies.| +| [OH_Rdb_ErrCode](#oh_rdb_errcode-1) {
RDB_ERR = -1, RDB_OK = 0, E_BASE = 14800000, RDB_E_NOT_SUPPORTED = 801,
RDB_E_ERROR = E_BASE, RDB_E_INVALID_ARGS = (E_BASE + 1), RDB_E_CANNOT_UPDATE_READONLY = (E_BASE + 2), RDB_E_REMOVE_FILE = (E_BASE + 3),
RDB_E_EMPTY_TABLE_NAME = (E_BASE + 5), RDB_E_EMPTY_VALUES_BUCKET = (E_BASE + 6), RDB_E_EXECUTE_IN_STEP_QUERY = (E_BASE + 7), RDB_E_INVALID_COLUMN_INDEX = (E_BASE + 8),
RDB_E_INVALID_COLUMN_TYPE = (E_BASE + 9), RDB_E_EMPTY_FILE_NAME = (E_BASE + 10), RDB_E_INVALID_FILE_PATH = (E_BASE + 11), RDB_E_TRANSACTION_IN_EXECUTE = (E_BASE + 12),
RDB_E_INVALID_STATEMENT = (E_BASE + 13), RDB_E_EXECUTE_WRITE_IN_READ_CONNECTION = (E_BASE + 14), RDB_E_BEGIN_TRANSACTION_IN_READ_CONNECTION = (E_BASE + 15), RDB_E_NO_TRANSACTION_IN_SESSION = (E_BASE + 16),
RDB_E_MORE_STEP_QUERY_IN_ONE_SESSION = (E_BASE + 17), RDB_E_NO_ROW_IN_QUERY = (E_BASE + 18), RDB_E_INVALID_BIND_ARGS_COUNT = (E_BASE + 19), RDB_E_INVALID_OBJECT_TYPE = (E_BASE + 20),
RDB_E_INVALID_CONFLICT_FLAG = (E_BASE + 21), RDB_E_HAVING_CLAUSE_NOT_IN_GROUP_BY = (E_BASE + 22), RDB_E_NOT_SUPPORTED_BY_STEP_RESULT_SET = (E_BASE + 23), RDB_E_STEP_RESULT_SET_CROSS_THREADS = (E_BASE + 24),
RDB_E_STEP_RESULT_QUERY_NOT_EXECUTED = (E_BASE + 25), RDB_E_STEP_RESULT_IS_AFTER_LAST = (E_BASE + 26), RDB_E_STEP_RESULT_QUERY_EXCEEDED = (E_BASE + 27), RDB_E_STATEMENT_NOT_PREPARED = (E_BASE + 28),
RDB_E_EXECUTE_RESULT_INCORRECT = (E_BASE + 29), RDB_E_STEP_RESULT_CLOSED = (E_BASE + 30), RDB_E_RELATIVE_PATH = (E_BASE + 31), RDB_E_EMPTY_NEW_ENCRYPT_KEY = (E_BASE + 32),
RDB_E_CHANGE_UNENCRYPTED_TO_ENCRYPTED = (E_BASE + 33), RDB_E_CHANGE_ENCRYPT_KEY_IN_BUSY = (E_BASE + 34), RDB_E_STEP_STATEMENT_NOT_INIT = (E_BASE + 35), RDB_E_NOT_SUPPORTED_ATTACH_IN_WAL_MODE = (E_BASE + 36),
RDB_E_CREATE_FOLDER_FAIL = (E_BASE + 37), RDB_E_SQLITE_SQL_BUILDER_NORMALIZE_FAIL = (E_BASE + 38), RDB_E_STORE_SESSION_NOT_GIVE_CONNECTION_TEMPORARILY = (E_BASE + 39), RDB_E_STORE_SESSION_NO_CURRENT_TRANSACTION = (E_BASE + 40),
RDB_E_NOT_SUPPORT = (E_BASE + 41), RDB_E_INVALID_PARCEL = (E_BASE + 42), RDB_E_QUERY_IN_EXECUTE = (E_BASE + 43), RDB_E_SET_PERSIST_WAL = (E_BASE + 44),
RDB_E_DB_NOT_EXIST = (E_BASE + 45), RDB_E_ARGS_READ_CON_OVERLOAD = (E_BASE + 46), RDB_E_WAL_SIZE_OVER_LIMIT = (E_BASE + 47), RDB_E_CON_OVER_LIMIT = (E_BASE + 48),
RDB_E_ALREADY_CLOSED = (E_BASE + 50), RDB_E_DATABASE_BUSY = (E_BASE + 51), RDB_E_SQLITE_CORRUPT = (E_BASE + 52), RDB_E_SQLITE_PERM = (E_BASE + 53),
RDB_E_SQLITE_BUSY = (E_BASE + 54), RDB_E_SQLITE_LOCKED = (E_BASE + 55), RDB_E_SQLITE_NOMEM = (E_BASE + 56), RDB_E_SQLITE_READONLY = (E_BASE + 57),
RDB_E_SQLITE_IOERR = (E_BASE + 58), RDB_E_SQLITE_FULL = (E_BASE + 59), RDB_E_SQLITE_CANT_OPEN = (E_BASE + 60), RDB_E_SQLITE_TOO_BIG = (E_BASE + 61),
RDB_E_SQLITE_MISMATCH = (E_BASE + 62), RDB_E_DATA_TYPE_NULL = (E_BASE + 63), RDB_E_TYPE_MISMATCH = (E_BASE + 64), RDB_E_SQLITE_CONSTRAINT = (E_BASE + 65)
} | Enumerates the RDB store error codes.| ### Functions | Name| Description| | -------- | -------- | +| int [OH_RdbTrans_BatchInsert](#oh_rdbtrans_batchinsert) ([OH_Rdb_Transaction](#oh_rdb_transaction) \*trans, const char \*table, const [OH_Data_VBuckets](#oh_data_vbuckets) \*rows, [Rdb_ConflictResolution](#rdb_conflictresolution) resolution, int64_t \*changes) | Inserts a batch of data into a table.| +| int [OH_Rdb_BatchInsert](#oh_rdb_batchinsert) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const char \*table, const [OH_Data_VBuckets](#oh_data_vbuckets) \*rows, [Rdb_ConflictResolution](#rdb_conflictresolution) resolution, int64_t \*changes) | Inserts a batch of data into a table.| +| int [OH_Rdb_SetPersistent](#oh_rdb_setpersistent) ([OH_Rdb_ConfigV2](#oh_rdb_configv2) \*config, bool isPersistent) | Sets whether to persist an RDB store.| | int [OH_Rdb_IsTokenizerSupported](#oh_rdb_istokenizersupported) ([Rdb_Tokenizer](#rdb_tokenizer) tokenizer, bool \*isSupported) | Checks whether the specified tokenizer is supported.| | int [OH_Rdb_SetTokenizer](#oh_rdb_settokenizer) ([OH_Rdb_ConfigV2](#oh_rdb_configv2) \*config, [Rdb_Tokenizer](#rdb_tokenizer) tokenizer) | Sets the tokenizer type.| -| int [OH_Cursor_GetFloatVectorCount](#oh_cursor_getfloatvectorcount) ([OH_Cursor](_o_h___cursor.md) \*cursor, int32_t columnIndex, size_t \*length) | Obtains the length of the floating-point array in the specified column of the current row.| -| int [OH_Cursor_GetFloatVector](#oh_cursor_getfloatvector) ([OH_Cursor](_o_h___cursor.md) \*cursor, int32_t columnIndex, float \*val, size_t inLen, size_t \*outLen) | Obtains the value in a specified column of the current row in the form of a floating-point array.| +| int [OH_Cursor_GetFloatVectorCount](#oh_cursor_getfloatvectorcount) ([OH_Cursor](_o_h___cursor.md) \*cursor, int32_t columnIndex, size_t \*length) | Obtains the length of the float array in the specified column of the current row.| +| int [OH_Cursor_GetFloatVector](#oh_cursor_getfloatvector) ([OH_Cursor](_o_h___cursor.md) \*cursor, int32_t columnIndex, float \*val, size_t inLen, size_t \*outLen) | Obtains the value in a specified column of the current row in the form of a float array.| | int [OH_Rdb_ExecuteV2](#oh_rdb_executev2) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const char \*sql, const [OH_Data_Values](#oh_data_values) \*args, [OH_Data_Value](#oh_data_value) \*\*result) | Executes an SQL statement with a return value. This API supports vector stores.| | [OH_Cursor](_o_h___cursor.md) \* [OH_Rdb_ExecuteQueryV2](#oh_rdb_executequeryv2) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const char \*sql, const [OH_Data_Values](#oh_data_values) \*args) | Queries data in the database using the specified SQL statement. This API supports vector stores.| | [OH_Data_Value](#oh_data_value) \* [OH_Value_Create](#oh_value_create) (void) | Creates an [OH_Data_Value](#oh_data_value) instance to store a single KV pair.| | int [OH_Value_Destroy](#oh_value_destroy) ([OH_Data_Value](#oh_data_value) \*value) | Destroys an [OH_Data_Value](#oh_data_value) instance.| -| int [OH_Value_PutNull](#oh_value_putnull) ([OH_Data_Value](#oh_data_value) \*value) | Adds empty data.| -| int [OH_Value_PutInt](#oh_value_putint) ([OH_Data_Value](#oh_data_value) \*value, int64_t val) | Adds integer data. | -| int [OH_Value_PutReal](#oh_value_putreal) ([OH_Data_Value](#oh_data_value) \*value, double val) | Adds data of the REAL type.| -| int [OH_Value_PutText](#oh_value_puttext) ([OH_Data_Value](#oh_data_value) \*value, const char \*val) | Adds data of the string type.| -| int [OH_Value_PutBlob](#oh_value_putblob) ([OH_Data_Value](#oh_data_value) \*value, const unsigned char \*val, size_t length) | Adds data of the BLOB type.| -| int [OH_Value_PutAsset](#oh_value_putasset) ([OH_Data_Value](#oh_data_value) \*value, const Data_Asset \*val) | Adds data of the ASSET type.| -| int [OH_Value_PutAssets](#oh_value_putassets) ([OH_Data_Value](#oh_data_value) \*value, const Data_Asset \*const \*val, size_t length) | Adds data of the ASSETS type.| -| int [OH_Value_PutFloatVector](#oh_value_putfloatvector) ([OH_Data_Value](#oh_data_value) \*value, const float \*val, size_t length) | Adds data of the floating-point array type.| -| int [OH_Value_PutUnlimitedInt](#oh_value_putunlimitedint) ([OH_Data_Value](#oh_data_value) \*value, int sign, const uint64_t \*trueForm, size_t length) | Adds an integer array of any length.| +| int [OH_Value_PutNull](#oh_value_putnull) ([OH_Data_Value](#oh_data_value) \*value) | Adds empty data to an **OH_Data_Value** instance.| +| int [OH_Value_PutInt](#oh_value_putint) ([OH_Data_Value](#oh_data_value) \*value, int64_t val) | Adds an integer to an **OH_Data_Value** instance.| +| int [OH_Value_PutReal](#oh_value_putreal) ([OH_Data_Value](#oh_data_value) \*value, double val) | Adds REAL data to an **OH_Data_Value** instance.| +| int [OH_Value_PutText](#oh_value_puttext) ([OH_Data_Value](#oh_data_value) \*value, const char \*val) | Adds a string to an **OH_Data_Value** instance.| +| int [OH_Value_PutBlob](#oh_value_putblob) ([OH_Data_Value](#oh_data_value) \*value, const unsigned char \*val, size_t length) | Adds BLOB data to an **OH_Data_Value** instance.| +| int [OH_Value_PutAsset](#oh_value_putasset) ([OH_Data_Value](#oh_data_value) \*value, const Data_Asset \*val) | Adds an asset to an **OH_Data_Value** instance.| +| int [OH_Value_PutAssets](#oh_value_putassets) ([OH_Data_Value](#oh_data_value) \*value, const Data_Asset \*const \*val, size_t length) | Adds assets to an **OH_Data_Value** instance.| +| int [OH_Value_PutFloatVector](#oh_value_putfloatvector) ([OH_Data_Value](#oh_data_value) \*value, const float \*val, size_t length) | Adds a float array to an **OH_Data_Value** instance.| +| int [OH_Value_PutUnlimitedInt](#oh_value_putunlimitedint) ([OH_Data_Value](#oh_data_value) \*value, int sign, const uint64_t \*trueForm, size_t length) | Adds an integer array of any length to an **OH_Data_Value** instance.| | int [OH_Value_GetType](#oh_value_gettype) ([OH_Data_Value](#oh_data_value) \*value, [OH_ColumnType](#oh_columntype) \*type) | Obtains the data type.| | int [OH_Value_IsNull](#oh_value_isnull) ([OH_Data_Value](#oh_data_value) \*value, bool \*val) | Checks whether a value is null.| -| int [OH_Value_GetInt](#oh_value_getint) ([OH_Data_Value](#oh_data_value) \*value, int64_t \*val) | Obtains integer data.| -| int [OH_Value_GetReal](#oh_value_getreal) ([OH_Data_Value](#oh_data_value) \*value, double \*val) | Obtains data of the REAL type.| -| int [OH_Value_GetText](#oh_value_gettext) ([OH_Data_Value](#oh_data_value) \*value, const char \*\*val) | Obtains data of the string type.| -| int [OH_Value_GetBlob](#oh_value_getblob) ([OH_Data_Value](#oh_data_value) \*value, const uint8_t \*\*val, size_t \*length) | Obtains data of the BLOB type.| -| int [OH_Value_GetAsset](#oh_value_getasset) ([OH_Data_Value](#oh_data_value) \*value, Data_Asset \*val) | Obtains data of the ASSET type.| -| int [OH_Value_GetAssetsCount](#oh_value_getassetscount) ([OH_Data_Value](#oh_data_value) \*value, size_t \*length) | Obtains the length of ASSETS data.| -| int [OH_Value_GetAssets](#oh_value_getassets) ([OH_Data_Value](#oh_data_value) \*value, Data_Asset \*\*val, size_t inLen, size_t \*outLen) | Obtains data of the ASSETS type.| -| int [OH_Value_GetFloatVectorCount](#oh_value_getfloatvectorcount) ([OH_Data_Value](#oh_data_value) \*value, size_t \*length) | Obtains the length of floating-point array data.| -| int [OH_Value_GetFloatVector](#oh_value_getfloatvector) ([OH_Data_Value](#oh_data_value) \*value, float \*val, size_t inLen, size_t \*outLen) | Obtains data of the floating-point array type.| -| int [OH_Value_GetUnlimitedIntBand](#oh_value_getunlimitedintband) ([OH_Data_Value](#oh_data_value) \*value, size_t \*length) | Obtains the length of an unlimited integer.| -| int [OH_Value_GetUnlimitedInt](#oh_value_getunlimitedint) ([OH_Data_Value](#oh_data_value) \*value, int \*sign, uint64_t \*trueForm, size_t inLen, size_t \*outLen) | Obtains integer data of any length.| +| int [OH_Value_GetInt](#oh_value_getint) ([OH_Data_Value](#oh_data_value) \*value, int64_t \*val) | Obtains the integer from an **OH_Data_Value** instance.| +| int [OH_Value_GetReal](#oh_value_getreal) ([OH_Data_Value](#oh_data_value) \*value, double \*val) | Obtains the REAL data from an **OH_Data_Value** instance.| +| int [OH_Value_GetText](#oh_value_gettext) ([OH_Data_Value](#oh_data_value) \*value, const char \*\*val) | Obtains the string from an **OH_Data_Value** instance.| +| int [OH_Value_GetBlob](#oh_value_getblob) ([OH_Data_Value](#oh_data_value) \*value, const uint8_t \*\*val, size_t \*length) | Obtains the BLOB data from an **OH_Data_Value** instance.| +| int [OH_Value_GetAsset](#oh_value_getasset) ([OH_Data_Value](#oh_data_value) \*value, Data_Asset \*val) | Obtains the asset from an **OH_Data_Value** instance.| +| int [OH_Value_GetAssetsCount](#oh_value_getassetscount) ([OH_Data_Value](#oh_data_value) \*value, size_t \*length) | Obtains the length of the asset in an **OH_Data_Value** instance.| +| int [OH_Value_GetAssets](#oh_value_getassets) ([OH_Data_Value](#oh_data_value) \*value, Data_Asset \*\*val, size_t inLen, size_t \*outLen) | Obtains the assets from an **OH_Data_Value** instance.| +| int [OH_Value_GetFloatVectorCount](#oh_value_getfloatvectorcount) ([OH_Data_Value](#oh_data_value) \*value, size_t \*length) | Obtains the length of the float array in an **OH_Data_Value** instance.| +| int [OH_Value_GetFloatVector](#oh_value_getfloatvector) ([OH_Data_Value](#oh_data_value) \*value, float \*val, size_t inLen, size_t \*outLen) | Obtains the float array from an **OH_Data_Value** instance.| +| int [OH_Value_GetUnlimitedIntBand](#oh_value_getunlimitedintband) ([OH_Data_Value](#oh_data_value) \*value, size_t \*length) | Obtains the length of the unlimited integer from an **OH_Data_Value** instance.| +| int [OH_Value_GetUnlimitedInt](#oh_value_getunlimitedint) ([OH_Data_Value](#oh_data_value) \*value, int \*sign, uint64_t \*trueForm, size_t inLen, size_t \*outLen) | Obtains the unlimited integer from an **OH_Data_Value** instance.| | [OH_Data_Values](#oh_data_values) \* [OH_Values_Create](#oh_values_create) (void) | Creates an [OH_Data_Values](#oh_data_values) instance to store multiple KV pairs.| | int [OH_Values_Destroy](#oh_values_destroy) ([OH_Data_Values](#oh_data_values) \*values) | Destroys an [OH_Data_Values](#oh_data_values) instance.| | int [OH_Values_Put](#oh_values_put) ([OH_Data_Values](#oh_data_values) \*values, const [OH_Data_Value](#oh_data_value) \*val) | Adds data of the **OH_Data_Value** type to an **OH_Data_Values** instance.| | int [OH_Values_PutNull](#oh_values_putnull) ([OH_Data_Values](#oh_data_values) \*values) | Adds empty data to an **OH_Data_Values** instance.| -| int [OH_Values_PutInt](#oh_values_putint) ([OH_Data_Values](#oh_data_values) \*values, int64_t val) | Adds integer data to an **OH_Data_Values** instance.| -| int [OH_Values_PutReal](#oh_values_putreal) ([OH_Data_Values](#oh_data_values) \*values, double val) | Adds data of the REAL type to an **OH_Data_Values** instance.| -| int [OH_Values_PutText](#oh_values_puttext) ([OH_Data_Values](#oh_data_values) \*values, const char \*val) | Adds data of the string type to an **OH_Data_Values** instance.| -| int [OH_Values_PutBlob](#oh_values_putblob) ([OH_Data_Values](#oh_data_values) \*values, const unsigned char \*val, size_t length) | Adds data of the BLOB type to an **OH_Data_Values** instance.| -| int [OH_Values_PutAsset](#oh_values_putasset) ([OH_Data_Values](#oh_data_values) \*values, const Data_Asset \*val) | Adds data of the ASSET type to an **OH_Data_Values** instance.| -| int [OH_Values_PutAssets](#oh_values_putassets) ([OH_Data_Values](#oh_data_values) \*values, const Data_Asset \*const \*val, size_t length) | Adds data of the ASSETS type to an **OH_Data_Values** instance.| -| int [OH_Values_PutFloatVector](#oh_values_putfloatvector) ([OH_Data_Values](#oh_data_values) \*values, const float \*val, size_t length) | Adds data of the floating-point array type to an **OH_Data_Values** instance.| +| int [OH_Values_PutInt](#oh_values_putint) ([OH_Data_Values](#oh_data_values) \*values, int64_t val) | Adds an integer to an **OH_Data_Values** instance.| +| int [OH_Values_PutReal](#oh_values_putreal) ([OH_Data_Values](#oh_data_values) \*values, double val) | Adds REAL data to an **OH_Data_Values** instance.| +| int [OH_Values_PutText](#oh_values_puttext) ([OH_Data_Values](#oh_data_values) \*values, const char \*val) | Adds a string to an **OH_Data_Values** instance.| +| int [OH_Values_PutBlob](#oh_values_putblob) ([OH_Data_Values](#oh_data_values) \*values, const unsigned char \*val, size_t length) | Adds BLOB data to an **OH_Data_Values** instance.| +| int [OH_Values_PutAsset](#oh_values_putasset) ([OH_Data_Values](#oh_data_values) \*values, const Data_Asset \*val) | Adds an asset to an **OH_Data_Values** instance.| +| int [OH_Values_PutAssets](#oh_values_putassets) ([OH_Data_Values](#oh_data_values) \*values, const Data_Asset \*const \*val, size_t length) | Adds assets to an **OH_Data_Values** instance.| +| int [OH_Values_PutFloatVector](#oh_values_putfloatvector) ([OH_Data_Values](#oh_data_values) \*values, const float \*val, size_t length) | Adds a float array to an **OH_Data_Values** instance.| | int [OH_Values_PutUnlimitedInt](#oh_values_putunlimitedint) ([OH_Data_Values](#oh_data_values) \*values, int sign, const uint64_t \*trueForm, size_t length) | Adds an integer array of any length to an **OH_Data_Values** instance.| -| int [OH_Values_Count](#oh_values_count) ([OH_Data_Values](#oh_data_values) \*values, size_t \*count) | Obtains the number of values.| -| int [OH_Values_GetType](#oh_values_gettype) ([OH_Data_Values](#oh_data_values) \*values, int index, [OH_ColumnType](#oh_columntype) \*type) | Obtains the data type.| +| int [OH_Values_Count](#oh_values_count) ([OH_Data_Values](#oh_data_values) \*values, size_t \*count) | Obtains the number of values in an **OH_Data_Values** instance.| +| int [OH_Values_GetType](#oh_values_gettype) ([OH_Data_Values](#oh_data_values) \*values, int index, [OH_ColumnType](#oh_columntype) \*type) | Obtains the type of a value in an **OH_Data_Values** instance.| | int [OH_Values_Get](#oh_values_get) ([OH_Data_Values](#oh_data_values) \*values, int index, [OH_Data_Value](#oh_data_value) \*\*val) | Obtains data of the **OH_Data_Value** type.| | int [OH_Values_IsNull](#oh_values_isnull) ([OH_Data_Values](#oh_data_values) \*values, int index, bool \*val) | Checks whether a value is null.| -| int [OH_Values_GetInt](#oh_values_getint) ([OH_Data_Values](#oh_data_values) \*values, int index, int64_t \*val) | Obtains integer data.| -| int [OH_Values_GetReal](#oh_values_getreal) ([OH_Data_Values](#oh_data_values) \*values, int index, double \*val) | Obtains data of the REAL type.| -| int [OH_Values_GetText](#oh_values_gettext) ([OH_Data_Values](#oh_data_values) \*values, int index, const char \*\*val) | Obtains data of the string type.| -| int [OH_Values_GetBlob](#oh_values_getblob) ([OH_Data_Values](#oh_data_values) \*values, int index, const uint8_t \*\*val, size_t \*length) | Obtains data of the BLOB type.| -| int [OH_Values_GetAsset](#oh_values_getasset) ([OH_Data_Values](#oh_data_values) \*values, int index, Data_Asset \*val) | Obtains data of the ASSET type.| -| int [OH_Values_GetAssetsCount](#oh_values_getassetscount) ([OH_Data_Values](#oh_data_values) \*values, int index, size_t \*length) | Obtains the length of ASSETS data.| -| int [OH_Values_GetAssets](#oh_values_getassets) ([OH_Data_Values](#oh_data_values) \*values, int index, Data_Asset \*\*val, size_t inLen, size_t \*outLen) | Obtains data of the ASSETS type.| -| int [OH_Values_GetFloatVectorCount](#oh_values_getfloatvectorcount) ([OH_Data_Values](#oh_data_values) \*values, int index, size_t \*length) | Obtains the length of a floating-point array.| -| int [OH_Values_GetFloatVector](#oh_values_getfloatvector) ([OH_Data_Values](#oh_data_values) \*values, int index, float \*val, size_t inLen, size_t \*outLen) | Obtains data of the floating-point array type.| -| int [OH_Values_GetUnlimitedIntBand](#oh_values_getunlimitedintband) ([OH_Data_Values](#oh_data_values) \*values, int index, size_t \*length) | Obtains the length of an unlimited integer.| -| int [OH_Values_GetUnlimitedInt](#oh_values_getunlimitedint) ([OH_Data_Values](#oh_data_values) \*values, int index, int \*sign, uint64_t \*trueForm, size_t inLen, size_t \*outLen) | Obtains integer data of any length.| -| [OH_Data_VBuckets](#oh_data_vbuckets) \* [OH_VBuckets_Create](#oh_vbuckets_create) (void) | Creates an **OH_Data_VBuckets** instance. | +| int [OH_Values_GetInt](#oh_values_getint) ([OH_Data_Values](#oh_data_values) \*values, int index, int64_t \*val) | Obtains the integer from an **OH_Data_Values** instance.| +| int [OH_Values_GetReal](#oh_values_getreal) ([OH_Data_Values](#oh_data_values) \*values, int index, double \*val) | Obtains the REAL data from an **OH_Data_Values** instance.| +| int [OH_Values_GetText](#oh_values_gettext) ([OH_Data_Values](#oh_data_values) \*values, int index, const char \*\*val) | Obtains the string from an **OH_Data_Values** instance.| +| int [OH_Values_GetBlob](#oh_values_getblob) ([OH_Data_Values](#oh_data_values) \*values, int index, const uint8_t \*\*val, size_t \*length) | Obtains the BLOB data from an **OH_Data_Values** instance.| +| int [OH_Values_GetAsset](#oh_values_getasset) ([OH_Data_Values](#oh_data_values) \*values, int index, Data_Asset \*val) | Obtains the asset from an **OH_Data_Values** instance.| +| int [OH_Values_GetAssetsCount](#oh_values_getassetscount) ([OH_Data_Values](#oh_data_values) \*values, int index, size_t \*length) | Obtains the length of the asset in an **OH_Data_Values** instance.| +| int [OH_Values_GetAssets](#oh_values_getassets) ([OH_Data_Values](#oh_data_values) \*values, int index, Data_Asset \*\*val, size_t inLen, size_t \*outLen) | Obtains the assets from an **OH_Data_Values** instance.| +| int [OH_Values_GetFloatVectorCount](#oh_values_getfloatvectorcount) ([OH_Data_Values](#oh_data_values) \*values, int index, size_t \*length) | Obtains the length of the float array in an **OH_Data_Values** instance.| +| int [OH_Values_GetFloatVector](#oh_values_getfloatvector) ([OH_Data_Values](#oh_data_values) \*values, int index, float \*val, size_t inLen, size_t \*outLen) | Obtains the float array from an **OH_Data_Values** instance.| +| int [OH_Values_GetUnlimitedIntBand](#oh_values_getunlimitedintband) ([OH_Data_Values](#oh_data_values) \*values, int index, size_t \*length) | Obtains the length of the unlimited integer from an **OH_Data_Values** instance.| +| int [OH_Values_GetUnlimitedInt](#oh_values_getunlimitedint) ([OH_Data_Values](#oh_data_values) \*values, int index, int \*sign, uint64_t \*trueForm, size_t inLen, size_t \*outLen) | Obtains the unlimited integer from an **OH_Data_Values** instance.| +| [OH_Data_VBuckets](#oh_data_vbuckets) \* [OH_VBuckets_Create](#oh_vbuckets_create) (void) | Creates an **OH_Data_VBuckets** instance.| | int [OH_VBuckets_Destroy](#oh_vbuckets_destroy) ([OH_Data_VBuckets](#oh_data_vbuckets) \*buckets) | Destroys an **OH_Data_VBuckets** instance.| -| int [OH_VBuckets_PutRow](#oh_vbuckets_putrow) ([OH_Data_VBuckets](#oh_data_vbuckets) \*buckets, const [OH_VBucket](_o_h___v_bucket.md) \*row) | Adds data of the **OH_VBucket** type.| -| int [OH_VBuckets_PutRows](#oh_vbuckets_putrows) ([OH_Data_VBuckets](#oh_data_vbuckets) \*buckets, const [OH_Data_VBuckets](#oh_data_vbuckets) \*rows) | Adds data of the **OH_Data_VBuckets** type.| -| int [OH_VBuckets_RowCount](#oh_vbuckets_rowcount) ([OH_Data_VBuckets](#oh_data_vbuckets) \*buckets, size_t \*count) | Obtains the number of rows in **OH_VBucket** in **OH_Data_VBuckets**.| -| [OH_RDB_TransOptions](#oh_rdb_transoptions) \* [OH_RdbTrans_CreateOptions](#oh_rdbtrans_createoptions) (void) | Creates a transaction configuration object. | -| int [OH_RdbTrans_DestroyOptions](#oh_rdbtrans_destroyoptions) ([OH_RDB_TransOptions](#oh_rdb_transoptions) \*opitons) | Destroys a transaction configuration instance.| -| int [OH_RdbTransOption_SetType](#oh_rdbtransoption_settype) ([OH_RDB_TransOptions](#oh_rdb_transoptions) \*opitons, [OH_RDB_TransType](#oh_rdb_transtype) type) | Sets the transaction type of an RDB store. | +| int [OH_VBuckets_PutRow](#oh_vbuckets_putrow) ([OH_Data_VBuckets](#oh_data_vbuckets) \*buckets, const [OH_VBucket](_o_h___v_bucket.md) \*row) | Adds data of the **OH_VBucket** type to an **OH_Data_VBuckets** instance.| +| int [OH_VBuckets_PutRows](#oh_vbuckets_putrows) ([OH_Data_VBuckets](#oh_data_vbuckets) \*buckets, const [OH_Data_VBuckets](#oh_data_vbuckets) \*rows) | Adds data of the **OH_Data_VBuckets** type to an **OH_Data_VBuckets** instance.| +| int [OH_VBuckets_RowCount](#oh_vbuckets_rowcount) ([OH_Data_VBuckets](#oh_data_vbuckets) \*buckets, size_t \*count) | Obtains the number **OH_VBucket**s in an **OH_Data_VBuckets** instance.| +| [OH_RDB_TransOptions](#oh_rdb_transoptions) \* [OH_RdbTrans_CreateOptions](#oh_rdbtrans_createoptions) (void) | Creates a **TransOptions** instance.| +| int [OH_RdbTrans_DestroyOptions](#oh_rdbtrans_destroyoptions) ([OH_RDB_TransOptions](#oh_rdb_transoptions) \*opitons) | Destroys a **TransOptions** instance.| +| int [OH_RdbTransOption_SetType](#oh_rdbtransoption_settype) ([OH_RDB_TransOptions](#oh_rdb_transoptions) \*opitons, [OH_RDB_TransType](#oh_rdb_transtype) type) | Sets the transaction type of an RDB store.| | int [OH_RdbTrans_Commit](#oh_rdbtrans_commit) ([OH_Rdb_Transaction](#oh_rdb_transaction) \*trans) | Commits a transaction.| | int [OH_RdbTrans_Rollback](#oh_rdbtrans_rollback) ([OH_Rdb_Transaction](#oh_rdb_transaction) \*trans) | Rolls back a transaction.| | int [OH_RdbTrans_Insert](#oh_rdbtrans_insert) ([OH_Rdb_Transaction](#oh_rdb_transaction) \*trans, const char \*table, const [OH_VBucket](_o_h___v_bucket.md) \*row, int64_t \*rowId) | Inserts a row of data into a table.| -| int [OH_RdbTrans_BatchInsert](#oh_rdbtrans_batchinsert) ([OH_Rdb_Transaction](#oh_rdb_transaction) \*trans, const char \*table, const [OH_Data_VBuckets](#oh_data_vbuckets) \*rows, int64_t \*changes) | Batch inserts data into a table.| | int [OH_RdbTrans_Update](#oh_rdbtrans_update) ([OH_Rdb_Transaction](#oh_rdb_transaction) \*trans, const [OH_VBucket](_o_h___v_bucket.md) \*row, const [OH_Predicates](_o_h___predicates.md) \*predicates, int64_t \*changes) | Updates data in an RDB store based on specified conditions.| | int [OH_RdbTrans_Delete](#oh_rdbtrans_delete) ([OH_Rdb_Transaction](#oh_rdb_transaction) \*trans, const [OH_Predicates](_o_h___predicates.md) \*predicates, int64_t \*changes) | Deletes data from the database based on the specified conditions.| | [OH_Cursor](_o_h___cursor.md) \* [OH_RdbTrans_Query](#oh_rdbtrans_query) ([OH_Rdb_Transaction](#oh_rdb_transaction) \*trans, const [OH_Predicates](_o_h___predicates.md) \*predicates, const char \*columns[], int len) | Queries data in the database based on specified conditions.| | [OH_Cursor](_o_h___cursor.md) \* [OH_RdbTrans_QuerySql](#oh_rdbtrans_querysql) ([OH_Rdb_Transaction](#oh_rdb_transaction) \*trans, const char \*sql, const [OH_Data_Values](#oh_data_values) \*args) | Queries data in the database using the specified SQL statement.| | int [OH_RdbTrans_Execute](#oh_rdbtrans_execute) ([OH_Rdb_Transaction](#oh_rdb_transaction) \*trans, const char \*sql, const [OH_Data_Values](#oh_data_values) \*args, [OH_Data_Value](#oh_data_value) \*\*result) | Executes an SQL statement that contains specified parameters.| | int [OH_RdbTrans_Destroy](#oh_rdbtrans_destroy) ([OH_Rdb_Transaction](#oh_rdb_transaction) \*trans) | Destroys a transaction object.| -| int [OH_VBucket_PutFloatVector](#oh_vbucket_putfloatvector) ([OH_VBucket](_o_h___v_bucket.md) \*bucket, const char \*field, const float \*vec, size_t len) | Puts a floating-point array into an [OH_VBucket](_o_h___v_bucket.md) object in the given column.| -| int [OH_VBucket_PutUnlimitedInt](#oh_vbucket_putunlimitedint) ([OH_VBucket](_o_h___v_bucket.md) \*bucket, const char \*field, int sign, const uint64_t \*trueForm, size_t len) | Puts an integer of any length into an [OH_VBucket](_o_h___v_bucket.md) object in the given column.| +| int [OH_VBucket_PutFloatVector](#oh_vbucket_putfloatvector) ([OH_VBucket](_o_h___v_bucket.md) \*bucket, const char \*field, const float \*vec, size_t len) | Puts a float array into an [OH_VBucket](_o_h___v_bucket.md) instance in the given column.| +| int [OH_VBucket_PutUnlimitedInt](#oh_vbucket_putunlimitedint) ([OH_VBucket](_o_h___v_bucket.md) \*bucket, const char \*field, int sign, const uint64_t \*trueForm, size_t len) | Puts an integer of any length into an [OH_VBucket](_o_h___v_bucket.md) instance in the given column.| | [OH_Rdb_ConfigV2](#oh_rdb_configv2) \* [OH_Rdb_CreateConfig](#oh_rdb_createconfig) () | Creates an [OH_Rdb_ConfigV2](#oh_rdb_configv2) instance.| | int [OH_Rdb_DestroyConfig](#oh_rdb_destroyconfig) ([OH_Rdb_ConfigV2](#oh_rdb_configv2) \*config) | Destroys an [OH_Rdb_ConfigV2](#oh_rdb_configv2) instance.| | int [OH_Rdb_SetDatabaseDir](#oh_rdb_setdatabasedir) ([OH_Rdb_ConfigV2](#oh_rdb_configv2) \*config, const char \*databaseDir) | Sets the database file path for an [OH_Rdb_ConfigV2](#oh_rdb_configv2) instance.| | int [OH_Rdb_SetStoreName](#oh_rdb_setstorename) ([OH_Rdb_ConfigV2](#oh_rdb_configv2) \*config, const char \*storeName) | Sets the RDB store name for an [OH_Rdb_ConfigV2](#oh_rdb_configv2) instance.| | int [OH_Rdb_SetBundleName](#oh_rdb_setbundlename) ([OH_Rdb_ConfigV2](#oh_rdb_configv2) \*config, const char \*bundleName) | Sets the application bundle name for an [OH_Rdb_ConfigV2](#oh_rdb_configv2) instance.| | int [OH_Rdb_SetModuleName](#oh_rdb_setmodulename) ([OH_Rdb_ConfigV2](#oh_rdb_configv2) \*config, const char \*moduleName) | Sets the module name for an [OH_Rdb_ConfigV2](#oh_rdb_configv2) instance.| -| int [OH_Rdb_SetEncrypted](#oh_rdb_setencrypted) ([OH_Rdb_ConfigV2](#oh_rdb_configv2) \*config, bool isEncrypted) | Sets whether to encrypt the RDB store for an [OH_Rdb_ConfigV2](#oh_rdb_configv2) instance.| -| int [OH_Rdb_SetSecurityLevel](#oh_rdb_setsecuritylevel) ([OH_Rdb_ConfigV2](#oh_rdb_configv2) \*config, int securityLevel) | Sets the RDB store security level ([OH_Rdb_SecurityLevel](#oh_rdb_securitylevel)) for an [OH_Rdb_ConfigV2](#oh_rdb_configv2) instance.| -| int [OH_Rdb_SetArea](#oh_rdb_setarea) ([OH_Rdb_ConfigV2](#oh_rdb_configv2) \*config, int area) | Sets the security area level ([Rdb_SecurityArea](#rdb_securityarea)) for an [OH_Rdb_ConfigV2](#oh_rdb_configv2) instance.| -| int [OH_Rdb_SetDbType](#oh_rdb_setdbtype) ([OH_Rdb_ConfigV2](#oh_rdb_configv2) \*config, int dbType) | Sets the database type ([Rdb_DBType](#rdb_dbtype)) for an [OH_Rdb_ConfigV2](#oh_rdb_configv2) instance.| +| int [OH_Rdb_SetEncrypted](#oh_rdb_setencrypted) ([OH_Rdb_ConfigV2](#oh_rdb_configv2) \*config, bool isEncrypted) | Sets whether to encrypt the database for an [OH_Rdb_ConfigV2](#oh_rdb_configv2) instance.| +| int [OH_Rdb_SetSecurityLevel](#oh_rdb_setsecuritylevel) ([OH_Rdb_ConfigV2](#oh_rdb_configv2) \*config, int securityLevel) | Sets the [OH_Rdb_SecurityLevel](#oh_rdb_securitylevel) for an [OH_Rdb_ConfigV2](#oh_rdb_configv2) instance.| +| int [OH_Rdb_SetArea](#oh_rdb_setarea) ([OH_Rdb_ConfigV2](#oh_rdb_configv2) \*config, int area) | Sets the [Rdb_SecurityArea](#rdb_securityarea) for an [OH_Rdb_ConfigV2](#oh_rdb_configv2) instance.| +| int [OH_Rdb_SetDbType](#oh_rdb_setdbtype) ([OH_Rdb_ConfigV2](#oh_rdb_configv2) \*config, int dbType) | Sets the [Rdb_DBType](#rdb_dbtype) for an [OH_Rdb_ConfigV2](#oh_rdb_configv2) instance.| | const int \* [OH_Rdb_GetSupportedDbType](#oh_rdb_getsupporteddbtype) (int \*typeCount) | Obtains the supported database types ([Rdb_DBType](#rdb_dbtype)).| | [OH_Rdb_Store](_o_h___rdb___store.md) \* [OH_Rdb_CreateOrOpen](#oh_rdb_createoropen) (const [OH_Rdb_ConfigV2](#oh_rdb_configv2) \*config, int \*errCode) | Creates or opens an [OH_Rdb_Store](_o_h___rdb___store.md) instance based on the given [OH_Rdb_ConfigV2](#oh_rdb_configv2).| -| int [OH_Rdb_DeleteStoreV2](#oh_rdb_deletestorev2) (const [OH_Rdb_ConfigV2](#oh_rdb_configv2) \*config) | Deletes an RDB store based on the given [OH_Rdb_ConfigV2](#oh_rdb_configv2). If a vector store is used, ensure that the vector store has been correctly closed before calling the API.| -| int [OH_Rdb_ExecuteByTrxId](#oh_rdb_executebytrxid) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, int64_t trxId, const char \*sql) | Executes an SQL statement that returns no value based on the specified transaction ID. This API supports vector stores.| -| int [OH_Rdb_BeginTransWithTrxId](#oh_rdb_begintranswithtrxid) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, int64_t \*trxId) | Begins a transaction and obtains the transaction ID before executing an SQL statement. This API supports vector stores.| -| int [OH_Rdb_RollBackByTrxId](#oh_rdb_rollbackbytrxid) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, int64_t trxId) | Rolls back the executed SQL statement based on the specified transaction ID. This API supports vector stores.| -| int [OH_Rdb_CommitByTrxId](#oh_rdb_commitbytrxid) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, int64_t trxId) | Commits the executed SQL statement based on the specified transaction ID. This API supports vector stores.| +| int [OH_Rdb_DeleteStoreV2](#oh_rdb_deletestorev2) (const [OH_Rdb_ConfigV2](#oh_rdb_configv2) \*config) | Deletes an RDB store based on the given [OH_Rdb_ConfigV2](#oh_rdb_configv2). For a vector store, ensure that the vector store is correctly closed before calling this API.| +| int [OH_Rdb_ExecuteByTrxId](#oh_rdb_executebytrxid) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, int64_t trxId, const char \*sql) | Executes an SQL statement that returns no value based on the specified transaction ID. This API supports only vector stores.| +| int [OH_Rdb_BeginTransWithTrxId](#oh_rdb_begintranswithtrxid) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, int64_t \*trxId) | Begins a transaction. This API returns a transaction ID. This API supports only vector stores.| +| int [OH_Rdb_RollBackByTrxId](#oh_rdb_rollbackbytrxid) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, int64_t trxId) | Rolls back the executed SQL statements based on the specified transaction ID. This API supports only vector stores.| +| int [OH_Rdb_CommitByTrxId](#oh_rdb_commitbytrxid) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, int64_t trxId) | Commits the executed SQL statements based on the specified transaction ID. This API supports only vector stores.| | [OH_VBucket_PutAsset](#oh_vbucket_putasset) ([OH_VBucket](_o_h___v_bucket.md) \*bucket, const char \*field, OH_Asset \*value) | Puts an **OH_Asset** object into an [OH_VBucket](_o_h___v_bucket.md) object in the given column.| -| [OH_VBucket_PutAssets](#oh_vbucket_putassets) ([OH_VBucket](_o_h___v_bucket.md) \*bucket, const char \*field, OH_Asset \*\*value, int count) | Puts an array of **OH_Asset** objects into an [OH_VBucket](_o_h___v_bucket.md) object in the given column.| +| [OH_VBucket_PutAssets](#oh_vbucket_putassets) ([OH_VBucket](_o_h___v_bucket.md) \*bucket, const char \*field, OH_Asset \*\*value, int count) | Puts an array of **OH_Asset** objects into the [OH_VBucket](_o_h___v_bucket.md) object in the given column.| | [OH_Rdb_CreateValueObject](#oh_rdb_createvalueobject) () | Creates an [OH_VObject](_o_h___v_object.md) instance.| | [OH_Rdb_CreateValuesBucket](#oh_rdb_createvaluesbucket) () | Creates an [OH_VBucket](_o_h___v_bucket.md) instance.| | [OH_Rdb_CreatePredicates](#oh_rdb_createpredicates) (const char \*table) | Creates an [OH_Predicates](_o_h___predicates.md) instance.| @@ -233,11 +238,11 @@ The relational database (RDB) store manages data based on relational models. The | [OH_Rdb_Update](#oh_rdb_update) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, [OH_VBucket](_o_h___v_bucket.md) \*valuesBucket, [OH_Predicates](_o_h___predicates.md) \*predicates) | Updates data in an RDB store based on specified conditions.| | [OH_Rdb_Delete](#oh_rdb_delete) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, [OH_Predicates](_o_h___predicates.md) \*predicates) | Deletes data from an RDB store based on specified conditions.| | [OH_Rdb_Query](#oh_rdb_query) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, [OH_Predicates](_o_h___predicates.md) \*predicates, const char \*const \*columnNames, int length) | Queries data in an RDB store based on specified conditions.| -| [OH_Rdb_Execute](#oh_rdb_execute) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const char \*sql) | Executes an SQL statement but returns no value.| +| [OH_Rdb_Execute](#oh_rdb_execute) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const char \*sql) | Executes an SQL statement that returns no value.| | [OH_Rdb_ExecuteQuery](#oh_rdb_executequery) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const char \*sql) | Queries data in the database using the specified SQL statement. This API supports vector stores.| -| [OH_Rdb_BeginTransaction](#oh_rdb_begintransaction) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store) | Starts the transaction before executing the SQL statement.| -| [OH_Rdb_RollBack](#oh_rdb_rollback) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store) | Rolls back the SQL statement executed.| -| [OH_Rdb_Commit](#oh_rdb_commit) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store) | Commits the executed SQL statement.| +| [OH_Rdb_BeginTransaction](#oh_rdb_begintransaction) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store) | Begins the transaction before executing SQL statements.| +| [OH_Rdb_RollBack](#oh_rdb_rollback) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store) | Rolls back the SQL statements executed.| +| [OH_Rdb_Commit](#oh_rdb_commit) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store) | Commits the executed SQL statements.| | [OH_Rdb_Backup](#oh_rdb_backup) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const char \*databasePath) | Backs up an RDB store using the backup file of the specified path. This API supports vector stores.| | [OH_Rdb_Restore](#oh_rdb_restore) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const char \*databasePath) | Restores a database from a specified database backup file. This API supports vector stores.| | [OH_Rdb_GetVersion](#oh_rdb_getversion) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, int \*version) | Obtains the RDB store version.| @@ -248,8 +253,8 @@ The relational database (RDB) store manages data based on relational models. The | [OH_Rdb_Unsubscribe](#oh_rdb_unsubscribe) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, [Rdb_SubscribeType](#rdb_subscribetype) type, const [Rdb_DataObserver](_rdb___data_observer.md) \*observer) | Unregisters the observer of the specified type.| | [OH_Rdb_GetTableDetails](#oh_rdb_gettabledetails) ([Rdb_ProgressDetails](_rdb___progress_details.md) \*progress, int32_t version) | Obtains the device-cloud sync statistics of a table.| | [OH_Rdb_CloudSync](#oh_rdb_cloudsync) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, [Rdb_SyncMode](#rdb_syncmode) mode, const char \*tables, int count, const [Rdb_ProgressObserver](_rdb___progress_observer.md) \*observer) | Performs device-cloud sync.| -| [OH_Rdb_SubscribeAutoSyncProgress](#oh_rdb_subscribeautosyncprogress) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const [Rdb_ProgressObserver](_rdb___progress_observer.md) \*observer) | Subscribes to the automatic sync progress of an RDB store. The registered callback will be invoked to return the automatic sync progress.| -| [OH_Rdb_UnsubscribeAutoSyncProgress](#oh_rdb_unsubscribeautosyncprogress) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const [Rdb_ProgressObserver](_rdb___progress_observer.md) \*observer) | Unsubscribes from the automatic sync process of an RDB store.| +| [OH_Rdb_SubscribeAutoSyncProgress](#oh_rdb_subscribeautosyncprogress) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const [Rdb_ProgressObserver](_rdb___progress_observer.md) \*observer) | Subscribes to the auto sync progress of an RDB store. The registered callback will be invoked to return the auto sync progress.| +| [OH_Rdb_UnsubscribeAutoSyncProgress](#oh_rdb_unsubscribeautosyncprogress) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const [Rdb_ProgressObserver](_rdb___progress_observer.md) \*observer) | Unsubscribes from the auto sync process of an RDB store.| | int [OH_Rdb_LockRow](#oh_rdb_lockrow) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, [OH_Predicates](_o_h___predicates.md) \*predicates) | Locks data in an RDB store based on specified conditions. The locked data will be blocked from the device-cloud sync.| | int [OH_Rdb_UnlockRow](#oh_rdb_unlockrow) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, [OH_Predicates](_o_h___predicates.md) \*predicates) | Unlocks data in an RDB store based on the specified conditions.| | [OH_Cursor](_o_h___cursor.md) \* [OH_Rdb_QueryLockedRow](#oh_rdb_querylockedrow) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, [OH_Predicates](_o_h___predicates.md) \*predicates, const char \*const \*columnNames, int length) | Queries the locked data in an RDB store.| @@ -275,28 +280,28 @@ The relational database (RDB) store manages data based on relational models. The | [OH_Cursor::getAsset](#getasset) | Pointer to the function used to obtain the value of the asset type based on the specified column and the current row.| | [OH_Cursor::getAssets](#getassets) | Pointer to the function used to obtain the values in the form of an asset array based on the specified column and the current row.| | [OH_Predicates::id](#id-25) | Unique identifier of the **OH_Predicates** struct.| -| [OH_Predicates::equalTo](#equalto) | Pointer to the function used to set a predicates object to match the field whose value is equal to the specified value.| -| [OH_Predicates::notEqualTo](#notequalto) | Pointer to the function used to set a predicates object to match the field whose value is not equal to the specified value.| +| [OH_Predicates::equalTo](#equalto) | Pointer to the function used to create a predicates object to search for the field values that are equal to the specified value.| +| [OH_Predicates::notEqualTo](#notequalto) | Pointer to the function used to create a predicates object to search for the field values that are not equal to the specified value.| | [OH_Predicates::beginWrap](#beginwrap) | Pointer to the function used to add a left parenthesis to the predicates.| | [OH_Predicates::endWrap](#endwrap) | Pointer to the function used to add a right parenthesis to the predicates.| | [OH_Predicates::orOperate](#oroperate) | Pointer to the function used to add the OR operator to the predicates.| | [OH_Predicates::andOperate](#andoperate) | Pointer to the function used to add the AND operator to the predicates.| -| [OH_Predicates::isNull](#isnull-22) | Pointer to the function used to set a predicates object to match the field whose value is null.| -| [OH_Predicates::isNotNull](#isnotnull) | Pointer to the function used to set a predicates object to match the field whose value is not null.| -| [OH_Predicates::like](#like) | Pointer to the function used to set a predicates object to match a string that is similar to the specified value.| -| [OH_Predicates::between](#between) | Pointer to the function used to set a predicates object to match the field whose value is within the specified range.| -| [OH_Predicates::notBetween](#notbetween) | Pointer to the function used to set a predicates object to match the field whose value is out of the specified range.| -| [OH_Predicates::greaterThan](#greaterthan) | Pointer to the function used to set a predicates object to match the field with value greater than the specified value.| -| [OH_Predicates::lessThan](#lessthan) | Pointer to the function used to set a predicates object to match the field with value less than the specified value.| -| [OH_Predicates::greaterThanOrEqualTo](#greaterthanorequalto) | Pointer to the function used to set a predicates object to match the field with value greater than or equal to the specified value.| -| [OH_Predicates::lessThanOrEqualTo](#lessthanorequalto) | Pointer to the function used to set a predicates object to match the field with value less than or equal to the specified value.| -| [OH_Predicates::orderBy](#orderby) | Pointer to the function used to set a predicates object to sort the values in a column in ascending or descending order.| -| [OH_Predicates::distinct](#distinct) | Pointer to the function used to set a predicates object to filter out duplicate records.| -| [OH_Predicates::limit](#limit) | Pointer to the function used to set a predicates object to specify the maximum number of records.| -| [OH_Predicates::offset](#offset) | Pointer to the function used to set a predicates object to specify the start position of the returned result.| -| [OH_Predicates::groupBy](#groupby) | Pointer to the function used to set a predicates object to group rows that have the same value into summary rows.| -| [OH_Predicates::in](#in) | Pointer to the function used to set a predicates object to match the field with the value within the specified range.| -| [OH_Predicates::notIn](#notin) | Pointer to the function used to set a predicates object to match the field with the value out of the specified range.| +| [OH_Predicates::isNull](#isnull-22) | Pointer to the function used to create a predicates object to search for the field values that are null.| +| [OH_Predicates::isNotNull](#isnotnull) | Pointer to the function used to create a predicates object to search for the field values that are not null.| +| [OH_Predicates::like](#like) | Pointer to the function used to create a predicates object to search for the field values that are similar to the specified string.| +| [OH_Predicates::between](#between) | Pointer to the function used to create a predicates object to search for the field values that are within the specified range.| +| [OH_Predicates::notBetween](#notbetween) | Pointer to the function used to create a predicates object to search for the field values that are out of the specified range.| +| [OH_Predicates::greaterThan](#greaterthan) | Pointer to the function used to create a predicates object to search for the field values that are greater than the specified value.| +| [OH_Predicates::lessThan](#lessthan) | Pointer to the function used to create a predicates object to search for the field values that are less than the specified value.| +| [OH_Predicates::greaterThanOrEqualTo](#greaterthanorequalto) | Pointer to the function used to create a predicates object to search for the field values that are greater than or equal to the specified value.| +| [OH_Predicates::lessThanOrEqualTo](#lessthanorequalto) | Pointer to the function used to create a predicates object to search for the field values that are less than or equal to the specified value.| +| [OH_Predicates::orderBy](#orderby) | Pointer to the function used to create a predicates object to sort the values in the specified column in ascending or descending order.| +| [OH_Predicates::distinct](#distinct) | Pointer to the function used to create a predicates object to filter out duplicate records.| +| [OH_Predicates::limit](#limit) | Pointer to the function used to create a predicates object to specify the maximum number of records.| +| [OH_Predicates::offset](#offset) | Pointer to the function used to create a predicates object to specify the start position of the query result.| +| [OH_Predicates::groupBy](#groupby) | Pointer to the function used to create a predicates object to group the results by the specified columns.| +| [OH_Predicates::in](#in) | Pointer to the function used to create a predicates object to search for the field values that are within the specified range.| +| [OH_Predicates::notIn](#notin) | Pointer to the function used to create a predicates object to search for the field values that are out of the specified range.| | [OH_Predicates::clear](#clear-12) | Pointer to the function used to clear a predicates instance.| | [OH_Predicates::destroy](#destroy-24) | Pointer to the function used to destroy an [OH_Predicates](_o_h___predicates.md) object to reclaim the memory occupied.| | [OH_VObject::id](#id-35) | Unique identifier of the **OH_VObject** struct.| @@ -306,10 +311,10 @@ The relational database (RDB) store manages data based on relational models. The | [OH_VObject::putTexts](#puttexts) | Pointer to the function used to convert a string array of the char type to a value of the [OH_VObject](_o_h___v_object.md) type.| | [OH_VObject::destroy](#destroy-44) | Pointer to the function used to destroy an [OH_VObject](_o_h___v_object.md) object to reclaim the memory occupied.| | [OH_VBucket::id](#id-45) | Unique identifier of the **OH_VBucket** struct.| -| [OH_VBucket::capability](#capability) | Number of the KV pairs in the struct.| +| [OH_VBucket::capability](#capability) | Number of the KV pairs in an **OH_VBucket** instance.| | [OH_VBucket::putText](#puttext-12) | Pointer to the function used to put a char value into an [OH_VBucket](_o_h___v_bucket.md) object in the given column.| | [OH_VBucket::putInt64](#putint64-12) | Pointer to the function used to put an int64_t value into an [OH_VBucket](_o_h___v_bucket.md) object in the given column.| -| [OH_VBucket::putReal](#putreal) | Pointer to the function used to put a double value into the {OH_VBucket} object in the given column.| +| [OH_VBucket::putReal](#putreal) | Pointer to the function used to put a double value into the **OH_VBucket** object in the given column.| | [OH_VBucket::putBlob](#putblob) | Pointer to the function used to put a const uint8_t value into an [OH_VBucket](_o_h___v_bucket.md) object in the given column.| | [OH_VBucket::putNull](#putnull) | Pointer to the function used to put a null value into an [OH_VBucket](_o_h___v_bucket.md) object in the given column.| | [OH_VBucket::clear](#clear-22) | Pointer to the function used to clear an [OH_VBucket](_o_h___v_bucket.md) object.| @@ -321,12 +326,12 @@ The relational database (RDB) store manages data based on relational models. The | [OH_Rdb_Config::moduleName](#modulename) | Module name. | | [OH_Rdb_Config::isEncrypt](#isencrypt) | Whether to encrypt the RDB store.| | [OH_Rdb_Config::securityLevel](#securitylevel) | RDB store security level. For details, see [OH_Rdb_SecurityLevel](#oh_rdb_securitylevel).| -| [OH_Rdb_Config::area](#area) | Security area level. For details, see [Rdb_SecurityArea](#rdb_securityarea).| +| [OH_Rdb_Config::area](#area) | Database file encryption level. For details, see [Rdb_SecurityArea](#rdb_securityarea).| | [OH_Rdb_Store::id](#id-55) | Unique identifier of the **OH_Rdb_Store** struct.| | [Rdb_DistributedConfig::version](#version-13) | Version of the **Rdb_DistributedConfig** struct.| -| [Rdb_DistributedConfig::isAutoSync](#isautosync) | Whether the table supports automatic sync.| +| [Rdb_DistributedConfig::isAutoSync](#isautosync) | Whether the table supports auto sync.| | [Rdb_KeyInfo::count](#count) | Number of the changed primary keys or row numbers.| -| [Rdb_KeyInfo::type](#type) | Type ([OH_ColumnType](#oh_columntype)) of the primary key.| +| [Rdb_KeyInfo::type](#type) | [OH_ColumnType](#oh_columntype) of the primary key.| | [Rdb_KeyInfo::Rdb_KeyData::integer](#integer) | Data of the uint64_t type.| | [Rdb_KeyInfo::Rdb_KeyData::real](#real) | Data of the double type.| | [Rdb_KeyInfo::Rdb_KeyData::text](#text) | Data of the char \* type.| @@ -334,9 +339,9 @@ The relational database (RDB) store manages data based on relational models. The | [Rdb_ChangeInfo::version](#version-23) | Version of the **Rdb_DistributedConfig** struct.| | [Rdb_ChangeInfo::tableName](#tablename) | Name of the table with data changes.| | [Rdb_ChangeInfo::ChangeType](#changetype) | Type of the data changed, which can be data or asset.| -| [Rdb_ChangeInfo::inserted](#inserted) | Location where data is inserted. If the primary key of the table is of the string type, the value is the value of the primary key. Otherwise, the value is the row number of the inserted data.| -| [Rdb_ChangeInfo::updated](#updated) | Location where data is updated. If the primary key of the table is of the string type, the value is the value of the primary key. Otherwise, the value is the row number of the updated data.| -| [Rdb_ChangeInfo::deleted](#deleted) | Location where data is deleted. If the primary key of the table is of the string type, the value is the value of the primary key. Otherwise, the value is the row number of the deleted data.| +| [Rdb_ChangeInfo::inserted](#inserted) | Location where data is inserted. If the primary key of the table is of the string type, it is the value of the primary key. Otherwise, it is the row number of the inserted data.| +| [Rdb_ChangeInfo::updated](#updated) | Location where data is updated. If the primary key of the table is of the string type, it is the value of the primary key. Otherwise, it is the row number of the updated data.| +| [Rdb_ChangeInfo::deleted](#deleted) | Location where data is deleted. If the primary key of the table is of the string type, it is the value of the primary key. Otherwise, it is the row number of the deleted data.| | [Rdb_SubscribeCallback::detailsObserver](#detailsobserver) | Callback used to return the details about the device-cloud data change.| | [Rdb_SubscribeCallback::briefObserver](#briefobserver) | Callback used to return the device-cloud data change event.| | [Rdb_DataObserver::context](#context-12) | Context of the data observer.| @@ -367,7 +372,7 @@ The relational database (RDB) store manages data based on relational models. The **Description** -Version of [Rdb_ChangeInfo](_rdb___change_info.md). +Indicates the version of [Rdb_ChangeInfo](_rdb___change_info.md). **Since**: 11 @@ -380,7 +385,7 @@ Version of [Rdb_ChangeInfo](_rdb___change_info.md). **Description** -Version of [Rdb_DistributedConfig](_rdb___distributed_config.md). +Indicates the version of [Rdb_DistributedConfig](_rdb___distributed_config.md). **Since**: 11 @@ -393,13 +398,25 @@ Version of [Rdb_DistributedConfig](_rdb___distributed_config.md). **Description** -Version of **OH_ProgressDetails**. +Indicates the version of **OH_ProgressDetails**. **Since**: 11 ## Type Description +### Rdb_ConflictResolution + +``` +typedef enum Rdb_ConflictResolution Rdb_ConflictResolution +``` + +**Description** + +Defines an enum for conflict resolution policies. + +**Since**: 18 + ### OH_ColumnType ``` @@ -410,7 +427,7 @@ typedef enum OH_ColumnType OH_ColumnType Defines an enum for column types. -**Since**: 16 +**Since**: 10 ### OH_Data_Value @@ -422,7 +439,7 @@ typedef struct OH_Data_Value OH_Data_Value Defines the [OH_Data_Value](#oh_data_value) struct. -**Since**: 16 +**Since**: 18 ### OH_Data_Values @@ -435,7 +452,7 @@ typedef struct OH_Data_Values OH_Data_Values Defines the [OH_Data_Values](#oh_data_values) struct. -**Since**: 16 +**Since**: 18 ### OH_Data_VBuckets @@ -448,7 +465,7 @@ typedef struct OH_Data_VBuckets OH_Data_VBuckets Defines the **OH_Data_VBuckets** struct. -**Since**: 16 +**Since**: 18 ### OH_Rdb_Transaction @@ -460,7 +477,7 @@ typedef struct OH_Rdb_Transaction OH_Rdb_Transaction Defines the [OH_Rdb_Transaction](#oh_rdb_transaction) struct. -**Since**: 16 +**Since**: 18 ### OH_RDB_TransOptions @@ -473,7 +490,7 @@ typedef struct OH_RDB_TransOptions OH_RDB_TransOptions Defines the [OH_RDB_TransOptions](#oh_rdb_transoptions) struct. -**Since**: 16 +**Since**: 18 ### OH_RDB_TransType @@ -486,7 +503,7 @@ typedef enum OH_RDB_TransType OH_RDB_TransType Defines an enum for transaction types of an RDB store. -**Since**: 16 +**Since**: 18 ### Rdb_Tokenizer @@ -496,9 +513,9 @@ typedef enum Rdb_Tokenizer Rdb_Tokenizer **Description** -Define an enum for database tokenizer types. +Defines an enum for database tokenizer types. -**Since**: 16 +**Since**: 18 ### OH_Rdb_ConfigV2 @@ -695,7 +712,7 @@ Defines a callback used to return the details about the device-cloud data change | Name| Description| | -------- | -------- | | context | Pointer to the context of the data observer.| -| changeInfo | Pointer to [Rdb_ChangeInfo](_rdb___change_info.md).| +| changeInfo | Double pointer to [Rdb_ChangeInfo](_rdb___change_info.md).| | count | Number of changed tables.| **See** @@ -737,7 +754,7 @@ typedef struct Rdb_KeyInfo Rdb_KeyInfo **Description** -Defines a struct for the primary key or row number of the row that changes. +Defines a struct for the primary key or number of the row that changes. **Since**: 11 @@ -750,7 +767,7 @@ typedef enum Rdb_Progress Rdb_Progress **Description** -Defines an enum for device-cloud sync progresses. +Defines an enum for device-cloud sync progress states. **Since**: 11 @@ -825,7 +842,7 @@ typedef enum Rdb_SecurityArea Rdb_SecurityArea **Description** -Defines an enum for encryption levels of an RDB store. +Defines an enum for encryption levels of database files. **Since**: 11 @@ -900,7 +917,7 @@ typedef enum Rdb_SyncMode Rdb_SyncMode **Description** -Defines an enum for RDB sync modes. +Defines an enum for RDB store sync modes. **Since**: 11 @@ -919,30 +936,26 @@ Defines a struct for statistics of device-cloud upload and download tasks of a d ## Enum Description - -### OH_ColumnType +### Rdb_ConflictResolution ``` -enum OH_ColumnType +enum Rdb_ConflictResolution ``` **Description** -Enumerates the column types. +Enumerates the conflict resolution policies. -**Since**: 16 +**Since**: 18 -| Value| Description| +| Value| Description| | -------- | -------- | -| TYPE_NULL | NULL.| -| TYPE_INT64 | INT64.| -| TYPE_REAL | REAL.| -| TYPE_TEXT | TEXT.| -| TYPE_BLOB | BLOB.| -| TYPE_ASSET | ASSET (asset attachment).| -| TYPE_ASSETS | ASSETS (multiple asset attachments).| -| TYPE_FLOAT_VECTOR | FLOAT VECTOR.| -| TYPE_UNLIMITED_INT | Number longer than 64 digits.| +| RDB_CONFLICT_NONE | No operation is performed when a conflict occurs.| +| RDB_CONFLICT_ROLLBACK | Throw an error and roll back the transaction.| +| RDB_CONFLICT_ABORT | Throw an error and roll back the current change.| +| RDB_CONFLICT_FAIL | Throw an error and abort the current change without rolling back the modifications before the conflict.| +| RDB_CONFLICT_IGNORE | Ignore the conflicted data and resolve the conflict later.| +| RDB_CONFLICT_REPLACE | Delete the data and then insert the data. If the conflict persists, apply **RDB_CONFLICT_ABORT**.| ### OH_Rdb_ErrCode @@ -956,74 +969,100 @@ Enumerates the error codes. **Since**: 10 +| Value| Description| +| -------- | -------- | +| RDB_ERR | Execution failed.| +| RDB_OK | Execution successful.| +| E_BASE | Base of the error code.| +| RDB_E_NOT_SUPPORTED | The RDB store does not have this capability.| +| RDB_E_ERROR | Common exception.| +| RDB_E_INVALID_ARGS | Invalid parameter.| +| RDB_E_CANNOT_UPDATE_READONLY | Failed to update data because the RDB store is read-only.| +| RDB_E_REMOVE_FILE | Failed to delete the file.| +| RDB_E_EMPTY_TABLE_NAME | The table name is empty.| +| RDB_E_EMPTY_VALUES_BUCKET | The content of the KV pair is empty.| +| RDB_E_EXECUTE_IN_STEP_QUERY | The SQL statement executed during the query is incorrect.| +| RDB_E_INVALID_COLUMN_INDEX | The column index is invalid.| +| RDB_E_INVALID_COLUMN_TYPE | The column type is invalid.| +| RDB_E_EMPTY_FILE_NAME | The file name is empty.| +| RDB_E_INVALID_FILE_PATH | The file path is invalid.| +| RDB_E_TRANSACTION_IN_EXECUTE | Failed to start the transaction.| +| RDB_E_INVALID_STATEMENT | Failed to precompile the SQL statements.| +| RDB_E_EXECUTE_WRITE_IN_READ_CONNECTION | Failed to perform a write operation in a read connection.| +| RDB_E_BEGIN_TRANSACTION_IN_READ_CONNECTION | Failed to start the transaction in a read connection.| +| RDB_E_NO_TRANSACTION_IN_SESSION | The transaction to start does not exist in the database session.| +| RDB_E_MORE_STEP_QUERY_IN_ONE_SESSION | Multiple queries are executed in a database session.| +| RDB_E_NO_ROW_IN_QUERY | The result set does not contain any record.| +| RDB_E_INVALID_BIND_ARGS_COUNT | The number of parameters bound in the SQL statement is invalid.| +| RDB_E_INVALID_OBJECT_TYPE | The object type is invalid.| +| RDB_E_INVALID_CONFLICT_FLAG | The conflict resolution type is invalid.| +| RDB_E_HAVING_CLAUSE_NOT_IN_GROUP_BY | The **HAVING** keyword can be used only after **GROUP BY**.| +| RDB_E_NOT_SUPPORTED_BY_STEP_RESULT_SET | The result set by step is not supported.| +| RDB_E_STEP_RESULT_SET_CROSS_THREADS | Failed to obtain the result set.| +| RDB_E_STEP_RESULT_QUERY_NOT_EXECUTED | The result set query statement is not executed.| +| RDB_E_STEP_RESULT_IS_AFTER_LAST | The pointer of the result set is already in the last row.| +| RDB_E_STEP_RESULT_QUERY_EXCEEDED | The number of result set query times exceeds the limit.| +| RDB_E_STATEMENT_NOT_PREPARED | The SQL statement is not precompiled.| +| RDB_E_EXECUTE_RESULT_INCORRECT | The database execution result is incorrect.| +| RDB_E_STEP_RESULT_CLOSED | The result set has been closed.| +| RDB_E_RELATIVE_PATH | The file path is a relative path.| +| RDB_E_EMPTY_NEW_ENCRYPT_KEY | The new encrypt key is empty.| +| RDB_E_CHANGE_UNENCRYPTED_TO_ENCRYPTED | The RDB store is non-encrypted and cannot be changed.| +| RDB_E_CHANGE_ENCRYPT_KEY_IN_BUSY | The database does not respond when the database key is updated.| +| RDB_E_STEP_STATEMENT_NOT_INIT | The precompiled SQL statement is not initialized.| +| RDB_E_NOT_SUPPORTED_ATTACH_IN_WAL_MODE | The WAL mode does not support the ATTACH operation.| +| RDB_E_CREATE_FOLDER_FAIL | Failed to create the folder.| +| RDB_E_SQLITE_SQL_BUILDER_NORMALIZE_FAIL | Failed to build the SQL statement.| +| RDB_E_STORE_SESSION_NOT_GIVE_CONNECTION_TEMPORARILY | The database session does not provide a connection.| +| RDB_E_STORE_SESSION_NO_CURRENT_TRANSACTION | The transaction does not exist in the database session.| +| RDB_E_NOT_SUPPORT | The current operation is not supported.| +| RDB_E_INVALID_PARCEL | The current PARCEL is invalid.| +| RDB_E_QUERY_IN_EXECUTE | Failed to execute query.| +| RDB_E_SET_PERSIST_WAL | Failed to set the persistence of the database file in WAL mode.| +| RDB_E_DB_NOT_EXIST | The database does not exist.| +| RDB_E_ARGS_READ_CON_OVERLOAD | The number of read connections to set is greater than the limit.| +| RDB_E_WAL_SIZE_OVER_LIMIT | The WAL log file size exceeds the default value.| +| RDB_E_CON_OVER_LIMIT | The number of database connections has reached the limit.| +| RDB_E_ALREADY_CLOSED18+ | The RDB store is already closed.| +| RDB_E_DATABASE_BUSY18+ | The database does not respond.| +| RDB_E_SQLITE_CORRUPT18+ | The database is corrupted.| +| RDB_E_SQLITE_PERM18+ | SQLite: access denied.| +| RDB_E_SQLITE_BUSY18+ | SQLite: database file locked.| +| RDB_E_SQLITE_LOCKED18+ | SQLite: database table locked.| +| RDB_E_SQLITE_NOMEM18+ | SQLite: insufficient database memory.| +| RDB_E_SQLITE_READONLY18+ | SQLite: attempt to write a read-only database.| +| RDB_E_SQLITE_IOERR18+ | SQLite: disk I/O error.| +| RDB_E_SQLITE_FULL18+ | SQLite: database is full.| +| RDB_E_SQLITE_CANT_OPEN18+ | SQLite: unable to open the database file.| +| RDB_E_SQLITE_TOO_BIG18+ | SQLite: TEXT or BLOB exceeds the limit.| +| RDB_E_SQLITE_MISMATCH18+ | SQLite: data types mismatch.| +| RDB_E_DATA_TYPE_NULL18+ | The data to be stored is empty.| +| RDB_E_TYPE_MISMATCH18+ | The data type is incorrect.| +| RDB_E_SQLITE_CONSTRAINT18+ | SQLite error code: SQLite constraint.| + +### OH_ColumnType + +``` +enum OH_ColumnType +``` + +**Description** + +Enumerates the column data types. + +**Since**: 10 + | Value| Description| | -------- | -------- | -| RDB_ERR | Execution failed.| -| RDB_OK | Execution successful.| -| E_BASE | Base of the error code.| -| RDB_E_NOT_SUPPORTED | The RDB store does not have this capability.| -| RDB_E_ERROR | Common exception.| -| RDB_E_INVALID_ARGS | Invalid parameter.| -| RDB_E_CANNOT_UPDATE_READONLY | Failed to update data because the RDB store is read-only.| -| RDB_E_REMOVE_FILE | Failed to delete the file.| -| RDB_E_EMPTY_TABLE_NAME | The table name is empty.| -| RDB_E_EMPTY_VALUES_BUCKET | The content of the KV pair is empty.| -| RDB_E_EXECUTE_IN_STEP_QUERY | The SQL statement executed during the query is incorrect.| -| RDB_E_INVALID_COLUMN_INDEX | The column index is invalid.| -| RDB_E_INVALID_COLUMN_TYPE | The column type is invalid.| -| RDB_E_EMPTY_FILE_NAME | The file name is empty.| -| RDB_E_INVALID_FILE_PATH | The file path is invalid.| -| RDB_E_TRANSACTION_IN_EXECUTE | Failed to start the transaction.| -| RDB_E_INVALID_STATEMENT | Failed to precompile the SQL statements.| -| RDB_E_EXECUTE_WRITE_IN_READ_CONNECTION | Failed to perform a write operation in a read connection.| -| RDB_E_BEGIN_TRANSACTION_IN_READ_CONNECTION | Failed to start the transaction in a read connection.| -| RDB_E_NO_TRANSACTION_IN_SESSION | The transaction to start does not exist in the database session.| -| RDB_E_MORE_STEP_QUERY_IN_ONE_SESSION | Multiple queries are executed in a database session.| -| RDB_E_NO_ROW_IN_QUERY | The result set does not contain any record.| -| RDB_E_INVALID_BIND_ARGS_COUNT | The number of parameters bound in the SQL statement is invalid.| -| RDB_E_INVALID_OBJECT_TYPE | The object type is invalid.| -| RDB_E_INVALID_CONFLICT_FLAG | The conflict resolution type is invalid.| -| RDB_E_HAVING_CLAUSE_NOT_IN_GROUP_BY | The HAVING keyword can be used only after GROUP BY.| -| RDB_E_NOT_SUPPORTED_BY_STEP_RESULT_SET | The result set by step is not supported.| -| RDB_E_STEP_RESULT_SET_CROSS_THREADS | Failed to obtain the result set.| -| RDB_E_STEP_RESULT_QUERY_NOT_EXECUTED | The result set query statement is not executed.| -| RDB_E_STEP_RESULT_IS_AFTER_LAST | The cursor of the result set is already in the last row.| -| RDB_E_STEP_RESULT_QUERY_EXCEEDED | The number of result set query times exceeds the limit.| -| RDB_E_STATEMENT_NOT_PREPARED | The SQL statement is not precompiled.| -| RDB_E_EXECUTE_RESULT_INCORRECT | The database execution result is incorrect.| -| RDB_E_STEP_RESULT_CLOSED | The result set has been closed.| -| RDB_E_RELATIVE_PATH | The file path is a relative path.| -| RDB_E_EMPTY_NEW_ENCRYPT_KEY | The new encrypt key is empty.| -| RDB_E_CHANGE_UNENCRYPTED_TO_ENCRYPTED | The RDB store is non-encrypted and cannot be changed.| -| RDB_E_CHANGE_ENCRYPT_KEY_IN_BUSY | The database does not respond when the database key is updated.| -| RDB_E_STEP_STATEMENT_NOT_INIT | The precompiled SQL statement is not initialized.| -| RDB_E_NOT_SUPPORTED_ATTACH_IN_WAL_MODE | The WAL mode does not support the ATTACH operation.| -| RDB_E_CREATE_FOLDER_FAIL | Failed to create the folder.| -| RDB_E_SQLITE_SQL_BUILDER_NORMALIZE_FAIL | Failed to build the SQL statement.| -| RDB_E_STORE_SESSION_NOT_GIVE_CONNECTION_TEMPORARILY | The database session does not provide a connection.| -| RDB_E_STORE_SESSION_NO_CURRENT_TRANSACTION | The transaction does not exist in the database session.| -| RDB_E_NOT_SUPPORT | The current operation is not supported.| -| RDB_E_INVALID_PARCEL | The current PARCEL is invalid.| -| RDB_E_QUERY_IN_EXECUTE | Failed to execute query.| -| RDB_E_SET_PERSIST_WAL | Failed to set the persistence of the database file in WAL mode.| -| RDB_E_DB_NOT_EXIST | The database does not exist.| -| RDB_E_ARGS_READ_CON_OVERLOAD | The number of read connections to set is greater than the limit.| -| RDB_E_WAL_SIZE_OVER_LIMIT | The WAL log file size exceeds the default value.| -| RDB_E_CON_OVER_LIMIT | The number of database connections has reached the limit.| -| RDB_E_ALREADY_CLOSED16+ | The RDB store is already closed.| -| RDB_E_DATABASE_BUSY16+ | The database does not respond.| -| RDB_E_NOT_SUPPORT_THE_SQL16+ | SQLite: generic error.| -| RDB_E_SQLITE_CORRUPT16+ | The database is corrupted.| -| RDB_E_SQLITE_PERM16+ | SQLite: access denied.| -| RDB_E_SQLITE_BUSY16+ | SQLite: database file locked.| -| RDB_E_SQLITE_LOCKED16+ | SQLite: database table locked.| -| RDB_E_SQLITE_NOMEM16+ | SQLite: insufficient database memory.| -| RDB_E_SQLITE_READONLY16+ | SQLite: attempt to write a read-only database.| -| RDB_E_SQLITE_IOERR16+ | SQLite: disk I/O error.| -| RDB_E_SQLITE_FULL16+ | SQLite: database is full.| -| RDB_E_SQLITE_CANT_OPEN16+ | SQLite: unable to open the database file.| -| RDB_E_SQLITE_TOO_BIG16+ | SQLite: TEXT or BLOB exceeds the limit.| -| RDB_E_SQLITE_MISMATCH16+ | SQLite: data types mismatch.| +| TYPE_NULL | NULL.| +| TYPE_INT64 | INT64.| +| TYPE_REAL | REAL.| +| TYPE_TEXT | TEXT.| +| TYPE_BLOB | BLOB.| +| TYPE_ASSET11+ | ASSET (asset attachment).| +| TYPE_ASSETS11+ | ASSETS (multiple asset attachments).| +| TYPE_FLOAT_VECTOR18+ | FLOAT VECTOR.| +| TYPE_UNLIMITED_INT18+ | Number longer than 64 digits.| ### OH_RDB_TransType @@ -1035,7 +1074,7 @@ enum OH_RDB_TransType Enumerates the transaction types of an RDB store. -**Since**: 16 +**Since**: 18 | Value| Description| | -------- | -------- | @@ -1054,13 +1093,13 @@ enum Rdb_Tokenizer Enumerates the database tokenizer types. -**Since**: 16 +**Since**: 18 | Value| Description| | -------- | -------- | | RDB_NONE_TOKENIZER | No tokenizer is used.| | RDB_ICU_TOKENIZER | Native ICU tokenizer.| -| RDB_CUSTOM_TOKENIZER | CUSTOM tokenizer.| +| RDB_CUSTOM_TOKENIZER | Custom tokenizer.| ### Rdb_DBType @@ -1094,10 +1133,10 @@ Enumerates the RDB store security levels. | Value| Description| | -------- | -------- | -| S1 | The security level of the RDB store is low.
If data leakage occurs, minor impact will be caused.| -| S2 | The security level of the RDB store is medium.
If data leakage occurs, moderate impact will be caused.| -| S3 | The security level of the RDB store is high.
If data leakage occurs, major impact will be caused.| -| S4 | The security level of the RDB store is critical.
If data leakage occurs, critical impact will be caused.| +| S1 | Low security level.
If data leakage occurs, minor impact will be caused.| +| S2 | Medium security level.
If data leakage occurs, moderate impact will be caused.| +| S3 | High security level.
If data leakage occurs, major impact will be caused.| +| S4 | Critical security level.
If data leakage occurs, critical impact will be caused.| ### Rdb_ChangeType @@ -1143,7 +1182,7 @@ enum Rdb_Progress **Description** -Enumerates the device-cloud sync progresses. +Enumerates the device-cloud sync progress states. **Since**: 11 @@ -1162,7 +1201,7 @@ enum Rdb_ProgressCode **Description** -Enumerates the device-cloud sync states. +Enumerates the device-cloud sync state codes. **Since**: 11 @@ -1185,7 +1224,7 @@ enum Rdb_SecurityArea **Description** -Enumerates the encryption levels of an RDB store. +Enumerates the encryption levels of database files. **Since**: 11 @@ -1211,8 +1250,8 @@ Enumerates the subscription types. | Value| Description| | -------- | -------- | -| RDB_SUBSCRIBE_TYPE_CLOUD | Subscription of cloud data changes.| -| RDB_SUBSCRIBE_TYPE_CLOUD_DETAILS | Subscription of cloud data change details.| +| RDB_SUBSCRIBE_TYPE_CLOUD | Subscribe to cloud data changes.| +| RDB_SUBSCRIBE_TYPE_CLOUD_DETAILS | Subscribe to cloud data change details.| | RDB_SUBSCRIBE_TYPE_LOCAL_DETAILS12+ | Subscribe to details of the local data change. This value is available since API version 12.| @@ -1224,7 +1263,7 @@ enum Rdb_SyncMode **Description** -Enumerates the RDB sync modes. +Enumerates the RDB store sync modes. **Since**: 11 @@ -1237,6 +1276,148 @@ Enumerates the RDB sync modes. ## Function Description +### OH_RdbTrans_BatchInsert() + +``` +int OH_RdbTrans_BatchInsert (OH_Rdb_Transaction *trans, const char *table, const OH_Data_VBuckets *rows, Rdb_ConflictResolution resolution, int64_t *changes) +``` + +**Description** + +Inserts a batch of data into a table. + +**Since**: 18 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| trans | Pointer to the [OH_Rdb_Transaction](#oh_rdb_transaction) instance.| +| table | Pointer to the target table.| +| rows | Pointer to the rows of data to insert.| +| resolution | Policy used to resolve file conflicts.| +| changes | Pointer to the number of successful insertions.| + +**Returns** + +Returns the execution result. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_ERROR** indicates a common database error. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. + +**RDB_E_ALREADY_CLOSED** indicates that the database is already closed. + +**RDB_E_WAL_SIZE_OVER_LIMIT** indicates that the size of the WAL log file exceeds the default value. + +**RDB_E_SQLITE_FULL** indicates an SQLite error: the database is full. + +**RDB_E_SQLITE_CORRUPT** indicates that the database is corrupted. + +**RDB_E_SQLITE_PERM** indicates an SQLite error: access denied. + +**RDB_E_SQLITE_BUSY** indicates an SQLite error: database file locked. + +**RDB_E_SQLITE_LOCKED** indicates an SQLite error: database table locked. + +**RDB_E_SQLITE_NOMEM** indicates an SQLite: insufficient database memory. + +**RDB_E_SQLITE_READONLY** indicates an SQLite error: attempt to write a read-only database. + +**RDB_E_SQLITE_IOERR** indicates an SQLite: disk I/O error. + +**RDB_E_SQLITE_TOO_BIG** indicates an SQLite error: TEXT or BLOB exceeds the limit. + +**RDB_E_SQLITE_MISMATCH** indicates an SQLite error: data types mismatch. + +**RDB_E_SQLITE_CONSTRAINT** indicates an SQLite error code: SQLite constraint. + + +### OH_Rdb_BatchInsert() + +``` +int OH_Rdb_BatchInsert (OH_Rdb_Store *store, const char *table, const OH_Data_VBuckets *rows, Rdb_ConflictResolution resolution, int64_t *changes ) +``` + +**Description** + +Inserts a batch of data into a table. + +**Since**: 18 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| store | Pointer to the [OH_Rdb_Store](_o_h___rdb___store.md) instance.| +| tables | Pointer to the names of the distributed tables to set.| +| rows | Pointer to the rows of data to insert.| +| resolution | Policy used to resolve file conflicts.| +| changes | Pointer to the number of successful insertions.| + +**Returns** + +Returns the execution result. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_ERROR** indicates a common database error. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. + +**RDB_E_ALREADY_CLOSED** indicates that the database is already closed. + +**RDB_E_WAL_SIZE_OVER_LIMIT** indicates that the size of the WAL log file exceeds the default value. + +**RDB_E_SQLITE_FULL** indicates an SQLite error: the database is full. + +**RDB_E_SQLITE_CORRUPT** indicates that the database is corrupted. + +**RDB_E_SQLITE_PERM** indicates an SQLite error: access denied. + +**RDB_E_SQLITE_BUSY** indicates an SQLite error: database file locked. + +**RDB_E_SQLITE_LOCKED** indicates an SQLite error: database table locked. + +**RDB_E_SQLITE_NOMEM** indicates an SQLite: insufficient database memory. + +**RDB_E_SQLITE_READONLY** indicates an SQLite error: attempt to write a read-only database. + +**RDB_E_SQLITE_IOERR** indicates an SQLite: disk I/O error. + +**RDB_E_SQLITE_TOO_BIG** indicates an SQLite error: TEXT or BLOB exceeds the limit. + +**RDB_E_SQLITE_MISMATCH** indicates an SQLite error: data types mismatch. + +**RDB_E_SQLITE_CONSTRAINT** indicates an SQLite error code: SQLite constraint. + + +### OH_Rdb_SetPersistent() + +``` +int OH_Rdb_SetPersistent (OH_Rdb_ConfigV2 *config, bool isPersistent ) +``` + +**Description** + +Sets whether to persist an RDB store. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| config | Pointer to the target **OH_Rdb_ConfigV2** instance, which specifies the database configuration.| +| isPersistent | Whether to persist the database data.| + +**Returns** + +Returns the status code of the execution. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Cursor_GetFloatVector() @@ -1246,35 +1427,49 @@ int OH_Cursor_GetFloatVector (OH_Cursor *cursor, int32_t columnIndex, float *val **Description** -Obtains the value in a specified column of the current row in the form of a floating-point array. +Obtains the value in a specified column of the current row in the form of a float array. -**Since**: 16 +**Since**: 18 **Parameters** | Name| Description| | -------- | -------- | | cursor | Pointer to the [OH_Cursor](_o_h___cursor.md) instance.| -| columnIndex | Index of the column. The index value starts from **0**.| -| val | Ponter to the value obtained, in a floating-point array. The caller needs to apply for array memory.| -| inLen | Length of the floating-point array requested.| -| outLen | Pointer to the actual length of the floating-point array.| +| columnIndex | Index of the column, which starts from **0**.| +| val | Ponter to the value obtained, in a float array. The caller needs to apply for the memory.| +| inLen | Length of the float array requested.| +| outLen | Pointer to the length of the value obtained.| **Returns** Returns the execution result. -**RDB_OK** indicates the operation is successful. + +**RDB_OK** indicates that the operation is successful. + **RDB_E_ERROR** indicates a common database error. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. -**RDB_E_SQLITE_CORRUPT** indicates the database is corrupted. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. + +**RDB_E_SQLITE_CORRUPT** indicates that the database is corrupted. + **RDB_E_STEP_RESULT_CLOSED** indicates the result set is closed. -**RDB_E_ALREADY_CLOSED** indicates the database is closed. + +**RDB_E_ALREADY_CLOSED** indicates that the database is already closed. + **RDB_E_SQLITE_PERM** indicates an SQLite error: access denied. + **RDB_E_SQLITE_BUSY** indicates an SQLite error: database file locked. + **RDB_E_SQLITE_LOCKED** indicates an SQLite error: database table locked. + **RDB_E_SQLITE_NOMEM** indicates an SQLite: insufficient database memory. + **RDB_E_SQLITE_IOERR** indicates an SQLite: disk I/O error. -**RDB_E_SQLITE_TOO_BIG** indicates an SQLite error: TEXT or BLOB exceeds the limit. **RDB_E_SQLITE_MISMATCH** indicates an SQLite error: data types mismatch. + +**RDB_E_SQLITE_TOO_BIG** indicates an SQLite error: TEXT or BLOB exceeds the limit. + +**RDB_E_SQLITE_MISMATCH** indicates an SQLite error: data types mismatch. **See** @@ -1289,33 +1484,46 @@ int OH_Cursor_GetFloatVectorCount (OH_Cursor *cursor, int32_t columnIndex, size_ **Description** -Obtains the length of the floating-point array in the specified column of the current row. +Obtains the length of the float array in the specified column of the current row. -**Since**: 16 +**Since**: 18 **Parameters** | Name| Description| | -------- | -------- | | cursor | Pointer to the [OH_Cursor](_o_h___cursor.md) instance.| -| columnIndex | Index of the column. The index value starts from **0**.| -| length | Pointer to the length of the floating-point array obtained.| +| columnIndex | Index of the column, which starts from **0**.| +| length | Pointer to the length of the float array obtained.| **Returns** Returns the execution result. -**RDB_OK** indicates the operation is successful. + +**RDB_OK** indicates that the operation is successful. + **RDB_E_ERROR** indicates a common database error. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. -**RDB_E_SQLITE_CORRUPT** indicates the database is corrupted. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. + +**RDB_E_SQLITE_CORRUPT** indicates that the database is corrupted. + **RDB_E_STEP_RESULT_CLOSED** indicates the result set is closed. -**RDB_E_ALREADY_CLOSED** indicates the database is closed. + +**RDB_E_ALREADY_CLOSED** indicates that the database is already closed. + **RDB_E_SQLITE_PERM** indicates an SQLite error: access denied. + **RDB_E_SQLITE_BUSY** indicates an SQLite error: database file locked. + **RDB_E_SQLITE_LOCKED** indicates an SQLite error: database table locked. + **RDB_E_SQLITE_NOMEM** indicates an SQLite: insufficient database memory. + **RDB_E_SQLITE_IOERR** indicates an SQLite: disk I/O error. + **RDB_E_SQLITE_TOO_BIG** indicates an SQLite error: TEXT or BLOB exceeds the limit. + **RDB_E_SQLITE_MISMATCH** indicates an SQLite error: data types mismatch. ### OH_Rdb_CreateTransaction() @@ -1328,33 +1536,33 @@ int OH_Rdb_CreateTransaction (OH_Rdb_Store *store, const OH_RDB_TransOptions *op Creates a transaction object. -**Since**: 16 +**Since**: 18 **Parameters** | Name| Description| | -------- | -------- | | store | Pointer to the [OH_Rdb_Store](_o_h___rdb___store.md) instance.| -| options | Pointer to the [OH_RDB_TransOptions](#oh_rdb_transoptions) instance.| -| trans | Pointer to the [OH_Rdb_Transaction](#oh_rdb_transaction) instance created if the operation is successful. If the operation fails, **nullptr** is returned. Call [OH_RdbTrans_Destroy](#oh_rdbtrans_destroy) to release the transaction instance that is no longer required.| +| options | Pointer to the [OH_RDB_TransOptions](#oh_rdb_transoptions) instance for the transaction instance to create.| +| trans | Double pointer to the [OH_Rdb_Transaction](#oh_rdb_transaction) instance created if the operation is successful. If the operation fails, **nullptr** is returned. Call [OH_RdbTrans_Destroy](#oh_rdbtrans_destroy) to release the transaction instance that is no longer required.| **Returns** Returns the execution result. -**RDB_OK** indicates the operation is successful. +**RDB_OK** indicates that the operation is successful. **RDB_E_ERROR** indicates a common database error. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. -**RDB_E_ALREADY_CLOSED** indicates the database is closed. +**RDB_E_ALREADY_CLOSED** indicates that the database is already closed. **RDB_E_DATABASE_BUSY** indicates the database does not respond. **RDB_E_SQLITE_FULL** indicates an SQLite error: the database is full. -**RDB_E_SQLITE_CORRUPT** indicates the database is corrupted. +**RDB_E_SQLITE_CORRUPT** indicates that the database is corrupted. **RDB_E_SQLITE_PERM** indicates an SQLite error: access denied. @@ -1381,7 +1589,7 @@ OH_Cursor *OH_Rdb_ExecuteQueryV2 (OH_Rdb_Store *store, const char *sql, const OH Queries data in the database using the specified SQL statement. This API supports vector stores. -**Since**: 16 +**Since**: 18 **Parameters** @@ -1393,7 +1601,9 @@ Queries data in the database using the specified SQL statement. This API support **Returns** -Returns a pointer to the [OH_Cursor](_o_h___cursor.md) instance if the operation is successful. Release the [OH_Cursor](_o_h___cursor.md) instance that is no longer required in time. Returns **NULL** if the SQL statement is invalid or the memory allocation fails. +Returns a pointer to the [OH_Cursor](_o_h___cursor.md) instance if the operation is successful. Release the [OH_Cursor](_o_h___cursor.md) instance that is no longer required in time. + +Returns **NULL** if the SQL statement is invalid or the memory allocation fails. **See** @@ -1410,7 +1620,7 @@ int OH_Rdb_ExecuteV2 (OH_Rdb_Store *store, const char *sql, const OH_Data_Values Executes an SQL statement with a return value. This API supports vector stores. -**Since**: 16 +**Since**: 18 **Parameters** @@ -1418,26 +1628,26 @@ Executes an SQL statement with a return value. This API supports vector stores. | -------- | -------- | | store | Pointer to the [OH_Rdb_Store](_o_h___rdb___store.md) instance.| | sql | Pointer to the SQL statement to execute.| -| args | Pointer to the **{\@OH_Data_Values}** instance. This parameter is optional.| -| result | Pointer to the [OH_Data_Value](#oh_data_value) instance returned if the operation is successful.
Use [OH_Value_Destroy](#oh_value_destroy) to release the memory in time.| +| args | Pointer to the **OH_Data_Values** instance. This parameter is optional.| +| result | Double pointer to the [OH_Data_Value](#oh_data_value) instance returned if the operation is successful.
Use [OH_Value_Destroy](#oh_value_destroy) to release the memory in time.| **Returns** Returns the execution result. -**RDB_OK** indicates the operation is successful. +**RDB_OK** indicates that the operation is successful. **RDB_E_ERROR** indicates a common database error. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. -**RDB_E_ALREADY_CLOSED** indicates the database is closed. +**RDB_E_ALREADY_CLOSED** indicates that the database is already closed. -**RDB_E_WAL_SIZE_OVER_LIMIT** indicates the size of the WAL log file exceeds the default value. +**RDB_E_WAL_SIZE_OVER_LIMIT** indicates that the size of the WAL log file exceeds the default value. **RDB_E_SQLITE_FULL** indicates an SQLite error: the database is full. -**RDB_E_SQLITE_CORRUPT** indicates the database is corrupted. +**RDB_E_SQLITE_CORRUPT** indicates that the database is corrupted. **RDB_E_SQLITE_PERM** indicates an SQLite error: access denied. @@ -1470,18 +1680,22 @@ int OH_Rdb_IsTokenizerSupported (Rdb_Tokenizer tokenizer, bool *isSupported ) Checks whether the specified tokenizer is supported. -**Since**: 16 +**Since**: 18 **Parameters** | Name| Description| | -------- | -------- | | tokenizer | Tokenizer to check.| -| isSupported | Pointer to the check.
The value **true** means the tokenizer is supported; the value **false** means the opposite.| +| isSupported | Pointer to the check result.
The value **true** means the tokenizer is supported; the value **false** means the opposite.| **Returns** -Returns the operation status code. **RDB_OK** indicates the operation is successful. **RDB_E_INVALID_ARGS** indicates invalid parameters are specified. +Returns the operation status code. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Rdb_SetTokenizer() @@ -1494,7 +1708,7 @@ int OH_Rdb_SetTokenizer (OH_Rdb_ConfigV2 *config, Rdb_Tokenizer tokenizer ) Sets the tokenizer type. -**Since**: 16 +**Since**: 18 **Parameters** @@ -1507,84 +1721,54 @@ Sets the tokenizer type. Returns the operation status code. -**RDB_OK** indicates the operation is successful. - -
**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. +**RDB_OK** indicates that the operation is successful. -
**RDB_E_NOT_SUPPORTED** indicates that the current operation is not supported. +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. +**RDB_E_NOT_SUPPORTED** indicates that the current operation is not supported. -### OH_RdbTrans_BatchInsert() +### OH_RdbTrans_Commit() ``` -int OH_RdbTrans_BatchInsert (OH_Rdb_Transaction *trans, const char *table, const OH_Data_VBuckets *rows, int64_t *changes ) +int OH_RdbTrans_Commit (OH_Rdb_Transaction *trans) ``` **Description** -Batch inserts data into a table. +Commits a transaction. -**Since**: 16 +**Since**: 18 **Parameters** | Name| Description| | -------- | -------- | -| trans | Pointer to the [OH_Rdb_Transaction](#oh_rdb_transaction) instance.| -| table | Pointer to the target table.| -| rows | Pointer to the rows of data to insert.| -| changes | Pointer to the number of successful insertions.| +| trans | Pointer to the [OH_Rdb_Transaction](#oh_rdb_transaction) instance to commit.| **Returns** Returns the execution result. -**RDB_OK** indicates the operation is successful. -**RDB_E_ERROR** indicates a common database error. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. -**RDB_E_ALREADY_CLOSED** indicates the database is closed. -**RDB_E_WAL_SIZE_OVER_LIMIT** indicates the size of the WAL log file exceeds the default value. -**RDB_E_SQLITE_FULL** indicates an SQLite error: the database is full. -**RDB_E_SQLITE_CORRUPT** indicates the database is corrupted. -**RDB_E_SQLITE_PERM** indicates an SQLite error: access denied. -**RDB_E_SQLITE_BUSY** indicates an SQLite error: database file locked. -**RDB_E_SQLITE_LOCKED** indicates an SQLite error: database table locked. -**RDB_E_SQLITE_NOMEM** indicates an SQLite: insufficient database memory. -**RDB_E_SQLITE_READONLY** indicates an SQLite error: attempt to write a read-only database. -**RDB_E_SQLITE_IOERR** indicates an SQLite: disk I/O error. -**RDB_E_SQLITE_TOO_BIG** indicates an SQLite error: TEXT or BLOB exceeds the limit. -**RDB_E_SQLITE_MISMATCH** indicates an SQLite error: data types mismatch. - -### OH_RdbTrans_Commit() - -``` -int OH_RdbTrans_Commit (OH_Rdb_Transaction *trans) -``` -**Description** +**RDB_OK** indicates that the operation is successful. -Commits a transaction. +**RDB_E_ERROR** indicates a common database error. -**Since**: 16 +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. -**Parameters** +**RDB_E_ALREADY_CLOSED** indicates that the database is already closed. -| Name| Description| -| -------- | -------- | -| trans | Pointer to the [OH_Rdb_Transaction](#oh_rdb_transaction) instance to commit.| +**RDB_E_SQLITE_FULL** indicates an SQLite error: the database is full. -**Returns** +**RDB_E_SQLITE_CORRUPT** indicates that the database is corrupted. -Returns the execution result. -**RDB_OK** indicates the operation is successful. -**RDB_E_ERROR** indicates a common database error. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. -**RDB_E_ALREADY_CLOSED** indicates the database is closed. -**RDB_E_SQLITE_FULL** indicates an SQLite error: the database is full. -**RDB_E_SQLITE_CORRUPT** indicates the database is corrupted. **RDB_E_SQLITE_PERM** indicates an SQLite error: access denied. + **RDB_E_SQLITE_BUSY** indicates an SQLite error: database file locked. + **RDB_E_SQLITE_NOMEM** indicates an SQLite: insufficient database memory. + **RDB_E_SQLITE_READONLY** indicates an SQLite error: attempt to write a read-only database. + **RDB_E_SQLITE_IOERR** indicates an SQLite: disk I/O error. ### OH_RdbTrans_Delete() @@ -1597,7 +1781,7 @@ int OH_RdbTrans_Delete (OH_Rdb_Transaction *trans, const OH_Predicates *predicat Deletes data from the database based on the specified conditions. -**Since**: 16 +**Since**: 18 **Parameters** @@ -1610,20 +1794,35 @@ Deletes data from the database based on the specified conditions. **Returns** Returns the execution result. -**RDB_OK** indicates the operation is successful. + +**RDB_OK** indicates that the operation is successful. + **RDB_E_ERROR** indicates a common database error. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. -**RDB_E_ALREADY_CLOSED** indicates the database is closed. -**RDB_E_WAL_SIZE_OVER_LIMIT** indicates the size of the WAL log file exceeds the default value. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. + +**RDB_E_ALREADY_CLOSED** indicates that the database is already closed. + +**RDB_E_WAL_SIZE_OVER_LIMIT** indicates that the size of the WAL log file exceeds the default value. + **RDB_E_SQLITE_FULL** indicates an SQLite error: the database is full. -**RDB_E_SQLITE_CORRUPT** indicates the database is corrupted. + +**RDB_E_SQLITE_CORRUPT** indicates that the database is corrupted. + **RDB_E_SQLITE_PERM** indicates an SQLite error: access denied. + **RDB_E_SQLITE_BUSY** indicates an SQLite error: database file locked. + **RDB_E_SQLITE_LOCKED** indicates an SQLite error: database table locked. + **RDB_E_SQLITE_NOMEM** indicates an SQLite: insufficient database memory. + **RDB_E_SQLITE_READONLY** indicates an SQLite error: attempt to write a read-only database. + **RDB_E_SQLITE_IOERR** indicates an SQLite: disk I/O error. + **RDB_E_SQLITE_TOO_BIG** indicates an SQLite error: TEXT or BLOB exceeds the limit. + **RDB_E_SQLITE_MISMATCH** indicates an SQLite error: data types mismatch. ### OH_RdbTrans_CreateOptions() @@ -1634,9 +1833,9 @@ OH_RDB_TransOptions* OH_RdbTrans_CreateOptions (void ) **Description** -Create a transaction configuration object. +Creates a transaction configuration object. -**Since**: 16 +**Since**: 18 **Returns** @@ -1656,17 +1855,21 @@ int OH_RdbTrans_Destroy (OH_Rdb_Transaction *trans) Destroys a transaction object. -**Since**: 16 +**Since**: 18 **Parameters** | Name| Description| | -------- | -------- | -| trans | Pointer to the [OH_Rdb_Transaction](#oh_rdb_transaction) instance to commit.| +| trans | Pointer to the [OH_Rdb_Transaction](#oh_rdb_transaction) instance to destroy.| **Returns** -Returns the operation status code. **RDB_OK** indicates the operation is successful. **RDB_E_INVALID_ARGS** indicates invalid parameters are specified. +Returns the operation status code. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_RdbTrans_DestroyOptions() @@ -1677,9 +1880,9 @@ int OH_RdbTrans_DestroyOptions (OH_RDB_TransOptions *opitons) **Description** -Destroys a transaction configuration instance. +Destroys a **TransOptions** instance. -**Since**: 16 +**Since**: 18 **Parameters** @@ -1690,8 +1893,10 @@ Destroys a transaction configuration instance. **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_RdbTrans_Execute() @@ -1704,7 +1909,7 @@ int OH_RdbTrans_Execute (OH_Rdb_Transaction *trans, const char *sql, const OH_Da Executes an SQL statement that contains specified parameters. -**Since**: 16 +**Since**: 18 **Parameters** @@ -1718,20 +1923,35 @@ Executes an SQL statement that contains specified parameters. **Returns** Returns the execution result. -**RDB_OK** indicates the operation is successful. + +**RDB_OK** indicates that the operation is successful. + **RDB_E_ERROR** indicates a common database error. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. -**RDB_E_ALREADY_CLOSED** indicates the database is closed. -**RDB_E_WAL_SIZE_OVER_LIMIT** indicates the size of the WAL log file exceeds the default value. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. + +**RDB_E_ALREADY_CLOSED** indicates that the database is already closed. + +**RDB_E_WAL_SIZE_OVER_LIMIT** indicates that the size of the WAL log file exceeds the default value. + **RDB_E_SQLITE_FULL** indicates an SQLite error: the database is full. -**RDB_E_SQLITE_CORRUPT** indicates the database is corrupted. + +**RDB_E_SQLITE_CORRUPT** indicates that the database is corrupted. + **RDB_E_SQLITE_PERM** indicates an SQLite error: access denied. + **RDB_E_SQLITE_BUSY** indicates an SQLite error: database file locked. + **RDB_E_SQLITE_LOCKED** indicates an SQLite error: database table locked. + **RDB_E_SQLITE_NOMEM** indicates an SQLite: insufficient database memory. + **RDB_E_SQLITE_READONLY** indicates an SQLite error: attempt to write a read-only database. + **RDB_E_SQLITE_IOERR** indicates an SQLite: disk I/O error. + **RDB_E_SQLITE_TOO_BIG** indicates an SQLite error: TEXT or BLOB exceeds the limit. + **RDB_E_SQLITE_MISMATCH** indicates an SQLite error: data types mismatch. **See** @@ -1749,7 +1969,7 @@ int OH_RdbTrans_Insert (OH_Rdb_Transaction *trans, const char *table, const OH_V Inserts a row of data into a table. -**Since**: 16 +**Since**: 18 **Parameters** @@ -1763,20 +1983,35 @@ Inserts a row of data into a table. **Returns** Returns the execution result. -**RDB_OK** indicates the operation is successful. + +**RDB_OK** indicates that the operation is successful. + **RDB_E_ERROR** indicates a common database error. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. -**RDB_E_ALREADY_CLOSED** indicates the database is closed. -**RDB_E_WAL_SIZE_OVER_LIMIT** indicates the size of the WAL log file exceeds the default value. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. + +**RDB_E_ALREADY_CLOSED** indicates that the database is already closed. + +**RDB_E_WAL_SIZE_OVER_LIMIT** indicates that the size of the WAL log file exceeds the default value. + **RDB_E_SQLITE_FULL** indicates an SQLite error: the database is full. -**RDB_E_SQLITE_CORRUPT** indicates the database is corrupted. + +**RDB_E_SQLITE_CORRUPT** indicates that the database is corrupted. + **RDB_E_SQLITE_PERM** indicates an SQLite error: access denied. + **RDB_E_SQLITE_BUSY** indicates an SQLite error: database file locked. + **RDB_E_SQLITE_LOCKED** indicates an SQLite error: database table locked. + **RDB_E_SQLITE_NOMEM** indicates an SQLite: insufficient database memory. + **RDB_E_SQLITE_READONLY** indicates an SQLite error: attempt to write a read-only database. + **RDB_E_SQLITE_IOERR** indicates an SQLite: disk I/O error. + **RDB_E_SQLITE_TOO_BIG** indicates an SQLite error: TEXT or BLOB exceeds the limit. + **RDB_E_SQLITE_MISMATCH** indicates an SQLite error: data types mismatch. ### OH_RdbTrans_Query() @@ -1789,7 +2024,7 @@ OH_Cursor* OH_RdbTrans_Query (OH_Rdb_Transaction *trans, const OH_Predicates *pr Queries data in the database based on specified conditions. -**Since**: 16 +**Since**: 18 **Parameters** @@ -1815,7 +2050,7 @@ OH_Cursor* OH_RdbTrans_QuerySql (OH_Rdb_Transaction *trans, const char *sql, con Queries data in the database using the specified SQL statement. -**Since**: 16 +**Since**: 18 **Parameters** @@ -1840,27 +2075,38 @@ int OH_RdbTrans_Rollback (OH_Rdb_Transaction *trans) Rolls back a transaction. -**Since**: 16 +**Since**: 18 **Parameters** | Name| Description| | -------- | -------- | -| trans | Pointer to the [OH_Rdb_Transaction](#oh_rdb_transaction) instance to commit.| +| trans | Pointer to the [OH_Rdb_Transaction](#oh_rdb_transaction) instance to roll back.| **Returns** Returns the execution result. -**RDB_OK** indicates the operation is successful. + +**RDB_OK** indicates that the operation is successful. + **RDB_E_ERROR** indicates a common database error. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. -**RDB_E_ALREADY_CLOSED** indicates the database is closed. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. + +**RDB_E_ALREADY_CLOSED** indicates that the database is already closed. + **RDB_E_SQLITE_FULL** indicates an SQLite error: the database is full. -**RDB_E_SQLITE_CORRUPT** indicates the database is corrupted. + +**RDB_E_SQLITE_CORRUPT** indicates that the database is corrupted. + **RDB_E_SQLITE_PERM** indicates an SQLite error: access denied. + **RDB_E_SQLITE_BUSY** indicates an SQLite error: database file locked. + **RDB_E_SQLITE_NOMEM** indicates an SQLite: insufficient database memory. + **RDB_E_SQLITE_READONLY** indicates an SQLite error: attempt to write a read-only database. + **RDB_E_SQLITE_IOERR** indicates an SQLite: disk I/O error. @@ -1874,7 +2120,7 @@ int OH_RdbTrans_Update (OH_Rdb_Transaction *trans, const OH_VBucket *row, const Updates data in an RDB store based on specified conditions. -**Since**: 16 +**Since**: 18 **Parameters** @@ -1888,20 +2134,35 @@ Updates data in an RDB store based on specified conditions. **Returns** Returns the execution result. -**RDB_OK** indicates the operation is successful. + +**RDB_OK** indicates that the operation is successful. + **RDB_E_ERROR** indicates a common database error. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. -**RDB_E_ALREADY_CLOSED** indicates the database is closed. -**RDB_E_WAL_SIZE_OVER_LIMIT** indicates the size of the WAL log file exceeds the default value. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. + +**RDB_E_ALREADY_CLOSED** indicates that the database is already closed. + +**RDB_E_WAL_SIZE_OVER_LIMIT** indicates that the size of the WAL log file exceeds the default value. + **RDB_E_SQLITE_FULL** indicates an SQLite error: the database is full. -**RDB_E_SQLITE_CORRUPT** indicates the database is corrupted. + +**RDB_E_SQLITE_CORRUPT** indicates that the database is corrupted. + **RDB_E_SQLITE_PERM** indicates an SQLite error: access denied. + **RDB_E_SQLITE_BUSY** indicates an SQLite error: database file locked. + **RDB_E_SQLITE_LOCKED** indicates an SQLite error: database table locked. + **RDB_E_SQLITE_NOMEM** indicates an SQLite: insufficient database memory. + **RDB_E_SQLITE_READONLY** indicates an SQLite error: attempt to write a read-only database. + **RDB_E_SQLITE_IOERR** indicates an SQLite: disk I/O error. + **RDB_E_SQLITE_TOO_BIG** indicates an SQLite error: TEXT or BLOB exceeds the limit. + **RDB_E_SQLITE_MISMATCH** indicates an SQLite error: data types mismatch. ### OH_RdbTransOption_SetType() @@ -1912,9 +2173,9 @@ int OH_RdbTransOption_SetType (OH_RDB_TransOptions *opitons, OH_RDB_TransType ty **Description** -Set the transaction type of an RDB store. +Sets the transaction type of an RDB store. -**Since**: 16 +**Since**: 18 **Parameters** @@ -1926,8 +2187,10 @@ Set the transaction type of an RDB store. **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Value_Create() @@ -1940,7 +2203,7 @@ OH_Data_Value* OH_Value_Create (void ) Creates an [OH_Data_Value](#oh_data_value) instance to store a single KV pair. -**Since**: 16 +**Since**: 18 **Returns** @@ -1961,7 +2224,7 @@ int OH_Value_Destroy (OH_Data_Value *value) Destroys an [OH_Data_Value](#oh_data_value) instance. -**Since**: 16 +**Since**: 18 **Parameters** @@ -1971,7 +2234,11 @@ Destroys an [OH_Data_Value](#oh_data_value) instance. **Returns** -Returns the operation status code. **RDB_OK** indicates the operation is successful. **RDB_E_INVALID_ARGS** indicates invalid parameters are specified. +Returns the operation status code. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Value_GetAsset() @@ -1982,9 +2249,9 @@ int OH_Value_GetAsset (OH_Data_Value *value, Data_Asset *val ) **Description** -Obtains data of the ASSET type. +Obtains the asset from an **OH_Data_Value** instance. -**Since**: 16 +**Since**: 18 **Parameters** @@ -1996,9 +2263,13 @@ Obtains data of the ASSET type. **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. + **RDB_E_DATA_TYPE_NULL** indicates the stored data is empty. + **RDB_E_TYPE_MISMATCH** indicates the data types do not match. ### OH_Value_GetAssets() @@ -2009,25 +2280,29 @@ int OH_Value_GetAssets (OH_Data_Value *value, Data_Asset **val, size_t inLen, si **Description** -Obtains data of the ASSETS type. +Obtains the assets from an **OH_Data_Value** instance. -**Since**: 16 +**Since**: 18 **Parameters** | Name| Description| | -------- | -------- | | value | Pointer to the target [OH_Data_Value](#oh_data_value) instance.| -| val | Pointer to the **Data_Asset** object obtained if the operation is successful. You need to apply for memory for it. This function is used to fill in data only. Otherwise, the operation fails.| +| val | Double pointer to the **Data_Asset** object obtained if the operation is successful. You need to apply for memory for it. This function is used to fill in data only. Otherwise, the operation fails.| | inLen | Size of **val**, which can be obtained by [OH_Values_GetAssetsCount](#oh_values_getassetscount).| -| outLen | Pointer to the actual length of the data obtained.| +| outLen | Pointer to the size of the obtained data.| **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. + **RDB_E_DATA_TYPE_NULL** indicates the stored data is empty. + **RDB_E_TYPE_MISMATCH** indicates the data types do not match. **See** @@ -2043,23 +2318,27 @@ int OH_Value_GetAssetsCount (OH_Data_Value *value, size_t *length ) **Description** -Obtains the length of ASSETS data. +Obtains the length of the asset in an **OH_Data_Value** instance. -**Since**: 16 +**Since**: 18 **Parameters** | Name| Description| | -------- | -------- | | value | Pointer to the target [OH_Data_Value](#oh_data_value) instance.| -| length | Pointer to the length of the ASSETS data obtained.| +| length | Pointer to the ASSETS data length obtained.| **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. + **RDB_E_DATA_TYPE_NULL** indicates the stored data is empty. + **RDB_E_TYPE_MISMATCH** indicates the data types do not match. @@ -2071,9 +2350,9 @@ int OH_Value_GetBlob (OH_Data_Value *value, const uint8_t **val, size_t *length **Description** -Obtains data of the BLOB type. +Obtains the BLOB data from an **OH_Data_Value** instance. -**Since**: 16 +**Since**: 18 **Parameters** @@ -2081,14 +2360,18 @@ Obtains data of the BLOB type. | -------- | -------- | | value | Pointer to the target [OH_Data_Value](#oh_data_value) instance.| | val | Double pointer to the BLOB data obtained. You do not need to apply for or release memory for it. The lifecycle of **val** complies with the value of **index** in **value**.| -| length | Pointer to the length of the BLOB array obtained.| +| length | Pointer to the length of the BLOB data obtained.| **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. + **RDB_E_DATA_TYPE_NULL** indicates the stored data is empty. + **RDB_E_TYPE_MISMATCH** indicates the data types do not match. @@ -2100,25 +2383,29 @@ int OH_Value_GetFloatVector (OH_Data_Value *value, float *val, size_t inLen, siz **Description** -Obtains data of the floating-point array type. +Obtains the float array from an **OH_Data_Value** instance. -**Since**: 16 +**Since**: 18 **Parameters** | Name| Description| | -------- | -------- | | value | Pointer to the target [OH_Data_Value](#oh_data_value) instance.| -| val | Pointer to the floating-point array obtained. You need to apply for memory for it. This function is used to fill in data only. Otherwise, the operation fails.| -| inLen | Size of **val**, which can be obtained by [OH_Values_GetFloatVectorCount](#oh_values_getfloatvectorcount).| -| outLen | Pointer to the actual length of the data obtained.| +| val | Pointer to the float array obtained. You need to apply for memory for it. This function is used to fill in data only. Otherwise, the operation fails.| +| inLen | Size of **val**, which can be obtained by using [OH_Values_GetFloatVectorCount](#oh_values_getfloatvectorcount).| +| outLen | Pointer to the length of the obtained data.| **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. + **RDB_E_DATA_TYPE_NULL** indicates the stored data is empty. + **RDB_E_TYPE_MISMATCH** indicates the data types do not match. **See** @@ -2134,23 +2421,27 @@ int OH_Value_GetFloatVectorCount (OH_Data_Value *value, size_t *length ) **Description** -Obtains the length of a floating-point array. +Obtains the length of a float array. -**Since**: 16 +**Since**: 18 **Parameters** | Name| Description| | -------- | -------- | | value | Pointer to the target [OH_Data_Value](#oh_data_value) instance.| -| length | Pointer to the length of the floating-point array obtained.| +| length | Pointer to the length of the float data obtained.| **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. + **RDB_E_DATA_TYPE_NULL** indicates the stored data is empty. + **RDB_E_TYPE_MISMATCH** indicates the data types do not match. @@ -2162,9 +2453,9 @@ int OH_Value_GetInt (OH_Data_Value *value, int64_t *val ) **Description** -Obtains integer data. +Obtains the integer from an **OH_Data_Value** instance. -**Since**: 16 +**Since**: 18 **Parameters** @@ -2176,9 +2467,13 @@ Obtains integer data. **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. + **RDB_E_DATA_TYPE_NULL** indicates the stored data is empty. + **RDB_E_TYPE_MISMATCH** indicates the data types do not match. @@ -2190,9 +2485,9 @@ int OH_Value_GetReal (OH_Data_Value *value, double *val ) **Description** -Obtains data of the REAL type. +Obtains the REAL data from an **OH_Data_Value** instance. -**Since**: 16 +**Since**: 18 **Parameters** @@ -2204,9 +2499,13 @@ Obtains data of the REAL type. **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. + **RDB_E_DATA_TYPE_NULL** indicates the stored data is empty. + **RDB_E_TYPE_MISMATCH** indicates the data types do not match. @@ -2218,23 +2517,27 @@ int OH_Value_GetText (OH_Data_Value *value, const char **val ) **Description** -Obtains data of the string type. +Obtains the string from an **OH_Data_Value** instance. -**Since**: 16 +**Since**: 18 **Parameters** | Name| Description| | -------- | -------- | | value | Pointer to the target [OH_Data_Value](#oh_data_value) instance.| -| val | Pointer to the string obtained. You do not need to apply for or release memory for it. The lifecycle of **val** complies with the value of **index** in **value**.| +| val | Double pointer to the string obtained. You do not need to apply for or release memory for it. The lifecycle of **val** complies with the value of **index** in **value**.| **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. + **RDB_E_DATA_TYPE_NULL** indicates the stored data is empty. + **RDB_E_TYPE_MISMATCH** indicates the data types do not match. ### OH_Value_GetType() @@ -2247,7 +2550,7 @@ int OH_Value_GetType (OH_Data_Value *value, OH_ColumnType *type ) Obtains the data type. -**Since**: 16 +**Since**: 18 **Parameters** @@ -2259,8 +2562,10 @@ Obtains the data type. **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Value_GetUnlimitedInt() @@ -2271,26 +2576,30 @@ int OH_Value_GetUnlimitedInt (OH_Data_Value *value, int *sign, uint64_t *trueFor **Description** -Obtains integer data of any length. +Obtains the unlimited integer from an **OH_Data_Value** instance. -**Since**: 16 +**Since**: 18 **Parameters** | Name| Description| | -------- | -------- | | value | Pointer to the target [OH_Data_Value](#oh_data_value) instance.| -| sign | Pointer to the sign notation of the integer obtained. The value **0** indicates a positive integer, and the value **1** indicates a negative integer.| +| sign | Pointer to the sign notation of the data obtained. The value **0** indicates a positive integer, and **1** indicates a negative integer.| | trueForm | Pointer to the integer array obtained. You need to apply for memory for it. This function is used to fill in data only. Otherwise, the operation fails.| -| inLen | **trueForm** length, which can be obtained by [OH_Values_GetUnlimitedIntBand](#oh_values_getunlimitedintband).| -| outLen | Pointer to the actual length of the data obtained.| +| inLen | **trueForm** length, which can be obtained by using [OH_Values_GetUnlimitedIntBand](#oh_values_getunlimitedintband).| +| outLen | Pointer to the length of the obtained data.| **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. + **RDB_E_DATA_TYPE_NULL** indicates the stored data is empty. + **RDB_E_TYPE_MISMATCH** indicates the data types do not match. **See** @@ -2306,23 +2615,27 @@ int OH_Value_GetUnlimitedIntBand (OH_Data_Value *value, size_t *length ) **Description** -Obtains the length of an unlimited integer. +Obtains the length of the unlimited integer from an **OH_Data_Value** instance. -**Since**: 16 +**Since**: 18 **Parameters** | Name| Description| | -------- | -------- | | value | Pointer to the target [OH_Data_Value](#oh_data_value) instance.| -| length | Pointer to the length obtained.| +| length | Pointer to the length of the integer obtained.| **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. + **RDB_E_DATA_TYPE_NULL** indicates the stored data is empty. + **RDB_E_TYPE_MISMATCH** indicates the data types do not match. ### OH_Value_IsNull() @@ -2335,20 +2648,22 @@ int OH_Value_IsNull (OH_Data_Value *value, bool *val ) Checks whether a value is null. -**Since**: 16 +**Since**: 18 **Parameters** | Name| Description| | -------- | -------- | | value | Pointer to the target [OH_Data_Value](#oh_data_value) instance.| -| val | Pointer to the check result. The value **true** means the value is null, and the value **false** means the opposite.| +| val | Pointer to a boolean value, which indicates whether the data is null. The value **true** means the data is null; the value **false** means the opposite.| **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Value_PutAsset() @@ -2359,9 +2674,9 @@ int OH_Value_PutAsset (OH_Data_Value *value, const Data_Asset *val ) **Description** -Adds data of the ASSET type. +Adds an asset to an **OH_Data_Value** instance. -**Since**: 16 +**Since**: 18 **Parameters** @@ -2373,8 +2688,10 @@ Adds data of the ASSET type. **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Value_PutAssets() @@ -2385,9 +2702,9 @@ int OH_Value_PutAssets (OH_Data_Value *value, const Data_Asset * const * val, si **Description** -Adds data of the ASSETS type. +Adds assets to an **OH_Data_Value** instance. -**Since**: 16 +**Since**: 18 **Parameters** @@ -2395,13 +2712,15 @@ Adds data of the ASSETS type. | -------- | -------- | | value | Pointer to the target [OH_Data_Value](#oh_data_value) instance.| | val | Pointer to the **Data_Asset** object to add.| -| length | Number of elements in the **OH_Asset** object array to add.| +| length | Number of elements in the **Data_Asset** array.| **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Value_PutBlob() @@ -2412,9 +2731,9 @@ int OH_Value_PutBlob (OH_Data_Value *value, const unsigned char *val, size_t len **Description** -Adds data of the BLOB type. +Adds BLOB data to an **OH_Data_Value** instance. -**Since**: 16 +**Since**: 18 **Parameters** @@ -2427,8 +2746,10 @@ Adds data of the BLOB type. **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Value_PutFloatVector() @@ -2439,23 +2760,25 @@ int OH_Value_PutFloatVector (OH_Data_Value *value, const float *val, size_t leng **Description** -Adds data of the floating-point array type. +Adds a float array to an **OH_Data_Value** instance. -**Since**: 16 +**Since**: 18 **Parameters** | Name| Description| | -------- | -------- | | value | Pointer to the target [OH_Data_Value](#oh_data_value) instance.| -| val | Pointer to the floating-point array to add.| -| length | Length of the floating-point array to add.| +| val | Pointer to the float array to add.| +| length | Length of the float array to add.| **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Value_PutInt() @@ -2467,7 +2790,7 @@ int OH_Value_PutInt (OH_Data_Value *value, int64_t val ) Add integer data. -**Since**: 16 +**Since**: 18 **Parameters** @@ -2479,8 +2802,10 @@ Add integer data. **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Value_PutNull() @@ -2491,21 +2816,23 @@ int OH_Value_PutNull (OH_Data_Value *value) **Description** -Adds empty data. +Adds empty data to an **OH_Data_Value** instance. -**Since**: 16 +**Since**: 18 **Parameters** | Name| Description| | -------- | -------- | -| value | Pointer to the [OH_Data_Value](#oh_data_value) instance to destroy.| +| value | Pointer to the target [OH_Data_Value](#oh_data_value) instance.| **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Value_PutReal() @@ -2516,9 +2843,9 @@ int OH_Value_PutReal (OH_Data_Value *value, double val ) **Description** -Adds data of the REAL type. +Adds REAL data to an **OH_Data_Value** instance. -**Since**: 16 +**Since**: 18 **Parameters** @@ -2530,8 +2857,10 @@ Adds data of the REAL type. **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Value_PutText() @@ -2542,9 +2871,9 @@ int OH_Value_PutText (OH_Data_Value *value, const char *val ) **Description** -Adds data of the string type. +Adds a string to an **OH_Data_Value** instance. -**Since**: 16 +**Since**: 18 **Parameters** @@ -2556,8 +2885,10 @@ Adds data of the string type. **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Value_PutUnlimitedInt() @@ -2568,9 +2899,9 @@ int OH_Value_PutUnlimitedInt (OH_Data_Value *value, int sign, const uint64_t *tr **Description** -Adds an integer array of any length. +Adds an integer array of any length to an **OH_Data_Value** instance. -**Since**: 16 +**Since**: 18 **Parameters** @@ -2578,14 +2909,16 @@ Adds an integer array of any length. | -------- | -------- | | value | Pointer to the target [OH_Data_Value](#oh_data_value) instance.| | sign | Sign notation of the integer array to add. The value **0** indicates a positive integer, and the value **1** indicates a negative integer.| -| trueForm | Pointer to the integer array obtained.| -| length | Length of the integer array.| +| trueForm | Pointer to the integer array to add.| +| length | Length of the integer array to add.| **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Values_Count() @@ -2595,22 +2928,24 @@ int OH_Values_Count (OH_Data_Values *values, size_t *count ) **Description** -Obtains the number of values. +Obtains the number of records in an [OH_Data_Values](#oh_data_values) instance. -**Since**: 16 +**Since**: 18 **Parameters** | Name| Description| | -------- | -------- | | values | Pointer to the target [OH_Data_Values](#oh_data_values) instance.| -| count | Pointer to the number of values contained in **values** obtained.| +| count | Pointer to the number of records obtained.| **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Values_Create() @@ -2623,7 +2958,7 @@ OH_Data_Values* OH_Values_Create (void ) Creates an [OH_Data_Values](#oh_data_values) instance to store multiple KV pairs. -**Since**: 16 +**Since**: 18 **Returns** @@ -2644,19 +2979,21 @@ int OH_Values_Destroy (OH_Data_Values *values) Destroys an [OH_Data_Values](#oh_data_values) instance. -**Since**: 16 +**Since**: 18 **Parameters** | Name| Description| | -------- | -------- | -| values | Pointer to the target [OH_Data_Values](#oh_data_values) instance.| +| values | Pointer to the [OH_Data_Values](#oh_data_values) instance to destroy.| **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Values_Get() @@ -2669,7 +3006,7 @@ int OH_Values_Get (OH_Data_Values *values, int index, OH_Data_Value **val ) Obtains data of the **OH_Data_Value** type. -**Since**: 16 +**Since**: 18 **Parameters** @@ -2682,8 +3019,10 @@ Obtains data of the **OH_Data_Value** type. **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Values_GetAsset() @@ -2693,9 +3032,9 @@ int OH_Values_GetAsset (OH_Data_Values *values, int index, Data_Asset *val ) **Description** -Obtains data of the ASSET type. +Obtains the asset from an **OH_Data_Values** instance. -**Since**: 16 +**Since**: 18 **Parameters** @@ -2708,9 +3047,13 @@ Obtains data of the ASSET type. **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. + **RDB_E_DATA_TYPE_NULL** indicates the stored data is empty. + **RDB_E_TYPE_MISMATCH** indicates the data types do not match. @@ -2722,9 +3065,9 @@ int OH_Values_GetAssets (OH_Data_Values *values, int index, Data_Asset **val, si **Description** -Obtains data of the ASSETS type. +Obtains the assets from an **OH_Data_Values** instance. -**Since**: 16 +**Since**: 18 **Parameters** @@ -2732,16 +3075,20 @@ Obtains data of the ASSETS type. | -------- | -------- | | values | Pointer to the target [OH_Data_Values](#oh_data_values) instance.| | index | Index of the value to obtain, which starts from 0 in **values**.| -| val | Pointer to the **Data_Asset** object obtained if the operation is successful. You need to apply for memory for it. This function is used to fill in data only. Otherwise, the operation fails.| +| val | Double pointer to the **Data_Asset** object obtained if the operation is successful. You need to apply for memory for it. This function is used to fill in data only. Otherwise, the operation fails.| | inLen | Size of **val**, which can be obtained by [OH_Values_GetAssetsCount](#oh_values_getassetscount).| -| outLen | Pointer to the actual length of the data obtained.| +| outLen | Pointer to the length of the obtained data.| **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. + **RDB_E_DATA_TYPE_NULL** indicates the stored data is empty. + **RDB_E_TYPE_MISMATCH** indicates the data types do not match. **See** @@ -2757,9 +3104,9 @@ int OH_Values_GetAssetsCount (OH_Data_Values *values, int index, size_t *length **Description** -Obtains the length of ASSETS data. +Obtains the length of the asset in an **OH_Data_Values** instance. -**Since**: 16 +**Since**: 18 **Parameters** @@ -2767,14 +3114,18 @@ Obtains the length of ASSETS data. | -------- | -------- | | values | Pointer to the target [OH_Data_Values](#oh_data_values) instance. Pointer to the target [OH_Data_Values](#oh_data_values) instance.| | index | Index of the value to obtain, which starts from 0 in **values**.| -| length | Pointer to the ASSETS data length obtained.| +| length | Pointer to the length of the ASSETS data obtained.| **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. + **RDB_E_DATA_TYPE_NULL** indicates the stored data is empty. + **RDB_E_TYPE_MISMATCH** indicates the data types do not match. @@ -2786,9 +3137,9 @@ int OH_Values_GetBlob (OH_Data_Values *values, int index, const uint8_t **val, s **Description** -Obtains data of the BLOB type. +Obtains the BLOB data from an **OH_Data_Values** instance. -**Since**: 16 +**Since**: 18 **Parameters** @@ -2797,14 +3148,18 @@ Obtains data of the BLOB type. | values | Pointer to the target [OH_Data_Values](#oh_data_values) instance.| | index | Index of the value to obtain, which starts from 0 in **values**.| | val | Double pointer to the BLOB data obtained. You do not need to apply for or release memory for it. The lifecycle of **val** complies with the value of **index** in **values**.| -| length | Pointer to the length of the BLOB array obtained.| +| length | Pointer to the length of the BLOB data obtained.| **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. + **RDB_E_DATA_TYPE_NULL** indicates the stored data is empty. + **RDB_E_TYPE_MISMATCH** indicates the data types do not match. ### OH_Values_GetFloatVector() @@ -2815,9 +3170,9 @@ int OH_Values_GetFloatVector (OH_Data_Values *values, int index, float *val, siz **Description** -Obtains data of the floating-point array type. +Obtains the float array from an **OH_Data_Values** instance. -**Since**: 16 +**Since**: 18 **Parameters** @@ -2825,16 +3180,20 @@ Obtains data of the floating-point array type. | -------- | -------- | | values | Pointer to the target [OH_Data_Values](#oh_data_values) instance.| | index | Index of the value to obtain, which starts from 0 in **values**.| -| val | Pointer to the floating-point array obtained. You need to apply for memory for it. This function is used to fill in data only. Otherwise, the operation fails.| -| inLen | Size of **val**, which can be obtained by [OH_Values_GetFloatVectorCount](#oh_values_getfloatvectorcount).| -| outLen | Pointer to the actual length of the data obtained.| +| val | Pointer to the float array obtained. You need to apply for memory for it. This function is used to fill in data only. Otherwise, the operation fails.| +| inLen | Size of **val**, which can be obtained by using [OH_Values_GetFloatVectorCount](#oh_values_getfloatvectorcount).| +| outLen | Pointer to the length of the obtained data.| **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. + **RDB_E_DATA_TYPE_NULL** indicates the stored data is empty. + **RDB_E_TYPE_MISMATCH** indicates the data types do not match. **See** @@ -2850,9 +3209,9 @@ int OH_Values_GetFloatVectorCount (OH_Data_Values *values, int index, size_t *le **Description** -Obtains the length of a floating-point array. +Obtains the length of the float array in an **OH_Data_Values** instance. -**Since**: 16 +**Since**: 18 **Parameters** @@ -2860,14 +3219,18 @@ Obtains the length of a floating-point array. | -------- | -------- | | values | Pointer to the target [OH_Data_Values](#oh_data_values) instance.| | index | Index of the value to obtain, which starts from 0 in **values**.| -| length | Pointer to the length of the floating-point array obtained.| +| length | Pointer to the length of the float data obtained.| **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. + **RDB_E_DATA_TYPE_NULL** indicates the stored data is empty. + **RDB_E_TYPE_MISMATCH** indicates the data types do not match. @@ -2879,9 +3242,9 @@ int OH_Values_GetInt (OH_Data_Values *values, int index, int64_t *val ) **Description** -Obtains integer data. +Obtains the integer from an **OH_Data_Values** instance. -**Since**: 16 +**Since**: 18 **Parameters** @@ -2894,9 +3257,13 @@ Obtains integer data. **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. + **RDB_E_DATA_TYPE_NULL** indicates the stored data is empty. + **RDB_E_TYPE_MISMATCH** indicates the data types do not match. ### OH_Values_GetReal() @@ -2907,9 +3274,9 @@ int OH_Values_GetReal (OH_Data_Values *values, int index, double *val ) **Description** -Obtains data of the REAL type. +Obtains the REAL data from an **OH_Data_Values** instance. -**Since**: 16 +**Since**: 18 **Parameters** @@ -2922,9 +3289,13 @@ Obtains data of the REAL type. **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. + **RDB_E_DATA_TYPE_NULL** indicates the stored data is empty. + **RDB_E_TYPE_MISMATCH** indicates the data types do not match. @@ -2936,9 +3307,9 @@ int OH_Values_GetText (OH_Data_Values *values, int index, const char **val ) **Description** -Obtains data of the string type. +Obtains the string from an **OH_Data_Values** instance. -**Since**: 16 +**Since**: 18 **Parameters** @@ -2946,14 +3317,18 @@ Obtains data of the string type. | -------- | -------- | | values | Pointer to the target [OH_Data_Values](#oh_data_values) instance.| | index | Index of the value to obtain, which starts from 0 in **values**.| -| val | Pointer to the string obtained. You do not need to apply for or release memory for it. The lifecycle of **val** complies with the value of **index** in **values**.| +| val | Double pointer to the string obtained. You do not need to apply for or release memory for it. The lifecycle of **val** complies with the value of **index** in **values**.| **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. + **RDB_E_DATA_TYPE_NULL** indicates the stored data is empty. + **RDB_E_TYPE_MISMATCH** indicates the data types do not match. @@ -2967,7 +3342,7 @@ int OH_Values_GetType (OH_Data_Values *values, int index, OH_ColumnType *type ) Obtains the data type. -**Since**: 16 +**Since**: 18 **Parameters** @@ -2980,8 +3355,10 @@ Obtains the data type. **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Values_GetUnlimitedInt() @@ -2992,9 +3369,9 @@ int OH_Values_GetUnlimitedInt (OH_Data_Values *values, int index, int *sign, uin **Description** -Obtains integer data of any length. +Obtains the unlimited integer from an **OH_Data_Values** instance. -**Since**: 16 +**Since**: 18 **Parameters** @@ -3002,17 +3379,21 @@ Obtains integer data of any length. | -------- | -------- | | values | Pointer to the target [OH_Data_Values](#oh_data_values) instance.| | index | Index of the value to obtain, which starts from 0 in **values**.| -| sign | Pointer to the sign notation of the integer obtained. The value **0** indicates a positive integer, and the value **1** indicates a negative integer.| +| sign | Pointer to the sign notation of the data obtained. The value **0** indicates a positive integer, and **1** indicates a negative integer.| | trueForm | Pointer to the integer array obtained. You need to apply for memory for it. This function is used to fill in data only. Otherwise, the operation fails.| -| inLen | **trueForm** length, which can be obtained by [OH_Values_GetUnlimitedIntBand](#oh_values_getunlimitedintband).| -| outLen | Pointer to the actual length of the data obtained.| +| inLen | **trueForm** length, which can be obtained by using [OH_Values_GetUnlimitedIntBand](#oh_values_getunlimitedintband).| +| outLen | Pointer to the length of the obtained data.| **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. + **RDB_E_DATA_TYPE_NULL** indicates the stored data is empty. + **RDB_E_TYPE_MISMATCH** indicates the data types do not match. **See** @@ -3028,9 +3409,9 @@ int OH_Values_GetUnlimitedIntBand (OH_Data_Values *values, int index, size_t *le **Description** -Obtains the length of an unlimited integer. +Obtains the length of the unlimited integer from an **OH_Data_Values** instance. -**Since**: 16 +**Since**: 18 **Parameters** @@ -3038,14 +3419,18 @@ Obtains the length of an unlimited integer. | -------- | -------- | | values | Pointer to the target [OH_Data_Values](#oh_data_values) instance.| | index | Index of the value to obtain, which starts from 0 in **values**.| -| length | Pointer to the length obtained.| +| length | Pointer to the length of the integer obtained.| **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. + **RDB_E_DATA_TYPE_NULL** indicates the stored data is empty. + **RDB_E_TYPE_MISMATCH** indicates the data types do not match. @@ -3059,21 +3444,23 @@ int OH_Values_IsNull (OH_Data_Values *values, int index, bool *val ) Checks whether a value is null. -**Since**: 16 +**Since**: 18 **Parameters** | Name| Description| | -------- | -------- | | values | Pointer to the target [OH_Data_Values](#oh_data_values) instance.| -| index | Index of the value to obtain, which starts from 0 in **values**.| -| val | Pointer to the check result. The value **true** means the value is null, and the value **false** means the opposite.| +| index | Index of the value to check, which starts from 0 in **values**.| +| val | Pointer to a boolean value, which indicates whether the data is null. The value **true** means the data is null; the value **false** means the opposite.| **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Values_Put() @@ -3085,7 +3472,7 @@ int OH_Values_Put (OH_Data_Values *values, const OH_Data_Value *val ) Adds data of the **OH_Data_Value** type to an **OH_Data_Values** instance. -**Since**: 16 +**Since**: 18 **Parameters** @@ -3097,8 +3484,10 @@ Adds data of the **OH_Data_Value** type to an **OH_Data_Values** instance. **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Values_PutAsset() @@ -3109,9 +3498,9 @@ int OH_Values_PutAsset (OH_Data_Values *values, const Data_Asset *val ) **Description** -Adds data of the ASSET type to an **OH_Data_Values** instance. +Adds an asset to an **OH_Data_Values** instance. -**Since**: 16 +**Since**: 18 **Parameters** @@ -3123,8 +3512,10 @@ Adds data of the ASSET type to an **OH_Data_Values** instance. **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Values_PutAssets() @@ -3135,9 +3526,9 @@ int OH_Values_PutAssets (OH_Data_Values *values, const Data_Asset * const * val, **Description** -Adds data of the ASSETS type to an **OH_Data_Values** instance. +Adds assets to an **OH_Data_Values** instance. -**Since**: 16 +**Since**: 18 **Parameters** @@ -3145,13 +3536,15 @@ Adds data of the ASSETS type to an **OH_Data_Values** instance. | -------- | -------- | | values | Pointer to the target [OH_Data_Values](#oh_data_values) instance.| | val | Pointer to the **Data_Asset** object to add.| -| length | Number of elements in the **OH_Asset** object to add.| +| length | Number of elements in the **Data_Asset** object to add.| **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Values_PutBlob() @@ -3162,9 +3555,9 @@ int OH_Values_PutBlob (OH_Data_Values *values, const unsigned char *val, size_t **Description** -Adds data of the BLOB type to an **OH_Data_Values** instance. +Adds BLOB data to an **OH_Data_Values** instance. -**Since**: 16 +**Since**: 18 **Parameters** @@ -3177,8 +3570,10 @@ Adds data of the BLOB type to an **OH_Data_Values** instance. **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Values_PutFloatVector() @@ -3189,23 +3584,25 @@ int OH_Values_PutFloatVector (OH_Data_Values *values, const float *val, size_t l **Description** -Adds data of the floating-point array type to an **OH_Data_Values** instance. +Adds a float array to an **OH_Data_Values** instance. -**Since**: 16 +**Since**: 18 **Parameters** | Name| Description| | -------- | -------- | | values | Pointer to the target [OH_Data_Values](#oh_data_values) instance.| -| val | Pointer to the floating-point array to add.| -| length | Length of the floating-point array to add.| +| val | Pointer to the float array to add.| +| length | Length of the float array to add.| **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Values_PutInt() @@ -3216,22 +3613,24 @@ int OH_Values_PutInt (OH_Data_Values *values, int64_t val ) **Description** -Adds integer data to an **OH_Data_Values** instance. +Adds an integer to an **OH_Data_Values** instance. -**Since**: 16 +**Since**: 18 **Parameters** | Name| Description| | -------- | -------- | | values | Pointer to the target [OH_Data_Values](#oh_data_values) instance.| -| val | Pointer to the integer data to add.| +| val | Pointer to the integer to add.| **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Values_PutNull() @@ -3244,7 +3643,7 @@ int OH_Values_PutNull (OH_Data_Values *values) Adds empty data to an **OH_Data_Values** instance. -**Since**: 16 +**Since**: 18 **Parameters** @@ -3255,8 +3654,10 @@ Adds empty data to an **OH_Data_Values** instance. **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Values_PutReal() @@ -3267,9 +3668,9 @@ int OH_Values_PutReal (OH_Data_Values *values, double val ) **Description** -Adds data of the REAL type to an **OH_Data_Values** instance. +Adds REAL data to an **OH_Data_Values** instance. -**Since**: 16 +**Since**: 18 **Parameters** @@ -3281,8 +3682,10 @@ Adds data of the REAL type to an **OH_Data_Values** instance. **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Values_PutText() @@ -3293,9 +3696,9 @@ int OH_Values_PutText (OH_Data_Values *values, const char *val ) **Description** -Adds data of the string type to an **OH_Data_Values** instance. +Adds a string to an **OH_Data_Values** instance. -**Since**: 16 +**Since**: 18 **Parameters** @@ -3307,8 +3710,10 @@ Adds data of the string type to an **OH_Data_Values** instance. **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Values_PutUnlimitedInt() @@ -3321,7 +3726,7 @@ int OH_Values_PutUnlimitedInt (OH_Data_Values *values, int sign, const uint64_t Adds an integer array of any length to an **OH_Data_Values** instance. -**Since**: 16 +**Since**: 18 **Parameters** @@ -3335,8 +3740,10 @@ Adds an integer array of any length to an **OH_Data_Values** instance. **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_VBucket_PutFloatVector() @@ -3346,9 +3753,9 @@ int OH_VBucket_PutFloatVector (OH_VBucket *bucket, const char *field, const floa **Description** -Puts a floating-point array into an [OH_VBucket](_o_h___v_bucket.md) object in the given column. +Puts a float array into an [OH_VBucket](_o_h___v_bucket.md) object in the given column. -**Since**: 16 +**Since**: 18 **Parameters** @@ -3356,13 +3763,16 @@ Puts a floating-point array into an [OH_VBucket](_o_h___v_bucket.md) object in t | -------- | -------- | | bucket | Pointer to the [OH_VBucket](_o_h___v_bucket.md) instance.| | field | Pointer to the column name in the database table.| -| vec | Pointer to the floating-point array to put.| -| len | Length of the floating-point array to put.| +| vec | Pointer to the float array to put.| +| len | Length of the float array to put.| **Returns** Returns **RDB_OK** if the operation is successful; returns an error code otherwise. -**RDB_OK** indicates the operation is successful.
**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. **See** @@ -3379,7 +3789,7 @@ int OH_VBucket_PutUnlimitedInt (OH_VBucket *bucket, const char *field, int sign, Puts an integer of any length into an [OH_VBucket](_o_h___v_bucket.md) object in the given column. -**Since**: 16 +**Since**: 18 **Parameters** @@ -3394,8 +3804,10 @@ Puts an integer of any length into an [OH_VBucket](_o_h___v_bucket.md) object in **Returns** Returns **RDB_OK** if the operation is successful; returns an error code otherwise. -**RDB_OK** indicates the operation is successful. -
**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. **See** @@ -3410,9 +3822,9 @@ OH_Data_VBuckets* OH_VBuckets_Create (void) **Description** -Create an **OH_Data_VBuckets** instance. +Creates an **OH_Data_VBuckets** instance. -**Since**: 16 +**Since**: 18 **Returns** @@ -3433,7 +3845,7 @@ int OH_VBuckets_Destroy (OH_Data_VBuckets *buckets) Destroys an **OH_Data_VBuckets** instance. -**Since**: 16 +**Since**: 18 **Parameters** @@ -3444,8 +3856,10 @@ Destroys an **OH_Data_VBuckets** instance. **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_VBuckets_PutRow() @@ -3458,7 +3872,7 @@ int OH_VBuckets_PutRow (OH_Data_VBuckets *buckets, const OH_VBucket *row ) Adds data of the **OH_VBucket** type. -**Since**: 16 +**Since**: 18 **Parameters** @@ -3470,8 +3884,10 @@ Adds data of the **OH_VBucket** type. **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_VBuckets_PutRows() @@ -3484,7 +3900,7 @@ int OH_VBuckets_PutRows (OH_Data_VBuckets *buckets, const OH_Data_VBuckets *rows Adds data of the **OH_Data_VBuckets** type. -**Since**: 16 +**Since**: 18 **Parameters** @@ -3496,8 +3912,10 @@ Adds data of the **OH_Data_VBuckets** type. **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_VBuckets_RowCount() @@ -3508,22 +3926,24 @@ int OH_VBuckets_RowCount (OH_Data_VBuckets *buckets, size_t *count ) **Description** -Obtains the number of rows in **OH_VBucket** in **OH_Data_VBuckets**. +Obtains the number of **OH_VBuckets** in **OH_Data_VBuckets**. -**Since**: 16 +**Since**: 18 **Parameters** | Name| Description| | -------- | -------- | | buckets | Pointer to the target [OH_Data_VBuckets](#oh_data_vbuckets) instance.| -| count | Pointer to the number of [OH_VBucket](_o_h___v_bucket.md)s contained in [OH_Data_VBuckets](#oh_data_vbuckets) obtained.| +| count | Pointer to the number of [OH_VBuckets](_o_h___v_bucket.md) in [OH_Data_VBuckets](#oh_data_vbuckets) obtained.| **Returns** Returns the operation status code. -**RDB_OK** indicates the operation is successful. -**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Rdb_CreateOrOpen() @@ -3542,7 +3962,7 @@ Creates or opens an [OH_Rdb_Store](_o_h___rdb___store.md) instance based on the | Name| Description| | -------- | -------- | | config | Pointer to the [OH_Rdb_ConfigV2](#oh_rdb_configv2) instance, which is the configuration of the RDB store.| -| errCode | Pointer to the execution result of this API. **RDB_OK** indicates the operation is successful. **RDB_E_INVALID_ARGS** indicates invalid parameters are specified.| +| errCode | Pointer to the execution result of this API. **RDB_OK** indicates that the operation is successful.
**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified.| **Returns** @@ -3561,7 +3981,7 @@ int OH_Rdb_BeginTransWithTrxId (OH_Rdb_Store *store, int64_t *trxId ) **Description** -Begins a transaction and obtains the transaction ID before executing an SQL statement. This API supports vector stores. +Begins a transaction. This API returns a transaction ID. This API supports only vector stores. **Since**: 14 @@ -3570,11 +3990,17 @@ Begins a transaction and obtains the transaction ID before executing an SQL stat | Name| Description| | -------- | -------- | | store | Pointer to the [OH_Rdb_Store](_o_h___rdb___store.md) instance.| -| trxId | Pointer to the transaction ID obtained.| +| trxId | Pointer to the transaction ID returned.| **Returns** -Returns **RDB_OK** if the operation is successful; returns an error code otherwise. **RDB_OK** indicates the operation is successful.
**RDB_E_INVALID_ARGS** indicates invalid parameters are specified.
**RDB_E_NOT_SUPPORTED** indicates that the current operation is not supported. +Returns **RDB_OK** if the operation is successful; returns an error code otherwise. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. + +**RDB_E_NOT_SUPPORTED** indicates that the current operation is not supported. **See** @@ -3589,7 +4015,7 @@ int OH_Rdb_CommitByTrxId (OH_Rdb_Store *store, int64_t trxId ) **Description** -Commits the executed SQL statement based on the specified transaction ID. This API supports vector stores. +Commits the executed SQL statements based on the specified transaction ID. This API supports only vector stores. **Since**: 14 @@ -3602,7 +4028,13 @@ Commits the executed SQL statement based on the specified transaction ID. This A **Returns** -Returns **RDB_OK** if the operation is successful; returns an error code otherwise.
**RDB_OK** indicates the operation is successful.
**RDB_E_INVALID_ARGS** indicates invalid parameters are specified.
Possible causes: A null pointer is passed in; the transaction ID is not obtained by [OH_Rdb_BeginTransWithTrxId](#oh_rdb_begintranswithtrxid); the transaction ID has been used by [OH_Rdb_CommitByTrxId](#oh_rdb_commitbytrxid); the transaction ID has been used by [OH_Rdb_RollBackByTrxId](#oh_rdb_rollbackbytrxid).
**RDB_E_NOT_SUPPORTED** indicates that the current operation is not supported. +Returns **RDB_OK** if the operation is successful; returns an error code otherwise. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates invalid parameters are specified.
Possible causes: A null pointer is passed in; the transaction ID is not obtained by [OH_Rdb_BeginTransWithTrxId](#oh_rdb_begintranswithtrxid); the transaction ID has been used by [OH_Rdb_CommitByTrxId](#oh_rdb_commitbytrxid); the transaction ID has been used by [OH_Rdb_RollBackByTrxId](#oh_rdb_rollbackbytrxid). + +**RDB_E_NOT_SUPPORTED** indicates that the current operation is not supported. **See** @@ -3639,7 +4071,7 @@ int OH_Rdb_DeleteStoreV2 (const OH_Rdb_ConfigV2 *config) **Description** -Deletes an RDB store based on the given [OH_Rdb_ConfigV2](#oh_rdb_configv2). If a vector store is used, ensure that the vector store has been correctly closed before calling the API. +Deletes an RDB store based on the given [OH_Rdb_ConfigV2](#oh_rdb_configv2). For a vector store, ensure that the vector store is correctly closed before calling this API. **Since**: 14 @@ -3651,7 +4083,11 @@ Deletes an RDB store based on the given [OH_Rdb_ConfigV2](#oh_rdb_configv2). If **Returns** -Returns **RDB_OK** if the operation is successful; returns an error code otherwise. **RDB_OK** indicates the operation is successful.
**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. +Returns **RDB_OK** if the operation is successful; returns an error code otherwise. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. **See** @@ -3678,7 +4114,11 @@ Destroys an [OH_Rdb_ConfigV2](#oh_rdb_configv2) instance. **Returns** -Returns **RDB_OK** if the operation is successful; returns an error code otherwise. **RDB_OK** indicates the operation is successful.
**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. +Returns **RDB_OK** if the operation is successful; returns an error code otherwise. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Rdb_ExecuteByTrxId() @@ -3689,7 +4129,7 @@ int OH_Rdb_ExecuteByTrxId (OH_Rdb_Store *store, int64_t trxId, const char *sql ) **Description** -Executes an SQL statement that returns no value based on the specified transaction ID. +Executes an SQL statement that returns no value based on the specified transaction ID. This API supports only vector stores. **Since**: 14 @@ -3703,7 +4143,13 @@ Executes an SQL statement that returns no value based on the specified transacti **Returns** -Returns **RDB_OK** if the operation is successful; returns an error code otherwise. **RDB_OK** indicates the operation is successful.
**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. Possible causes: A null pointer is passed in; the transaction ID is not obtained by [OH_Rdb_BeginTransWithTrxId](#oh_rdb_begintranswithtrxid); the transaction ID has been used by [OH_Rdb_CommitByTrxId](#oh_rdb_commitbytrxid); the transaction ID has been used by [OH_Rdb_RollBackByTrxId](#oh_rdb_rollbackbytrxid); **store** or **sql** is **NULL**.
**RDB_E_NOT_SUPPORTED** indicates that the current operation is not supported. +Returns **RDB_OK** if the operation is successful; returns an error code otherwise. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates invalid parameters are specified.
Possible causes: A null pointer is passed in; the transaction ID is not obtained by [OH_Rdb_BeginTransWithTrxId](#oh_rdb_begintranswithtrxid); the transaction ID has been used by [OH_Rdb_CommitByTrxId](#oh_rdb_commitbytrxid); the transaction ID has been used by [OH_Rdb_RollBackByTrxId](#oh_rdb_rollbackbytrxid); **store** or **sql** is **NULL**. + +**RDB_E_NOT_SUPPORTED** indicates that the current operation is not supported. **See** @@ -3730,7 +4176,11 @@ Obtains the supported database types. **Returns** -Returns **RDB_OK** if the operation is successful; returns an error code otherwise. **RDB_OK** indicates the operation is successful.
**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. +Returns **RDB_OK** if the operation is successful; returns an error code otherwise. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Rdb_RollBackByTrxId() @@ -3741,7 +4191,7 @@ int OH_Rdb_RollBackByTrxId (OH_Rdb_Store *store, int64_t trxId ) **Description** -Rolls back the executed SQL statement based on the specified transaction ID. This API supports vector stores. +Rolls back the executed SQL statements based on the specified transaction ID. This API supports only vector stores. **Since**: 14 @@ -3754,7 +4204,13 @@ Rolls back the executed SQL statement based on the specified transaction ID. Thi **Returns** -Returns **RDB_OK** if the operation is successful; returns an error code otherwise. **RDB_OK** indicates the operation is successful.
**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. Possible causes: A null pointer is passed in; the transaction ID is not obtained by [OH_Rdb_BeginTransWithTrxId](#oh_rdb_begintranswithtrxid); the transaction ID has been used by [OH_Rdb_CommitByTrxId](#oh_rdb_commitbytrxid); the transaction ID has been used by [OH_Rdb_RollBackByTrxId](#oh_rdb_rollbackbytrxid).
**RDB_E_NOT_SUPPORTED** indicates that the current operation is not supported. +Returns **RDB_OK** if the operation is successful; returns an error code otherwise. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates invalid parameters are specified.
Possible causes: A null pointer is passed in; the transaction ID is not obtained by [OH_Rdb_BeginTransWithTrxId](#oh_rdb_begintranswithtrxid); the transaction ID has been used by [OH_Rdb_CommitByTrxId](#oh_rdb_commitbytrxid); the transaction ID has been used by [OH_Rdb_RollBackByTrxId](#oh_rdb_rollbackbytrxid). + +**RDB_E_NOT_SUPPORTED** indicates that the current operation is not supported. **See** @@ -3769,7 +4225,7 @@ int OH_Rdb_SetArea (OH_Rdb_ConfigV2 *config, int area ) **Description** -Sets the security area level ([Rdb_SecurityArea](#rdb_securityarea)) for an [OH_Rdb_ConfigV2](#oh_rdb_configv2) instance. +Sets the [Rdb_SecurityArea](#rdb_securityarea) for an [OH_Rdb_ConfigV2](#oh_rdb_configv2) instance. **Since**: 14 @@ -3778,11 +4234,15 @@ Sets the security area level ([Rdb_SecurityArea](#rdb_securityarea)) for an [OH_ | Name| Description| | -------- | -------- | | config | Pointer to the [OH_Rdb_ConfigV2](#oh_rdb_configv2) instance, which is the configuration of the RDB store.| -| area | Security area level to set. For details, see [Rdb_SecurityArea](#rdb_securityarea).| +| area | Database file encryption level to set. For details, see [Rdb_SecurityArea](#rdb_securityarea).| **Returns** -Returns **RDB_OK** if the operation is successful; returns an error code otherwise. **RDB_OK** indicates the operation is successful.
**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. +Returns **RDB_OK** if the operation is successful; returns an error code otherwise. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Rdb_SetBundleName() @@ -3806,7 +4266,11 @@ Sets the application bundle name for an [OH_Rdb_ConfigV2](#oh_rdb_configv2) inst **Returns** -Returns **RDB_OK** if the operation is successful; returns an error code otherwise. **RDB_OK** indicates the operation is successful.
**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. +Returns **RDB_OK** if the operation is successful; returns an error code otherwise. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Rdb_SetDatabaseDir() @@ -3830,7 +4294,11 @@ Sets the database file path for an [OH_Rdb_ConfigV2](#oh_rdb_configv2) instance. **Returns** -Returns **RDB_OK** if the operation is successful; returns an error code otherwise. **RDB_OK** indicates the operation is successful.
**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. +Returns **RDB_OK** if the operation is successful; returns an error code otherwise. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Rdb_SetDbType() @@ -3841,7 +4309,7 @@ int OH_Rdb_SetDbType (OH_Rdb_ConfigV2 *config, int dbType ) **Description** -Sets the database type ([Rdb_DBType](#rdb_dbtype)) for an [OH_Rdb_ConfigV2](#oh_rdb_configv2) instance. +Sets the [Rdb_DBType](#rdb_dbtype) for an [OH_Rdb_ConfigV2](#oh_rdb_configv2) instance. **Since**: 14 @@ -3854,7 +4322,13 @@ Sets the database type ([Rdb_DBType](#rdb_dbtype)) for an [OH_Rdb_ConfigV2](#oh_ **Returns** -Returns **RDB_OK** if the operation is successful; returns an error code otherwise. **RDB_OK** indicates the operation is successful.
**RDB_E_INVALID_ARGS** indicates invalid parameters are specified.
**RDB_E_NOT_SUPPORTED** indicates that the current operation is not supported. +Returns **RDB_OK** if the operation is successful; returns an error code otherwise. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. + +**RDB_E_NOT_SUPPORTED** indicates that the current operation is not supported. ### OH_Rdb_SetEncrypted() @@ -3878,7 +4352,11 @@ Sets whether to encrypt the RDB store for an [OH_Rdb_ConfigV2](#oh_rdb_configv2) **Returns** -Returns **RDB_OK** if the operation is successful; returns an error code otherwise. **RDB_OK** indicates the operation is successful.
**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. +Returns **RDB_OK** if the operation is successful; returns an error code otherwise. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Rdb_SetModuleName() @@ -3902,7 +4380,11 @@ Sets the module name for an [OH_Rdb_ConfigV2](#oh_rdb_configv2) instance. **Returns** -Returns **RDB_OK** if the operation is successful; returns an error code otherwise. **RDB_OK** indicates the operation is successful.
**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. +Returns **RDB_OK** if the operation is successful; returns an error code otherwise. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Rdb_SetSecurityLevel() @@ -3913,7 +4395,7 @@ int OH_Rdb_SetSecurityLevel (OH_Rdb_ConfigV2 *config, int securityLevel ) **Description** -Sets the RDB store security level ([OH_Rdb_SecurityLevel](#oh_rdb_securitylevel)) for an [OH_Rdb_ConfigV2](#oh_rdb_configv2) instance. +Sets the [OH_Rdb_SecurityLevel](#oh_rdb_securitylevel) for an [OH_Rdb_ConfigV2](#oh_rdb_configv2) instance. **Since**: 14 @@ -3926,7 +4408,11 @@ Sets the RDB store security level ([OH_Rdb_SecurityLevel](#oh_rdb_securitylevel) **Returns** -Returns **RDB_OK** if the operation is successful; returns an error code otherwise. **RDB_OK** indicates the operation is successful.
**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. +Returns **RDB_OK** if the operation is successful; returns an error code otherwise. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Rdb_SetStoreName() @@ -3950,7 +4436,11 @@ Sets the RDB store name for an [OH_Rdb_ConfigV2](#oh_rdb_configv2) instance. **Returns** -Returns **RDB_OK** if the operation is successful; returns an error code otherwise. **RDB_OK** indicates the operation is successful.
**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. +Returns **RDB_OK** if the operation is successful; returns an error code otherwise. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. ### OH_Rdb_Backup() @@ -3969,11 +4459,15 @@ Backs up an RDB store using the backup file of the specified path. This API supp | Name| Description| | -------- | -------- | | store | Pointer to the [OH_Rdb_Store](_o_h___rdb___store.md) instance.| -| databasePath | Pointer to the destination directory in which the RDB store is backed up.| +| databasePath | Pointer to the destination directory, in which the RDB store is backed up.| **Returns** -Returns **RDB_OK** if the operation is successful; returns an error code otherwise. **RDB_OK** indicates the operation is successful.
**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. +Returns **RDB_OK** if the operation is successful; returns an error code otherwise. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. **See** @@ -3988,7 +4482,7 @@ int OH_Rdb_BeginTransaction (OH_Rdb_Store *store) **Description** -Starts the transaction before executing the SQL statement. +Begins the transaction before executing SQL statements. **Since**: 10 @@ -4000,7 +4494,11 @@ Starts the transaction before executing the SQL statement. **Returns** -Returns **RDB_OK** if the operation is successful; returns an error code otherwise. **RDB_OK** indicates the operation is successful.
**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. +Returns **RDB_OK** if the operation is successful; returns an error code otherwise. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. **See** @@ -4023,11 +4521,15 @@ Closes an [OH_Rdb_Store](_o_h___rdb___store.md) object to reclaim the memory occ | Name| Description| | -------- | -------- | -| store | Pointer to the [OH_Rdb_Store](_o_h___rdb___store.md) instance.| +| store | Pointer to the [OH_Rdb_Store](_o_h___rdb___store.md) instance to close.| **Returns** -Returns **RDB_OK** if the operation is successful; returns an error code otherwise. **RDB_OK** indicates the operation is successful.
**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. +Returns **RDB_OK** if the operation is successful; returns an error code otherwise. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. **See** @@ -4052,13 +4554,17 @@ Performs device-cloud sync. | -------- | -------- | | store | Pointer to the [OH_Rdb_Store](_o_h___rdb___store.md) instance.| | mode | Sync mode [Rdb_SyncMode](#rdb_syncmode).| -| tables | Pointer to the names of the tables to be synced.| +| tables | Pointer to the tables to sync.| | count | Number of tables to sync. If the value is **0**, all tables in the RDB store are synced.| -| observer | Observer [Rdb_ProgressObserver](_rdb___progress_observer.md) of the device-cloud sync progress.| +| observer | [Rdb_ProgressObserver](_rdb___progress_observer.md) of the device-cloud sync progress.| **Returns** -Returns **RDB_OK** if the operation is successful; returns an error code otherwise. **RDB_OK** indicates the operation is successful.
**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. +Returns **RDB_OK** if the operation is successful; returns an error code otherwise. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. **See** @@ -4073,7 +4579,7 @@ int OH_Rdb_Commit (OH_Rdb_Store *store) **Description** -Commits the executed SQL statement. +Commits the executed SQL statements. **Since**: 10 @@ -4085,7 +4591,11 @@ Commits the executed SQL statement. **Returns** -Returns **RDB_OK** if the operation is successful; returns an error code otherwise. **RDB_OK** indicates the operation is successful.
**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. +Returns **RDB_OK** if the operation is successful; returns an error code otherwise. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. **See** @@ -4220,7 +4730,7 @@ int OH_Rdb_Execute (OH_Rdb_Store *store, const char *sql ) **Description** -Executes an SQL statement but returns no value. +Executes an SQL statement that returns no value. **Since**: 10 @@ -4233,7 +4743,11 @@ Executes an SQL statement but returns no value. **Returns** -Returns **RDB_OK** if the operation is successful; returns an error code otherwise. **RDB_OK** indicates the operation is successful.
**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. +Returns **RDB_OK** if the operation is successful; returns an error code otherwise. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. **See** @@ -4458,7 +4972,7 @@ Queries data in an RDB store based on specified conditions. | store | Pointer to the [OH_Rdb_Store](_o_h___rdb___store.md) instance.| | predicates | Pointer to the [OH_Predicates](_o_h___predicates.md) instance, which specifies the query conditions.| | columnNames | Pointer to the columns to query. If this parameter is not specified, data of columns will be queried.| -| length | Length of the **columnNames** array. If length is greater than the length of columnNames array, out-of-bounds access occurs.| +| length | Length of **columnNames**. If length is greater than the length of columnNames array, out-of-bounds access occurs.| **Returns** @@ -4487,7 +5001,7 @@ Queries the locked data in an RDB store. | store | Pointer to the [OH_Rdb_Store](_o_h___rdb___store.md) instance.| | predicates | Pointer to the [OH_Predicates](_o_h___predicates.md) instance, which specifies the query conditions.| | columnNames | Pointer to the columns to query. If this parameter is not specified, data of columns will be queried.| -| length | Length of the **columnNames** array. If length is greater than the length of columnNames array, out-of-bounds access occurs.| +| length | Length of **columnNames**. If length is greater than the length of columnNames array, out-of-bounds access occurs.| **Returns** @@ -4518,7 +5032,11 @@ Restores a database from a specified database backup file. This API supports vec **Returns** -Returns **RDB_OK** if the operation is successful; returns an error code otherwise. **RDB_OK** indicates the operation is successful.
**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. +Returns **RDB_OK** if the operation is successful; returns an error code otherwise. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. **See** @@ -4533,7 +5051,7 @@ int OH_Rdb_RollBack (OH_Rdb_Store *store) **Description** -Rolls back the SQL statement executed. +Rolls back the SQL statements executed. **Since**: 10 @@ -4545,7 +5063,11 @@ Rolls back the SQL statement executed. **Returns** -Returns **RDB_OK** if the operation is successful; returns an error code otherwise. **RDB_OK** indicates the operation is successful.
**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. +Returns **RDB_OK** if the operation is successful; returns an error code otherwise. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. **See** @@ -4570,13 +5092,17 @@ Sets distributed database tables. | -------- | -------- | | store | Pointer to the [OH_Rdb_Store](_o_h___rdb___store.md) instance.| | tables | Pointer to the names of the distributed tables to set.| -| count | Number of distributed database tables to be set.| +| count | Number of distributed database tables to set.| | type | [Rdb_DistributedType](#rdb_distributedtype).| | config | Configuration of the distributed mode. For details, see [Rdb_DistributedConfig](_rdb___distributed_config.md).| **Returns** -Returns **RDB_OK** if the operation is successful; returns an error code otherwise. **RDB_OK** indicates the operation is successful.
**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. +Returns **RDB_OK** if the operation is successful; returns an error code otherwise. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. **See** @@ -4604,7 +5130,11 @@ Sets the RDB store version. **Returns** -Returns **RDB_OK** if the operation is successful; returns an error code otherwise. **RDB_OK** indicates the operation is successful.
**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. +Returns **RDB_OK** if the operation is successful; returns an error code otherwise. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. **See** @@ -4633,7 +5163,11 @@ Registers an observer for an RDB store. When data in the RDB store changes, a ca **Returns** -Returns **RDB_OK** if the operation is successful; returns an error code otherwise. **RDB_OK** indicates the operation is successful.
**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. +Returns **RDB_OK** if the operation is successful; returns an error code otherwise. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. **See** @@ -4650,7 +5184,7 @@ int OH_Rdb_SubscribeAutoSyncProgress (OH_Rdb_Store *store, const Rdb_ProgressObs **Description** -Subscribes to the automatic sync progress of an RDB store. The registered callback will be invoked to return the automatic sync progress. **RDB_OK** indicates the operation is successful.
**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. +Subscribes to the auto sync progress of an RDB store. The registered callback will be invoked to return the auto sync progress. **RDB_OK** indicates that the operation is successful.
**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. **Since**: 11 @@ -4716,11 +5250,15 @@ Unregisters the observer of the specified type. | -------- | -------- | | store | Pointer to the [OH_Rdb_Store](_o_h___rdb___store.md) instance.| | type | Subscription type defined in [Rdb_SubscribeType](#rdb_subscribetype).| -| observer | Pointer to the [Rdb_DataObserver](_rdb___data_observer.md) instance. If this parameter is **nullptr**, all observers of this type will be unregistered.| +| observer | Pointer to the [Rdb_DataObserver](_rdb___data_observer.md) instance to unregister. If this parameter is **nullptr**, all observers of this type will be unregistered.| **Returns** -Returns **RDB_OK** if the operation is successful; returns an error code otherwise. **RDB_OK** indicates the operation is successful.
**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. +Returns **RDB_OK** if the operation is successful; returns an error code otherwise. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. **See** @@ -4737,7 +5275,7 @@ int OH_Rdb_UnsubscribeAutoSyncProgress (OH_Rdb_Store *store, const Rdb_ProgressO **Description** -Unsubscribes from the automatic sync process of an RDB store. +Unsubscribes from the auto sync process of an RDB store. **Since**: 11 @@ -4746,11 +5284,15 @@ Unsubscribes from the automatic sync process of an RDB store. | Name| Description| | -------- | -------- | | store | Pointer to the target [OH_Rdb_Store](_o_h___rdb___store.md) instance.| -| observer | Pointer to [Rdb_ProgressObserver](_rdb___progress_observer.md). If the pointer is null, all callbacks for the automatic sync process will be unregistered.| +| observer | Pointer to [Rdb_ProgressObserver](_rdb___progress_observer.md) to unregister. If the pointer is null, all callbacks for the auto sync process will be unregistered.| **Returns** -Returns **RDB_OK** if the operation is successful; returns an error code otherwise. **RDB_OK** indicates the operation is successful.
**RDB_E_INVALID_ARGS** indicates invalid parameters are specified. +Returns **RDB_OK** if the operation is successful; returns an error code otherwise. + +**RDB_OK** indicates that the operation is successful. + +**RDB_E_INVALID_ARGS** indicates that invalid parameters are specified. **See** @@ -4776,7 +5318,7 @@ Updates data in an RDB store based on specified conditions. | Name| Description| | -------- | -------- | | store | Pointer to the [OH_Rdb_Store](_o_h___rdb___store.md) instance.| -| valuesBucket | Pointer to the new data [OH_VBucket](_o_h___v_bucket.md) to be updated to the table.| +| valuesBucket | Pointer to the new [OH_VBucket](_o_h___v_bucket.md) to be inserted to the table.| | predicates | Pointer to the [OH_Predicates](_o_h___predicates.md) instance, specifying the update conditions.| **Returns** @@ -4796,7 +5338,7 @@ int OH_VBucket_PutAsset (OH_VBucket *bucket, const char *field, OH_Asset *value **Description** -Puts an **OH_Asset** object into an [OH_VBucket](_o_h___v_bucket.md) object with the given column name. +Puts an **OH_Asset** object into the [OH_VBucket](_o_h___v_bucket.md) object in the given column. **Since**: 11 @@ -4806,7 +5348,7 @@ Puts an **OH_Asset** object into an [OH_VBucket](_o_h___v_bucket.md) object with | -------- | -------- | | bucket | Pointer to the [OH_VBucket](_o_h___v_bucket.md) instance.| | field | Pointer to the column name in the database table.| -| value | Pointer to the value to put.| +| value | Pointer to the data to put.| **Returns** @@ -4825,7 +5367,7 @@ int OH_VBucket_PutAssets (OH_VBucket *bucket, const char *field, OH_Asset **valu **Description** -Puts an array of **OH_Asset** objects into an [OH_VBucket](_o_h___v_bucket.md) object with the given column name. +Puts an array of **OH_Asset** objects into the [OH_VBucket](_o_h___v_bucket.md) object in the given column. **Since**: 11 @@ -4835,8 +5377,8 @@ Puts an array of **OH_Asset** objects into an [OH_VBucket](_o_h___v_bucket.md) o | -------- | -------- | | bucket | Pointer to the [OH_VBucket](_o_h___v_bucket.md) instance.| | field | Pointer to the column name in the database table.| -| value | Pointer to the value to put.| -| count | Number of elements in the **OH_Asset** object array.| +| value | Double pointer to the data to put.| +| count | Number of elements in the **OH_Asset** array.| **Returns** @@ -4928,7 +5470,7 @@ OH_Predicates *(*between) (OH_Predicates *predicates, const char *field, OH_VObj **Description** -Pointer to the function used to set a predicates object to match the field whose value is within the specified range. +Pointer to the function used to create a predicates object to search for the field values that are within the specified range. This method is equivalent to **BETWEEN** in SQL statements. @@ -5037,7 +5579,7 @@ Pointer to the function used to clear a predicates instance. **Returns** -Returns the cleared predicates. +Cleared predicates. **See** @@ -5134,7 +5676,7 @@ Rdb_KeyInfo Rdb_ChangeInfo::deleted **Description** -Location where data is deleted. If the primary key of the table is of the string type, the value is the value of the primary key. Otherwise, the value is the row number of the deleted data. +Location where data is deleted. If the primary key of the table is of the string type, it is the value of the primary key. Otherwise, the value is the row number of the deleted data. ### destroy [1/4] @@ -5264,7 +5806,7 @@ OH_Predicates *(*distinct) (OH_Predicates *predicates) **Description** -Pointer to the function used to set a predicates object to filter out duplicate records. +Pointer to the function used to create a predicates object to filter out duplicate records. This method is equivalent to **DISTINCT** in SQL statements. @@ -5333,7 +5875,7 @@ OH_Predicates *(*equalTo) (OH_Predicates *predicates, const char *field, OH_VObj **Description** -Pointer to the function used to set a predicates object to match the field whose value is equal to the specified value. +Pointer to the function used to create a predicates object to search for the field values that are equal to the specified value. This method is equivalent to "=" in SQL statements. @@ -5384,7 +5926,7 @@ Pointer to the function used to obtain the value of the asset type based on the | Name| Description| | -------- | -------- | | cursor | Pointer to the [OH_Cursor](_o_h___cursor.md) instance.| -| columnIndex | Index of the column. The index value starts from **0**.| +| columnIndex | Index of the column, which starts from **0**.| | value | Pointer to the value obtained.| **Returns** @@ -5413,9 +5955,9 @@ Pointer to the function used to obtain the values in the form of an asset array | Name| Description| | -------- | -------- | | cursor | Pointer to the [OH_Cursor](_o_h___cursor.md) instance.| -| columnIndex | Index of the column. The index value starts from **0**.| -| value | Pointer to the value obtained.| -| length | Length of an asset array.| +| columnIndex | Index of the column, which starts from **0**.| +| value | Double pointer to the value obtained.| +| length | Length of the buffer, which is a variable of the uint32_t type passed in. After the API is executed, the variable is updated to the length of the returned asset array.| **Returns** @@ -5443,9 +5985,9 @@ Pointer to the function used to obtain the values in the form of a byte array ba | Name| Description| | -------- | -------- | | cursor | Pointer to the [OH_Cursor](_o_h___cursor.md) instance.| -| columnIndex | Index of the column. The index value starts from **0**.| +| columnIndex | Index of the column, which starts from **0**.| | value | Pointer to the values in the form of a byte array obtained.| -| length | Length of the value, which can be obtained by **getSize()**.| +| length | Length of **value**, obtained by using **getSize**.| **Returns** @@ -5530,9 +6072,9 @@ Pointer to the function used to obtain the column name based on the specified co | Name| Description| | -------- | -------- | | cursor | Pointer to the [OH_Cursor](_o_h___cursor.md) instance.| -| columnIndex | Index of the column. The index value starts from **0**.| +| columnIndex | Index of the column, which starts from **0**.| | name | Pointer to the column name obtained.| -| length | Length of a column name.| +| length | Total length of the column name obtained, including the terminator.| **Returns** @@ -5560,7 +6102,7 @@ Pointer to the function used to obtain the column type based on the specified co | Name| Description| | -------- | -------- | | cursor | Pointer to the [OH_Cursor](_o_h___cursor.md) instance.| -| columnIndex | Index of the column. The index value starts from **0**.| +| columnIndex | Index of the column, which starts from **0**.| | columnType | Pointer to the [OH_ColumnType](#oh_columntype) obtained.| **Returns** @@ -5589,7 +6131,7 @@ Pointer to the function used to obtain the value of the int64_t type based on th | Name| Description| | -------- | -------- | | cursor | Pointer to the [OH_Cursor](_o_h___cursor.md) instance.| -| columnIndex | Index of the column. The index value starts from **0**.| +| columnIndex | Index of the column, which starts from **0**.| | value | Pointer to the value obtained.| **Returns** @@ -5618,7 +6160,7 @@ Pointer to the function used to obtain the value of the double type based on the | Name| Description| | -------- | -------- | | cursor | Pointer to the [OH_Cursor](_o_h___cursor.md) instance.| -| columnIndex | Index of the column. The index value starts from **0**.| +| columnIndex | Index of the column, which starts from **0**.| | value | Pointer to the value obtained.| **Returns** @@ -5675,7 +6217,7 @@ Pointer to the function used to obtain information about the memory required whe | Name| Description| | -------- | -------- | | cursor | Pointer to the [OH_Cursor](_o_h___cursor.md) instance.| -| columnIndex | Index of the column. The index value starts from **0**.| +| columnIndex | Index of the column, which starts from **0**.| | size | Pointer to the memory size obtained.| **Returns** @@ -5704,9 +6246,9 @@ Pointer to the function used to obtain the value of the string type based on the | Name| Description| | -------- | -------- | | cursor | Pointer to the [OH_Cursor](_o_h___cursor.md) instance.| -| columnIndex | Index of the column. The index value starts from **0**.| +| columnIndex | Index of the column, which starts from **0**.| | value | Pointer to the value of the string type obtained.| -| length | Length of the value, which can be obtained by **getSize()**.| +| length | Length of **value**, obtained by using **getSize**.| **Returns** @@ -5752,7 +6294,7 @@ OH_Predicates *(*greaterThan) (OH_Predicates *predicates, const char *field, OH_ **Description** -Pointer to the function used to set a predicates object to match the field with value greater than the specified value. +Pointer to the function used to create a predicates object to search for the field values that are greater than the specified value. This method is equivalent to ">" in SQL statements. @@ -5783,7 +6325,7 @@ OH_Predicates *(*greaterThanOrEqualTo) (OH_Predicates *predicates, const char *f **Description** -Pointer to the function used to set a predicates object to match the field with value greater than or equal to the specified value. +Pointer to the function used to create a predicates object to search for the field values that are greater than or equal to the specified value. This method is equivalent to ">=" in SQL statements. @@ -5814,7 +6356,7 @@ OH_Predicates *(*groupBy) (OH_Predicates *predicates, char const *const *fields, **Description** -Pointer to the function used to set a predicates object to group rows that have the same value into summary rows. +Pointer to the function used to create a predicates object to group the results by the specified columns. This method is equivalent to **GROUP BY** in SQL statements. @@ -5826,7 +6368,7 @@ This method is equivalent to **GROUP BY** in SQL statements. | -------- | -------- | | predicates | Pointer to the [OH_Predicates](_o_h___predicates.md) instance.| | fields | Pointer to the names of the columns by which the records are grouped.| -| length | Length of the **fields** value.| +| length | Length of **fields**.| **Returns** @@ -5900,7 +6442,7 @@ OH_Predicates *(*in) (OH_Predicates *predicates, const char *field, OH_VObject * **Description** -Pointer to the function used to set a predicates object to match the field with the value within the specified range. +Pointer to the function used to create a predicates object to search for the field values that are within the specified range. This method is equivalent to **IN** in SQL statements. @@ -5931,7 +6473,7 @@ Rdb_KeyInfo Rdb_ChangeInfo::inserted **Description** -Location where data is inserted. If the primary key of the table is of the string type, the value is the value of the primary key. Otherwise, the value is the row number of the inserted data. +Location where data is inserted. If the primary key of the table is of the string type, it is the value of the primary key. Otherwise, the value is the row number of the inserted data. ### integer @@ -5953,7 +6495,7 @@ bool Rdb_DistributedConfig::isAutoSync **Description** -Whether the table supports automatic sync. +Whether the table supports auto sync. ### isEncrypt @@ -5975,7 +6517,7 @@ OH_Predicates *(*isNotNull) (OH_Predicates *predicates, const char *field) **Description** -Pointer to the function used to set a predicates object to match the field whose value is not null. +Pointer to the function used to create a predicates object to search for the field values that are not null. This method is equivalent to **IS NOT NULL** in SQL statements. @@ -6014,7 +6556,7 @@ Pointer to the function used to check whether the value in the specified column | Name| Description| | -------- | -------- | | cursor | Pointer to the [OH_Cursor](_o_h___cursor.md) instance.| -| columnIndex | Index of the column. The index value starts from **0**.| +| columnIndex | Index of the column, which starts from **0**.| | isNull | Pointer to the value returned. The value **true** means the value is null; the value **false** means the opposite.| **Returns** @@ -6034,7 +6576,7 @@ OH_Predicates *(*isNull) (OH_Predicates *predicates, const char *field) **Description** -Pointer to the function used to set a predicates object to match the field whose value is null. +Pointer to the function used to create a predicates object to search for the field values that are null. This method is equivalent to **IS NULL** in SQL statements. @@ -6064,7 +6606,7 @@ OH_Predicates *(*lessThan) (OH_Predicates *predicates, const char *field, OH_VOb **Description** -Pointer to the function used to set a predicates object to match the field with value less than the specified value. +Pointer to the function used to create a predicates object to search for the records that are less than the given value in the specified field. This method is equivalent to "<" in SQL statements. @@ -6095,7 +6637,7 @@ OH_Predicates *(*lessThanOrEqualTo) (OH_Predicates *predicates, const char *fiel **Description** -Pointer to the function used to set a predicates object to match the field with value less than or equal to the specified value. +Pointer to the function used to create a predicates object to search for the records that are less than or equal to the specified **valueObject** in the specified field. This method is equivalent to "<=" in SQL statements. @@ -6126,7 +6668,7 @@ OH_Predicates *(*like) (OH_Predicates *predicates, const char *field, OH_VObject **Description** -Pointer to the function used to set a predicates object to match a string that is similar to the specified value. +Pointer to the function used to create a predicates object to search for the field values that are similar to the specified string. This method is equivalent to **LIKE** in SQL statements. @@ -6157,7 +6699,7 @@ OH_Predicates *(*limit) (OH_Predicates *predicates, unsigned int value) **Description** -Pointer to the function used to set a predicates object to specify the maximum number of records. +Pointer to the function used to create a predicates object to specify the maximum number of records. This method is equivalent to **LIMIT** in SQL statements. @@ -6198,7 +6740,7 @@ OH_Predicates *(*notBetween) (OH_Predicates *predicates, const char *field, OH_V **Description** -Pointer to the function used to set a predicates object to match the field whose value is out of the specified range. +Pointer to the function used to create a predicates object to search for the field values that are out of the specified range. This method is equivalent to **NOT BETWEEN** in SQL statements. @@ -6229,7 +6771,7 @@ OH_Predicates *(*notEqualTo) (OH_Predicates *predicates, const char *field, OH_V **Description** -Pointer to the function used to set a predicates object to match the field whose value is not equal to the specified value. +Pointer to the function used to create a predicates object to search for the field values that are not equal to the specified value. This method is equivalent to "!=" in SQL statements. @@ -6260,7 +6802,7 @@ OH_Predicates *(*notIn) (OH_Predicates *predicates, const char *field, OH_VObjec **Description** -Pointer to the function used to set a predicates object to match the field with the value out of the specified range. +Pointer to the function used to create a predicates object to search for the field values that are out of the specified range. This method is equivalent to **NOT IN** in SQL statements. @@ -6291,7 +6833,7 @@ OH_Predicates *(*offset) (OH_Predicates *predicates, unsigned int rowOffset) **Description** -Pointer to the function used to set a predicates object to specify the start position of the returned result. +Pointer to the function used to create a predicates object to specify the start position of the query result. This method is equivalent to **OFFSET** in SQL statements. @@ -6321,7 +6863,7 @@ OH_Predicates *(*orderBy) (OH_Predicates *predicates, const char *field, OH_Orde **Description** -Pointer to the function used to set a predicates object to sort the values in a column in ascending or descending order. +Pointer to the function used to create a predicates object to sort the values in the specified column in ascending or descending order. This method is equivalent to **ORDER BY** in SQL statements. @@ -6621,7 +7163,7 @@ Pointer to the function used to convert a string array of the char type to a val | Name| Description| | -------- | -------- | | valueObject | Pointer to the [OH_VObject](_o_h___v_object.md) instance.| -| value | Pointer to the string array to convert.| +| value | Double pointer to the string array to convert.| | count | Length of the string array to convert.| **Returns** @@ -6773,7 +7315,7 @@ int Rdb_KeyInfo::type **Description** -Type ([OH_ColumnType](#oh_columntype)) of the primary key. +[OH_ColumnType](#oh_columntype) of the primary key. ### updated @@ -6784,7 +7326,7 @@ Rdb_KeyInfo Rdb_ChangeInfo::updated **Description** -Location where data is updated. If the primary key of the table is of the string type, the value is the value of the primary key. Otherwise, the value is the row number of the updated data. +Location where data is updated. If the primary key of the table is of the string type, it is the value of the primary key. Otherwise, the value is the row number of the updated data. ### upload diff --git a/en/application-dev/reference/apis-arkdata/_rdb___progress_details.md b/en/application-dev/reference/apis-arkdata/_rdb___progress_details.md index 1ce6189ae423147cb428d32a4a203bb92883c8f6..90f9b95800521e6c366e65e235f772899ddb4687 100644 --- a/en/application-dev/reference/apis-arkdata/_rdb___progress_details.md +++ b/en/application-dev/reference/apis-arkdata/_rdb___progress_details.md @@ -19,5 +19,5 @@ Defines a struct for statistics of the overall device-cloud sync (upload and dow | -------- | -------- | | [version](_r_d_b.md#version-33) | Version of the **OH_TableDetails** struct.| | [schedule](_r_d_b.md#schedule) | Device-cloud sync process.| -| [code](_r_d_b.md#code) | device-cloud sync state.| -| [tableLength](_r_d_b.md#tablelength) | Number of the tables synchronized between the device and cloud.| +| [code](_r_d_b.md#code) | Device-cloud sync state.| +| [tableLength](_r_d_b.md#tablelength) | Number of the tables synced between the device and cloud.| diff --git a/en/application-dev/reference/apis-arkdata/_u_d_m_f.md b/en/application-dev/reference/apis-arkdata/_u_d_m_f.md index c569dfbdaf47c65edc89550eb4c3af5ebeebfc51..6b967c4d5c6d290dad513085d6b6b4f625b9111d 100644 --- a/en/application-dev/reference/apis-arkdata/_u_d_m_f.md +++ b/en/application-dev/reference/apis-arkdata/_u_d_m_f.md @@ -15,326 +15,343 @@ The Unified Data Management Framework (UDMF) defines standards for data manageme ### Files -| Name| Description| +| Name| Description| | -------- | -------- | -| [udmf.h](udmf_8h.md) | Defines the APIs, data structs, and enums for accessing the UDMF.
File to include: <database/udmf/udmf.h> | -| [udmf_err_code.h](udmf__err__code_8h.md) | Declares the error codes used in the UDMF.
File to include: <database/udmf/udmf_err_code.h> | -| [udmf_meta.h](udmf__meta_8h.md) | Declares the uniform data types.
File to include: <database/udmf/udmf_meta.h> | -| [uds.h](uds_8h.md) | Defines the APIs and structs related to the uniform data structs.
File to include: <database/udmf/uds.h> | -| [utd.h](utd_8h.md) | Defines APIs and structs related to the Uniform Type Descriptors (UTDs).
File to include: <database/udmf/utd.h> | +| [udmf.h](udmf_8h.md) | Defines the APIs, data structs, and enums for accessing the UDMF.
File to include: <database/udmf/udmf.h> | +| [udmf_err_code.h](udmf__err__code_8h.md) | Declares the error codes used in the UDMF.
File to include: <database/udmf/udmf_err_code.h> | +| [udmf_meta.h](udmf__meta_8h.md) | Declares the uniform data types.
File to include: <database/udmf/udmf_meta.h> | +| [uds.h](uds_8h.md) | Defines the APIs and structs related to the uniform data structs.
File to include: <database/udmf/uds.h> | +| [utd.h](utd_8h.md) | Defines APIs and structs related to the Uniform Type Descriptors (UTDs).
File to include: <database/udmf/utd.h> | ### Macros -| Name| Description| -| -------- | -------- | -| [UDMF_KEY_BUFFER_LEN](#udmf_key_buffer_len) (512) | Minimum length of the buffer that holds the key (unique identifier) of a uniform data object.| -| [UDMF_META_ENTITY](#udmf_meta_entity) "general.entity" | Generic type that represents all physical storage types. It is used to define physical properties of a type.
This type is uncategorized.| -| [UDMF_META_OBJECT](#udmf_meta_object) "general.object" | Generic type that represents all logical content types. It is used to define physical properties of a type.
This type is uncategorized.| -| [UDMF_META_COMPOSITE_OBJECT](#udmf_meta_composite_object) "general.composite-object" | Generic composite content type. For example, a PDF file that contains text and image.
This type belongs to **OBJECT**.| -| [UDMF_META_TEXT](#udmf_meta_text) "general.text" | Generic text type.
This type belongs to **OBJECT**.| -| [UDMF_META_PLAIN_TEXT](#udmf_meta_plain_text) "general.plain-text" | Text without specific encoding or identifier.
This type belongs to **TEXT**.| -| [UDMF_META_HTML](#udmf_meta_html) "general.html" | HTML.
This type belongs to **TEXT**.| -| [UDMF_META_HYPERLINK](#udmf_meta_hyperlink) "general.hyperlink" | Hyperlink.
This type belongs to **TEXT**.| -| [UDMF_META_XML](#udmf_meta_xml) "general.xml" | XML.
This type belongs to **TEXT**.| -| [UDMF_META_SOURCE_CODE](#udmf_meta_source_code) "general.source-code" | Generic source code type.
This type belongs to **PLAIN_TEXT**.| -| [UDMF_META_SCRIPT](#udmf_meta_script) "general.script" | Source code in any scripting language.
This type belongs to **SOURCE_CODE**.| -| [UDMF_META_SHELL_SCRIPT](#udmf_meta_shell_script) "general.shell-script" | Shell script.
This type belongs to **SCRIPT**.| -| [UDMF_META_CSH_SCRIPT](#udmf_meta_csh_script) "general.csh-script" | C shell script.
This type belongs to **SHELL_SCRIPT**.| -| [UDMF_META_PERL_SCRIPT](#udmf_meta_perl_script) "general.perl-script" | Perl script.
This type belongs to **SHELL_SCRIPT**.| -| [UDMF_META_PHP_SCRIPT](#udmf_meta_php_script) "general.php-script" | PHP script.
This type belongs to **SHELL_SCRIPT**.| -| [UDMF_META_PYTHON_SCRIPT](#udmf_meta_python_script) "general.python-script" | Python script.
This type belongs to **SHELL_SCRIPT**.| -| [UDMF_META_RUBY_SCRIPT](#udmf_meta_ruby_script) "general.ruby-script" | Ruby script.
This type belongs to **SHELL_SCRIPT**.| -| [UDMF_META_TYPE_SCRIPT](#udmf_meta_type_script) "general.type-script" | TypeScript source code.
This type belongs to **SCRIPT**.| -| [UDMF_META_JAVA_SCRIPT](#udmf_meta_java_script) "general.java-script" | JavaScript source code.
This type belongs to **SCRIPT**.| -| [UDMF_META_C_HEADER](#udmf_meta_c_header) "general.c-header" | Header file in C.
This type belongs to **SOURCE_CODE**.| -| [UDMF_META_C_SOURCE](#udmf_meta_c_source) "general.c-source" | Source code in C.
This type belongs to **SOURCE_CODE**.| -| [UDMF_META_C_PLUS_PLUS_HEADER](#udmf_meta_c_plus_plus_header) "general.c-plus-plus-header" | Header file in C++.
This type belongs to **SOURCE_CODE**.| -| [UDMF_META_C_PLUS_PLUS_SOURCE](#udmf_meta_c_plus_plus_source) "general.c-plus-plus-source" | Source code in C++.
This type belongs to **SOURCE_CODE**.| -| [UDMF_META_JAVA_SOURCE](#udmf_meta_java_source) "general.java-source" | Source code in Java.
This type belongs to **SOURCE_CODE**.| -| [UDMF_META_EBOOK](#udmf_meta_ebook) "general.ebook" | Generic eBook file format type.
This type belongs to **COMPOSITE_OBJECT**.| -| [UDMF_META_EPUB](#udmf_meta_epub) "general.epub" | Electronic publication (EPUB).
This type belongs to **EBOOK**.| -| [UDMF_META_AZW](#udmf_meta_azw) "com.amazon.azw" | AZW.
This type belongs to **EBOOK**.| -| [UDMF_META_AZW3](#udmf_meta_azw3) "com.amazon.azw3" | AZW3.
This type belongs to **EBOOK**.| -| [UDMF_META_KFX](#udmf_meta_kfx) "com.amazon.kfx" | KFX.
This type belongs to **EBOOK**.| -| [UDMF_META_MOBI](#udmf_meta_mobi) "com.amazon.mobi" | MOBI.
This type belongs to **EBOOK**.| -| [UDMF_META_MEDIA](#udmf_meta_media) "general.media" | Generic media type.
This type belongs to **OBJECT**.| -| [UDMF_META_IMAGE](#udmf_meta_image) "general.image" | Image.
This type belongs to **MEDIA**.| -| [UDMF_META_JPEG](#udmf_meta_jpeg) "general.jpeg" | JPEG.
This type belongs to **IMAGE**.| -| [UDMF_META_PNG](#udmf_meta_png) "general.png" | PNG.
This type belongs to **IMAGE**.| -| [UDMF_META_RAW_IMAGE](#udmf_meta_raw_image) "general.raw-image" | Raw image.
This type belongs to **IMAGE**.| -| [UDMF_META_TIFF](#udmf_meta_tiff) "general.tiff" | TIFF.
This type belongs to **IMAGE**.| -| [UDMF_META_BMP](#udmf_meta_bmp) "com.microsoft.bmp" | BMP.
This type belongs to **IMAGE**.| -| [UDMF_META_ICO](#udmf_meta_ico) "com.microsoft.ico" | Windows icon.
This type belongs to **IMAGE**.| -| [UDMF_META_PHOTOSHOP_IMAGE](#udmf_meta_photoshop_image) "com.adobe.photoshop-image" | Adobe Photoshop image.
This type belongs to **IMAGE**.| -| [UDMF_META_AI_IMAGE](#udmf_meta_ai_image) "com.adobe.illustrator.ai-image" | Adobe Illustrator image (.ai).
This type belongs to **IMAGE**.| -| [UDMF_META_WORD_DOC](#udmf_meta_word_doc) "com.microsoft.word.doc" | Microsoft Word.
This type belongs to **COMPOSITE_OBJECT**.| -| [UDMF_META_EXCEL](#udmf_meta_excel) "com.microsoft.excel.xls" | Microsoft Excel.
This type belongs to **COMPOSITE_OBJECT**.| -| [UDMF_META_PPT](#udmf_meta_ppt) "com.microsoft.powerpoint.ppt" | Microsoft PowerPoint presentation format.
This type belongs to **COMPOSITE_OBJECT**.| -| [UDMF_META_PDF](#udmf_meta_pdf) "com.adobe.pdf" | PDF.
This type belongs to **COMPOSITE_OBJECT**.| -| [UDMF_META_POSTSCRIPT](#udmf_meta_postscript) "com.adobe.postscript" | PostScript.
This type belongs to **COMPOSITE_OBJECT**.| -| [UDMF_META_ENCAPSULATED_POSTSCRIPT](#udmf_meta_encapsulated_postscript) "com.adobe.encapsulated-postscript" | Encapsulated PostScript.
This type belongs to **POSTSCRIPT**.| -| [UDMF_META_VIDEO](#udmf_meta_video) "general.video" | Generic video type.
This type belongs to **MEDIA**.| -| [UDMF_META_AVI](#udmf_meta_avi) "general.avi" | AVI.
This type belongs to **VIDEO**.| -| [UDMF_META_MPEG](#udmf_meta_mpeg) "general.mpeg" | MPGE-1 or MPGE-2.
This type belongs to **VIDEO**.| -| [UDMF_META_MPEG4](#udmf_meta_mpeg4) "general.mpeg-4" | MPGE-4.
This type belongs to **VIDEO**.| -| [UDMF_META_VIDEO_3GPP](#udmf_meta_video_3gpp) "general.3gpp" | 3GP (3GPP file format).
This type belongs to **VIDEO**.| -| [UDMF_META_VIDEO_3GPP2](#udmf_meta_video_3gpp2) "general.3gpp2" | 3G2 (3GPP2 file format).
This type belongs to **VIDEO**.| -| [UDMF_META_WINDOWS_MEDIA_WM](#udmf_meta_windows_media_wm) "com.microsoft.windows-media-wm" | Windows WM format.
This type belongs to **VIDEO**.| -| [UDMF_META_WINDOWS_MEDIA_WMV](#udmf_meta_windows_media_wmv) "com.microsoft.windows-media-wmv" | Windows WMV format.
This type belongs to **VIDEO**.| -| [UDMF_META_WINDOWS_MEDIA_WMP](#udmf_meta_windows_media_wmp) "com.microsoft.windows-media-wmp" | Windows WMP format.
This type belongs to **VIDEO**.| -| [UDMF_META_AUDIO](#udmf_meta_audio) "general.audio" | Generic audio type.
This type belongs to **MEDIA**.| -| [UDMF_META_AAC](#udmf_meta_aac) "general.aac" | AAC.
This type belongs to **AUDIO**.| -| [UDMF_META_AIFF](#udmf_meta_aiff) "general.aiff" | AIFF.
This type belongs to **AUDIO**.| -| [UDMF_META_ALAC](#udmf_meta_alac) "general.alac" | ALAC.
This type belongs to **AUDIO**.| -| [UDMF_META_FLAC](#udmf_meta_flac) "general.flac" | FLAC.
This type belongs to **AUDIO**.| -| [UDMF_META_MP3](#udmf_meta_mp3) "general.mp3" | MP3.
This type belongs to **AUDIO**.| -| [UDMF_META_OGG](#udmf_meta_ogg) "general.ogg" | OGG.
This type belongs to **AUDIO**.| -| [UDMF_META_PCM](#udmf_meta_pcm) "general.pcm" | PCM.
This type belongs to **AUDIO**.| -| [UDMF_META_WINDOWS_MEDIA_WMA](#udmf_meta_windows_media_wma) "com.microsoft.windows-media-wma" | Windows WMA.
This type belongs to **AUDIO**.| -| [UDMF_META_WAVEFORM_AUDIO](#udmf_meta_waveform_audio) "com.microsoft.waveform-audio" | Windows Waveform.
This type belongs to **AUDIO**.| -| [UDMF_META_WINDOWS_MEDIA_WMX](#udmf_meta_windows_media_wmx) "com.microsoft.windows-media-wmx" | Windows WMX format.
This type belongs to **VIDEO**.| -| [UDMF_META_WINDOWS_MEDIA_WVX](#udmf_meta_windows_media_wvx) "com.microsoft.windows-media-wvx" | Windows WVX format.
This type belongs to **VIDEO**.| -| [UDMF_META_WINDOWS_MEDIA_WAX](#udmf_meta_windows_media_wax) "com.microsoft.windows-media-wax" | Windows WAX.
This type belongs to **AUDIO**.| -| [UDMF_META_GENERAL_FILE](#udmf_meta_general_file) "general.file" | Generic file type.
This type belongs to **ENTITY**.| -| [UDMF_META_DIRECTORY](#udmf_meta_directory) "general.directory" | Generic directory type.
This type belongs to **ENTITY**.| -| [UDMF_META_FOLDER](#udmf_meta_folder) "general.folder" | Generic folder type.
This type belongs to **DIRECTORY**.| -| [UDMF_META_SYMLINK](#udmf_meta_symlink) "general.symlink" | Generic symbolic type.
This type belongs to **ENTITY**.| -| [UDMF_META_ARCHIVE](#udmf_meta_archive) "general.archive" | Generic archive file type.
This type belongs to **OBJECT**.| -| [UDMF_META_BZ2_ARCHIVE](#udmf_meta_bz2_archive) "general.bz2-archive" | BZ2.
This type belongs to **ARCHIVE**.| -| [UDMF_META_DISK_IMAGE](#udmf_meta_disk_image) "general.disk-image" | Generic type of any file that can be mounted as a volume.
This type belongs to **ARCHIVE**.| -| [UDMF_META_TAR_ARCHIVE](#udmf_meta_tar_archive) "general.tar-archive" | TAR.
This type belongs to ARCHIVE.| -| [UDMF_META_ZIP_ARCHIVE](#udmf_meta_zip_archive) "general.zip-archive" | ZIP.
This type belongs to **ARCHIVE**.| -| [UDMF_META_JAVA_ARCHIVE](#udmf_meta_java_archive) "com.sun.java-archive" | JAR (Java archive).
This type belongs to **ARCHIVE** and **EXECUTABLE**.| -| [UDMF_META_GNU_TAR_ARCHIVE](#udmf_meta_gnu_tar_archive) "org.gnu.gnu-tar-archive" | GUN archive.
This type belongs to **ARCHIVE**.| -| [UDMF_META_GNU_ZIP_ARCHIVE](#udmf_meta_gnu_zip_archive) "org.gnu.gnu-zip-archive" | GZIP archive.
This type belongs to **ARCHIVE**.| -| [UDMF_META_GNU_ZIP_TAR_ARCHIVE](#udmf_meta_gnu_zip_tar_archive) "org.gnu.gnu-zip-tar-archive" | GZIP TAR.
This type belongs to **ARCHIVE**.| -| [UDMF_META_CALENDAR](#udmf_meta_calendar) "general.calendar" | Generic calendar type.
This type belongs to **OBJECT**.| -| [UDMF_META_CONTACT](#udmf_meta_contact) "general.contact" | Generic contact type.
This type belongs to **OBJECT**.| -| [UDMF_META_DATABASE](#udmf_meta_database) "general.database" | Generic database file type.
This type belongs to **OBJECT**.| -| [UDMF_META_MESSAGE](#udmf_meta_message) "general.message" | Generic message type.
This type belongs to **OBJECT**.| -| [UDMF_META_VCARD](#udmf_meta_vcard) "general.vcard" | Generic electronic business card type.
This type belongs to **OBJECT**.| -| [UDMF_META_NAVIGATION](#udmf_meta_navigation) "general.navigation" | Generic navigation data type.
This type belongs to **OBJECT**.| -| [UDMF_META_LOCATION](#udmf_meta_location) "general.location" | Location data.
This type belongs to **NAVIGATION**.| -| [UDMF_META_OPENHARMONY_FORM](#udmf_meta_openharmony_form) "openharmony.form" | Widget defined for the system.
This type belongs to **OBJECT**.| -| [UDMF_META_OPENHARMONY_APP_ITEM](#udmf_meta_openharmony_app_item) "openharmony.app-item" | Home screen icon defined for the system.
This type belongs to **OBJECT**.| -| [UDMF_META_OPENHARMONY_PIXEL_MAP](#udmf_meta_openharmony_pixel_map) "openharmony.pixel-map" | Pixel map defined for the system.
This type belongs to **IMAGE**.| -| [UDMF_META_OPENHARMONY_ATOMIC_SERVICE](#udmf_meta_openharmony_atomic_service) "openharmony.atomic-service" | Atomic service type defined for the system.
This type belongs to **OBJECT**.| -| [UDMF_META_OPENHARMONY_PACKAGE](#udmf_meta_openharmony_package) "openharmony.package" | Package (compressed folder) defined for the system.
This type belongs to **DIRECTORY**.| -| [UDMF_META_OPENHARMONY_HAP](#udmf_meta_openharmony_hap) "openharmony.hap" | Ability package defined for the system.
This type belongs to **OPENHARMONY_PACKAGE**.| -| [UDMF_META_SMIL](#udmf_meta_smil) "com.real.smil" | Synchronized Multimedia Integration Language (SMIL).
This type belongs to **XML**.| -| [UDMF_META_MARKDOWN](#udmf_meta_markdown) "general.markdown" | Markdown.
This type belongs to **PLAIN_TEXT**.| -| [UDMF_META_FAX](#udmf_meta_fax) "general.fax" | Generic type of the fax.
This type belongs to **IMAGE**.| -| [UDMF_META_JFX_FAX](#udmf_meta_jfx_fax) "com.j2.jfx-fax" | J2 jConnect fax file format.
This type belongs to **FAX**.| -| [UDMF_META_EFX_FAX](#udmf_meta_efx_fax) "com.js.efx-fax" | EFX file format.
This type belongs to **FAX**.| -| [UDMF_META_XBITMAP_IMAGE](#udmf_meta_xbitmap_image) "general.xbitmap-image" | X BitMAP (XBM) used in the X Window system (X11).
This type belongs to **IMAGE**.| -| [UDMF_META_TGA_IMAGE](#udmf_meta_tga_image) "com.truevision.tga-image" | Tagged Graphics (TGA) format.
This type belongs to **IMAGE**.| -| [UDMF_META_SGI_IMAGE](#udmf_meta_sgi_image) "com.sgi.sgi-image" | Silicon Graphics image (SGI) format.
This type belongs to **IMAGE**.| -| [UDMF_META_OPENEXR_IMAGE](#udmf_meta_openexr_image) "com.ilm.openexr-image" | OpenXR image format.
This type belongs to **IMAGE**.| -| [UDMF_META_FLASHPIX_IMAGE](#udmf_meta_flashpix_image) "com.kodak.flashpix.image" | FlashPix image format.
This type belongs to **IMAGE**.| -| [UDMF_META_REALMEDIA](#udmf_meta_realmedia) "com.real.realmedia" | RealMedia format.
This type belongs to **VIDEO**.| -| [UDMF_META_AU_AUDIO](#udmf_meta_au_audio) "general.au-audio" | AU format.
This type belongs to **AUDIO**.| -| [UDMF_META_AIFC_AUDIO](#udmf_meta_aifc_audio) "general.aifc-audio" | AIFC.
This type belongs to **AUDIO**.| -| [UDMF_META_SD2_AUDIO](#udmf_meta_sd2_audio) "com.digidesign.sd2-audio" | Digidesign Sound Designer II (SDII).
This type belongs to **AUDIO**.| -| [UDMF_META_REALAUDIO](#udmf_meta_realaudio) "com.real.realaudio" | RealAudio.
This type belongs to **AUDIO**.| -| [UDMF_META_OPENXML](#udmf_meta_openxml) "org.openxmlformats.openxml" | OpenXML base type.
This type belongs to **ARCHIVE**.| -| [UDMF_META_WORDPROCESSINGML_DOCUMENT](#udmf_meta_wordprocessingml_document) "org.openxmlformats.wordprocessingml.document" | WordProcessingML format.
This type belongs to **OPENXML** and **COMPOSITE_OBJECT**.| -| [UDMF_META_SPREADSHEETML_SHEET](#udmf_meta_spreadsheetml_sheet) "org.openxmlformats.spreadsheetml.sheet" | SpreadsheetML format.
This type belongs to **OPENXML** and **COMPOSITE_OBJECT**.| -| [UDMF_META_PRESENTATIONML_PRESENTATION](#udmf_meta_presentationml_presentation) "org.openxmlformats.presentationml.presentation" | PresentationML format.
This type belongs to **OPENXML** and **COMPOSITE_OBJECT**.| -| [UDMF_META_OPENDOCUMENT](#udmf_meta_opendocument) "org.oasis.opendocument" | OpenDocument format for Office applications.
This type belongs to **ARCHIVE**.| -| [UDMF_META_OPENDOCUMENT_TEXT](#udmf_meta_opendocument_text) "org.oasis.opendocument.text" | OpenDocument format for word processing (text) documents.
This type belongs to **OPENDOCUMENT** and **COMPOSITE_OBJECT**.| -| [UDMF_META_OPENDOCUMENT_SPREADSHEET](#udmf_meta_opendocument_spreadsheet) "org.oasis.opendocument.spreadsheet" | OpenDocument format for spreadsheets.
This type belongs to **OPENDOCUMENT** and **COMPOSITE_OBJECT**.| -| [UDMF_META_OPENDOCUMENT_PRESENTATION](#udmf_meta_opendocument_presentation) "org.oasis.opendocument.presentation" | OpenDocument format for presentations.
This type belongs to **OPENDOCUMENT** and **COMPOSITE_OBJECT**.| -| [UDMF_META_OPENDOCUMENT_GRAPHICS](#udmf_meta_opendocument_graphics) "org.oasis.opendocument.graphics" | OpenDocument format for graphics.
This type belongs to **OPENDOCUMENT** and **COMPOSITE_OBJECT**.| -| [UDMF_META_OPENDOCUMENT_FORMULA](#udmf_meta_opendocument_formula) "org.oasis.opendocument.formula" | OpenDocument format for formula.
This type belongs to **OPENDOCUMENT**.| -| [UDMF_META_STUFFIT_ARCHIVE](#udmf_meta_stuffit_archive) "com.allume.stuffit-archive" | Stuffit compression format (stuffit archive).
This type belongs to **ARCHIVE**.| -| [UDMF_META_VCS](#udmf_meta_vcs) "general.vcs" | VCalendar (VCS) format.
This type belongs to **CALENDAR** and **TEXT**.| -| [UDMF_META_ICS](#udmf_meta_ics) "general.ics" | Internet Calendaring and Scheduling (ICS) format.
This type belongs to **CALENDAR** and **TEXT**.| -| [UDMF_META_EXECUTABLE](#udmf_meta_executable) "general.executable" | Generic type of all executable files.
This type belongs to **OBJECT**.| -| [UDMF_META_PORTABLE_EXECUTABLE](#udmf_meta_portable_executable) "com.microsoft.portable-executable" | Microsoft Windows portable executable format.
This type belongs to **EXECUTABLE**.| -| [UDMF_META_SUN_JAVA_CLASS](#udmf_meta_sun_java_class) "com.sun.java-class" | Java class file format.
This type belongs to **EXECUTABLE**.| -| [UDMF_META_FONT](#udmf_meta_font) "general.font" | Basic type of fonts.
This type belongs to **OBJECT**.| -| [UDMF_META_TRUETYPE_FONT](#udmf_meta_truetype_font) "general.truetype-font" | TrueType font format.
This type belongs to **FONT**.| -| [UDMF_META_TRUETYPE_COLLECTION_FONT](#udmf_meta_truetype_collection_font) "general.truetype-collection-font" | TrueType Collection font format.
This type belongs to **FONT**.| -| [UDMF_META_OPENTYPE_FONT](#udmf_meta_opentype_font) "general.opentype-font" | OpenType font format.
This type belongs to **FONT**.| -| [UDMF_META_POSTSCRIPT_FONT](#udmf_meta_postscript_font) "com.adobe.postscript-font" | PostScript font format.
This type belongs to **FONT**.| -| [UDMF_META_POSTSCRIPT_PFB_FONT](#udmf_meta_postscript_pfb_font) "com.adobe.postscript-pfb-font" | PostScript Font Binary font format.
This type belongs to **FONT**.| -| [UDMF_META_POSTSCRIPT_PFA_FONT](#udmf_meta_postscript_pfa_font) "com.adobe.postscript-pfa-font" | Adobe Type 1 font format.
This type belongs to **FONT**.| -| [UDMF_META_OPENHARMONY_HDOC](#udmf_meta_openharmony_hdoc) "openharmony.hdoc" | Memo format defined for the system.
This type belongs to **COMPOSITE_OBJECT**.| -| [UDMF_META_OPENHARMONY_HINOTE](#udmf_meta_openharmony_hinote) "openharmony.hinote" | Note format defined for the system.
This type belongs to **COMPOSITE_OBJECT**.| -| [UDMF_META_OPENHARMONY_STYLED_STRING](#udmf_meta_openharmony_styled_string) "openharmony.styled-string" | Style string type defined for the system.
This type belongs to **COMPOSITE_OBJECT**.| -| [UDMF_META_OPENHARMONY_WANT](#udmf_meta_openharmony_want) "openharmony.want" | Want defined for the system.
This type belongs to **OBJECT**.| -| [UDMF_META_GENERAL_FILE_URI](#udmf_meta_general_file_uri) "general.file-uri" | File address type.
This type belongs to **TEXT**.| -| [UDMF_METE_GENERAL_CONTENT_FORM](#udmf_mete_general_content_form) "general.content-form" | Content widget type.
This type belongs to **OBJECT**.| +| Name| Description| +| -------- | -------- | +| [UDMF_KEY_BUFFER_LEN](#udmf_key_buffer_len) (512) | Minimum length of the buffer that holds the key (unique identifier) of a uniform data object.| +| [UDMF_META_ENTITY](#udmf_meta_entity) "general.entity" | Generic type that represents all physical storage types. It is used to define physical properties of a type.
This type is uncategorized.| +| [UDMF_META_OBJECT](#udmf_meta_object) "general.object" | Generic type that represents all logical content types. It is used to define physical properties of a type.
This type is uncategorized.| +| [UDMF_META_COMPOSITE_OBJECT](#udmf_meta_composite_object) "general.composite-object" | Generic composite content type. For example, a PDF file that contains text and image.
This type belongs to **OBJECT**.| +| [UDMF_META_TEXT](#udmf_meta_text) "general.text" | Generic text type.
This type belongs to **OBJECT**.| +| [UDMF_META_PLAIN_TEXT](#udmf_meta_plain_text) "general.plain-text" | Text without specific encoding or identifier.
This type belongs to **TEXT**.| +| [UDMF_META_HTML](#udmf_meta_html) "general.html" | HTML.
This type belongs to **TEXT**.| +| [UDMF_META_HYPERLINK](#udmf_meta_hyperlink) "general.hyperlink" | Hyperlink.
This type belongs to **TEXT**.| +| [UDMF_META_XML](#udmf_meta_xml) "general.xml" | XML.
This type belongs to **TEXT**.| +| [UDMF_META_SOURCE_CODE](#udmf_meta_source_code) "general.source-code" | Generic source code type.
This type belongs to **PLAIN_TEXT**.| +| [UDMF_META_SCRIPT](#udmf_meta_script) "general.script" | Source code in any scripting language.
This type belongs to **SOURCE_CODE**.| +| [UDMF_META_SHELL_SCRIPT](#udmf_meta_shell_script) "general.shell-script" | Shell script.
This type belongs to **SCRIPT**.| +| [UDMF_META_CSH_SCRIPT](#udmf_meta_csh_script) "general.csh-script" | C shell script.
This type belongs to **SHELL_SCRIPT**.| +| [UDMF_META_PERL_SCRIPT](#udmf_meta_perl_script) "general.perl-script" | Perl script.
This type belongs to **SHELL_SCRIPT**.| +| [UDMF_META_PHP_SCRIPT](#udmf_meta_php_script) "general.php-script" | PHP script.
This type belongs to **SHELL_SCRIPT**.| +| [UDMF_META_PYTHON_SCRIPT](#udmf_meta_python_script) "general.python-script" | Python script.
This type belongs to **SHELL_SCRIPT**.| +| [UDMF_META_RUBY_SCRIPT](#udmf_meta_ruby_script) "general.ruby-script" | Ruby script.
This type belongs to **SHELL_SCRIPT**.| +| [UDMF_META_TYPE_SCRIPT](#udmf_meta_type_script) "general.type-script" | TypeScript source code.
This type belongs to **SCRIPT**.| +| [UDMF_META_JAVA_SCRIPT](#udmf_meta_java_script) "general.java-script" | JavaScript source code.
This type belongs to **SCRIPT**.| +| [UDMF_META_C_HEADER](#udmf_meta_c_header) "general.c-header" | Header file in C.
This type belongs to **SOURCE_CODE**.| +| [UDMF_META_C_SOURCE](#udmf_meta_c_source) "general.c-source" | Source code in C.
This type belongs to **SOURCE_CODE**.| +| [UDMF_META_C_PLUS_PLUS_HEADER](#udmf_meta_c_plus_plus_header) "general.c-plus-plus-header" | Header file in C++.
This type belongs to **SOURCE_CODE**.| +| [UDMF_META_C_PLUS_PLUS_SOURCE](#udmf_meta_c_plus_plus_source) "general.c-plus-plus-source" | Source code in C++.
This type belongs to **SOURCE_CODE**.| +| [UDMF_META_JAVA_SOURCE](#udmf_meta_java_source) "general.java-source" | Source code in Java.
This type belongs to **SOURCE_CODE**.| +| [UDMF_META_EBOOK](#udmf_meta_ebook) "general.ebook" | Generic eBook file format type.
This type belongs to **COMPOSITE_OBJECT**.| +| [UDMF_META_EPUB](#udmf_meta_epub) "general.epub" | Electronic publication (EPUB).
This type belongs to **EBOOK**.| +| [UDMF_META_AZW](#udmf_meta_azw) "com.amazon.azw" | AZW.
This type belongs to **EBOOK**.| +| [UDMF_META_AZW3](#udmf_meta_azw3) "com.amazon.azw3" | AZW3.
This type belongs to **EBOOK**.| +| [UDMF_META_KFX](#udmf_meta_kfx) "com.amazon.kfx" | KFX.
This type belongs to **EBOOK**.| +| [UDMF_META_MOBI](#udmf_meta_mobi) "com.amazon.mobi" | MOBI.
This type belongs to **EBOOK**.| +| [UDMF_META_MEDIA](#udmf_meta_media) "general.media" | Generic media type.
This type belongs to **OBJECT**.| +| [UDMF_META_IMAGE](#udmf_meta_image) "general.image" | Image.
This type belongs to **MEDIA**.| +| [UDMF_META_JPEG](#udmf_meta_jpeg) "general.jpeg" | JPEG.
This type belongs to **IMAGE**.| +| [UDMF_META_PNG](#udmf_meta_png) "general.png" | PNG.
This type belongs to **IMAGE**.| +| [UDMF_META_RAW_IMAGE](#udmf_meta_raw_image) "general.raw-image" | Raw image.
This type belongs to **IMAGE**.| +| [UDMF_META_TIFF](#udmf_meta_tiff) "general.tiff" | TIFF.
This type belongs to **IMAGE**.| +| [UDMF_META_BMP](#udmf_meta_bmp) "com.microsoft.bmp" | BMP.
This type belongs to **IMAGE**.| +| [UDMF_META_ICO](#udmf_meta_ico) "com.microsoft.ico" | Windows icon.
This type belongs to **IMAGE**.| +| [UDMF_META_PHOTOSHOP_IMAGE](#udmf_meta_photoshop_image) "com.adobe.photoshop-image" | Adobe Photoshop image.
This type belongs to **IMAGE**.| +| [UDMF_META_AI_IMAGE](#udmf_meta_ai_image) "com.adobe.illustrator.ai-image" | Adobe Illustrator image (.ai).
This type belongs to **IMAGE**.| +| [UDMF_META_WORD_DOC](#udmf_meta_word_doc) "com.microsoft.word.doc" | Microsoft Word.
This type belongs to **COMPOSITE_OBJECT**.| +| [UDMF_META_EXCEL](#udmf_meta_excel) "com.microsoft.excel.xls" | Microsoft Excel.
This type belongs to **COMPOSITE_OBJECT**.| +| [UDMF_META_PPT](#udmf_meta_ppt) "com.microsoft.powerpoint.ppt" | Microsoft PowerPoint presentation format.
This type belongs to **COMPOSITE_OBJECT**.| +| [UDMF_META_PDF](#udmf_meta_pdf) "com.adobe.pdf" | PDF.
This type belongs to **COMPOSITE_OBJECT**.| +| [UDMF_META_POSTSCRIPT](#udmf_meta_postscript) "com.adobe.postscript" | PostScript.
This type belongs to **COMPOSITE_OBJECT**.| +| [UDMF_META_ENCAPSULATED_POSTSCRIPT](#udmf_meta_encapsulated_postscript) "com.adobe.encapsulated-postscript" | Encapsulated PostScript.
This type belongs to **POSTSCRIPT**.| +| [UDMF_META_VIDEO](#udmf_meta_video) "general.video" | Generic video type.
This type belongs to **MEDIA**.| +| [UDMF_META_AVI](#udmf_meta_avi) "general.avi" | AVI.
This type belongs to **VIDEO**.| +| [UDMF_META_MPEG](#udmf_meta_mpeg) "general.mpeg" | MPGE-1 or MPGE-2.
This type belongs to **VIDEO**.| +| [UDMF_META_MPEG4](#udmf_meta_mpeg4) "general.mpeg-4" | MPGE-4.
This type belongs to **VIDEO**.| +| [UDMF_META_VIDEO_3GPP](#udmf_meta_video_3gpp) "general.3gpp" | 3GP (3GPP file format).
This type belongs to **VIDEO**.| +| [UDMF_META_VIDEO_3GPP2](#udmf_meta_video_3gpp2) "general.3gpp2" | 3G2 (3GPP2 file format).
This type belongs to **VIDEO**.| +| [UDMF_META_WINDOWS_MEDIA_WM](#udmf_meta_windows_media_wm) "com.microsoft.windows-media-wm" | Windows WM format.
This type belongs to **VIDEO**.| +| [UDMF_META_WINDOWS_MEDIA_WMV](#udmf_meta_windows_media_wmv) "com.microsoft.windows-media-wmv" | Windows WMV format.
This type belongs to **VIDEO**.| +| [UDMF_META_WINDOWS_MEDIA_WMP](#udmf_meta_windows_media_wmp) "com.microsoft.windows-media-wmp" | Windows WMP format.
This type belongs to **VIDEO**.| +| [UDMF_META_AUDIO](#udmf_meta_audio) "general.audio" | Generic audio type.
This type belongs to **MEDIA**.| +| [UDMF_META_AAC](#udmf_meta_aac) "general.aac" | AAC.
This type belongs to **AUDIO**.| +| [UDMF_META_AIFF](#udmf_meta_aiff) "general.aiff" | AIFF.
This type belongs to **AUDIO**.| +| [UDMF_META_ALAC](#udmf_meta_alac) "general.alac" | ALAC.
This type belongs to **AUDIO**.| +| [UDMF_META_FLAC](#udmf_meta_flac) "general.flac" | FLAC.
This type belongs to **AUDIO**.| +| [UDMF_META_MP3](#udmf_meta_mp3) "general.mp3" | MP3.
This type belongs to **AUDIO**.| +| [UDMF_META_OGG](#udmf_meta_ogg) "general.ogg" | OGG.
This type belongs to **AUDIO**.| +| [UDMF_META_PCM](#udmf_meta_pcm) "general.pcm" | PCM.
This type belongs to **AUDIO**.| +| [UDMF_META_WINDOWS_MEDIA_WMA](#udmf_meta_windows_media_wma) "com.microsoft.windows-media-wma" | Windows WMA.
This type belongs to **AUDIO**.| +| [UDMF_META_WAVEFORM_AUDIO](#udmf_meta_waveform_audio) "com.microsoft.waveform-audio" | Windows Waveform.
This type belongs to **AUDIO**.| +| [UDMF_META_WINDOWS_MEDIA_WMX](#udmf_meta_windows_media_wmx) "com.microsoft.windows-media-wmx" | Windows WMX format.
This type belongs to **VIDEO**.| +| [UDMF_META_WINDOWS_MEDIA_WVX](#udmf_meta_windows_media_wvx) "com.microsoft.windows-media-wvx" | Windows WVX format.
This type belongs to **VIDEO**.| +| [UDMF_META_WINDOWS_MEDIA_WAX](#udmf_meta_windows_media_wax) "com.microsoft.windows-media-wax" | Windows WAX.
This type belongs to **AUDIO**.| +| [UDMF_META_GENERAL_FILE](#udmf_meta_general_file) "general.file" | Generic file type.
This type belongs to **ENTITY**.| +| [UDMF_META_DIRECTORY](#udmf_meta_directory) "general.directory" | Generic directory type.
This type belongs to **ENTITY**.| +| [UDMF_META_FOLDER](#udmf_meta_folder) "general.folder" | Generic folder type.
This type belongs to **DIRECTORY**.| +| [UDMF_META_SYMLINK](#udmf_meta_symlink) "general.symlink" | Generic symbolic type.
This type belongs to **ENTITY**.| +| [UDMF_META_ARCHIVE](#udmf_meta_archive) "general.archive" | Generic archive file type.
This type belongs to **OBJECT**.| +| [UDMF_META_BZ2_ARCHIVE](#udmf_meta_bz2_archive) "general.bz2-archive" | BZ2.
This type belongs to **ARCHIVE**.| +| [UDMF_META_DISK_IMAGE](#udmf_meta_disk_image) "general.disk-image" | Generic type of any file that can be mounted as a volume.
This type belongs to **ARCHIVE**.| +| [UDMF_META_TAR_ARCHIVE](#udmf_meta_tar_archive) "general.tar-archive" | TAR.
This type belongs to ARCHIVE.| +| [UDMF_META_ZIP_ARCHIVE](#udmf_meta_zip_archive) "general.zip-archive" | ZIP.
This type belongs to **ARCHIVE**.| +| [UDMF_META_JAVA_ARCHIVE](#udmf_meta_java_archive) "com.sun.java-archive" | JAR (Java archive).
This type belongs to **ARCHIVE** and **EXECUTABLE**.| +| [UDMF_META_GNU_TAR_ARCHIVE](#udmf_meta_gnu_tar_archive) "org.gnu.gnu-tar-archive" | GUN archive.
This type belongs to **ARCHIVE**.| +| [UDMF_META_GNU_ZIP_ARCHIVE](#udmf_meta_gnu_zip_archive) "org.gnu.gnu-zip-archive" | GZIP archive.
This type belongs to **ARCHIVE**.| +| [UDMF_META_GNU_ZIP_TAR_ARCHIVE](#udmf_meta_gnu_zip_tar_archive) "org.gnu.gnu-zip-tar-archive" | GZIP TAR.
This type belongs to **ARCHIVE**.| +| [UDMF_META_CALENDAR](#udmf_meta_calendar) "general.calendar" | Generic calendar type.
This type belongs to **OBJECT**.| +| [UDMF_META_CONTACT](#udmf_meta_contact) "general.contact" | Generic contact type.
This type belongs to **OBJECT**.| +| [UDMF_META_DATABASE](#udmf_meta_database) "general.database" | Generic database file type.
This type belongs to **OBJECT**.| +| [UDMF_META_MESSAGE](#udmf_meta_message) "general.message" | Generic message type.
This type belongs to **OBJECT**.| +| [UDMF_META_VCARD](#udmf_meta_vcard) "general.vcard" | Generic electronic business card type.
This type belongs to **OBJECT**.| +| [UDMF_META_NAVIGATION](#udmf_meta_navigation) "general.navigation" | Generic navigation data type.
This type belongs to **OBJECT**.| +| [UDMF_META_LOCATION](#udmf_meta_location) "general.location" | Location data.
This type belongs to **NAVIGATION**.| +| [UDMF_META_OPENHARMONY_FORM](#udmf_meta_openharmony_form) "openharmony.form" | Widget defined for the system.
This type belongs to **OBJECT**.| +| [UDMF_META_OPENHARMONY_APP_ITEM](#udmf_meta_openharmony_app_item) "openharmony.app-item" | Home screen icon defined for the system.
This type belongs to **OBJECT**.| +| [UDMF_META_OPENHARMONY_PIXEL_MAP](#udmf_meta_openharmony_pixel_map) "openharmony.pixel-map" | Pixel map defined for the system.
This type belongs to **IMAGE**.| +| [UDMF_META_OPENHARMONY_ATOMIC_SERVICE](#udmf_meta_openharmony_atomic_service) "openharmony.atomic-service" | Atomic service type defined for the system.
This type belongs to **OBJECT**.| +| [UDMF_META_OPENHARMONY_PACKAGE](#udmf_meta_openharmony_package) "openharmony.package" | Package (compressed folder) defined for the system.
This type belongs to **DIRECTORY**.| +| [UDMF_META_OPENHARMONY_HAP](#udmf_meta_openharmony_hap) "openharmony.hap" | Ability package defined for the system.
This type belongs to **OPENHARMONY_PACKAGE**.| +| [UDMF_META_SMIL](#udmf_meta_smil) "com.real.smil" | Synchronized Multimedia Integration Language (SMIL).
This type belongs to **XML**.| +| [UDMF_META_MARKDOWN](#udmf_meta_markdown) "general.markdown" | Markdown.
This type belongs to **PLAIN_TEXT**.| +| [UDMF_META_FAX](#udmf_meta_fax) "general.fax" | Generic type of the fax.
This type belongs to **IMAGE**.| +| [UDMF_META_JFX_FAX](#udmf_meta_jfx_fax) "com.j2.jfx-fax" | J2 jConnect fax file format.
This type belongs to **FAX**.| +| [UDMF_META_EFX_FAX](#udmf_meta_efx_fax) "com.js.efx-fax" | EFX file format.
This type belongs to **FAX**.| +| [UDMF_META_XBITMAP_IMAGE](#udmf_meta_xbitmap_image) "general.xbitmap-image" | X BitMAP (XBM) used in the X Window system (X11).
This type belongs to **IMAGE**.| +| [UDMF_META_TGA_IMAGE](#udmf_meta_tga_image) "com.truevision.tga-image" | Tagged Graphics (TGA) format.
This type belongs to **IMAGE**.| +| [UDMF_META_SGI_IMAGE](#udmf_meta_sgi_image) "com.sgi.sgi-image" | Silicon Graphics image (SGI) format.
This type belongs to **IMAGE**.| +| [UDMF_META_OPENEXR_IMAGE](#udmf_meta_openexr_image) "com.ilm.openexr-image" | OpenXR image format.
This type belongs to **IMAGE**.| +| [UDMF_META_FLASHPIX_IMAGE](#udmf_meta_flashpix_image) "com.kodak.flashpix.image" | FlashPix image format.
This type belongs to **IMAGE**.| +| [UDMF_META_REALMEDIA](#udmf_meta_realmedia) "com.real.realmedia" | RealMedia format.
This type belongs to **VIDEO**.| +| [UDMF_META_AU_AUDIO](#udmf_meta_au_audio) "general.au-audio" | AU format.
This type belongs to **AUDIO**.| +| [UDMF_META_AIFC_AUDIO](#udmf_meta_aifc_audio) "general.aifc-audio" | AIFC.
This type belongs to **AUDIO**.| +| [UDMF_META_SD2_AUDIO](#udmf_meta_sd2_audio) "com.digidesign.sd2-audio" | Digidesign Sound Designer II (SDII).
This type belongs to **AUDIO**.| +| [UDMF_META_REALAUDIO](#udmf_meta_realaudio) "com.real.realaudio" | RealAudio.
This type belongs to **AUDIO**.| +| [UDMF_META_OPENXML](#udmf_meta_openxml) "org.openxmlformats.openxml" | OpenXML base type.
This type belongs to **ARCHIVE**.| +| [UDMF_META_WORDPROCESSINGML_DOCUMENT](#udmf_meta_wordprocessingml_document) "org.openxmlformats.wordprocessingml.document" | WordProcessingML format.
This type belongs to **OPENXML** and **COMPOSITE_OBJECT**.| +| [UDMF_META_SPREADSHEETML_SHEET](#udmf_meta_spreadsheetml_sheet) "org.openxmlformats.spreadsheetml.sheet" | SpreadsheetML format.
This type belongs to **OPENXML** and **COMPOSITE_OBJECT**.| +| [UDMF_META_PRESENTATIONML_PRESENTATION](#udmf_meta_presentationml_presentation) "org.openxmlformats.presentationml.presentation" | PresentationML format.
This type belongs to **OPENXML** and **COMPOSITE_OBJECT**.| +| [UDMF_META_OPENDOCUMENT](#udmf_meta_opendocument) "org.oasis.opendocument" | OpenDocument format for Office applications.
This type belongs to **ARCHIVE**.| +| [UDMF_META_OPENDOCUMENT_TEXT](#udmf_meta_opendocument_text) "org.oasis.opendocument.text" | OpenDocument format for word processing (text) documents.
This type belongs to **OPENDOCUMENT** and **COMPOSITE_OBJECT**.| +| [UDMF_META_OPENDOCUMENT_SPREADSHEET](#udmf_meta_opendocument_spreadsheet) "org.oasis.opendocument.spreadsheet" | OpenDocument format for spreadsheets.
This type belongs to **OPENDOCUMENT** and **COMPOSITE_OBJECT**.| +| [UDMF_META_OPENDOCUMENT_PRESENTATION](#udmf_meta_opendocument_presentation) "org.oasis.opendocument.presentation" | OpenDocument format for presentations.
This type belongs to **OPENDOCUMENT** and **COMPOSITE_OBJECT**.| +| [UDMF_META_OPENDOCUMENT_GRAPHICS](#udmf_meta_opendocument_graphics) "org.oasis.opendocument.graphics" | OpenDocument format for graphics.
This type belongs to **OPENDOCUMENT** and **COMPOSITE_OBJECT**.| +| [UDMF_META_OPENDOCUMENT_FORMULA](#udmf_meta_opendocument_formula) "org.oasis.opendocument.formula" | OpenDocument format for formula.
This type belongs to **OPENDOCUMENT**.| +| [UDMF_META_STUFFIT_ARCHIVE](#udmf_meta_stuffit_archive) "com.allume.stuffit-archive" | Stuffit compression format (stuffit archive).
This type belongs to **ARCHIVE**.| +| [UDMF_META_VCS](#udmf_meta_vcs) "general.vcs" | VCalendar (VCS) format.
This type belongs to **CALENDAR** and **TEXT**.| +| [UDMF_META_ICS](#udmf_meta_ics) "general.ics" | Internet Calendaring and Scheduling (ICS) format.
This type belongs to **CALENDAR** and **TEXT**.| +| [UDMF_META_EXECUTABLE](#udmf_meta_executable) "general.executable" | Generic type of all executable files.
This type belongs to **OBJECT**.| +| [UDMF_META_PORTABLE_EXECUTABLE](#udmf_meta_portable_executable) "com.microsoft.portable-executable" | Microsoft Windows portable executable format.
This type belongs to **EXECUTABLE**.| +| [UDMF_META_SUN_JAVA_CLASS](#udmf_meta_sun_java_class) "com.sun.java-class" | Java class file format.
This type belongs to **EXECUTABLE**.| +| [UDMF_META_FONT](#udmf_meta_font) "general.font" | Basic type of fonts.
This type belongs to **OBJECT**.| +| [UDMF_META_TRUETYPE_FONT](#udmf_meta_truetype_font) "general.truetype-font" | TrueType font format.
This type belongs to **FONT**.| +| [UDMF_META_TRUETYPE_COLLECTION_FONT](#udmf_meta_truetype_collection_font) "general.truetype-collection-font" | TrueType Collection font format.
This type belongs to **FONT**.| +| [UDMF_META_OPENTYPE_FONT](#udmf_meta_opentype_font) "general.opentype-font" | OpenType font format.
This type belongs to **FONT**.| +| [UDMF_META_POSTSCRIPT_FONT](#udmf_meta_postscript_font) "com.adobe.postscript-font" | PostScript font format.
This type belongs to **FONT**.| +| [UDMF_META_POSTSCRIPT_PFB_FONT](#udmf_meta_postscript_pfb_font) "com.adobe.postscript-pfb-font" | PostScript Font Binary font format.
This type belongs to **FONT**.| +| [UDMF_META_POSTSCRIPT_PFA_FONT](#udmf_meta_postscript_pfa_font) "com.adobe.postscript-pfa-font" | Adobe Type 1 font format.
This type belongs to **FONT**.| +| [UDMF_META_OPENHARMONY_HDOC](#udmf_meta_openharmony_hdoc) "openharmony.hdoc" | Memo format defined for the system.
This type belongs to **COMPOSITE_OBJECT**.| +| [UDMF_META_OPENHARMONY_HINOTE](#udmf_meta_openharmony_hinote) "openharmony.hinote" | Note format defined for the system.
This type belongs to **COMPOSITE_OBJECT**.| +| [UDMF_META_OPENHARMONY_STYLED_STRING](#udmf_meta_openharmony_styled_string) "openharmony.styled-string" | Style string type defined for the system.
This type belongs to **COMPOSITE_OBJECT**.| +| [UDMF_META_OPENHARMONY_WANT](#udmf_meta_openharmony_want) "openharmony.want" | Want defined for the system.
This type belongs to **OBJECT**.| +| [UDMF_META_GENERAL_FILE_URI](#udmf_meta_general_file_uri) "general.file-uri" | File address type.
This type belongs to **TEXT**.| +| [UDMF_METE_GENERAL_CONTENT_FORM](#udmf_mete_general_content_form) "general.content-form" | Content widget type.
This type belongs to **OBJECT**.| ### Types -| Name| Description| -| -------- | -------- | -| typedef enum [Udmf_Intention](#udmf_intention) [Udmf_Intention](#udmf_intention) | Defines an enum for UDMF data channels.| -| typedef enum [Udmf_ShareOption](#udmf_shareoption) [Udmf_ShareOption](#udmf_shareoption) | Defines an enum for the scopes of the uniform data to be used on a device.| -| typedef struct [OH_UdmfData](#oh_udmfdata) [OH_UdmfData](#oh_udmfdata) | Defines a struct for a uniform data object.| -| typedef struct [OH_UdmfRecord](#oh_udmfrecord) [OH_UdmfRecord](#oh_udmfrecord) | Defines a struct for a data record in a uniform data object.| -| typedef struct [OH_UdmfRecordProvider](#oh_udmfrecordprovider) [OH_UdmfRecordProvider](#oh_udmfrecordprovider) | Defines a struct for the data record provider in a uniform data object.| -| typedef struct [OH_UdmfProperty](#oh_udmfproperty) [OH_UdmfProperty](#oh_udmfproperty) | Defines a struct for a data record property in a uniform data object.| -| typedef void(\* [UdmfData_Finalize](#udmfdata_finalize)) (void \*context) | Defines a callback function used to release the context. This callback is invoked when the **OH_UdmfRecordProvider** instance is destroyed.| -| typedef void \*(\* [OH_UdmfRecordProvider_GetData](#oh_udmfrecordprovider_getdata)) (void \*context, const char \*type) | Defines a callback function used to obtain data by type. This callback will be invoked to return the data obtained from **OH_UdmfRecord**.| -| typedef enum [Udmf_ErrCode](#udmf_errcode) [Udmf_ErrCode](#udmf_errcode) | Defines an enum for error codes.| -| typedef struct [OH_UdsPlainText](#oh_udsplaintext) [OH_UdsPlainText](#oh_udsplaintext) | Defines a struct for the uniform data of the plain text type.| -| typedef struct [OH_UdsHyperlink](#oh_udshyperlink) [OH_UdsHyperlink](#oh_udshyperlink) | Defines a struct for the uniform data of the hyperlink type.| -| typedef struct [OH_UdsHtml](#oh_udshtml) [OH_UdsHtml](#oh_udshtml) | Defines a struct for the uniform data of the Hypertext Markup Language (HTML) type.| -| typedef struct [OH_UdsAppItem](#oh_udsappitem) [OH_UdsAppItem](#oh_udsappitem) | Defines a struct for the uniform data of the home screen icon type.| -| typedef struct [OH_UdsFileUri](#oh_udsfileuri) [OH_UdsFileUri](#oh_udsfileuri) | Defines a struct for the file URI type.| -| typedef struct [OH_UdsPixelMap](#oh_udspixelmap) [OH_UdsPixelMap](#oh_udspixelmap) | Defines a struct for the pixel map type.| -| typedef struct [OH_UdsArrayBuffer](#oh_udsarraybuffer) [OH_UdsArrayBuffer](#oh_udsarraybuffer) | Defines a struct for the ArrayBuffer type.| -| typedef struct [OH_Utd](#oh_utd) [OH_Utd](#oh_utd) | Defines a struct for a Uniform Type Descriptor (UTD).| +| Name| Description| +| -------- | -------- | +| typedef enum [Udmf_Intention](#udmf_intention) [Udmf_Intention](#udmf_intention) | Defines an enum for UDMF data channels.| +| typedef enum [Udmf_ShareOption](#udmf_shareoption) [Udmf_ShareOption](#udmf_shareoption) | Defines an enum for the scopes of the uniform data to be used on a device.| +| typedef struct [OH_UdmfData](#oh_udmfdata) [OH_UdmfData](#oh_udmfdata) | Defines a struct for a uniform data object.| +| typedef struct [OH_UdmfRecord](#oh_udmfrecord) [OH_UdmfRecord](#oh_udmfrecord) | Defines a struct for a data record in a uniform data object.| +| typedef struct [OH_UdmfRecordProvider](#oh_udmfrecordprovider) [OH_UdmfRecordProvider](#oh_udmfrecordprovider) | Defines a struct for the data record provider in a uniform data object.| +| typedef struct [OH_UdmfProperty](#oh_udmfproperty) [OH_UdmfProperty](#oh_udmfproperty) | Defines a struct for a data record property in a uniform data object.| +| typedef void(\* [UdmfData_Finalize](#udmfdata_finalize)) (void \*context) | Defines a callback function used to release the context. This callback is invoked when the **OH_UdmfRecordProvider** instance is destroyed.| +| typedef void \*(\* [OH_UdmfRecordProvider_GetData](#oh_udmfrecordprovider_getdata)) (void \*context, const char \*type) | Defines a callback function used to obtain data by type. This callback will be invoked to return the data obtained from **OH_UdmfRecord**.| +| typedef enum [Udmf_ErrCode](#udmf_errcode) [Udmf_ErrCode](#udmf_errcode) | Defines an enum for error codes.| +| typedef struct [OH_UdsPlainText](#oh_udsplaintext) [OH_UdsPlainText](#oh_udsplaintext) | Defines a struct for the uniform data of the plain text type.| +| typedef struct [OH_UdsHyperlink](#oh_udshyperlink) [OH_UdsHyperlink](#oh_udshyperlink) | Defines a struct for the uniform data of the hyperlink type.| +| typedef struct [OH_UdsHtml](#oh_udshtml) [OH_UdsHtml](#oh_udshtml) | Defines a struct for the uniform data of the Hypertext Markup Language (HTML) type.| +| typedef struct [OH_UdsAppItem](#oh_udsappitem) [OH_UdsAppItem](#oh_udsappitem) | Defines a struct for the uniform data of the home screen icon type.| +| typedef struct [OH_UdsFileUri](#oh_udsfileuri) [OH_UdsFileUri](#oh_udsfileuri) | Defines a struct for the file URI type.| +| typedef struct [OH_UdsPixelMap](#oh_udspixelmap) [OH_UdsPixelMap](#oh_udspixelmap) | Defines a struct for the pixel map type.| +| typedef struct [OH_UdsArrayBuffer](#oh_udsarraybuffer) [OH_UdsArrayBuffer](#oh_udsarraybuffer) | Defines a struct for the ArrayBuffer type.| +| typedef struct [OH_Utd](#oh_utd) [OH_Utd](#oh_utd) | Defines a struct for a Uniform Type Descriptor (UTD).| | typedef struct [OH_UdsContentForm](#oh_udscontentform) [OH_UdsContentForm](#oh_udscontentform) | Defines a struct for the uniform data of the content widget type.| +| typedef enum [Udmf_ListenerStatus](#udmf_listenerstatus) [Udmf_ListenerStatus](#udmf_listenerstatus) | Defines an enum for the status codes returned when data is obtained asynchronously.| +| typedef enum [Udmf_FileConflictOptions](#udmf_fileconflictoptions) [Udmf_FileConflictOptions](#udmf_fileconflictoptions) | Defines an enum for the options used to resolve file copy conflicts.| +| typedef enum [Udmf_ProgressIndicator](#udmf_progressindicator) [Udmf_ProgressIndicator](#udmf_progressindicator) | Defines an enum for the progress indicator options.| +| typedef struct [OH_Udmf_ProgressInfo](#oh_udmf_progressinfo) [OH_Udmf_ProgressInfo](#oh_udmf_progressinfo) | Defines a struct for progress information.| +| typedef struct [OH_UdmfGetDataParams](#oh_udmfgetdataparams) [OH_UdmfGetDataParams](#oh_udmfgetdataparams) | Defines a struct for parameters used to obtain UDMF data asynchronously.| +| typedef void(\* [OH_Udmf_DataProgressListener](#oh_udmf_dataprogresslistener)) ([OH_Udmf_ProgressInfo](#oh_udmf_progressinfo) \*progressInfo, [OH_UdmfData](#oh_udmfdata) \*data) | Defines the callback used to return the data retrieval progress information and data obtained.
A null pointer is returned if the progress is not 100. The data obtained is returned only when the progress reaches 100.| ### Enums -| Name| Description| +| Name| Description| | -------- | -------- | | [Udmf_Intention](#udmf_intention) { UDMF_INTENTION_DRAG, UDMF_INTENTION_PASTEBOARD } | Enumerates the UDMF data channel types. | | [Udmf_ShareOption](#udmf_shareoption-1) { SHARE_OPTIONS_INVALID, SHARE_OPTIONS_IN_APP, SHARE_OPTIONS_CROSS_APP } | Enumerates the scopes of the uniform data to be used on a device. | -| [Udmf_ErrCode](#udmf_errcode-1) { UDMF_E_OK = 0, UDMF_ERR = 20400000, UDMF_E_INVALID_PARAM = (UDMF_ERR + 1) } | Enumerates the error codes.| +| [Udmf_ErrCode](#udmf_errcode-1) { UDMF_E_OK = 0, UDMF_ERR = 20400000, UDMF_E_INVALID_PARAM = (UDMF_ERR + 1) } | Enumerates the error codes.| +| [Udmf_ListenerStatus](#udmf_listenerstatus-1) {
UDMF_FINISHED = 0, UDMF_PROCESSING, UDMF_CANCELED, UDMF_INNER_ERROR = 200,
UDMF_INVALID_PARAMETERS, UDMF_DATA_NOT_FOUND, UDMF_SYNC_FAILED, UDMF_COPY_FILE_FAILED
} | Enumerates the status codes returned when data is obtained asynchronously.| +| [Udmf_FileConflictOptions](#udmf_fileconflictoptions-1) { UDMF_OVERWRITE = 0, UDMF_SKIP = 1 } | Enumerates the options used to resolve file copy conflicts.| +| [Udmf_ProgressIndicator](#udmf_progressindicator-1) { UDMF_NONE = 0, UDMF_DEFAULT = 1 } | Enumerates the progress indicator options.| ### Functions -| Name| Description| -| -------- | -------- | -| int [OH_UdmfRecord_AddContentForm](#oh_udmfrecord_addcontentform) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis, [OH_UdsContentForm](#oh_udscontentform) \*contentForm) | Adds data of the [OH_UdsContentForm](#oh_udscontentform) type to an [OH_UdmfRecord](#oh_udmfrecord) instance.| -| int [OH_UdmfRecord_GetContentForm](#oh_udmfrecord_getcontentform) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis, [OH_UdsContentForm](#oh_udscontentform) \*contentForm) | Obtains data of the [OH_UdsContentForm](#oh_udscontentform) type from an [OH_UdmfRecord](#oh_udmfrecord) instance.| -| [OH_UdsContentForm](#oh_udscontentform) \* [OH_UdsContentForm_Create](#oh_udscontentform_create) () | Creates an [OH_UdsContentForm](#oh_udscontentform) instance and a pointer to it.| -| void [OH_UdsContentForm_Destroy](#oh_udscontentform_destroy) ([OH_UdsContentForm](#oh_udscontentform) \*pThis) | Destroys an [OH_UdsContentForm](#oh_udscontentform) instance.| -| const char \* [OH_UdsContentForm_GetType](#oh_udscontentform_gettype) ([OH_UdsContentForm](#oh_udscontentform) \*pThis) | Obtains the type ID from an [OH_UdsContentForm](#oh_udscontentform) instance.| -| int [OH_UdsContentForm_GetThumbData](#oh_udscontentform_getthumbdata) ([OH_UdsContentForm](#oh_udscontentform) \*pThis, unsigned char \*\*thumbData, unsigned int \*len) | Obtains image data from an [OH_UdsContentForm](#oh_udscontentform) instance.| -| const char \* [OH_UdsContentForm_GetDescription](#oh_udscontentform_getdescription) ([OH_UdsContentForm](#oh_udscontentform) \*pThis) | Obtains the description from an [OH_UdsContentForm](#oh_udscontentform) instance.| -| const char \* [OH_UdsContentForm_GetTitle](#oh_udscontentform_gettitle) ([OH_UdsContentForm](#oh_udscontentform) \*pThis) | Obtains the title from an [OH_UdsContentForm](#oh_udscontentform) instance.| -| int [OH_UdsContentForm_GetAppIcon](#oh_udscontentform_getappicon) ([OH_UdsContentForm](#oh_udscontentform) \*pThis, unsigned char \*\*appIcon, unsigned int \*len) | Obtains the application icon data from an [OH_UdsContentForm](#oh_udscontentform) instance.| -| const char \* [OH_UdsContentForm_GetAppName](#oh_udscontentform_getappname) ([OH_UdsContentForm](#oh_udscontentform) \*pThis) | Obtains the application name from an [OH_UdsContentForm](#oh_udscontentform) instance.| -| const char \* [OH_UdsContentForm_GetLinkUri](#oh_udscontentform_getlinkuri) ([OH_UdsContentForm](#oh_udscontentform) \*pThis) | Obtains the hyperlink information from an [OH_UdsContentForm](#oh_udscontentform) instance.| -| int [OH_UdsContentForm_SetThumbData](#oh_udscontentform_setthumbdata) ([OH_UdsContentForm](#oh_udscontentform) \*pThis, const unsigned char \*thumbData, unsigned int len) | Sets the image data for an [OH_UdsContentForm](#oh_udscontentform) instance.| -| int [OH_UdsContentForm_SetDescription](#oh_udscontentform_setdescription) ([OH_UdsContentForm](#oh_udscontentform) \*pThis, const char \*description) | Sets the description for an [OH_UdsContentForm](#oh_udscontentform) instance.| -| int [OH_UdsContentForm_SetTitle](#oh_udscontentform_settitle) ([OH_UdsContentForm](#oh_udscontentform) \*pThis, const char \*title) | Sets the title for an [OH_UdsContentForm](#oh_udscontentform) instance.| -| int [OH_UdsContentForm_SetAppIcon](#oh_udscontentform_setappicon) ([OH_UdsContentForm](#oh_udscontentform) \*pThis, const unsigned char \*appIcon, unsigned int len) | Sets the application icon data for an [OH_UdsContentForm](#oh_udscontentform) instance.| -| int [OH_UdsContentForm_SetAppName](#oh_udscontentform_setappname) ([OH_UdsContentForm](#oh_udscontentform) \*pThis, const char \*appName) | Sets the application name for an [OH_UdsContentForm](#oh_udscontentform) instance.| -| int [OH_UdsContentForm_SetLinkUri](#oh_udscontentform_setlinkuri) ([OH_UdsContentForm](#oh_udscontentform) \*pThis, const char \*linkUri) | Sets the hyperlink data for an [OH_UdsContentForm](#oh_udscontentform) instance.| -| [OH_UdmfData](#oh_udmfdata) \* [OH_UdmfData_Create](#oh_udmfdata_create) () | Creates an [OH_UdmfData](#oh_udmfdata) instance and a pointer to it. If this pointer is no longer required, use [OH_UdmfData_Destroy](#oh_udmfdata_destroy) to destroy it. Otherwise, memory leaks may occur.| -| void [OH_UdmfData_Destroy](#oh_udmfdata_destroy) ([OH_UdmfData](#oh_udmfdata) \*pThis) | Destroys an [OH_UdmfData](#oh_udmfdata) instance.| -| int [OH_UdmfData_AddRecord](#oh_udmfdata_addrecord) ([OH_UdmfData](#oh_udmfdata) \*pThis, [OH_UdmfRecord](#oh_udmfrecord) \*record) | Adds an [OH_UdmfRecord](#oh_udmfrecord) to an [OH_UdmfData](#oh_udmfdata) instance.| -| bool [OH_UdmfData_HasType](#oh_udmfdata_hastype) ([OH_UdmfData](#oh_udmfdata) \*pThis, const char \*type) | Checks whether the specified type exists in an [OH_UdmfData](#oh_udmfdata) instance.| -| char \*\* [OH_UdmfData_GetTypes](#oh_udmfdata_gettypes) ([OH_UdmfData](#oh_udmfdata) \*pThis, unsigned int \*count) | Obtains all data types in an [OH_UdmfData](#oh_udmfdata) instance.| -| [OH_UdmfRecord](#oh_udmfrecord) \*\* [OH_UdmfData_GetRecords](#oh_udmfdata_getrecords) ([OH_UdmfData](#oh_udmfdata) \*pThis, unsigned int \*count) | Obtains all records contained in an [OH_UdmfData](#oh_udmfdata) instance.| -| [OH_UdmfRecordProvider](#oh_udmfrecordprovider) \* [OH_UdmfRecordProvider_Create](#oh_udmfrecordprovider_create) () | Creates an [OH_UdmfRecordProvider](#oh_udmfrecordprovider) instance and a pointer to it. If this pointer is no longer required, use [OH_UdmfRecordProvider_Destroy](#oh_udmfrecordprovider_destroy) to destroy it. Otherwise, memory leaks may occur.| -| int [OH_UdmfRecordProvider_Destroy](#oh_udmfrecordprovider_destroy) ([OH_UdmfRecordProvider](#oh_udmfrecordprovider) \*provider) | Destroys an [OH_UdmfRecordProvider](#oh_udmfrecordprovider) instance.| -| int [OH_UdmfRecordProvider_SetData](#oh_udmfrecordprovider_setdata) ([OH_UdmfRecordProvider](#oh_udmfrecordprovider) \*provider, void \*context, const [OH_UdmfRecordProvider_GetData](#oh_udmfrecordprovider_getdata) callback, const [UdmfData_Finalize](#udmfdata_finalize) finalize) | Sets a callback for an **OH_UdmfRecordProvider** instance to provide data.| -| [OH_UdmfRecord](#oh_udmfrecord) \* [OH_UdmfRecord_Create](#oh_udmfrecord_create) () | Creates an [OH_UdmfRecord](#oh_udmfrecord) instance and a pointer to it. If this pointer is no longer required, use [OH_UdmfRecord_Destroy](#oh_udmfrecord_destroy) to destroy it. Otherwise, memory leaks may occur.| -| void [OH_UdmfRecord_Destroy](#oh_udmfrecord_destroy) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis) | Destroys an [OH_UdmfRecord](#oh_udmfrecord) instance.| -| int [OH_UdmfRecord_AddGeneralEntry](#oh_udmfrecord_addgeneralentry) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis, const char \*typeId, unsigned char \*entry, unsigned int count) | Adds customized uniform data to an [OH_UdmfRecord](#oh_udmfrecord) instance.| -| int [OH_UdmfRecord_AddPlainText](#oh_udmfrecord_addplaintext) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis, [OH_UdsPlainText](#oh_udsplaintext) \*plainText) | Adds data of the [OH_UdsPlainText](#oh_udsplaintext) type to an [OH_UdmfRecord](#oh_udmfrecord) instance.| -| int [OH_UdmfRecord_AddHyperlink](#oh_udmfrecord_addhyperlink) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis, [OH_UdsHyperlink](#oh_udshyperlink) \*hyperlink) | Adds data of the hyperlink type [OH_UdsHyperlink](#oh_udshyperlink) type to an [OH_UdmfRecord](#oh_udmfrecord) instance.| -| int [OH_UdmfRecord_AddHtml](#oh_udmfrecord_addhtml) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis, [OH_UdsHtml](#oh_udshtml) \*html) | Adds data of the [OH_UdsHtml](#oh_udshtml) type to an [OH_UdmfRecord](#oh_udmfrecord) instance.| -| int [OH_UdmfRecord_AddAppItem](#oh_udmfrecord_addappitem) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis, [OH_UdsAppItem](#oh_udsappitem) \*appItem) | Adds data of the [OH_UdsAppItem](#oh_udsappitem) type to an [OH_UdmfRecord](#oh_udmfrecord) instance.| -| int [OH_UdmfRecord_AddFileUri](#oh_udmfrecord_addfileuri) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis, [OH_UdsFileUri](#oh_udsfileuri) \*fileUri) | Adds a data record of the [OH_UdsFileUri](#oh_udsfileuri) type to an [OH_UdmfRecord](#oh_udmfrecord) instance.| -| int [OH_UdmfRecord_AddPixelMap](#oh_udmfrecord_addpixelmap) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis, [OH_UdsPixelMap](#oh_udspixelmap) \*pixelMap) | Adds a data record of the [OH_UdsPixelMap](#oh_udspixelmap) type to an [OH_UdmfRecord](#oh_udmfrecord) instance.| -| int [OH_UdmfRecord_AddArrayBuffer](#oh_udmfrecord_addarraybuffer) ([OH_UdmfRecord](#oh_udmfrecord) \*record, const char \*type, [OH_UdsArrayBuffer](#oh_udsarraybuffer) \*buffer) | Adds a data record of the [OH_UdsArrayBuffer](#oh_udsarraybuffer) type to an [OH_UdmfRecord](#oh_udmfrecord) instance.| -| char \*\* [OH_UdmfRecord_GetTypes](#oh_udmfrecord_gettypes) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis, unsigned int \*count) | Obtains all data types in an [OH_UdmfRecord](#oh_udmfrecord) instance.| -| int [OH_UdmfRecord_GetGeneralEntry](#oh_udmfrecord_getgeneralentry) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis, const char \*typeId, unsigned char \*\*entry, unsigned int \*count) | Obtains the data of the specified type in an [OH_UdmfRecord](#oh_udmfrecord) instance.| -| int [OH_UdmfRecord_GetPlainText](#oh_udmfrecord_getplaintext) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis, [OH_UdsPlainText](#oh_udsplaintext) \*plainText) | Obtains [OH_UdsPlainText](#oh_udsplaintext) data from an [OH_UdmfRecord](#oh_udmfrecord) instance.| -| int [OH_UdmfRecord_GetHyperlink](#oh_udmfrecord_gethyperlink) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis, [OH_UdsHyperlink](#oh_udshyperlink) \*hyperlink) | Obtains [OH_UdsHyperlink](#oh_udshyperlink) data from an [OH_UdmfRecord](#oh_udmfrecord) instance.| -| int [OH_UdmfRecord_GetHtml](#oh_udmfrecord_gethtml) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis, [OH_UdsHtml](#oh_udshtml) \*html) | Obtains [OH_UdsHtml](#oh_udshtml) data from an [OH_UdmfRecord](#oh_udmfrecord) instance.| -| int [OH_UdmfRecord_GetAppItem](#oh_udmfrecord_getappitem) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis, [OH_UdsAppItem](#oh_udsappitem) \*appItem) | Obtains [OH_UdsAppItem](#oh_udsappitem) data from an [OH_UdmfRecord](#oh_udmfrecord) instance.| -| int [OH_UdmfRecord_SetProvider](#oh_udmfrecord_setprovider) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis, const char \*const \*types, unsigned int count, [OH_UdmfRecordProvider](#oh_udmfrecordprovider) \*provider) | Sets the [OH_UdmfRecordProvider](#oh_udmfrecordprovider) in an [OH_UdmfRecord](#oh_udmfrecord) instance.| -| int [OH_UdmfRecord_GetFileUri](#oh_udmfrecord_getfileuri) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis, [OH_UdsFileUri](#oh_udsfileuri) \*fileUri) | Obtains the [OH_UdsFileUri](#oh_udsfileuri) data from an [OH_UdmfRecord](#oh_udmfrecord) instance.| -| int [OH_UdmfRecord_GetPixelMap](#oh_udmfrecord_getpixelmap) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis, [OH_UdsPixelMap](#oh_udspixelmap) \*pixelMap) | Obtains the [OH_UdsPixelMap](#oh_udspixelmap) data from an [OH_UdmfRecord](#oh_udmfrecord) instance.| -| int [OH_UdmfRecord_GetArrayBuffer](#oh_udmfrecord_getarraybuffer) ([OH_UdmfRecord](#oh_udmfrecord) \*record, const char \*type, [OH_UdsArrayBuffer](#oh_udsarraybuffer) \*buffer) | Obtains the [OH_UdsArrayBuffer](#oh_udsarraybuffer) data from an [OH_UdmfRecord](#oh_udmfrecord) instance.| -| int [OH_UdmfData_GetPrimaryPlainText](#oh_udmfdata_getprimaryplaintext) ([OH_UdmfData](#oh_udmfdata) \*data, [OH_UdsPlainText](#oh_udsplaintext) \*plainText) | Obtains the first [OH_UdsPlainText](#oh_udsplaintext) data from an [OH_UdmfData](#oh_udmfdata) instance.| -| int [OH_UdmfData_GetPrimaryHtml](#oh_udmfdata_getprimaryhtml) ([OH_UdmfData](#oh_udmfdata) \*data, [OH_UdsHtml](#oh_udshtml) \*html) | Obtains the first [OH_UdsHtml](#oh_udshtml) data from an [OH_UdmfData](#oh_udmfdata) instance.| -| int [OH_UdmfData_GetRecordCount](#oh_udmfdata_getrecordcount) ([OH_UdmfData](#oh_udmfdata) \*data) | Obtains the number of data records contained in an [OH_UdmfData](#oh_udmfdata) instance.| -| [OH_UdmfRecord](#oh_udmfrecord) \* [OH_UdmfData_GetRecord](#oh_udmfdata_getrecord) ([OH_UdmfData](#oh_udmfdata) \*data, unsigned int index) | Obtains the specified data record from an [OH_UdmfData](#oh_udmfdata) instance.| +| Name| Description| +| -------- | -------- | +| int [OH_UdmfProgressInfo_GetProgress](#oh_udmfprogressinfo_getprogress) ([OH_Udmf_ProgressInfo](#oh_udmf_progressinfo) \*progressInfo) | Obtains the progress information from [OH_Udmf_ProgressInfo](#oh_udmf_progressinfo).| +| int [OH_UdmfProgressInfo_GetStatus](#oh_udmfprogressinfo_getstatus) ([OH_Udmf_ProgressInfo](#oh_udmf_progressinfo) \*progressInfo) | Obtains the status information from [OH_Udmf_ProgressInfo](#oh_udmf_progressinfo).| +| [OH_UdmfGetDataParams](#oh_udmfgetdataparams) \* [OH_UdmfGetDataParams_Create](#oh_udmfgetdataparams_create) () | Creates an [OH_UdmfGetDataParams](#oh_udmfgetdataparams) instance for asynchronously obtaining UDMF data.
If this pointer is no longer required, use [OH_UdmfGetDataParams_Destroy](#oh_udmfgetdataparams_destroy) to destroy it. Otherwise, memory leaks may occur.| +| void [OH_UdmfGetDataParams_Destroy](#oh_udmfgetdataparams_destroy) ([OH_UdmfGetDataParams](#oh_udmfgetdataparams) \*pThis) | Destroys an [OH_UdmfGetDataParams](#oh_udmfgetdataparams) instance.| +| void [OH_UdmfGetDataParams_SetDestUri](#oh_udmfgetdataparams_setdesturi) ([OH_UdmfGetDataParams](#oh_udmfgetdataparams) \*params, const char \*destUri) | Sets the destination directory in an [OH_UdmfGetDataParams](#oh_udmfgetdataparams) instance.
If the destination directory is set, data of the file type will be copied to the specified directory. The file type data obtained in the callback will be replaced with the URI of the destination directory.
If the destination directory is not specified, the file will not be copied. The file type data obtained in the callback is the URI of the source directory.
If the application involves complex file processing or files need to be copied to multiple directories, you are advised to leave this parameter unspecified and let the application to handle the file copy.| +| void [OH_UdmfGetDataParams_SetFileConflictOptions](#oh_udmfgetdataparams_setfileconflictoptions) ([OH_UdmfGetDataParams](#oh_udmfgetdataparams) \*params, const [Udmf_FileConflictOptions](#udmf_fileconflictoptions) options) | Sets the policy for resolving file conflicts in an [OH_UdmfGetDataParams](#oh_udmfgetdataparams) instance.| +| void [OH_UdmfGetDataParams_SetProgressIndicator](#oh_udmfgetdataparams_setprogressindicator) ([OH_UdmfGetDataParams](#oh_udmfgetdataparams) \*params, const [Udmf_ProgressIndicator](#udmf_progressindicator) progressIndicator) | Sets the progress indicator in an [OH_UdmfGetDataParams](#oh_udmfgetdataparams) instance.| +| void [OH_UdmfGetDataParams_SetDataProgressListener](#oh_udmfgetdataparams_setdataprogresslistener) ([OH_UdmfGetDataParams](#oh_udmfgetdataparams) \*params, const [OH_Udmf_DataProgressListener](#oh_udmf_dataprogresslistener) dataProgressListener) | Sets the callback used to return the data obtained in an [OH_UdmfGetDataParams](#oh_udmfgetdataparams) instance.| +| int [OH_UdmfRecord_AddContentForm](#oh_udmfrecord_addcontentform) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis, [OH_UdsContentForm](#oh_udscontentform) \*contentForm) | Adds data of the [OH_UdsContentForm](#oh_udscontentform) type to an [OH_UdmfRecord](#oh_udmfrecord) instance.| +| int [OH_UdmfRecord_GetContentForm](#oh_udmfrecord_getcontentform) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis, [OH_UdsContentForm](#oh_udscontentform) \*contentForm) | Obtains data of the [OH_UdsContentForm](#oh_udscontentform) type from an [OH_UdmfRecord](#oh_udmfrecord) instance.| +| [OH_UdsContentForm](#oh_udscontentform) \* [OH_UdsContentForm_Create](#oh_udscontentform_create) () | Creates an [OH_UdsContentForm](#oh_udscontentform) instance and a pointer to it.| +| void [OH_UdsContentForm_Destroy](#oh_udscontentform_destroy) ([OH_UdsContentForm](#oh_udscontentform) \*pThis) | Destroys an [OH_UdsContentForm](#oh_udscontentform) instance.| +| const char \* [OH_UdsContentForm_GetType](#oh_udscontentform_gettype) ([OH_UdsContentForm](#oh_udscontentform) \*pThis) | Obtains the type ID from an [OH_UdsContentForm](#oh_udscontentform) instance.| +| int [OH_UdsContentForm_GetThumbData](#oh_udscontentform_getthumbdata) ([OH_UdsContentForm](#oh_udscontentform) \*pThis, unsigned char \*\*thumbData, unsigned int \*len) | Obtains image data from an [OH_UdsContentForm](#oh_udscontentform) instance.| +| const char \* [OH_UdsContentForm_GetDescription](#oh_udscontentform_getdescription) ([OH_UdsContentForm](#oh_udscontentform) \*pThis) | Obtains the description from an [OH_UdsContentForm](#oh_udscontentform) instance.| +| const char \* [OH_UdsContentForm_GetTitle](#oh_udscontentform_gettitle) ([OH_UdsContentForm](#oh_udscontentform) \*pThis) | Obtains the title from an [OH_UdsContentForm](#oh_udscontentform) instance.| +| int [OH_UdsContentForm_GetAppIcon](#oh_udscontentform_getappicon) ([OH_UdsContentForm](#oh_udscontentform) \*pThis, unsigned char \*\*appIcon, unsigned int \*len) | Obtains the application icon data from an [OH_UdsContentForm](#oh_udscontentform) instance.| +| const char \* [OH_UdsContentForm_GetAppName](#oh_udscontentform_getappname) ([OH_UdsContentForm](#oh_udscontentform) \*pThis) | Obtains the application name from an [OH_UdsContentForm](#oh_udscontentform) instance.| +| const char \* [OH_UdsContentForm_GetLinkUri](#oh_udscontentform_getlinkuri) ([OH_UdsContentForm](#oh_udscontentform) \*pThis) | Obtains the hyperlink information from an [OH_UdsContentForm](#oh_udscontentform) instance.| +| int [OH_UdsContentForm_SetThumbData](#oh_udscontentform_setthumbdata) ([OH_UdsContentForm](#oh_udscontentform) \*pThis, const unsigned char \*thumbData, unsigned int len) | Sets the image data for an [OH_UdsContentForm](#oh_udscontentform) instance.| +| int [OH_UdsContentForm_SetDescription](#oh_udscontentform_setdescription) ([OH_UdsContentForm](#oh_udscontentform) \*pThis, const char \*description) | Sets the description for an [OH_UdsContentForm](#oh_udscontentform) instance.| +| int [OH_UdsContentForm_SetTitle](#oh_udscontentform_settitle) ([OH_UdsContentForm](#oh_udscontentform) \*pThis, const char \*title) | Sets the title for an [OH_UdsContentForm](#oh_udscontentform) instance.| +| int [OH_UdsContentForm_SetAppIcon](#oh_udscontentform_setappicon) ([OH_UdsContentForm](#oh_udscontentform) \*pThis, const unsigned char \*appIcon, unsigned int len) | Sets the application icon data for an [OH_UdsContentForm](#oh_udscontentform) instance.| +| int [OH_UdsContentForm_SetAppName](#oh_udscontentform_setappname) ([OH_UdsContentForm](#oh_udscontentform) \*pThis, const char \*appName) | Sets the application name for an [OH_UdsContentForm](#oh_udscontentform) instance.| +| int [OH_UdsContentForm_SetLinkUri](#oh_udscontentform_setlinkuri) ([OH_UdsContentForm](#oh_udscontentform) \*pThis, const char \*linkUri) | Sets the hyperlink data for an [OH_UdsContentForm](#oh_udscontentform) instance.| +| [OH_UdmfData](#oh_udmfdata) \* [OH_UdmfData_Create](#oh_udmfdata_create) () | Creates an [OH_UdmfData](#oh_udmfdata) instance and a pointer to it. If this pointer is no longer required, use [OH_UdmfData_Destroy](#oh_udmfdata_destroy) to destroy it. Otherwise, memory leaks may occur.| +| void [OH_UdmfData_Destroy](#oh_udmfdata_destroy) ([OH_UdmfData](#oh_udmfdata) \*pThis) | Destroys an [OH_UdmfData](#oh_udmfdata) instance.| +| int [OH_UdmfData_AddRecord](#oh_udmfdata_addrecord) ([OH_UdmfData](#oh_udmfdata) \*pThis, [OH_UdmfRecord](#oh_udmfrecord) \*record) | Adds an [OH_UdmfRecord](#oh_udmfrecord) to an [OH_UdmfData](#oh_udmfdata) instance.| +| bool [OH_UdmfData_HasType](#oh_udmfdata_hastype) ([OH_UdmfData](#oh_udmfdata) \*pThis, const char \*type) | Checks whether the specified type exists in an [OH_UdmfData](#oh_udmfdata) instance.| +| char \*\* [OH_UdmfData_GetTypes](#oh_udmfdata_gettypes) ([OH_UdmfData](#oh_udmfdata) \*pThis, unsigned int \*count) | Obtains all data types in an [OH_UdmfData](#oh_udmfdata) instance.| +| [OH_UdmfRecord](#oh_udmfrecord) \*\* [OH_UdmfData_GetRecords](#oh_udmfdata_getrecords) ([OH_UdmfData](#oh_udmfdata) \*pThis, unsigned int \*count) | Obtains all records contained in an [OH_UdmfData](#oh_udmfdata) instance.| +| [OH_UdmfRecordProvider](#oh_udmfrecordprovider) \* [OH_UdmfRecordProvider_Create](#oh_udmfrecordprovider_create) () | Creates an [OH_UdmfRecordProvider](#oh_udmfrecordprovider) instance and a pointer to it. If this pointer is no longer required, use [OH_UdmfRecordProvider_Destroy](#oh_udmfrecordprovider_destroy) to destroy it. Otherwise, memory leaks may occur.| +| int [OH_UdmfRecordProvider_Destroy](#oh_udmfrecordprovider_destroy) ([OH_UdmfRecordProvider](#oh_udmfrecordprovider) \*provider) | Destroys an [OH_UdmfRecordProvider](#oh_udmfrecordprovider) instance.| +| int [OH_UdmfRecordProvider_SetData](#oh_udmfrecordprovider_setdata) ([OH_UdmfRecordProvider](#oh_udmfrecordprovider) \*provider, void \*context, const [OH_UdmfRecordProvider_GetData](#oh_udmfrecordprovider_getdata) callback, const [UdmfData_Finalize](#udmfdata_finalize) finalize) | Sets a callback for an **OH_UdmfRecordProvider** instance to provide data.| +| [OH_UdmfRecord](#oh_udmfrecord) \* [OH_UdmfRecord_Create](#oh_udmfrecord_create) () | Creates an [OH_UdmfRecord](#oh_udmfrecord) instance and a pointer to it. If this pointer is no longer required, use [OH_UdmfRecord_Destroy](#oh_udmfrecord_destroy) to destroy it. Otherwise, memory leaks may occur.| +| void [OH_UdmfRecord_Destroy](#oh_udmfrecord_destroy) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis) | Destroys an [OH_UdmfRecord](#oh_udmfrecord) instance.| +| int [OH_UdmfRecord_AddGeneralEntry](#oh_udmfrecord_addgeneralentry) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis, const char \*typeId, unsigned char \*entry, unsigned int count) | Adds customized uniform data to an [OH_UdmfRecord](#oh_udmfrecord) instance.| +| int [OH_UdmfRecord_AddPlainText](#oh_udmfrecord_addplaintext) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis, [OH_UdsPlainText](#oh_udsplaintext) \*plainText) | Adds data of the [OH_UdsPlainText](#oh_udsplaintext) type to an [OH_UdmfRecord](#oh_udmfrecord) instance.| +| int [OH_UdmfRecord_AddHyperlink](#oh_udmfrecord_addhyperlink) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis, [OH_UdsHyperlink](#oh_udshyperlink) \*hyperlink) | Adds data of the hyperlink type [OH_UdsHyperlink](#oh_udshyperlink) type to an [OH_UdmfRecord](#oh_udmfrecord) instance.| +| int [OH_UdmfRecord_AddHtml](#oh_udmfrecord_addhtml) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis, [OH_UdsHtml](#oh_udshtml) \*html) | Adds data of the [OH_UdsHtml](#oh_udshtml) type to an [OH_UdmfRecord](#oh_udmfrecord) instance.| +| int [OH_UdmfRecord_AddAppItem](#oh_udmfrecord_addappitem) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis, [OH_UdsAppItem](#oh_udsappitem) \*appItem) | Adds data of the [OH_UdsAppItem](#oh_udsappitem) type to an [OH_UdmfRecord](#oh_udmfrecord) instance.| +| int [OH_UdmfRecord_AddFileUri](#oh_udmfrecord_addfileuri) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis, [OH_UdsFileUri](#oh_udsfileuri) \*fileUri) | Adds a data record of the [OH_UdsFileUri](#oh_udsfileuri) type to an [OH_UdmfRecord](#oh_udmfrecord) instance.| +| int [OH_UdmfRecord_AddPixelMap](#oh_udmfrecord_addpixelmap) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis, [OH_UdsPixelMap](#oh_udspixelmap) \*pixelMap) | Adds a data record of the [OH_UdsPixelMap](#oh_udspixelmap) type to an [OH_UdmfRecord](#oh_udmfrecord) instance.| +| int [OH_UdmfRecord_AddArrayBuffer](#oh_udmfrecord_addarraybuffer) ([OH_UdmfRecord](#oh_udmfrecord) \*record, const char \*type, [OH_UdsArrayBuffer](#oh_udsarraybuffer) \*buffer) | Adds a data record of the [OH_UdsArrayBuffer](#oh_udsarraybuffer) type to an [OH_UdmfRecord](#oh_udmfrecord) instance.| +| char \*\* [OH_UdmfRecord_GetTypes](#oh_udmfrecord_gettypes) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis, unsigned int \*count) | Obtains all data types in an [OH_UdmfRecord](#oh_udmfrecord) instance.| +| int [OH_UdmfRecord_GetGeneralEntry](#oh_udmfrecord_getgeneralentry) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis, const char \*typeId, unsigned char \*\*entry, unsigned int \*count) | Obtains the data of the specified type in an [OH_UdmfRecord](#oh_udmfrecord) instance.| +| int [OH_UdmfRecord_GetPlainText](#oh_udmfrecord_getplaintext) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis, [OH_UdsPlainText](#oh_udsplaintext) \*plainText) | Obtains [OH_UdsPlainText](#oh_udsplaintext) data from an [OH_UdmfRecord](#oh_udmfrecord) instance.| +| int [OH_UdmfRecord_GetHyperlink](#oh_udmfrecord_gethyperlink) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis, [OH_UdsHyperlink](#oh_udshyperlink) \*hyperlink) | Obtains [OH_UdsHyperlink](#oh_udshyperlink) data from an [OH_UdmfRecord](#oh_udmfrecord) instance.| +| int [OH_UdmfRecord_GetHtml](#oh_udmfrecord_gethtml) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis, [OH_UdsHtml](#oh_udshtml) \*html) | Obtains [OH_UdsHtml](#oh_udshtml) data from an [OH_UdmfRecord](#oh_udmfrecord) instance.| +| int [OH_UdmfRecord_GetAppItem](#oh_udmfrecord_getappitem) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis, [OH_UdsAppItem](#oh_udsappitem) \*appItem) | Obtains [OH_UdsAppItem](#oh_udsappitem) data from an [OH_UdmfRecord](#oh_udmfrecord) instance.| +| int [OH_UdmfRecord_SetProvider](#oh_udmfrecord_setprovider) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis, const char \*const \*types, unsigned int count, [OH_UdmfRecordProvider](#oh_udmfrecordprovider) \*provider) | Sets the [OH_UdmfRecordProvider](#oh_udmfrecordprovider) in an [OH_UdmfRecord](#oh_udmfrecord) instance.| +| int [OH_UdmfRecord_GetFileUri](#oh_udmfrecord_getfileuri) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis, [OH_UdsFileUri](#oh_udsfileuri) \*fileUri) | Obtains the [OH_UdsFileUri](#oh_udsfileuri) data from an [OH_UdmfRecord](#oh_udmfrecord) instance.| +| int [OH_UdmfRecord_GetPixelMap](#oh_udmfrecord_getpixelmap) ([OH_UdmfRecord](#oh_udmfrecord) \*pThis, [OH_UdsPixelMap](#oh_udspixelmap) \*pixelMap) | Obtains the [OH_UdsPixelMap](#oh_udspixelmap) data from an [OH_UdmfRecord](#oh_udmfrecord) instance.| +| int [OH_UdmfRecord_GetArrayBuffer](#oh_udmfrecord_getarraybuffer) ([OH_UdmfRecord](#oh_udmfrecord) \*record, const char \*type, [OH_UdsArrayBuffer](#oh_udsarraybuffer) \*buffer) | Obtains the [OH_UdsArrayBuffer](#oh_udsarraybuffer) data from an [OH_UdmfRecord](#oh_udmfrecord) instance.| +| int [OH_UdmfData_GetPrimaryPlainText](#oh_udmfdata_getprimaryplaintext) ([OH_UdmfData](#oh_udmfdata) \*data, [OH_UdsPlainText](#oh_udsplaintext) \*plainText) | Obtains the first [OH_UdsPlainText](#oh_udsplaintext) data from an [OH_UdmfData](#oh_udmfdata) instance.| +| int [OH_UdmfData_GetPrimaryHtml](#oh_udmfdata_getprimaryhtml) ([OH_UdmfData](#oh_udmfdata) \*data, [OH_UdsHtml](#oh_udshtml) \*html) | Obtains the first [OH_UdsHtml](#oh_udshtml) data from an [OH_UdmfData](#oh_udmfdata) instance.| +| int [OH_UdmfData_GetRecordCount](#oh_udmfdata_getrecordcount) ([OH_UdmfData](#oh_udmfdata) \*data) | Obtains the number of data records contained in an [OH_UdmfData](#oh_udmfdata) instance.| +| [OH_UdmfRecord](#oh_udmfrecord) \* [OH_UdmfData_GetRecord](#oh_udmfdata_getrecord) ([OH_UdmfData](#oh_udmfdata) \*data, unsigned int index) | Obtains the specified data record from an [OH_UdmfData](#oh_udmfdata) instance.| | bool [OH_UdmfData_IsLocal](#oh_udmfdata_islocal) ([OH_UdmfData](#oh_udmfdata) \*data) | Checks whether an [OH_UdmfData](#oh_udmfdata) instance is from the local device.| -| [OH_UdmfProperty](#oh_udmfproperty) \* [OH_UdmfProperty_Create](#oh_udmfproperty_create) ([OH_UdmfData](#oh_udmfdata) \*unifiedData) | Creates an [OH_UdmfProperty](#oh_udmfproperty) instance and a pointer to it. If this pointer is no longer required, use [OH_UdmfProperty_Destroy](#oh_udmfproperty_destroy) to destroy it. Otherwise, memory leaks may occur.| -| void [OH_UdmfProperty_Destroy](#oh_udmfproperty_destroy) ([OH_UdmfProperty](#oh_udmfproperty) \*pThis) | Destroys an [OH_UdmfProperty](#oh_udmfproperty) instance.| -| const char \* [OH_UdmfProperty_GetTag](#oh_udmfproperty_gettag) ([OH_UdmfProperty](#oh_udmfproperty) \*pThis) | Obtains the custom tag value from an [OH_UdmfProperty](#oh_udmfproperty) instance.| -| int64_t [OH_UdmfProperty_GetTimestamp](#oh_udmfproperty_gettimestamp) ([OH_UdmfProperty](#oh_udmfproperty) \*pThis) | Obtains the timestamp from an [OH_UdmfProperty](#oh_udmfproperty) instance.| -| [Udmf_ShareOption](#udmf_shareoption) [OH_UdmfProperty_GetShareOption](#oh_udmfproperty_getshareoption) ([OH_UdmfProperty](#oh_udmfproperty) \*pThis) | Obtains the share option from an [OH_UdmfProperty](#oh_udmfproperty) instance.| -| int [OH_UdmfProperty_GetExtrasIntParam](#oh_udmfproperty_getextrasintparam) ([OH_UdmfProperty](#oh_udmfproperty) \*pThis, const char \*key, int defaultValue) | Obtains the customized extra integer parameter from an [OH_UdmfProperty](#oh_udmfproperty) instance.| -| const char \* [OH_UdmfProperty_GetExtrasStringParam](#oh_udmfproperty_getextrasstringparam) ([OH_UdmfProperty](#oh_udmfproperty) \*pThis, const char \*key) | Obtains the customized extra string parameter from an [OH_UdmfProperty](#oh_udmfproperty) instance.| -| int [OH_UdmfProperty_SetTag](#oh_udmfproperty_settag) ([OH_UdmfProperty](#oh_udmfproperty) \*pThis, const char \*tag) | Sets the tag value for an [OH_UdmfProperty](#oh_udmfproperty) instance.| -| int [OH_UdmfProperty_SetShareOption](#oh_udmfproperty_setshareoption) ([OH_UdmfProperty](#oh_udmfproperty) \*pThis, [Udmf_ShareOption](#udmf_shareoption) option) | Sets the share option for an [OH_UdmfProperty](#oh_udmfproperty) instance.| -| int [OH_UdmfProperty_SetExtrasIntParam](#oh_udmfproperty_setextrasintparam) ([OH_UdmfProperty](#oh_udmfproperty) \*pThis, const char \*key, int param) | Sets the extra integer parameter for an [OH_UdmfProperty](#oh_udmfproperty) instance.| -| int [OH_UdmfProperty_SetExtrasStringParam](#oh_udmfproperty_setextrasstringparam) ([OH_UdmfProperty](#oh_udmfproperty) \*pThis, const char \*key, const char \*param) | Sets the extra string parameter for an [OH_UdmfProperty](#oh_udmfproperty) instance.| -| int [OH_Udmf_GetUnifiedData](#oh_udmf_getunifieddata) (const char \*key, [Udmf_Intention](#udmf_intention) intention, [OH_UdmfData](#oh_udmfdata) \*unifiedData) | Obtains an [OH_UdmfData](#oh_udmfdata) instance from the UDMF database.| -| int [OH_Udmf_SetUnifiedData](#oh_udmf_setunifieddata) ([Udmf_Intention](#udmf_intention) intention, [OH_UdmfData](#oh_udmfdata) \*unifiedData, char \*key, unsigned int keyLen) | Sets an [OH_UdmfData](#oh_udmfdata) instance in the UDMF database.| -| [OH_UdsPlainText](#oh_udsplaintext) \* [OH_UdsPlainText_Create](#oh_udsplaintext_create) () | Creates an [OH_UdsPlainText](#oh_udsplaintext) instance and a pointer to it. If this pointer is no longer required, use [OH_UdsPlainText_Destroy](#oh_udsplaintext_destroy) to destroy it. Otherwise, memory leaks may occur.| -| void [OH_UdsPlainText_Destroy](#oh_udsplaintext_destroy) ([OH_UdsPlainText](#oh_udsplaintext) \*pThis) | Destroys an [OH_UdsPlainText](#oh_udsplaintext) instance.| -| const char \* [OH_UdsPlainText_GetType](#oh_udsplaintext_gettype) ([OH_UdsPlainText](#oh_udsplaintext) \*pThis) | Obtains the type ID from an [OH_UdsPlainText](#oh_udsplaintext) instance.| -| const char \* [OH_UdsPlainText_GetContent](#oh_udsplaintext_getcontent) ([OH_UdsPlainText](#oh_udsplaintext) \*pThis) | Obtains the plaintext from an [OH_UdsPlainText](#oh_udsplaintext) instance.| -| const char \* [OH_UdsPlainText_GetAbstract](#oh_udsplaintext_getabstract) ([OH_UdsPlainText](#oh_udsplaintext) \*pThis) | Obtains the abstract from an [OH_UdsPlainText](#oh_udsplaintext) instance.| -| int [OH_UdsPlainText_SetContent](#oh_udsplaintext_setcontent) ([OH_UdsPlainText](#oh_udsplaintext) \*pThis, const char \*content) | Sets the plaintext for an [OH_UdsPlainText](#oh_udsplaintext) instance.| -| int [OH_UdsPlainText_SetAbstract](#oh_udsplaintext_setabstract) ([OH_UdsPlainText](#oh_udsplaintext) \*pThis, const char \*abstract) | Sets the abstract for an [OH_UdsPlainText](#oh_udsplaintext) instance.| -| [OH_UdsHyperlink](#oh_udshyperlink) \* [OH_UdsHyperlink_Create](#oh_udshyperlink_create) () | Creates an [OH_UdsHyperlink](#oh_udshyperlink) instance and a pointer to it. If this pointer is no longer required, use [OH_UdsHyperlink_Destroy](#oh_udshyperlink_destroy) to destroy it. Otherwise, memory leaks may occur.| -| void [OH_UdsHyperlink_Destroy](#oh_udshyperlink_destroy) ([OH_UdsHyperlink](#oh_udshyperlink) \*pThis) | Destroys an [OH_UdsHyperlink](#oh_udshyperlink) instance.| -| const char \* [OH_UdsHyperlink_GetType](#oh_udshyperlink_gettype) ([OH_UdsHyperlink](#oh_udshyperlink) \*pThis) | Obtains the type ID from an [OH_UdsHyperlink](#oh_udshyperlink) instance.| -| const char \* [OH_UdsHyperlink_GetUrl](#oh_udshyperlink_geturl) ([OH_UdsHyperlink](#oh_udshyperlink) \*pThis) | Obtains the URL from an [OH_UdsHyperlink](#oh_udshyperlink) instance.| -| const char \* [OH_UdsHyperlink_GetDescription](#oh_udshyperlink_getdescription) ([OH_UdsHyperlink](#oh_udshyperlink) \*pThis) | Obtains the description from an [OH_UdsHyperlink](#oh_udshyperlink) instance.| -| int [OH_UdsHyperlink_SetUrl](#oh_udshyperlink_seturl) ([OH_UdsHyperlink](#oh_udshyperlink) \*pThis, const char \*url) | Sets the URL for an [OH_UdsHyperlink](#oh_udshyperlink) instance.| -| int [OH_UdsHyperlink_SetDescription](#oh_udshyperlink_setdescription) ([OH_UdsHyperlink](#oh_udshyperlink) \*pThis, const char \*description) | Sets the description for an [OH_UdsHyperlink](#oh_udshyperlink) instance.| -| [OH_UdsHtml](#oh_udshtml) \* [OH_UdsHtml_Create](#oh_udshtml_create) () | Creates an [OH_UdsHtml](#oh_udshtml) instance and a pointer to it. If this pointer is no longer required, use [OH_UdsHtml_Destroy](#oh_udshtml_destroy) to destroy it. Otherwise, memory leaks may occur.| -| void [OH_UdsHtml_Destroy](#oh_udshtml_destroy) ([OH_UdsHtml](#oh_udshtml) \*pThis) | Destroys an [OH_UdsHtml](#oh_udshtml) instance.| -| const char \* [OH_UdsHtml_GetType](#oh_udshtml_gettype) ([OH_UdsHtml](#oh_udshtml) \*pThis) | Obtains the type ID from an [OH_UdsHtml](#oh_udshtml) instance.| -| const char \* [OH_UdsHtml_GetContent](#oh_udshtml_getcontent) ([OH_UdsHtml](#oh_udshtml) \*pThis) | Obtains the HTML content from an [OH_UdsHtml](#oh_udshtml) instance.| -| const char \* [OH_UdsHtml_GetPlainContent](#oh_udshtml_getplaincontent) ([OH_UdsHtml](#oh_udshtml) \*pThis) | Obtains the plaintext from an [OH_UdsHtml](#oh_udshtml) instance.| -| int [OH_UdsHtml_SetContent](#oh_udshtml_setcontent) ([OH_UdsHtml](#oh_udshtml) \*pThis, const char \*content) | Sets the HTML content for an [OH_UdsHtml](#oh_udshtml) instance.| -| int [OH_UdsHtml_SetPlainContent](#oh_udshtml_setplaincontent) ([OH_UdsHtml](#oh_udshtml) \*pThis, const char \*plainContent) | Sets the plaintext for an [OH_UdsHtml](#oh_udshtml) instance.| -| [OH_UdsAppItem](#oh_udsappitem) \* [OH_UdsAppItem_Create](#oh_udsappitem_create) () | Creates an [OH_UdsAppItem](#oh_udsappitem) instance and a pointer to it. If this pointer is no longer required, use [OH_UdsAppItem_Destroy](#oh_udsappitem_destroy) to destroy it. Otherwise, memory leaks may occur.| -| void [OH_UdsAppItem_Destroy](#oh_udsappitem_destroy) ([OH_UdsAppItem](#oh_udsappitem) \*pThis) | Destroys an [OH_UdsAppItem](#oh_udsappitem) instance.| -| const char \* [OH_UdsAppItem_GetType](#oh_udsappitem_gettype) ([OH_UdsAppItem](#oh_udsappitem) \*pThis) | Obtains the type ID from an [OH_UdsAppItem](#oh_udsappitem) instance.| -| const char \* [OH_UdsAppItem_GetId](#oh_udsappitem_getid) ([OH_UdsAppItem](#oh_udsappitem) \*pThis) | Obtains the application ID from an [OH_UdsAppItem](#oh_udsappitem) instance.| -| const char \* [OH_UdsAppItem_GetName](#oh_udsappitem_getname) ([OH_UdsAppItem](#oh_udsappitem) \*pThis) | Obtains the application name from an [OH_UdsAppItem](#oh_udsappitem) instance.| -| const char \* [OH_UdsAppItem_GetIconId](#oh_udsappitem_geticonid) ([OH_UdsAppItem](#oh_udsappitem) \*pThis) | Obtains the application icon ID from an [OH_UdsAppItem](#oh_udsappitem) instance.| -| const char \* [OH_UdsAppItem_GetLabelId](#oh_udsappitem_getlabelid) ([OH_UdsAppItem](#oh_udsappitem) \*pThis) | Obtains the application label ID from an [OH_UdsAppItem](#oh_udsappitem) instance.| -| const char \* [OH_UdsAppItem_GetBundleName](#oh_udsappitem_getbundlename) ([OH_UdsAppItem](#oh_udsappitem) \*pThis) | Obtains the bundle name from an [OH_UdsAppItem](#oh_udsappitem) instance.| -| const char \* [OH_UdsAppItem_GetAbilityName](#oh_udsappitem_getabilityname) ([OH_UdsAppItem](#oh_udsappitem) \*pThis) | Obtains the ability name from an [OH_UdsAppItem](#oh_udsappitem) instance.| -| int [OH_UdsAppItem_SetId](#oh_udsappitem_setid) ([OH_UdsAppItem](#oh_udsappitem) \*pThis, const char \*appId) | Sets the application ID for an [OH_UdsAppItem](#oh_udsappitem) instance.| -| int [OH_UdsAppItem_SetName](#oh_udsappitem_setname) ([OH_UdsAppItem](#oh_udsappitem) \*pThis, const char \*appName) | Sets the application name for an [OH_UdsAppItem](#oh_udsappitem) instance.| -| int [OH_UdsAppItem_SetIconId](#oh_udsappitem_seticonid) ([OH_UdsAppItem](#oh_udsappitem) \*pThis, const char \*appIconId) | Sets the application icon ID for an [OH_UdsAppItem](#oh_udsappitem) instance.| -| int [OH_UdsAppItem_SetLabelId](#oh_udsappitem_setlabelid) ([OH_UdsAppItem](#oh_udsappitem) \*pThis, const char \*appLabelId) | Sets the application label ID for an [OH_UdsAppItem](#oh_udsappitem) instance.| -| int [OH_UdsAppItem_SetBundleName](#oh_udsappitem_setbundlename) ([OH_UdsAppItem](#oh_udsappitem) \*pThis, const char \*bundleName) | Sets the bundle name for an [OH_UdsAppItem](#oh_udsappitem) instance.| -| int [OH_UdsAppItem_SetAbilityName](#oh_udsappitem_setabilityname) ([OH_UdsAppItem](#oh_udsappitem) \*pThis, const char \*abilityName) | Sets the ability name for an [OH_UdsAppItem](#oh_udsappitem) instance.| -| [OH_UdsFileUri](#oh_udsfileuri) \* [OH_UdsFileUri_Create](#oh_udsfileuri_create) () | Creates an [OH_UdsFileUri](#oh_udsfileuri) instance and a pointer to it. If this pointer is no longer required, use [OH_UdsFileUri_Destroy](#oh_udsfileuri_destroy) to destroy it. Otherwise, memory leaks may occur.| -| void [OH_UdsFileUri_Destroy](#oh_udsfileuri_destroy) ([OH_UdsFileUri](#oh_udsfileuri) \*pThis) | Destroys an [OH_UdsFileUri](#oh_udsfileuri) instance.| -| const char \* [OH_UdsFileUri_GetType](#oh_udsfileuri_gettype) ([OH_UdsFileUri](#oh_udsfileuri) \*pThis) | Obtains the type ID from an [OH_UdsFileUri](#oh_udsfileuri) instance.| -| const char \* [OH_UdsFileUri_GetFileUri](#oh_udsfileuri_getfileuri) ([OH_UdsFileUri](#oh_udsfileuri) \*pThis) | Obtains the file URI from an [OH_UdsFileUri](#oh_udsfileuri) instance.| -| const char \* [OH_UdsFileUri_GetFileType](#oh_udsfileuri_getfiletype) ([OH_UdsFileUri](#oh_udsfileuri) \*pThis) | Obtains the file type from an [OH_UdsFileUri](#oh_udsfileuri) instance.| -| int [OH_UdsFileUri_SetFileUri](#oh_udsfileuri_setfileuri) ([OH_UdsFileUri](#oh_udsfileuri) \*pThis, const char \*fileUri) | Sets the URI information for an [OH_UdsFileUri](#oh_udsfileuri) instance.| -| int [OH_UdsFileUri_SetFileType](#oh_udsfileuri_setfiletype) ([OH_UdsFileUri](#oh_udsfileuri) \*pThis, const char \*fileType) | Sets the file type for an [OH_UdsFileUri](#oh_udsfileuri) instance.| -| [OH_UdsPixelMap](#oh_udspixelmap) \* [OH_UdsPixelMap_Create](#oh_udspixelmap_create) () | Creates an [OH_UdsPixelMap](#oh_udspixelmap) instance and a pointer to it. If this pointer is no longer required, use [OH_UdsPixelMap_Destroy](#oh_udspixelmap_destroy) to destroy it. Otherwise, memory leaks may occur.| -| void [OH_UdsPixelMap_Destroy](#oh_udspixelmap_destroy) ([OH_UdsPixelMap](#oh_udspixelmap) \*pThis) | Destroys an [OH_UdsPixelMap](#oh_udspixelmap) instance.| -| const char \* [OH_UdsPixelMap_GetType](#oh_udspixelmap_gettype) ([OH_UdsPixelMap](#oh_udspixelmap) \*pThis) | Obtains the type ID from an [OH_UdsPixelMap](#oh_udspixelmap) instance.| -| void [OH_UdsPixelMap_GetPixelMap](#oh_udspixelmap_getpixelmap) ([OH_UdsPixelMap](#oh_udspixelmap) \*pThis, OH_PixelmapNative \*pixelmapNative) | Obtains the pointer to the **OH_PixelmapNative** instance from an [OH_UdsPixelMap](#oh_udspixelmap) instance.| -| int [OH_UdsPixelMap_SetPixelMap](#oh_udspixelmap_setpixelmap) ([OH_UdsPixelMap](#oh_udspixelmap) \*pThis, OH_PixelmapNative \*pixelmapNative) | Sets the pixel map content for an [OH_UdsPixelMap](#oh_udspixelmap) instance.| -| [OH_UdsArrayBuffer](#oh_udsarraybuffer) \* [OH_UdsArrayBuffer_Create](#oh_udsarraybuffer_create) () | Creates an [OH_UdsArrayBuffer](#oh_udsarraybuffer) instance and a pointer to it. If this pointer is no longer required, use [OH_UdsArrayBuffer_Destroy](#oh_udsarraybuffer_destroy) to destroy it. Otherwise, memory leaks may occur.| -| int [OH_UdsArrayBuffer_Destroy](#oh_udsarraybuffer_destroy) ([OH_UdsArrayBuffer](#oh_udsarraybuffer) \*buffer) | Destroys an [OH_UdsArrayBuffer](#oh_udsarraybuffer) instance.| -| int [OH_UdsArrayBuffer_SetData](#oh_udsarraybuffer_setdata) ([OH_UdsArrayBuffer](#oh_udsarraybuffer) \*buffer, unsigned char \*data, unsigned int len) | Sets an [OH_UdsArrayBuffer](#oh_udsarraybuffer) instance.| -| int [OH_UdsArrayBuffer_GetData](#oh_udsarraybuffer_getdata) ([OH_UdsArrayBuffer](#oh_udsarraybuffer) \*buffer, unsigned char \*\*data, unsigned int \*len) | Obtains the custom ArrayBuffer data from an [OH_UdsArrayBuffer](#oh_udsarraybuffer) instance.| -| [OH_Utd](#oh_utd) \* [OH_Utd_Create](#oh_utd_create) (const char \*typeId) | Creates an [OH_Utd](#oh_utd) instance and a pointer to it.| -| void [OH_Utd_Destroy](#oh_utd_destroy) ([OH_Utd](#oh_utd) \*pThis) | Destroys an [OH_Utd](#oh_utd) instance.| -| const char \* [OH_Utd_GetTypeId](#oh_utd_gettypeid) ([OH_Utd](#oh_utd) \*pThis) | Obtains the type ID from an [OH_Utd](#oh_utd) instance.| -| const char \* [OH_Utd_GetDescription](#oh_utd_getdescription) ([OH_Utd](#oh_utd) \*pThis) | Obtains the description from an [OH_Utd](#oh_utd) instance.| -| const char \* [OH_Utd_GetReferenceUrl](#oh_utd_getreferenceurl) ([OH_Utd](#oh_utd) \*pThis) | Obtains the URL from an [OH_Utd](#oh_utd) instance.| -| const char \* [OH_Utd_GetIconFile](#oh_utd_geticonfile) ([OH_Utd](#oh_utd) \*pThis) | Obtains the path of the default icon file from an [OH_Utd](#oh_utd) instance.| -| const char \*\* [OH_Utd_GetBelongingToTypes](#oh_utd_getbelongingtotypes) ([OH_Utd](#oh_utd) \*pThis, unsigned int \*count) | Obtains the relationships between the data in an [OH_Utd](#oh_utd) instance.| -| const char \*\* [OH_Utd_GetFilenameExtensions](#oh_utd_getfilenameextensions) ([OH_Utd](#oh_utd) \*pThis, unsigned int \*count) | Obtains the file name extensions associated with an [OH_Utd](#oh_utd) instance.| -| const char \*\* [OH_Utd_GetMimeTypes](#oh_utd_getmimetypes) ([OH_Utd](#oh_utd) \*pThis, unsigned int \*count) | Obtains the MIME types associated with an [OH_Utd](#oh_utd) instance.| -| const char \*\* [OH_Utd_GetTypesByFilenameExtension](#oh_utd_gettypesbyfilenameextension) (const char \*extension, unsigned int \*count) | Obtains the uniform data types based on the file name extensions.| -| const char \*\* [OH_Utd_GetTypesByMimeType](#oh_utd_gettypesbymimetype) (const char \*mimeType, unsigned int \*count) | Obtains the uniform data types based on the MIME types.| -| bool [OH_Utd_BelongsTo](#oh_utd_belongsto) (const char \*srcTypeId, const char \*destTypeId) | Checks whether a UTD belongs to the target UTD.| -| bool [OH_Utd_IsLower](#oh_utd_islower) (const char \*srcTypeId, const char \*destTypeId) | Checks whether a UTD is a lower-level type of the target UTD. For example, **TYPE_SCRIPT** is a lower-level type of **SOURCE_CODE**, and **TYPE_SCRIPT** and **SOURCE_CODE** are lower-level types of **PLAIN_TEXT**.| -| bool [OH_Utd_IsHigher](#oh_utd_ishigher) (const char \*srcTypeId, const char \*destTypeId) | Checks whether a UTD is a higher-level type of the target UTD. For example, **SOURCE_CODE** is a higher-level type of **TYPE_SCRIPT**, and **PLAIN_TEXT** is a higher-level type of **SOURCE_CODE** and **TYPE_SCRIPT**.| -| bool [OH_Utd_Equals](#oh_utd_equals) ([OH_Utd](#oh_utd) \*utd1, [OH_Utd](#oh_utd) \*utd2) | Checks whether two UTDs are the same.| -| void [OH_Utd_DestroyStringList](#oh_utd_destroystringlist) (const char \*\*list, unsigned int count) | Destroys a UTD string list.| +| [OH_UdmfProperty](#oh_udmfproperty) \* [OH_UdmfProperty_Create](#oh_udmfproperty_create) ([OH_UdmfData](#oh_udmfdata) \*unifiedData) | Creates an [OH_UdmfProperty](#oh_udmfproperty) instance and a pointer to it. If this pointer is no longer required, use [OH_UdmfProperty_Destroy](#oh_udmfproperty_destroy) to destroy it. Otherwise, memory leaks may occur.| +| void [OH_UdmfProperty_Destroy](#oh_udmfproperty_destroy) ([OH_UdmfProperty](#oh_udmfproperty) \*pThis) | Destroys an [OH_UdmfProperty](#oh_udmfproperty) instance.| +| const char \* [OH_UdmfProperty_GetTag](#oh_udmfproperty_gettag) ([OH_UdmfProperty](#oh_udmfproperty) \*pThis) | Obtains the custom tag value from an [OH_UdmfProperty](#oh_udmfproperty) instance.| +| int64_t [OH_UdmfProperty_GetTimestamp](#oh_udmfproperty_gettimestamp) ([OH_UdmfProperty](#oh_udmfproperty) \*pThis) | Obtains the timestamp from an [OH_UdmfProperty](#oh_udmfproperty) instance.| +| [Udmf_ShareOption](#udmf_shareoption) [OH_UdmfProperty_GetShareOption](#oh_udmfproperty_getshareoption) ([OH_UdmfProperty](#oh_udmfproperty) \*pThis) | Obtains the share option from an [OH_UdmfProperty](#oh_udmfproperty) instance.| +| int [OH_UdmfProperty_GetExtrasIntParam](#oh_udmfproperty_getextrasintparam) ([OH_UdmfProperty](#oh_udmfproperty) \*pThis, const char \*key, int defaultValue) | Obtains the customized extra integer parameter from an [OH_UdmfProperty](#oh_udmfproperty) instance.| +| const char \* [OH_UdmfProperty_GetExtrasStringParam](#oh_udmfproperty_getextrasstringparam) ([OH_UdmfProperty](#oh_udmfproperty) \*pThis, const char \*key) | Obtains the customized extra string parameter from an [OH_UdmfProperty](#oh_udmfproperty) instance.| +| int [OH_UdmfProperty_SetTag](#oh_udmfproperty_settag) ([OH_UdmfProperty](#oh_udmfproperty) \*pThis, const char \*tag) | Sets the tag value for an [OH_UdmfProperty](#oh_udmfproperty) instance.| +| int [OH_UdmfProperty_SetShareOption](#oh_udmfproperty_setshareoption) ([OH_UdmfProperty](#oh_udmfproperty) \*pThis, [Udmf_ShareOption](#udmf_shareoption) option) | Sets the share option for an [OH_UdmfProperty](#oh_udmfproperty) instance.| +| int [OH_UdmfProperty_SetExtrasIntParam](#oh_udmfproperty_setextrasintparam) ([OH_UdmfProperty](#oh_udmfproperty) \*pThis, const char \*key, int param) | Sets the extra integer parameter for an [OH_UdmfProperty](#oh_udmfproperty) instance.| +| int [OH_UdmfProperty_SetExtrasStringParam](#oh_udmfproperty_setextrasstringparam) ([OH_UdmfProperty](#oh_udmfproperty) \*pThis, const char \*key, const char \*param) | Sets the extra string parameter for an [OH_UdmfProperty](#oh_udmfproperty) instance.| +| int [OH_Udmf_GetUnifiedData](#oh_udmf_getunifieddata) (const char \*key, [Udmf_Intention](#udmf_intention) intention, [OH_UdmfData](#oh_udmfdata) \*unifiedData) | Obtains an [OH_UdmfData](#oh_udmfdata) instance from the UDMF database.| +| int [OH_Udmf_SetUnifiedData](#oh_udmf_setunifieddata) ([Udmf_Intention](#udmf_intention) intention, [OH_UdmfData](#oh_udmfdata) \*unifiedData, char \*key, unsigned int keyLen) | Sets an [OH_UdmfData](#oh_udmfdata) instance in the UDMF database.| +| [OH_UdsPlainText](#oh_udsplaintext) \* [OH_UdsPlainText_Create](#oh_udsplaintext_create) () | Creates an [OH_UdsPlainText](#oh_udsplaintext) instance and a pointer to it. If this pointer is no longer required, use [OH_UdsPlainText_Destroy](#oh_udsplaintext_destroy) to destroy it. Otherwise, memory leaks may occur.| +| void [OH_UdsPlainText_Destroy](#oh_udsplaintext_destroy) ([OH_UdsPlainText](#oh_udsplaintext) \*pThis) | Destroys an [OH_UdsPlainText](#oh_udsplaintext) instance.| +| const char \* [OH_UdsPlainText_GetType](#oh_udsplaintext_gettype) ([OH_UdsPlainText](#oh_udsplaintext) \*pThis) | Obtains the type ID from an [OH_UdsPlainText](#oh_udsplaintext) instance.| +| const char \* [OH_UdsPlainText_GetContent](#oh_udsplaintext_getcontent) ([OH_UdsPlainText](#oh_udsplaintext) \*pThis) | Obtains the plaintext from an [OH_UdsPlainText](#oh_udsplaintext) instance.| +| const char \* [OH_UdsPlainText_GetAbstract](#oh_udsplaintext_getabstract) ([OH_UdsPlainText](#oh_udsplaintext) \*pThis) | Obtains the abstract from an [OH_UdsPlainText](#oh_udsplaintext) instance.| +| int [OH_UdsPlainText_SetContent](#oh_udsplaintext_setcontent) ([OH_UdsPlainText](#oh_udsplaintext) \*pThis, const char \*content) | Sets the plaintext for an [OH_UdsPlainText](#oh_udsplaintext) instance.| +| int [OH_UdsPlainText_SetAbstract](#oh_udsplaintext_setabstract) ([OH_UdsPlainText](#oh_udsplaintext) \*pThis, const char \*abstract) | Sets the abstract for an [OH_UdsPlainText](#oh_udsplaintext) instance.| +| [OH_UdsHyperlink](#oh_udshyperlink) \* [OH_UdsHyperlink_Create](#oh_udshyperlink_create) () | Creates an [OH_UdsHyperlink](#oh_udshyperlink) instance and a pointer to it. If this pointer is no longer required, use [OH_UdsHyperlink_Destroy](#oh_udshyperlink_destroy) to destroy it. Otherwise, memory leaks may occur.| +| void [OH_UdsHyperlink_Destroy](#oh_udshyperlink_destroy) ([OH_UdsHyperlink](#oh_udshyperlink) \*pThis) | Destroys an [OH_UdsHyperlink](#oh_udshyperlink) instance.| +| const char \* [OH_UdsHyperlink_GetType](#oh_udshyperlink_gettype) ([OH_UdsHyperlink](#oh_udshyperlink) \*pThis) | Obtains the type ID from an [OH_UdsHyperlink](#oh_udshyperlink) instance.| +| const char \* [OH_UdsHyperlink_GetUrl](#oh_udshyperlink_geturl) ([OH_UdsHyperlink](#oh_udshyperlink) \*pThis) | Obtains the URL from an [OH_UdsHyperlink](#oh_udshyperlink) instance.| +| const char \* [OH_UdsHyperlink_GetDescription](#oh_udshyperlink_getdescription) ([OH_UdsHyperlink](#oh_udshyperlink) \*pThis) | Obtains the description from an [OH_UdsHyperlink](#oh_udshyperlink) instance.| +| int [OH_UdsHyperlink_SetUrl](#oh_udshyperlink_seturl) ([OH_UdsHyperlink](#oh_udshyperlink) \*pThis, const char \*url) | Sets the URL for an [OH_UdsHyperlink](#oh_udshyperlink) instance.| +| int [OH_UdsHyperlink_SetDescription](#oh_udshyperlink_setdescription) ([OH_UdsHyperlink](#oh_udshyperlink) \*pThis, const char \*description) | Sets the description for an [OH_UdsHyperlink](#oh_udshyperlink) instance.| +| [OH_UdsHtml](#oh_udshtml) \* [OH_UdsHtml_Create](#oh_udshtml_create) () | Creates an [OH_UdsHtml](#oh_udshtml) instance and a pointer to it. If this pointer is no longer required, use [OH_UdsHtml_Destroy](#oh_udshtml_destroy) to destroy it. Otherwise, memory leaks may occur.| +| void [OH_UdsHtml_Destroy](#oh_udshtml_destroy) ([OH_UdsHtml](#oh_udshtml) \*pThis) | Destroys an [OH_UdsHtml](#oh_udshtml) instance.| +| const char \* [OH_UdsHtml_GetType](#oh_udshtml_gettype) ([OH_UdsHtml](#oh_udshtml) \*pThis) | Obtains the type ID from an [OH_UdsHtml](#oh_udshtml) instance.| +| const char \* [OH_UdsHtml_GetContent](#oh_udshtml_getcontent) ([OH_UdsHtml](#oh_udshtml) \*pThis) | Obtains the HTML content from an [OH_UdsHtml](#oh_udshtml) instance.| +| const char \* [OH_UdsHtml_GetPlainContent](#oh_udshtml_getplaincontent) ([OH_UdsHtml](#oh_udshtml) \*pThis) | Obtains the plaintext from an [OH_UdsHtml](#oh_udshtml) instance.| +| int [OH_UdsHtml_SetContent](#oh_udshtml_setcontent) ([OH_UdsHtml](#oh_udshtml) \*pThis, const char \*content) | Sets the HTML content for an [OH_UdsHtml](#oh_udshtml) instance.| +| int [OH_UdsHtml_SetPlainContent](#oh_udshtml_setplaincontent) ([OH_UdsHtml](#oh_udshtml) \*pThis, const char \*plainContent) | Sets the plaintext for an [OH_UdsHtml](#oh_udshtml) instance.| +| [OH_UdsAppItem](#oh_udsappitem) \* [OH_UdsAppItem_Create](#oh_udsappitem_create) () | Creates an [OH_UdsAppItem](#oh_udsappitem) instance and a pointer to it. If this pointer is no longer required, use [OH_UdsAppItem_Destroy](#oh_udsappitem_destroy) to destroy it. Otherwise, memory leaks may occur.| +| void [OH_UdsAppItem_Destroy](#oh_udsappitem_destroy) ([OH_UdsAppItem](#oh_udsappitem) \*pThis) | Destroys an [OH_UdsAppItem](#oh_udsappitem) instance.| +| const char \* [OH_UdsAppItem_GetType](#oh_udsappitem_gettype) ([OH_UdsAppItem](#oh_udsappitem) \*pThis) | Obtains the type ID from an [OH_UdsAppItem](#oh_udsappitem) instance.| +| const char \* [OH_UdsAppItem_GetId](#oh_udsappitem_getid) ([OH_UdsAppItem](#oh_udsappitem) \*pThis) | Obtains the application ID from an [OH_UdsAppItem](#oh_udsappitem) instance.| +| const char \* [OH_UdsAppItem_GetName](#oh_udsappitem_getname) ([OH_UdsAppItem](#oh_udsappitem) \*pThis) | Obtains the application name from an [OH_UdsAppItem](#oh_udsappitem) instance.| +| const char \* [OH_UdsAppItem_GetIconId](#oh_udsappitem_geticonid) ([OH_UdsAppItem](#oh_udsappitem) \*pThis) | Obtains the application icon ID from an [OH_UdsAppItem](#oh_udsappitem) instance.| +| const char \* [OH_UdsAppItem_GetLabelId](#oh_udsappitem_getlabelid) ([OH_UdsAppItem](#oh_udsappitem) \*pThis) | Obtains the application label ID from an [OH_UdsAppItem](#oh_udsappitem) instance.| +| const char \* [OH_UdsAppItem_GetBundleName](#oh_udsappitem_getbundlename) ([OH_UdsAppItem](#oh_udsappitem) \*pThis) | Obtains the bundle name from an [OH_UdsAppItem](#oh_udsappitem) instance.| +| const char \* [OH_UdsAppItem_GetAbilityName](#oh_udsappitem_getabilityname) ([OH_UdsAppItem](#oh_udsappitem) \*pThis) | Obtains the ability name from an [OH_UdsAppItem](#oh_udsappitem) instance.| +| int [OH_UdsAppItem_SetId](#oh_udsappitem_setid) ([OH_UdsAppItem](#oh_udsappitem) \*pThis, const char \*appId) | Sets the application ID for an [OH_UdsAppItem](#oh_udsappitem) instance.| +| int [OH_UdsAppItem_SetName](#oh_udsappitem_setname) ([OH_UdsAppItem](#oh_udsappitem) \*pThis, const char \*appName) | Sets the application name for an [OH_UdsAppItem](#oh_udsappitem) instance.| +| int [OH_UdsAppItem_SetIconId](#oh_udsappitem_seticonid) ([OH_UdsAppItem](#oh_udsappitem) \*pThis, const char \*appIconId) | Sets the application icon ID for an [OH_UdsAppItem](#oh_udsappitem) instance.| +| int [OH_UdsAppItem_SetLabelId](#oh_udsappitem_setlabelid) ([OH_UdsAppItem](#oh_udsappitem) \*pThis, const char \*appLabelId) | Sets the application label ID for an [OH_UdsAppItem](#oh_udsappitem) instance.| +| int [OH_UdsAppItem_SetBundleName](#oh_udsappitem_setbundlename) ([OH_UdsAppItem](#oh_udsappitem) \*pThis, const char \*bundleName) | Sets the bundle name for an [OH_UdsAppItem](#oh_udsappitem) instance.| +| int [OH_UdsAppItem_SetAbilityName](#oh_udsappitem_setabilityname) ([OH_UdsAppItem](#oh_udsappitem) \*pThis, const char \*abilityName) | Sets the ability name for an [OH_UdsAppItem](#oh_udsappitem) instance.| +| [OH_UdsFileUri](#oh_udsfileuri) \* [OH_UdsFileUri_Create](#oh_udsfileuri_create) () | Creates an [OH_UdsFileUri](#oh_udsfileuri) instance and a pointer to it. If this pointer is no longer required, use [OH_UdsFileUri_Destroy](#oh_udsfileuri_destroy) to destroy it. Otherwise, memory leaks may occur.| +| void [OH_UdsFileUri_Destroy](#oh_udsfileuri_destroy) ([OH_UdsFileUri](#oh_udsfileuri) \*pThis) | Destroys an [OH_UdsFileUri](#oh_udsfileuri) instance.| +| const char \* [OH_UdsFileUri_GetType](#oh_udsfileuri_gettype) ([OH_UdsFileUri](#oh_udsfileuri) \*pThis) | Obtains the type ID from an [OH_UdsFileUri](#oh_udsfileuri) instance.| +| const char \* [OH_UdsFileUri_GetFileUri](#oh_udsfileuri_getfileuri) ([OH_UdsFileUri](#oh_udsfileuri) \*pThis) | Obtains the file URI from an [OH_UdsFileUri](#oh_udsfileuri) instance.| +| const char \* [OH_UdsFileUri_GetFileType](#oh_udsfileuri_getfiletype) ([OH_UdsFileUri](#oh_udsfileuri) \*pThis) | Obtains the file type from an [OH_UdsFileUri](#oh_udsfileuri) instance.| +| int [OH_UdsFileUri_SetFileUri](#oh_udsfileuri_setfileuri) ([OH_UdsFileUri](#oh_udsfileuri) \*pThis, const char \*fileUri) | Sets the URI information for an [OH_UdsFileUri](#oh_udsfileuri) instance.| +| int [OH_UdsFileUri_SetFileType](#oh_udsfileuri_setfiletype) ([OH_UdsFileUri](#oh_udsfileuri) \*pThis, const char \*fileType) | Sets the file type for an [OH_UdsFileUri](#oh_udsfileuri) instance.| +| [OH_UdsPixelMap](#oh_udspixelmap) \* [OH_UdsPixelMap_Create](#oh_udspixelmap_create) () | Creates an [OH_UdsPixelMap](#oh_udspixelmap) instance and a pointer to it. If this pointer is no longer required, use [OH_UdsPixelMap_Destroy](#oh_udspixelmap_destroy) to destroy it. Otherwise, memory leaks may occur.| +| void [OH_UdsPixelMap_Destroy](#oh_udspixelmap_destroy) ([OH_UdsPixelMap](#oh_udspixelmap) \*pThis) | Destroys an [OH_UdsPixelMap](#oh_udspixelmap) instance.| +| const char \* [OH_UdsPixelMap_GetType](#oh_udspixelmap_gettype) ([OH_UdsPixelMap](#oh_udspixelmap) \*pThis) | Obtains the type ID from an [OH_UdsPixelMap](#oh_udspixelmap) instance.| +| void [OH_UdsPixelMap_GetPixelMap](#oh_udspixelmap_getpixelmap) ([OH_UdsPixelMap](#oh_udspixelmap) \*pThis, OH_PixelmapNative \*pixelmapNative) | Obtains the pointer to the **OH_PixelmapNative** instance from an [OH_UdsPixelMap](#oh_udspixelmap) instance.| +| int [OH_UdsPixelMap_SetPixelMap](#oh_udspixelmap_setpixelmap) ([OH_UdsPixelMap](#oh_udspixelmap) \*pThis, OH_PixelmapNative \*pixelmapNative) | Sets the pixel map content for an [OH_UdsPixelMap](#oh_udspixelmap) instance.| +| [OH_UdsArrayBuffer](#oh_udsarraybuffer) \* [OH_UdsArrayBuffer_Create](#oh_udsarraybuffer_create) () | Creates an [OH_UdsArrayBuffer](#oh_udsarraybuffer) instance and a pointer to it. If this pointer is no longer required, use [OH_UdsArrayBuffer_Destroy](#oh_udsarraybuffer_destroy) to destroy it. Otherwise, memory leaks may occur.| +| int [OH_UdsArrayBuffer_Destroy](#oh_udsarraybuffer_destroy) ([OH_UdsArrayBuffer](#oh_udsarraybuffer) \*buffer) | Destroys an [OH_UdsArrayBuffer](#oh_udsarraybuffer) instance.| +| int [OH_UdsArrayBuffer_SetData](#oh_udsarraybuffer_setdata) ([OH_UdsArrayBuffer](#oh_udsarraybuffer) \*buffer, unsigned char \*data, unsigned int len) | Sets an [OH_UdsArrayBuffer](#oh_udsarraybuffer) instance.| +| int [OH_UdsArrayBuffer_GetData](#oh_udsarraybuffer_getdata) ([OH_UdsArrayBuffer](#oh_udsarraybuffer) \*buffer, unsigned char \*\*data, unsigned int \*len) | Obtains the custom ArrayBuffer data from an [OH_UdsArrayBuffer](#oh_udsarraybuffer) instance.| +| [OH_Utd](#oh_utd) \* [OH_Utd_Create](#oh_utd_create) (const char \*typeId) | Creates an [OH_Utd](#oh_utd) instance and a pointer to it.| +| void [OH_Utd_Destroy](#oh_utd_destroy) ([OH_Utd](#oh_utd) \*pThis) | Destroys an [OH_Utd](#oh_utd) instance.| +| const char \* [OH_Utd_GetTypeId](#oh_utd_gettypeid) ([OH_Utd](#oh_utd) \*pThis) | Obtains the type ID from an [OH_Utd](#oh_utd) instance.| +| const char \* [OH_Utd_GetDescription](#oh_utd_getdescription) ([OH_Utd](#oh_utd) \*pThis) | Obtains the description from an [OH_Utd](#oh_utd) instance.| +| const char \* [OH_Utd_GetReferenceUrl](#oh_utd_getreferenceurl) ([OH_Utd](#oh_utd) \*pThis) | Obtains the URL from an [OH_Utd](#oh_utd) instance.| +| const char \* [OH_Utd_GetIconFile](#oh_utd_geticonfile) ([OH_Utd](#oh_utd) \*pThis) | Obtains the path of the default icon file from an [OH_Utd](#oh_utd) instance.| +| const char \*\* [OH_Utd_GetBelongingToTypes](#oh_utd_getbelongingtotypes) ([OH_Utd](#oh_utd) \*pThis, unsigned int \*count) | Obtains the relationships between the data in an [OH_Utd](#oh_utd) instance.| +| const char \*\* [OH_Utd_GetFilenameExtensions](#oh_utd_getfilenameextensions) ([OH_Utd](#oh_utd) \*pThis, unsigned int \*count) | Obtains the file name extensions associated with an [OH_Utd](#oh_utd) instance.| +| const char \*\* [OH_Utd_GetMimeTypes](#oh_utd_getmimetypes) ([OH_Utd](#oh_utd) \*pThis, unsigned int \*count) | Obtains the MIME types associated with an [OH_Utd](#oh_utd) instance.| +| const char \*\* [OH_Utd_GetTypesByFilenameExtension](#oh_utd_gettypesbyfilenameextension) (const char \*extension, unsigned int \*count) | Obtains the uniform data types based on the file name extensions.| +| const char \*\* [OH_Utd_GetTypesByMimeType](#oh_utd_gettypesbymimetype) (const char \*mimeType, unsigned int \*count) | Obtains the uniform data types based on the MIME types.| +| bool [OH_Utd_BelongsTo](#oh_utd_belongsto) (const char \*srcTypeId, const char \*destTypeId) | Checks whether a UTD belongs to the target UTD.| +| bool [OH_Utd_IsLower](#oh_utd_islower) (const char \*srcTypeId, const char \*destTypeId) | Checks whether a UTD is a lower-level type of the target UTD. For example, **TYPE_SCRIPT** is a lower-level type of **SOURCE_CODE**, and **TYPE_SCRIPT** and **SOURCE_CODE** are lower-level types of **PLAIN_TEXT**.| +| bool [OH_Utd_IsHigher](#oh_utd_ishigher) (const char \*srcTypeId, const char \*destTypeId) | Checks whether a UTD is a higher-level type of the target UTD. For example, **SOURCE_CODE** is a higher-level type of **TYPE_SCRIPT**, and **PLAIN_TEXT** is a higher-level type of **SOURCE_CODE** and **TYPE_SCRIPT**.| +| bool [OH_Utd_Equals](#oh_utd_equals) ([OH_Utd](#oh_utd) \*utd1, [OH_Utd](#oh_utd) \*utd2) | Checks whether two UTDs are the same.| +| void [OH_Utd_DestroyStringList](#oh_utd_destroystringlist) (const char \*\*list, unsigned int count) | Destroys a UTD string list.| ## Macro Description @@ -2134,6 +2151,90 @@ Indicates ZIP, which belongs to **ARCHIVE**. ## Type Description + +### Udmf_ListenerStatus + +``` +typedef enum Udmf_ListenerStatusUdmf_ListenerStatus +``` + +**Description** + +Defines an enum for the status codes returned when data is obtained asynchronously. + +**Since**: 15 + + +### Udmf_FileConflictOptions + +``` +typedef enum Udmf_FileConflictOptionsUdmf_FileConflictOptions +``` + +**Description** + +Defines an enum for the options used to resolve file copy conflicts. + +**Since**: 15 + +### Udmf_ProgressIndicator + +``` +typedef enum Udmf_ProgressIndicatorUdmf_ProgressIndicator +``` + +**Description** + +Defines an enum for progress indicator options. You can use the default progress indicator as required. + +**Since**: 15 + +### OH_Udmf_ProgressInfo + +``` +typedef struct OH_Udmf_ProgressInfoOH_Udmf_ProgressInfo +``` + +**Description** + +Defines a struct for progress information. + +**Since**: 15 + +### OH_UdmfGetDataParams + +``` +typedef struct OH_UdmfGetDataParamsOH_UdmfGetDataParams +``` + +**Description** + +Defines a struct for the parameters used to obtain UDMF data asynchronously. + +**Since**: 15 + +### OH_Udmf_DataProgressListener + +``` +typedef void(* OH_Udmf_DataProgressListener) (OH_Udmf_ProgressInfo *progressInfo, OH_UdmfData *data) +``` + +**Description** + +Defines the callback used to return the data retrieval progress information and data obtained. + +A null pointer is returned if the progress is not 100. The data obtained is returned only when the progress reaches 100. + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| progressInfo | Progress information obtained.| +| data | Data obtained.| + + ### OH_UdsContentForm ``` @@ -2212,10 +2313,10 @@ Defines a callback function used to obtain data by type. This callback will be i **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| context | Pointer to the context set by [OH_UdmfRecordProvider_SetData](#oh_udmfrecordprovider_setdata).| -| type | Pointer to the type of the data to obtain. For details, see [udmf_meta.h](udmf__meta_8h.md).| +| context | Pointer to the context set by [OH_UdmfRecordProvider_SetData](#oh_udmfrecordprovider_setdata).| +| type | Pointer to the type of the data to obtain. For details, see [udmf_meta.h](udmf__meta_8h.md).| **Returns** @@ -2379,13 +2480,69 @@ Defines a callback function used to release the context. This callback is invoke **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| context | Pointer to the context to release.| +| context | Pointer to the context to release.| ## Enum Description +### Udmf_ListenerStatus + +``` +enum Udmf_ListenerStatus +``` + +**Description** + +Enumerates the status codes returned when data is obtained asynchronously. + +**Since**: 15 + +| Value| Description| +| -------- | -------- | +| UDMF_FINISHED | Data is obtained successfully.| +| UDMF_PROCESSING | The data retrieval task is being processed.| +| UDMF_CANCELED | The data retrieval task is canceled.| +| UDMF_INNER_ERROR | An internal error occurs.| +| UDMF_INVALID_PARAMETERS | Invalid parameters are detected.| +| UDMF_DATA_NOT_FOUND | No data is obtained.| +| UDMF_SYNC_FAILED | An error occurs during data synchronization.| +| UDMF_COPY_FILE_FAILED | Failed to copy the file.| + +### Udmf_FileConflictOptions + +``` +enum Udmf_FileConflictOptions +``` + +**Description** + +Enumerates the options used to resolve file copy conflicts. + +**Since**: 15 + +| Value| Description| +| -------- | -------- | +| UDMF_OVERWRITE | Overwrite the file with the same name in the destination directory. This is the default value.| +| UDMF_SKIP | Skip the file if there is a file with the same name in the destination directory.| + +### Udmf_ProgressIndicator + +``` +enum Udmf_ProgressIndicator +``` + +**Description** + +Enumerates the progress indicator options. You can use the default progress indicator as required. + +**Since**: 15 + +| Value| Description| +| -------- | -------- | +| UDMF_NONE | Do not use the default progress indicator.| +| UDMF_DEFAULT | Use the default progress indicator. If data is obtained within 500 ms, the default progress bar is not started.| ### Udmf_ErrCode @@ -2399,11 +2556,11 @@ Enumerates the error codes. **Since**: 12 -| Value| Description| +| Value| Description| | -------- | -------- | -| UDMF_E_OK | The operation is successful.| -| UDMF_ERR | Common error.| -| UDMF_E_INVALID_PARAM | Invalid parameter.| +| UDMF_E_OK | The operation is successful.| +| UDMF_ERR | Common error.| +| UDMF_E_INVALID_PARAM | Invalid parameter.| ### Udmf_Intention @@ -2418,10 +2575,10 @@ Enumerates the UDMF data channel types. **Since**: 12 -| Value| Description| +| Value| Description| | -------- | -------- | -| UDMF_INTENTION_DRAG | Channel for dragging data.| -| UDMF_INTENTION_PASTEBOARD | Channel for clipboard data.| +| UDMF_INTENTION_DRAG | Channel for dragging data.| +| UDMF_INTENTION_PASTEBOARD | Channel for clipboard data.| ### Udmf_ShareOption @@ -2436,15 +2593,218 @@ Enumerates the scopes of the uniform data to be used on a device. **Since**: 12 -| Value| Description| +| Value| Description| | -------- | -------- | -| SHARE_OPTIONS_INVALID | Invalid use.| -| SHARE_OPTIONS_IN_APP | Use the uniform data only in the same application of a device.| -| SHARE_OPTIONS_CROSS_APP | Use the uniform data across applications of a device.| +| SHARE_OPTIONS_INVALID | Invalid use.| +| SHARE_OPTIONS_IN_APP | Use the uniform data only in the same application of a device.| +| SHARE_OPTIONS_CROSS_APP | Use the uniform data across applications of a device.| ## Function Description +### OH_UdmfProgressInfo_GetProgress() + +``` +int OH_UdmfProgressInfo_GetProgress (OH_Udmf_ProgressInfo* progressInfo) +``` + +**Description** + +Obtains the progress information from [OH_Udmf_ProgressInfo](#oh_udmf_progressinfo). + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| progressInfo | [OH_Udmf_ProgressInfo](#oh_udmf_progressinfo).| + +**Returns** + +Progress obtained, in percentage. + +**See** + +[OH_Udmf_ProgressInfo](#oh_udmf_progressinfo) + +### OH_UdmfProgressInfo_GetStatus() + +``` +int OH_UdmfProgressInfo_GetStatus (OH_Udmf_ProgressInfo* progressInfo) +``` + +**Description** + +Obtains the status information from [OH_Udmf_ProgressInfo](#oh_udmf_progressinfo). + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| progressInfo | [OH_Udmf_ProgressInfo](#oh_udmf_progressinfo).| + +**Returns** + +Status information obtained. + +**See** + +[OH_Udmf_ProgressInfo](#oh_udmf_progressinfo) + +[Udmf_ListenerStatus](#udmf_listenerstatus) + +### OH_UdmfGetDataParams_Create() + +``` +OH_UdmfGetDataParams* OH_UdmfGetDataParams_Create () +``` + +### OH_UdmfGetDataParams_Destroy() + +``` +void OH_UdmfGetDataParams_Destroy (OH_UdmfGetDataParams* pThis) +``` + +**Description** + +Destroys an [OH_UdmfGetDataParams](#oh_udmfgetdataparams) instance. + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| pThis | Pointer to the [OH_UdmfGetDataParams](#oh_udmfgetdataparams) instance to destroy.| + +**See** + +[OH_UdmfGetDataParams](#oh_udmfgetdataparams) + + +**Description** + +Creates an [OH_UdmfGetDataParams](#oh_udmfgetdataparams) instance for asynchronously obtaining UDMF data. + +If this pointer is no longer required, use [OH_UdmfGetDataParams_Destroy](#oh_udmfgetdataparams_destroy) to destroy it. Otherwise, memory leaks may occur. + +**Since**: 15 + +**Returns** + +Returns a pointer to the [OH_UdmfGetDataParams](#oh_udmfgetdataparams) instance created if the operation is successful; returns **nullptr** otherwise. + +**See** + +[OH_UdmfGetDataParams](#oh_udmfgetdataparams) + +### OH_UdmfGetDataParams_SetDestUri() + +``` +void OH_UdmfGetDataParams_SetDestUri (OH_UdmfGetDataParams* params, const char* destUri ) +``` + +**Description** + +Sets the destination directory in an [OH_UdmfGetDataParams](#oh_udmfgetdataparams) instance. + +If the destination directory is set, data of the file type will be copied to the specified directory. The file type data obtained in the callback will be replaced with the URI of the destination directory. + +If the destination directory is not specified, the file will not be copied. The file type data obtained in the callback is the URI of the source directory. + +If the application involves complex file processing or files need to be copied to multiple directories, you are advised to leave this parameter unspecified and let the application to handle the file copy. + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| params | Pointer to the target [OH_UdmfGetDataParams](#oh_udmfgetdataparams) instance.| +| destUri | Destination directory to set.| + +**See** + +[OH_UdmfGetDataParams](#oh_udmfgetdataparams) + +### OH_UdmfGetDataParams_SetFileConflictOptions() + +``` +void OH_UdmfGetDataParams_SetFileConflictOptions (OH_UdmfGetDataParams* params, const Udmf_FileConflictOptions options ) +``` + +**Description** + +Sets the policy for resolving file conflicts in an [OH_UdmfGetDataParams](#oh_udmfgetdataparams) instance. + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| params | Pointer to the target [OH_UdmfGetDataParams](#oh_udmfgetdataparams) instance.| +| options | Policy to set.| + +**See** + +[OH_UdmfGetDataParams](#oh_udmfgetdataparams) + +[Udmf_FileConflictOptions](#udmf_fileconflictoptions) + +### OH_UdmfGetDataParams_SetProgressIndicator() + +``` +void OH_UdmfGetDataParams_SetProgressIndicator (OH_UdmfGetDataParams* params, const Udmf_ProgressIndicator progressIndicator ) +``` + +**Description** + +Sets the progress indicator in an [OH_UdmfGetDataParams](#oh_udmfgetdataparams) instance. + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| params | Pointer to the target [OH_UdmfGetDataParams](#oh_udmfgetdataparams) instance.| +| progressIndicator | Whether to use the default progress indicator.| + +**See** + +[OH_UdmfGetDataParams](#oh_udmfgetdataparams) + +[Udmf_ProgressIndicator](#udmf_progressindicator) + +### OH_UdmfGetDataParams_SetDataProgressListener() + +``` +void OH_UdmfGetDataParams_SetDataProgressListener (OH_UdmfGetDataParams* params, const OH_Udmf_DataProgressListener dataProgressListener ) +``` + +**Description** + +Sets the callback used to return the data obtained in an [OH_UdmfGetDataParams](#oh_udmfgetdataparams) instance. + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| params | Pointer to the target [OH_UdmfGetDataParams](#oh_udmfgetdataparams) instance.| +| dataProgressListener | Callback to set.| + +**See** + +[OH_UdmfGetDataParams](#oh_udmfgetdataparams) + +[OH_Udmf_DataProgressListener](#oh_udmf_dataprogresslistener) + ### OH_UdmfRecord_AddContentForm() ``` @@ -2459,14 +2819,14 @@ Adds data of the [OH_UdsContentForm](#oh_udscontentform) type to an [OH_UdmfReco **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| -| contentForm | Pointer to the [OH_UdsContentForm](#oh_udscontentform) instance to add.| +| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| +| contentForm | Pointer to the [OH_UdsContentForm](#oh_udscontentform) instance to add.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -2491,14 +2851,14 @@ Obtains data of the [OH_UdsContentForm](#oh_udscontentform) type from an [OH_Udm **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| -| contentForm | Pointer to the [OH_UdsContentForm](#oh_udscontentform) instance obtained.| +| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| +| contentForm | Pointer to the [OH_UdsContentForm](#oh_udscontentform) instance obtained.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -2544,9 +2904,9 @@ Destroys an [OH_UdsContentForm](#oh_udscontentform) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdsContentForm](#oh_udscontentform) instance to destroy.| +| pThis | Pointer to the [OH_UdsContentForm](#oh_udscontentform) instance to destroy.| **See** @@ -2567,15 +2927,15 @@ Obtains the application icon data from an [OH_UdsContentForm](#oh_udscontentform **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the target [OH_UdsContentForm](#oh_udscontentform) instance.| -| appIcon | Double pointer to the binary application icon data obtained.| -| len | Pointer to the length of the binary application icon data obtained.| +| pThis | Pointer to the target [OH_UdsContentForm](#oh_udscontentform) instance.| +| appIcon | Double pointer to the binary application icon data obtained.| +| len | Pointer to the length of the binary application icon data obtained.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. Returns **UDMF_ERR** if an internal system error occurs. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in.
Returns **UDMF_ERR** if an internal system error occurs. **See** @@ -2598,9 +2958,9 @@ Obtains the application name from an [OH_UdsContentForm](#oh_udscontentform) ins **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the target [OH_UdsContentForm](#oh_udscontentform) instance.| +| pThis | Pointer to the target [OH_UdsContentForm](#oh_udscontentform) instance.| **Returns** @@ -2625,9 +2985,9 @@ Obtains the description from an [OH_UdsContentForm](#oh_udscontentform) instance **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the target [OH_UdsContentForm](#oh_udscontentform) instance.| +| pThis | Pointer to the target [OH_UdsContentForm](#oh_udscontentform) instance.| **Returns** @@ -2652,9 +3012,9 @@ Obtains the hyperlink information from an [OH_UdsContentForm](#oh_udscontentform **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the target [OH_UdsContentForm](#oh_udscontentform) instance.| +| pThis | Pointer to the target [OH_UdsContentForm](#oh_udscontentform) instance.| **Returns** @@ -2679,15 +3039,15 @@ Obtains image data from an [OH_UdsContentForm](#oh_udscontentform) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the target [OH_UdsContentForm](#oh_udscontentform) instance.| -| thumbData | Double pointer to the binary image data obtained.| -| len | Pointer to the length of the binary image data obtained.| +| pThis | Pointer to the target [OH_UdsContentForm](#oh_udscontentform) instance.| +| thumbData | Double pointer to the binary image data obtained.| +| len | Pointer to the length of the binary image data obtained.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. Returns **UDMF_ERR** if an internal system error occurs. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in.
Returns **UDMF_ERR** if an internal system error occurs. **See** @@ -2710,9 +3070,9 @@ Obtains the title from an [OH_UdsContentForm](#oh_udscontentform) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the target [OH_UdsContentForm](#oh_udscontentform) instance.| +| pThis | Pointer to the target [OH_UdsContentForm](#oh_udscontentform) instance.| **Returns** @@ -2737,9 +3097,9 @@ Obtains the type ID from an [OH_UdsContentForm](#oh_udscontentform) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the target [OH_UdsContentForm](#oh_udscontentform) instance.| +| pThis | Pointer to the target [OH_UdsContentForm](#oh_udscontentform) instance.| **Returns** @@ -2764,15 +3124,15 @@ Sets the application icon data for an [OH_UdsContentForm](#oh_udscontentform) in **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the target [OH_UdsContentForm](#oh_udscontentform) instance.| -| appIcon | Pointer to the binary application icon data to set.| -| len | Length of the binary application icon data to set.| +| pThis | Pointer to the target [OH_UdsContentForm](#oh_udscontentform) instance.| +| appIcon | Pointer to the binary application icon data to set.| +| len | Length of the binary application icon data to set.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -2795,14 +3155,14 @@ Sets the application name for an [OH_UdsContentForm](#oh_udscontentform) instanc **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the target [OH_UdsContentForm](#oh_udscontentform) instance.| -| appName | Pointer to the application name to set.| +| pThis | Pointer to the target [OH_UdsContentForm](#oh_udscontentform) instance.| +| appName | Pointer to the application name to set.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -2825,14 +3185,14 @@ Sets the description for an [OH_UdsContentForm](#oh_udscontentform) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the target [OH_UdsContentForm](#oh_udscontentform) instance.| -| description | Pointer to the description to set.| +| pThis | Pointer to the target [OH_UdsContentForm](#oh_udscontentform) instance.| +| description | Pointer to the description to set.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -2855,14 +3215,14 @@ Sets the hyperlink data for an [OH_UdsContentForm](#oh_udscontentform) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the target [OH_UdsContentForm](#oh_udscontentform) instance.| -| linkUri | Pointer to the hyperlink to set.| +| pThis | Pointer to the target [OH_UdsContentForm](#oh_udscontentform) instance.| +| linkUri | Pointer to the hyperlink to set.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -2885,15 +3245,15 @@ Sets the image data for an [OH_UdsContentForm](#oh_udscontentform) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the target [OH_UdsContentForm](#oh_udscontentform) instance.| -| thumbData | Pointer to the binary image data to set.| -| len | Length of the binary image data to set.| +| pThis | Pointer to the target [OH_UdsContentForm](#oh_udscontentform) instance.| +| thumbData | Pointer to the binary image data to set.| +| len | Length of the binary image data to set.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -2916,14 +3276,14 @@ Sets the title for an [OH_UdsContentForm](#oh_udscontentform) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the target [OH_UdsContentForm](#oh_udscontentform) instance.| -| title | Pointer to the title to set.| +| pThis | Pointer to the target [OH_UdsContentForm](#oh_udscontentform) instance.| +| title | Pointer to the title to set.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -2946,15 +3306,15 @@ Obtains an [OH_UdmfData](#oh_udmfdata) instance from the UDMF database. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| key | Pointer to the identifier of the data in the database.| -| intention | Type of the data channel. For details, see [Udmf_Intent]( #udmf_intention).| -| unifiedData | Pointer to the [OH_UdmfData](#oh_udmfdata) obtained.| +| key | Pointer to the identifier of the data in the database.| +| intention | Type of the data channel. For details, see [Udmf_Intent]( #udmf_intention).| +| unifiedData | Pointer to the [OH_UdmfData](#oh_udmfdata) obtained.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -2979,16 +3339,16 @@ Sets an [OH_UdmfData](#oh_udmfdata) instance in the UDMF database. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| intention | Type of the data channel. For details, see [Udmf_Intent]( #udmf_intention).| -| unifiedData | Pointer to the [OH_UdmfData](#oh_udmfdata) data to set.| -| key | Pointer to the key that uniquely identifies the data in the database.| -| keyLen | Length of the key. The memory size must be greater than or equal to 512 bytes.| +| intention | Type of the data channel. For details, see [Udmf_Intent]( #udmf_intention).| +| unifiedData | Pointer to the [OH_UdmfData](#oh_udmfdata) data to set.| +| key | Pointer to the key that uniquely identifies the data in the database.| +| keyLen | Length of the key. The memory size must be greater than or equal to 512 bytes.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -3013,14 +3373,14 @@ Adds an [OH_UdmfRecord](#oh_udmfrecord) to an [OH_UdmfData](#oh_udmfdata) instan **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdmfData](#oh_udmfdata) instance.| -| record | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| +| pThis | Pointer to the [OH_UdmfData](#oh_udmfdata) instance.| +| record | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -3064,9 +3424,9 @@ Destroys an [OH_UdmfData](#oh_udmfdata) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdmfData](#oh_udmfdata) instance to destroy.| +| pThis | Pointer to the [OH_UdmfData](#oh_udmfdata) instance to destroy.| **See** @@ -3087,14 +3447,14 @@ Obtains the first [OH_UdsHtml](#oh_udshtml) data from an [OH_UdmfData](#oh_udmfd **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| data | Pointer to the [OH_UdmfData](#oh_udmfdata) instance.| -| html | Pointer to the [OH_UdsHtml](#oh_udshtml) data obtained.| +| data | Pointer to the [OH_UdmfData](#oh_udmfdata) instance.| +| html | Pointer to the [OH_UdsHtml](#oh_udshtml) data obtained.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -3119,14 +3479,14 @@ Obtains the first [OH_UdsPlainText](#oh_udsplaintext) data from an [OH_UdmfData] **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| data | Pointer to the [OH_UdmfData](#oh_udmfdata) instance.| -| plainText | Pointer to the [OH_UdsPlainText](#oh_udsplaintext) data obtained.| +| data | Pointer to the [OH_UdmfData](#oh_udmfdata) instance.| +| plainText | Pointer to the [OH_UdsPlainText](#oh_udsplaintext) data obtained.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -3151,10 +3511,10 @@ Obtains the specified data record from an [OH_UdmfData](#oh_udmfdata) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| data | Pointer to the [OH_UdmfData](#oh_udmfdata) instance.| -| index | Index of the [OH_UdmfRecord]( #oh_udmfrecord) in the OH_UdmfData]( #oh_udmfdata) instance.| +| data | Pointer to the [OH_UdmfData](#oh_udmfdata) instance.| +| index | Index of the [OH_UdmfRecord]( #oh_udmfrecord) in the OH_UdmfData]( #oh_udmfdata) instance.| **Returns** @@ -3177,7 +3537,7 @@ Obtains the number of data records contained in an [OH_UdmfData](#oh_udmfdata) i **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | | data | Pointer to the target [OH_UdmfData](#oh_udmfdata) instance. | @@ -3196,10 +3556,10 @@ Obtains all records contained in an [OH_UdmfData](#oh_udmfdata) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the target [OH_UdmfData](#oh_udmfdata) instance.| -| count | Pointer to the number of records obtained.| +| pThis | Pointer to the target [OH_UdmfData](#oh_udmfdata) instance.| +| count | Pointer to the number of records obtained.| **Returns** @@ -3226,10 +3586,10 @@ Obtains all data types in an [OH_UdmfData](#oh_udmfdata) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the target [OH_UdmfData](#oh_udmfdata) instance.| -| count | Pointer to the number of data types obtained.| +| pThis | Pointer to the target [OH_UdmfData](#oh_udmfdata) instance.| +| count | Pointer to the number of data types obtained.| **Returns** @@ -3254,10 +3614,10 @@ Checks whether the specified type exists in an [OH_UdmfData](#oh_udmfdata) insta **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the target [OH_UdmfData](#oh_udmfdata) instance.| -| type | Pointer to the type to check.| +| pThis | Pointer to the target [OH_UdmfData](#oh_udmfdata) instance.| +| type | Pointer to the type to check.| **Returns** @@ -3282,9 +3642,9 @@ Checks whether an [OH_UdmfData](#oh_udmfdata) instance is from the local device. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| data | Pointer to the [OH_UdmfData](#oh_udmfdata) instance.| +| data | Pointer to the [OH_UdmfData](#oh_udmfdata) instance.| **Returns** @@ -3309,9 +3669,9 @@ Creates an [OH_UdmfProperty](#oh_udmfproperty) instance and a pointer to it. If **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| unifiedData | Pointer to the [OH_UdmfData](#oh_udmfdata) instance.| +| unifiedData | Pointer to the [OH_UdmfData](#oh_udmfdata) instance.| **Returns** @@ -3338,9 +3698,9 @@ Destroys an [OH_UdmfProperty](#oh_udmfproperty) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdmfProperty](#oh_udmfproperty) instance to destroy.| +| pThis | Pointer to the [OH_UdmfProperty](#oh_udmfproperty) instance to destroy.| **See** @@ -3361,11 +3721,11 @@ Obtains the customized extra integer parameter from an [OH_UdmfProperty](#oh_udm **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdmfProperty](#oh_udmfproperty) instance.| -| key | Pointer to the key of the parameter to obtain.| -| defaultValue | Default value to be returned if the parameter fails to be obtained.| +| pThis | Pointer to the [OH_UdmfProperty](#oh_udmfproperty) instance.| +| key | Pointer to the key of the parameter to obtain.| +| defaultValue | Default value to be returned if the parameter fails to be obtained.| **Returns** @@ -3390,10 +3750,10 @@ Obtains the customized extra string parameter from an [OH_UdmfProperty](#oh_udmf **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdmfProperty](#oh_udmfproperty) instance.| -| key | Pointer to the key of the parameter to obtain.| +| pThis | Pointer to the [OH_UdmfProperty](#oh_udmfproperty) instance.| +| key | Pointer to the key of the parameter to obtain.| **Returns** @@ -3418,9 +3778,9 @@ Obtains the share option from an [OH_UdmfProperty](#oh_udmfproperty) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdmfProperty](#oh_udmfproperty) instance.| +| pThis | Pointer to the [OH_UdmfProperty](#oh_udmfproperty) instance.| **Returns** @@ -3447,9 +3807,9 @@ Obtains the custom tag value from an [OH_UdmfProperty](#oh_udmfproperty) instanc **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdmfProperty](#oh_udmfproperty) instance.| +| pThis | Pointer to the [OH_UdmfProperty](#oh_udmfproperty) instance.| **Returns** @@ -3474,9 +3834,9 @@ Obtains the timestamp from an [OH_UdmfProperty](#oh_udmfproperty) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdmfProperty](#oh_udmfproperty) instance.| +| pThis | Pointer to the [OH_UdmfProperty](#oh_udmfproperty) instance.| **Returns** @@ -3501,15 +3861,15 @@ Sets the extra integer parameter for an [OH_UdmfProperty](#oh_udmfproperty) inst **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| -| key | Pointer to the key of the parameter to set.| -| param | Parameter value to set.| +| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| +| key | Pointer to the key of the parameter to set.| +| param | Parameter value to set.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -3532,15 +3892,15 @@ Sets the extra string parameter for an [OH_UdmfProperty](#oh_udmfproperty) insta **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| -| key | Pointer to the key of the parameter to set.| -| param | Parameter value to set.| +| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| +| key | Pointer to the key of the parameter to set.| +| param | Parameter value to set.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -3563,14 +3923,14 @@ Sets the share option for an [OH_UdmfProperty](#oh_udmfproperty) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdmfProperty](#oh_udmfproperty) instance.| -| option | [Udmf_ShareOption](#udmf_shareoption) to set.| +| pThis | Pointer to the [OH_UdmfProperty](#oh_udmfproperty) instance.| +| option | [Udmf_ShareOption](#udmf_shareoption) to set.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -3595,14 +3955,14 @@ Sets the tag value for an [OH_UdmfProperty](#oh_udmfproperty) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdmfProperty](#oh_udmfproperty) instance.| -| tag | Pointer to the tag value to set.| +| pThis | Pointer to the [OH_UdmfProperty](#oh_udmfproperty) instance.| +| tag | Pointer to the tag value to set.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -3625,14 +3985,14 @@ Adds data of the [OH_UdsAppItem](#oh_udsappitem) type to an [OH_UdmfRecord](#oh_ **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| -| appItem | Pointer to the [OH_UdsAppItem](#oh_udsappitem) instance to add.| +| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| +| appItem | Pointer to the [OH_UdsAppItem](#oh_udsappitem) instance to add.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -3657,15 +4017,15 @@ Adds a data record of the [OH_UdsArrayBuffer](#oh_udsarraybuffer) type to an [OH **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| record | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| -| type | Pointer to the ArrayBuffer type ID, which must be unique.| -| buffer | Pointer to the [OH_UdsArrayBuffer]( #oh_udsarraybuffer) instance.| +| record | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| +| type | Pointer to the ArrayBuffer type ID, which must be unique.| +| buffer | Pointer to the [OH_UdsArrayBuffer]( #oh_udsarraybuffer) instance.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -3690,14 +4050,14 @@ Adds a data record of the [OH_UdsFileUri](#oh_udsfileuri) type to an [OH_UdmfRec **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| -| fileUri | Pointer to the [OH_UdsFileUri]( #oh_udsfileuri) instance.| +| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| +| fileUri | Pointer to the [OH_UdsFileUri]( #oh_udsfileuri) instance.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -3722,16 +4082,16 @@ Adds customized uniform data to an [OH_UdmfRecord](#oh_udmfrecord) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| -| typeId | Pointer to the data type ID.| -| entry | Pointer to the customized data to add.| -| count | Size of customized data to add. The data size cannot exceed 4 KB.| +| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| +| typeId | Pointer to the data type ID.| +| entry | Pointer to the customized data to add.| +| count | Size of customized data to add. The data size cannot exceed 4 KB.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -3754,14 +4114,14 @@ Adds data of the [OH_UdsHtml](#oh_udshtml) type to an [OH_UdmfRecord](#oh_udmfre **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| -| html | Pointer to the [OH_UdsHtml](#oh_udshtml) instance to add.| +| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| +| html | Pointer to the [OH_UdsHtml](#oh_udshtml) instance to add.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -3786,14 +4146,14 @@ Adds data of the hyperlink type [OH_UdsHyperlink](#oh_udshyperlink) type to an [ **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| -| hyperlink | Pointer to the [OH_UdsHyperlink](#oh_udshyperlink) instance to add.| +| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| +| hyperlink | Pointer to the [OH_UdsHyperlink](#oh_udshyperlink) instance to add.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -3818,14 +4178,14 @@ Adds a data record of the [OH_UdsPixelMap](#oh_udspixelmap) type to an [OH_UdmfR **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| -| pixelMap | Pointer to the [OH_UdsPixelMap]( #oh_udspixelmap) instance.| +| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| +| pixelMap | Pointer to the [OH_UdsPixelMap]( #oh_udspixelmap) instance.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -3850,14 +4210,14 @@ Adds data of the [OH_UdsPlainText](#oh_udsplaintext) type to an [OH_UdmfRecord]( **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| -| plainText | Pointer to the [OH_UdsPlainText](#oh_udsplaintext) instance to add.| +| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| +| plainText | Pointer to the [OH_UdsPlainText](#oh_udsplaintext) instance to add.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -3903,9 +4263,9 @@ Destroys an [OH_UdmfRecord](#oh_udmfrecord) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance to destroy.| +| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance to destroy.| **See** @@ -3926,14 +4286,14 @@ Obtains [OH_UdsAppItem](#oh_udsappitem) data from an [OH_UdmfRecord](#oh_udmfrec **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| -| appItem | Pointer to the [OH_UdsAppItem](#oh_udsappitem) instance obtained.| +| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| +| appItem | Pointer to the [OH_UdsAppItem](#oh_udsappitem) instance obtained.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -3958,15 +4318,15 @@ Obtains the [OH_UdsArrayBuffer](#oh_udsarraybuffer) data from an [OH_UdmfRecord] **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| record | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| -| type | Pointer to the data type ID of the ArrayBuffer data to obtain.| -| buffer | Pointer to the [OH_UdsArrayBuffer]( #oh_udsarraybuffer) data obtained.| +| record | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| +| type | Pointer to the data type ID of the ArrayBuffer data to obtain.| +| buffer | Pointer to the [OH_UdsArrayBuffer]( #oh_udsarraybuffer) data obtained.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -3991,14 +4351,14 @@ Obtains the [OH_UdsFileUri](#oh_udsfileuri) data from an [OH_UdmfRecord](#oh_udm **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| -| fileUri | Pointer to the [OH_UdsFileUri]( #oh_udsfileuri) data obtained.| +| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| +| fileUri | Pointer to the [OH_UdsFileUri]( #oh_udsfileuri) data obtained.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -4023,16 +4383,16 @@ Obtains the data of the specified type in an [OH_UdmfRecord](#oh_udmfrecord) ins **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| -| typeId | Pointer to the data type ID.| -| entry | Double pointer to the data obtained.| -| count | Length of the data obtained.| +| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| +| typeId | Pointer to the data type ID.| +| entry | Double pointer to the data obtained.| +| count | Length of the data obtained.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -4055,14 +4415,14 @@ Obtains [OH_UdsHtml](#oh_udshtml) data from an [OH_UdmfRecord](#oh_udmfrecord) i **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| -| html | Pointer to the [OH_UdsHtml](#oh_udshtml) data obtained.| +| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| +| html | Pointer to the [OH_UdsHtml](#oh_udshtml) data obtained.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -4087,14 +4447,14 @@ Obtains [OH_UdsHyperlink](#oh_udshyperlink) data from an [OH_UdmfRecord](#oh_udm **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| -| hyperlink | Pointer to the [OH_UdsHyperlink](#oh_udshyperlink) data obtained.| +| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| +| hyperlink | Pointer to the [OH_UdsHyperlink](#oh_udshyperlink) data obtained.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -4119,14 +4479,14 @@ Obtains the [OH_UdsPixelMap](#oh_udspixelmap) data from an [OH_UdmfRecord](#oh_u **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| -| pixelMap | Pointer to the [OH_UdsPixelMap]( #oh_udspixelmap) data obtained.| +| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| +| pixelMap | Pointer to the [OH_UdsPixelMap]( #oh_udspixelmap) data obtained.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -4151,14 +4511,14 @@ Obtains [OH_UdsPlainText](#oh_udsplaintext) data from an [OH_UdmfRecord](#oh_udm **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| -| plainText | Pointer to the [OH_UdsPlainText](#oh_udsplaintext) data obtained.| +| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| +| plainText | Pointer to the [OH_UdsPlainText](#oh_udsplaintext) data obtained.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -4183,10 +4543,10 @@ Obtains all data types in an [OH_UdmfRecord](#oh_udmfrecord) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| -| count | Pointer to the number of data types obtained.| +| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| +| count | Pointer to the number of data types obtained.| **Returns** @@ -4211,16 +4571,16 @@ Sets the [OH_UdmfRecordProvider](#oh_udmfrecordprovider) in an [OH_UdmfRecord](# **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| -| types | Pointer to the data types to be provided.| -| count | Number of the data types.| -| provider | Pointer to the [OH_UdmfRecordProvider]( #oh_udmfrecordprovider) instance to set.| +| pThis | Pointer to the [OH_UdmfRecord](#oh_udmfrecord) instance.| +| types | Pointer to the data types to be provided.| +| count | Number of the data types.| +| provider | Pointer to the [OH_UdmfRecordProvider]( #oh_udmfrecordprovider) instance to set.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -4266,13 +4626,13 @@ Destroys an [OH_UdmfRecordProvider](#oh_udmfrecordprovider) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | | provider | Pointer to the [OH_UdmfRecordProvider](#oh_udmfrecordprovider) instance to destroy.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -4295,16 +4655,16 @@ Sets a callback for an **OH_UdmfRecordProvider** instance to provide data. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| provider | Pointer to the target [OH_UdmfRecordProvider](#oh_udmfrecordprovider) instance.| -| context | Pointer to the context, which is passed as the first parameter to [OH_UdmfRecordProvider_GetData](#oh_udmfrecordprovider_getdata).| -| callback | Callback used to obtain data. For details, see [OH_UdmfRecordProvider_GetData](#oh_udmfrecordprovider_getdata).| -| finalize | Optional callback used to release the context data when the **OH_UdmfRecordProvider** instance is destroyed. For details, see [UdmfData_Finalize](#udmfdata_finalize).| +| provider | Pointer to the target [OH_UdmfRecordProvider](#oh_udmfrecordprovider) instance.| +| context | Pointer to the context, which is passed as the first parameter to [OH_UdmfRecordProvider_GetData](#oh_udmfrecordprovider_getdata).| +| callback | Callback used to obtain data. For details, see [OH_UdmfRecordProvider_GetData](#oh_udmfrecordprovider_getdata).| +| finalize | Optional callback used to release the context data when the **OH_UdmfRecordProvider** instance is destroyed. For details, see [UdmfData_Finalize](#udmfdata_finalize).| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -4350,9 +4710,9 @@ Destroys an [OH_UdsAppItem](#oh_udsappitem) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdsAppItem](#oh_udsappitem) instance to destroy.| +| pThis | Pointer to the [OH_UdsAppItem](#oh_udsappitem) instance to destroy.| **See** @@ -4373,9 +4733,9 @@ Obtains the ability name from an [OH_UdsAppItem](#oh_udsappitem) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdsAppItem](#oh_udsappitem) instance.| +| pThis | Pointer to the [OH_UdsAppItem](#oh_udsappitem) instance.| **Returns** @@ -4400,9 +4760,9 @@ Obtains the bundle name from an [OH_UdsAppItem](#oh_udsappitem) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdsAppItem](#oh_udsappitem) instance.| +| pThis | Pointer to the [OH_UdsAppItem](#oh_udsappitem) instance.| **Returns** @@ -4427,9 +4787,9 @@ Obtains the application icon ID from an [OH_UdsAppItem](#oh_udsappitem) instance **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdsAppItem](#oh_udsappitem) instance.| +| pThis | Pointer to the [OH_UdsAppItem](#oh_udsappitem) instance.| **Returns** @@ -4454,9 +4814,9 @@ Obtains the application ID from an [OH_UdsAppItem](#oh_udsappitem) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdsAppItem](#oh_udsappitem) instance.| +| pThis | Pointer to the [OH_UdsAppItem](#oh_udsappitem) instance.| **Returns** @@ -4481,9 +4841,9 @@ Obtains the application label ID from an [OH_UdsAppItem](#oh_udsappitem) instanc **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdsAppItem](#oh_udsappitem) instance.| +| pThis | Pointer to the [OH_UdsAppItem](#oh_udsappitem) instance.| **Returns** @@ -4508,9 +4868,9 @@ Obtains the application name from an [OH_UdsAppItem](#oh_udsappitem) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdsAppItem](#oh_udsappitem) instance.| +| pThis | Pointer to the [OH_UdsAppItem](#oh_udsappitem) instance.| **Returns** @@ -4535,9 +4895,9 @@ Obtains the type ID from an [OH_UdsAppItem](#oh_udsappitem) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdsAppItem](#oh_udsappitem) instance.| +| pThis | Pointer to the [OH_UdsAppItem](#oh_udsappitem) instance.| **Returns** @@ -4562,14 +4922,14 @@ Sets the ability name for an [OH_UdsAppItem](#oh_udsappitem) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdsAppItem](#oh_udsappitem) instance.| -| abilityName | Pointer to the ability name to set.| +| pThis | Pointer to the [OH_UdsAppItem](#oh_udsappitem) instance.| +| abilityName | Pointer to the ability name to set.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -4590,14 +4950,14 @@ Sets the bundle name for an [OH_UdsAppItem](#oh_udsappitem) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdsAppItem](#oh_udsappitem) instance.| -| bundleName | Pointer to the bundle name to set.| +| pThis | Pointer to the [OH_UdsAppItem](#oh_udsappitem) instance.| +| bundleName | Pointer to the bundle name to set.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -4618,14 +4978,14 @@ Sets the application icon ID for an [OH_UdsAppItem](#oh_udsappitem) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdsAppItem](#oh_udsappitem) instance.| -| appIconId | Pointer to the application icon ID to set.| +| pThis | Pointer to the [OH_UdsAppItem](#oh_udsappitem) instance.| +| appIconId | Pointer to the application icon ID to set.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -4646,14 +5006,14 @@ Sets the application ID for an [OH_UdsAppItem](#oh_udsappitem) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdsAppItem](#oh_udsappitem) instance.| -| appId | Pointer to the application ID to set.| +| pThis | Pointer to the [OH_UdsAppItem](#oh_udsappitem) instance.| +| appId | Pointer to the application ID to set.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -4674,14 +5034,14 @@ Sets the application label ID for an [OH_UdsAppItem](#oh_udsappitem) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdsAppItem](#oh_udsappitem) instance.| -| appLabelId | Pointer to the application label ID to set.| +| pThis | Pointer to the [OH_UdsAppItem](#oh_udsappitem) instance.| +| appLabelId | Pointer to the application label ID to set.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -4702,14 +5062,14 @@ Sets the application name for an [OH_UdsAppItem](#oh_udsappitem) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdsAppItem](#oh_udsappitem) instance.| -| appName | Pointer to the application name to set.| +| pThis | Pointer to the [OH_UdsAppItem](#oh_udsappitem) instance.| +| appName | Pointer to the application name to set.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -4751,13 +5111,13 @@ Destroys an [OH_UdsArrayBuffer](#oh_udsarraybuffer) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| buffer | Pointer to the [OH_UdsArrayBuffer]( #oh_udsarraybuffer) instance.| +| buffer | Pointer to the [OH_UdsArrayBuffer]( #oh_udsarraybuffer) instance.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -4780,15 +5140,15 @@ Obtains the custom ArrayBuffer data from an [OH_UdsArrayBuffer](#oh_udsarraybuff **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| buffer | Pointer to the target [OH_UdsArrayBuffer](#oh_udsarraybuffer) instance.| -| data | Double pointer to the ArrayBuffer data obtained.| -| len | Pointer to the length of the ArrayBuffer data obtained.| +| buffer | Pointer to the target [OH_UdsArrayBuffer](#oh_udsarraybuffer) instance.| +| data | Double pointer to the ArrayBuffer data obtained.| +| len | Pointer to the length of the ArrayBuffer data obtained.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -4811,15 +5171,15 @@ Sets an [OH_UdsArrayBuffer](#oh_udsarraybuffer) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| buffer | Pointer to the target [OH_UdsArrayBuffer](#oh_udsarraybuffer) instance.| -| data | Pointer to the ArrayBuffer data to set.| -| len | Length of the ArrayBuffer data to set.| +| buffer | Pointer to the target [OH_UdsArrayBuffer](#oh_udsarraybuffer) instance.| +| data | Pointer to the ArrayBuffer data to set.| +| len | Length of the ArrayBuffer data to set.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -4863,9 +5223,9 @@ Destroys an [OH_UdsFileUri](#oh_udsfileuri) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdsFileUri]( #oh_udsfileuri) instance to destroy.| +| pThis | Pointer to the [OH_UdsFileUri]( #oh_udsfileuri) instance to destroy.| **See** @@ -4886,9 +5246,9 @@ Obtains the file type from an [OH_UdsFileUri](#oh_udsfileuri) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the target [OH_UdsFileUri]( #oh_udsfileuri) instance.| +| pThis | Pointer to the target [OH_UdsFileUri]( #oh_udsfileuri) instance.| **Returns** @@ -4913,9 +5273,9 @@ Obtains the file URI from an [OH_UdsFileUri](#oh_udsfileuri) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the target [OH_UdsFileUri]( #oh_udsfileuri) instance.| +| pThis | Pointer to the target [OH_UdsFileUri]( #oh_udsfileuri) instance.| **Returns** @@ -4940,9 +5300,9 @@ Obtains the type ID from an [OH_UdsFileUri](#oh_udsfileuri) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the target [OH_UdsFileUri]( #oh_udsfileuri) instance.| +| pThis | Pointer to the target [OH_UdsFileUri]( #oh_udsfileuri) instance.| **Returns** @@ -4967,14 +5327,14 @@ Sets the file type for an [OH_UdsFileUri](#oh_udsfileuri) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the target [OH_UdsFileUri]( #oh_udsfileuri) instance.| -| fileType | Pointer to the file type to set.| +| pThis | Pointer to the target [OH_UdsFileUri]( #oh_udsfileuri) instance.| +| fileType | Pointer to the file type to set.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -4997,14 +5357,14 @@ Sets the URI information for an [OH_UdsFileUri](#oh_udsfileuri) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the target [OH_UdsFileUri]( #oh_udsfileuri) instance.| -| fileUri | Pointer to the file URI to set.| +| pThis | Pointer to the target [OH_UdsFileUri]( #oh_udsfileuri) instance.| +| fileUri | Pointer to the file URI to set.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -5048,9 +5408,9 @@ Destroys an [OH_UdsHtml](#oh_udshtml) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdsHtml](#oh_udshtml) instance to destroy.| +| pThis | Pointer to the [OH_UdsHtml](#oh_udshtml) instance to destroy.| **See** @@ -5071,9 +5431,9 @@ Obtains the HTML content from an [OH_UdsHtml](#oh_udshtml) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdsHtml](#oh_udshtml) instance.| +| pThis | Pointer to the [OH_UdsHtml](#oh_udshtml) instance.| **Returns** @@ -5098,9 +5458,9 @@ Obtains the plaintext from an [OH_UdsHtml](#oh_udshtml) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdsHtml](#oh_udshtml) instance.| +| pThis | Pointer to the [OH_UdsHtml](#oh_udshtml) instance.| **Returns** @@ -5125,9 +5485,9 @@ Obtains the type ID from an [OH_UdsHtml](#oh_udshtml) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdsHtml](#oh_udshtml) instance.| +| pThis | Pointer to the [OH_UdsHtml](#oh_udshtml) instance.| **Returns** @@ -5152,14 +5512,14 @@ Sets the HTML content for an [OH_UdsHtml](#oh_udshtml) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdsHtml](#oh_udshtml) instance.| -| content | Pointer to the content in HTML format to set.| +| pThis | Pointer to the [OH_UdsHtml](#oh_udshtml) instance.| +| content | Pointer to the content in HTML format to set.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -5180,14 +5540,14 @@ Sets the plaintext for an [OH_UdsHtml](#oh_udshtml) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdsHtml](#oh_udshtml) instance.| -| plainContent | Pointer to the plain text content to set.| +| pThis | Pointer to the [OH_UdsHtml](#oh_udshtml) instance.| +| plainContent | Pointer to the plain text content to set.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -5229,9 +5589,9 @@ Destroys an [OH_UdsHyperlink](#oh_udshyperlink) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdsHyperlink](#oh_udshyperlink) instance to destroy.| +| pThis | Pointer to the [OH_UdsHyperlink](#oh_udshyperlink) instance to destroy.| **See** @@ -5252,9 +5612,9 @@ Obtains the description from an [OH_UdsHyperlink](#oh_udshyperlink) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdsHyperlink](#oh_udshyperlink) instance.| +| pThis | Pointer to the [OH_UdsHyperlink](#oh_udshyperlink) instance.| **Returns** @@ -5279,9 +5639,9 @@ Obtains the type ID from an [OH_UdsHyperlink](#oh_udshyperlink) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdsHyperlink](#oh_udshyperlink) instance.| +| pThis | Pointer to the [OH_UdsHyperlink](#oh_udshyperlink) instance.| **Returns** @@ -5306,9 +5666,9 @@ Obtains the URL from an [OH_UdsHyperlink](#oh_udshyperlink) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdsHyperlink](#oh_udshyperlink) instance.| +| pThis | Pointer to the [OH_UdsHyperlink](#oh_udshyperlink) instance.| **Returns** @@ -5333,14 +5693,14 @@ Sets the description for an [OH_UdsHyperlink](#oh_udshyperlink) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdsHyperlink](#oh_udshyperlink) instance.| -| description | Pointer to the description to set.| +| pThis | Pointer to the [OH_UdsHyperlink](#oh_udshyperlink) instance.| +| description | Pointer to the description to set.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -5361,14 +5721,14 @@ Sets the URL for an [OH_UdsHyperlink](#oh_udshyperlink) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdsHyperlink](#oh_udshyperlink) instance.| -| url | Pointer to the URL to set.| +| pThis | Pointer to the [OH_UdsHyperlink](#oh_udshyperlink) instance.| +| url | Pointer to the URL to set.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -5410,9 +5770,9 @@ Destroys an [OH_UdsPixelMap](#oh_udspixelmap) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdsPixelMap]( #oh_udspixelmap) instance to destroy.| +| pThis | Pointer to the [OH_UdsPixelMap]( #oh_udspixelmap) instance to destroy.| **See** @@ -5433,10 +5793,10 @@ Obtains the pointer to the **OH_PixelmapNative** instance from an [OH_UdsPixelMa **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the target [OH_UdsPixelMap]( #oh_udspixelmap) instance.| -| pixelmapNative | Pointer to the **OH_PixelmapNative** instance obtained.| +| pThis | Pointer to the target [OH_UdsPixelMap]( #oh_udspixelmap) instance.| +| pixelmapNative | Pointer to the **OH_PixelmapNative** instance obtained.| **See** @@ -5459,9 +5819,9 @@ Obtains the type ID from an [OH_UdsPixelMap](#oh_udspixelmap) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the target [OH_UdsPixelMap]( #oh_udspixelmap) instance.| +| pThis | Pointer to the target [OH_UdsPixelMap]( #oh_udspixelmap) instance.| **Returns** @@ -5486,14 +5846,14 @@ Sets the pixel map content for an [OH_UdsPixelMap](#oh_udspixelmap) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the target [OH_UdsPixelMap]( #oh_udspixelmap) instance.| -| pixelmapNative | Pointer to the **OH_PixelmapNative** instance.| +| pThis | Pointer to the target [OH_UdsPixelMap]( #oh_udspixelmap) instance.| +| pixelmapNative | Pointer to the **OH_PixelmapNative** instance.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -5539,9 +5899,9 @@ Destroys an [OH_UdsPlainText](#oh_udsplaintext) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdsPlainText](#oh_udsplaintext) instance to destroy.| +| pThis | Pointer to the [OH_UdsPlainText](#oh_udsplaintext) instance to destroy.| **See** @@ -5562,9 +5922,9 @@ Obtains the abstract from an [OH_UdsPlainText](#oh_udsplaintext) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdsPlainText](#oh_udsplaintext) instance.| +| pThis | Pointer to the [OH_UdsPlainText](#oh_udsplaintext) instance.| **Returns** @@ -5589,9 +5949,9 @@ Obtains the plaintext from an [OH_UdsPlainText](#oh_udsplaintext) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdsPlainText](#oh_udsplaintext) instance.| +| pThis | Pointer to the [OH_UdsPlainText](#oh_udsplaintext) instance.| **Returns** @@ -5616,9 +5976,9 @@ Obtains the type ID from an [OH_UdsPlainText](#oh_udsplaintext) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdsPlainText](#oh_udsplaintext) instance.| +| pThis | Pointer to the [OH_UdsPlainText](#oh_udsplaintext) instance.| **Returns** @@ -5643,14 +6003,14 @@ Sets the abstract for an [OH_UdsPlainText](#oh_udsplaintext) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdsPlainText](#oh_udsplaintext) instance.| -| abstract | Pointer to the abstract to set.| +| pThis | Pointer to the [OH_UdsPlainText](#oh_udsplaintext) instance.| +| abstract | Pointer to the abstract to set.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -5671,14 +6031,14 @@ Sets the plaintext content for an [OH_UdsPlainText](#oh_udsplaintext) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_UdsPlainText](#oh_udsplaintext) instance.| -| content | Pointer to the plaintext content to set.| +| pThis | Pointer to the [OH_UdsPlainText](#oh_udsplaintext) instance.| +| content | Pointer to the plaintext content to set.| **Returns** -Returns a [Udmf_ErrCode](#udmf_errcode). Returns **UDMF_E_OK** if the operation is successful. Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. +Returns a [Udmf_ErrCode](#udmf_errcode).
Returns **UDMF_E_OK** if the operation is successful.
Returns **UDMF_E_INVALID_PARAM** if an invalid parameter is passed in. **See** @@ -5699,10 +6059,10 @@ Checks whether a UTD belongs to the target UTD. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| srcTypeId | Pointer to the UTD to check. | -| destTypeId | Pointer to the target UTD.| +| srcTypeId | Pointer to the UTD to check. | +| destTypeId | Pointer to the target UTD.| **Returns** @@ -5723,9 +6083,9 @@ Creates an [OH_Utd](#oh_utd) instance and a pointer to it. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| typeId | Pointer to the type ID of the instance to create.| +| typeId | Pointer to the type ID of the instance to create.| **Returns** @@ -5750,9 +6110,9 @@ Destroys an [OH_Utd](#oh_utd) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_Utd](#oh_utd) instance to destroy.| +| pThis | Pointer to the [OH_Utd](#oh_utd) instance to destroy.| **See** @@ -5773,10 +6133,10 @@ Destroys a UTD list. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| list | Double pointer to the UTD list to destroy.| -| count | Length of the UTD list.| +| list | Double pointer to the UTD list to destroy.| +| count | Length of the UTD list.| ### OH_Utd_Equals() @@ -5793,10 +6153,10 @@ Checks whether two UTDs are the same. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| desc1 | Pointer to one [OH_Utd](#oh_utd) instance to compare.| -| desc2 | Pointer to the other [OH_Utd](#oh_utd) instance to compare.| +| desc1 | Pointer to one [OH_Utd](#oh_utd) instance to compare.| +| desc2 | Pointer to the other [OH_Utd](#oh_utd) instance to compare.| **Returns** @@ -5817,10 +6177,10 @@ Obtains the relationships between the data in an [OH_Utd](#oh_utd) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_Utd](#oh_utd) instance.| -| count | Pointer to the number of data types obtained.| +| pThis | Pointer to the [OH_Utd](#oh_utd) instance.| +| count | Pointer to the number of data types obtained.| **Returns** @@ -5845,9 +6205,9 @@ Obtains the description from an [OH_Utd](#oh_utd) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_Utd](#oh_utd) instance.| +| pThis | Pointer to the [OH_Utd](#oh_utd) instance.| **Returns** @@ -5872,10 +6232,10 @@ Obtains the file name extensions associated with an [OH_Utd](#oh_utd) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_Utd](#oh_utd) instance.| -| count | Pointer to the number of file name extensions obtained.| +| pThis | Pointer to the [OH_Utd](#oh_utd) instance.| +| count | Pointer to the number of file name extensions obtained.| **Returns** @@ -5900,9 +6260,9 @@ Obtains the path of the default icon file from an [OH_Utd](#oh_utd) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_Utd](#oh_utd) instance.| +| pThis | Pointer to the [OH_Utd](#oh_utd) instance.| **Returns** @@ -5927,10 +6287,10 @@ Obtains the MIME types associated with an [OH_Utd](#oh_utd) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_Utd](#oh_utd) instance.| -| count | Pointer to the number of MIME types obtained.| +| pThis | Pointer to the [OH_Utd](#oh_utd) instance.| +| count | Pointer to the number of MIME types obtained.| **Returns** @@ -5955,9 +6315,9 @@ Obtains the URL from an [OH_Utd](#oh_utd) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_Utd](#oh_utd) instance.| +| pThis | Pointer to the [OH_Utd](#oh_utd) instance.| **Returns** @@ -5982,9 +6342,9 @@ Obtains the type ID from an [OH_Utd](#oh_utd) instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pThis | Pointer to the [OH_Utd](#oh_utd) instance.| +| pThis | Pointer to the [OH_Utd](#oh_utd) instance.| **Returns** @@ -6009,10 +6369,10 @@ Obtains the uniform data types based on the file name extensions. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| extension | Pointer to the file name extensions.| -| count | Pointer to the number of data types obtained.| +| extension | Pointer to the file name extensions.| +| count | Pointer to the number of data types obtained.| **Returns** @@ -6033,10 +6393,10 @@ Obtains the uniform data types based on the MIME types. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| mimeType | Pointer to the MIME types.| -| count | Pointer to the number of data types obtained.| +| mimeType | Pointer to the MIME types.| +| count | Pointer to the number of data types obtained.| **Returns** @@ -6057,10 +6417,10 @@ Checks whether a UTD is a higher-level type of the target UTD. For example, **SO **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| srcTypeId | Pointer to the UTD to check. | -| destTypeId | Pointer to the target UTD.| +| srcTypeId | Pointer to the UTD to check. | +| destTypeId | Pointer to the target UTD.| **Returns** @@ -6081,10 +6441,10 @@ Checks whether a UTD is a lower-level type of the target UTD. For example, **TYP **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| srcTypeId | Pointer to the UTD to check. | -| destTypeId | Pointer to the target UTD.| +| srcTypeId | Pointer to the UTD to check. | +| destTypeId | Pointer to the target UTD.| **Returns** diff --git a/en/application-dev/reference/apis-arkdata/errorcode-collaboration-edit-object.md b/en/application-dev/reference/apis-arkdata/errorcode-collaboration-edit-object.md new file mode 100644 index 0000000000000000000000000000000000000000..b8d84003f714648617f51291a6c36641f7bf4175 --- /dev/null +++ b/en/application-dev/reference/apis-arkdata/errorcode-collaboration-edit-object.md @@ -0,0 +1,85 @@ +# Collaboration Edit Object Error Codes + +> **NOTE** +> +> This topic describes only module-specific error codes. For details about universal error codes, see [Universal Error Codes](../errorcode-universal.md). + +## 15410000 Internal Error + +**Error Message** + +Internal error. + +**Description** + +An internal error occurs. + +**Possible Causes** + +View the error log to determine the cause of the error. Possible causes include the following: + +1. Incorrect use of APIs. + +2. System errors, such as null pointer, insufficient memory, IPC exception, and JS engine exception. + +**Solution** + +1. Check whether the APIs are called correctly. If not, apply necessary corrections. +2. If the problem persists, ask the user to restart or update the application or upgrade the device version. + +## 15410001 Unsupported Operation + +**Error Message** + +Unsupported operation. + +**Description** + +The current operation is not supported. + +**Possible Causes** + +The conditions for calling the API are not satisfied. + +**Solution** + +Check whether the conditions for calling the API are satisfied. For example, the APIs of **Node** and **Text** can be called only after the node object or text object is inserted into the collaboration edit object. + +## 15410002 Index Out of Range + +**Error Message** + +Index out of range. + +**Description** + +The specified index is out of the value range. + +**Possible Causes** + +The index value passed in is incorrect. + +**Solution** + +Ensure that the index value is correct. + +## 15410003 Database Error + +**Error Message** + +Database error. + +**Description** + +A database error occurs. + +**Possible Causes** + +1. The database kernel APIs are not correctly called when the collaboration edit object APIs are used to insert, delete, or query data in the database. +2. The database file is corrupted. + +**Solution** + +1. Check whether the parameters of the API are correct. +2. Analyze the relationship between the shared data types and check that the APIs are correctly called. +3. Delete the local database, and create a new one by synchronizing data from the cloud. diff --git a/en/application-dev/reference/apis-arkdata/errorcode-data-gdb.md b/en/application-dev/reference/apis-arkdata/errorcode-data-gdb.md new file mode 100644 index 0000000000000000000000000000000000000000..00cac14c83168495461e4d4a94d467e9b4b12649 --- /dev/null +++ b/en/application-dev/reference/apis-arkdata/errorcode-data-gdb.md @@ -0,0 +1,290 @@ +# Graph Store Error Codes + +> **NOTE** +> +> This topic describes only module-specific error codes. For details about universal error codes, see [Universal Error Codes](../errorcode-universal.md). + +## 31300000 Internal Error + +**Error Message** + +Inner error. + +**Description** + +Internal error. + +**Possible Causes** + +View the error log to determine the cause of the error. Possible causes include the following: +1. The GQL statement fails to be executed. +2. The internal state is abnormal. +3. There is API that is incorrectly used. +4. A system error, such as null pointer, unexpected restart of the data service, I/O error, or JS engine exception, occurs. + +**Solution** + +1. Check whether the APIs are called correctly. If not, apply necessary corrections. +2. If the problem persists, ask the user to restart or update the application or upgrade the device version. + +## 31300001 Database File Corrupted + +**Error Message** + +Database corrupted. + +**Description** + +The database is corrupted when **read()** or **write()** is called. + +**Possible Causes** + +The database file is corrupted. + +**Solution** + +Currently, graph stores cannot be backed up or restored. If data loss is acceptable, delete the database and create a new one. + +## 31300002 Database or Transaction Closed + +**Error Message** + +Already closed. + +**Description** + +The graph store or transaction is already closed. + +**Possible Causes** + +1. Before the current operation is performed, the graph store fails to be opened or [close](js-apis-data-graphStore-sys.md#close) is called to close the graph store. +2. Before the current operation is performed, [commit](js-apis-data-graphStore-sys.md#commit) is called to commit the transaction or [rollback](js-apis-data-graphStore-sys.md#rollback) is called to roll back the transaction. + +**Solution** + +1. Call [getStore](js-apis-data-graphStore-sys.md#graphstoregetstore) to open the graph store again. Ensure that the input parameters are correct. +2. Call [createTransaction](js-apis-data-graphStore-sys.md#createtransaction) to create a transaction. + +## 31300003 Database not Respond + +**Error Message** + +The database is busy. + +**Description** + +The database does not respond. + +**Possible Causes** + +1. The graph store is being accessed by multiple processes of the same application. +2. Multiple threads in a process perform read and write operations at the same time, resulting in timeout on a thread. +3. The data written by a transaction using [write](js-apis-data-graphStore-sys.md#write) has not been committed or rolled back. + +**Solution** + +1. Avoid concurrent database operations from processes. +2. Wait for a while and try again. +3. Commit or roll back the unclosed transaction. + +## 31300004 Insufficient Memory + +**Error Message** + +The database is out of memory. + +**Description** + +The graph store memory is insufficient. + +**Possible Causes** + +The data volume is too large or the memory allocated is insufficient. + +**Solution** + +Reduce the data volume or clear other processes to release the memory. + +## 31300005 Database Is Full + +**Error Message** + +The database is full. + +**Description** + +The database is full. + +**Possible Causes** + +The data volume in the database reaches the upper limit or the disk space is insufficient. + +**Solution** + +Call [GraphStore.write](js-apis-data-graphStore-sys.md#write-1) or [Transaction.write](js-apis-data-graphStore-sys.md#write) to delete unnecessary data. + +## 31300006 Duplicate Graph Name, Vertex Type or Property, or Edge Type or Property + +**Error Message** + +A duplicate graph name, vertex or edge type, or vertex or edge property name exists. + +**Description** + +Duplicate graph name, vertex type or property, or edge type or property exists. + +**Possible Causes** + +1. A graph with the same name already exists in the database. +2. Different vertexes use the same type or property. +3. Different edges use the same type or property. + +**Solution** + +When using [GraphStore.write](js-apis-data-graphStore-sys.md#write-1) or [Transaction.write](js-apis-data-graphStore-sys.md#write) to create a graph, check the graph name, vertex type ([Vertex.labels](js-apis-data-graphStore-sys.md#vertex)) and properties ([Vertex.properties](js-apis-data-graphStore-sys.md#vertex)), and edge type ([Edge.type](js-apis-data-graphStore-sys.md#edge)) and properties ([Edge.labels](js-apis-data-graphStore-sys.md#edge)) in the graph creation statement to prevent conflict. + +## 31300007 Undefined Graph Name, Vertex Type or Property, or Edge Type or Property + +**Error Message** + +The graph name, vertex or edge type, or vertex or edge property is not defined. + +**Description** + +There is undefined graph name, vertex or edge type, or vertex or edge property. + +**Possible Causes** + +There is undefined graph name, vertex or edge type, or vertex or edge property. + +**Solution** + +Check for undefined graph name, vertex type ([Vertex.labels](js-apis-data-graphStore-sys.md#vertex)) or properties ([Vertex.properties](js-apis-data-graphStore-sys.md#vertex)), and edge type ([Edge.type](js-apis-data-graphStore-sys.md#edge)) or properties ([Edge.labels](js-apis-data-graphStore-sys.md#edge)) in [GraphStore.write](js-apis-data-graphStore-sys.md#write-1) or [Transaction.write](js-apis-data-graphStore-sys.md#write). + +## 31300008 Invalid Graph Name, Vertex Type or Property, or Edge Type or Property + +**Error Message** + +The graph name, vertex or edge type, or vertex or edge property name does not conform to constraints. + +**Description** + +The specified graph name, vertex or edge type, or vertex or edge property violates constraints. + +**Possible Causes** + +1. The graph name exceeds 128 bytes. +2. The primary keys conflict. +3. Duplicate identifiers exist. + +**Solution** + +When using [GraphStore.write](js-apis-data-graphStore-sys.md#write-1) or [Transaction.write](js-apis-data-graphStore-sys.md#write) to create a graph, check the graph name, vertex type ([Vertex.labels](js-apis-data-graphStore-sys.md#vertex)) and properties ([Vertex.properties](js-apis-data-graphStore-sys.md#vertex)), and edge type ([Edge.type](js-apis-data-graphStore-sys.md#edge)) and properties ([Edge.labels](js-apis-data-graphStore-sys.md#edge)) in the graph creation statement to prevent conflict. + +## 31300009 Syntax Error in the GQL Statement + +**Error Message** + +The GQL statement syntax error. + +**Description** + +The GQL statement has a syntax error. + +**Possible Causes** + +There is syntax error in the GQL statement. + +**Solution** + +Check and correct the syntax error in the GQL statement. + +## 31300010 Semantic Error in the GQL Statement + +**Error Message** + +The GQL statement semantic error. + +**Description** + +The GQL statement has a semantic error. + +**Possible Causes** + +There is a semantic error in the GQL statement. + +**Solution** + +Check and correct the semantic error in the GQL statement. + +## 31300012 Number of Graphs, Vertex Types or Properties, or Edge Types or Properties Exceeds the Limit + +**Error Message** + +The number of graph names, vertex or edge types, or vertex or edge properties exceeds the limit. + +**Description** + +The number of graph names, vertex types or properties, or edge types or properties exceeds the limit. + +**Possible Causes** + +The number of graph names, vertex types or properties, or edge types or properties exceeds the limit. + +**Solution** + +Reduce the number of vertex or edge types or properties. A graph store allows only one graph and a maximum of 1024 vertex or edge properties. + +## 31300013 Conflict Constraints + +**Error Message** + +A conflicting constraint already exists. + +**Description** + +Conflict constraints are found. + +**Possible Causes** + +There are primary key conflicts, identifier conflicts, or other syntax conflicts. + +**Solution** + +Check for and resolve conflicts in the GQL statement. + +## 31300014 Invalid Database Path + +**Error Message** + +Invalid database path. + +**Description** + +The graph store path is invalid. + +**Possible Causes** + +Access to the graph store is denied due to lack of permission. + +**Solution** + +Currently, graph stores do not support custom paths. The default sandbox path in [Context](../apis-ability-kit/js-apis-inner-app-context.md) is used. Correct the code by referring to the sample code in [getStore](js-apis-data-graphStore-sys.md#graphstoregetstore). + +## 31300015 Key Configuration Changed + +**Error Message** + +Config changed. + +**Description** + +The key configuration of the graph store has been modified. + +**Possible Causes** + +Key configuration such as **name**, **securityLevel**, and **encrypt** is changed. + +**Solution** + +Restore the original configuration if required. Otherwise, delete the old graph store, use the new configuration to create a graph store, and import the data to the new graph store. **securityLevel** cannot be changed from a higher level to a lower one. diff --git a/en/application-dev/reference/apis-arkdata/errorcode-data-rdb.md b/en/application-dev/reference/apis-arkdata/errorcode-data-rdb.md index f02210d361e82eb6210249eccb07bf4e323ae718..b48d3610621cda93c5ef75321a32aff240bef481 100644 --- a/en/application-dev/reference/apis-arkdata/errorcode-data-rdb.md +++ b/en/application-dev/reference/apis-arkdata/errorcode-data-rdb.md @@ -55,11 +55,11 @@ Database corrupted. **Description** -The RDB store is corrupted when an API for adding, deleting, querying, or synchronizing data is invoked. +The database is abnormal. **Possible Causes** -The RDB store file has been corrupted. +The database file is damaged and incomplete, the database FD is incorrectly operated, or the database memory is illegally accessed. **Solution** @@ -95,10 +95,10 @@ The column value is null, or the column data type is incompatible with the API c **Possible Causes** -- The result set is empty. -- The current row number in the result set is out of range [0, m - 1]. **m** is **resultsetV9.rowCount**. -- The column number is out of the range [0, n - 1]. **n** is **resultsetV9.columnCount**. -- The API called does not support the type of the column data. +1. The result set is empty. +2. The current row number in the result set is out of range [0, m - 1]. **m** is **resultsetV9.rowCount**. +3. The column number is out of the range [0, n - 1]. **n** is **resultsetV9.columnCount**. +4. The API called does not support the type of the column data. **Solution** @@ -196,7 +196,7 @@ The SQL statement used for query is incorrect, or the data does not exist. **Solution** Use the correct query statement or add data. - + ## 14800019 SQL Query Statement Required **Error Message** @@ -263,7 +263,7 @@ SQLite: Callback routine requested an abort. **Description** -The asynchronous callback request is aborted. +The asynchronous callback request is aborted. This error is reported by the underlying SQLite. **Possible Causes** @@ -305,7 +305,7 @@ SQLite: The database file is locked. **Description** -The SQLite database file is locked. +The SQLite database file is locked. This error is reported by the underlying SQLite. **Possible Causes** @@ -325,7 +325,7 @@ SQLite: A table in the database is locked. **Description** -An SQLite database table is locked. +An SQLite database table is locked. This error is reported by the underlying SQLite. **Possible Causes** @@ -348,10 +348,10 @@ SQLite: The database is out of memory. **Description** -The database memory is insufficient. +The database memory is insufficient. This error is reported by the underlying SQLite. **Possible Causes** - + The data volume is too large or the memory allocated is insufficient. **Solution** @@ -366,7 +366,7 @@ SQLite: Attempt to write a readonly database. **Description** -A write operation is invoked on a read-only database. +A write operation is invoked on a read-only database. This error is reported by the underlying SQLite. **Possible Causes** @@ -387,7 +387,7 @@ SQLite: Some kind of disk I/O error occurred. **Description** -A disk I/O error occurs. +A disk I/O error occurs. This error is reported by the underlying SQLite. **Possible Causes** @@ -413,7 +413,7 @@ SQLite: The database is full. **Description** -The SQLite database is full. +The SQLite database is full. This error is reported by the underlying SQLite. **Possible Causes** @@ -431,7 +431,7 @@ SQLite: Unable to open the database file. **Description** -The database file fails to be opened. +The database file fails to be opened. This error is reported by the underlying SQLite. **Possible Causes** @@ -454,7 +454,7 @@ SQLite: TEXT or BLOB exceeds size limit. **Description** -The size of the text or BLOB exceeds the limit. +The size of the text or BLOB exceeds the limit. This error is reported by the underlying SQLite. **Possible Causes** @@ -473,7 +473,7 @@ SQLite: Abort due to constraint violation. **Description** -The database operation violates the constraint rule and is aborted. +The database operation violates the constraint rule and is aborted. This error is reported by the underlying SQLite. **Possible Causes** @@ -492,7 +492,7 @@ SQLite: Data type mismatch. **Description** -The data types mismatch. +The data types mismatch. This error is reported by the underlying SQLite. **Possible Causes** @@ -511,7 +511,7 @@ SQLite: Library used incorrectly. **Description** -The SQLite interface is used incorrectly. +The SQLite interface is used incorrectly. This error is reported by the underlying SQLite. **Possible Causes** diff --git a/en/application-dev/reference/apis-arkdata/errorcode-datashare.md b/en/application-dev/reference/apis-arkdata/errorcode-datashare.md index cea5ff3d9564abae384fa13c3beaa70664055370..25e84d30d9e8d07cd999cfe3f6ca15d273a5f8a2 100644 --- a/en/application-dev/reference/apis-arkdata/errorcode-datashare.md +++ b/en/application-dev/reference/apis-arkdata/errorcode-datashare.md @@ -4,6 +4,31 @@ > > This topic describes only module-specific error codes. For details about universal error codes, see [Universal Error Codes](../errorcode-universal.md). +## 15700000 Internal Error + +**Error Message** + +Inner error. + +**Description** + +Internal error. + +**Possible Causes** + +View the error log to determine the cause of the error. Possible causes include the following: +1. Abnormal internal state. +2. Incorrect use of APIs. +3. Incorrect permission configuration. +4. System errors, such as null pointers, insufficient memory, unexpected restart of data services, I/O errors, IPC exceptions, and JS engine exceptions. + +**Solution** + +1. Check whether a closed object is reused. +2. Check whether the APIs are called correctly. If not, apply necessary corrections. +3. Check whether the permission configuration is correct. +4. If the problem persists, ask the user to restart or update the application or upgrade the device version. + ## 15700010 Failed to Create a DataShareHelper **Error Message** @@ -25,7 +50,7 @@ The **DataShareHelper** class fails to be created. 1. Obtain the correct URI. 2. Check that the context of the stage model is used. 3. Check whether the client has the read or write permission on data. Perform the following steps: - (1) Obtain the data provider bundle name in the path of the URI. For example, the bundle name in uri = "datashareproxy://com.acts.ohos.data.datasharetest/test" is **com.acts.ohos.data.datasharetest**. + (1) Obtain the data provider bundle name from the URI. For example, the bundle name in uri "datashareproxy://com.acts.ohos.data.datasharetest/test" is **com.acts.ohos.data.datasharetest**. (2) Obtain the configuration based on the bundle name. For example, run **bm dump --bundle-name com.acts.ohos.data.datasharetest** to obtain the **DataShareExtension** configuration, and check whether the data consumer has **readPermission** or **writePermission**. ## 15700011 URI Not Exist diff --git a/en/application-dev/reference/apis-arkdata/errorcode-intelligence.md b/en/application-dev/reference/apis-arkdata/errorcode-intelligence.md new file mode 100644 index 0000000000000000000000000000000000000000..c78a43d634b8ed3065f2c07ba18a6267e0b95aba --- /dev/null +++ b/en/application-dev/reference/apis-arkdata/errorcode-intelligence.md @@ -0,0 +1,24 @@ +# AIP Error Codes + +> NOTE +> +> This topic describes only module-specific error codes. For details about universal error codes, see [Universal Error Codes](../errorcode-universal.md). + +## 31300000 Internal Error + +**Error Message** + +Inner error. + +**Description** + +An internal service error occurs when an ArkData Intelligence Platform (AIP) interface is called. + +**Possible Causes** + +The internal service is in abnormal status. For example, the application calls **getEmbedding()** without loading the embedding model. + +**Solution** + +1. Check whether the APIs are called correctly. If not, apply necessary corrections. +2. Try again at specific intervals, for example, at 1s intervals or at exponentially increasing intervals. If the problem persists, ask the user to restart or update the application or update the device. diff --git a/en/application-dev/reference/apis-arkdata/js-apis-data-DataShareResultSet-sys.md b/en/application-dev/reference/apis-arkdata/js-apis-data-DataShareResultSet-sys.md index 80fbcaea058ee6b09cd709a8b0a187629853c10b..ae069600b6935c13af7e643995f35eccf885c30d 100644 --- a/en/application-dev/reference/apis-arkdata/js-apis-data-DataShareResultSet-sys.md +++ b/en/application-dev/reference/apis-arkdata/js-apis-data-DataShareResultSet-sys.md @@ -67,7 +67,7 @@ The column or key names are returned as a string array, in which the strings are | columnNames | Array<string> | Yes | Names of all columns in the result set. | | columnCount | number | Yes | Number of columns in the result set. | | rowCount | number | Yes | Number of rows in the result set. | -| isClosed | boolean | Yes | Whether the result set is closed.| +| isClosed | boolean | Yes | Whether the result set is closed. The value **true** means the result set is closed; the value **false** means the opposite.| ### goToFirstRow diff --git a/en/application-dev/reference/apis-arkdata/js-apis-data-ability.md b/en/application-dev/reference/apis-arkdata/js-apis-data-ability.md index 55b07a5baccb2df068f50e9350681fb8701e86c3..768cd9f4c4246099011183584b6822df65991ee9 100644 --- a/en/application-dev/reference/apis-arkdata/js-apis-data-ability.md +++ b/en/application-dev/reference/apis-arkdata/js-apis-data-ability.md @@ -17,35 +17,35 @@ import { dataAbility } from '@kit.ArkData'; createRdbPredicates(name: string, dataAbilityPredicates: DataAbilityPredicates): rdb.RdbPredicates -Creates an **RdbPredicates** object with the specified table name and **DataAbilityPredicates** object. +Creates an **RdbPredicates** object with a table name and **DataAbilityPredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| name | string | Yes | Name of a database table. | -| dataAbilityPredicates | [DataAbilityPredicates](#dataabilitypredicates) | Yes | **DataAbilityPredicates** object. | +| name | string | Yes| Name of a database table.| +| dataAbilityPredicates | [DataAbilityPredicates](#dataabilitypredicates) | Yes| **DataAbilityPredicates** object. | **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| rdb.[RdbPredicates](js-apis-data-rdb.md#rdbpredicates) | **RdbPredicates** object created. | +| rdb.[RdbPredicates](js-apis-data-rdb.md#rdbpredicates) | **RdbPredicates** object created.| **Example** ```js let dataAbilityPredicates = new dataAbility.DataAbilityPredicates() dataAbilityPredicates.equalTo("NAME", "Rose") - // EMPLOYEE is a table created in a relational database. + // EMPLOYEE is a table created in an RDB store. let predicates = dataAbility.createRdbPredicates("EMPLOYEE", dataAbilityPredicates) ``` ## DataAbilityPredicates -Provides predicates for implementing diverse query methods. +Provides APIs for creating diverse query conditions. **Initialization** @@ -57,7 +57,7 @@ Provides predicates for implementing diverse query methods. equalTo(field: string, value: ValueType): DataAbilityPredicates -Sets a **DataAbilityPredicates** object to match the field with data type **ValueType** and value equals to the specified value. +Creates a **DataAbilityPredicates** object to search for the records in the specified column that are equal to the given value. This API is similar to the SQL equal to (=) operator. @@ -65,16 +65,16 @@ This API is similar to the SQL equal to (=) operator. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the table. | -| value | [ValueType](#valuetype) | Yes | Value to match the **DataAbilityPredicates**. | +| field | string | Yes| Column name in the table.| +| value | [ValueType](#valuetype) | Yes| Value to match.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field. | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object created.| **Example** @@ -86,7 +86,7 @@ This API is similar to the SQL equal to (=) operator. notEqualTo(field: string, value: ValueType): DataAbilityPredicates -Sets a **DataAbilityPredicates** object to match the field with data type **ValueType** and value not equal to the specified value. +Creates a **DataAbilityPredicates** object to search for the records in the specified column that are not equal to the given value. This API is similar to the SQL not equal (!=) operator. @@ -94,16 +94,16 @@ This API is similar to the SQL not equal (!=) operator. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the table. | -| value | [ValueType](#valuetype) | Yes | Value to match the **DataAbilityPredicates**. | +| field | string | Yes| Column name in the table.| +| value | [ValueType](#valuetype) | Yes| Value to match.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field. | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object created.| **Example** @@ -115,15 +115,15 @@ This API is similar to the SQL not equal (!=) operator. beginWrap(): DataAbilityPredicates -Adds a left parenthesis to this **DataAbilityPredicates**. This API is similar to "(" in an SQL statement and must be used with **endWrap**. +Creates a **DataAbilityPredicates** object to add a left parenthesis. This API is similar to "(" in an SQL statement and must be used with **endWrap**. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with a left parenthesis. | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with a left parenthesis.| **Example** @@ -140,15 +140,15 @@ Adds a left parenthesis to this **DataAbilityPredicates**. This API is similar t endWrap(): DataAbilityPredicates -Adds a right parenthesis to this **DataAbilityPredicates**. This API is similar to ")" in an SQL statement and must be used with **beginWrap**. +Creates a **DataAbilityPredicates** object to add a right parenthesis. This API is similar to ")" in an SQL statement and must be used with **beginWrap**. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with a right parenthesis. | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with a right parenthesis.| **Example** @@ -165,7 +165,7 @@ Adds a right parenthesis to this **DataAbilityPredicates**. This API is similar or(): DataAbilityPredicates -Adds the OR condition to this **DataAbilityPredicates**. +Creates a **DataAbilityPredicates** object to add the OR condition. This API is similar to the SQL **or** operator. @@ -173,9 +173,9 @@ This API is similar to the SQL **or** operator. **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with the OR condition. | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with the OR condition.| **Example** @@ -189,15 +189,15 @@ This API is similar to the SQL **or** operator. and(): DataAbilityPredicates -Adds the AND condition to this **DataAbilityPredicates**. +Creates a **DataAbilityPredicates** object to add the AND condition. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with the AND condition. | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with the AND condition.| **Example** @@ -211,22 +211,22 @@ Adds the AND condition to this **DataAbilityPredicates**. contains(field: string, value: string): DataAbilityPredicates -Sets a **DataAbilityPredicates** object to match a string containing the specified value. +Creates a **DataAbilityPredicates** object to search for the records in the specified column that contain the given value. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the table. | -| value | string | Yes | Value to match the **DataAbilityPredicates**. | +| field | string | Yes| Column name in the table.| +| value | string | Yes| Value to match.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field. | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object created.| **Example** @@ -238,7 +238,7 @@ Sets a **DataAbilityPredicates** object to match a string containing the specifi beginsWith(field: string, value: string): DataAbilityPredicates -Sets a **DataAbilityPredicates** object to match a string that starts with the specified value. +Creates a **DataAbilityPredicates** object to search for the records in the specified column that begin with the given value. This API is similar to the percent sign (%) in SQL statements. @@ -246,16 +246,16 @@ This API is similar to the percent sign (%) in SQL statements. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the table. | -| value | string | Yes | Value to match the **DataAbilityPredicates**. | +| field | string | Yes| Column name in the table.| +| value | string | Yes| Value to match.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field. | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object created.| **Example** @@ -267,7 +267,7 @@ This API is similar to the percent sign (%) in SQL statements. endsWith(field: string, value: string): DataAbilityPredicates -Sets a **DataAbilityPredicates** object to match a string that ends with the specified value. +Creates a **DataAbilityPredicates** object to search for the records in the specified column that end with the given value. This API is similar to the percent sign (%) in SQL statements. @@ -275,16 +275,16 @@ This API is similar to the percent sign (%) in SQL statements. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the table. | -| value | string | Yes | Value to match the **DataAbilityPredicates**. | +| field | string | Yes| Column name in the table.| +| value | string | Yes| Value to match.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field. | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object created.| **Example** @@ -296,21 +296,21 @@ This API is similar to the percent sign (%) in SQL statements. isNull(field: string): DataAbilityPredicates -Sets a **DataAbilityPredicates** object to match the field whose value is null. +Creates a **DataAbilityPredicates** object to search for the records in the specified column that are **null**. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the table. | +| field | string | Yes| Column name in the table.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field. | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object created.| **Example** @@ -322,21 +322,21 @@ Sets a **DataAbilityPredicates** object to match the field whose value is null. isNotNull(field: string): DataAbilityPredicates -Sets a **DataAbilityPredicates** object to match the field whose value is not null. +Creates a **DataAbilityPredicates** object to search for the records in the specified column that are not **null**. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the table. | +| field | string | Yes| Column name in the table.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field. | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object created.| **Example** @@ -348,7 +348,7 @@ Sets a **DataAbilityPredicates** object to match the field whose value is not nu like(field: string, value: string): DataAbilityPredicates -Sets a **DataAbilityPredicates** object to match a string that is similar to the specified value. +Creates a **DataAbilityPredicates** object to search for the records in the specified column that are similar to the given value. This API is similar to the SQL **like** statement. @@ -356,16 +356,16 @@ This API is similar to the SQL **like** statement. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the table. | -| value | string | Yes | Value to match the **DataAbilityPredicates**. | +| field | string | Yes| Column name in the table.| +| value | string | Yes| Value to match.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field. | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object created.| **Example** @@ -377,32 +377,32 @@ This API is similar to the SQL **like** statement. glob(field: string, value: string): DataAbilityPredicates -Sets a **DataAbilityPredicates** object to match the specified string. Different from **like**, the input parameters of this API are case-sensitive. +Creates a **DataAbilityPredicates** object to search for the records in the specified column that match the given string. Different from **like**, the input parameters of this API are case-sensitive. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the table. | -| value | string | Yes | Value to match the **DataAbilityPredicates**. | +| field | string | Yes| Column name in the table.| +| value | string | Yes| Value to match.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field. | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object created.| **Example** ```js dataAbilityPredicates.glob("NAME", "?h*g") - // Only the data with name of Lisa matches the specified predicate. + // Only the records whose value is "Lisa" in the "name" column are matched. dataAbilityPredicates.glob("NAME", "Lisa") - // Only the data with name of lisa matches the specified predicate. + // Only the records whose value is "lisa" in the "name" column are matched. dataAbilityPredicates.glob("NAME", "lisa") ``` @@ -410,23 +410,23 @@ Sets a **DataAbilityPredicates** object to match the specified string. Different between(field: string, low: ValueType, high: ValueType): DataAbilityPredicates -Sets a **DataAbilityPredicates** object to match a field whose data type is **ValueType** and value is within the specified range. +Creates a **DataAbilityPredicates** object to search for the records in the specified column that are within the given range. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the table. | -| low | [ValueType](#valuetype) | Yes | Minimum value to match the **DataAbilityPredicates**. | -| high | [ValueType](#valuetype) | Yes | Maximum value to match the **DataAbilityPredicates**. | +| field | string | Yes| Column name in the table.| +| low | [ValueType](#valuetype) | Yes| Minimum value of the range to set.| +| high | [ValueType](#valuetype) | Yes| Maximum value of the range to set.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field. | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object created.| **Example** @@ -438,23 +438,23 @@ Sets a **DataAbilityPredicates** object to match a field whose data type is **Va notBetween(field: string, low: ValueType, high: ValueType): DataAbilityPredicates -Sets a **DataAbilityPredicates** object to match the field with data type **ValueType** and value out of the specified range. +Creates a **DataAbilityPredicates** object to search for the records in the specified column that are out of the given range. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the table. | -| low | [ValueType](#valuetype) | Yes | Minimum value to match the **DataAbilityPredicates**. | -| high | [ValueType](#valuetype) | Yes | Maximum value to match the **DataAbilityPredicates**. | +| field | string | Yes| Column name in the table.| +| low | [ValueType](#valuetype) | Yes| Minimum value of the range to set.| +| high | [ValueType](#valuetype) | Yes| Maximum value of the range to set.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field. | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object created.| **Example** @@ -466,22 +466,22 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu greaterThan(field: string, value: ValueType): DataAbilityPredicates -Sets a **DataAbilityPredicates** object to match the field with data type **ValueType** and value greater than the specified value. +Creates a **DataAbilityPredicates** object to search for the records in the specified column that are greater than the given value. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the table. | -| value | [ValueType](#valuetype) | Yes | Value to match the **DataAbilityPredicates**. | +| field | string | Yes| Column name in the table.| +| value | [ValueType](#valuetype) | Yes| Value to match.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field. | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object created.| **Example** @@ -493,22 +493,22 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu lessThan(field: string, value: ValueType): DataAbilityPredicates -Sets a **DataAbilityPredicates** object to match the field with data type **ValueType** and value less than the specified value. +Creates a **DataAbilityPredicates** object to search for the records in the specified column that are less than the given value. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the table. | -| value | [ValueType](#valuetype) | Yes | Value to match the **DataAbilityPredicates**. | +| field | string | Yes| Column name in the table.| +| value | [ValueType](#valuetype) | Yes| Value to match.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field. | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object created.| **Example** @@ -520,22 +520,22 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu greaterThanOrEqualTo(field: string, value: ValueType): DataAbilityPredicates -Sets a **DataAbilityPredicates** object to match the field with data type **ValueType** and value greater than or equal to the specified value. +Creates a **DataAbilityPredicates** object to search for the records in the specified column that are greater than or equal to the given value. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the table. | -| value | [ValueType](#valuetype) | Yes | Value to match the **DataAbilityPredicates**. | +| field | string | Yes| Column name in the table.| +| value | [ValueType](#valuetype) | Yes| Value to match.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field. | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object created.| **Example** @@ -547,22 +547,22 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu lessThanOrEqualTo(field: string, value: ValueType): DataAbilityPredicates -Sets a **DataAbilityPredicates** object to match the field with data type **ValueType** and value less than or equal to the specified value. +Creates a **DataAbilityPredicates** object to search for the records in the specified column that are less than or equal to the given value. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the table. | -| value | [ValueType](#valuetype) | Yes | Value to match the **DataAbilityPredicates**. | +| field | string | Yes| Column name in the table.| +| value | [ValueType](#valuetype) | Yes| Value to match.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field. | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object created.| **Example** @@ -574,21 +574,21 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu orderByAsc(field: string): DataAbilityPredicates -Sets a **DataAbilityPredicates** object to sort the data records in ascending order. When there are multiple **orderByAsc**s, the first **orderByAsc** used has the highest priority. +Creates a **DataAbilityPredicates** object to sort the records in the specified column in ascending order. When there are multiple **orderByAsc**s, the first **orderByAsc** used has the highest priority. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the table. | +| field | string | Yes| Column name in the table.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field. | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object created.| **Example** @@ -601,21 +601,21 @@ Sets a **DataAbilityPredicates** object to sort the data records in ascending or orderByDesc(field: string): DataAbilityPredicates -Sets a **DataAbilityPredicates** object to sort the data records in descending order. When there are multiple **orderByDesc**s, the first **orderByDesc** used has the highest priority. +Creates a **DataAbilityPredicates** object to sort the records in the specified column in descending order. When there are multiple **orderByDesc**s, the first **orderByDesc** used has the highest priority. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the table. | +| field | string | Yes| Column name in the table.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field. | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object created.| **Example** @@ -628,15 +628,15 @@ Sets a **DataAbilityPredicates** object to sort the data records in descending o distinct(): DataAbilityPredicates -Sets a **DataAbilityPredicates** object to filter out duplicate records. +Creates a **DataAbilityPredicates** object to filter out duplicate records. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that can filter out duplicate records. | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object created.| **Example** @@ -648,21 +648,21 @@ Sets a **DataAbilityPredicates** object to filter out duplicate records. limitAs(value: number): DataAbilityPredicates -Set a **DataAbilityPredicates** object to specify the maximum number of records. +Creates a **DataAbilityPredicates** object to limit the number of records. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | number | Yes | Maximum number of records. | +| value | number | Yes| Maximum number of records. The value should be a positive integer. If a value less than or equal to **0** is specified, the number of records is not limited.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the maximum number of records. | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object created.| **Example** @@ -674,21 +674,21 @@ Set a **DataAbilityPredicates** object to specify the maximum number of records. offsetAs(rowOffset: number): DataAbilityPredicates -Sets a **DataAbilityPredicates** object to specify the start position of the returned result. This API must be used with **limitAs**. +Creates a **DataAbilityPredicates** object to set the start position of the query result. This API must be used together with **limitAs**. Otherwise, no result will be returned. To query all rows after the specified offset, pass in **-1** in **limitAs**. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| rowOffset | number | Yes | Number of rows to offset from the beginning. The value is a positive integer. | +| rowOffset | number | Yes| Start position. The value should be a positive integer. If a value less than or equal to **0** is specified, the query result is returned from the first element.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the start position of the returned result. | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object created.| **Example** @@ -702,21 +702,21 @@ Sets a **DataAbilityPredicates** object to specify the start position of the ret groupBy(fields: Array<string>): DataAbilityPredicates -Sets a **DataAbilityPredicates** object to group rows that have the same value into summary rows. +Creates a **DataAbilityPredicates** object to group the query results based on the specified columns. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| fields | Array<string> | Yes | Names of columns to group. | +| fields | Array<string> | Yes| Names of columns to group.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that groups rows with the same value. | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object created.| **Example** @@ -728,21 +728,21 @@ Sets a **DataAbilityPredicates** object to group rows that have the same value i indexedBy(field: string): DataAbilityPredicates -Sets a **DataAbilityPredicates** object to specify the index column. Before calling this API, you need to create an index column. +Creates a **DataAbilityPredicates** object to specify the index column. Before calling this API, you need to create an index column. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Name of the index. | +| field | string | Yes| Name of the index.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the index column. | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object created.| **Example** @@ -784,23 +784,23 @@ Sets a **DataAbilityPredicates** object to specify the index column. Before call in(field: string, value: Array<ValueType>): DataAbilityPredicates -Sets a **DataAbilityPredicates** object to match the field with data type Array\ and value within the specified range. +Creates a **DataAbilityPredicates** object to search for the records in the specified column that are in the given range. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the table. | -| value | Array<[ValueType](#valuetype)> | Yes | Array of **ValueType**s to match. | +| field | string | Yes| Column name in the table.| +| value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field. | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object created.| **Example** @@ -812,22 +812,22 @@ Sets a **DataAbilityPredicates** object to match the field with data type Array\ notIn(field: string, value: Array<ValueType>): DataAbilityPredicates -Sets a **DataAbilityPredicates** object to match the field with data type Array\ and value out of the specified range. +Creates a **DataAbilityPredicates** object to search for the records in the specified column that are out of the given range. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the table. | -| value | Array<[ValueType](#valuetype)> | Yes | Array of **ValueType**s to match. | +| field | string | Yes| Column name in the table.| +| value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field. | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object created.| **Example** @@ -839,7 +839,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type Array\ type ValueType = number | string | boolean -Enumerates the value types. +Defines the value types. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -847,4 +847,4 @@ Enumerates the value types. | ------- | -------------------- | | number | The value is a number. | | string | The value is a string. | -| boolean | The value is of Boolean type. | +| boolean | The value is of Boolean type.| diff --git a/en/application-dev/reference/apis-arkdata/js-apis-data-cloudData-sys.md b/en/application-dev/reference/apis-arkdata/js-apis-data-cloudData-sys.md index 1ccdebbd2dfb19cf878ff2ff86f02c7e66da6f1c..f6a5dc7738b802c471dce4f5bb5f534536747bee 100644 --- a/en/application-dev/reference/apis-arkdata/js-apis-data-cloudData-sys.md +++ b/en/application-dev/reference/apis-arkdata/js-apis-data-cloudData-sys.md @@ -4,18 +4,19 @@ The **cloudData** module provides APIs for implementing device-cloud synergy and Device-cloud synergy enables sync of the structured data (in RDB stores) between devices and the cloud. The cloud serves as a data hub to implement data backup in the cloud and data consistency between the devices with the same account. -Device-cloud sharing enables data sharing across accounts based on device-cloud synergy. Understanding the following concepts helps you better understand the device-cloud sharing process: +Device-cloud sharing enables data sharing across accounts based on device-cloud synergy. Understanding the following concepts helps you better understand the device-cloud sharing process: - **sharingResource**: an identifier of the string type generated for each data record shared by an application before device-cloud sync is performed. It uniquely identifies the data record being shared. - **Participant**: all participants involved in a share, including the inviter and invitees. + - **invitationCode**: an invitation code generated by the share server for a share operation. It is generated after a data share is initiated and attached to an invitation pushed to the devices of target invitees. The target invitees then confirm the invitation via this code. The **cloudData** module provides the following functionalities: - [Config](#config): provides APIs for setting device-cloud synergy, including enabling and disabling device-cloud sync, clearing data, and notifying data changes. -- [sharing11+](#sharing11): provides APIs for device-cloud sharing, including sharing or unsharing data, exiting a share, changing the privilege on the shared data, querying participants, confirming an invitation, changing invitation confirmation state, and querying the shared resource. +- [sharing](#sharing11): provides APIs for device-cloud data sharing, including sharing or unsharing data, exiting a share, changing the privilege on the shared data, querying participants, confirming an invitation, changing the invitation confirmation state, and querying the shared resource. -> **NOTE** +> **NOTE** > > - The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version. > @@ -37,7 +38,7 @@ Enumerates the operations for clearing the downloaded cloud data locally. | Name | Description | | --------- | ---------------------------- | -| CLEAR_CLOUD_INFO | Clear the cloud identifier of the data downloaded from the cloud and retain the data locally. | +| CLEAR_CLOUD_INFO | Clear the cloud identifier of the data downloaded from the cloud and retain the data locally.| | CLEAR_CLOUD_DATA_AND_INFO |Clear the data downloaded from the cloud, excluding the cloud data that has been modified locally. | ## ExtraData11+ @@ -46,7 +47,7 @@ Represents the transparently transmitted data, which contains information requir **System capability**: SystemCapability.DistributedDataManager.CloudSync.Config -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | --------- | ------ | ---- | ------------------------------------------------------------ | | eventId | string | Yes | Event ID. The value **cloud_data_change** indicates cloud data changes. | | extraData | string | Yes | Data to be transmitted transparently.
**extraData** is a JSON string that must contain the **data** field. The **data** field contains information required for a change notification, including the account ID, application name, database name, database type, and database table name. All the fields cannot be empty. | @@ -58,7 +59,7 @@ Represents the transparently transmitted data, which contains information requir // bundleName: application bundle name. // containerName: name of the cloud database. // databaseScopes: type of the cloud database. -// recordTypes: name of the cloud database table. +// recordTypes: names of the tables in the cloud database. interface ExtraData { eventId: "cloud_data_change", @@ -81,24 +82,36 @@ Represents the device-cloud sync statistics. **System capability**: SystemCapability.DistributedDataManager.CloudSync.Config -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | --------- | ------ | ---- |-----------------------------------------------------| -| table | string | Yes | Name of the table queried. For example, the value **cloud_notes** indicates that the sync information of the **cloud_notes** table is queried. | +| table | string | Yes | Name of the table queried. For example, the value **cloud_notes** indicates that the sync information of the **cloud_notes** table is queried.| | inserted | number | Yes | Number of data records that are added locally and have not been synced to the cloud. For example, the value **2** indicates that the table has two data records that are added locally but not synced to the cloud. | | updated | number | Yes | Number of data records that are modified locally or on the cloud but have not been synced. For example, the value **2** indicates that the table has two data records that are updated locally or on the cloud but not synced. | | normal | number | Yes | Number of consistent data records between the device and the cloud. For example, the value **2** indicates that table has two data records that are consistent between the device and the cloud. | +## SyncStatus18+ + +Enumerates the device-cloud sync task statuses. + +**System capability**: SystemCapability.DistributedDataManager.CloudSync.Config + +| Name | Value | Description | +| -------- |-----|-----------------| +| RUNNING | 0 | The device-cloud sync task is running.| +| FINISHED | 1 | The device-cloud sync task is completed.| + ## SyncInfo12+ -Represents information required for the last device-cloud sync. +Represents information about the last device-cloud sync. **System capability**: SystemCapability.DistributedDataManager.CloudSync.Config -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | -------------------------- | -| startTime | Date | Yes | Start time of the last device-cloud sync. | -| finishTime | Date | Yes | End time of the last device-cloud sync. | -| code | [relationalStore.ProgressCode](js-apis-data-relationalStore.md#progresscode10) | Yes | Status of the last device-cloud sync. | +| startTime | Date | Yes | Start time of the last device-cloud sync.| +| finishTime | Date | Yes | End time of the last device-cloud sync.| +| code | [relationalStore.ProgressCode](js-apis-data-relationalStore.md#progresscode10) | Yes | Result of the last device-cloud sync.| +| syncStatus18+ | [SyncStatus](#syncstatus18) | No| Status of the last device-cloud sync. The default value is **cloudData.SyncStatus.RUNNING**.| ## Config @@ -116,17 +129,17 @@ Enables device-cloud synergy. This API uses an asynchronous callback to return t **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | --------- | ------------------------------- | ---- | ------------------------------------------------------------ | | accountId | string | Yes | ID of the cloud account. | -| switches | Record | Yes | Device-cloud synergy settings for applications. The value **true** means to enable device-cloud synergy; the value **false** means the opposite. | +| switches | Record | Yes | Device-cloud synergy settings for applications. The value **true** means to enable device-cloud synergy; the value **false** means the opposite.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------- | | 201 | Permission verification failed, usually the result returned by VerifyAccessToken.| | 202 | Permission verification failed, application which is not a system application uses system API.| @@ -166,22 +179,22 @@ Enables device-cloud synergy. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | --------- | ------------------------------- | ---- | ------------------------------------------------------------ | | accountId | string | Yes | ID of the cloud account. | -| switches | Record | Yes | Device-cloud synergy settings for applications. The value **true** means to enable device-cloud synergy; the value **false** means the opposite. | +| switches | Record | Yes | Device-cloud synergy settings for applications. The value **true** means to enable device-cloud synergy; the value **false** means the opposite.| **Return value** | Type | Description | | ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value. | +| Promise<void> | Promise that returns no value.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------- | | 201 | Permission verification failed, usually the result returned by VerifyAccessToken.| | 202 | Permission verification failed, application which is not a system application uses system API.| @@ -219,16 +232,16 @@ Disables device-cloud synergy. This API uses an asynchronous callback to return **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | --------- | ------------------------- | ---- | -------------------- | -| accountId | string | Yes | ID of the cloud account. | +| accountId | string | Yes | ID of the cloud account.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------- | | 201 | Permission verification failed, usually the result returned by VerifyAccessToken.| | 202 | Permission verification failed, application which is not a system application uses system API.| @@ -267,21 +280,21 @@ Disables device-cloud synergy. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | --------- | ------ | ---- | -------------------- | -| accountId | string | Yes | ID of the cloud account. | +| accountId | string | Yes | ID of the cloud account.| **Return value** | Type | Description | | ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value. | +| Promise<void> | Promise that returns no value.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------- | | 201 | Permission verification failed, usually the result returned by VerifyAccessToken.| | 202 | Permission verification failed, application which is not a system application uses system API.| @@ -318,18 +331,18 @@ Changes the device-cloud synergy setting for an application. This API uses an as **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | --------- | ------------------------------- | ---- | ---------------------------- | -| accountId | string | Yes | ID of the cloud account. | -| bundleName| string | Yes | Bundle name of the application. | -| status | boolean | Yes | Device-cloud synergy setting for the application. The value **true** means to enable device-cloud synergy; the value **false** means the opposite. | +| accountId | string | Yes | ID of the cloud account.| +| bundleName| string | Yes | Bundle name of the application.| +| status | boolean | Yes | New device-cloud synergy setting. The value **true** means to enable device-cloud synergy; the value **false** means the opposite.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------- | | 201 | Permission verification failed, usually the result returned by VerifyAccessToken.| | 202 | Permission verification failed, application which is not a system application uses system API.| @@ -369,23 +382,23 @@ Changes the device-cloud synergy setting for an application. This API uses a pro **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | --------- | ------------------------------- | ---- | ---------------------------- | -| accountId | string | Yes | ID of the cloud account. | -| bundleName| string | Yes | Bundle name of the application. | -| status | boolean | Yes | Device-cloud synergy setting for the application. The value **true** means to enable device-cloud synergy; the value **false** means the opposite. | +| accountId | string | Yes | ID of the cloud account.| +| bundleName| string | Yes | Bundle name of the application.| +| status | boolean | Yes | New device-cloud synergy setting. The value **true** means to enable device-cloud synergy; the value **false** means the opposite.| **Return value** | Type | Description | | ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value. | +| Promise<void> | Promise that returns no value.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------- | | 201 | Permission verification failed, usually the result returned by VerifyAccessToken.| | 202 | Permission verification failed, application which is not a system application uses system API.| @@ -423,9 +436,9 @@ Notifies the data changes in the cloud. This API uses an asynchronous callback t **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ---------- | ------------------------- | ---- | -------------------- | -| accountId | string | Yes | ID of the cloud account. | +| accountId | string | Yes | ID of the cloud account.| | bundleName | string | Yes | Bundle name of the application. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. | @@ -433,7 +446,7 @@ Notifies the data changes in the cloud. This API uses an asynchronous callback t For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------- | | 201 | Permission verification failed, usually the result returned by VerifyAccessToken.| | 202 | Permission verification failed, application which is not a system application uses system API.| @@ -473,22 +486,22 @@ Notifies the data changes in the cloud. This API uses a promise to return the re **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ---------- | ------ | ---- | -------------------- | -| accountId | string | Yes | ID of the cloud account. | +| accountId | string | Yes | ID of the cloud account.| | bundleName | string | Yes | Bundle name of the application. | **Return value** | Type | Description | | ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value. | +| Promise<void> | Promise that returns no value.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------- | | 201 | Permission verification failed, usually the result returned by VerifyAccessToken.| | 202 | Permission verification failed, application which is not a system application uses system API.| @@ -516,7 +529,7 @@ try { ### notifyDataChange11+ - **static** notifyDataChange(extInfo: ExtraData, callback: AsyncCallback<void>):void + static notifyDataChange(extInfo: ExtraData, callback: AsyncCallback<void>):void Notifies the data changes in the cloud with the specified information, such as the database and table names (specified by the **extraData** field in **extInfo**). This API uses an asynchronous callback to return the result. @@ -526,16 +539,16 @@ Notifies the data changes in the cloud with the specified information, such as t **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | --------------------------------------- | -| extInfo | [ExtraData](#extradata11) | Yes | Transparently transmitted data, including information about the application that has data changes. | +| extInfo | [ExtraData](#extradata11) | Yes | Transparently transmitted data, including information about the application that has data changes.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------- | | 201 | Permission verification failed, which is usually returned by VerifyAccessToken.| | 202 | Permission verification failed, application which is not a system application uses system API.| @@ -577,17 +590,17 @@ Notifies the data changes of a user in the cloud. This API uses an asynchronous **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ----------------------------------------------- | | extInfo | [ExtraData](#extradata11) | Yes | Transparently transmitted data, including information about the application that has data changes. | -| userId | number | Yes | User ID in the system. | +| userId | number | Yes | User ID in the system.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------- | | 201 | Permission verification failed, which is usually returned by VerifyAccessToken.| | 202 | Permission verification failed, application which is not a system application uses system API.| @@ -620,7 +633,7 @@ try { ### notifyDataChange11+ -**static** notifyDataChange(extInfo: ExtraData, userId?: number): Promise<void> +static notifyDataChange(extInfo: ExtraData, userId?: number): Promise<void> Notifies the data changes in the cloud. This API uses a promise to return the result. You can specify the database and tables with data changes in the **extraData** field in **extInfo**, and specify the user ID. @@ -630,22 +643,22 @@ Notifies the data changes in the cloud. This API uses a promise to return the re **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ------- | ----------------------- | ---- | ----------------------------------------------- | | extInfo | [ExtraData](#extradata11) | Yes | Transparently transmitted data, including information about the application that has data changes. | -| userId | number | No | User ID. This parameter is optional. The default value is the current user ID. If this parameter is specified, the value must be an existing user ID in the system. | +| userId | number | No | User ID. This parameter is optional. The default value is the current user ID. If this parameter is specified, the value must be an existing user ID in the system.| **Return value** | Type | Description | | ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value. | +| Promise<void> | Promise that returns no value.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------- | | 201 | Permission verification failed, which is usually returned by VerifyAccessToken.| | 202 | Permission verification failed, application which is not a system application uses system API.| @@ -678,7 +691,7 @@ try { static queryStatistics(accountId: string, bundleName: string, storeId?: string): Promise<Record<string, Array<StatisticInfo>>> -Queries device-cloud data statistics, which include the data not synchronized, data synced and consistent, and data synced but inconsistent between the device and the cloud. This API uses a promise to return the result. +Queries device-cloud data statistics, which include the data not synced, data synced and consistent, and data synced but inconsistent between the device and the cloud. This API uses a promise to return the result. **Required permissions**: ohos.permission.CLOUDDATA_CONFIG @@ -686,23 +699,23 @@ Queries device-cloud data statistics, which include the data not synchronized, d **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ------- |---------| ---- |-----------------------------------| | accountId | string | Yes | ID of the cloud account. | | bundleName | string | Yes | Bundle name of the application. | -| storeId | string | No | Name of the RDB store. If this parameter is not specified, all local databases of this application are queried by default. | +| storeId | string | No | Name of the RDB store. If this parameter is not specified, all local databases of this application are queried by default.| **Return value** | Type | Description | |--------------------------------------------------------------------------------------| ------------------------ | -| Promise<Record<string, Array<[StatisticInfo](#statisticinfo12)>>> | Promise used to return the table name and statistics. | +| Promise<Record<string, Array<[StatisticInfo](#statisticinfo12)>>> | Promise used to return the table name and statistics.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------- | | 201 | Permission verification failed, usually the result returned by VerifyAccessToken.| | 202 | Permission verification failed, application which is not a system application uses system API.| @@ -737,23 +750,23 @@ Queries information about the last device-cloud sync. This API uses a promise to **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ---------- | ------ | ---- | ------------------------------------------------------------ | | accountId | string | Yes | ID of the cloud account. | | bundleName | string | Yes | Bundle name of the application. | -| storeId | string | No | Name of the RDB store. The default value is an empty string. If the default value is used, this API queries the last device-cloud sync information of all databases of this application. | +| storeId | string | No | Name of the RDB store. The default value is an empty string. If the default value is used, this API queries the last device-cloud sync information of all databases of this application.| **Return value** | Type | Description | | ------------------------------------------------------------ | -------------------------------------------- | -| Promise<Record<string, [SyncInfo](#syncinfo12)>> | Promise used to return the database name and the result set of the last device-cloud sync. | +| Promise<Record<string, [SyncInfo](#syncinfo12)>> | Promise used to return the database name and the result set of the last device-cloud sync.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------- | | 201 | Permission verification failed, usually the result returned by VerifyAccessToken.| | 202 | Permission verification failed, application which is not a system application uses system API.| @@ -792,22 +805,22 @@ Sets a global device-cloud sync strategy. This API uses a promise to return the **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ---------- |------------------------------------------------------------------------| ---- |-------------------| | strategy | [StrategyType](js-apis-data-cloudData.md#strategytype) | Yes | Type of the strategy to set. | -| param | Array<[commonType.ValueType](js-apis-data-commonType.md#valuetype)> | No | Strategy parameters to set. If this parameter is not specified, all the strategy configuration is canceled by default. | +| param | Array<[commonType.ValueType](js-apis-data-commonType.md#valuetype)> | No | Strategy parameters to set. If this parameter is not specified, the strategy configuration is deleted by default. | **Return value** | Type | Description | | ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value. | +| Promise<void> | Promise that returns no value.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------- | | 201 | Permission verification failed, usually the result returned by VerifyAccessToken.| | 202 | Permission verification failed, application which is not a system application uses system API.| @@ -838,17 +851,17 @@ Clears the cloud data locally. This API uses an asynchronous callback to return **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ---------- | --------------------------------------------------- | ---- | -------------------------------- | | accountId | string | Yes | ID of the cloud account. | -| appActions | Record | Yes | Information about the application whose data is to be cleared and the operation to perform. | +| appActions | Record | Yes | Information about the application whose data is to be cleared and the operation to perform.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------- | | 201 | Permission verification failed, usually the result returned by VerifyAccessToken.| | 202 | Permission verification failed, application which is not a system application uses system API.| @@ -892,22 +905,22 @@ Clears the cloud data locally. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ---------- | --------------------------------------------------- | ---- | -------------------------------- | | accountId | string | Yes | ID of the cloud account. | -| appActions | Record | Yes | Information about the application whose data is to be cleared and the operation to perform. | +| appActions | Record | Yes | Information about the application whose data is to be cleared and the operation to perform.| **Return value** | Type | Description | | ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value. | +| Promise<void> | Promise that returns no value.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------- | | 201 | Permission verification failed, usually the result returned by VerifyAccessToken.| | 202 | Permission verification failed, application which is not a system application uses system API.| @@ -949,8 +962,8 @@ Enumerates the roles of the participants in a device-cloud share. | Name | Value | Description | | --------------| ---- | ---------------------------------- | -| ROLE_INVITER | 0 | Inviter, the one who shares data. Use the enum name rather than the enum value. | -| ROLE_INVITEE | 1 | Invitee, the one who can use the shared data. Use the enum name rather than the enum value. | +| ROLE_INVITER | 0 | Inviter, the one who shares data. Use the enum name rather than the enum value.| +| ROLE_INVITEE | 1 | Invitee, the one who can use the shared data. Use the enum name rather than the enum value.| ### State11+ @@ -961,10 +974,10 @@ Enumerates the device-cloud sharing states. | Name | Value | Description | | --------------| ---- | ---------------------------------- | | STATE_UNKNOWN | 0 | Unknown state. Use the enum name rather than the enum value. | -| STATE_ACCEPTED | 1 | The device-cloud sharing invitation is accepted. Use the enum name rather than the enum value. | -| STATE_REJECTED | 2 | The device-cloud sharing invitation is rejected. Use the enum name rather than the enum value. | -| STATE_SUSPENDED | 3 | The device-cloud sharing is suspended temporarily. Use the enum name rather than the enum value. | -| STATE_UNAVAILABLE12+ | 4 | The device-cloud sharing is unavailable. Use the enum name rather than the enum value. | +| STATE_ACCEPTED | 1 | The device-cloud sharing invitation is accepted. Use the enum name rather than the enum value.| +| STATE_REJECTED | 2 | The device-cloud sharing invitation is rejected. Use the enum name rather than the enum value.| +| STATE_SUSPENDED | 3 | The device-cloud sharing is suspended temporarily. Use the enum name rather than the enum value.| +| STATE_UNAVAILABLE12+ | 4 | The device-cloud sharing is unavailable. Use the enum name rather than the enum value.| ### SharingCode11+ @@ -975,19 +988,19 @@ Enumerates the error codes for device-cloud sharing. | Name | Value | Description | | --------------| ---- | ---------------------------------- | | SUCCESS | 0 | Operation successful. Use the enum name rather than the enum value. | -| REPEATED_REQUEST | 1 | Repeated invitation, which means the participant has been invited. Use the enum name rather than the enum value. | -| NOT_INVITER | 2 | The participant is not the inviter of this share. Use the enum name rather than the enum value. | -| NOT_INVITER_OR_INVITEE | 3 | Invalid participant, which means the participant is neither the inviter nor the invitee. Use the enum name rather than the enum value. | +| REPEATED_REQUEST | 1 | Repeated invitation, which means the participant has been invited. Use the enum name rather than the enum value.| +| NOT_INVITER | 2 | The participant is not the inviter of this share. Use the enum name rather than the enum value.| +| NOT_INVITER_OR_INVITEE | 3 | Invalid participant, which means the participant is neither the inviter nor the invitee. Use the enum name rather than the enum value.| | OVER_QUOTA | 4 | The number of device-cloud sharing times has reached the limit for the current account. Use the enum name rather than the enum value. | -| TOO_MANY_PARTICIPANTS | 5 | The number of device-cloud sharing participants has reached the limit. Use the enum name rather than the enum value. | -| INVALID_ARGS | 6 | Invalid parameter. Use the enum name rather than the enum value. | -| NETWORK_ERROR | 7 | Network error. Use the enum name rather than the enum value. | +| TOO_MANY_PARTICIPANTS | 5 | The number of device-cloud sharing participants has reached the limit. Use the enum name rather than the enum value.| +| INVALID_ARGS | 6 | Invalid parameter. Use the enum name rather than the enum value.| +| NETWORK_ERROR | 7 | Network error. Use the enum name rather than the enum value.| | CLOUD_DISABLED | 8 | Cloud is disabled. Use the enum name rather than the enum value. | -| SERVER_ERROR | 9 | Server error. Use the enum name rather than the enum value. | -| INNER_ERROR | 10 | System internal error. Use the enum name rather than the enum value. | -| INVALID_INVITATION | 11 | Invalid invitation, which means the current invitation has expired or does not exist. Use the enum name rather than the enum value. | -| RATE_LIMIT | 12 | The amount of data to be synchronized at a time has reached the limit. Use the enum name rather than the enum value. | -| CUSTOM_ERROR | 1000 | Customized error. Error codes smaller than **1000** are used to define internal error codes, and error codes greater than **1000** are used to customize error codes. Use the enum name rather than the enum value. | +| SERVER_ERROR | 9 | Server error. Use the enum name rather than the enum value.| +| INNER_ERROR | 10 | System internal error. Use the enum name rather than the enum value.| +| INVALID_INVITATION | 11 | Invalid invitation, which means the current invitation has expired or does not exist. Use the enum name rather than the enum value.| +| RATE_LIMIT | 12 | The amount of data to be synced at a time has reached the limit. Use the enum name rather than the enum value. | +| CUSTOM_ERROR | 1000 | Customized error. Error codes smaller than **1000** are used to define internal error codes, and error codes greater than **1000** are used to customize error codes. Use the enum name rather than the enum value.| ### Result<T>11+ @@ -999,7 +1012,7 @@ Represents the device-cloud sharing result. | ----------- | --------------------------- | --- | ------------ | | code | number | Yes | Error code. | | description | string | No | Detailed description of the error code. The default value is **undefined**. | -| value | T | No | Value returned. The specific type is specified by the **T** parameter. The default value is **undefined**. | +| value | T | No | Value returned. The specific type is specified by the **T** parameter. The default value is **undefined**.| ### Privilege11+ @@ -1025,9 +1038,9 @@ Represents information about a participant of device-cloud sharing. | ----------- | --------------------------- | --- | ------------ | | identity | string | Yes | ID of the participant. | | role | [Role](#role11) | No | Role of the participant, inviter or invitee. The default value is **undefined**. | -| state | [State](#state11) | No | State of the device-cloud sharing. The default value is **undefined**. | -| privilege | [Privilege](#privilege11) | No | Permissions on the shared data. The [Privilege](#privilege11) defaults are used by default. | -| attachInfo | string | No | Additional information, such as the verification code used for participant identity verification. The default value is an empty string. | +| state | [State](#state11) | No | State of the device-cloud sharing. The default value is **undefined**.| +| privilege | [Privilege](#privilege11) | No | Permissions on the shared data. The [Privilege](#privilege11) defaults are used by default.| +| attachInfo | string | No | Additional information, such as the verification code used for participant identity verification. The default value is an empty string.| ### allocResourceAndShare11+ @@ -1039,24 +1052,24 @@ Allocates a shared resource ID based on the data that matches the specified pred **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | --------- | ------------------------------- | ---- | ---------------------------- | -| storeId | string | Yes | Name of the RDB store. | -| predicates | [relationalStore.RdbPredicates](js-apis-data-relationalStore.md#rdbpredicates) | Yes | Predicates for matching the data to share. | -| participants | Array<[Participant](#participant11)> | Yes | Participants of the share. | -| columns | Array<string> | No | Columns in which the data is located. The default value is **undefined**, which means column names are not returned. | +| storeId | string | Yes | Name of the RDB store.| +| predicates | [relationalStore.RdbPredicates](js-apis-data-relationalStore.md#rdbpredicates) | Yes | Predicates for matching the data to share.| +| participants | Array<[Participant](#participant11)> | Yes | Participants of the share.| +| columns | Array<string> | No | Columns in which the data is located. The default value is **undefined**, which means column names are not returned.| **Return value** | Type | Description | | ------------------- | ------------------------- | -| Promise<[relationalStore.ResultSet](js-apis-data-relationalStore.md#resultset)> | Promise used to return the result set of the data to share. | +| Promise<[relationalStore.ResultSet](js-apis-data-relationalStore.md#resultset)> | Promise used to return the result set of the data to share.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------- | | 202 | Permission verification failed, application which is not a system application uses system API.| | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.| @@ -1109,19 +1122,19 @@ Allocates a shared resource ID based on the data that matches the specified pred **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | --------- | ------------------------------- | ---- | ---------------------------- | -| storeId | string | Yes | Name of the RDB store. | -| predicates | [relationalStore.RdbPredicates](js-apis-data-relationalStore.md#rdbpredicates) | Yes | Predicates for matching the data to share. | -| participants | Array<[Participant](#participant11)> | Yes | Participants of the share. | -| columns | Array<string> | Yes | Columns in which the data is located. | -| callback | AsyncCallback<[relationalStore.ResultSet](js-apis-data-relationalStore.md#resultset)> | Yes | Callback used to return the result set of the data to share. | +| storeId | string | Yes | Name of the RDB store.| +| predicates | [relationalStore.RdbPredicates](js-apis-data-relationalStore.md#rdbpredicates) | Yes | Predicates for matching the data to share.| +| participants | Array<[Participant](#participant11)> | Yes | Participants of the share.| +| columns | Array<string> | Yes | Columns in which the data is located.| +| callback | AsyncCallback<[relationalStore.ResultSet](js-apis-data-relationalStore.md#resultset)> | Yes | Callback used to return the result set of the data to share.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------- | | 202 | Permission verification failed, application which is not a system application uses system API.| | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.| @@ -1176,18 +1189,18 @@ Allocates a shared resource ID based on the data that matches the specified pred **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | --------- | ------------------------------- | ---- | ---------------------------- | -| storeId | string | Yes | Name of the RDB store. | -| predicates | [relationalStore.RdbPredicates](js-apis-data-relationalStore.md#rdbpredicates) | Yes | Predicates for matching the data to share. | -| participants | Array<[Participant](#participant11)> | Yes | Participants of the share. | -| callback | AsyncCallback<[relationalStore.ResultSet](js-apis-data-relationalStore.md#resultset)> | Yes | Callback used to return the result set of the data to share. | +| storeId | string | Yes | Name of the RDB store.| +| predicates | [relationalStore.RdbPredicates](js-apis-data-relationalStore.md#rdbpredicates) | Yes | Predicates for matching the data to share.| +| participants | Array<[Participant](#participant11)> | Yes | Participants of the share.| +| callback | AsyncCallback<[relationalStore.ResultSet](js-apis-data-relationalStore.md#resultset)> | Yes | Callback used to return the result set of the data to share.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------- | | 202 | Permission verification failed, application which is not a system application uses system API.| | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.| @@ -1242,22 +1255,22 @@ Shares data based on the specified shared resource ID and participants. This API **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | --------- | ------------------------------- | ---- | ---------------------------- | -| sharingResource | string | Yes | Shared resource ID. | -| participants | Array<[Participant](#participant11)> | Yes | Participants of the share. | +| sharingResource | string | Yes | Shared resource ID.| +| participants | Array<[Participant](#participant11)> | Yes | Participants of the share.| **Return value** | Type | Description | | ------------------- | ------------------------- | -| Promise<[Result](#resultt11)<Array<[Result](#resultt11)<[Participant](#participant11)>>>> | Promise used to return the result. | +| Promise<[Result](#resultt11)<Array<[Result](#resultt11)<[Participant](#participant11)>>>> | Promise used to return the result.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------- | | 202 | Permission verification failed, application which is not a system application uses system API.| | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.| @@ -1300,17 +1313,17 @@ Shares data based on the specified shared resource ID and participants. This API **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | --------- | ------------------------------- | ---- | ---------------------------- | -| sharingResource | string | Yes | Shared resource ID. | -| participants | Array<[Participant](#participant11)> | Yes | Participants of the share. | -| callback | AsyncCallback<[Result](#resultt11)<Array<[Result](#resultt11)<[Participant](#participant11)>>>> | Yes | Callback used to return the result. | +| sharingResource | string | Yes | Shared resource ID.| +| participants | Array<[Participant](#participant11)> | Yes | Participants of the share.| +| callback | AsyncCallback<[Result](#resultt11)<Array<[Result](#resultt11)<[Participant](#participant11)>>>> | Yes | Callback used to return the result. | **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------- | | 202 | Permission verification failed, application which is not a system application uses system API.| | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.| @@ -1355,22 +1368,22 @@ Unshares data based on the specified shared resource ID and participants. This A **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | --------- | ------------------------------- | ---- | ---------------------------- | -| sharingResource | string | Yes | Shared resource ID. | -| participants | Array<[Participant](#participant11)> | Yes | Participants of the share. | +| sharingResource | string | Yes | Shared resource ID.| +| participants | Array<[Participant](#participant11)> | Yes | Participants of the share.| **Return value** | Type | Description | | ------------------- | ------------------------- | -| Promise<[Result](#resultt11)<Array<[Result](#resultt11)<[Participant](#participant11)>>>> | Promise used to return the result. | +| Promise<[Result](#resultt11)<Array<[Result](#resultt11)<[Participant](#participant11)>>>> | Promise used to return the result.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------- | | 202 | Permission verification failed, application which is not a system application uses system API.| | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.| @@ -1413,17 +1426,17 @@ Unshares data based on the specified shared resource ID and participants. This A **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | --------- | ------------------------------- | ---- | ---------------------------- | -| sharingResource | string | Yes | Shared resource ID. | -| participants | Array<[Participant](#participant11)> | Yes | Participants of the share. | -| callback | AsyncCallback<[Result](#resultt11)<Array<[Result](#resultt11)<[Participant](#participant11)>>>> | Yes | Callback used to return the result. | +| sharingResource | string | Yes | Shared resource ID.| +| participants | Array<[Participant](#participant11)> | Yes | Participants of the share.| +| callback | AsyncCallback<[Result](#resultt11)<Array<[Result](#resultt11)<[Participant](#participant11)>>>> | Yes | Callback used to return the result. | **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------- | | 202 | Permission verification failed, application which is not a system application uses system API.| | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.| @@ -1468,21 +1481,21 @@ Exits the share of the specified shared resource. This API uses a promise to ret **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | --------- | ------------------------------- | ---- | ---------------------------- | -| sharingResource | string | Yes | Shared resource ID. | +| sharingResource | string | Yes | Shared resource ID.| **Return value** | Type | Description | | ------------------- | ------------------------- | -| Promise<[Result](#resultt11)<void>> | Promise used to return the result. | +| Promise<[Result](#resultt11)<void>> | Promise used to return the result.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------- | | 202 | Permission verification failed, application which is not a system application uses system API.| | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.| @@ -1511,16 +1524,16 @@ Exits the share of the specified shared resource. This API uses an asynchronous **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | --------- | ------------------------------- | ---- | ---------------------------- | -| sharingResource | string | Yes | Shared resource ID. | -| callback | AsyncCallback<[Result](#resultt11)<void>> | Yes | Callback used to return the result. | +| sharingResource | string | Yes | Shared resource ID.| +| callback | AsyncCallback<[Result](#resultt11)<void>> | Yes | Callback used to return the result. | **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------- | | 202 | Permission verification failed, application which is not a system application uses system API.| | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.| @@ -1551,22 +1564,22 @@ Changes the privilege on the shared data. This API uses a promise to return the **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | --------- | ------------------------------- | ---- | ---------------------------- | -| sharingResource | string | Yes | Shared resource ID. | +| sharingResource | string | Yes | Shared resource ID.| | participants | Array<[Participant](#participant11)> | Yes | Participants with new privilege.| **Return value** | Type | Description | | ------------------- | ------------------------- | -| Promise<[Result](#resultt11)<Array<[Result](#resultt11)<[Participant](#participant11)>>>> | Promise used to return the result. | +| Promise<[Result](#resultt11)<Array<[Result](#resultt11)<[Participant](#participant11)>>>> | Promise used to return the result.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------- | | 202 | Permission verification failed, application which is not a system application uses system API.| | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.| @@ -1610,17 +1623,17 @@ Changes the privilege on the shared data. This API uses an asynchronous callback **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | --------- | ------------------------------- | ---- | ---------------------------- | -| sharingResource | string | Yes | Shared resource ID. | +| sharingResource | string | Yes | Shared resource ID.| | participants | Array<[Participant](#participant11)> | Yes | Participants with new privilege.| -| callback | callback: AsyncCallback<[Result](#resultt11)<Array<[Result](#resultt11)<[Participant](#participant11)>>>> | Yes | Callback used to return the result. | +| callback | callback: AsyncCallback<[Result](#resultt11)<Array<[Result](#resultt11)<[Participant](#participant11)>>>> | Yes | Callback used to return the result. | **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------- | | 202 | Permission verification failed, application which is not a system application uses system API.| | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.| @@ -1666,21 +1679,21 @@ Queries the participants of the specified shared data. This API uses a promise t **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | --------- | ------------------------------- | ---- | ---------------------------- | -| sharingResource | string | Yes | Shared resource ID. | +| sharingResource | string | Yes | Shared resource ID.| **Return value** | Type | Description | | ------------------- | ------------------------- | -| Promise<[Result](#resultt11)<Array<[Participant](#participant11)>>> | Promise used to return the participants obtained. | +| Promise<[Result](#resultt11)<Array<[Participant](#participant11)>>> | Promise used to return the participants obtained.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------- | | 202 | Permission verification failed, application which is not a system application uses system API.| | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.| @@ -1709,16 +1722,16 @@ Queries the participants of the specified shared data. This API uses an asynchro **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | --------- | ------------------------------- | ---- | ---------------------------- | -| sharingResource | string | Yes | Shared resource ID. | -| callback | AsyncCallback<[Result](#resultt11)<Array<[Participant](#participant11)>>> | Yes | Callback used to return the participants obtained. | +| sharingResource | string | Yes | Shared resource ID.| +| callback | AsyncCallback<[Result](#resultt11)<Array<[Participant](#participant11)>>> | Yes | Callback used to return the participants obtained.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------- | | 202 | Permission verification failed, application which is not a system application uses system API.| | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.| @@ -1749,9 +1762,9 @@ Queries the participants based on the sharing invitation code. This API uses a p **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | --------- | ------------------------------- | ---- | ---------------------------- | -| invitationCode | string | Yes | Invitation code of the share. | +| invitationCode | string | Yes | Invitation code of the share.| **Return value** @@ -1763,7 +1776,7 @@ Queries the participants based on the sharing invitation code. This API uses a p For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------- | | 202 | Permission verification failed, application which is not a system application uses system API.| | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.| @@ -1792,16 +1805,16 @@ Queries the participants based on the sharing invitation code. This API uses an **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | --------- | ------------------------------- | ---- | ---------------------------- | -| invitationCode | string | Yes | Invitation code of the share. | -| callback | AsyncCallback<[Result](#resultt11)<Array<[Participant](#participant11)>>> | Yes | Callback used to return the participants obtained. | +| invitationCode | string | Yes | Invitation code of the share.| +| callback | AsyncCallback<[Result](#resultt11)<Array<[Participant](#participant11)>>> | Yes | Callback used to return the participants obtained.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------- | | 202 | Permission verification failed, application which is not a system application uses system API.| | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.| @@ -1832,22 +1845,22 @@ Confirms the invitation based on the sharing invitation code and obtains the sha **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | --------- | ------------------------------- | ---- | ---------------------------- | -| invitationCode | string | Yes | Invitation code of the share. | -| state | [State](#state11) | Yes | Confirmation state. | +| invitationCode | string | Yes | Invitation code of the share.| +| state | [State](#state11) | Yes | Confirmation state.| **Return value** | Type | Description | | ------------------- | ------------------------- | -| Promise<[Result](#resultt11)<string>> | Promise used to return the result. | +| Promise<[Result](#resultt11)<string>> | Promise used to return the result.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------- | | 202 | Permission verification failed, application which is not a system application uses system API.| | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.| @@ -1878,17 +1891,17 @@ Confirms the invitation based on the sharing invitation code and obtains the sha **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | --------- | ------------------------------- | ---- | ---------------------------- | -| invitationCode | string | Yes | Invitation code of the share. | -| state | [State](#state11) | Yes | Confirmation state. | -| callback | AsyncCallback<[Result](#resultt11)<string>> | Yes | Callback used to return the result. | +| invitationCode | string | Yes | Invitation code of the share.| +| state | [State](#state11) | Yes | Confirmation state.| +| callback | AsyncCallback<[Result](#resultt11)<string>> | Yes | Callback used to return the result. | **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------- | | 202 | Permission verification failed, application which is not a system application uses system API.| | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.| @@ -1921,22 +1934,22 @@ Changes the invitation confirmation state based on the shared resource ID. This **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | --------- | ------------------------------- | ---- | ---------------------------- | -| sharingResource | string | Yes | Shared resource ID. | -| state | [State](#state11) | Yes | New confirmation state of the invitation. | +| sharingResource | string | Yes | Shared resource ID.| +| state | [State](#state11) | Yes | New confirmation state of the invitation.| **Return value** | Type | Description | | ------------------- | ------------------------- | -| Promise<[Result](#resultt11)<void>> | Promise used to return the result. | +| Promise<[Result](#resultt11)<void>> | Promise used to return the result.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------- | | 202 | Permission verification failed, application which is not a system application uses system API.| | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.| @@ -1965,17 +1978,17 @@ Changes the invitation confirmation state based on the shared resource ID. This **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | --------- | ------------------------------- | ---- | ---------------------------- | -| sharingResource | string | Yes | Shared resource ID. | -| state | [State](#state11) | Yes | New confirmation state of the invitation. | -| callback | AsyncCallback<[Result](#resultt11)<void>> | Yes | Callback used to return the result. | +| sharingResource | string | Yes | Shared resource ID.| +| state | [State](#state11) | Yes | New confirmation state of the invitation.| +| callback | AsyncCallback<[Result](#resultt11)<void>> | Yes | Callback used to return the result. | **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message | | -------- | ---------------------------------------------------- | | 202 | Permission verification failed, application which is not a system application uses system API.| | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.| diff --git a/en/application-dev/reference/apis-arkdata/js-apis-data-cloudData.md b/en/application-dev/reference/apis-arkdata/js-apis-data-cloudData.md index 15e5fe4c74c0aeba00345da3b0a9db0d88c5b972..e95f5ad0da2f85fe0ac657bd658f169168d6403a 100644 --- a/en/application-dev/reference/apis-arkdata/js-apis-data-cloudData.md +++ b/en/application-dev/reference/apis-arkdata/js-apis-data-cloudData.md @@ -7,7 +7,7 @@ This module also provides the capability of setting the device-cloud sync strate > **NOTE** > -> The initial APIs of this module are supported since API version 12. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The initial APIs of this module are supported since API version 12. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -21,9 +21,9 @@ Enumerates the types of the cloud-device sync strategy. **System capability**: SystemCapability.DistributedDataManager.CloudSync.Client -| Name | Value | Description | +| Name | Value| Description | | --------- |---|-----------| -| NETWORK | 0 | Sync over the network. | +| NETWORK | 0 | Sync over the network.| ## NetWorkStrategy @@ -31,35 +31,35 @@ Enumerates the network sync options. **System capability**: SystemCapability.DistributedDataManager.CloudSync.Client -| Name | Value | Description | +| Name | Value| Description | | --------- |---|-----------| -| WIFI | 1 | Sync over Wi-Fi. | +| WIFI | 1 | Sync over Wi-Fi.| | CELLULAR | 2 | Sync over the cellular network. | ## cloudData.setCloudStrategy setCloudStrategy(strategy: StrategyType, param?: Array<commonType.ValueType>): Promise<void> -Sets the device-cloud sync strategy for the application. If no strategy is set, the global strategy set by [setGlobalCloudStrategy12+](js-apis-data-cloudData-sys.md#setglobalcloudstrategy12) is used. If the global strategy is not set, the application data is synced over Wi-Fi and the cellular network by default. This API uses a promise to return the result. - +Sets the device-cloud sync strategy for the application. If no strategy is set, the global strategy set by [setGlobalCloudStrategy](js-apis-data-cloudData-sys.md#setglobalcloudstrategy12) is used. If the global strategy is not set, the application data is synced over Wi-Fi and the cellular network by default. This API uses a promise to return the result. + **System capability**: SystemCapability.DistributedDataManager.CloudSync.Client -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ---------- |-----------------------------------------------------------------------------| ---- | -------------------------------- | | strategy | [StrategyType](#strategytype) | Yes | Type of the strategy to set. | -| param | Array<[commonType.ValueType](js-apis-data-commonType.md#valuetype)> | No | Strategy parameters to set. If this parameter is not specified, all the configuration is canceled. | +| param | Array<[commonType.ValueType](js-apis-data-commonType.md#valuetype)> | No | Strategy parameters to set. If this parameter is not specified, all the configuration is canceled.| **Return value** | Type | Description | | ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value. | +| Promise<void> | Promise that returns no value.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| **ID** | **Error Message** | +| **ID**| **Error Message** | |-----------| ------------------------------------------------------------ | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 801 | Capability not supported.| diff --git a/en/application-dev/reference/apis-arkdata/js-apis-data-cloudExtension-sys.md b/en/application-dev/reference/apis-arkdata/js-apis-data-cloudExtension-sys.md index 58c704636cbe4080e0577074b1331a1642422971..da1933c6de3270d695c15a49a11fa91d025e9b32 100644 --- a/en/application-dev/reference/apis-arkdata/js-apis-data-cloudExtension-sys.md +++ b/en/application-dev/reference/apis-arkdata/js-apis-data-cloudExtension-sys.md @@ -13,7 +13,7 @@ Before you get started, it is helpful to understand the following concepts: - **ShareCenter**: device-cloud sharing server, which implements cross-account and cross-device data sharing for the same application. -> **NOTE** +> **NOTE** > > - The initial APIs of this module are supported since API version 11. Newly added APIs will be marked with a superscript to indicate their earliest API version. > @@ -43,10 +43,10 @@ Represents the cloud asset information. **System capability**: SystemCapability.DistributedDataManager.CloudSync.Server -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ------- | ------ | ---- | ------------------------------------ | | assetId | string | Yes | Asset ID. | -| hash | string | Yes | Hashed value of the asset modification time and size. | +| hash | string | Yes | Hashed value of the asset modification time and size.| ## CloudAssets @@ -56,7 +56,7 @@ Represents an array of [CloudAssets](#cloudasset). | Type | Description | | -------------------------------- | ----------------------------------------- | -| Array<[CloudAsset](#cloudasset)> | Array of [CloudAssets](#cloudasset). | +| Array<[CloudAsset](#cloudasset)> | Array of [CloudAssets](#cloudasset).| ## ServiceInfo @@ -64,9 +64,9 @@ Represents the cloud service information. **System capability**: SystemCapability.DistributedDataManager.CloudSync.Server -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | -------------- | ------- | ---- | ------------------------------------------------------------ | -| enableCloud | boolean | Yes | Whether the cloud service is enabled. The value **true** means the cloud service is enabled, and the value **false** means the opposite. | +| enableCloud | boolean | Yes | Whether the cloud service is enabled. The value **true** means the cloud service is enabled, and the value **false** means the opposite.| | id | string | Yes | Cloud account ID generated using SHA-256. | | totalSpace | number | Yes | Total account space on the server, in KB. | | remainingSpace | number | Yes | Available account space on the server, in KB. | @@ -80,9 +80,9 @@ Enumerates the operations that can be performed on a database. Use the enum name | Name | Value | Description | | ------ | ---- | ---------- | -| INSERT | 0 | Insert data. | -| UPDATE | 1 | Update data. | -| DELETE | 2 | Delete data. | +| INSERT | 0 | Insert data.| +| UPDATE | 1 | Update data.| +| DELETE | 2 | Delete data.| ## ExtensionValue @@ -90,12 +90,12 @@ Represents additional information about a data record. **System capability**: SystemCapability.DistributedDataManager.CloudSync.Server -| Name | Type | Read-Only | Optional | Description | +| Name | Type | Read-Only| Optional| Description | | ---------- | --------------- | ---- | ---- | ------------------ | -| id | string | Yes | No | ID generated when data is inserted. | +| id | string | Yes | No | ID generated when data is inserted.| | createTime | number | Yes | No | Time when a row of data is created. | | modifyTime | number | Yes | No | Time when a row of data is modified. | -| operation | [Flag](#flag) | Yes | No | Operation performed. | +| operation | [Flag](#flag) | Yes | No | Operation performed.| ## CloudType @@ -109,7 +109,7 @@ Enumerates the types of the cloud data field. The specific type is determined by | number | The value is a number. | | string | The value is a string. | | boolean | The value is true or false. | -| Uint8Array | The value is a Uint8 array. | +| Uint8Array | The value is a Uint8 array.| | [CloudAsset](#cloudasset) | The value is of the cloud asset type. | | [CloudAssets](#cloudassets) | The value is an array of cloud assets. | @@ -119,10 +119,10 @@ Represents the cloud information. **System capability**: SystemCapability.DistributedDataManager.CloudSync.Server -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | --------- | --------------------------------------------------- | ---- | -------------- | | cloudInfo | [ServiceInfo](#serviceinfo) | Yes | Cloud service information. | -| apps | Record<string, [AppBriefInfo](#appbriefinfo)> | Yes | Brief application information. | +| apps | Record<string, [AppBriefInfo](#appbriefinfo)> | Yes | Brief application information.| ## CloudData @@ -130,11 +130,11 @@ Represents the cloud data. **System capability**: SystemCapability.DistributedDataManager.CloudSync.Server -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ---------- | ---------------------------------------------------------- | ---- | ------------------------------------------------------------ | | nextCursor | string | Yes | Cursor for data query. | -| hasMore | boolean | Yes | Whether the server has more data to be queried. The value **true** means the server has data to be queried, and the value **false** means the opposite. | -| values | Array<Record<string, [CloudType](#cloudtype)>> | Yes | Array of data to be queried, which consists of the data value and [ExtensionValue](#extensionvalue). | +| hasMore | boolean | Yes | Whether there is still data to be queried on the on the server. The value **true** means there is data to be queried on the server; the value **false** means the opposite.| +| values | Array<Record<string, [CloudType](#cloudtype)>> | Yes | Array of data to be queried, which consists of the data value and [ExtensionValue](#extensionvalue).| ## AppBriefInfo @@ -142,12 +142,12 @@ Represents the brief application information. **System capability**: SystemCapability.DistributedDataManager.CloudSync.Server -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ----------- | ------- | ---- | ---------------------------------- | | appId | string | Yes | Application ID. | | bundleName | string | Yes | Bundle name of the application. | -| cloudSwitch | boolean | Yes | Whether the cloud service is enabled for the application. The value **true** means the cloud service is enabled; the value **false** means the opposite. | -| instanceId | number | Yes | Application twin ID. The value **0** indicates the application itself, and the twin ID increases in ascending order. | +| cloudSwitch | boolean | Yes | Whether the cloud service is enabled for the application. The value **true** means the cloud service is enabled; the value **false** means the opposite.| +| instanceId | number | Yes | Application twin ID. The value **0** indicates the application itself, and the twin ID increases in ascending order.| ## FieldType @@ -162,7 +162,7 @@ Enumerates the types of the fields in a database table. Use the enum name rather | REAL | 2 | Double-precision floating point. | | TEXT | 3 | Text. | | BOOL | 4 | Boolean. | -| BLOB | 5 | BLOB, which can hold a binary file. | +| BLOB | 5 | BLOB, which can hold a binary file.| | [ASSET](js-apis-data-relationalStore.md#asset10) | 6 | Asset. | | [ASSETS](js-apis-data-relationalStore.md#assets10) | 7 | Assets. | @@ -172,12 +172,12 @@ Represents a field in the database. **System capability**: SystemCapability.DistributedDataManager.CloudSync.Server -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ---------------------- | -| alias | string | Yes | Alias of the field in the table. | +| alias | string | Yes | Alias of the field in the table.| | colName | string | Yes | Name of the column, in which the field is located. | | type | [FieldType](#fieldtype) | Yes | Type of the field. | -| primary | boolean | Yes | Whether the current column is the primary key. The value **true** means the current column is the primary key; the value **false** means the opposite. | +| primary | boolean | Yes | Whether the current column is the primary key. The value **true** means the current column is the primary key; the value **false** means the opposite.| | nullable | boolean | Yes | Whether the current column can be null. The value **true** means the current column can be null; the value **false** means the opposite. | ## Table @@ -186,9 +186,9 @@ Represents the table information. **System capability**: SystemCapability.DistributedDataManager.CloudSync.Server -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ------ | ---------------------------- | ---- | ---------------------------- | -| alias | string | Yes | Alias of the table in the database. | +| alias | string | Yes | Alias of the table in the database.| | name | string | Yes | Table name. | | fields | Array<[Field](#field)> | Yes | Field information in the table. | @@ -198,11 +198,11 @@ Represents the database information. **System capability**: SystemCapability.DistributedDataManager.CloudSync.Server -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ------ | ---------------------------- | ---- | -------------------------------- | | name | string | Yes | Name of the database. | | alias | string | Yes | Alias of the database on the server. | -| tables | Array<[Table](#table)> | Yes | Table in the database, including the detailed data information. | +| tables | Array<[Table](#table)> | Yes | Table in the database, including the detailed data information.| ## AppSchema @@ -210,11 +210,11 @@ Represents the application database schema. **System capability**: SystemCapability.DistributedDataManager.CloudSync.Server -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ---------- | ------------------------------------ | ---- | ------------------ | | bundleName | string | Yes | Bundle name of the application. | -| version | number | Yes | Version of the database schema. | -| databases | Array<[Database](#database)> | Yes | Database information of the application. | +| version | number | Yes | Version of the database schema.| +| databases | Array<[Database](#database)> | Yes | Database information of the application.| ## SubscribeId @@ -222,9 +222,9 @@ Represents the subscription ID information. **System capability**: SystemCapability.DistributedDataManager.CloudSync.Server -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ------------- | ------ | ---- | ---------------------- | -| databaseAlias | string | Yes | Name of the database on the server. | +| databaseAlias | string | Yes | Name of the database on the server.| | id | string | Yes | Subscription ID. | ## SubscribeInfo @@ -233,9 +233,9 @@ Represents the subscription information. **System capability**: SystemCapability.DistributedDataManager.CloudSync.Server -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | -------------- | ------------------------------------------------------------ | ---- | -------------------- | -| expirationTime | number | Yes | Subscription expiration time, in ms. | +| expirationTime | number | Yes | Subscription expiration time, in ms.| | subscribe | Record<string, Array<[SubscribeId](#subscribeid)>> | Yes | Subscription information. | ## LockInfo @@ -244,9 +244,9 @@ Represents the cloud database lock information. **System capability**: SystemCapability.DistributedDataManager.CloudSync.Server -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------------------------- | -| interval | number | Yes | Lock period of the cloud database, in seconds. | +| interval | number | Yes | Lock period of the cloud database, in seconds.| | lockId | number | Yes | Lock ID. | ## ErrorCode @@ -261,8 +261,8 @@ Enumerates the device-cloud sync states. Use the enum name rather than the enum | UNKNOWN_ERROR | 1 | An unknown error occurs during the device-cloud sync process. | | NETWORK_ERROR | 2 | A network error occurs during the device-cloud sync process. | | CLOUD_DISABLED | 3 | Cloud sync is disabled. | -| LOCKED_BY_OTHERS | 4 | The device-cloud sync of another device is being performed. The sync of the local device can be performed only when the device-cloud resources are available. | -| RECORD_LIMIT_EXCEEDED | 5 | The number of records or size of the data to be synced exceeds the maximum. The maximum value is configured on the cloud. | +| LOCKED_BY_OTHERS | 4 | The device-cloud sync of another device is being performed. The sync of the local device can be performed only when the device-cloud resources are available.| +| RECORD_LIMIT_EXCEEDED | 5 | The number of records or size of the data to be synced exceeds the maximum. The maximum value is configured on the cloud.| | NO_SPACE_FOR_ASSET | 6 | The remaining cloud space is less than the size of the data to be synced. | ## cloudExtension.createCloudServiceStub @@ -275,7 +275,7 @@ Creates a [RemoteObject](../apis-ipc-kit/js-apis-rpc.md#remoteobject) instance b **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | --------- | ------------------------------- | ---- | -------------------------------- | | instance | [CloudService](#cloudservice) | Yes | Instance of the [CloudService](#cloudservice) class. | @@ -283,7 +283,7 @@ Creates a [RemoteObject](../apis-ipc-kit/js-apis-rpc.md#remoteobject) instance b | Type | Description | | ------------------- | ------------------------- | -| Promise<[rpc.RemoteObject](../apis-ipc-kit/js-apis-rpc.md#remoteobject)> | Promise used to return the [RemoteObject](../apis-ipc-kit/js-apis-rpc.md#remoteobject) instance of [CloudService](#cloudservice). | +| Promise<[rpc.RemoteObject](../apis-ipc-kit/js-apis-rpc.md#remoteobject)> | Promise used to return the [RemoteObject](../apis-ipc-kit/js-apis-rpc.md#remoteobject) instance of [CloudService](#cloudservice).| **Example** @@ -328,7 +328,7 @@ Creates a [RemoteObject](../apis-ipc-kit/js-apis-rpc.md#remoteobject) instance b **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | --------- | ------------------------------- | ---- | -------------------------------- | | instance | [ShareCenter](#sharecenter) | Yes | Instance of the [ShareCenter](#sharecenter) class. | @@ -336,7 +336,7 @@ Creates a [RemoteObject](../apis-ipc-kit/js-apis-rpc.md#remoteobject) instance b | Type | Description | | ------------------- | ------------------------- | -| Promise<[rpc.RemoteObject](../apis-ipc-kit/js-apis-rpc.md#remoteobject)> | Promise used to return the [RemoteObject](../apis-ipc-kit/js-apis-rpc.md#remoteobject) instance of [ShareCenter](#sharecenter). | +| Promise<[rpc.RemoteObject](../apis-ipc-kit/js-apis-rpc.md#remoteobject)> | Promise used to return the [RemoteObject](../apis-ipc-kit/js-apis-rpc.md#remoteobject) instance of [ShareCenter](#sharecenter).| **Example** @@ -367,15 +367,15 @@ Creates a [RemoteObject](../apis-ipc-kit/js-apis-rpc.md#remoteobject) instance b **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ------------------------------- | -| instance | [CloudDB](#clouddb) | Yes | [CloudDB](#clouddb) instance. | +| instance | [CloudDB](#clouddb) | Yes | [CloudDB](#clouddb) instance.| **Return value** | Type | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| Promise<[rpc.RemoteObject](../apis-ipc-kit/js-apis-rpc.md#remoteobject)> | Promise used to return the [rpc.RemoteObject](../apis-ipc-kit/js-apis-rpc.md#remoteobject) instance of [CloudDB](#clouddb). | +| Promise<[rpc.RemoteObject](../apis-ipc-kit/js-apis-rpc.md#remoteobject)> | Promise used to return the [rpc.RemoteObject](../apis-ipc-kit/js-apis-rpc.md#remoteobject) instance of [CloudDB](#clouddb).| ```ts import { rpc } from '@kit.IPCKit'; @@ -402,9 +402,9 @@ Creates a [RemoteObject](../apis-ipc-kit/js-apis-rpc.md#remoteobject) instance b **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | -------- | ----------------------------- | ---- | ------------------------------------------------- | -| instance | [AssetLoader](#assetloader) | Yes | [AssetLoader](#assetloader) instance. | +| instance | [AssetLoader](#assetloader) | Yes | [AssetLoader](#assetloader) instance.| **System capability**: SystemCapability.DistributedDataManager.CloudSync.Server @@ -412,7 +412,7 @@ Creates a [RemoteObject](../apis-ipc-kit/js-apis-rpc.md#remoteobject) instance b | Type | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| Promise<[rpc.RemoteObject](../apis-ipc-kit/js-apis-rpc.md#remoteobject)> | Promise used to return the [rpc.RemoteObject](../apis-ipc-kit/js-apis-rpc.md#remoteobject) instance of [AssetLoader](#assetloader). | +| Promise<[rpc.RemoteObject](../apis-ipc-kit/js-apis-rpc.md#remoteobject)> | Promise used to return the [rpc.RemoteObject](../apis-ipc-kit/js-apis-rpc.md#remoteobject) instance of [AssetLoader](#assetloader).| **Example** @@ -449,15 +449,15 @@ Generates IDs for the data records inserted to the cloud database. The IDs are u **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------- | -| count | number | Yes | Number of IDs to generate. | +| count | number | Yes | Number of IDs to generate.| **Return value** | Type | Description | | -------------------------------------------------------- | ------------------------------------------------------------ | -| Promise<[Result](#resultt)<Array<string>> | Promise used to return the generated IDs in [Result](#resultt). | +| Promise<[Result](#resultt)<Array<string>> | Promise used to return the generated IDs in [Result](#resultt).| **Example** @@ -487,17 +487,17 @@ Updates data in the cloud. **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ---------------------- | -| table | string | Yes | Name of the table to update. | +| table | string | Yes | Name of the table to update.| | values | Array<Record<string, [CloudType](#cloudtype)>> | Yes | Data to insert. | -| extensions | Array<Record<string, [CloudType](#cloudtype)>> | Yes | Extended information about the current data. | +| extensions | Array<Record<string, [CloudType](#cloudtype)>> | Yes | Extended information about the current data.| **Return value** | Type | Description | | ------------------------------------------------------------ | --------------------------------------- | -| Promise<Array<[Result](#resultt)<Record<string, [CloudType](#cloudtype)>>>> | Promise used to return the update result and updated data. | +| Promise<Array<[Result](#resultt)<Record<string, [CloudType](#cloudtype)>>>> | Promise used to return the update result and updated data.| **Example** @@ -525,17 +525,17 @@ Inserts data to a cloud database table. **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ---------- | ---------------------------------------------------------- | ---- | ------------------------ | | table | string | Yes | Name of the target table. | | values | Array<Record<string, [CloudType](#cloudtype)>> | Yes | Data to insert. | -| extensions | Array<Record<string, [CloudType](#cloudtype)>> | Yes | Extended information about the current data. | +| extensions | Array<Record<string, [CloudType](#cloudtype)>> | Yes | Extended information about the current data.| **Return value** | Type | Description | | ------------------------------------------------------------ | ------------------------------------- | -| Promise<Array<[Result](#resultt)<Record<string, [CloudType](#cloudtype)>>>> | Promise used to return the inserted data and operation result. | +| Promise<Array<[Result](#resultt)<Record<string, [CloudType](#cloudtype)>>>> | Promise used to return the inserted data and operation result.| **Example** @@ -563,16 +563,16 @@ Deletes data from a cloud database table. **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ---------- | --------------------------------------------------------- | ---- | ------------------------ | | table | string | Yes | Name of the target table. | -| extensions | Array<Record<string,[CloudType](#cloudtype)>> | Yes | Extended information about the current data. | +| extensions | Array<Record<string,[CloudType](#cloudtype)>> | Yes | Extended information about the current data.| **Return value** | Type | Description | | ------------------------------------------------------------ | ----------------------------------------- | -| Promise<Array<[Result](#resultt)<Record<string, [CloudType](#cloudtype)>>>> | Promise used to return the deleted data and operation result. | +| Promise<Array<[Result](#resultt)<Record<string, [CloudType](#cloudtype)>>>> | Promise used to return the deleted data and operation result.| **Example** @@ -600,18 +600,18 @@ Queries data in a cloud database table. **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ----------- | ------------- | ---- | ------------------------ | | table | string | Yes | Name of the target table. | | fields | Array<string> | Yes | Name of the fields to query. | -| queryCount | number | Yes | Number of data records to query. | +| queryCount | number | Yes | Number of data records to query.| | queryCursor | string | Yes | Cursor for the query. | **Return value** | Type | Description | | ------------------------------------------------------------ | --------------------------------------- | -| Promise<[Result](#resultt)<[CloudData](#clouddata)>> | Promise used to return the data and operation result. | +| Promise<[Result](#resultt)<[CloudData](#clouddata)>> | Promise used to return the data and operation result.| **Example** @@ -648,7 +648,7 @@ Locks this cloud database. | Type | Description | | ------------------------------------------------------------ | --------------------------------------------------- | -| Promise<[Result](#resultt)<[LockInfo](#lockinfo)>> | Promise used to return the lock ID and lock period. | +| Promise<[Result](#resultt)<[LockInfo](#lockinfo)>> | Promise used to return the lock ID and lock period.| **Example** @@ -684,15 +684,15 @@ Extends the lock period of the database. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | --------------------- | -| lockId | number | Yes | Lock ID. | +| lockId | number | Yes | Lock ID.| **Return value** | Type | Description | | ------------------------------------------------------------ | ------------------------------------------------- | -| Promise<[Result](#resultt)<[LockInfo](#lockinfo)>> | Promise used to return the lock ID and lock period. | +| Promise<[Result](#resultt)<[LockInfo](#lockinfo)>> | Promise used to return the lock ID and lock period.| **Example** @@ -720,7 +720,7 @@ export default class MyCloudDB implements cloudExtension.CloudDB { ### unlock -unlock(lockId: number): Promise<Result<boolean>>; +unlock(lockId: number): Promise<Result<boolean>> Unlocks a cloud database. @@ -728,15 +728,15 @@ Unlocks a cloud database. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------- | -| lockId | number | Yes | Lock ID to release. | +| lockId | number | Yes | Lock ID to release.| **Return value** | Type | Description | | ------------------------------------------------ | ------------------------------------------------------------ | -| Promise<[Result](#resultt)<boolean>> | Promise used to return the result. The value **true** means the operation is successful; the value **false** means the opposite. | +| Promise<[Result](#resultt)<boolean>> | Promise used to return the result. The value **true** means the operation is successful; the value **false** means the opposite. | **Example** @@ -773,7 +773,7 @@ Obtains the server information. This API uses a promise to return the result. | Type | Description | | -------------------------------------------- | ----------------------------------- | -| Promise<[ServiceInfo](#serviceinfo)> | Promise used to return the server information obtained. | +| Promise<[ServiceInfo](#serviceinfo)> | Promise used to return the server information obtained.| **Example** @@ -812,7 +812,7 @@ Obtains brief application information. This API uses a promise to return the res | Type | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| Promise<Record<string, [AppBriefInfo](#appbriefinfo)>>> | Promise used to return **bundleName** and [AppBriefInfo](#appbriefinfo), in KV pairs. | +| Promise<Record<string, [AppBriefInfo](#appbriefinfo)>>> | Promise used to return **bundleName** and [AppBriefInfo](#appbriefinfo), in KV pairs.| **Example** @@ -846,15 +846,15 @@ Obtains the application database schema information. This API uses a promise to **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ---------- | ------ | ---- | ---------- | -| bundleName | string | Yes | Bundle name of the application. | +| bundleName | string | Yes | Bundle name of the application.| **Return value** | Type | Description | | ------------------------------------------------------------ | ------------------------------------- | -| Promise<[Result](#resultt)<[AppSchema](#appschema)>> | Promise used to return the schema information obtained. | +| Promise<[Result](#resultt)<[AppSchema](#appschema)>> | Promise used to return the schema information obtained.| **Example** @@ -889,16 +889,16 @@ Subscribes to data. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | -------------- | ---------------------------------------------------------- | ---- | ------------------------------------------------------ | -| subInfo | Record<string, Array<[Database](#database)>> | Yes | Data to be subscribed to, in KV pairs of the application bundle name and database information. | +| subInfo | Record<string, Array<[Database](#database)>> | Yes | Data to be subscribed to, in KV pairs of the application bundle name and database information.| | expirationTime | number | Yes | Subscription expiration time. | **Return value** | Type | Description | | ------------------------------------------------------------ | ----------------------------------------------------------- | -| Promise<[Result](#resultt)<[SubscribeInfo](#subscribeinfo)>> | Promise used to return the result, including the subscription expiration time and subscription information. | +| Promise<[Result](#resultt)<[SubscribeInfo](#subscribeinfo)>> | Promise used to return the result, including the subscription expiration time and subscription information.| **Example** @@ -936,15 +936,15 @@ Unsubscribes from data changes in the cloud. This API uses a promise to return t **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | --------------- | -------------------------------------- | ---- | ------------------------------------------------------------ | -| unsubscribeInfo | Record<string, Array **NOTE** +> +> - The initial APIs of this module are supported since API version 18. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The current page contains only the system interfaces of this module. + +## Modules to Import + +```ts +import { collaborationEditObject } from '@kit.ArkData'; +``` + +## collaborationEditObject.getCollaborationEditObject + +getCollaborationEditObject(context: Context, config: CollaborationConfig): CollaborationEditObject + +Obtains a **CollaborationEditObject** instance. You can set parameters for the **CollaborationEditObject** instance based on actual requirements and use the created **CollaborationEditObject** instance to perform document editing across devices. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context. The stage model is recommended.
For details about the application context of the FA model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md).| +| config | [CollaborationConfig](#collaborationconfig) | Yes | Configuration of the collaboration edit object. | + +**Return value** + +| Type | Description | +| --------------------------------------------------- | ---------------------- | +| [CollaborationEditObject](#collaborationeditobject) | **CollaborationEditObject** instance obtained.| + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [Collaboration Data Model Error Codes](errorcode-collaboration-edit-object.md). + +| **ID**| **Error Message** | +|-----------|---------| +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 202 | Not system application. | +| 15410000 | Internal Error. | +| 15410003 | Database Error. | + +**Example** + +FA model: + + + +```ts +import { featureAbility } from '@kit.AbilityKit'; + +let editObject: collaborationEditObject.CollaborationEditObject | undefined = undefined; +let context = featureAbility.getContext(); + +const DOC_CONFIG: collaborationEditObject.CollaborationConfig = { + name: "test" +}; + +try { + editObject = collaborationEditObject.getCollaborationEditObject(context, DOC_CONFIG); +} catch (err) { + console.error(`Get edit object failed, code is ${err.code}, message is ${err.message}`); +} +``` + +Stage model: + +```ts +import { UIAbility } from '@kit.AbilityKit'; +import { window } from '@kit.ArkUI'; + +let editObject: collaborationEditObject.CollaborationEditObject | undefined = undefined; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + const DOC_CONFIG: collaborationEditObject.CollaborationConfig = { + name: "test" + }; + + try { + editObject = collaborationEditObject.getCollaborationEditObject(this.context, DOC_CONFIG); + } catch (err) { + console.error(`Get edit object failed, code is ${err.code}, message is ${err.message}`); + } + } +} +``` + + + + +## collaborationEditObject.deleteCollaborationEditObject + +deleteCollaborationEditObject(context: Context, config: CollaborationConfig): void + +Deletes a collaboration edit object. After the deletion, you are advised to set the **CollaborationEditObject** instance to **null**. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context. The stage model is recommended.
For details about the application context of the FA model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md).| +| config | [CollaborationConfig](#collaborationconfig) | Yes | Configuration of the collaboration edit object to delete. | + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [Collaboration Data Model Error Codes](errorcode-collaboration-edit-object.md). + +| **ID**| **Error Message** | +|-----------|---------| +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 202 | Not system application. | +| 15410000 | Internal Error. | +| 15410003 | Database Error. | + +**Example** + +FA model: + + + +```ts +import { featureAbility } from '@kit.AbilityKit'; + +let editObject: collaborationEditObject.CollaborationEditObject | undefined = undefined; +let context = featureAbility.getContext(); + +const DOC_CONFIG: collaborationEditObject.CollaborationConfig = { + name: "test" +}; + +try { + editObject = collaborationEditObject.getCollaborationEditObject(context, DOC_CONFIG); + collaborationEditObject.deleteCollaborationEditObject(context, DOC_CONFIG); +} catch (err) { + console.error(`Get edit object failed, code is ${err.code}, message is ${err.message}`); +} +``` + + + +Stage model: + +```ts +import { UIAbility } from '@kit.AbilityKit'; +import { window } from '@kit.ArkUI'; + +let editObject: collaborationEditObject.CollaborationEditObject | undefined = undefined; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + const DOC_CONFIG: collaborationEditObject.CollaborationConfig = { + name: "test" + }; + + try { + editObject = collaborationEditObject.getCollaborationEditObject(this.context, DOC_CONFIG); + collaborationEditObject.deleteCollaborationEditObject(this.context, DOC_CONFIG); + } catch (err) { + console.error(`Delete edit object failed, code is ${err.code}, message is ${err.message}`); + } + } +} +``` + + + +## CollaborationConfig + +Represents the collaboration edit object configuration. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +| Name| Type | Mandatory| Description | +| ---- | ------ | ---- | ------------------------------------------------------------ | +| name | string | Yes | Document name.
The naming rules comply with the naming rules for the operating system files.
It is recommended that the value contain letters, digits, underscores (_), and hyphens (-). The value cannot contain slashes (/). Avoid using special characters such as $, @, and #.| + + + +## CollaborationEditObject + +Provides APis for managing the **CollaborationEditObject** instance. + +Before calling any of the following APIs, you must use [getCollaborationEditObject](#collaborationeditobjectgetcollaborationeditobject) to create a **CollaborationEditObject** instance. + +### getEditUnit + +getEditUnit(editUnitName: string): EditUnit + +Obtains an editing unit. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| editUnitName | string | Yes | Name of the editing unit to obtain.
The editing unit name is case-insensitive, and cannot be an empty string or exceed 255 bytes.| + +**Return value** + +| Type | Description | +| ----------------------------------------- | --------------------------------- | +| [EditUnit](#editunit) | Editing unit obtained. If the editing unit does not exist, an editing unit will be created.| + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [Collaboration Data Model Error Codes](errorcode-collaboration-edit-object.md). + +| **ID**| **Error Message** | +|-----------|---------| +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 202 | Not system application. | +| 15410000 | Internal Error. | +| 15410003 | Database Error. | + +**Example** + +```ts +let editUnit: collaborationEditObject.EditUnit | undefined = undefined; + +if (editObject != undefined) { + try { + editUnit = editObject.getEditUnit("editUnit01"); + } catch (err) { + console.error(`Get edit unit failed, code is ${err.code}, message is ${err.message}`); + } +} +``` + + + +### getUndoRedoManager + +getUndoRedoManager(editUnitName: string, config: UndoRedoConfig): UndoRedoManager + +Obtains an **UndoRedoManager** instance for an editing unit. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | ------------------------------------------------------------ | +| editUnitName | string | Yes | Name of the target editing unit.
Generally, it is the same as that in [getEditUnit](#geteditunit).| +| config | [UndoRedoConfig](#undoredoconfig) | Yes | Configuration of the **UndoRedoManager** instance. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| [UndoRedoManager](#undoredomanager) | **UndoRedoManager** instance obtained.| + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [Collaboration Data Model Error Codes](errorcode-collaboration-edit-object.md). + +| **ID**| **Error Message** | +|-----------|---------| +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 202 | Not system application. | +| 15410000 | Internal Error. | +| 15410003 | Database Error. | + +**Example** + +```ts +let editUnit: collaborationEditObject.EditUnit | undefined = undefined; +let undoRedoManager: collaborationEditObject.UndoRedoManager | undefined = undefined; + +if (editObject != undefined) { + try { + editUnit = editObject.getEditUnit("editUnit01"); + undoRedoManager = editObject.getUndoRedoManager("editUnit01", {captureTimeout: 500}); + } catch (err) { + console.error(`Get undoRedoManager failed, code is ${err.code}, message is ${err.message}`); + } +} +``` + + + + +### deleteUndoRedoManager + +deleteUndoRedoManager(editUnitName: string): void + +Deletes the **UndoRedoManager** instance of an editing unit. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| editUnitName | string | Yes | Name of the target editing unit.
Generally, it is the same as that in [getEditUnit](#geteditunit).| + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [Collaboration Data Model Error Codes](errorcode-collaboration-edit-object.md). + +| **ID**| **Error Message** | +|-----------|---------| +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 202 | Not system application. | +| 15410000 | Internal Error. | +| 15410003 | Database Error. | + +**Example** + +```ts +let editUnit: collaborationEditObject.EditUnit | undefined = undefined; +let undoRedoManager: collaborationEditObject.UndoRedoManager | undefined = undefined; + +if (editObject != undefined) { + try { + editUnit = editObject.getEditUnit("editUnit01"); + undoRedoManager = editObject.getUndoRedoManager("editUnit01", {captureTimeout: 500}); + editObject.deleteUndoRedoManager("editUnit01"); + } catch (err) { + console.error(`Delete undoRedoManager failed, code is ${err.code}, message is ${err.message}`); + } +} +``` + +### getLocalId + +getLocalId(): string + +Obtains the local device ID. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Return value** + +| Type | Description | +| ------ | ----------------------------------------------------------- | +| string | Local device ID obtained.
It is generated by the collaboration edit object.| + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [Collaboration Data Model Error Codes](errorcode-collaboration-edit-object.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 202 | Not system application. | +| 15410000 | Internal Error. | +| 15410003 | Database Error. | + +**Example** + +```ts +if (editObject != undefined) { + try { + let id: string = editObject.getLocalId(); + } catch (err) { + console.error(`Get local id failed, code is ${err.code}, message is ${err.message}`); + } +} +``` + +### applyUpdate + +applyUpdate(): Array\ + +Applies the local updates to this collaboration edit object. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Return value** + +| Type | Description | +| ---------------------------------- | -------------------------------------------------- | +| Array<[UpdatedNode](#updatednode)> | Array of the data changed.| + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [Collaboration Data Model Error Codes](errorcode-collaboration-edit-object.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 202 | Not system application. | +| 15410000 | Internal Error. | +| 15410003 | Database Error. | + +**Example** + +```ts +function syncCallback(progress: collaborationEditObject.ProgressDetail) { + if (progress.code !== collaborationEditObject.ProgressCode.CLOUD_SYNC_SUCCESS) { + return; + } + if (editObject != undefined) { + try { + let updatedNode: Array = editObject.applyUpdate(); + } catch (err) { + console.error(`Apply update failed, code is ${err.code}, message is ${err.message}`); + } + } +} + +if (editObject != undefined) { + try { + editObject.cloudSync(collaborationEditObject.SyncMode.SYNC_MODE_PUSH, syncCallback); + } catch (err) { + console.error(`Cloud sync failed, code is ${err.code}, message is ${err.message}`); + } +} +``` + +### writeUpdate + +writeUpdate(update: EditObjectRecord): void + +Writes the updates in the cloud to the device. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------- | ---- | ---------------------- | +| update | [EditObjectRecord](#editobjectrecord) | Yes | Data to write.| + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [Collaboration Data Model Error Codes](errorcode-collaboration-edit-object.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 202 | Not system application. | +| 15410000 | Internal Error. | +| 15410003 | Database Error. | + +**Example** + +```ts +if (editObject != undefined) { + try { + let updatedRecords: Array = new Array(); + for (let updatedRecord of updatedRecords) { + editObject.writeUpdate(updatedRecord); + } + } catch (err) { + console.error(`Write update failed, code is ${err.code}, message is ${err.message}`); + } +} +``` + +### setCloudDB + +setCloudDB(cloudDB: CloudDB): void + +Sets the callbacks for device-cloud sync. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------- | ---- | ---------------------- | +| cloudDB | [CloudDB](#clouddb) | Yes | Callbacks to set.| + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [Collaboration Data Model Error Codes](errorcode-collaboration-edit-object.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 202 | Not system application. | +| 15410000 | Internal Error. | +| 15410003 | Database Error. | + +**Example** + +```ts +function uploadAssetHandler(config: collaborationEditObject.AssetOperationConfig): Promise { + return new Promise((resolve, reject) => { + resolve(); + }); +} + +function downloadAssetHandler(config: collaborationEditObject.AssetOperationConfig): Promise { + return new Promise((resolve, reject) => { + resolve(); + }); +} + +function deleteAssetHandler(config: collaborationEditObject.AssetOperationConfig): Promise { + return new Promise((resolve, reject) => { + resolve(); + }); +} + +function deleteLocalAssetHandler(config: collaborationEditObject.AssetOperationConfig): Promise { + return new Promise((resolve, reject) => { + resolve(); + }); +} + +function batchInsertHandler(updates: Array): Promise { + return new Promise((resolve, reject) => { + resolve(0); + }); +} + +function queryHandler(queryConditions: Array): Promise> { + return new Promise((resolve, reject) => { + let res: Array = new Array(); + resolve(res); + }); +} + +const CLOUD_DB_FUNC: collaborationEditObject.CloudDB = { + batchInsert: batchInsertHandler, + query: queryHandler, + downloadAsset: downloadAssetHandler, + uploadAsset: uploadAssetHandler, + deleteAsset: deleteAssetHandler, + deleteLocalAsset: deleteLocalAssetHandler, +}; + +if (editObject != undefined) { + try { + editObject.setCloudDB(CLOUD_DB_FUNC); + } catch (err) { + console.error(`Set cloud db failed, code is ${err.code}, message is ${err.message}`); + } +} +``` + +### cloudSync + +cloudSync(syncMode: SyncMode, progress: Callback\): void + +Synchronizes data from the local device to the cloud. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | -------------- | +| syncMode | [SyncMode](#syncmode) | Yes | Sync mode. | +| progress | Callback<[ProgressDetail](#progressdetail)> | Yes | Callback used to return the sync result.| + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [Collaboration Data Model Error Codes](errorcode-collaboration-edit-object.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 202 | Not system application. | +| 15410000 | Internal Error. | +| 15410003 | Database Error. | + +**Example** + +```ts +function cloudSyncCallback(progress: collaborationEditObject.ProgressDetail) { + console.log(`Cloud sync progress code is ${progress.code}`); +} + +if (editObject != undefined) { + try { + editObject.cloudSync(collaborationEditObject.SyncMode.SYNC_MODE_PUSH, cloudSyncCallback); + } catch (err) { + console.error(`Cloud sync failed, code is ${err.code}, message is ${err.message}`); + } +} +``` + +## BatchInsertHandler + +type BatchInsertHandler = (records: Array\) => Promise\ + +Defines a callback used to upload data from the local device to the cloud. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | -------------- | +| records | Array<[EditObjectRecord](#editobjectrecord)> | Yes | Data to be uploaded to the cloud. | + +**Return value** +| Type | Description | +| ---------------------------------- | -------------------------------------------------- | +| Promise\ | Promise used to return the number of data records that are successfully uploaded.| + +## QueryHandler + +type QueryHandler = (queryConditions: Array\) => Promise\> + +Defines a callback used to download data from the cloud to the local device. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | -------------- | +| queryConditions | Array<[QueryCondition](#querycondition)> | Yes | Conditions for matching the data to download. | + +**Return value** +| Type | Description | +| ---------------------------------- | -------------------------------------------------- | +| Promise\> | Promise used to return the cloud data downloaded.| + +## AssetHandler + +type AssetHandler = (config: AssetOperationConfig) => Promise\ + +Defines a callback used to upload, download, or delete assets. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | -------------- | +| config | [AssetOperationConfig](#assetoperationconfig) | Yes | Configuration of the asset operation. | + +**Return value** +| Type | Description | +| ---------------------------------- | -------------------------------------------------- | +| Promise\ | Promise that returns no value.| + +## CloudDB + +Defines the callbacks used for device-cloud sync. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +| Name | Type | Read Only| Optional| Description | +| ------- | ------ | ---- | ---- | ------ | +| batchInsert | [BatchInsertHandler](#batchinserthandler) | Yes| No| Callback used to upload data from the local device to the cloud. You need to define the callback based on service requirements.| +| query | [QueryHandler](#queryhandler) | Yes| No| Callback used to download data from the cloud to the local device. You need to define the callback based on service requirements.| +| downloadAsset | [AssetHandler](#assethandler) | Yes| No| Callback used to download assets from the cloud to the local device. You need to define the callback based on service requirements.| +| uploadAsset | [AssetHandler](#assethandler) | Yes| No| Callback used to upload assets from the local device to the cloud. You need to define the callback based on service requirements.| +| deleteAsset | [AssetHandler](#assethandler) | Yes| No| Callback used to delete assets from the cloud. You need to define the callback based on service requirements.| +| deleteLocalAsset | [AssetHandler](#assethandler) | Yes| No| Callback used to delete assets from the local device. You need to define the callback based on service requirements.| + +## SyncMode +Enumerates the device-cloud sync modes. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +| Name| Value | Description| +| ---- | ---- | ---- | +| SYNC_MODE_PUSH | 0 | Push data from the local device to the cloud. | +| SYNC_MODE_PULL | 1 | Pull data from the cloud to the local device.| +| SYNC_MODE_PULL_PUSH | 2 | Pull data from the cloud to the local device, and then push data to the cloud.| + +## ProgressCode +Enumerates the device-cloud sync results. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +| Name| Value | Description| +| ---- | ---- | ---- | +| CLOUD_SYNC_SUCCESS | 0 | The device-cloud sync is successful. | +| CLOUD_NOT_SET | 1 | The callback required for device-cloud sync is not configured.| +| INTERNAL_ERROR | 2 | An internal error occurs during the sync.| +| EXTERNAL_ERROR | 3 | An error occurs when a callback is invoked during the sync process.| + +## ProgressDetail +Represents the device-cloud sync result. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +| Name | Type | Read Only| Optional| Description | +| ------- | ------ | ---- | ---- | ------ | +| code | [ProgressCode](#progresscode) | Yes| No| Device-cloud sync result.| + +## Predicate + +Enumerates the predicates used to set the conditions for the data to be downloaded. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +| Name| Value | Description| +| ---- | ---- | ---- | +| EQUAL_TO | 0 | Seeks data whose value equals the given value in the cloud. | +| NOT_EQUAL_TO | 1 | Seeks data whose value does not equal the given value in the cloud.| +| GREATER_THAN | 2 | Seeks data whose value is greater than the given value in the cloud.| +| LESS_THAN | 3 | Seeks data whose value is less than the given value in the cloud.| +| GREATER_THAN_OR_EQUAL_TO | 4 | Seeks data whose value is greater than or equal to the given value in the cloud.| +| LESS_THAN_OR_EQUAL_TO | 5 | Seeks data whose value is less than or equal to the given value in the cloud.| + +## QueryCondition + +Represents the condition for seeking the data to be download in the cloud. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +| Name | Type | Read Only| Optional| Description | +| ------- | ------ | ---- | ---- | ------ | +| condition | [Predicate](#predicate) | Yes| No| Predicate to set.| +| fieldName | string | Yes| No| Field corresponding to the specified condition, generated internally by the collaboration edit object.| +| fieldValue | string \| number | Yes| No| Value corresponding to the specified condition, generated internally by the collaboration edit object.| + + +## AssetOperationConfig + +Represents the configuration of the access operation. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +| Name | Type | Read Only| Optional| Description | +| ------- | ------ | ---- | ---- | ------ | +| path | string | Yes| No| Path of the asset file. The value can be any non-empty string.| + + +## RelativePos + +Represents the relative position of the cursor in an editing unit. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + + +| Name | Type | Read Only | Optional | Description | +| ------------------- | ------------------------- | ------------------- | ------------------- | ------------------- | +| parentId | [UniqueId](#uniqueid) \| null | Yes| No| Parent node. If the parent node is the editing unit, the value is **null**.| +| parentName | string \| null | Yes| No| Name of the parent node. If the parent node is the editing unit, the value is the name of the editing unit. Otherwise, the value is **null**.
**Constraints**: See the constraints for the **editUnitName** parameter in [getEditUnit](#geteditunit).| +| id | [UniqueId](#uniqueid) \| null | Yes| No| Left or right node. If there is no left or right node, the value is **null**.
**Constraints**: **parentId**, **parentName**, and **id** cannot be **null** at the same time.| +| pos | number | Yes| No| Offset of the character to the node. The value **0** indicates the current node; a value less than **0** indicates a character on the left side of the node; a value greater than **0** indicates a character on the right side of the node. The value must be an integer.| + + +## UndoRedoConfig + +Represents the configuration of the **UndoRedoManager** instance. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +| Name | Type | Mandatory| Description | +| -------------- | ------ | ---- | ------------------------------------------------------------ | +| captureTimeout | number | Yes | Operation capture time.
If the interval between any two operations is less than this value, an undo or redo operation will be triggered.
**Constraints**: The value must be a positive integer. If a decimal is passed in, the value will be rounded down.| + +## UpdatedNode + +Represents the node updated after the operation log is applied to the collaboration edit object. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +| Name | Type | Read Only| Optional| Description | +| ------------ | ------------------------------ | ---- | ---- | ------------------------------------------------------------ | +| editUnitName | string | Yes | No | Name of the editing unit where the updated node is located after the operation log is applied to the collaboration edit object. The value is returned by the collaboration edit object.
**Constraints**: See the constraints for the **editUnitName** parameter in [getEditUnit](#geteditunit).| +| node | [Node](#node) \| [Text](#text) | Yes | No | Node updated. | + +## EditObjectRecord + +Represents the data uploaded or downloaded. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +| Name | Type | Read Only| Optional| Description | +| ------ | ---------- | ---- | ---- | ------------------------------------------------------------ | +| cursor | number | Yes | No | Watermark information of the data.
It is a non-negative integer internally generated by the collaboration edit object in ascending order by 1.| +| id | string | Yes | No | Unique identifier of the device. For details, see **id** in [UniqueId](#uniqueid).| +| data | Uint8Array | Yes | No | Data to upload or download. | + +## EditUnit + +Provides APIs for managing the editing units. + +Before calling any of the following APIs, you must use [getEditUnit](#geteditunit) to create a **EditUnit** instance. + +### getName + +getName(): string + +Obtains the name of this object. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| string | Object name obtained.
If the object is an editing unit instance, the return value is the same as the **editUnitName** value in [getEditUnit](#geteditunit). If the object is a paragraph instance, the return value is the same as the parameter value in the constructor.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| **ID**| **Error Message** | +|-----------|---------| +| 202 | Not system application. | + +**Example** + +```ts +let editUnit: collaborationEditObject.EditUnit | undefined = undefined; + +if (editObject != undefined) { + try { + editUnit = editObject.getEditUnit("editUnit01"); + let name: string | undefined = editUnit.getName(); + } catch (err) { + console.error(`Catch an error, code is ${err.code}, message is ${err.message}`); + } +} +``` + + + +### insertNodes + +insertNodes(index: number, nodes: Node[]): void + +Inserts multiple paragraphs to the specified index in this object. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | ------------------------------------------------------------ | +| index | number | Yes | Index from which the nodes are inserted.
The value must be a non-negative integer. Any decimal passed in will be rounded down.
The value cannot exceed the index range of the object.| +| nodes | [Node](#node)[] | Yes | Nodes to insert. | + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [Collaboration Data Model Error Codes](errorcode-collaboration-edit-object.md). + +| **ID**| **Error Message** | +|-----------|---------| +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 202 | Not system application. | +| 15410000 | Internal error. | +| 15410001 | Unsupported operation. | +| 15410002 | Index out of range. | +| 15410003 | Database error. | + +**Example** + +```ts +let editUnit: collaborationEditObject.EditUnit | undefined = undefined; + +if (editObject != undefined) { + try { + editUnit = editObject.getEditUnit("editUnit01"); + let node01: collaborationEditObject.Node = new collaborationEditObject.Node("p1"); + editUnit.insertNodes(0, [node01]); + } catch (err) { + console.error(`Catch an error, code is ${err.code}, message is ${err.message}`); + } +} +``` + +### delete + +delete(index: number, length: number): void + +Deletes a child node of the given length from the specified position. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | ------------------------------------------------------------ | +| index | number | Yes | Start position.
The value must be a non-negative integer. Any decimal passed in will be rounded down.
If the value exceeds the index range of the object, error 15410002 will be thrown.| +| length | number | Yes | Length of the child node to delete.
The value must be a positive integer. Any decimal passed in will be rounded down.
If the sum of **index** and **length** is greater than the object length, all the child nodes will be deleted from the start position.| + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [Collaboration Data Model Error Codes](errorcode-collaboration-edit-object.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 202 | Not system application. | +| 15410000 | Internal error. | +| 15410001 | Unsupported operation. | +| 15410002 | Index out of range. | +| 15410003 | Database error. | + +**Example** + +```ts +let editUnit: collaborationEditObject.EditUnit | undefined = undefined; + +if (editObject != undefined) { + try { + editUnit = editObject.getEditUnit("editUnit01"); + let node01: collaborationEditObject.Node = new collaborationEditObject.Node("p1"); + let node02: collaborationEditObject.Node = new collaborationEditObject.Node("p2"); + editUnit.insertNodes(0, [node01, node02]); + editUnit.delete (0, 1); // Delete the first paragraph. + } catch (err) { + console.error(`Catch an error, code is ${err.code}, message is ${err.message}`); + } +} +``` + + + +### getChildren + +getChildren(start: number, end: number): Array + +Obtains the child nodes in a specified range in this object. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | ------------------------------------------------------------ | +| start | number | Yes | Start position.
The value must be a non-negative integer. Any decimal passed in will be rounded down.
The value cannot exceed the actual index range.| +| end | number | Yes | End position.
The value must a non-negative integer and greater than the value of **start**. Any decimal passed in will be rounded down.
If the value is out of the index range, all child nodes from the start position will be returned.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Array<[Node](#node) \| [Text](#text)> | Child nodes obtained.| + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [Collaboration Data Model Error Codes](errorcode-collaboration-edit-object.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 202 | Not system application. | +| 15410000 | Internal error. | +| 15410001 | Unsupported operation. | +| 15410002 | Index out of range. | +| 15410003 | Database error. | + +**Example** + +```ts +let editUnit: collaborationEditObject.EditUnit | undefined = undefined; + +if (editObject != undefined) { + try { + editUnit = editObject.getEditUnit("editUnit01"); + let node01: collaborationEditObject.Node = new collaborationEditObject.Node("p1"); + let node02: collaborationEditObject.Node = new collaborationEditObject.Node("p2"); + editUnit.insertNodes(0, [node01, node02]); + let children: Array | undefined = editUnit.getChildren(0, 1); // Obtain the first child node. + } catch (err) { + console.error(`Catch an error, code is ${err.code}, message is ${err.message}`); + } +} +``` + + + +### getJsonResult + +getJsonResult(): string + +Obtains the JSON string of this object. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| string | JSON string obtained.| + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [Collaboration Data Model Error Codes](errorcode-collaboration-edit-object.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 202 | Not system application. | +| 15410000 | Internal error. | +| 15410001 | Unsupported operation. | +| 15410002 | Index out of range. | +| 15410003 | Database error. | + +**Example** + +```ts +let editUnit: collaborationEditObject.EditUnit | undefined = undefined; + +if (editObject != undefined) { + try { + editUnit = editObject.getEditUnit("editUnit01"); + let node01: collaborationEditObject.Node = new collaborationEditObject.Node("p1"); + let node02: collaborationEditObject.Node = new collaborationEditObject.Node("p2"); + editUnit.insertNodes(0, [node01, node02]); + let json: string | undefined = editUnit.getJsonResult(); + } catch (err) { + console.error(`Catch an error, code is ${err.code}, message is ${err.message}`); + } +} +``` + + +### getRelativePos + +getRelativePos(absolutePos: number): RelativePos + +Obtains the relative position of the cursor in the editing unit. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | ------------------------------------------------------------ | +| absolutePos | number | Yes| Absolute position of the cursor in the editing unit. The value must be a non-negative integer.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| [RelativePos](#relativepos) | Relative position of the cursor obtained.| + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [Collaboration Data Model Error Codes](errorcode-collaboration-edit-object.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 202 | Not system application. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 15410000 | Internal error. | +| 15410003 | Database error. | + +**Example** + +```ts +let editUnit: collaborationEditObject.EditUnit | undefined = undefined; + +if (editObject != undefined) { + try { + editUnit = editObject.getEditUnit("editUnit01"); + let node01: collaborationEditObject.Node = new collaborationEditObject.Node("p1"); + editUnit.insertNodes(0, [node01]); + let text01: collaborationEditObject.Text = new collaborationEditObject.Text(); + node01.insertTexts(0, [text01]); + text01.insert (0, "Hello"); + let relPos = editUnit.getRelativePos (2); // 2 is the absolute position of the cursor in the editor. + } catch (err) { + console.error(`Catch an error, code is ${err.code}, message is ${err.message}`); + } +} +``` + +### getAbsolutePos + +getAbsolutePos(relativePos: RelativePos): number + +Obtains the absolute position of the cursor in the editing unit. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | ------------------------------------------------------------ | +| relativePos | [RelativePos](#relativepos) | Yes| Relative position of the cursor in the editing unit.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| number | Absolute position of the cursor obtained. The value must be a non-negative integer.| + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [Collaboration Data Model Error Codes](errorcode-collaboration-edit-object.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 202 | Not system application. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 15410000 | Internal error. | +| 15410003 | Database error. | + +**Example** + +```ts +let editUnit: collaborationEditObject.EditUnit | undefined = undefined; + +if (editObject != undefined) { + try { + editUnit = editObject.getEditUnit("editUnit01"); + let node01: collaborationEditObject.Node = new collaborationEditObject.Node("p1"); + editUnit.insertNodes(0, [node01]); + let text01: collaborationEditObject.Text = new collaborationEditObject.Text(); + node01.insertTexts(0, [text01]); + text01.insert(0, "followRedone"); + + let node02: collaborationEditObject.Node = new collaborationEditObject.Node("p2"); + editUnit.insertNodes(1, [node02]); + let pos = editUnit.getAbsolutePos({parentId: null, parentName: "top", id: null, pos: 0}); // Obtain the absolute position of node2 in the editor. + } catch (err) { + console.error(`Catch an error, code is ${err.code}, message is ${err.message}`); + } +} +``` + + + +## UniqueId +Represents the unique ID of a node. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +| Name | Type | Read Only | Optional | Description | +| ------------------- | ------------------------- | ------------------- | ------------------- | ------------------- | +| id | string | Yes| No| Identifier of the client, internally generated by the collaboration edit object.| +| clock | number | Yes| No| Clock number of the node.
The value is a non-negative integer internally generated by the collaboration edit object.| + + +## AttributesRecord +type AttributesRecord = Record + +Represents the [Node](#node) properties, stored in key-value (KV) pairs. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +| Type | Description | +| ------------------------------------------ | ------------------------------------------------------------ | +| Record | Types of the key and value in a KV pair. The key must be a string, and the value can be a string, number, or Boolean value.| + + +## Node +Provides APIs for managing paragraphs. This class is inherited from [EditUnit](#editunit). + +### constructor +constructor(name: string) + +A constructor used to create a paragraph instance. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | ------------------------------------------------------------ | +| name | string | Yes | Name of the paragraph, which
cannot be an empty string.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| **ID**| **Error Message** | +|-----------|---------| +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 202 | Not system application. | + +### getId +getId(): UniqueId + +Obtains the unique identifier of this paragraph. This API can be called only after the paragraph is inserted into the collaboration edit object. Otherwise, the error code 15410001 will be thrown. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| [UniqueId](#uniqueid) | Paragraph ID obtained.| + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [Collaboration Data Model Error Codes](errorcode-collaboration-edit-object.md). + +| **ID**| **Error Message** | +|-----------|---------| +| 202 | Not system application. | +| 15410000 | Internal error. | +| 15410001 | Unsupported operation. | + +**Example** + +```ts +let editUnit: collaborationEditObject.EditUnit | undefined = undefined; + +if (editObject != undefined) { + try { + editUnit = editObject.getEditUnit("editUnit01"); + let node01: collaborationEditObject.Node = new collaborationEditObject.Node("p1"); + editUnit.insertNodes(0, [node01]); + let id: collaborationEditObject.UniqueId | undefined = node01.getId(); + } catch (err) { + console.error(`Catch an error, code is ${err.code}, message is ${err.message}`); + } +} +``` + + + +### insertTexts + +insertTexts(index: number, texts: Text[]): void + +Inserts multiple text objects into this paragraph. This API can be called only after the paragraph is inserted into the collaboration edit object. Otherwise, the error code 15410001 will be thrown. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | ------------------------------------------------------------ | +| index | number | Yes | Index from which the text objects are inserted.
The value must be a non-negative integer. Any decimal passed in will be rounded down.
The value cannot exceed the index range of the object.| +| texts | [Text](#text)[] | Yes | Text objects to insert.| + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [Collaboration Data Model Error Codes](errorcode-collaboration-edit-object.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 202 | Not system application. | +| 15410000 | Internal error. | +| 15410001 | Unsupported operation. | +| 15410002 | Index out of range. | +| 15410003 | Database error. | + +**Example** + +```ts +let editUnit: collaborationEditObject.EditUnit | undefined = undefined; + +if (editObject != undefined) { + try { + editUnit = editObject.getEditUnit("editUnit01"); + let node01: collaborationEditObject.Node = new collaborationEditObject.Node("p1"); + editUnit.insertNodes(0, [node01]); + let text01: collaborationEditObject.Text = new collaborationEditObject.Text(); + node01.insertTexts(0, [text01]); + } catch (err) { + console.error(`Catch an error, code is ${err.code}, message is ${err.message}`); + } +} +``` + + + +### setAttributes + +setAttributes(attributes: AttributesRecord): void + +Sets attributes for this paragraph. This API can be called only after the paragraph is inserted into the collaboration edit object. Otherwise, the error code 15410001 will be thrown. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | ------------------------------------------------------------ | +| attributes | [AttributesRecord](#attributesrecord) | Yes | Attribute names and values to set. | + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [Collaboration Data Model Error Codes](errorcode-collaboration-edit-object.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 202 | Not system application. | +| 15410000 | Internal error. | +| 15410001 | Unsupported operation. | +| 15410002 | Index out of range. | +| 15410003 | Database error. | + +**Example** + +```ts +let editUnit: collaborationEditObject.EditUnit | undefined = undefined; + +if (editObject != undefined) { + try { + editUnit = editObject.getEditUnit("editUnit01"); + let node01: collaborationEditObject.Node = new collaborationEditObject.Node("p1"); + editUnit.insertNodes(0, [node01]); + node01.setAttributes({"align":"left", width:48}); + } catch (err) { + console.error(`Catch an error, code is ${err.code}, message is ${err.message}`); + } +} +``` + + + +### removeAttributes + +removeAttributes(attributeNames: string[]): void + +Removes attributes of this paragraph. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | ------------------------------------------------------------ | +| attributeNames | string[] | Yes | Names of the attributes to remove. | + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [Collaboration Data Model Error Codes](errorcode-collaboration-edit-object.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 202 | Not system application. | +| 15410000 | Internal error. | +| 15410001 | Unsupported operation. | +| 15410002 | Index out of range. | +| 15410003 | Database error. | + +**Example** + +```ts +let editUnit: collaborationEditObject.EditUnit | undefined = undefined; + +if (editObject != undefined) { + try { + editUnit = editObject.getEditUnit("editUnit01"); + let node01: collaborationEditObject.Node = new collaborationEditObject.Node("p1"); + editUnit.insertNodes(0, [node01]); + node01.removeAttributes(["align", "width"]); + } catch (err) { + console.error(`Catch an error, code is ${err.code}, message is ${err.message}`); + } +} +``` + + + +### getAttributes + +getAttributes(): AttributesRecord + +Obtains all attributes of this paragraph. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| [AttributesRecord](#attributesrecord) | All attributes of the current node.| + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [Collaboration Data Model Error Codes](errorcode-collaboration-edit-object.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 202 | Not system application. | +| 15410000 | Internal error. | +| 15410001 | Unsupported operation. | +| 15410002 | Index out of range. | +| 15410003 | Database error. | + +**Example** + +```ts +let editUnit: collaborationEditObject.EditUnit | undefined = undefined; + +if (editObject != undefined) { + try { + editUnit = editObject.getEditUnit("editUnit01"); + let node01: collaborationEditObject.Node = new collaborationEditObject.Node("p1"); + editUnit.insertNodes(0, [node01]); + node01.setAttributes({"align":"left", width:48}); + let attrs: collaborationEditObject.AttributesRecord = node01.getAttributes(); + } catch (err) { + console.error(`Catch an error, code is ${err.code}, message is ${err.message}`); + } +} +``` + +### setAsset + +setAsset(assetKey: string, assetValue: string): void + +Sets an asset of this node. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | ------------------------------------------------------------ | +| assetKey | string | Yes | Key of the asset to set. The key is regarded as the asset. The value can be any non-empty string. | +| assetValue | string | Yes | Asset attribute value to be set. The value can be any non-empty string. | + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [Collaboration Data Model Error Codes](errorcode-collaboration-edit-object.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 202 | Not system application. | +| 15410000 | Internal error. | +| 15410001 | Unsupported operation. | +| 15410002 | Index out of range. | +| 15410003 | Database error. | + + +**Example** +```ts +let editUnit: collaborationEditObject.EditUnit | undefined = undefined; + +if (editObject != undefined) { + try { + editUnit = editObject.getEditUnit("editUnit01"); + let node01: collaborationEditObject.Node = new collaborationEditObject.Node("p1"); + editUnit.insertNodes(0, [node01]); + node01.setAsset("src", "/path/to/asset/asset.jpg"); + } catch (err) { + console.error(`Catch an error, code is ${err.code}, message is ${err.message}`); + } +} +``` + + +## FormatValueType + +type FormatValueType = null | number | string | boolean + +Defines the data types allowed for text object formatting. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +| Type | Description | +| ------- | -------------------------------- | +| null | The value is null. | +| number | The value is a number of any value. | +| string | The value is a string of any value.| +| boolean | The value is of Boolean type. | + +## TextFormat +type TextFormat = Record + +Defines the format of a text object, in the form of a KV pair. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +| Type | Description | +| --------------------------------------------------- | ------------------------------------------------------------ | +| Record | Types of the key and value in a KV pair. The key type is string, and the value type is [FormatValueType](#formatvaluetype).| + +## Text + +Provides APIs for managing the text objects. + +### constructor + +constructor() + +A constructor used to create a text instance. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 202 | Not system application. | + +### getId +getId(): UniqueId + +Obtains the ID of this text object. This API can be called only after the text object is inserted into the collaboration edit object. Otherwise, the error code 15410001 will be thrown. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| [UniqueId](#uniqueid) | ID of the text object obtained.| + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [Collaboration Data Model Error Codes](errorcode-collaboration-edit-object.md). + +| **ID**| **Error Message** | +|-----------|---------| +| 202 | Not system application. | +| 15410000 | Internal error. | +| 15410001 | Unsupported operation. | + +**Example** + +```ts +let editUnit: collaborationEditObject.EditUnit | undefined = undefined; + +if (editObject != undefined) { + try { + editUnit = editObject.getEditUnit("editUnit01"); + let node01: collaborationEditObject.Node = new collaborationEditObject.Node("p1"); + editUnit.insertNodes(0, [node01]); + let text01: collaborationEditObject.Text = new collaborationEditObject.Text(); + node01.insertTexts(0, [text01]); + let id: collaborationEditObject.UniqueId | undefined = text01.getId(); + } catch (err) { + console.error(`Catch an error, code is ${err.code}, message is ${err.message}`); + } +} +``` + +### insert + +insert(index: number, text: string, format?: TextFormat): void + +Inserts text to the specified position of this text object. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | ------------------------------------------------------------ | +| index | number | Yes | Index from which the text is inserted.
The value must be a non-negative integer. Any decimal passed in will be rounded down.
The value cannot be greater than the length of the text object.| +| text | string | Yes | Text to insert. | +| format | [TextFormat](#textformat) | No| Format of the text inserted. | + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [Collaboration Data Model Error Codes](errorcode-collaboration-edit-object.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 202 | Not system application. | +| 15410000 | Internal error. | +| 15410001 | Unsupported operation. | +| 15410002 | Index out of range. | +| 15410003 | Database error. | + +**Example** + +```ts +let editUnit: collaborationEditObject.EditUnit | undefined = undefined; + +if (editObject != undefined) { + try { + editUnit = editObject.getEditUnit("editUnit01"); + let node01: collaborationEditObject.Node = new collaborationEditObject.Node("p1"); + editUnit.insertNodes(0, [node01]); + let text01: collaborationEditObject.Text = new collaborationEditObject.Text(); + node01.insertTexts(0, [text01]); + text01.insert(0, "abc"); + text01.insert(3, "def", {"color":"red"}); + } catch (err) { + console.error(`Catch an error, code is ${err.code}, message is ${err.message}`); + } +} +``` + + + +### delete + +delete(index: number, length: number): void + +Deletes text of the given length from the specified position. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | ------------------------------------------------------------ | +| index | number | Yes | Start position.
The value must be a non-negative integer. Any decimal passed in will be rounded down.
If the value exceeds the index range of the object, error 15410002 will be thrown.| +| length | number | Yes | Length of the text to delete.
The value must be a positive integer. Any decimal passed in will be rounded down.
If the sum of **index** and **length** is greater than the length of the text object, all the text content from the start position will be deleted.| + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [Collaboration Data Model Error Codes](errorcode-collaboration-edit-object.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 202 | Not system application. | +| 15410000 | Internal error. | +| 15410001 | Unsupported operation. | +| 15410002 | Index out of range. | +| 15410003 | Database error. | + +**Example** + +```ts +let editUnit: collaborationEditObject.EditUnit | undefined = undefined; + +if (editObject != undefined) { + try { + editUnit = editObject.getEditUnit("editUnit01"); + let node01: collaborationEditObject.Node = new collaborationEditObject.Node("p1"); + editUnit.insertNodes(0, [node01]); + let text01: collaborationEditObject.Text = new collaborationEditObject.Text(); + node01.insertTexts(0, [text01]); + text01.insert(0, "abc"); + text01.insert(3, "def", {"color":"red"}); + text01.delete (1, 2); // Characters b and c will be deleted. + } catch (err) { + console.error(`Catch an error, code is ${err.code}, message is ${err.message}`); + } +} +``` + + + +### format + +format(index: number, length: number, format: TextFormat): void + +Formats the text of the given length from the specified position. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Parameters** +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | ------------------------------------------------------------ | +| index | number | Yes| Start position for formatting.
The value must be a non-negative integer. Any decimal passed in will be rounded down.
If the value exceeds the index range of the object, error 15410002 will be thrown.| +| length | number | Yes | Length of the text to format.
The value must be a positive integer. Any decimal passed in will be rounded down.
If the sum of **index** and **length** is greater than the length of the text object, all the text content from the start position will be formatted.| +| format | [TextFormat](#textformat) | Yes | Format to apply. | + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [Collaboration Data Model Error Codes](errorcode-collaboration-edit-object.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 202 | Not system application. | +| 15410000 | Internal error. | +| 15410001 | Unsupported operation. | +| 15410002 | Index out of range. | +| 15410003 | Database error. | + +**Example** + +```ts +let editUnit: collaborationEditObject.EditUnit | undefined = undefined; + +if (editObject != undefined) { + try { + editUnit = editObject.getEditUnit("editUnit01"); + let node01: collaborationEditObject.Node = new collaborationEditObject.Node("p1"); + editUnit.insertNodes(0, [node01]); + let text01: collaborationEditObject.Text = new collaborationEditObject.Text(); + node01.insertTexts(0, [text01]); + text01.insert(0, "abc"); + text01.insert(3, "def", {"color":"red"}); + text01.format(0, 3, {"color":"green"}); + } catch (err) { + console.error(`Catch an error, code is ${err.code}, message is ${err.message}`); + } +} +``` + + + +### getPlainText + +getPlainText(): string + +Obtains the plain text content of this text object. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| string | Plain text content obtained.| + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [Collaboration Data Model Error Codes](errorcode-collaboration-edit-object.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 202 | Not system application. | +| 15410000 | Internal error. | +| 15410001 | Unsupported operation. | +| 15410002 | Index out of range. | +| 15410003 | Database error. | + +**Example** + +```ts +let editUnit: collaborationEditObject.EditUnit | undefined = undefined; + +if (editObject != undefined) { + try { + editUnit = editObject.getEditUnit("editUnit01"); + let node01: collaborationEditObject.Node = new collaborationEditObject.Node("p1"); + editUnit.insertNodes(0, [node01]); + let text01: collaborationEditObject.Text = new collaborationEditObject.Text(); + node01.insertTexts(0, [text01]); + text01.insert(0, "abc"); + text01.insert(3, "def", {"color":"red"}); + let content: string | undefined = text01.getPlainText(); // 'abcdef' is returned. + } catch (err) { + console.error(`Catch an error, code is ${err.code}, message is ${err.message}`); + } +} +``` + + + +### getJsonResult + +getJsonResult(): string + +Obtains the text in JSON string from this text object. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| string | Text in JSON string obtained.| + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [Collaboration Data Model Error Codes](errorcode-collaboration-edit-object.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 202 | Not system application. | +| 15410000 | Internal error. | +| 15410001 | Unsupported operation. | +| 15410002 | Index out of range. | +| 15410003 | Database error. | + +**Example** + +```ts +let editUnit: collaborationEditObject.EditUnit | undefined = undefined; + +if (editObject != undefined) { + try { + editUnit = editObject.getEditUnit("editUnit01"); + let node01: collaborationEditObject.Node = new collaborationEditObject.Node("p1"); + editUnit.insertNodes(0, [node01]); + let text01: collaborationEditObject.Text = new collaborationEditObject.Text(); + node01.insertTexts(0, [text01]); + text01.insert(0, "abc"); + text01.insert(3, "def", {"color":"red"}); + let json: string | undefined = text01.getJsonResult(); + } catch (err) { + console.error(`Catch an error, code is ${err.code}, message is ${err.message}`); + } +} +``` + + + +## UndoRedoManager + +Provides APIs for performing undo or redo operations. + +The system distinguishes different operations based on **captureTimeout**, which can be set in the **UndoRedoManager** instance obtained by using [getUndoRedoManager](#getundoredomanager). An undo or redo operation will be triggered if the time interval between the operations does not exceed **captureTimeout**. + +Before calling any of the following APIs, you must use [getUndoRedoManager](#getundoredomanager) to create an **UndoRedoManager** instance. + +### undo +undo(): void + +Reverses the most recent operation. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [Collaboration Data Model Error Codes](errorcode-collaboration-edit-object.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 202 | Not system application. | +| 15410000 | Internal error. | +| 15410003 | Database error. | + +**Example** + +```ts +let editUnit: collaborationEditObject.EditUnit | undefined = undefined; +let undoRedoManager: collaborationEditObject.UndoRedoManager | undefined = undefined; + +function sleep(ms: number): Promise { + return new Promise(resolve => setTimeout(resolve, ms)); +} + +async function undoTest() { + if (editObject != undefined) { + try { + editUnit = editObject.getEditUnit("editUnit01"); + undoRedoManager = editObject.getUndoRedoManager("editUnit01", {captureTimeout: 500}); + let node01: collaborationEditObject.Node = new collaborationEditObject.Node("p1"); + editUnit.insertNodes(0, [node01]); + await sleep(500); + node01.setAttributes({"align":"left", "width":48}); + undoRedoManager.undo(); + let attrs: collaborationEditObject.AttributesRecord = node01.getAttributes(); // attrs does not contain any attribute. + } catch (err) { + console.error(`Catch an error, code is ${err.code}, message is ${err.message}`); + } + } +} + +undoTest() +``` + + + +### redo + +redo(): void + +Reapplies the operation that was previously undone. + +**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [Collaboration Data Model Error Codes](errorcode-collaboration-edit-object.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 202 | Not system application. | +| 15410000 | Internal error. | +| 15410003 | Database error. | + +**Example** + +```ts +let editUnit: collaborationEditObject.EditUnit | undefined = undefined; +let undoRedoManager: collaborationEditObject.UndoRedoManager | undefined = undefined; + +function sleep(ms: number): Promise { + return new Promise(resolve => setTimeout(resolve, ms)); +} + +async function redoTest() { + if (editObject != undefined) { + try { + editUnit = editObject.getEditUnit("editUnit01"); + undoRedoManager = editObject.getUndoRedoManager("editUnit01", {captureTimeout: 500}); + let node01: collaborationEditObject.Node = new collaborationEditObject.Node("p1"); + editUnit.insertNodes(0, [node01]); + await sleep(500); + node01.setAttributes({"align":"left", "width":48}); + undoRedoManager.undo(); + let attrs: collaborationEditObject.AttributesRecord = node01.getAttributes(); // attrs does not contain any attribute. + undoRedoManager.redo(); + attrs = node01.getAttributes(); // attrs contains the previously set attributes. + } catch (err) { + console.error(`Catch an error, code is ${err.code}, message is ${err.message}`); + } + } +} + +redoTest() +``` diff --git a/en/application-dev/reference/apis-arkdata/js-apis-data-commonType.md b/en/application-dev/reference/apis-arkdata/js-apis-data-commonType.md index f8cdeab09fbcabfcdc0cc3e6eea412799661275b..a08d0ed0b6a4113ef900e49d4fc6cf336f5ee12e 100644 --- a/en/application-dev/reference/apis-arkdata/js-apis-data-commonType.md +++ b/en/application-dev/reference/apis-arkdata/js-apis-data-commonType.md @@ -29,7 +29,7 @@ Enumerates the asset statuses. Use the enum name rather than the enum value. ## Asset -Defines information about an asset (such as a document, image, and video). +Represents asset (such as a file, image, or video) information. For details, see the sample code in [Using Distributed Data Objects in Cross-Device Migration](../../database/data-sync-of-distributed-data-object.md#using-distributed-data-objects-in-cross-device migration). **System capability**: SystemCapability.DistributedDataManager.CommonType diff --git a/en/application-dev/reference/apis-arkdata/js-apis-data-dataShare-sys.md b/en/application-dev/reference/apis-arkdata/js-apis-data-dataShare-sys.md index 2f8cc42f594495b28245b354eadb7fcf907a0e63..a1e2a02fc92849af15648f1b5bf83cb5d017b715 100644 --- a/en/application-dev/reference/apis-arkdata/js-apis-data-dataShare-sys.md +++ b/en/application-dev/reference/apis-arkdata/js-apis-data-dataShare-sys.md @@ -89,7 +89,7 @@ Creates a **DataShareHelper** instance. This API uses an asynchronous callback t | -------- | -------------------------------------------------------- | ---- | ------------------------------------------------------------ | | context | [Context](../apis-ability-kit/js-apis-inner-application-context.md#context) | Yes | Context of the application. | | uri | string | Yes | URI of the server application to connect. | -| options | [DataShareHelperOptions](#datasharehelperoptions10)| Yes | Whether [DataShareHelper](#datasharehelper) is in proxy mode and the waiting time for starting the data provider process in non-silent access mode. If this parameter is not set, [DataShareHelper](#datasharehelper) is not in proxy mode and the waiting time for starting the data provider process in non-silent access mode is 2 seconds.| +| options | [DataShareHelperOptions](#datasharehelperoptions10)| Yes | Whether [DataShareHelper](#datasharehelper) is in proxy mode and the waiting time for starting the data provider process in non-silent access mode.
If this parameter is not set, [DataShareHelper](#datasharehelper) is not in proxy mode and the waiting time for starting the data provider process in non-silent access mode is 2 seconds.
If the URI starts with **datashareproxy**, the **isProxy** parameter in **options** must be set. Otherwise, **DataShareHelper** will fail to be created and an error will be returned.| | callback | AsyncCallback<[DataShareHelper](#datasharehelper)> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the **DataShareHelper** instance created. Otherwise, **err** is an error object.| **Error codes** @@ -143,7 +143,7 @@ Creates a **DataShareHelper** instance. This API uses a promise to return the re | ------- | ------------------------------------------------- | ---- | ------------------------------ | | context | [Context](../apis-ability-kit/js-apis-inner-application-context.md#context) | Yes | Context of the application. | | uri | string | Yes | URI of the server application to connect.| -| options10+ | [DataShareHelperOptions](#datasharehelperoptions10) | No| Configuration of the **DataShareHelper** instance. This parameter is supported since API version 10. If it is not set, [DataShareHelper](#datasharehelper) is not in proxy mode and the waiting time for starting the data provider process in non-silent access mode is 2 seconds. If the URI starts with **datashareproxy**, **isProxy** in **options** is mandatory. Otherwise, an error will be returned.| +| options10+ | [DataShareHelperOptions](#datasharehelperoptions10) | No| Optional configuration of the **DataShareHelper** instance. It specifies whether [DataShareHelper](#datasharehelper) is in proxy mode and the waiting time for starting the data provider process in non-silent access mode.
If this parameter is not set, [DataShareHelper](#datasharehelper) is not in proxy mode and the waiting time for starting the data provider process in non-silent access mode is 2 seconds.
If the URI starts with **datashareproxy**, the **isProxy** parameter in **options** must be set. Otherwise, **DataShareHelper** will fail to be created and an error will be returned. | **Return value** @@ -291,8 +291,8 @@ Represents the optional parameters of [DataShareHelper](#datasharehelper). | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| isProxy | boolean | No| Whether the [DataShareHelper](#datasharehelper) is in proxy mode.
The default value is **false**.
If the value is **true**, the [DataShareHelper](#datasharehelper) to be created is in proxy mode, and all operations will not open the data provider application unless the database does not exist. If the database does not exist, [createDataShareHelper](#datasharecreatedatasharehelper10) will start the data provider to create a database.| -| waitTime16+ | number | No| Waiting time for starting the data provider process, in seconds.
The default value is **2**.| +| isProxy | boolean | No| Whether the [DataShareHelper](#datasharehelper) is in proxy mode.
The default value is **false**.
If the value is **true**, the [DataShareHelper](#datasharehelper) to be created is in proxy mode, and all operations will not open the data provider application unless the database does not exist. If the database does not exist, [createDataShareHelper](#datasharecreatedatasharehelper10) will start the data provider to create a database.| +| waitTime16+ | number | No| Waiting time for starting the data provider process, in seconds.
The default value is **2**.| ## TemplateId10+ @@ -319,7 +319,7 @@ Defines the data to publish. ## RdbDataChangeNode10+ -Defines the subscription/unsubscription result of the RDB data changes. The callback can return the data not larger than 200 KB in size. +Represents the RDB data change result. The data returned by the callback is not larger than 200 KB in size. **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer @@ -1545,7 +1545,7 @@ try { batchUpdate(operations: Record<string, Array<UpdateOperation>>): Promise<Record<string, Array<number>>> -Updates data in batches. A maximum of 900 KB data can be updated at a time. If the data volume exceeds 900 KB, the update will fail. The transaction of this API depends on the data provider. This API uses a promise to return the result. +Updates data in batches. A maximum of 900 KB data can be updated at a time. If the data volume exceeds 900 KB, the update will fail. The transaction of this API depends on the data provider. This API uses a promise to return the result. Silent access is not supported currently. **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer diff --git a/en/application-dev/reference/apis-arkdata/js-apis-data-dataSharePredicates.md b/en/application-dev/reference/apis-arkdata/js-apis-data-dataSharePredicates.md index 718fba7fbf4e1de1dc8aba48b0c8b2a181cfab56..505cfd4ea2d24692c78d87837aafed30c167a839 100644 --- a/en/application-dev/reference/apis-arkdata/js-apis-data-dataSharePredicates.md +++ b/en/application-dev/reference/apis-arkdata/js-apis-data-dataSharePredicates.md @@ -19,13 +19,13 @@ import { dataSharePredicates } from '@kit.ArkData'; ``` ## DataSharePredicates -Provides methods for setting different **DataSharePredicates** objects. This type is not multi-thread safe. If a **DataSharePredicates** instance is operated by multiple threads at the same time in an application, use a lock for the instance. +Provides APIs for setting different **DataSharePredicates** objects. This type is not multi-thread safe. If a **DataSharePredicates** instance is operated by multiple threads at the same time in an application, use a lock for it. ### equalTo10+ equalTo(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the data that is equal to the specified value. +Creates a **DataSharePredicates** object to search for the records in the specified column that are equal to the given value. Currently, only the relational database (RDB) and key-value database (KVDB, schema) support this **DataSharePredicates** object. @@ -56,7 +56,7 @@ predicates.equalTo("NAME", "Rose") and(): DataSharePredicates -Adds the AND condition to this **DataSharePredicates** object. +Creates a **DataSharePredicates** object to add the AND condition. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -81,7 +81,7 @@ predicates.equalTo("NAME", "lisi") orderByAsc(field: string): DataSharePredicates -Sets a **DataSharePredicates** object that sorts data in ascending order. +Creates a **DataSharePredicates** object that sorts records in ascending order. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -110,7 +110,7 @@ predicates.orderByAsc("AGE") orderByDesc(field: string): DataSharePredicates -Sets a **DataSharePredicates** object that sorts data in descending order. +Creates a **DataSharePredicates** object that sorts data in descending order. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -139,7 +139,7 @@ predicates.orderByDesc("AGE") limit(total: number, offset: number): DataSharePredicates -Sets a **DataSharePredicates** object to specify the number of results and the start position. +Creates a **DataSharePredicates** object to specify the number of records in the result and the start position. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -149,8 +149,8 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name | Type | Mandatory| Description | | -------- | ------ | ---- | -------------- | -| total | number | Yes | Number of results. | -| offset | number | Yes | Start position.| +| total | number | Yes | Number of records. The value should be a positive integer. If a value less than or equal to **0** is specified, the number of records is not limited. | +| offset | number | Yes | Start position. The value should be a positive integer. If a value less than or equal to **0** is specified, the query result is returned from the first element.| **Return value** @@ -169,7 +169,7 @@ predicates.equalTo("NAME", "Rose").limit(10, 3) in(field: string, value: Array<ValueType>): DataSharePredicates -Sets a **DataSharePredicates** object to match the data that is within the specified value. +Creates a **DataSharePredicates** object to search for the records in the specified column that are within the specified range. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. diff --git a/en/application-dev/reference/apis-arkdata/js-apis-data-distributedobject.md b/en/application-dev/reference/apis-arkdata/js-apis-data-distributedobject.md index cf14bd15e3181afea95565ff40fe96ee700ef393..374c1f029c1d67701b5eef29297269ae11e76df0 100644 --- a/en/application-dev/reference/apis-arkdata/js-apis-data-distributedobject.md +++ b/en/application-dev/reference/apis-arkdata/js-apis-data-distributedobject.md @@ -26,7 +26,7 @@ Creates a distributed data object. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | context | Context | Yes| Application context.
For details about the application context of the FA model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md).| - | source | object | Yes | Properties of the distributed data object. | + | source | object | Yes| Properties of the distributed data object.| **Return value** @@ -126,7 +126,7 @@ Represents the information returned by the callback of [save](#save9). | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | sessionId | string | Yes| Unique ID for multi-device collaboration.| -| version | number | Yes| Version of the distributed data object saved.| +| version | number | Yes| Version of the saved object, which is a non-negative integer.| | deviceId | string | Yes| ID of the device where the distributed data object is stored. The value **local** indicates the local device.| ## RevokeSaveSuccessResponse9+ @@ -299,7 +299,7 @@ Subscribes to data changes of this distributed data object. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **change**, which indicates data changes.| -| callback | Function | Yes | Callback used to return the changes of the distributed data object.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed properties of the distributed data object. | +| callback | Function | Yes| Callback used to return the changes of the distributed data object.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed properties of the distributed data object.| **Error codes** @@ -335,7 +335,7 @@ Unsubscribes from the data changes of this distributed data object. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **change**, which indicates data changes.| -| callback | Function | No | Callback to unregister. If this parameter is not specified, this API unregisters all data change callbacks of this distributed data object.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed properties of the distributed data object. | +| callback | Function | No| Callback to unregister. If this parameter is not specified, this API unregisters all data change callbacks of this distributed data object.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed properties of the distributed data object.| **Error codes** @@ -516,11 +516,11 @@ The saved data will be released in the following cases: ```ts g_object.setSessionId("123456"); -g_object.save("local").then((result: distributedDataObject.SaveSuccessResponse) => { +g_object.save("local").then((callbackInfo: distributedDataObject.SaveSuccessResponse) => { console.info("save callback"); - console.info("save sessionId " + result.sessionId); - console.info("save version " + result.version); - console.info("save deviceId " + result.deviceId); + console.info("save sessionId " + callbackInfo.sessionId); + console.info("save version " + callbackInfo.version); + console.info("save deviceId " + callbackInfo.deviceId); }).catch((err: BusinessError) => { console.info("save failed, error code = " + err.code); console.info("save failed, error message: " + err.message); @@ -815,7 +815,7 @@ Creates a distributed data object. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | source | object | Yes | Properties of the distributed data object. | + | source | object | Yes| Properties of the distributed data object.| **Return value** @@ -912,7 +912,7 @@ Subscribes to data changes of this distributed data object. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **change**, which indicates data changes.| -| callback | Function | Yes | Callback used to return the changes of the distributed data object.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed properties of the distributed data object. | +| callback | Function | Yes| Callback used to return the changes of the distributed data object.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed properties of the distributed data object.| **Example** @@ -958,7 +958,7 @@ Unsubscribes from the data changes of this distributed data object. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **change**, which indicates data changes.| -| callback | Function | No | Callback to unregister. If this parameter is not specified, this API unregisters all data change callbacks of this distributed data object.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed properties of the distributed data object. | +| callback | Function | No| Callback to unregister. If this parameter is not specified, this API unregisters all data change callbacks of this distributed data object.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed properties of the distributed data object.| **Example** diff --git a/en/application-dev/reference/apis-arkdata/js-apis-data-graphStore-sys.md b/en/application-dev/reference/apis-arkdata/js-apis-data-graphStore-sys.md new file mode 100644 index 0000000000000000000000000000000000000000..668ecd837bb75247137c1fbea90d02981db91079 --- /dev/null +++ b/en/application-dev/reference/apis-arkdata/js-apis-data-graphStore-sys.md @@ -0,0 +1,671 @@ +# @ohos.data.graphStore (Graph Database) (System API) + +A graph database (GDB) is a data management system designed to efficiently store and query graph data. It organizes data as [vertexes](#vertex) and [edges](#edge). The **graphStore** module provides a complete set of mechanisms for local GDB management. It provides read (query), write (add, delete, and modify), and transaction management APIs that can directly run the Graph Query Language (GQL) statements to store, query, and analyze highly interconnected data. + +- [Vertex](#vertex): represents an entity or instance, such as a person, enterprise, account, or any other item to be tracked. It is equivalent to a record, relationship, or row in a relational database, or a document in a document database. +- [Edge](#edge): represents the relationship between vertexes. Edge is a unique data abstraction exclusive to GDB, and must be materialized at runtime when queried. +- [Path](#path): a sequence of vertices and edges in a certain sequence. +- [PathSegment](#pathsegment): an edge along with its start and end vertexes in a path. + +The **graphStore** module provides the following functionalities: + +- [GraphStore](#graphstore): provides APIs for manipulating a GDB. +- [Result](#result): provides the result returned by **read()** or **write()**. +- [Transaction](#transaction): provides APIs for managing transaction objects. + +> **NOTE** +> +> - The initial APIs of this module are supported since API version 18. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The current page contains only the system interfaces of this module. + +## Modules to Import + +```ts +import { graphStore } from '@kit.ArkData'; +``` + +## graphStore.getStore + +getStore(context: Context, config: StoreConfig): Promise<GraphStore> + +Obtains a GraphStore instance for GDB operations. You can set parameters for the instance as required and call related APIs through this instance to perform data operations. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.DataIntelligence.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | -------------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context. The stage model is recommended.
For details about the application context of the FA model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md).| +| config | [StoreConfig](#storeconfig) | Yes | Configuration of the GDB. | + +**Return value** + +| Type | Description | +| ----------------------------------------- | --------------------------------- | +| Promise<[GraphStore](#graphstore)> | Promise used to return the **GraphStore** instance obtained.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Graph Store Error Codes](errorcode-data-gdb.md). + +| **ID**| **Error Message** | +|-----------| ------------------------------------------------------------ | +| 202 | Permission verification failed, application which is not a system application uses system API. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 31300000 | Inner error. | +| 31300001 | Database corrupted. | +| 31300014 | Invalid database path. | +| 31300015 | Config changed. | + +**Example** + +```ts +import { UIAbility } from '@kit.AbilityKit'; +import { window } from '@kit.ArkUI'; +import { BusinessError } from '@kit.BasicServicesKit'; + +let store: graphStore.GraphStore | null = null; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + const STORE_CONFIG: graphStore.StoreConfig = { + name: "testGraphDb", + securityLevel: graphStore.SecurityLevel.S2 + }; + + graphStore.getStore(this.context, STORE_CONFIG).then(async (gdb: graphStore.GraphStore) => { + store = gdb; + console.info('Get GraphStore successfully.') + }).catch((err: BusinessError) => { + console.error(`Get GraphStore failed, code is ${err.code}, message is ${err.message}`); + }) + } +} +``` + +## graphStore.deleteStore + +deleteStore(context: Context, config: StoreConfig): Promise<void> + +Deletes a graph store. This API uses a promise to return the result. + +Before calling this API, call [close](#close) to close the graph store to be deleted. After the deletion, the opened graph store handle becomes invalid. You are advised to set the graph store instance to null. + +**System capability**: SystemCapability.DistributedDataManager.DataIntelligence.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context. The stage model is recommended.
For details about the application context of the FA model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md).| +| config | [StoreConfig](#storeconfig) | Yes | Configuration of the graph store to delete.
**Constraints**
Only **config.name** is used to identify the graph store to be deleted.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Graph Store Error Codes](errorcode-data-gdb.md). + +| **ID**| **Error Message** | +|-----------| ------------------------------------------------------------ | +| 202 | Permission verification failed, application which is not a system application uses system API. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 31300000 | Inner error. | +| 31300014 | Invalid database path. | + +**Example** + +```ts +import { UIAbility } from '@kit.AbilityKit'; +import { window } from '@kit.ArkUI'; +import { BusinessError } from '@kit.BasicServicesKit'; + +let store: graphStore.GraphStore | null = null; + +const STORE_CONFIG: graphStore.StoreConfig = { + name: "testGraphDb", + securityLevel: graphStore.SecurityLevel.S2 +}; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage){ + graphStore.deleteStore(this.context, STORE_CONFIG).then(()=>{ + store = null; + console.info('Delete GraphStore successfully.'); + }).catch((err: BusinessError) => { + console.error(`Delete GraphStore failed, code is ${err.code},message is ${err.message}`); + }) + } +} +``` + +## StoreConfig + +Represents the configuration of a graph store. + +**System capability**: SystemCapability.DistributedDataManager.DataIntelligence.Core + +| Name | Type | Mandatory| Description | +| ------------- | ------------- | ---- | --------------------------------------------------------- | +| name | string | Yes | Database file name, which is the unique identifier of the graph store.
**Constraints**
1. The file name cannot exceed 128 bytes.
2. The file name does not include the .db filename extension.| +| securityLevel | [SecurityLevel](#securitylevel) | Yes | Security level of the graph store.
**Constraints**
1. The security level cannot be downgraded. For example, you can change the security level from S2 to S3, but not from S3 to S2.
2. If the security level of a graph store needs to be changed, call [close](#close) to close the graph store instance, and then call [getStore](#graphstoregetstore) with **StoreConfig**.| +| encrypt | boolean | No | Whether to encrypt the graph store.
The value **true** means to encrypt the graph store; the value **false** means the opposite.
**Constraints**
1. It is not allowed to change **encrypt** from **true** to **false**.
2. If you need to change **encrypt** from **false** to **true**, call [close](#close) to close the graph store instance, and then call [getStore](#graphstoregetstore) with **StoreConfig**. | + +## SecurityLevel + +Enumerates the graph store security levels. Use the enum name rather than the enum value. + +**System capability**: SystemCapability.DistributedDataManager.DataIntelligence.Core + +| Name| Value | Description | +| ---- | ---- | ------------------------------------------------------------ | +| S1 | 1 | Low security level, where any data leakage may result in minor impact. An example would be a graph store containing non-sensitive system data such as wallpapers.| +| S2 | 2 | Medium security level, where any data leakage may result in moderate impact. An example would be a graph store containing audio and video data created by users or call logs.| +| S3 | 3 | High security level, where any data leakage may result in severe impact. An example would be a graph store containing user fitness, health, and location data.| +| S4 | 4 | Critical security level, where any data leakage may result in critical impact. An example would be a graph store containing authentication credentials and financial data.| + +## ValueType + +type ValueType = null | number | string + +Represents the allowed value types. The value type varies, depending on its usage. + +**System capability**: SystemCapability.DistributedDataManager.DataIntelligence.Core + +| Type | Description | +| ------- | -------------------- | +| null | The value is null.| +| number | The value can be any number.| +| string | The value can be any string.| + +## Vertex + +Represents information about a vertex. **Vertex** is used only as the type in the return value ([Result](#result)) and cannot be customized. You can use [read](#read) to obtain its value. + +**System capability**: SystemCapability.DistributedDataManager.DataIntelligence.Core + +| Name | Type | Mandatory | Description | +| ----------- | --------------------------- | --- | ------------ | +| vid | string | Yes | Identifier of the vertex. The value cannot be customized. It is a globally unique identifier allocated by the system when a vertex is written by using [GraphStore.write](#write-1) or [Transaction.write](#write). | +| labels | Array<string> | Yes | Labels of the vertex. The labels are specified in the GQL statement in [GraphStore.write](#write-1) or [Transaction.write](#write). Each label is case-insensitive, stored in uppercase format, and cannot exceed 128 bytes.| +| properties | Record<string, [ValueType](#valuetype)> | Yes | Properties of the vertex. The key has a maximum length of 128 bytes, with a limit of 1024 entries. It is specified in the GQL statement in [GraphStore.write](#write-1) or [Transaction.write](#write). If the value is a string, it cannot exceed 64 x 1024 bytes. | + +## Edge + +Represents information about an edge. **Edge** is used only as the type in the return value ([Result](#result)) and cannot be customized. You can use [read](#read) to obtain its value. + +**System capability**: SystemCapability.DistributedDataManager.DataIntelligence.Core + +| Name | Type | Mandatory | Description | +| ----------- | --------------------------- | --- | ------------ | +| eid | string | Yes | Identifier of the edge. The value cannot be customized. It is a globally unique identifier allocated by the system when an edge is written by [GraphStore.write](#write-1) or [Transaction.write](#write). | +| type | string | Yes | Type of the edge. It is specified in the GQL statement in [GraphStore.write](#write-1) or [Transaction.write](#write). It is case-insensitive, stored in uppercase format, and cannot exceed 128 bytes. | +| startVid | string | Yes | Identifier of the start vertex. The value cannot be customized. It is a globally unique identifier allocated by the system when a vertex is written by [GraphStore.write](#write-1) or [Transaction.write](#write). | +| endVid | string | Yes | Identifier of the end vertex. The value cannot be customized. It is a globally unique identifier allocated by the system when a vertex is written by [GraphStore.write](#write-1) or [Transaction.write](#write). | +| properties | Record<string, [ValueType](#valuetype)> | Yes | Properties of the edge. The key has a maximum length of 128 bytes, with a limit of 1024 entries. It is specified in the GQL statement in [GraphStore.write](#write-1) or [Transaction.write](#write). If the value is a string, it cannot exceed 64 x 1024 bytes. | + +## PathSegment + +Represents information about a path segment, including the edge along with the start and end vertexes. **PathSegment** is used only as the ([Path.segments](#path)) type and cannot be customized. + +**System capability**: SystemCapability.DistributedDataManager.DataIntelligence.Core + +| Name | Type | Mandatory | Description | +| ----------- | --------------------------- | --- | ------------ | +| start | [Vertex](#vertex) | Yes | Start vertex of the path segment.| +| end | [Vertex](#vertex) | Yes | End vertex of the path segment.| +| edge | [Edge](#edge) | Yes | Edge of the path segment.| + +## Path + +Represents information about a path. **Path** is used only as the type in the return value ([Result](#result)) and cannot be customized. You can use [read](#read) to obtain its value. + +**System capability**: SystemCapability.DistributedDataManager.DataIntelligence.Core + +| Name | Type | Mandatory | Description | +| ----------- | --------------------------- | --- | ------------ | +| start | [Vertex](#vertex) | Yes | Start vertex of the path.| +| end | [Vertex](#vertex) | Yes | End vertex of the path.| +| length | number | Yes | Number of segments in the path, which cannot exceed 1024.| +| segments | Array<[PathSegment](#pathsegment)> | Yes | Segments in the path.| + +## Result + +Represents the GQL statement execution result. + +**System capability**: SystemCapability.DistributedDataManager.DataIntelligence.Core + +| Name | Type | Mandatory | Description | +| ----------- | --------------------------- | --- | ------------ | +| records | Array<Record<string, Object>> | No | GQL statement execution result. It is left blank by default.
If there is an execution result, the object type varies depending on the GQL statement. It can be [Vertex](#vertex), [Edge](#edge), [Path](#path), or [ValueType](#valuetype).| + + +## Transaction + +Provides APIs for transaction management in a graph store. + +Operations on different transaction objects are isolated. The graph stores use database-level locks. + +If [commit](#commit) or [rollback](#rollback) is not called after a transaction is written using [write](#write), calling [read](#read) or [write](#write) for another transaction instance or calling [GraphStore.read](#read-1) or [GraphStore.write](#write-1) with the **GraphStore** instance will return error 31300003. + +If [commit](#commit) or [rollback](#rollback) is not called after [read](#read) is called for a transaction, calling [write](#write) for another transaction instance or calling [GraphStore.write](#write-1) with the **GraphStore** instance will return error 31300003. + +Before calling any **Transaction** API, you must create a transaction instance by using [createTransaction](#createtransaction). + +### read + +read(gql: string): Promise<Result> + +Reads data, which includes the data written by using [GraphStore.write](#write-1), data written by another transaction using [write](#write) and committed by using [commit](#commit), and data written by the current transaction using [write](#write). + +**System capability**: SystemCapability.DistributedDataManager.DataIntelligence.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | -------------------------- | +| gql | string | Yes | GQL statement to execute, which cannot exceed 1024 x 1024 bytes.| + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------------------------- | +| Promise<[Result](#result)> | Promise used to return the execution result if the operation is successful.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Graph Store Error Codes](errorcode-data-gdb.md). + +| **ID**| **Error Message** | +|-----------| ------------------------------------------------------------ | +| 202 | Permission verification failed, application which is not a system application uses system API. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 31300000 | Inner error. | +| 31300001 | Database corrupted. | +| 31300002 | Already closed. | +| 31300003 | The database is busy. | +| 31300004 | The database is out of memory. | +| 31300005 | The database is full. | +| 31300006 | A duplicate graph name, vertex or edge type, or vertex or edge property name exists. | +| 31300007 | The graph name, vertex or edge type, or vertex or edge property is not defined. | +| 31300008 | The graph name, vertex or edge type, or vertex or edge property name does not conform to constraints. | +| 31300009 | The GQL statement syntax error. | +| 31300010 | The GQL statement semantic error. | + +**Example** + +```ts +import { BusinessError } from '@kit.BasicServicesKit'; + +const QUERY_PATH_GQL = "MATCH path=(a:Person {name : \'name_1\'})-[]->{2, 2}(b:Person {name : \'name_3\'}) RETURN path;" +if(transaction != undefined) { + (transaction as graphStore.Transaction).read(QUERY_PATH_GQL).then((result: graphStore.Result) => { + console.info('Read successfully'); + result.records?.forEach((data) => { + for (let item of Object.entries(data)) { + const key = item[0]; + const value = item[1]; + const path = value as graphStore.Path; + console.info(`key : ${key}, path.length : ${path.length}`); + } + }); + }).catch((err: BusinessError) => { + console.error(`Read failed, code is ${err.code}, message is ${err.message}`); + }) +} +``` + +### write + +write(gql: string): Promise<Result> + +Writes data. You can use this API to add, delete, and modify data. Currently, it cannot be used to modify the table structure (types or properties of [Vertex](#vertex) and [Edge](#edge)), or create or delete graphs or indexes. This API cannot be used to execute transaction operation statements, including **START TRANSACTION**, **COMMIT**, and **ROLLBACK**. + +**System capability**: SystemCapability.DistributedDataManager.DataIntelligence.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | -------------------------- | +| gql | string | Yes | GQL statement to execute, which cannot exceed 1024 x 1024 bytes.| + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------------------------- | +| Promise<[Result](#result)> | Promise used to return the execution result if the operation is successful.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Graph Store Error Codes](errorcode-data-gdb.md). + +| **ID**| **Error Message** | +|-----------| ------------------------------------------------------------ | +| 202 | Permission verification failed, application which is not a system application uses system API. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 31300000 | Inner error. | +| 31300001 | Database corrupted. | +| 31300002 | Already closed. | +| 31300003 | The database is busy. | +| 31300004 | The database is out of memory. | +| 31300005 | The database is full. | +| 31300006 | A duplicate graph name, vertex or edge type, or vertex or edge property name exists. | +| 31300007 | The graph name, vertex or edge type, or vertex or edge property is not defined. | +| 31300008 | The graph name, vertex or edge type, or vertex or edge property name does not conform to constraints. | +| 31300009 | The GQL statement syntax error. | +| 31300010 | The GQL statement semantic error. | +| 31300012 | The number of graph names, vertex or edge types, or vertex or edge properties exceeds the limit. | +| 31300013 | A conflicting constraint already exists. | + +**Example** + +```ts +import { BusinessError } from '@kit.BasicServicesKit'; + +const INSERT_GQL = "INSERT (:Person {name: 'name_1', age: 11});" +if(transaction != undefined) { + (transaction as graphStore.Transaction).write(INSERT_GQL).then(() => { + console.info('Write successfully'); + }).catch((err: BusinessError) => { + console.error(`Write failed, code is ${err.code}, message is ${err.message}`); + }) +} +``` + +### commit + +commit(): Promise<void> + +Commits the GQL statements executed in this transaction. After the commit, the transaction will be no longer available. + +**System capability**: SystemCapability.DistributedDataManager.DataIntelligence.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Graph Store Error Codes](errorcode-data-gdb.md). + +| **ID**| **Error Message** | +|-----------| ------------------------------------------------------------ | +| 202 | Permission verification failed, application which is not a system application uses system API. | +| 31300000 | Inner error. | +| 31300001 | Database corrupted. | +| 31300002 | Already closed. | +| 31300003 | The database is busy. | +| 31300004 | The database is out of memory. | +| 31300005 | The database is full. | + +**Example** + +```ts +import { BusinessError } from '@kit.BasicServicesKit'; + +if(transaction != undefined) { + (transaction as graphStore.Transaction).commit().then(() => { + console.info(`Commit successfully`); + }).catch ((err: BusinessError) => { + console.error(`Commit failed, code is ${err.code}, message is ${err.message}`); + }) +} +``` + +### rollback + +rollback(): Promise<void> + +Rolls back the GQL statements executed in this transaction. After the rollback, the transaction will be no longer available. + +**System capability**: SystemCapability.DistributedDataManager.DataIntelligence.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Graph Store Error Codes](errorcode-data-gdb.md). + +| **ID**| **Error Message** | +|-----------| ------------------------------------------------------------ | +| 202 | Permission verification failed, application which is not a system application uses system API. | +| 31300000 | Inner error. | +| 31300001 | Database corrupted. | +| 31300002 | Already closed. | +| 31300003 | The database is busy. | +| 31300004 | The database is out of memory. | +| 31300005 | The database is full. | + +**Example** + +```ts +import { BusinessError } from '@kit.BasicServicesKit'; + +if(transaction != undefined) { + (transaction as graphStore.Transaction).rollback().then(() => { + console.info(`Rollback successfully`); + }).catch ((err: BusinessError) => { + console.error(`Rollback failed, code is ${err.code}, message is ${err.message}`); + }) +} +``` + + +## GraphStore + +Provides APIs for managing the data in a graph store. + +Before calling any **GraphStore** API, you must create a **GraphStore** instance by using [getStore](#graphstoregetstore). + +### read + +read(gql: string): Promise<Result> + +Reads data, which includes the data written by using [write](#write-1) and the data written by using [Transaction.write](#write) and committed by [Transaction.commit](#commit) in all transactions. + +**System capability**: SystemCapability.DistributedDataManager.DataIntelligence.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | -------------------------- | +| gql | string | Yes | GQL statement to execute, which cannot exceed 1024 x 1024 bytes.| + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------------------------- | +| Promise<[Result](#result)> | Promise used to return the execution result if the operation is successful.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Graph Store Error Codes](errorcode-data-gdb.md). + +| **ID**| **Error Message** | +|-----------| ------------------------------------------------------------ | +| 202 | Permission verification failed, application which is not a system application uses system API. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 31300000 | Inner error. | +| 31300001 | Database corrupted. | +| 31300002 | Already closed. | +| 31300003 | The database is busy. | +| 31300004 | The database is out of memory. | +| 31300005 | The database is full. | +| 31300006 | A duplicate graph name, vertex or edge type, or vertex or edge property name exists. | +| 31300007 | The graph name, vertex or edge type, or vertex or edge property is not defined. | +| 31300008 | The graph name, vertex or edge type, or vertex or edge property name does not conform to constraints. | +| 31300009 | The GQL statement syntax error. | +| 31300010 | The GQL statement semantic error. | + +**Example** + +```ts +import { BusinessError } from '@kit.BasicServicesKit'; + +const QUERY_PATH_GQL = "MATCH path=(a:Person {name : \'name_1\'})-[]->{2, 2}(b:Person {name : \'name_3\'}) RETURN path;" +if(store != null) { + (store as graphStore.GraphStore).read(QUERY_PATH_GQL).then((result: graphStore.Result) => { + console.info('Read successfully'); + result.records?.forEach((data) => { + for (let item of Object.entries(data)) { + const key = item[0]; + const value = item[1]; + const path = value as graphStore.Path; + console.info(`key : ${key}, path.length : ${path.length}`); + } + }); + }).catch((err: BusinessError) => { + console.error(`Read failed, code is ${err.code}, message is ${err.message}`); + }) +} +``` + +### write + +write(gql: string): Promise<Result> + +Writes data. You can use this API to create or delete a graph, and add, delete, or modify data. Currently, the table structure (types or properties of [Vertex](#vertex) and [Edge](#edge)) cannot be modified. This API cannot be used to execute transaction operation statements, including **START TRANSACTION**, **COMMIT**, and **ROLLBACK**. + +**System capability**: SystemCapability.DistributedDataManager.DataIntelligence.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | -------------------------- | +| gql | string | Yes | GQL statement to execute, which cannot exceed 1024 x 1024 bytes.| + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------------------------- | +| Promise<[Result](#result)> | Promise used to return the execution result if the operation is successful.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Graph Store Error Codes](errorcode-data-gdb.md). + +| **ID**| **Error Message** | +|-----------| ------------------------------------------------------------ | +| 202 | Permission verification failed, application which is not a system application uses system API. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 31300000 | Inner error. | +| 31300001 | Database corrupted. | +| 31300002 | Already closed. | +| 31300003 | The database is busy. | +| 31300004 | The database is out of memory. | +| 31300005 | The database is full. | +| 31300006 | A duplicate graph name, vertex or edge type, or vertex or edge property name exists. | +| 31300007 | The graph name, vertex or edge type, or vertex or edge property is not defined. | +| 31300008 | The graph name, vertex or edge type, or vertex or edge property name does not conform to constraints. | +| 31300009 | The GQL statement syntax error. | +| 31300010 | The GQL statement semantic error. | +| 31300012 | The number of graph names, vertex or edge types, or vertex or edge properties exceeds the limit. | +| 31300013 | A conflicting constraint already exists. | + +**Example** + +```ts +import { BusinessError } from '@kit.BasicServicesKit'; + +const CREATE_GRAPH_GQL = "CREATE GRAPH test { (person:Person {name STRING, age INT}),(person)-[:Friend {year INT}]->(person) };" +if(store != null) { + (store as graphStore.GraphStore).write(CREATE_GRAPH_GQL).then(() => { + console.info('Write successfully'); + }).catch((err: BusinessError) => { + console.error(`Write failed, code is ${err.code}, message is ${err.message}`); + }) +} +``` + +### createTransaction + +createTransaction(): Promise<Transaction> + +Creates a transaction instance. Currently, a maximum of four transaction instances can be created at a time in a graph store. + +**System capability**: SystemCapability.DistributedDataManager.DataIntelligence.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<[Transaction](#transaction)> | Promise used to return the created transaction instance.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Graph Store Error Codes](errorcode-data-gdb.md). + +| **ID**| **Error Message** | +|-----------| ------------------------------------------------------------ | +| 202 | Permission verification failed, application which is not a system application uses system API. | +| 31300000 | Inner error. | +| 31300001 | Database corrupted. | +| 31300002 | Already closed. | +| 31300003 | The database is busy. | +| 31300004 | The database is out of memory. | +| 31300005 | The database is full. | + +**Example** + +```ts +import { BusinessError } from '@kit.BasicServicesKit'; + +let transaction: graphStore.Transaction | undefined = undefined; + +if(store != undefined) { + (store as graphStore.GraphStore).createTransaction().then((trans: graphStore.Transaction) => { + transaction = trans; + console.info('createTransaction successfully'); + }).catch((err: BusinessError) => { + console.error(`createTransaction failed, code is ${err.code}, message is ${err.message}`); + }) +} +``` + +### close + +close(): Promise<void> + +Closes this graph store. After this API is called, uncommitted transactions will be rolled back. + +**System capability**: SystemCapability.DistributedDataManager.DataIntelligence.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Graph Store Error Codes](errorcode-data-gdb.md). + +| **ID**| **Error Message** | +|-----------| ------------------------------------------------------------ | +| 202 | Permission verification failed, application which is not a system application uses system API. | +| 31300000 | Inner error. | + +**Example** + +```ts +import { BusinessError } from '@kit.BasicServicesKit'; + +if(store != null) { + (store as graphStore.GraphStore).close().then(() => { + console.info(`Close successfully`); + }).catch ((err: BusinessError) => { + console.error(`Close failed, code is ${err.code}, message is ${err.message}`); + }) +} +``` diff --git a/en/application-dev/reference/apis-arkdata/js-apis-data-intelligence.md b/en/application-dev/reference/apis-arkdata/js-apis-data-intelligence.md new file mode 100644 index 0000000000000000000000000000000000000000..286a0b77bca453daed0566f96a2b989ac78647b3 --- /dev/null +++ b/en/application-dev/reference/apis-arkdata/js-apis-data-intelligence.md @@ -0,0 +1,531 @@ +# @ohos.data.intelligence (ArkData Intelligence Platform) + +The ArkData Intelligence Platform (AIP) provides on-device data intelligence capabilities, enabling AI-powered data processing data on devices. To underpin AI-powered processing on devices, the AIP aims to build the following capabilities: +- Multimodal embedding model: leverages embedding models to generate vector representations for multimodal data, mapping text, images, and other data into a unified vector space for semantic-based multimodal knowledge retrieval. +- Multimodal data storage: supports on-device storage for vectors, inverted indexes, and other multimodal data, eliminating the need to send raw data to the server for processing. This reduces the risk of data leakage. +- Knowledge retrieval: enables semantic retrieval of user knowledge based on capabilities such as semantic indexing, knowledge graphs, recall, and re-ranking. +- Knowledge generation and collation: implements efficient data organization and knowledge generation based on user data such as user documents, messages, emails, photos, videos, calendar events, and screen context, enabling the transformation of data into knowledge. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 15. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> Considering the significant computing workload and resources of data vectorization processing, the APIs are only available to 2-in-1 device applications. + + +## Modules to Import + +```ts +import { intelligence } from '@kit.ArkData'; +``` + +## intelligence.getTextEmbeddingModel + +getTextEmbeddingModel(config: ModelConfig): Promise<TextEmbedding> + +Obtains a text embedding model. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.DataIntelligence.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | --------------------------------------- | ---- | :--------------------------------- | +| config | [ModelConfig](#modelconfig) | Yes | Configuration of the embedded model to obtain.| + +**Return value** + +| Type | Description | +| ----------------------------- | ------------------------------------ | +| Promise<[TextEmbedding](#textembedding)> | Promise used to return the text embedding model object.| + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [AIP Error Codes](errorcode-intelligence.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 801 | Capability not supported. | +| 31300000 | Inner error. | | + +**Example** + +```ts +import { BusinessError } from '@kit.BasicServicesKit'; + +let textConfig:intelligence.ModelConfig = { + version:intelligence.ModelVersion.BASIC_MODEL, + isNpuAvailable:false, + cachePath:"/data" +} +let textEmbedding:intelligence.TextEmbedding; + +intelligence.getTextEmbeddingModel(textConfig) + .then((data:intelligence.TextEmbedding) => { + console.info("Succeeded in getting TextModel"); + textEmbedding = data; + }) + .catch((err:BusinessError) => { + console.error("Failed to get TextModel and code is " + err.code); + }) +``` + +## intelligence.getImageEmbeddingModel + +getImageEmbeddingModel(config: ModelConfig): Promise<ImageEmbedding> + +Obtains an image embedding model. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.DataIntelligence.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | --------------------------------------- | ---- | :--------------------------------- | +| config | [ModelConfig](#modelconfig) | Yes | Configuration of the embedded model to obtain.| + +**Return value** + +| Type | Description | +| ----------------------------- | ------------------------------------ | +| Promise<[ImageEmbedding](#imageembedding)> | Promise used to return the image embedding model object.| + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [AIP Error Codes](errorcode-intelligence.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 801 | Capability not supported. | +| 31300000 | Inner error. | | + +**Example** + +```ts +import { BusinessError } from '@kit.BasicServicesKit'; + +let imageConfig:intelligence.ModelConfig = { + version:intelligence.ModelVersion.BASIC_MODEL, + isNpuAvailable:false, + cachePath:"/data" +} +let imageEmbedding:intelligence.ImageEmbedding; + +intelligence.getImageEmbeddingModel(imageConfig) + .then((data:intelligence.ImageEmbedding) => { + console.info("Succeeded in getting ImageModel"); + imageEmbedding = data; + }) + .catch((err:BusinessError) => { + console.error("Failed to get ImageModel and code is " + err.code); + }) +``` + +## intelligence.splitText + +splitText(text: string, config: SplitConfig): Promise<Array<string>> + +Splits text. + +**System capability**: SystemCapability.DistributedDataManager.DataIntelligence.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | --------------------------------------- | ---- | :--------------------------------- | +| text | string | Yes | Text to split, which can be any value.| +| config | [SplitConfig](#splitconfig) | Yes | Configuration for splitting the text.| + +**Return value** + +| Type | Description | +| ----------------------------- | ------------------------------------ | +| Promise<Array<string>> | Promise used to return the blocks of the text.| + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [AIP Error Codes](errorcode-intelligence.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 801 | Capability not supported. | +| 31300000 | Inner error. | | + +**Example** + +```ts +import { BusinessError } from '@kit.BasicServicesKit'; + +let splitConfig:intelligence.SplitConfig = { + size:10, + overlapRatio:0.1 +} +let splitText = 'text'; + +intelligence.splitText(splitText, splitConfig) + .then((data:Array) => { + console.info("Succeeded in splitting Text"); + }) + .catch((err:BusinessError) => { + console.error("Failed to split Text and code is " + err.code); + }) +``` + +## ModelConfig + +Represents the configuration an embedded model. + +**System capability**: SystemCapability.DistributedDataManager.DataIntelligence.Core + +| Name | Type | Mandatory| Description | +| ---------- | --------------------- | ---- | ------------------------------------------------------------ | +| version | [ModelVersion](#modelversion) | Yes |Version of the model.| +| isNpuAvailable | boolean | Yes | Whether to use the NPU to accelerate the vectorization process. The value **true** means to use the NPU, and the value **false** means the opposite. If this parameter is set to **true** but the device does not support NPUs, loading an embedding model will trigger error 31300000.| +| cachePath | string | No | Local directory for model caching if the NPU is used. The value is in the /xxx/xxx/xxx format, for example, **/data**. The path cannot exceed 512 characters.
Default value: **""**| + +## ModelVersion + +Enumerates the model versions. + +**System capability**: SystemCapability.DistributedDataManager.DataIntelligence.Core + +| Name | Value | Description | +| ---------- | ---------- | ---------------------- | +| BASIC_MODEL | 0 | Basic embedding model version. | + +## Image + +type Image = string + +Represents the URI of an image, which is of the string type. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Type | Description | +| ---------------------------- | --------------------- | +| string | Image URI, which cannot exceed 512 characters.| + +## SplitConfig + +Represents the configuration for text splitting. + +**System capability**: SystemCapability.DistributedDataManager.DataIntelligence.Core + +| Name | Type | Mandatory| Description | +| ---------- | --------------------- | ---- | ------------------------------------------------------------ | +| size | number | Yes |Maximum size of a block. The value is a non-negative integer.| +| overlapRatio | number | Yes | Overlap ratio between adjacent blocks.
Value range: [0,1]
The value **0** indicates the lowest overlap ratio, and **1** indicates the highest overlap ratio.| + + +## TextEmbedding + +Provides APIs for manipulating text embedding models. + +Before calling any of the following APIs, you must obtain a **TextEmbedding** instance by using [intelligence.getTextEmbeddingModel](#intelligencegettextembeddingmodel). + +**System capability**: SystemCapability.DistributedDataManager.DataIntelligence.Core + +### loadModel + +loadModel(): Promise<void> + +Loads this embedding model. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.DataIntelligence.Core + +**Return value** + +| Type | Description | +| ----------------------------- | ------------------------------------ | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [AIP Error Codes](errorcode-intelligence.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- | +| 801 | Capability not supported. | +| 31300000 | Inner error. | | + +**Example** + +```ts +import { BusinessError } from '@kit.BasicServicesKit'; + +textEmbedding.loadModel() + .then(() => { + console.info("Succeeded in loading Model"); + }) + .catch((err:BusinessError) => { + console.error("Failed to load Model and code is " + err.code); + }) +``` + +### releaseModel + +releaseModel(): Promise<void> + +Releases this embedding model. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.DataIntelligence.Core + +**Return value** + +| Type | Description | +| ----------------------------- | ------------------------------------ | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [AIP Error Codes](errorcode-intelligence.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- | +| 801 | Capability not supported. | +| 31300000 | Inner error. | | + +**Example** + +```ts +import { BusinessError } from '@kit.BasicServicesKit'; + +textEmbedding.releaseModel() + .then(() => { + console.info("Succeeded in releasing Model"); + }) + .catch((err:BusinessError) => { + console.error("Failed to release Model and code is " + err.code); + }) +``` + +### getEmbedding + +getEmbedding(text: string): Promise<Array<number>> + +Obtains the embedding vector of the given text. + +Before calling this API, ensure that an embedding model is successfully loaded by using [loadModel](#loadmodel). + +**System capability**: SystemCapability.DistributedDataManager.DataIntelligence.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | --------------------------------------- | ---- | :--------------------------------- | +| text | string | Yes | Text for the embedding model. It cannot exceed 512 characters.| + +**Return value** + +| Type | Description | +| ----------------------------- | ------------------------------------ | +| Promise<Array<number>> | Promise used to return the vectorization result.| + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [AIP Error Codes](errorcode-intelligence.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 801 | Capability not supported. | +| 31300000 | Inner error. | | + +**Example** + +```ts +import { BusinessError } from '@kit.BasicServicesKit'; + + +textEmbedding.loadModel(); +let text = 'text'; +textEmbedding.getEmbedding(text) + .then((data:Array) => { + console.info("Succeeded in getting Embedding"); + }) + .catch((err:BusinessError) => { + console.error("Failed to get Embedding and code is " + err.code); + }) +``` + +### getEmbedding + +getEmbedding(batchTexts: Array<string>): Promise<Array<Array<number>>> + +Obtains the embedding vector of a given batch of texts. + +Before calling this API, ensure that an embedding model is successfully loaded by using [loadModel](#loadmodel). + +**System capability**: SystemCapability.DistributedDataManager.DataIntelligence.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | --------------------------------------- | ---- | :--------------------------------- | +| batchTexts | Array<string> | Yes | Batch of texts, each of which cannot exceed 512 characters.| + +**Return value** + +| Type | Description | +| ----------------------------- | ------------------------------------ | +| Promise<Array<Array<number>>> | Promise used to return the vectorization result.| + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [AIP Error Codes](errorcode-intelligence.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 801 | Capability not supported. | +| 31300000 | Inner error. | | + +**Example** + +```ts +import { BusinessError } from '@kit.BasicServicesKit'; + + +textEmbedding.loadModel(); +let batchTexts = ['text1','text2']; +textEmbedding.getEmbedding(batchTexts) + .then((data:Array>) => { + console.info("Succeeded in getting Embedding"); + }) + .catch((err:BusinessError) => { + console.error("Failed to get Embedding and code is " + err.code); + }) +``` + +## ImageEmbedding + +Provides APIs for manipulating image embedding models. + +Before calling any of the following APIs, you must obtain a **ImageEmbedding** instance by using [intelligence.getImageEmbeddingModel](#intelligencegetimageembeddingmodel). + +**System capability**: SystemCapability.DistributedDataManager.DataIntelligence.Core + +### loadModel + +loadModel(): Promise<void> + +Loads this embedding model. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.DataIntelligence.Core + +**Return value** + +| Type | Description | +| ----------------------------- | ------------------------------------ | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [AIP Error Codes](errorcode-intelligence.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- | +| 801 | Capability not supported. | +| 31300000 | Inner error. | | + +**Example** + +```ts +import { BusinessError } from '@kit.BasicServicesKit'; + +imageEmbedding.loadModel() + .then(() => { + console.info("Succeeded in loading Model"); + }) + .catch((err:BusinessError) => { + console.error("Failed to load Model and code is " + err.code); + }) +``` + +### releaseModel + +releaseModel(): Promise<void> + +Releases this embedding model. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.DataIntelligence.Core + +**Return value** + +| Type | Description | +| ----------------------------- | ------------------------------------ | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [AIP Error Codes](errorcode-intelligence.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- | +| 801 | Capability not supported. | +| 31300000 | Inner error. | | + +**Example** + +```ts +import { BusinessError } from '@kit.BasicServicesKit'; + +imageEmbedding.releaseModel() + .then(() => { + console.info("Succeeded in releasing Model"); + }) + .catch((err:BusinessError) => { + console.error("Failed to release Model and code is " + err.code); + }) +``` + +### getEmbedding + +getEmbedding(image: Image): Promise<Array<number>> + +Obtains the embedding vector of the given image. + +Before calling this API, ensure that an embedding model is successfully loaded by using [loadModel](#loadmodel). + +**System capability**: SystemCapability.DistributedDataManager.DataIntelligence.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | --------------------------------------- | ---- | :--------------------------------- | +| image | [Image](#image) | Yes | URI of the target image.| + +**Return value** + +| Type | Description | +| ----------------------------- | ------------------------------------ | +| Promise<Array<number>> | Promise used to return the vectorization result.| + +**Error codes** + +For details about the error codes, see [Common Error Codes](../errorcode-universal.md) and [AIP Error Codes](errorcode-intelligence.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 801 | Capability not supported. | +| 31300000 | Inner error. | | + +**Example** + +```ts +import { BusinessError } from '@kit.BasicServicesKit'; + +imageEmbedding.loadModel(); +let image = 'file:///data/storage/el2/base/haps/entry/files/xxx.jpg'; +imageEmbedding.getEmbedding(image) + .then((data:Array) => { + console.info("Succeeded in getting Embedding"); + }) + .catch((err:BusinessError) => { + console.error("Failed to get Embedding and code is " + err.code); + }) +``` diff --git a/en/application-dev/reference/apis-arkdata/js-apis-data-preferences.md b/en/application-dev/reference/apis-arkdata/js-apis-data-preferences.md index 1a8fc216c2f70415a30464218b357a2ec7235c43..7ea3b61635d9debaeab2ef4bcbf4826540def685 100644 --- a/en/application-dev/reference/apis-arkdata/js-apis-data-preferences.md +++ b/en/application-dev/reference/apis-arkdata/js-apis-data-preferences.md @@ -4,7 +4,7 @@ The **Preferences** module provides APIs for processing data in the form of key- The key is of the string type, and the value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values. -The persistent files of user preferences are stored in the [preferencesDir](../../../application-dev/application-models/application-context-stage.md#obtaining-application-file-path) directory. Before creating a preferences object, ensure that the **preferencesDir** path can be read and written. The [encryption level](../../../application-dev/reference/apis-ability-kit/js-apis-app-ability-contextConstant.md#areamode) of the persistent file path affects the read and write permissions on the file. For details, see [Application File Directory and Application File Path](../../../application-dev/file-management/app-sandbox-directory.md#application-file-directory-and-application-file-path). +The user preference persistent files are stored in the [preferencesDir](../../application-models/application-context-stage.md#obtaining-application-file-path) directory. Before creating a preferences object, ensure that the **preferencesDir** directory is readable and writeable. The [encryption level](../apis-ability-kit/js-apis-app-ability-contextConstant.md#areamode) of the persistent file directory determines the access to the files. For details, see [Application File Directory and Application File Path](../../file-management/app-sandbox-directory.md#application-file-directory-and-application-file-path). > **NOTE** > @@ -26,7 +26,7 @@ import { preferences } from '@kit.ArkData'; | Name | Type| Readable| Writable| Description | | ---------------- | -------- | ---- | ---- | --------------------------------------- | -| MAX_KEY_LENGTH | number | Yes | No | Maximum length of a key, which is 1024 bytes. | +| MAX_KEY_LENGTH | number | Yes | No | Maximum key length, which is 1024 bytes. | | MAX_VALUE_LENGTH | number | Yes | No | Maximum value length, which is 16 MB.| @@ -54,7 +54,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | **Example** @@ -131,7 +131,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | **Example** @@ -202,7 +202,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 801 | Capability not supported. | | 15500000 | Inner error. | | 15501001 | The operations is supported in stage mode only. | @@ -286,7 +286,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 801 | Capability not supported. | | 15500000 | Inner error. | | 15501001 | The operations is supported in stage mode only. | @@ -367,7 +367,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 801 | Capability not supported. | | 15500000 | Inner error. | | 15501001 | The operations is supported in stage mode only. | @@ -433,7 +433,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | | 15500010 | Failed to delete the user preferences persistence file. | @@ -511,7 +511,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | | 15500010 | Failed to delete the user preferences persistence file. | @@ -582,7 +582,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 801 | Capability not supported. | | 15500000 | Inner error. | | 15500010 | Failed to delete the user preferences persistence file. | @@ -666,7 +666,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 801 | Capability not supported. | | 15500000 | Inner error. | | 15500010 | Failed to delete the user preferences persistence file. | @@ -743,7 +743,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | **Example** @@ -819,7 +819,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | **Example** @@ -887,7 +887,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | **Example** @@ -943,7 +943,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 801 | Capability not supported. | | 15500000 | Inner error. | | 15501001 | The operations is supported in stage mode only. | @@ -1024,7 +1024,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 801 | Capability not supported. | | 15500000 | Inner error. | | 15501001 | The operations is supported in stage mode only. | @@ -1097,7 +1097,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 801 | Capability not supported. | | 15500000 | Inner error. | | 15501001 | The operations is supported in stage mode only. | @@ -1130,17 +1130,17 @@ class EntryAbility extends UIAbility { } ``` -## StorageType16+ +## StorageType18+ Enumerates the storage types of preferences. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core | Name| Value | Description| | ---- | ---- | ---- | | XML | 0 | XML, which is the default storage mode of preferences.
In this mode, data is stored in XML format. Data operations are performed in the memory. To persist data, call **flush()**. | -| CLKV | 1 |CLKV.
Data is stored in CLKV database mode. Data operations are flushed on a real-time basis without calling **flush()**. | +| GSKV | 1 |GSKV.
Data is stored in GSKV mode. Data operations are flushed on a real-time basis without calling **flush()**. | > **NOTE** @@ -1149,14 +1149,14 @@ Enumerates the storage types of preferences. > - Data cannot be directly migrated between the **Preferences** instances that use different storage types. To migrate data between them, you need to read the data to be migrated and then write the data. > - If you need to change the storage directory of preferences, you cannot move or overwrite files. Instead, you need to read the data and then write the data. -## preferences.isStorageTypeSupported16+ +## preferences.isStorageTypeSupported18+ isStorageTypeSupported(type: StorageType): boolean Checks whether the specified storage type is supported. This API returns the result synchronously. If the storage type is supported, **true** is returned. Otherwise, **false** is returned. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core @@ -1164,7 +1164,7 @@ If the storage type is supported, **true** is returned. Otherwise, **false** is | Name | Type | Mandatory| Description | | ------- | --------------------- | ---- | ------------------------------------------------------------ | -| type | [StorageType](#storagetype16) | Yes | Storage type to check.| +| type | [StorageType](#storagetype18) | Yes | Storage type to check.| **Return value** @@ -1185,11 +1185,11 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts let xmlType = preferences.StorageType.XML; -let clkvType = preferences.StorageType.CLKV; +let gskvType = preferences.StorageType.GSKV; let isXmlSupported = preferences.isStorageTypeSupported(xmlType); -let isClkvSupported = preferences.isStorageTypeSupported(clkvType); +let isGskvSupported = preferences.isStorageTypeSupported(gskvType); console.info("Is xml supported in current platform: " + isXmlSupported); -console.info("Is clkv supported in current platform: " + isClkvSupported); +console.info("Is gskv supported in current platform: " + isGskvSupported); ``` ## Options10+ @@ -1200,9 +1200,9 @@ Represents the configuration of a **Preferences** instance. | Name | Type | Mandatory| Description | | ----------- | ------ | ---- | ------------------------------------------------------------ | -| name | string | Yes | Name of the **Preferences** instance.
**Atomic service API**: This API can be used in atomic services since API version 11.
| +| name | string | Yes | Name of the **Preferences** instance. It must be longer than 0 bytes and less than or equal to 255 bytes, and cannot contain or end with slashes (/).
**Atomic service API**: This API can be used in atomic services since API version 11.
| | dataGroupId | string\|null\|undefined | No | Application group ID. Currently, this parameter is not supported.
This parameter is optional. A **Preferences** instance will be created in the sandbox path corresponding to the specified **dataGroupId**. If this parameter is not specified, the **Preferences** instance is created in the sandbox directory of the application.
**Model restriction**: This attribute can be used only in the stage model.
**Atomic service API**: This API can be used in atomic services since API version 11.
| -| storageType16+ | [StorageType](#storagetype16)\|null\|undefined | No | Storage mode to be used by the **Preferences** instance. This parameter is optional. If this parameter is left blank, the XML storage type is used by default. After the storage type is set for a **Preferences** instance, it cannot be changed.
**Atomic service API**: This API can be used in atomic services since API version 16.
| +| storageType18+ | [StorageType](#storagetype18)\|null\|undefined | No | Storage mode to be used by the **Preferences** instance. This parameter is optional. If this parameter is left blank, the XML storage type is used by default. After the storage type is set for a **Preferences** instance, it cannot be changed.
**Atomic service API**: This API can be used in atomic services since API version 18.| ## Preferences @@ -1236,7 +1236,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | **Example** @@ -1282,7 +1282,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | **Example** @@ -1327,7 +1327,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | **Example** @@ -1501,7 +1501,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | **Example** @@ -1554,7 +1554,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | **Example** @@ -1600,7 +1600,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | **Example** @@ -1633,7 +1633,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | **Example** @@ -1683,7 +1683,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | **Example** @@ -1732,7 +1732,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | **Example** @@ -1770,7 +1770,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | **Example** @@ -1816,7 +1816,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | **Example** @@ -1855,7 +1855,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | **Example** @@ -1873,7 +1873,7 @@ Flushes the data in this **Preferences** instance to the persistent file. This A > **NOTE** > - > If no data is modified or the modified data is the same as the cached data, the persistence file will not be updated. + > If no data is modified or the modified data is the same as the cached data, the persistent file will not be updated. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -1917,7 +1917,7 @@ Flushes the data in this **Preferences** instance to the persistent file. This A > **NOTE** > - > If no data is modified or the modified data is the same as the cached data, the persistence file will not be updated. + > If no data is modified or the modified data is the same as the cached data, the persistent file will not be updated. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -1958,7 +1958,7 @@ Flushes the data in the cached **Preferences** instance to the persistent file. > **NOTE** > - > If no data is modified or the modified data is the same as the cached data, the persistence file will not be updated. + > If no data is modified or the modified data is the same as the cached data, the persistent file will not be updated. **Atomic service API**: This API can be used in atomic services since API version 14. @@ -2100,7 +2100,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | **Example** @@ -2153,7 +2153,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | -------------------------------------- | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | | 15500019 | Failed to obtain the subscription service. | @@ -2204,7 +2204,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | **Example** @@ -2254,7 +2254,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | **Example** @@ -2302,7 +2302,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | **Example** @@ -2348,7 +2348,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | **Example** diff --git a/en/application-dev/reference/apis-arkdata/js-apis-data-rdb.md b/en/application-dev/reference/apis-arkdata/js-apis-data-rdb.md index 128c7029842b6c1a717a9e4d4dfed8ca0cfadaad..27f9696f717267e02e0d7f4e4a66ca9448cdd4fa 100644 --- a/en/application-dev/reference/apis-arkdata/js-apis-data-rdb.md +++ b/en/application-dev/reference/apis-arkdata/js-apis-data-rdb.md @@ -4,8 +4,8 @@ The relational database (RDB) manages data based on relational models. With the This module provides the following RDB-related functions: -- [RdbPredicates](#rdbpredicates): provides predicates indicating the nature, feature, or relationship of a data entity in an RDB store. It is used to define the operation conditions for an RDB store. -- [RdbStore](#rdbstore): provides APIs for managing an RDB store. +- [RdbPredicates](#rdbpredicates): provides APIs for creating predicates. The predicates represent the properties, characteristics, or relationships between data entities in an RDB store and are used to define data operation conditions. +- [RdbStore](#rdbstore): provides APIs for managing data in an RDB store. > **NOTE** > @@ -29,9 +29,9 @@ Obtains an RDB store. This API uses an asynchronous callback to return the resul **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ | -| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md). | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).| | config | [StoreConfig](#storeconfig) | Yes | Configuration of the RDB store. | | version | number | Yes | RDB store version.
Currently, automatic RDB upgrades and downgrades performed based on **version** is not supported. | | callback | AsyncCallback<[RdbStore](#rdbstore)> | Yes | Callback used to return the RDB store obtained. | @@ -87,9 +87,9 @@ Obtains an RDB store. This API uses a promise to return the result. You can set **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ------- | --------------------------- | ---- | ------------------------------------------------------------ | -| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md). | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).| | config | [StoreConfig](#storeconfig) | Yes | Configuration of the RDB store. | | version | number | Yes | RDB store version.
Currently, automatic RDB upgrades and downgrades performed based on **version** is not supported. | @@ -97,7 +97,7 @@ Obtains an RDB store. This API uses a promise to return the result. You can set | Type | Description | | ------------------------------------ | ------------------------------- | -| Promise<[RdbStore](#rdbstore)> | Promise used to return the **RdbStore** object. | +| Promise<[RdbStore](#rdbstore)> | Promise used to return the **RdbStore** object.| **Example** @@ -148,9 +148,9 @@ Deletes an RDB store. This API uses an asynchronous callback to return the resul **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------------------------------------ | -| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md). | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).| | name | string | Yes | Name of the RDB store to delete. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. | @@ -202,16 +202,16 @@ Deletes an RDB store. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ------- | ------- | ---- | ------------------------------------------------------------ | -| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md). | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).| | name | string | Yes | Name of the RDB store to delete. | **Return value** | Type | Description | | ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value. | +| Promise<void> | Promise that returns no value.| **Example** @@ -262,7 +262,7 @@ Defines the data types allowed. | ------- | -------------------- | | number | Number. | | string | String. | -| boolean | Boolean. | +| boolean | Boolean.| ## ValuesBucket @@ -273,7 +273,7 @@ Defines the types of the key and value in a KV pair. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -| Key Type | Value Type | +| Key Type| Value Type | | ------ | ----------------------------------------------------------- | | string | [ValueType](#valuetype)\| Uint8Array \| null | @@ -285,7 +285,7 @@ Defines the database sync mode. | Name | Value | Description | | -------------- | ---- | ---------------------------------- | -| SYNC_MODE_PUSH | 0 | Data is pushed from a local device to a remote device. | +| SYNC_MODE_PUSH | 0 | Data is pushed from a local device to a remote device.| | SYNC_MODE_PULL | 1 | Data is pulled from a remote device to a local device. | ## SubscribeType8+ @@ -298,7 +298,7 @@ Defines the subscription type. | Name | Value | Description | | --------------------- | ---- | ------------------ | -| SUBSCRIBE_TYPE_REMOTE | 0 | Subscribe to remote data changes. | +| SUBSCRIBE_TYPE_REMOTE | 0 | Subscribe to remote data changes.| ## StoreConfig @@ -306,9 +306,9 @@ Defines the RDB store configuration. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| name | string | Yes | Database file name. | +| name | string | Yes| Database file name.| ## RdbPredicates @@ -324,9 +324,9 @@ A constructor used to create an **RdbPredicates** object. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| name | string | Yes | Database table name. | +| name | string | Yes| Database table name.| **Example** @@ -338,25 +338,25 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") inDevices(devices: Array<string>): RdbPredicates -Sets an **RdbPredicates** to specify the remote devices to connect on the network during distributed database sync. +Creates an **RdbPredicates** object to specify the remote devices to connect on the network during distributed database sync. -> **NOTE** +> **NOTE**
> -> The value of **devices** can be obtained by [deviceManager.getTrustedDeviceListSync](../apis-distributedservice-kit/js-apis-device-manager-sys.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. +> The value of **devices** can be obtained by using [deviceManager.getTrustedDeviceListSync](../apis-distributedservice-kit/js-apis-device-manager-sys.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| devices | Array<string> | Yes | IDs of the remote devices in the same network. | +| devices | Array<string> | Yes| IDs of the remote devices in the same network.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created. | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** @@ -390,15 +390,15 @@ predicates.inDevices(deviceIds); inAllDevices(): RdbPredicates -Sets an **RdbPredicates** to specify all remote devices on the network to connect during distributed database sync. +Creates an **RdbPredicates** object to specify all remote devices on the network to connect during distributed database sync. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created. | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** @@ -411,22 +411,22 @@ predicates.inAllDevices() equalTo(field: string, value: ValueType): RdbPredicates -Sets an **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value. +Creates an **RdbPredicates** object to search for the records in the specified column that are equal to the given value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the database table. | -| value | [ValueType](#valuetype) | Yes | Value to match the **RdbPredicates**. | +| field | string | Yes| Column name in the database table.| +| value | [ValueType](#valuetype) | Yes| Value to match.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created. | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** @@ -440,22 +440,22 @@ predicates.equalTo("NAME", "lisi") notEqualTo(field: string, value: ValueType): RdbPredicates -Sets an **RdbPredicates** to match the field with data type **ValueType** and value not equal to the specified value. +Creates an **RdbPredicates** object to search for the records in the specified column that are not equal to the given value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the database table. | -| value | [ValueType](#valuetype) | Yes | Value to match the **RdbPredicates**. | +| field | string | Yes| Column name in the database table.| +| value | [ValueType](#valuetype) | Yes| Value to match.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created. | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** @@ -469,15 +469,15 @@ predicates.notEqualTo("NAME", "lisi") beginWrap(): RdbPredicates -Adds a left parenthesis to the **RdbPredicates**. +Creates an **RdbPredicates** object to add a left parenthesis. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** with a left parenthesis. | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** @@ -495,15 +495,15 @@ predicates.equalTo("NAME", "lisi") endWrap(): RdbPredicates -Adds a right parenthesis to the **RdbPredicates**. +Creates an **RdbPredicates** object to add a right parenthesis. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** with a right parenthesis. | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** created.| **Example** @@ -521,15 +521,15 @@ predicates.equalTo("NAME", "lisi") or(): RdbPredicates -Adds the OR condition to the **RdbPredicates**. +Creates an **RdbPredicates** object to add the OR condition. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** with the OR condition. | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** created.| **Example** @@ -544,15 +544,15 @@ predicates.equalTo("NAME", "Lisa") and(): RdbPredicates -Adds the AND condition to the **RdbPredicates**. +Creates an **RdbPredicates** object to add the AND condition. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** with the AND condition. | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** @@ -567,22 +567,22 @@ predicates.equalTo("NAME", "Lisa") contains(field: string, value: string): RdbPredicates -Sets an **RdbPredicates** to match a string containing the specified value. +Creates an **RdbPredicates** object to search for the records in the specified column that contain the given value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the database table. | -| value | string | Yes | Value to match the **RdbPredicates**. | +| field | string | Yes| Column name in the database table.| +| value | string | Yes| Value to match.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created. | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** @@ -595,22 +595,22 @@ predicates.contains("NAME", "os") beginsWith(field: string, value: string): RdbPredicates -Sets an **RdbPredicates** to match a string that starts with the specified value. +Creates an **RdbPredicates** object to search for the records in the specified column that start with the given value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the database table. | -| value | string | Yes | Value to match the **RdbPredicates**. | +| field | string | Yes| Column name in the database table.| +| value | string | Yes| Value to match.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created. | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** @@ -623,22 +623,22 @@ predicates.beginsWith("NAME", "os") endsWith(field: string, value: string): RdbPredicates -Sets an **RdbPredicates** to match a string that ends with the specified value. +Creates an **RdbPredicates** object to search for the records in the specified column that end with the given value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the database table. | -| value | string | Yes | Value to match the **RdbPredicates**. | +| field | string | Yes| Column name in the database table.| +| value | string | Yes| Value to match.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created. | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** @@ -651,21 +651,21 @@ predicates.endsWith("NAME", "se") isNull(field: string): RdbPredicates -Sets an **RdbPredicates** to match the field whose value is null. +Creates an **RdbPredicates** object to search for the records in the specified column that are **null**. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the database table. | +| field | string | Yes| Column name in the database table.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created. | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** ```ts @@ -677,27 +677,27 @@ predicates.isNull("NAME") isNotNull(field: string): RdbPredicates -Sets an **RdbPredicates** to match the field whose value is not null. +Creates an **RdbPredicates** object to search for the records in the specified column that are not **null**. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the database table. | +| field | string | Yes| Column name in the database table.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created. | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| **Error Code** | **Error Message** | +| **Error Code**| **Error Message** | | --------- |----------------------------------------------------------------------------------------------------------------| | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | @@ -712,22 +712,22 @@ predicates.isNotNull("NAME") like(field: string, value: string): RdbPredicates -Sets an **RdbPredicates** to match a string that is similar to the specified value. +Creates an **RdbPredicates** object to search for the records in the specified column that are similar to the given value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the database table. | -| value | string | Yes | Value to match the **RdbPredicates**. | +| field | string | Yes| Column name in the database table.| +| value | string | Yes| Value to match.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created. | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** @@ -740,22 +740,22 @@ predicates.like("NAME", "%os%") glob(field: string, value: string): RdbPredicates -Sets an **RdbPredicates** to match the specified string. +Creates an **RdbPredicates** object to search for the records in the specified column that match the given string. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the database table. | -| value | string | Yes | Value to match the **RdbPredicates**.

Wildcards are supported. * indicates zero, one, or multiple digits or characters. **?** indicates a single digit or character. | +| field | string | Yes| Column name in the database table.| +| value | string | Yes| Value to match.

Wildcards are supported. * indicates zero, one, or multiple digits or characters. **?** indicates a single digit or character.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created. | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** @@ -768,23 +768,23 @@ predicates.glob("NAME", "?h*g") between(field: string, low: ValueType, high: ValueType): RdbPredicates -Sets an **RdbPredicates** to match the field with data type **ValueType** and value within the specified range. +Creates an **RdbPredicates** object to search for the records in the specified column that are within the specified range. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the database table. | -| low | [ValueType](#valuetype) | Yes | Minimum value to match the **RdbPredicates**. | -| high | [ValueType](#valuetype) | Yes | Maximum value to match the **RdbPredicates**. | +| field | string | Yes| Column name in the database table.| +| low | [ValueType](#valuetype) | Yes| Minimum value of the range to set.| +| high | [ValueType](#valuetype) | Yes| Maximum value of the range to set.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created. | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** @@ -797,23 +797,23 @@ predicates.between("AGE", 10, 50) notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates -Sets an **RdbPredicates** to match the field with data type **ValueType** and value out of the specified range. +Creates an **RdbPredicates** object to search for the records in the specified column that are out of the specified range. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the database table. | -| low | [ValueType](#valuetype) | Yes | Minimum value to match the **RdbPredicates**. | -| high | [ValueType](#valuetype) | Yes | Maximum value to match the **RdbPredicates**. | +| field | string | Yes| Column name in the database table.| +| low | [ValueType](#valuetype) | Yes| Minimum value of the range to set.| +| high | [ValueType](#valuetype) | Yes| Maximum value of the range to set.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created. | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** @@ -826,22 +826,22 @@ predicates.notBetween("AGE", 10, 50) greaterThan(field: string, value: ValueType): RdbPredicates -Sets an **RdbPredicates** to match the field with data type **ValueType** and value greater than the specified value. +Creates an **RdbPredicates** object to search for the records in the specified column that are greater than the given value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the database table. | -| value | [ValueType](#valuetype) | Yes | Value to match the **RdbPredicates**. | +| field | string | Yes| Column name in the database table.| +| value | [ValueType](#valuetype) | Yes| Value to match.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created. | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** @@ -854,22 +854,22 @@ predicates.greaterThan("AGE", 18) lessThan(field: string, value: ValueType): RdbPredicates -Sets an **RdbPredicates** to match the field with data type **ValueType** and value less than the specified value. +Creates an **RdbPredicates** object to search for the records in the specified column that are less than the given value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the database table. | -| value | [ValueType](#valuetype) | Yes | Value to match the **RdbPredicates**. | +| field | string | Yes| Column name in the database table.| +| value | [ValueType](#valuetype) | Yes| Value to match.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created. | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** @@ -882,22 +882,22 @@ predicates.lessThan("AGE", 20) greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates -Sets an **RdbPredicates** to match the field with data type **ValueType** and value greater than or equal to the specified value. +Creates an **RdbPredicates** object to search for the records in the specified column that are greater than or equal to the given value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the database table. | -| value | [ValueType](#valuetype) | Yes | Value to match the **RdbPredicates**. | +| field | string | Yes| Column name in the database table.| +| value | [ValueType](#valuetype) | Yes| Value to match.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created. | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** @@ -910,22 +910,22 @@ predicates.greaterThanOrEqualTo("AGE", 18) lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates -Sets an **RdbPredicates** to match the field with data type **ValueType** and value less than or equal to the specified value. +Creates an **RdbPredicates** object to search for the records in the specified column that are less than or equal to the given value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the database table. | -| value | [ValueType](#valuetype) | Yes | Value to match the **RdbPredicates**. | +| field | string | Yes| Column name in the database table.| +| value | [ValueType](#valuetype) | Yes| Value to match.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created. | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** @@ -938,21 +938,21 @@ predicates.lessThanOrEqualTo("AGE", 20) orderByAsc(field: string): RdbPredicates -Sets an **RdbPredicates** to match the column with values sorted in ascending order. +Creates an **RdbPredicates** object to sort the records in the specified column in ascending order. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the database table. | +| field | string | Yes| Column name in the database table.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created. | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** @@ -965,21 +965,21 @@ predicates.orderByAsc("NAME") orderByDesc(field: string): RdbPredicates -Sets an **RdbPredicates** to match the column with values sorted in descending order. +Creates an **RdbPredicates** object to sort the records in the specified column in descending order. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the database table. | +| field | string | Yes| Column name in the database table.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created. | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** @@ -992,15 +992,15 @@ predicates.orderByDesc("AGE") distinct(): RdbPredicates -Sets an **RdbPredicates** to filter out duplicate records. +Creates an **RdbPredicates** object to filter out duplicate records. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that can filter out duplicate records. | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** @@ -1013,21 +1013,21 @@ predicates.equalTo("NAME", "Rose").distinct() limitAs(value: number): RdbPredicates -Sets an **RdbPredicates** to specify the maximum number of records. +Creates an **RdbPredicates** object to limit the number of records. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | number | Yes | Maximum number of records. | +| value | number | Yes| Maximum number of records.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the maximum number of records. | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** @@ -1040,48 +1040,48 @@ predicates.equalTo("NAME", "Rose").limitAs(3) offsetAs(rowOffset: number): RdbPredicates -Sets an **RdbPredicates** to specify the start position of the returned result. +Creates an **RdbPredicates** object to specify the start position of the returned result. This API must be used together with **limitAs**. Otherwise, no result will be returned. To query all rows after the specified offset, pass in **-1** in **limitAs**. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| rowOffset | number | Yes | Number of rows to offset from the beginning. The value is a positive integer. | +| rowOffset | number | Yes| Start position, which is a positive integer.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the start position of the returned result. | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** ```ts let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Rose").offsetAs(3) +predicates.equalTo("NAME", "Rose").limitAs(-1).offsetAs(3) ``` ### groupBy groupBy(fields: Array<string>): RdbPredicates -Sets an **RdbPredicates** to group rows that have the same value into summary rows. +Creates an **RdbPredicates** object to group the query results based on the specified columns. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| fields | Array<string> | Yes | Names of columns to group. | +| fields | Array<string> | Yes| Names of columns to group.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that groups rows with the same value. | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** @@ -1094,22 +1094,22 @@ predicates.groupBy(["AGE", "NAME"]) indexedBy(field: string): RdbPredicates -Sets an **RdbPredicates** object to specify the index column. +Creates an **RdbPredicates** object to specify the index column. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Name of the index column. | +| field | string | Yes| Name of the index column.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the index column. | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** @@ -1122,22 +1122,22 @@ predicates.indexedBy("SALARY_INDEX") in(field: string, value: Array<ValueType>): RdbPredicates -Sets an **RdbPredicates** to match the field with data type **Array<ValueType>** and value within the specified range. +Creates an **RdbPredicates** object to search for the records in the specified column that are within the specified range. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the database table. | -| value | Array<[ValueType](#valuetype)> | Yes | Array of **ValueType**s to match. | +| field | string | Yes| Column name in the database table.| +| value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created. | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** @@ -1150,22 +1150,22 @@ predicates.in("AGE", [18, 20]) notIn(field: string, value: Array<ValueType>): RdbPredicates -Sets an **RdbPredicates** to match the field with data type **Array<ValueType>** and value out of the specified range. +Creates an **RdbPredicates** object to search for the records in the specified column that are out of the specified range. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| field | string | Yes | Column name in the database table. | -| value | Array<[ValueType](#valuetype)> | Yes | Array of **ValueType**s to match. | +| field | string | Yes| Column name in the database table.| +| value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created. | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** @@ -1176,7 +1176,7 @@ predicates.notIn("NAME", ["Lisa", "Rose"]) ## RdbStore -Provides methods to manage an RDB store. +Provides APIs for managing data in an RDB store. Before using the APIs of this class, use [executeSql](#executesql8) to initialize the database table structure and related data. @@ -1190,11 +1190,11 @@ Inserts a row of data into a table. This API uses an asynchronous callback to re **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| table | string | Yes | Name of the target table. | -| values | [ValuesBucket](#valuesbucket) | Yes | Row of data to insert. | -| callback | AsyncCallback<number> | Yes | Callback used to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned. | +| table | string | Yes| Name of the target table.| +| values | [ValuesBucket](#valuesbucket) | Yes| Row of data to insert.| +| callback | AsyncCallback<number> | Yes| Callback used to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| **Example** @@ -1235,16 +1235,16 @@ Inserts a row of data into a table. This API uses a promise to return the result **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| table | string | Yes | Name of the target table. | -| values | [ValuesBucket](#valuesbucket) | Yes | Row of data to insert. | +| table | string | Yes| Name of the target table.| +| values | [ValuesBucket](#valuesbucket) | Yes| Row of data to insert.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<number> | Promise used to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned. | +| Promise<number> | Promise used to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| **Example** @@ -1278,17 +1278,17 @@ promise.then((rowId: BusinessError) => { batchInsert(table: string, values: Array<ValuesBucket>, callback: AsyncCallback<number>):void -Batch inserts data into a table. This API uses an asynchronous callback to return the result. +Inserts a batch of data into a table. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| table | string | Yes | Name of the target table. | -| values | Array<[ValuesBucket](#valuesbucket)> | Yes | An array of data to insert. | -| callback | AsyncCallback<number> | Yes | Callback used to return the result. If the operation is successful, the number of inserted data records is returned. Otherwise, **-1** is returned. | +| table | string | Yes| Name of the target table.| +| values | Array<[ValuesBucket](#valuesbucket)> | Yes| An array of data to insert.| +| callback | AsyncCallback<number> | Yes| Callback used to return the result. If the operation is successful, the number of inserted data records is returned. Otherwise, **-1** is returned.| **Example** @@ -1344,22 +1344,22 @@ rdbStore.batchInsert("EMPLOYEE", valueBuckets, (status: number, insertNum: numbe batchInsert(table: string, values: Array<ValuesBucket>):Promise<number> -Batch inserts data into a table. This API uses a promise to return the result. +Inserts a batch of data into a table. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| table | string | Yes | Name of the target table. | -| values | Array<[ValuesBucket](#valuesbucket)> | Yes | An array of data to insert. | +| table | string | Yes| Name of the target table.| +| values | Array<[ValuesBucket](#valuesbucket)> | Yes| An array of data to insert.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<number> | Promise used to return the result. If the operation is successful, the number of inserted data records is returned. Otherwise, **-1** is returned. | +| Promise<number> | Promise used to return the result. If the operation is successful, the number of inserted data records is returned. Otherwise, **-1** is returned.| **Example** @@ -1420,10 +1420,10 @@ Updates data in the RDB store based on the specified **RdbPredicates** object. T **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| values | [ValuesBucket](#valuesbucket) | Yes | Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table. | -| predicates | [RdbPredicates](#rdbpredicates) | Yes | Update conditions specified by the **RdbPredicates** object. | +| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes| Update conditions specified by the **RdbPredicates** object.| | callback | AsyncCallback<number> | Yes | Callback used to return the number of rows updated. | **Example** @@ -1467,16 +1467,16 @@ Updates data based on the specified **RdbPredicates** object. This API uses a pr **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| values | [ValuesBucket](#valuesbucket) | Yes | Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table. | -| predicates | [RdbPredicates](#rdbpredicates) | Yes | Update conditions specified by the **RdbPredicates** object. | +| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes| Update conditions specified by the **RdbPredicates** object.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<number> | Promise used to return the number of rows updated. | +| Promise<number> | Promise used to return the number of rows updated.| **Example** @@ -1518,9 +1518,9 @@ Deletes data from the RDB store based on the specified **RdbPredicates** object. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| predicates | [RdbPredicates](#rdbpredicates) | Yes | Conditions specified by the **RdbPredicates** object for deleting data. | +| predicates | [RdbPredicates](#rdbpredicates) | Yes| Conditions specified by the **RdbPredicates** object for deleting data.| | callback | AsyncCallback<number> | Yes | Callback used to return the number of rows updated. | **Example** @@ -1547,15 +1547,15 @@ Deletes data from the RDB store based on the specified **RdbPredicates** object. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| predicates | [RdbPredicates](#rdbpredicates) | Yes | Conditions specified by the **RdbPredicates** object for deleting data. | +| predicates | [RdbPredicates](#rdbpredicates) | Yes| Conditions specified by the **RdbPredicates** object for deleting data.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<number> | Promise used to return the number of rows updated. | +| Promise<number> | Promise used to return the number of rows updated.| **Example** @@ -1580,11 +1580,11 @@ Queries data from the RDB store based on specified conditions. This API uses an **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| predicates | [RdbPredicates](#rdbpredicates) | Yes | Query conditions specified by the **RdbPredicates** object. | -| columns | Array<string> | Yes | Columns to query. If this parameter is not specified, the query applies to all columns. | -| callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md)> | Yes | Callback used to return the result. If the operation is successful, a **ResultSet** object will be returned. | +| predicates | [RdbPredicates](#rdbpredicates) | Yes| Query conditions specified by the **RdbPredicates** object.| +| columns | Array<string> | Yes| Columns to query. If this parameter is not specified, the query applies to all columns.| +| callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md)> | Yes| Callback used to return the result. If the operation is successful, a **ResultSet** object will be returned.| **Example** @@ -1611,16 +1611,16 @@ Queries data from the RDB store based on specified conditions. This API uses a p **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| predicates | [RdbPredicates](#rdbpredicates) | Yes | Query conditions specified by the **RdbPredicates** object. | -| columns | Array<string> | No | Columns to query. If this parameter is not specified, the query applies to all columns. | +| predicates | [RdbPredicates](#rdbpredicates) | Yes| Query conditions specified by the **RdbPredicates** object.| +| columns | Array<string> | No| Columns to query. If this parameter is not specified, the query applies to all columns.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<[ResultSet](js-apis-data-resultset.md)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned. | +| Promise<[ResultSet](js-apis-data-resultset.md)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| **Example** @@ -1640,17 +1640,17 @@ promise.then((resultSet: void) => { querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<ResultSet>):void -Queries data in the RDB store using the specified SQL statement. This API uses an asynchronous callback to return the result. +Queries data using the specified SQL statement. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| sql | string | Yes | SQL statement to run. | -| bindArgs | Array<[ValueType](#valuetype)> | Yes | Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If the SQL parameter statement is complete, the value of this parameter must be an empty array. | -| callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md)> | Yes | Callback used to return the result. If the operation is successful, a **ResultSet** object will be returned. | +| sql | string | Yes| SQL statement to run.| +| bindArgs | Array<[ValueType](#valuetype)> | Yes| Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If the SQL parameter statement is complete, the value of this parameter must be an empty array.| +| callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md)> | Yes| Callback used to return the result. If the operation is successful, a **ResultSet** object will be returned.| **Example** @@ -1675,16 +1675,16 @@ Queries data using the specified SQL statement. This API uses a promise to retur **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| sql | string | Yes | SQL statement to run. | -| bindArgs | Array<[ValueType](#valuetype)> | No | Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If the SQL parameter statement is complete, leave this parameter blank. | +| sql | string | Yes| SQL statement to run.| +| bindArgs | Array<[ValueType](#valuetype)> | No| Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If the SQL parameter statement is complete, leave this parameter blank.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<[ResultSet](js-apis-data-resultset.md)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned. | +| Promise<[ResultSet](js-apis-data-resultset.md)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| **Example** @@ -1708,11 +1708,11 @@ Executes an SQL statement that contains specified arguments but returns no value **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| sql | string | Yes | SQL statement to run. | -| bindArgs | Array<[ValueType](#valuetype)> | Yes | Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If the SQL parameter statement is complete, the value of this parameter must be an empty array. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| sql | string | Yes| SQL statement to run.| +| bindArgs | Array<[ValueType](#valuetype)> | Yes| Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If the SQL parameter statement is complete, the value of this parameter must be an empty array.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -1737,16 +1737,16 @@ Executes an SQL statement that contains specified arguments but returns no value **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| sql | string | Yes | SQL statement to run. | -| bindArgs | Array<[ValueType](#valuetype)> | No | Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If the SQL parameter statement is complete, leave this parameter blank. | +| sql | string | Yes| SQL statement to run.| +| bindArgs | Array<[ValueType](#valuetype)> | No| Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If the SQL parameter statement is complete, leave this parameter blank.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<void> | Promise that returns no value. | +| Promise<void> | Promise that returns no value.| **Example** @@ -1888,10 +1888,10 @@ Sets distributed tables. This API uses an asynchronous callback to return the re **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| tables | Array<string> | Yes | Names of the distributed tables to set. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| tables | Array<string> | Yes| Names of the distributed tables to set.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -1917,15 +1917,15 @@ Sets distributed tables. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| tables | Array<string> | Yes | Names of the distributed tables to set. | +| tables | Array<string> | Yes| Names of the distributed tables to set.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<void> | Promise that returns no value. | +| Promise<void> | Promise that returns no value.| **Example** @@ -1954,11 +1954,11 @@ Obtains the distributed table name of a remote device based on the local table n **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| device | string | Yes | ID of the remote device. | -| table | string | Yes | Local table name of the remote device. | -| callback | AsyncCallback<string> | Yes | Callback used to return the result. If the operation succeeds, the distributed table name of the remote device is returned. | +| device | string | Yes| ID of the remote device.| +| table | string | Yes| Local table name of the remote device.| +| callback | AsyncCallback<string> | Yes| Callback used to return the result. If the operation succeeds, the distributed table name of the remote device is returned.| **Example** @@ -2002,16 +2002,16 @@ Obtains the distributed table name of a remote device based on the local table n **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| device | string | Yes | ID of the remote device. | -| table | string | Yes | Local table name of the remote device. | +| device | string | Yes| ID of the remote device.| +| table | string | Yes| Local table name of the remote device.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<string> | Promise used to return the result. If the operation succeeds, the distributed table name of the remote device is returned. | +| Promise<string> | Promise used to return the result. If the operation succeeds, the distributed table name of the remote device is returned.| **Example** @@ -2042,7 +2042,7 @@ promise.then((tableName: String) => { sync(mode: SyncMode, predicates: RdbPredicates, callback: AsyncCallback<Array<[string, number]>>): void -Synchronizes data between devices. This API uses an asynchronous callback to return the result. +Synchronizes data across devices. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -2050,11 +2050,11 @@ Synchronizes data between devices. This API uses an asynchronous callback to ret **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| mode | [SyncMode](#syncmode8) | Yes | Data sync mode. The value can be **push** or **pull**. | -| predicates | [RdbPredicates](#rdbpredicates) | Yes | **RdbPredicates** object that specifies the data and devices to synchronize. | -| callback | AsyncCallback<Array<[string, number]>> | Yes | Callback used to send the sync result to the caller.
**string** indicates the device ID.
**number** indicates the sync status of that device. The value **0** indicates a successful sync. Other values indicate a sync failure. | +| mode | [SyncMode](#syncmode8) | Yes| Data sync mode. The value can be **push** or **pull**.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes| **RdbPredicates** object that specifies the data and devices to synchronize.| +| callback | AsyncCallback<Array<[string, number]>> | Yes| Callback used to send the sync result to the caller.
**string** indicates the device ID.
**number** indicates the sync status of that device. The value **0** indicates a successful sync. Other values indicate a sync failure. | **Example** @@ -2093,7 +2093,7 @@ rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicates, (err: BusinessError, sync(mode: SyncMode, predicates: RdbPredicates): Promise<Array<[string, number]>> -Synchronizes data between devices. This API uses a promise to return the result. +Synchronizes data across devices. This API uses a promise to return the result. **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -2101,16 +2101,16 @@ Synchronizes data between devices. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| mode | [SyncMode](#syncmode8) | Yes | Data sync mode. The value can be **push** or **pull**. | -| predicates | [RdbPredicates](#rdbpredicates) | Yes | **RdbPredicates** object that specifies the data and devices to synchronize. | +| mode | [SyncMode](#syncmode8) | Yes| Data sync mode. The value can be **push** or **pull**.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes| **RdbPredicates** object that specifies the data and devices to synchronize.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<Array<[string, number]>> | Promise used to send the sync result.
**string** indicates the device ID.
**number** indicates the sync status of that device. The value **0** indicates a successful sync. Other values indicate a sync failure. | +| Promise<Array<[string, number]>> | Promise used to send the sync result.
**string** indicates the device ID.
**number** indicates the sync status of that device. The value **0** indicates a successful sync. Other values indicate a sync failure. | **Example** @@ -2154,10 +2154,10 @@ Registers an observer for this RDB store. When the data in the RDB store changes **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | event | string | Yes| Event type. The value is 'dataChange', which indicates data changes. | -| type | [SubscribeType](#subscribetype8) | Yes | Subscription type to register. | +| type | [SubscribeType](#subscribetype8) | Yes| Subscription type to register.| | observer | Callback<Array<string>> | Yes | Observer that listens for the data changes in the RDB store. **Array\** indicates the ID of the peer device whose data in the database is changed. | **Example** @@ -2180,13 +2180,13 @@ try { off(event:'dataChange', type: SubscribeType, observer: Callback<Array<string>>): void -Unregisters the observer of the specified type from the RDB store. This API uses a callback to return the result. +Unregisters the observer of the specified type from the RDB store. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | event | string | Yes| Event type. The value is 'dataChange', which indicates data changes. | | type | [SubscribeType](#subscribetype8) | Yes| Subscription type to unregister.| diff --git a/en/application-dev/reference/apis-arkdata/js-apis-data-relationalStore-sys.md b/en/application-dev/reference/apis-arkdata/js-apis-data-relationalStore-sys.md index 573e421dbf37c3d95de3b364d2a4dc1c9c79eedc..84ed370e5309efa1af3bed99b17a8305f2de1db3 100644 --- a/en/application-dev/reference/apis-arkdata/js-apis-data-relationalStore-sys.md +++ b/en/application-dev/reference/apis-arkdata/js-apis-data-relationalStore-sys.md @@ -278,7 +278,7 @@ Deletes data from the RDB store based on the specified **DataSharePredicates** o | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | --------------------------------------------- | -| table | string | Yes | Name of the target table. | +| table | string | Yes | Name of the target table, which cannot be an empty string. | | predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Conditions specified by the **DataSharePredicates** object for deleting data.| | callback | AsyncCallback<number> | Yes | Callback used to return the number of rows deleted. | @@ -591,8 +591,10 @@ cloudSync(mode: SyncMode, predicates: RdbPredicates, progress: Callback<Progr Manually performs device-cloud sync based on specified conditions. This API uses an asynchronous callback to return the result. The cloud sync function must be implemented. Otherwise, this API cannot be used. > **NOTE** -> -> Since API version 16, you can specify the asset download capability as a condition for device-cloud sync. If the sync mode is set to [SYNC_MODE_CLOUD_FIRST](js-apis-data-relationalStore.md#syncmode), the primary key (mandatory) and asset (optional) can be used as sync conditions in the predicates. If asset is used as the sync condition, only [equalTo](js-apis-data-relationalStore.md#equalto) is supported. If a large number of assets (max. 50) are specified, you are advised to use only the primary key in the predicates. +> +> Since API version 18, you can specify assets in predicates when performing manual device-cloud sync. In this case, the sync mode must be **relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST**. +> +> When specifying the predicates, you can use the primary key (mandatory) and asset (optional) as sync conditions. If assets are specified, the predicate supports only [equalTo](js-apis-data-relationalStore.md#equalto), with a limit of 50 assets. If more assets are involved, you are advised to use only the primary key as the sync condition. **System capability**: SystemCapability.DistributedDataManager.CloudSync.Client @@ -649,7 +651,7 @@ let asset : relationalStore.Asset = { modifyTime: new Date().getTime().toString(), size: "1024" } -// Specify the primary key and asset (asset column in the database ) in the predicates. +// Specify the primary key and asset (asset column in the database) in the predicates. predicates.beginWrap().equalTo("id", "id1").and().equalTo("asset", asset).endWrap(); if(store != undefined) { @@ -671,9 +673,11 @@ cloudSync(mode: SyncMode, predicates: RdbPredicates, progress: Callback<Progr Manually performs device-cloud sync based on specified conditions. This API uses a promise to return the result. The cloud sync function must be implemented. Otherwise, this API cannot be used. ->**NOTE** -> ->Since API version 16, you can specify the asset download capability as a condition for device-cloud sync. If the sync mode is set to [SYNC_MODE_CLOUD_FIRST](js-apis-data-relationalStore.md#syncmode), the primary key (mandatory) and asset (optional) can be used as sync conditions in the predicates. If asset is used as the sync condition, only [equalTo](js-apis-data-relationalStore.md#equalto) is supported. If a large number of assets (max. 50) are specified, you are advised to use only the primary key in the predicates. +> **NOTE** +> +> Since API version 18, you can specify assets in predicates when performing manual device-cloud sync. In this case, the sync mode must be **relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST**. +> +> When specifying the predicates, you can use the primary key (mandatory) and asset (optional) as sync conditions. If assets are specified, the predicate supports only [equalTo](js-apis-data-relationalStore.md#equalto), with a limit of 50 assets. If more assets are involved, you are advised to use only the primary key as the sync condition. **System capability**: SystemCapability.DistributedDataManager.CloudSync.Client @@ -735,7 +739,7 @@ let asset : relationalStore.Asset = { modifyTime: new Date().getTime().toString(), size: "1024" } -// Specify the primary key and asset (asset column in the database ) in the predicates. +// Specify the primary key and asset (asset column in the database) in the predicates. predicates.beginWrap().equalTo("id", "id1").and().equalTo("asset", asset).endWrap(); if(store != undefined) { diff --git a/en/application-dev/reference/apis-arkdata/js-apis-data-relationalStore.md b/en/application-dev/reference/apis-arkdata/js-apis-data-relationalStore.md index 325b67959f4c83a42dbe9629bd37d2cc49bc0640..d8b946df11dd055f87b5323b9cd17cec10347b96 100644 --- a/en/application-dev/reference/apis-arkdata/js-apis-data-relationalStore.md +++ b/en/application-dev/reference/apis-arkdata/js-apis-data-relationalStore.md @@ -10,12 +10,12 @@ Querying data from a large amount of data may take time or even cause applicatio - Keep concatenated SQL statements as concise as possible. - Query data in batches. -The **relationalStore** module provides the following functionality: +The **relationalStore** module provides the following functionalities: -- [RdbPredicates](#rdbpredicates): provides predicates indicating the nature, feature, or relationship of a data entity in an RDB store. It is used to define the operation conditions for an RDB store. +- [RdbPredicates](#rdbpredicates): provides APIs for creating predicates. The predicates represent the properties, characteristics, or relationships between data entities in an RDB store and are used to define data operation conditions. - [RdbStore](#rdbstore): provides APIs for managing data in an RDB store. - [Resultset](#resultset): provides APIs for accessing the result set obtained from the RDB store. -- [Transaction](#transaction14): provides APIs for managing transaction objects. +- [Transaction](#transaction14): provides APIs for managing transactions. > **NOTE** > @@ -31,7 +31,7 @@ import { relationalStore } from '@kit.ArkData'; getRdbStore(context: Context, config: StoreConfig, callback: AsyncCallback<RdbStore>): void -Obtains an RDB store. This API uses an asynchronous callback to return the result. You can set parameters for the RDB store based on service requirements and call APIs to perform data operations. +Obtains an RdbStore instance. This API uses an asynchronous callback to return the result. You can set parameters for the RDB store based on service requirements and call APIs to perform data operations. The parameter [encrypt](#storeconfig) takes effect only when the RDB store is created for the first time, and cannot be modified. It is important to set this parameter correctly. @@ -50,7 +50,7 @@ Currently, **getRdbStore()** does not support multi-thread concurrent operations | -------- | ---------------------------------------------- | ---- | ------------------------------------------------------------ | | context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](../apis-ability-kit/js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md).| | config | [StoreConfig](#storeconfig) | Yes | Configuration of the RDB store. | -| callback | AsyncCallback<[RdbStore](#rdbstore)> | Yes | Callback used to return the RDB store obtained. | +| callback | AsyncCallback<[RdbStore](#rdbstore)> | Yes | Callback used to return the RdbStore instance obtained. | **Error codes** @@ -63,7 +63,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 14800010 | Invalid database path. | | 14800011 | Database corrupted. | | 14801001 | The operation is supported in the stage model only. | -| 14801002 | Invalid data group ID. | +| 14801002 | Invalid data group ID. | | 14800017 | Config changed. | | 14800020 | The secret key is corrupted or lost. | | 14800021 | SQLite: Generic error. | @@ -91,13 +91,14 @@ const STORE_CONFIG: relationalStore.StoreConfig = { securityLevel: relationalStore.SecurityLevel.S3 }; -relationalStore.getRdbStore(context, STORE_CONFIG, (err: BusinessError, rdbStore: relationalStore.RdbStore) => { - store = rdbStore; +relationalStore.getRdbStore(context, STORE_CONFIG, async (err: BusinessError, rdbStore: relationalStore.RdbStore) => { if (err) { console.error(`Get RdbStore failed, code is ${err.code},message is ${err.message}`); return; } console.info('Get RdbStore successfully.'); + store = rdbStore; + // Perform subsequent operations after the rdbStore instance is successfully obtained. }) ``` @@ -117,13 +118,14 @@ class EntryAbility extends UIAbility { securityLevel: relationalStore.SecurityLevel.S3 }; - relationalStore.getRdbStore(this.context, STORE_CONFIG, (err: BusinessError, rdbStore: relationalStore.RdbStore) => { - store = rdbStore; + relationalStore.getRdbStore(this.context, STORE_CONFIG, async (err: BusinessError, rdbStore: relationalStore.RdbStore) => { if (err) { console.error(`Get RdbStore failed, code is ${err.code},message is ${err.message}`); return; } console.info('Get RdbStore successfully.'); + store = rdbStore; + // Perform subsequent operations after the rdbStore instance is successfully obtained. }) } } @@ -133,7 +135,7 @@ class EntryAbility extends UIAbility { getRdbStore(context: Context, config: StoreConfig): Promise<RdbStore> -Obtains an RDB store. This API uses a promise to return the result. You can set parameters for the RDB store based on service requirements and call APIs to perform data operations. +Obtains an RdbStore instance. This API uses a promise to return the result. You can set parameters for the RDB store based on service requirements and call APIs to perform data operations. The parameter [encrypt](#storeconfig) takes effect only when the RDB store is created for the first time, and cannot be modified. It is important to set this parameter correctly. @@ -157,7 +159,7 @@ Currently, **getRdbStore()** does not support multi-thread concurrent operations | Type | Description | | ----------------------------------------- | --------------------------------- | -| Promise<[RdbStore](#rdbstore)> | Promise used to return the **RdbStore** object obtained.| +| Promise<[RdbStore](#rdbstore)> | Promise used to return the **RdbStore** instance obtained.| **Error codes** @@ -238,7 +240,7 @@ deleteRdbStore(context: Context, name: string, callback: AsyncCallback<void&g Deletes an RDB store. This API uses an asynchronous callback to return the result. -After the deletion, you are advised to set the database object to null. If a customized path is set in [StoreConfig](#storeconfig) when an RDB store is created, using this API cannot delete the RDB store. Use [deleteRdbStore10+](#relationalstoredeleterdbstore10) instead. +After the deletion, you are advised to set the database object to null. If a custom path is set in [StoreConfig](#storeconfig) when an RDB store is created, using this API cannot delete the RDB store. Use [deleteRdbStore](#relationalstoredeleterdbstore10) instead. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -311,7 +313,7 @@ deleteRdbStore(context: Context, name: string): Promise<void> Deletes an RDB store. This API uses a promise to return the result. -After the deletion, you are advised to set the database object to null. If a customized path is set in [StoreConfig](#storeconfig) when an RDB store is created, using this API cannot delete the RDB store. Use [deleteRdbStore10+](#relationalstoredeleterdbstore10-1) instead. +After the deletion, you are advised to set the database object to null. If a custom path is set in [StoreConfig](#storeconfig) when an RDB store is created, using this API cannot delete the RDB store. Use [deleteRdbStore](#relationalstoredeleterdbstore10-1) instead. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -548,7 +550,7 @@ class EntryAbility extends UIAbility { } } ``` -## relationalStore.isVectorSupported16+ +## relationalStore.isVectorSupported18+ isVectorSupported(): boolean @@ -568,7 +570,7 @@ Checks whether the system supports vector stores. let result = relationalStore.isVectorSupported(); ``` -## relationalStore.isTokenizerSupported16+ +## relationalStore.isTokenizerSupported18+ isTokenizerSupported(tokenizer: Tokenizer): boolean @@ -582,7 +584,7 @@ This API returns **true** if the specified tokenizer is supported; returns **fal | Name | Type | Mandatory| Description | | ------- | --------------------- | ---- | ------------------------------------------------------------ | -| tokenizer | [Tokenizer](#tokenizer16) | Yes | Tokenizer to check.| +| tokenizer | [Tokenizer](#tokenizer18) | Yes | Tokenizer to check.| **Return value** @@ -617,17 +619,18 @@ Defines the RDB store configuration. | ------------- | ------------- | ---- | --------------------------------------------------------- | | name | string | Yes | Database file name, which is the unique identifier of the database.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core | | securityLevel | [SecurityLevel](#securitylevel) | Yes | Security level of the RDB store.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core| -| encrypt | boolean | No | Whether to encrypt the RDB store.
The value **true** means to encrypt the RDB store; the value **false** (default) means the opposite.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core| -| dataGroupId10+ | string | No| Application group ID, which needs to be obtained from AppGallery Connect (AGC). This parameter is not supported currently.
**Model restriction**: This attribute can be used only in the stage model.
This parameter is supported since API version 10. If this parameter is specified, the **RdbStore** instance will be created in the sandbox directory corresponding to the specified **dataGroupId**. The encrypted database in the sandbox directory corresponding to a **dataGroupId** does not support multi-process access. If this parameter is left blank, the **RdbStore** instance is created in the sandbox directory of the current application by default.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core| -| customDir11+ | string | No| Customized path of the RDB store.
**Constraints**: The value cannot exceed 128 bytes.
This parameter is supported since API version 11. The RDB store directory is in the **context.databaseDir**/**rdb**/**customDir** format. **context.databaseDir** specifies the application sandbox path. **rdb** is a fixed field that indicates an RDB store. **customDir** specifies the customized path. If this parameter is not specified, the **RdbStore** instance is created in the sandbox directory of the application. Since API version 16, if the **rootDir** parameter is also configured, the RDB store in the following directory will be opened or deleted: rootDir + "/" + customDir + "/" + name.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core| -| rootDir16+ | string | No| Root path of the database.
This parameter is supported since API version 16. The database in the **rootDir** + "/" + **customDir** directory will be opened or deleted. The database opened is read-only. Writing data to a read-only database will trigger error 801. If this parameter is set when you want to open or delete an RDB store, ensure that the database file exists in the corresponding path and the caller has the read permission. Otherwise, error 14800010 will be returned.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core| -| autoCleanDirtyData11+ | boolean | No| Whether to automatically clear the dirty data (data that has been deleted from the cloud) from the local device. The value **true** means to clear the dirty data automatically. The value **false** means to clear the data manually. The default value is **true**.
This parameter applies to the RDB stores with device-cloud synergy. To manually clear the dirty data, use [cleanDirtyData11+](#cleandirtydata11).
This parameter is supported since API version 11.
**System capability**: SystemCapability.DistributedDataManager.CloudSync.Client| -| allowRebuild12+ | boolean | No| Whether auto rebuild is allowed when the RDB store is corrupted. The default value is **false**.
The value **true** means auto rebuild is allowed.
The value **false** means the opposite.
This parameter is supported since API version 12.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core| -| isReadOnly12+ | boolean | No| Whether the RDB store is read-only. The default value is **false**, which means the RDB store is readable and writeable.
If the value is **true** (read-only), writing data to the RDB store will throw error code 801.
The value **false** means the RDB store is readable and writeable.
This parameter is supported since API version 12.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core| +| encrypt | boolean | No | Whether to encrypt the RDB store.
**true**: encrypt the RDB store.
**false** (default): not encrypt the RDB store.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core| +| dataGroupId10+ | string | No| Application group ID. Currently, this parameter is not supported.
**Model restriction**: This parameter can be used only in the stage model.
This parameter is supported since API version 10. If **dataGroupId** is specified, the **RdbStore** instance will be created in the sandbox directory of the specified **dataGroupId**. However, the encrypted RDB store in this sandbox directory does not support multi-process access. If this parameter is left blank, the **RdbStore** instance will be created in the sandbox directory of the application by default.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core| +| customDir11+ | string | No| Customized path of the RDB store.
**Constraints**: The value cannot exceed 128 bytes.
This parameter is supported since API version 11. The RDB store directory is in the **context.databaseDir**/**rdb**/**customDir** format. **context.databaseDir** specifies the application sandbox path. **rdb** is a fixed field that indicates an RDB store. **customDir** specifies the customized path. If this parameter is not specified, the **RdbStore** instance is created in the sandbox directory of the application. Since API version 18, if the **rootDir** parameter is also configured, the RDB store in the following directory will be opened or deleted: rootDir + "/" + customDir + "/" + name.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core| +| rootDir18+ | string | No| Root path of the database.
This parameter is supported since API version 18. The database in the **rootDir** + "/" + **customDir** directory will be opened or deleted. The database opened is read-only. Writing data to a read-only database will trigger error 801. If this parameter is set when you want to open or delete an RDB store, ensure that the database file exists in the corresponding path and the caller has the read permission. Otherwise, error 14800010 will be returned.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core| +| autoCleanDirtyData11+ | boolean | No| Whether to automatically clear the dirty data (data that has been deleted from the cloud) from the local device. The value **true** means to clear the dirty data automatically. The value **false** means to clear the data manually.
Default value: **true**.
This parameter applies to the RDB stores with device-cloud synergy. To manually clear the dirty data, use [cleanDirtyData11+](#cleandirtydata11).
This parameter is supported since API version 11.
**System capability**: SystemCapability.DistributedDataManager.CloudSync.Client| +| allowRebuild12+ | boolean | No| Whether to automatically delete the RDB store and create an empty table in the case of an exception.
**true**: delete the RDB store and create an empty table in the case of an exception.
**false** (default): not delete the RDB store in the case of an exception.
This parameter is supported since API version 12.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core| +| isReadOnly12+ | boolean | No| Whether the RDB store is read-only.
**true**: The RDB store is read-only. Writing data to the RDB store will result in error code 801.
**false** (default): The RDB store is readable and writeable.
This parameter is supported since API version 12.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core| | pluginLibs12+ | Array\ | No| Dynamic libraries with capabilities such as Full-Text Search (FTS).
**Constraints**
1. The maximum number of dynamic library names is 16. If the number of dynamic library names exceeds 16, the library fails to be opened and an error is returned.
2. The dynamic libraries must be those in the sandbox directory or system directory of the application. If a dynamic library fails to be loaded, the RDB store cannot be opened and an error will be returned.
3. The dynamic library name must be a complete path that can be loaded by SQLite.
Example: [context.bundleCodeDir + "/libs/arm64/" + libtokenizer.so], where **context.bundleCodeDir** indicates the application sandbox path, **/libs/arm64/** is the subdirectory, **libtokenizer.so** indicates the file name of the dynamic library. If this parameter is left blank, dynamic libraries are not loaded by default.
4. The dynamic library must contain all its dependencies to prevent the failure caused by the lack of dependencies.
For example, in an NDK project, the default compilation parameters are used to build **libtokenizer.so**, which depends on the C++ standard library. When the dynamic library is loaded, **libc++_shared.so** is linked by mistake because the namespace is different from that during compilation. As a result, the **__emutls_get_address** symbol cannot be found. To solve this problem, you need to statically link the C++ standard library during compilation. For details, see [NDK Project Building Overview](../../napi/build-with-ndk-overview.md).
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core| | cryptoParam14+ | [CryptoParam](#cryptoparam14) | No| Custom encryption parameters.
If this parameter is left empty, the default encryption parameters are used. For details, see default values of [CryptoParam](#cryptoparam14).
This parameter is valid only when **encrypt** is **true**.
This parameter is supported since API version 14.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core| -| vector16+ | boolean | No| Whether the RDB store is a vector store. The value **true** means the RDB store is a vector store, and the value **false** means the opposite.
The vector store is ideal for storing and managing high-dimensional vector data, while the relational database is optimal for storing and processing structured data.
Currently, vector stores support [execute](#execute12-1), [querySql](#querysql-1), [beginTrans](#begintrans12), [commit](#commit12), [rollback](#rollback12), [backup](#backup), [restore](#restore), and [ResultSet](#resultset) APIs. Before calling **deleteRdbStore** to delete a vector store, ensure that the vector store is properly closed. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core| -| tokenizer16+ | [Tokenizer](#tokenizer16) | No| Type of the tokenizer to be used for FTS.
If this parameter is left blank, English tokenization is supported if FTS does not support Chinese or multi-language tokenization.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core| +| vector18+ | boolean | No| Whether the RDB store is a vector store. The value **true** means the RDB store is a vector store; the value **false** means the opposite.
The vector store is ideal for storing and managing high-dimensional vector data, while the relational database is optimal for storing and processing structured data.
Currently, vector databases support [execute](#execute12-1), [querySql](#querysql-1), [beginTrans](#begintrans12), [commit](#commit12), [rollback](#rollback12), [backup](#backup), [restore](#restore), and [ResultSet](#resultset) APIs. Before calling **deleteRdbStore** to delete a vector store, ensure that the vector store is properly closed.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core| +| tokenizer18+ | [Tokenizer](#tokenizer18) | No| Type of the tokenizer to be used for FTS.
If this parameter is left blank, English tokenization is supported if FTS does not support Chinese or multi-language tokenization.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core| +| persist18+ | boolean | No| Whether to persist the RDB store. The value **true** means to persist the RDB store; the value **false** means the opposite (using an in-memory database).
Default value: **true**.
An in-memory database does not support encryption, backup, restore, cross-process access, and distributed capabilities, with the **securityLevel** property ignored.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core| ## SecurityLevel @@ -655,11 +658,11 @@ Represents the configuration of database encryption parameters. This parameter i | Name | Type | Mandatory| Description | | ------------- | ------ | ---- | ------------------------------------------------------------ | | encryptionKey | Uint8Array | Yes | Key used for database encryption and decryption.
If this parameter is not specified, the RDB store generates a key, saves the key, and uses the key to open the database file.
If the key is not required, you need to set the key to 0s.| -| iterationCount | number | No| Number of iterations of the PBKDF2 algorithm used in the RDB store. The value is an integer. The default value is **10000**.
The value must be an integer greater than 0. If it is not an integer, the value is rounded down.
If this parameter is not specified or is set to **0**, the default value **10000** and the default encryption algorithm **AES_256_GCM** are used.| -| encryptionAlgo | [EncryptionAlgo](#encryptionalgo14) | No| Algorithm used for database encryption and decryption. The default value is **AES_256_GCM**.| -| hmacAlgo | [HmacAlgo](#hmacalgo14) | No| HMAC algorithm used for database encryption and decryption. The default value is **SHA256**.| -| kdfAlgo | [KdfAlgo](#kdfalgo14) | No| PBKDF2 algorithm used for database encryption and decryption. The default value is the same as the HMAC algorithm used.| -| cryptoPageSize | number | No| Page size used for database encryption and decryption. The default value is **1024** bytes.
The value must be an integer within the range of 1024 to 65536 and must be 2n. If the specified value is not an integer, the value is rounded down.| +| iterationCount | number | No| Number of iterations of the PBKDF2 algorithm used in the RDB store. The value is an integer.
Default value: **10000**.
The value must be an integer greater than 0. If it is not an integer, the value is rounded down.
If this parameter is not specified or is set to **0**, the default value **10000** and the default encryption algorithm **AES_256_GCM** are used.| +| encryptionAlgo | [EncryptionAlgo](#encryptionalgo14) | No| Algorithm used for database encryption and decryption.
Default value: **AES_256_GCM**.| +| hmacAlgo | [HmacAlgo](#hmacalgo14) | No| HMAC algorithm used for database encryption and decryption.
Default value: **SHA256**.| +| kdfAlgo | [KdfAlgo](#kdfalgo14) | No| PBKDF2 algorithm used for database encryption and decryption.
Default value: the same as the HMAC algorithm used.| +| cryptoPageSize | number | No| Page size used for database encryption and decryption.
Default value: **1024** bytes.
The value must be an integer within the range of 1024 to 65536 and must be 2n. If the specified value is not an integer, the value is rounded down.| ## EncryptionAlgo14+ @@ -696,7 +699,7 @@ Enumerates the PBKDF2 algorithms for the database. Use the enum name rather than | KDF_SHA256 | 1 | PBKDF2_HMAC_SHA256. | | KDF_SHA512 | 2 | PBKDF2_HMAC_SHA512. | -## Tokenizer16+ +## Tokenizer18+ Enumerates tokenizers that can be used for FTS. Use the enum name rather than the enum value. @@ -722,7 +725,7 @@ import { window } from '@kit.ArkUI'; // In this example, Ability is used to obtain an RdbStore instance in the stage model. You can use other implementations as required. class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage: window.WindowStage) { + async onWindowStageCreate(windowStage: window.WindowStage) { let store: relationalStore.RdbStore | undefined = undefined; const STORE_CONFIG: relationalStore.StoreConfig = { name: "MyStore.db", @@ -732,7 +735,7 @@ class EntryAbility extends UIAbility { store = await relationalStore.getRdbStore(this.context, STORE_CONFIG); const SQL_CREATE_TABLE = "CREATE VIRTUAL TABLE example USING fts4(name, content, tokenize=icu zh_CN)" - if(store != undefined) { + if (store != undefined) { (store as relationalStore.RdbStore).executeSql(SQL_CREATE_TABLE, (err) => { if (err) { console.error(`ExecuteSql failed, code is ${err.code},message is ${err.message}`); @@ -755,7 +758,7 @@ import { window } from '@kit.ArkUI'; // In this example, Ability is used to obtain an RdbStore instance in the stage model. You can use other implementations as required. class EntryAbility extends UIAbility { - onWindowStageCreate(windowStage: window.WindowStage) { + async onWindowStageCreate(windowStage: window.WindowStage) { let store: relationalStore.RdbStore | undefined = undefined; const STORE_CONFIG: relationalStore.StoreConfig = { name: "MyStore.db", @@ -765,13 +768,13 @@ class EntryAbility extends UIAbility { store = await relationalStore.getRdbStore(this.context, STORE_CONFIG); const SQL_CREATE_TABLE = "CREATE VIRTUAL TABLE example USING fts5(name, content, tokenize='customtokenizer')" - if(store != undefined) { + if (store != undefined) { (store as relationalStore.RdbStore).executeSql(SQL_CREATE_TABLE, (err) => { if (err) { console.error(`ExecuteSql failed, code is ${err.code},message is ${err.message}`); return; } - console.info('create virtual table done.'); + console.info('create virtual table done.'); }) } } @@ -807,7 +810,7 @@ Defines information about an asset (such as a document, image, and video). | createTime | string | Yes | Time when the asset was created. | | modifyTime | string | Yes | Time when the asset was last modified.| | size | string | Yes | Size of the asset. | -| status | [AssetStatus](#assetstatus10) | No | Asset status. The default value is **ASSET_NORMAL**. | +| status | [AssetStatus](#assetstatus10) | No | Asset status.
Default value: **ASSET_NORMAL**. | ## Assets10+ @@ -825,7 +828,7 @@ Defines an array of the [Asset](#asset10) type. type ValueType = null | number | string | boolean | Uint8Array | Asset | Assets | Float32Array | bigint -Enumerates the types of the value in a KV pair. The type varies with the parameter function. +Enumerates the types of the value in a KV pair. The type varies with the parameter usage. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -996,7 +999,8 @@ Defines the configuration of the distributed mode of tables. | Name | Type | Mandatory| Description | | -------- | ------- | ---- | ------------------------------------------------------------ | | autoSync | boolean | Yes | The value **true** means both auto sync and manual sync are supported for the table. The value **false** means only manual sync is supported for the table.| -| asyncDownloadAsset16+ | boolean | No| Whether to download assets synchronously or asynchronously when device-cloud sync is being performed for the current RDB store. The value **true** means to use an asynchronous task to download assets after all data is downloaded. The value **false** means to downloaded assets synchronously. The default value is **false**.| +| asyncDownloadAsset18+ | boolean | No| Whether to download assets synchronously or asynchronously when device-cloud sync is being performed for the current RDB store. The value **true** means to use an asynchronous task to download assets after all data is downloaded. The value **false** means to downloaded assets synchronously.
Default value: **false**.| +| enableCloud18+ | boolean | No| Whether to enable device-cloud sync for this RDB store. The value **true** means to enable device-cloud sync; the value **false** means the opposite.
Default value: **true**| ## ConflictResolution10+ @@ -1112,11 +1116,29 @@ Represents the configuration of a transaction object. | Name | Type | Mandatory| Description | | ------------- | ------------- | ---- | --------------------------------------------------------- | -| transactionType | [TransactionType](#transactiontype14) | No | Transaction object type. The default value is **DEFERRED**. | +| transactionType | [TransactionType](#transactiontype14) | No | Transaction object type.
Default value: **DEFERRED**. | + +## ColumnType18+ + +Enumerates the types of the column data. Use the enum name rather than the enum value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Value | Description | +| ------------- | ---- | ------------------------------------------------------------ | +| NULL | 0 | NULL. | +| INTEGER | 1 | 64-bit integer.
The column can hold 8-bit (including Boolean values), 16-bit, 32-bit, and 64-bit integers. For the 64-bit integer greater than 2^53 or less than -2^53, use [getString](#getstring) to convert it into a string.| +| REAL | 2 | Floating-point number. | +| TEXT | 3 | String. | +| BLOB | 4 | Uint8Array. | +| ASSET | 5 | [Asset](#asset10). | +| ASSETS | 6 | [Assets](#assets10). | +| FLOAT_VECTOR | 7 | Float32Array. | +| UNLIMITED_INT | 8 | bigint. | ## RdbPredicates -Defines the predicates for an RDB store. This class determines whether the conditional expression for the RDB store is true or false. Multiple predicates statements can be concatenated by using **and()** by default. **RdbPredicates** cannot be passed across threads. +Provides APIs for creating the predicates (condition) for RDB store operations. This class determines whether the conditional expression for the RDB store is true or false. Multiple predicates statements can be concatenated by using **and()** by default. **RdbPredicates** cannot be passed across threads. ### constructor @@ -1150,12 +1172,12 @@ let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); inDevices(devices: Array<string>): RdbPredicates -Sets an **RdbPredicates** object to specify the remote devices to connect during the distributed database sync. +Creates an **RdbPredicates** object to specify the remote devices to connect during the distributed database sync. > **NOTE** > -> **devices** can be obtained by [deviceManager.getAvailableDeviceListSync](../apis-distributedservice-kit/js-apis-distributedDeviceManager.md#getavailabledevicelistsync). -If **inDevices** is specified in **predicates** when **sync()** is called, data is synchronized with the specified device. If **inDevices** is not specified, data is synchronized with all devices on the network by default. +> **devices** can be obtained by using [deviceManager.getAvailableDeviceListSync](../apis-distributedservice-kit/js-apis-distributedDeviceManager.md#getavailabledevicelistsync). +When calling **sync()**, you need to call **inDevices** to specify the devices. If **inDevices** is not used, data will be synced to all devices on the network by default. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1163,7 +1185,7 @@ If **inDevices** is specified in **predicates** when **sync()** is called, data | Name | Type | Mandatory| Description | | ------- | ------------------- | ---- | -------------------------- | -| devices | Array<string> | Yes | IDs of the remote devices in the same network.| +| devices | Array<string> | Yes | IDs of the remote devices to connect.| **Return value** @@ -1208,7 +1230,7 @@ predicates.inDevices(deviceIds); inAllDevices(): RdbPredicates -Sets an **RdbPredicates** instance to specify all remote devices to connect during the distributed database sync. +Creates an **RdbPredicates** object to specify all remote devices to connect during the distributed database sync. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1230,7 +1252,7 @@ predicates.inAllDevices(); equalTo(field: string, value: ValueType): RdbPredicates -Sets an **RdbPredicates** object to match the fields in the specified column that are equal to the given value. +Creates an **RdbPredicates** object to search for the records in the specified column that are equal to the given value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1239,7 +1261,7 @@ Sets an **RdbPredicates** object to match the fields in the specified column tha | Name| Type | Mandatory| Description | | ------ | ----------------------- | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | [ValueType](#valuetype) | Yes | Value to match the **RdbPredicates**.| +| value | [ValueType](#valuetype) | Yes | Value to match.| **Return value** @@ -1258,7 +1280,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -// Locate data of Lisa in the EMPLOYEE table. +// Find all the records in the NAME column where the value is Lisa. let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Lisa"); ``` @@ -1268,7 +1290,7 @@ predicates.equalTo("NAME", "Lisa"); notEqualTo(field: string, value: ValueType): RdbPredicates -Sets an **RdbPredicates** object to match the fields in the specified column that are not equal to the given value. +Creates an **RdbPredicates** object to search for the records in the specified column that are not equal to the given value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1277,7 +1299,7 @@ Sets an **RdbPredicates** object to match the fields in the specified column tha | Name| Type | Mandatory| Description | | ------ | ----------------------- | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | [ValueType](#valuetype) | Yes | Value to match the **RdbPredicates**.| +| value | [ValueType](#valuetype) | Yes | Value to match.| **Return value** @@ -1296,7 +1318,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -// Locate data of the employees whose name is not Lisa in the table. +// Find all the records in the NAME column where the value is not Lisa. let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.notEqualTo("NAME", "Lisa"); ``` @@ -1306,7 +1328,7 @@ predicates.notEqualTo("NAME", "Lisa"); beginWrap(): RdbPredicates -Adds a left parenthesis to the **RdbPredicates**. +Creates an **RdbPredicates** object to add a left parenthesis. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1314,7 +1336,7 @@ Adds a left parenthesis to the **RdbPredicates**. | Type | Description | | ------------------------------------ | ------------------------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** with a left parenthesis.| +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** @@ -1332,7 +1354,7 @@ predicates.equalTo("NAME", "Lisa") endWrap(): RdbPredicates -Adds a right parenthesis to the **RdbPredicates**. +Creates an **RdbPredicates** object to add a right parenthesis. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1340,7 +1362,7 @@ Adds a right parenthesis to the **RdbPredicates**. | Type | Description | | ------------------------------------ | ------------------------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** with a right parenthesis.| +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** @@ -1358,7 +1380,7 @@ predicates.equalTo("NAME", "Lisa") or(): RdbPredicates -Adds the OR condition to the **RdbPredicates**. +Creates an **RdbPredicates** object to add the OR condition. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1366,12 +1388,12 @@ Adds the OR condition to the **RdbPredicates**. | Type | Description | | ------------------------------------ | ------------------------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** with the OR condition.| +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** ```ts -// Locate the employees named Lisa or Rose in the table. +// Find all records in the NAME column where the value is Lisa or Rose. let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Lisa") .or() @@ -1382,7 +1404,7 @@ predicates.equalTo("NAME", "Lisa") and(): RdbPredicates -Adds the AND condition to the **RdbPredicates**. +Creates an **RdbPredicates** object to add the AND condition. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1390,12 +1412,12 @@ Adds the AND condition to the **RdbPredicates**. | Type | Description | | ------------------------------------ | ------------------------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** with the AND condition.| +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** ```ts -// Locate the field with name of Lisa and salary of 200.5 in the table. +// Find the records in the EMPLOYEE table where the NAME column is Lisa and the SALARY column is 200.5. let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Lisa") .and() @@ -1406,7 +1428,7 @@ predicates.equalTo("NAME", "Lisa") contains(field: string, value: string): RdbPredicates -Sets an **RdbPredicates** object to match the fields in the specified column that contain the given value. +Creates an **RdbPredicates** object to search for the records in the specified column that contain the given value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1415,7 +1437,7 @@ Sets an **RdbPredicates** object to match the fields in the specified column tha | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | string | Yes | Value to match the **RdbPredicates**.| +| value | string | Yes | Value to match.| **Return value** @@ -1434,7 +1456,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -// Locate data of the employees whose name contains os, for example, Rose, in the table. +// Find all the records that contain the string 'os' in the NAME column. let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.contains("NAME", "os"); ``` @@ -1443,7 +1465,7 @@ predicates.contains("NAME", "os"); beginsWith(field: string, value: string): RdbPredicates -Sets an **RdbPredicates** object to match the fields in the specified column that begin with the given value. +Creates an **RdbPredicates** object to search for the records in the specified column that begin with the given value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1452,7 +1474,7 @@ Sets an **RdbPredicates** object to match the fields in the specified column tha | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | string | Yes | Value to match the **RdbPredicates**.| +| value | string | Yes | Value to match.| **Return value** @@ -1471,7 +1493,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -// Locate data of the employees whose name begins with Li, for example, Lisa, in the table. +// Find all the records that start with "Li" in the NAME column, for example, Lisa. let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.beginsWith("NAME", "Li"); ``` @@ -1480,7 +1502,7 @@ predicates.beginsWith("NAME", "Li"); endsWith(field: string, value: string): RdbPredicates -Sets an **RdbPredicates** object to match the fields in the specified column that end with the given value. +Creates an **RdbPredicates** object to search for the records in the specified column that end with the given value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1489,7 +1511,7 @@ Sets an **RdbPredicates** object to match the fields in the specified column tha | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | string | Yes | Value to match the **RdbPredicates**.| +| value | string | Yes | Value to match.| **Return value** @@ -1508,7 +1530,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -// Locate data of the employees whose name ends with se, for example, Rose, in the table. +// Find all the records that end with "se" in the NAME column, for example, Rose. let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.endsWith("NAME", "se"); ``` @@ -1517,7 +1539,7 @@ predicates.endsWith("NAME", "se"); isNull(field: string): RdbPredicates -Sets an **RdbPredicates** object to match the fields in the specified column that are **null**. +Creates an **RdbPredicates** object to search for the records in the specified column that are **null**. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1552,7 +1574,7 @@ predicates.isNull("NAME"); isNotNull(field: string): RdbPredicates -Sets an **RdbPredicates** object to match the fields in the specified column that are not **null**. +Creates an **RdbPredicates** object to search for the records in the specified column that are not **null**. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1587,7 +1609,7 @@ predicates.isNotNull("NAME"); like(field: string, value: string): RdbPredicates -Sets an **RdbPredicates** object to match the fields in the specified column that are similar to the given value. +Creates an **RdbPredicates** object to search for the records in the specified column that are similar to the given value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1596,7 +1618,7 @@ Sets an **RdbPredicates** object to match the fields in the specified column tha | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | string | Yes | Value to match the **RdbPredicates**.| +| value | string | Yes | Value to match.| **Return value** @@ -1615,7 +1637,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -// Locate data of the employees whose name is similar to os in the table, for example, Rose. +// Find all the records that are similar to "os" in the NAME column, for example, Rose. let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.like("NAME", "%os%"); ``` @@ -1624,7 +1646,7 @@ predicates.like("NAME", "%os%"); glob(field: string, value: string): RdbPredicates -Sets an **RdbPredicates** object to locate the fields in the specified column that match the given string. +Creates an **RdbPredicates** object to search for the records in the specified column that match the given string. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1633,7 +1655,7 @@ Sets an **RdbPredicates** object to locate the fields in the specified column th | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | | field | string | Yes | Column name in the database table. | -| value | string | Yes | Value to match the **RdbPredicates**.

Wildcards are supported. * indicates zero, one, or multiple digits or characters. **?** indicates a single digit or character.| +| value | string | Yes | Value to match.

Wildcards are supported. * indicates zero, one, or multiple digits or characters. **?** indicates a single digit or character.| **Return value** @@ -1652,7 +1674,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -// Locate data of the employees whose name matches the "?h*g" string in the table. +// Find the strings that match "?h*g" in the NAME column. let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.glob("NAME", "?h*g"); ``` @@ -1661,7 +1683,7 @@ predicates.glob("NAME", "?h*g"); between(field: string, low: ValueType, high: ValueType): RdbPredicates -Sets an **RdbPredicates** object to match the fields in the specified column that are within the given range (including the min. and max. values). +Creates an **RdbPredicates** object to search for the records that are within the given range (including the min. and max. values) in the specified column. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1670,8 +1692,8 @@ Sets an **RdbPredicates** object to match the fields in the specified column tha | Name| Type | Mandatory| Description | | ------ | ----------------------- | ---- | -------------------------- | | field | string | Yes | Column name in the database table. | -| low | [ValueType](#valuetype) | Yes | Minimum value to match. | -| high | [ValueType](#valuetype) | Yes | Maximum value to match.| +| low | [ValueType](#valuetype) | Yes | Minimum value of the range to set. | +| high | [ValueType](#valuetype) | Yes | Maximum value of the range to set.| **Return value** @@ -1690,7 +1712,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -// Locate data of the employees with age between 10 and 50 (including 10 and 50) in the table. +// Find the records that are greater than or equal to 10 and less than or equal to 50 in the AGE column. let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.between("AGE", 10, 50); ``` @@ -1699,7 +1721,7 @@ predicates.between("AGE", 10, 50); notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates -Sets an **RdbPredicates** object to match the fields in the specified column that are out of the given range (excluding the min. and max. values). +Creates an **RdbPredicates** object to search for the records that are out of the given range (excluding the min. and max. values) in the specified column. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1708,8 +1730,8 @@ Sets an **RdbPredicates** object to match the fields in the specified column tha | Name| Type | Mandatory| Description | | ------ | ----------------------- | ---- | -------------------------- | | field | string | Yes | Column name in the database table. | -| low | [ValueType](#valuetype) | Yes | Minimum value to match. | -| high | [ValueType](#valuetype) | Yes | Maximum value to match.| +| low | [ValueType](#valuetype) | Yes | Minimum value of the range to set. | +| high | [ValueType](#valuetype) | Yes | Maximum value of the range to set.| **Return value** @@ -1728,7 +1750,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -// Locate data of the employees who are younger than 10 or older than 50 in the table. +// Find the records that are less than 10 or greater than 50 in the AGE column. let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.notBetween("AGE", 10, 50); ``` @@ -1737,7 +1759,7 @@ predicates.notBetween("AGE", 10, 50); greaterThan(field: string, value: ValueType): RdbPredicates -Sets an **RdbPredicates** object to match the fields in the specified column that are greater than the given value. +Creates an **RdbPredicates** object to search for the records that are greater than the given value in the specified column. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1746,7 +1768,7 @@ Sets an **RdbPredicates** object to match the fields in the specified column tha | Name| Type | Mandatory| Description | | ------ | ----------------------- | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | [ValueType](#valuetype) | Yes | Value to match the **RdbPredicates**.| +| value | [ValueType](#valuetype) | Yes | Value to match.| **Return value** @@ -1765,7 +1787,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -// Locate data of the employees who are older than 18 in the table. +// Find all the records that are greater than 18 in the AGE column. let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.greaterThan("AGE", 18); ``` @@ -1774,7 +1796,7 @@ predicates.greaterThan("AGE", 18); lessThan(field: string, value: ValueType): RdbPredicates -Sets an **RdbPredicates** object to match the fields in the specified column that are less than the given value. +Creates an **RdbPredicates** object to search for the records that are less than the given value in the specified column. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1783,7 +1805,7 @@ Sets an **RdbPredicates** object to match the fields in the specified column tha | Name| Type | Mandatory| Description | | ------ | ----------------------- | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | [ValueType](#valuetype) | Yes | Value to match the **RdbPredicates**.| +| value | [ValueType](#valuetype) | Yes | Value to match.| **Return value** @@ -1802,7 +1824,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -// Locate data of the employees who are younger than 20 in the table. +// Find all the records that are less than 20 in the AGE column. let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.lessThan("AGE", 20); ``` @@ -1811,7 +1833,7 @@ predicates.lessThan("AGE", 20); greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates -Sets an **RdbPredicates** object to match the fields in the specified column that are greater than or equal to the given value. +Creates an **RdbPredicates** object to search for the records that are greater than or equal to the given value in the specified column. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1820,7 +1842,7 @@ Sets an **RdbPredicates** object to match the fields in the specified column tha | Name| Type | Mandatory| Description | | ------ | ----------------------- | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | [ValueType](#valuetype) | Yes | Value to match the **RdbPredicates**.| +| value | [ValueType](#valuetype) | Yes | Value to match.| **Return value** @@ -1839,7 +1861,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -// Locate data of the employees who are 18 or older in the table. +// Find all the records that are greater than or equal to 18 in the AGE column. let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.greaterThanOrEqualTo("AGE", 18); ``` @@ -1848,7 +1870,7 @@ predicates.greaterThanOrEqualTo("AGE", 18); lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates -Sets an **RdbPredicates** object to match the fields in the specified column that are less than or equal to the given value. +Creates an **RdbPredicates** object to search for the records that are less than or equal to the given value in the specified column. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1857,7 +1879,7 @@ Sets an **RdbPredicates** object to match the fields in the specified column tha | Name| Type | Mandatory| Description | | ------ | ----------------------- | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | [ValueType](#valuetype) | Yes | Value to match the **RdbPredicates**.| +| value | [ValueType](#valuetype) | Yes | Value to match.| **Return value** @@ -1876,7 +1898,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -// Locate data of the employees who are 20 or younger in the table. +// Find all the records that are less than or equal to 20 in the AGE column. let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.lessThanOrEqualTo("AGE", 20); ``` @@ -1885,7 +1907,7 @@ predicates.lessThanOrEqualTo("AGE", 20); orderByAsc(field: string): RdbPredicates -Sets an **RdbPredicates** object to sort the fields in the specified column in ascending order. +Creates an **RdbPredicates** object to sort the records in the specified column in ascending order. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1920,7 +1942,7 @@ predicates.orderByAsc("NAME"); orderByDesc(field: string): RdbPredicates -Sets an **RdbPredicates** object to sort the fields in the specified column in descending order. +Creates an **RdbPredicates** object to sort the records in the specified column in descending order. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1955,7 +1977,7 @@ predicates.orderByDesc("AGE"); distinct(): RdbPredicates -Sets an **RdbPredicates** object to filter out duplicate records. +Creates an **RdbPredicates** object to filter out duplicate records. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1976,7 +1998,7 @@ predicates.equalTo("NAME", "Rose").distinct(); limitAs(value: number): RdbPredicates -Sets an **RdbPredicates** object to specify the maximum number of records. +Creates an **RdbPredicates** object to limit the number of data records. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1984,7 +2006,7 @@ Sets an **RdbPredicates** object to specify the maximum number of records. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------- | -| value | number | Yes | Maximum number of records.| +| value | number | Yes | Maximum number of data records. The value should be a positive integer. If a value less than or equal to **0** is specified, the number of records is not limited.| **Return value** @@ -2011,7 +2033,7 @@ predicates.equalTo("NAME", "Rose").limitAs(3); offsetAs(rowOffset: number): RdbPredicates -Sets an **RdbPredicates** object to specify the start position of the returned result. +Creates an **RdbPredicates** object to set the start position of the query result. This API must be used together with **limitAs**. Otherwise, no result will be returned. To query all rows after the specified offset, pass in **-1** in **limitAs**. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -2019,13 +2041,13 @@ Sets an **RdbPredicates** object to specify the start position of the returned r | Name | Type | Mandatory| Description | | --------- | ------ | ---- | ---------------------------------- | -| rowOffset | number | Yes | Number of rows to offset from the beginning. The value is a positive integer.| +| rowOffset | number | Yes | Start position to set. The value should be a positive integer. The start position of the result set is **0**. If a value less than or equal to **0** is specified, the query result is returned from the 0 index position.| **Return value** | Type | Description | | ------------------------------------ | ------------------------------------ | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the start position of the returned result.| +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the start position of the query result.| **Error codes** @@ -2039,14 +2061,14 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); -predicates.equalTo("NAME", "Rose").offsetAs(3); +predicates.equalTo("NAME", "Rose").limitAs(-1).offsetAs(3); ``` ### groupBy groupBy(fields: Array<string>): RdbPredicates -Sets an **RdbPredicates** object to group rows that have the same value into summary rows. +Creates an **RdbPredicates** object to group the query results based on the specified columns. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -2060,7 +2082,7 @@ Sets an **RdbPredicates** object to group rows that have the same value into sum | Type | Description | | ------------------------------------ | ---------------------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that groups rows with the same value.| +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Error codes** @@ -2081,7 +2103,7 @@ predicates.groupBy(["AGE", "NAME"]); indexedBy(field: string): RdbPredicates -Sets an **RdbPredicates** object to specify the index column. +Creates an **RdbPredicates** object to specify the index column. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -2096,7 +2118,7 @@ Sets an **RdbPredicates** object to specify the index column. | Type | Description | | ------------------------------------ | ------------------------------------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the index column.| +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Error codes** @@ -2117,7 +2139,7 @@ predicates.indexedBy("SALARY"); in(field: string, value: Array<ValueType>): RdbPredicates -Sets an **RdbPredicates** object to match the fields in the specified column that are in the given range. +Creates an **RdbPredicates** object to search for the records that are in the given range in the specified column. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -2145,7 +2167,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -// Locate data of the employees with age of [18, 20] in the table. +// Find records that are within [18, 20] in the AGE column. let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.in("AGE", [18, 20]); ``` @@ -2154,7 +2176,7 @@ predicates.in("AGE", [18, 20]); notIn(field: string, value: Array<ValueType>): RdbPredicates -Sets an **RdbPredicates** object to match the fields in the specified column that are out of the given range. +Creates an **RdbPredicates** object to search for the records that are out of the given range in the specified column. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -2182,7 +2204,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -// Locate data of all the employees except Lisa and Rose in the table. +// Find the records that are not within [Lisa, Rose] in the NAME column. let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.notIn("NAME", ["Lisa", "Rose"]); ``` @@ -2191,7 +2213,7 @@ predicates.notIn("NAME", ["Lisa", "Rose"]); notContains(field: string, value: string): RdbPredicates -Sets an **RdbPredicates** object to match the fields in the specified column that do not contain the given value. +Creates an **RdbPredicates** object to search for the records that do not contain the given value in the specified column. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -2200,7 +2222,7 @@ Sets an **RdbPredicates** object to match the fields in the specified column tha | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | string | Yes | Value to match the **RdbPredicates**.| +| value | string | Yes | Value to match.| **Return value** @@ -2219,7 +2241,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -// Match the fields that do not contain "os" in the NAME column of the data table, for example, Lisa in the list. +// Find the records that do not contain the string "os" in the NAME column, for example, Lisa. let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.notContains("NAME", "os"); ``` @@ -2228,7 +2250,7 @@ predicates.notContains("NAME", "os"); notLike(field: string, value: string): RdbPredicates -Sets an **RdbPredicates** object to match the fields in the specified column that are not similar to the given value. +Creates an **RdbPredicates** object to search for the records that are not similar to the given value in the specified column. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -2237,7 +2259,7 @@ Sets an **RdbPredicates** object to match the fields in the specified column tha | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | string | Yes | Value to match the **RdbPredicates**.| +| value | string | Yes | Value to match.| **Return value** @@ -2256,7 +2278,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -// Match the fields that are not "os" in the NAME column of the data table, for example, Rose in the list. +// Find the records that are not "os" in the NAME column, for example, Rose. let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.notLike("NAME", "os"); ``` @@ -2265,7 +2287,7 @@ predicates.notLike("NAME", "os"); ## RdbStore -Provides APIs to manage an RDB store. +Provides APIs for managing data in an RDB store. Before using the APIs of this class, use [executeSql](#executesql) to initialize the database table structure and related data. @@ -2303,12 +2325,36 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts // Set the RDB store version. -if(store != undefined) { - (store as relationalStore.RdbStore).version = 3; - // Obtain the RDB store version. - console.info(`RdbStore version is ${store.version}`); - // Whether the RDB store has been rebuilt. - console.info(`RdbStore rebuilt is ${store.rebuilt}`); +import { UIAbility } from '@kit.AbilityKit'; +import { BusinessError } from '@kit.BasicServicesKit'; +import { window } from '@kit.ArkUI'; + +let store: relationalStore.RdbStore | undefined = undefined; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + const STORE_CONFIG: relationalStore.StoreConfig = { + name: "RdbTest.db", + securityLevel: relationalStore.SecurityLevel.S3, + }; + const SQL_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB, IDENTITY UNLIMITED INT, ASSETDATA ASSET, ASSETSDATA ASSETS, FLOATARRAY floatvector(128))' + relationalStore.getRdbStore(this.context, STORE_CONFIG).then(async (rdbStore: relationalStore.RdbStore) => { + store = rdbStore; + await (store as relationalStore.RdbStore).executeSql(SQL_CREATE_TABLE); + console.info('Get RdbStore successfully.') + }).catch((err: BusinessError) => { + console.error(`Get RdbStore failed, code is ${err.code},message is ${err.message}`); + }) + + // Set the RDB store version. + if (store != undefined) { + (store as relationalStore.RdbStore).version = 3; + // Obtain the RDB store version. + console.info(`RdbStore version is ${store.version}`); + // Whether the RDB store has been rebuilt. + console.info(`RdbStore rebuilt is ${store.rebuilt}`); + } + } } ``` @@ -2383,7 +2429,7 @@ const valueBucket3: relationalStore.ValuesBucket = { "CODES": value4, }; -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).insert("EMPLOYEE", valueBucket1, (err: BusinessError, rowId: number) => { if (err) { console.error(`Insert is failed, code is ${err.code},message is ${err.message}`); @@ -2466,7 +2512,7 @@ const valueBucket3: relationalStore.ValuesBucket = { "CODES": value4, }; -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).insert("EMPLOYEE", valueBucket1, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE, (err: BusinessError, rowId: number) => { if (err) { @@ -2556,7 +2602,7 @@ const valueBucket3: relationalStore.ValuesBucket = { "CODES": value4, }; -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).insert("EMPLOYEE", valueBucket1).then((rowId: number) => { console.info(`Insert is successful, rowId = ${rowId}`); }).catch((err: BusinessError) => { @@ -2644,7 +2690,7 @@ const valueBucket3: relationalStore.ValuesBucket = { "CODES": value4, }; -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).insert("EMPLOYEE", valueBucket1, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE).then((rowId: number) => { console.info(`Insert is successful, rowId = ${rowId}`); }).catch((err: BusinessError) => { @@ -2667,7 +2713,7 @@ Inserts a row of data into a table. Due to the limit of the shared memory (max. | -------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | | table | string | Yes | Name of the target table. | | values | [ValuesBucket](#valuesbucket) | Yes | Row of data to insert. | -| conflict | [ConflictResolution](#conflictresolution10) | No | Resolution used to resolve the conflict. The default value is **relationalStore.ConflictResolution.ON_CONFLICT_NONE**.| +| conflict | [ConflictResolution](#conflictresolution10) | No | Resolution used to resolve the conflict.
Default value: **relationalStore.ConflictResolution.ON_CONFLICT_NONE**.| **Return value** @@ -2732,7 +2778,7 @@ const valueBucket3: relationalStore.ValuesBucket = { "CODES": value4, }; -if(store != undefined) { +if (store != undefined) { try { let rowId : number = (store as relationalStore.RdbStore).insertSync("EMPLOYEE", valueBucket1, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE); console.info(`Insert is successful, rowId = ${rowId}`); @@ -2756,7 +2802,7 @@ Inserts a row of Sendable data into a table. This API returns the result synchro | -------- | ---------------------------------------------------------------------------------------------- | ---- | ------------------------------------------------------------------------------- | | table | string | Yes | Name of the target table. | | values | [sendableRelationalStore.ValuesBucket](./js-apis-data-sendableRelationalStore.md#valuesbucket) | Yes | Sendable data to insert. | -| conflict | [ConflictResolution](#conflictresolution10) | No | Resolution used to resolve the conflict. The default value is **relationalStore.ConflictResolution.ON_CONFLICT_NONE**.| +| conflict | [ConflictResolution](#conflictresolution10) | No | Resolution used to resolve the conflict.
Default value: **relationalStore.ConflictResolution.ON_CONFLICT_NONE**.| **Return value** @@ -2804,7 +2850,7 @@ const valuesBucket: relationalStore.ValuesBucket = { }; const sendableValuesBucket = sendableRelationalStore.toSendableValuesBucket(valuesBucket); -if(store != undefined) { +if (store != undefined) { try { let rowId : number = (store as relationalStore.RdbStore).insertSync("EMPLOYEE", sendableValuesBucket, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE); console.info(`Insert is successful, rowId = ${rowId}`); @@ -2818,7 +2864,7 @@ if(store != undefined) { batchInsert(table: string, values: Array<ValuesBucket>, callback: AsyncCallback<number>):void -Batch inserts data into a table. This API uses an asynchronous callback to return the result. +Inserts a batch of data into a table. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -2894,7 +2940,7 @@ const valueBucket3: relationalStore.ValuesBucket = { }; let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).batchInsert("EMPLOYEE", valueBuckets, (err, insertNum) => { if (err) { console.error(`batchInsert is failed, code is ${err.code},message is ${err.message}`); @@ -2909,7 +2955,7 @@ if(store != undefined) { batchInsert(table: string, values: Array<ValuesBucket>):Promise<number> -Batch inserts data into a table. This API uses a promise to return the result. +Inserts a batch of data into a table. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -2991,7 +3037,7 @@ const valueBucket3: relationalStore.ValuesBucket = { }; let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).batchInsert("EMPLOYEE", valueBuckets).then((insertNum: number) => { console.info(`batchInsert is successful, the number of values that were inserted = ${insertNum}`); }).catch((err: BusinessError) => { @@ -3004,7 +3050,7 @@ if(store != undefined) { batchInsertSync(table: string, values: Array<ValuesBucket>):number -Inserts a row of data into a table. +Inserts a batch of data into a table. This API returns the result synchronously. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -3086,7 +3132,7 @@ const valueBucket3: relationalStore.ValuesBucket = { }; let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); -if(store != undefined) { +if (store != undefined) { try { let insertNum: number = (store as relationalStore.RdbStore).batchInsertSync("EMPLOYEE", valueBuckets); console.info(`batchInsert is successful, the number of values that were inserted = ${insertNum}`); @@ -3096,6 +3142,199 @@ if(store != undefined) { } ``` +### batchInsertWithConflictResolution18+ + +batchInsertWithConflictResolution(table: string, values: Array<ValuesBucket>, conflict: ConflictResolution): Promise<number> + +Inserts a batch of data into a table. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------ | ---- | ---------------------------- | +| table | string | Yes | Name of the target table. | +| values | Array<[ValuesBucket](#valuesbucket)> | Yes | An array of data to insert.| +| conflict | [ConflictResolution](#conflictresolution10) | Yes | Resolution used to resolve the conflict. | + +**Return value** + +| Type | Description | +| ------ | ---------------------------------------------- | +| Promise<number> | Promise used to return the result. If the operation is successful, the number of inserted data records is returned. Otherwise, **-1** is returned.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 14800000 | Inner error. | +| 14800011 | Database corrupted. | +| 14800014 | Already closed. | +| 14800015 | The database does not respond. | +| 14800021 | SQLite: Generic error. | +| 14800022 | SQLite: Callback routine requested an abort. | +| 14800023 | SQLite: Access permission denied. | +| 14800024 | SQLite: The database file is locked. | +| 14800025 | SQLite: A table in the database is locked. | +| 14800026 | SQLite: The database is out of memory. | +| 14800027 | SQLite: Attempt to write a readonly database. | +| 14800028 | SQLite: Some kind of disk I/O error occurred. | +| 14800029 | SQLite: The database is full. | +| 14800030 | SQLite: Unable to open the database file. | +| 14800031 | SQLite: TEXT or BLOB exceeds size limit. | +| 14800032 | SQLite: Abort due to constraint violation. | +| 14800033 | SQLite: Data type mismatch. | +| 14800034 | SQLite: Library used incorrectly. | +| 14800047 | The WAL file size exceeds the default limit. | + +**Example** + +```ts +import { BusinessError } from '@kit.BasicServicesKit'; + +let value1 = "Lisa"; +let value2 = 18; +let value3 = 100.5; +let value4 = new Uint8Array([1, 2, 3, 4, 5]); +let value5 = "Jack"; +let value6 = 19; +let value7 = 101.5; +let value8 = new Uint8Array([6, 7, 8, 9, 10]); +let value9 = "Tom"; +let value10 = 20; +let value11 = 102.5; +let value12 = new Uint8Array([11, 12, 13, 14, 15]); + +const valueBucket1: relationalStore.ValuesBucket = { + 'NAME': value1, + 'AGE': value2, + 'SALARY': value3, + 'CODES': value4, +}; +const valueBucket2: relationalStore.ValuesBucket = { + 'NAME': value5, + 'AGE': value6, + 'SALARY': value7, + 'CODES': value8, +}; +const valueBucket3: relationalStore.ValuesBucket = { + 'NAME': value9, + 'AGE': value10, + 'SALARY': value11, + 'CODES': value12, +}; + +let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); +if (store != undefined) { + (store as relationalStore.RdbStore).batchInsertWithConflictResolution("EMPLOYEE", valueBuckets, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE).then((insertNum: number) => { + console.info(`batchInsert is successful, insertNum = ${insertNum}`); + }).catch((err: BusinessError) => { + console.error(`batchInsert is failed, code is ${err.code},message is ${err.message}`); + }) +} +``` + +### batchInsertWithConflictResolutionSync18+ + +batchInsertWithConflictResolutionSync(table: string, values: Array<ValuesBucket>, conflict: ConflictResolution): number + +Inserts a batch of data into a table. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------ | ---- | ---------------------------- | +| table | string | Yes | Name of the target table. | +| values | Array<[ValuesBucket](#valuesbucket)> | Yes | An array of data to insert.| +| conflict | [ConflictResolution](#conflictresolution10) | Yes | Resolution used to resolve the conflict. | + +**Return value** + +| Type | Description | +| ------ | ---------------------------------------------- | +| number | If the operation is successful, the number of inserted data records is returned. Otherwise, **-1** is returned.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 14800000 | Inner error. | +| 14800011 | Database corrupted. | +| 14800014 | Already closed. | +| 14800015 | The database does not respond. | +| 14800021 | SQLite: Generic error. | +| 14800022 | SQLite: Callback routine requested an abort. | +| 14800023 | SQLite: Access permission denied. | +| 14800024 | SQLite: The database file is locked. | +| 14800025 | SQLite: A table in the database is locked. | +| 14800026 | SQLite: The database is out of memory. | +| 14800027 | SQLite: Attempt to write a readonly database. | +| 14800028 | SQLite: Some kind of disk I/O error occurred. | +| 14800029 | SQLite: The database is full. | +| 14800030 | SQLite: Unable to open the database file. | +| 14800031 | SQLite: TEXT or BLOB exceeds size limit. | +| 14800032 | SQLite: Abort due to constraint violation. | +| 14800033 | SQLite: Data type mismatch. | +| 14800034 | SQLite: Library used incorrectly. | +| 14800047 | The WAL file size exceeds the default limit. | + +**Example** + +```ts +import { BusinessError } from '@kit.BasicServicesKit'; + +let value1 = "Lisa"; +let value2 = 18; +let value3 = 100.5; +let value4 = new Uint8Array([1, 2, 3, 4, 5]); +let value5 = "Jack"; +let value6 = 19; +let value7 = 101.5; +let value8 = new Uint8Array([6, 7, 8, 9, 10]); +let value9 = "Tom"; +let value10 = 20; +let value11 = 102.5; +let value12 = new Uint8Array([11, 12, 13, 14, 15]); + +const valueBucket1: relationalStore.ValuesBucket = { + 'NAME': value1, + 'AGE': value2, + 'SALARY': value3, + 'CODES': value4, +}; +const valueBucket2: relationalStore.ValuesBucket = { + 'NAME': value5, + 'AGE': value6, + 'SALARY': value7, + 'CODES': value8, +}; +const valueBucket3: relationalStore.ValuesBucket = { + 'NAME': value9, + 'AGE': value10, + 'SALARY': value11, + 'CODES': value12, +}; + +let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); +if (store != undefined) { + try { + let insertNum: number = (store as relationalStore.RdbStore).batchInsertWithConflictResolutionSync("EMPLOYEE", valueBuckets, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE); + console.info(`batchInsert is successful, the number of values that were inserted = ${insertNum}`); + } catch (err) { + console.error(`batchInsert is failed, code is ${err.code},message is ${err.message}`); + } +} +``` + ### update update(values: ValuesBucket, predicates: RdbPredicates, callback: AsyncCallback<number>):void @@ -3170,7 +3409,7 @@ const valueBucket3: relationalStore.ValuesBucket = { let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Lisa"); -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).update(valueBucket1, predicates,(err, rows) => { if (err) { console.error(`Updated failed, code is ${err.code},message is ${err.message}`); @@ -3256,7 +3495,7 @@ const valueBucket3: relationalStore.ValuesBucket = { let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Lisa"); -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).update(valueBucket1, predicates, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE, (err, rows) => { if (err) { console.error(`Updated failed, code is ${err.code},message is ${err.message}`); @@ -3347,7 +3586,7 @@ const valueBucket3: relationalStore.ValuesBucket = { let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Lisa"); -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).update(valueBucket1, predicates).then(async (rows: Number) => { console.info(`Updated row count: ${rows}`); }).catch((err: BusinessError) => { @@ -3437,7 +3676,7 @@ const valueBucket3: relationalStore.ValuesBucket = { let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Lisa"); -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).update(valueBucket1, predicates, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE).then(async (rows: Number) => { console.info(`Updated row count: ${rows}`); }).catch((err: BusinessError) => { @@ -3460,7 +3699,7 @@ Updates data in the RDB store based on the specified **RdbPredicates** instance. | ---------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | | values | [ValuesBucket](#valuesbucket) | Yes | Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| | predicates | [RdbPredicates](#rdbpredicates) | Yes | Update conditions specified by the **RdbPredicates** object. | -| conflict | [ConflictResolution](#conflictresolution10) | No | Resolution used to resolve the conflict. The default value is **relationalStore.ConflictResolution.ON_CONFLICT_NONE**.| +| conflict | [ConflictResolution](#conflictresolution10) | No | Resolution used to resolve the conflict.
Default value: **relationalStore.ConflictResolution.ON_CONFLICT_NONE**.| **Return value** @@ -3527,7 +3766,7 @@ const valueBucket3: relationalStore.ValuesBucket = { let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Lisa"); -if(store != undefined) { +if (store != undefined) { try { let rows: Number = (store as relationalStore.RdbStore).updateSync(valueBucket1, predicates, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE); console.info(`Updated row count: ${rows}`); @@ -3584,7 +3823,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Lisa"); -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).delete(predicates, (err, rows) => { if (err) { console.error(`Delete failed, code is ${err.code},message is ${err.message}`); @@ -3649,7 +3888,7 @@ import { BusinessError } from '@kit.BasicServicesKit'; let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Lisa"); -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).delete(predicates).then((rows: Number) => { console.info(`Delete rows: ${rows}`); }).catch((err: BusinessError) => { @@ -3676,7 +3915,7 @@ Deletes data from the RDB store based on the specified **RdbPredicates** object. | Type | Description | | ------ | ------------------ | -| number | return the number of rows updated.| +| number | Number of rows updated.| **Error codes** @@ -3712,7 +3951,7 @@ import { BusinessError } from '@kit.BasicServicesKit'; let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Lisa"); -if(store != undefined) { +if (store != undefined) { try { let rows: Number = (store as relationalStore.RdbStore).deleteSync(predicates) console.info(`Delete rows: ${rows}`); @@ -3753,7 +3992,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Rose"); -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).query(predicates, (err, resultSet) => { if (err) { console.error(`Query failed, code is ${err.code},message is ${err.message}`); @@ -3806,7 +4045,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Rose"); -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], (err, resultSet) => { if (err) { console.error(`Query failed, code is ${err.code},message is ${err.message}`); @@ -3866,7 +4105,7 @@ import { BusinessError } from '@kit.BasicServicesKit'; let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Rose"); -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]).then((resultSet: relationalStore.ResultSet) => { console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); // resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0. @@ -3898,7 +4137,7 @@ Queries data in the RDB store based on specified conditions. This API returns th | Name | Type | Mandatory| Description | | ---------- | ------------------------------- | ---- | ------------------------------------------------------------ | | predicates | [RdbPredicates](#rdbpredicates) | Yes | Query conditions specified by the **RdbPredicates** object. | -| columns | Array<string> | No | Columns to query. If this parameter is not specified, the query applies to all columns. The default value is null.| +| columns | Array<string> | No | Columns to query. If this parameter is not specified, the query applies to all columns.
Default value: null.| **Error codes** @@ -3924,7 +4163,7 @@ import { BusinessError } from '@kit.BasicServicesKit'; let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Rose"); -if(store != undefined) { +if (store != undefined) { try { let resultSet: relationalStore.ResultSet = (store as relationalStore.RdbStore).querySync(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); @@ -3989,7 +4228,7 @@ let deviceId: string | undefined = undefined; try { dmInstance = distributedDeviceManager.createDeviceManager("com.example.appdatamgrverify"); let devices = dmInstance.getAvailableDeviceListSync(); - if(deviceId != undefined) { + if (deviceId != undefined) { deviceId = devices[0].networkId; } } catch (err) { @@ -4000,7 +4239,7 @@ try { let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); predicates.greaterThan("id", 0); -if(store != undefined && deviceId != undefined) { +if (store != undefined && deviceId != undefined) { (store as relationalStore.RdbStore).remoteQuery(deviceId, "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]).then((resultSet: relationalStore.ResultSet) => { console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); // resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0. @@ -4069,7 +4308,7 @@ let deviceId: string | undefined = undefined; try { dmInstance = distributedDeviceManager.createDeviceManager("com.example.appdatamgrverify"); let devices: Array = dmInstance.getAvailableDeviceListSync(); - if(devices != undefined) { + if (devices != undefined) { deviceId = devices[0].networkId; } } catch (err) { @@ -4080,7 +4319,7 @@ try { let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); predicates.greaterThan("id", 0); -if(store != undefined && deviceId != undefined) { +if (store != undefined && deviceId != undefined) { (store as relationalStore.RdbStore).remoteQuery(deviceId, "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]).then((resultSet: relationalStore.ResultSet) => { console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); // resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0. @@ -4105,7 +4344,9 @@ querySql(sql: string, callback: AsyncCallback<ResultSet>):void Queries data in the RDB store using the specified SQL statement. The number of relational operators between expressions and operators in the SQL statement cannot exceed 1000. This API uses an asynchronous callback to return the result. -[vector stores](#storeconfig) support standard syntax like **where**, **limit**, **offset**, **order by**, **group by**, and **having**, and special syntax **<->** and **<=>**, which are used to calculate vector similarity and cosine distance, respectively. +[Vector stores](#storeconfig) support standard syntax including **where**, **limit**, **offset**, **order by**, **group by**, and **having**, as well as extended syntax like **<->** (computing similarity) and **<=>** (computing cosine distance). This API can be used in aggregate functions (**max** and **min**), but cannot be used in aggregate functions like **sum**, **avg**, and **count** or basic functions (**random**, **abs**, **upper**, **lower**, and **length**). + +Aggregate functions cannot be nested. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -4132,7 +4373,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ RDB store: ```ts -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = 'sanguo'", (err, resultSet) => { if (err) { console.error(`Query failed, code is ${err.code},message is ${err.message}`); @@ -4175,7 +4416,9 @@ querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback& Queries data in the RDB store using the specified SQL statement. The number of relational operators between expressions and operators in the SQL statement cannot exceed 1000. This API uses an asynchronous callback to return the result. -[vector stores](#storeconfig) support standard syntax like **where**, **limit**, **offset**, **order by**, **group by**, and **having**, and special syntax **<->** and **<=>**, which are used to calculate vector similarity and cosine distance, respectively. +[Vector stores](#storeconfig) support standard syntax including **where**, **limit**, **offset**, **order by**, **group by**, and **having**, as well as extended syntax like **<->** (computing similarity) and **<=>** (computing cosine distance). This API can be used in aggregate functions (**max** and **min**), but cannot be used in aggregate functions like **sum**, **avg**, and **count** or basic functions (**random**, **abs**, **upper**, **lower**, and **length**). + +Aggregate functions cannot be nested. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -4201,7 +4444,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo'], (err, resultSet) => { if (err) { console.error(`Query failed, code is ${err.code},message is ${err.message}`); @@ -4228,7 +4471,9 @@ querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSet> Queries data in the RDB store using the specified SQL statement. The number of relational operators between expressions and operators in the SQL statement cannot exceed 1000. This API uses a promise to return the result. -[vector stores](#storeconfig) support standard syntax like **where**, **limit**, **offset**, **order by**, **group by**, and **having**, and special syntax **<->** and **<=>**, which are used to calculate vector similarity and cosine distance, respectively. +[Vector stores](#storeconfig) support standard syntax including **where**, **limit**, **offset**, **order by**, **group by**, and **having**, as well as extended syntax like **<->** (computing similarity) and **<=>** (computing cosine distance). This API can be used in aggregate functions (**max** and **min**), but cannot be used in aggregate functions like **sum**, **avg**, and **count** or basic functions (**random**, **abs**, **upper**, **lower**, and **length**). + +Aggregate functions cannot be nested. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -4263,7 +4508,7 @@ RDB store: ```ts import { BusinessError } from '@kit.BasicServicesKit'; -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = 'sanguo'").then((resultSet: relationalStore.ResultSet) => { console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); // resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0. @@ -4304,7 +4549,7 @@ Queries data in the RDB store using the specified SQL statement. The number of r | Name | Type | Mandatory| Description | | -------- | ------------------------------------ | ---- | ------------------------------------------------------------ | | sql | string | Yes | SQL statement to run. | -| bindArgs | Array<[ValueType](#valuetype)> | No | Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If the SQL parameter statement is complete, leave this parameter blank. The default value is null.| +| bindArgs | Array<[ValueType](#valuetype)> | No | Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If the SQL parameter statement is complete, leave this parameter blank.
Default value: null.| **Return value** @@ -4328,7 +4573,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts import { BusinessError } from '@kit.BasicServicesKit'; -if(store != undefined) { +if (store != undefined) { try { let resultSet: relationalStore.ResultSet = (store as relationalStore.RdbStore).querySqlSync("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = 'sanguo'"); console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); @@ -4399,7 +4644,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts const SQL_DELETE_TABLE = "DELETE FROM test WHERE name = 'zhangsan'" -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).executeSql(SQL_DELETE_TABLE, (err) => { if (err) { console.error(`ExecuteSql failed, code is ${err.code},message is ${err.message}`); @@ -4462,7 +4707,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts const SQL_DELETE_TABLE = "DELETE FROM test WHERE name = ?" -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).executeSql(SQL_DELETE_TABLE, ['zhangsan'], (err) => { if (err) { console.error(`ExecuteSql failed, code is ${err.code},message is ${err.message}`); @@ -4532,7 +4777,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ import { BusinessError } from '@kit.BasicServicesKit'; const SQL_DELETE_TABLE = "DELETE FROM test WHERE name = 'zhangsan'" -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).executeSql(SQL_DELETE_TABLE).then(() => { console.info('Delete table done.'); }).catch((err: BusinessError) => { @@ -4551,6 +4796,8 @@ This API can be used to add, delete, and modify data, run SQL statements of the This API does not support query, attach, or transaction operations. To perform these operations, use [querySql](#querysql10), [query](#query10), [attach](#attach12), [beginTransaction](#begintransaction), and [commit](#commit). +When this API is used to insert data originating from a subquery to a vector store, full-field insertion is supported, but partial-field insertion is not yet supported. + Statements separated by semicolons (\;) are not supported. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -4604,7 +4851,7 @@ RDB store: import { BusinessError } from '@kit.BasicServicesKit'; // Check the RDB store integrity. -if(store != undefined) { +if (store != undefined) { const SQL_CHECK_INTEGRITY = 'PRAGMA integrity_check'; (store as relationalStore.RdbStore).execute(SQL_CHECK_INTEGRITY).then((data) => { console.info(`check result: ${data}`); @@ -4614,7 +4861,7 @@ if(store != undefined) { } // Delete all data from the table. -if(store != undefined) { +if (store != undefined) { const SQL_DELETE_TABLE = 'DELETE FROM test'; (store as relationalStore.RdbStore).execute(SQL_DELETE_TABLE).then((data) => { console.info(`delete result: ${data}`); @@ -4624,7 +4871,7 @@ if(store != undefined) { } // Delete a table. -if(store != undefined) { +if (store != undefined) { const SQL_DROP_TABLE = 'DROP TABLE test'; (store as relationalStore.RdbStore).execute(SQL_DROP_TABLE).then((data) => { console.info(`drop result: ${data}`); @@ -4655,7 +4902,7 @@ execute(sql: string, txId: number, args?: Array<ValueType>): Promise<Va Executes an SQL statement that contains specified arguments. The number of relational operators between expressions and operators in the statement cannot exceed 1000. This API uses a promise to return the result. -This API supports only [vector stores](#storeconfig). +This API supports only [vector stores](#storeconfig). When this API is used to insert data originating from a subquery, full-field insertion is supported, but partial-field insertion is not yet supported. This API does not support data query. To query data, use [querySql](#querysql10). @@ -4669,7 +4916,7 @@ Statements separated by semicolons (\;) are not supported. | -------- | ------------------------------------ | ---- | ------------------------------------------------------------ | | sql | string | Yes | SQL statement to run. | | txId | number | Yes | Transaction ID obtained via [beginTrans](#begintrans12). If the value is **0**, the SQL statement is executed in a separate transaction by default. | -| args | Array<[ValueType](#valuetype)> | No | Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If this parameter is left blank or set to **null** or **undefined**, the SQL statement is complete.| +| args | Array<[ValueType](#valuetype)> | No | Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If this parameter is left blank or set to **null** or **undefined**, the SQL statement is considered complete.| **Return value** @@ -4709,7 +4956,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts import { BusinessError } from '@kit.BasicServicesKit'; -if(store != null) { +if (store != null) { let txId : number; (store as relationalStore.RdbStore).beginTrans().then((txId : number) => { (store as relationalStore.RdbStore).execute("DELETE FROM TEST WHERE age = ? OR age = ?", txId, ["18", "20"]) @@ -4743,7 +4990,7 @@ Statements separated by semicolons (\;) are not supported. | Name| Type | Mandatory| Description | | ------ | ------------------------------------ | ---- | ------------------------------------------------------------ | | sql | string | Yes | SQL statement to run. | -| args | Array<[ValueType](#valuetype)> | No | Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If this parameter is left blank or set to **null** or **undefined**, the SQL statement is complete. The default value is null.| +| args | Array<[ValueType](#valuetype)> | No | Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If this parameter is left blank or set to **null** or **undefined**, the SQL statement is complete.
Default value: null.| **Return value** @@ -4784,7 +5031,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ import { BusinessError } from '@kit.BasicServicesKit'; // Check the RDB store integrity. -if(store != undefined) { +if (store != undefined) { const SQL_CHECK_INTEGRITY = 'PRAGMA integrity_check'; try { let data = (store as relationalStore.RdbStore).executeSync(SQL_CHECK_INTEGRITY) @@ -4795,7 +5042,7 @@ if(store != undefined) { } // Delete all data from the table. -if(store != undefined) { +if (store != undefined) { const SQL_DELETE_TABLE = 'DELETE FROM test'; try { let data = (store as relationalStore.RdbStore).executeSync(SQL_DELETE_TABLE) @@ -4806,7 +5053,7 @@ if(store != undefined) { } // Delete a table. -if(store != undefined) { +if (store != undefined) { const SQL_DROP_TABLE = 'DROP TABLE test'; try { let data = (store as relationalStore.RdbStore).executeSync(SQL_DROP_TABLE) @@ -4865,7 +5112,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts let PRIKey = [1, 4, 2, 3]; -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).getModifyTime("EMPLOYEE", "NAME", PRIKey, (err, modifyTime: relationalStore.ModifyTime) => { if (err) { console.error(`getModifyTime failed, code is ${err.code},message is ${err.message}`); @@ -4931,7 +5178,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ import { BusinessError } from '@kit.BasicServicesKit'; let PRIKey = [1, 2, 3]; -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).getModifyTime("EMPLOYEE", "NAME", PRIKey) .then((modifyTime: relationalStore.ModifyTime) => { let size = modifyTime.size; @@ -4987,7 +5234,7 @@ let value2 = 18; let value3 = 100.5; let value4 = new Uint8Array([1, 2, 3]); -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).beginTransaction(); const valueBucket: relationalStore.ValuesBucket = { 'NAME': value1, @@ -5050,7 +5297,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts import { BusinessError } from '@kit.BasicServicesKit'; -if(store != null) { +if (store != null) { let txId : number; (store as relationalStore.RdbStore).beginTrans().then((txId : number) => { (store as relationalStore.RdbStore).execute("DELETE FROM TEST WHERE age = ? OR age = ?", txId, ["18", "20"]) @@ -5071,7 +5318,11 @@ createTransaction(options?: TransactionOptions): Promise<Transaction> Creates a transaction object and starts a transaction. This API uses a promise to return the result. -Different from [beginTransaction](#begintransaction), **createTransaction()** returns a transaction object, which is isolated from other transaction objects. A store supports a maximum of four transaction objects at a time. Exceeding the limit will return error 14800015. If this occurs, check for the transaction object that is being held too long or if there are too many concurrent transactions. If optimization is not possible, wait for other transactions to be released before creating a transaction object again. +Different from [beginTransaction](#begintransaction), **createTransaction()** returns a transaction object, which is isolated from other transaction objects. When a transaction object is used to insert, delete, or update data, these changes cannot be detected by [on ('dataChange')](#ondatachange). + +A store supports a maximum of four transaction objects at a time. If the number of transaction objects exceeds the upper limit, error 14800015 is returned. In this case, check whether transaction objects are being held too long or whether there are too many concurrent transactions. If the problem cannot be solved through these optimizations, you are advised to create transaction objects after existing transactions are released. + +You are advised to use **createTransaction** instead of **beginTransaction**. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -5109,7 +5360,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts import { BusinessError } from '@kit.BasicServicesKit'; -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { transaction.execute("DELETE FROM test WHERE age = ? OR age = ?", [21, 20]).then(() => { transaction.commit(); @@ -5167,7 +5418,7 @@ let value2 = 18; let value3 = 100.5; let value4 = new Uint8Array([1, 2, 3]); -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).beginTransaction(); const valueBucket: relationalStore.ValuesBucket = { 'NAME': value1, @@ -5232,7 +5483,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts import { BusinessError } from '@kit.BasicServicesKit'; -if(store != null) { +if (store != null) { let txId : number; (store as relationalStore.RdbStore).beginTrans().then((txId : number) => { (store as relationalStore.RdbStore).execute("DELETE FROM TEST WHERE age = ? OR age = ?", txId, ["18", "20"]) @@ -5292,7 +5543,7 @@ let value2 = 18; let value3 = 100.5; let value4 = new Uint8Array([1, 2, 3]); -if(store != undefined) { +if (store != undefined) { try { (store as relationalStore.RdbStore).beginTransaction() const valueBucket: relationalStore.ValuesBucket = { @@ -5364,7 +5615,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts import { BusinessError } from '@kit.BasicServicesKit'; -if(store != null) { +if (store != null) { let txId : number; (store as relationalStore.RdbStore).beginTrans().then((txId : number) => { (store as relationalStore.RdbStore).execute("DELETE FROM TEST WHERE age = ? OR age = ?", txId, ["18", "20"]) @@ -5424,7 +5675,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).backup("dbBackup.db", (err) => { if (err) { console.error(`Backup failed, code is ${err.code},message is ${err.message}`); @@ -5486,7 +5737,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts import { BusinessError } from '@kit.BasicServicesKit'; -if(store != undefined) { +if (store != undefined) { let promiseBackup = (store as relationalStore.RdbStore).backup("dbBackup.db"); promiseBackup.then(() => { console.info('Backup success.'); @@ -5540,7 +5791,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).restore("dbBackup.db", (err) => { if (err) { console.error(`Restore failed, code is ${err.code},message is ${err.message}`); @@ -5602,7 +5853,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts import { BusinessError } from '@kit.BasicServicesKit'; -if(store != undefined) { +if (store != undefined) { let promiseRestore = (store as relationalStore.RdbStore).restore("dbBackup.db"); promiseRestore.then(() => { console.info('Restore success.'); @@ -5643,7 +5894,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).setDistributedTables(["EMPLOYEE"], (err) => { if (err) { console.error(`SetDistributedTables failed, code is ${err.code},message is ${err.message}`); @@ -5692,7 +5943,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts import { BusinessError } from '@kit.BasicServicesKit'; -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).setDistributedTables(["EMPLOYEE"]).then(() => { console.info('SetDistributedTables successfully.'); }).catch((err: BusinessError) => { @@ -5734,7 +5985,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).setDistributedTables(["EMPLOYEE"], relationalStore.DistributedType.DISTRIBUTED_CLOUD, (err) => { if (err) { console.error(`SetDistributedTables failed, code is ${err.code},message is ${err.message}`); @@ -5779,7 +6030,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).setDistributedTables(["EMPLOYEE"], relationalStore.DistributedType.DISTRIBUTED_CLOUD, { autoSync: true }, (err) => { @@ -5807,7 +6058,7 @@ Sets distributed tables. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ------ | ----------------------------------------- | ---- | ------------------------------------------------------------ | | tables | Array<string> | Yes | Names of the distributed tables to set. | -| type | [DistributedType](#distributedtype10) | No | Distributed type of the tables. The default value is **relationalStore.DistributedType.DISTRIBUTED_DEVICE**.| +| type | [DistributedType](#distributedtype10) | No | Distributed type of the tables.
Default value: **relationalStore.DistributedType.DISTRIBUTED_DEVICE**.| | config | [DistributedConfig](#distributedconfig10) | No | Configuration of the distributed mode. If this parameter is not specified, the value of **autoSync** is **false** by default, which means only manual sync is supported.| **Return value** @@ -5833,7 +6084,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts import { BusinessError } from '@kit.BasicServicesKit'; -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).setDistributedTables(["EMPLOYEE"], relationalStore.DistributedType.DISTRIBUTED_CLOUD, { autoSync: true }).then(() => { @@ -5896,7 +6147,7 @@ try { console.error("createDeviceManager errCode:" + code + ",errMessage:" + message); } -if(store != undefined && deviceId != undefined) { +if (store != undefined && deviceId != undefined) { (store as relationalStore.RdbStore).obtainDistributedTableName(deviceId, "EMPLOYEE", (err, tableName) => { if (err) { console.error(`ObtainDistributedTableName failed, code is ${err.code},message is ${err.message}`); @@ -5964,7 +6215,7 @@ try { console.error("createDeviceManager errCode:" + code + ",errMessage:" + message); } -if(store != undefined && deviceId != undefined) { +if (store != undefined && deviceId != undefined) { (store as relationalStore.RdbStore).obtainDistributedTableName(deviceId, "EMPLOYEE").then((tableName: string) => { console.info(`ObtainDistributedTableName successfully, tableName= ${tableName}`); }).catch((err: BusinessError) => { @@ -6025,7 +6276,7 @@ try { let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); predicates.inDevices(deviceIds); -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).sync(relationalStore.SyncMode.SYNC_MODE_PUSH, predicates, (err, result) => { if (err) { console.error(`Sync failed, code is ${err.code},message is ${err.message}`); @@ -6096,7 +6347,7 @@ try { let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); predicates.inDevices(deviceIds); -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).sync(relationalStore.SyncMode.SYNC_MODE_PUSH, predicates).then((result: Object[][]) => { console.info('Sync done.'); for (let i = 0; i < result.length; i++) { @@ -6137,7 +6388,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, (progressDetails) => { console.info(`Progess: ${progressDetails}`); }, (err) => { @@ -6186,7 +6437,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts import { BusinessError } from '@kit.BasicServicesKit'; -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, (progressDetail: relationalStore.ProgressDetails) => { console.info(`progress: ${progressDetail}`); }).then(() => { @@ -6229,7 +6480,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts const tables = ["table1", "table2"]; -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, tables, (progressDetail: relationalStore.ProgressDetails) => { console.info(`Progess: ${progressDetail}`); }, (err) => { @@ -6281,7 +6532,7 @@ import { BusinessError } from '@kit.BasicServicesKit'; const tables = ["table1", "table2"]; -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, tables, (progressDetail: relationalStore.ProgressDetails) => { console.info(`progress: ${progressDetail}`); }).then(() => { @@ -6385,7 +6636,7 @@ let storeObserver = (devices: Array) => { } try { - if(store != undefined) { + if (store != undefined) { (store as relationalStore.RdbStore).on('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver); } } catch (err) { @@ -6407,7 +6658,7 @@ let changeInfos = (changeInfos: Array) => { } try { - if(store != undefined) { + if (store != undefined) { (store as relationalStore.RdbStore).on('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_LOCAL_DETAILS, changeInfos); } } catch (err) { @@ -6429,7 +6680,7 @@ try { 'blobType': value4, }; - if(store != undefined) { + if (store != undefined) { (store as relationalStore.RdbStore).insert('test', valueBucket); } } catch (err) { @@ -6451,7 +6702,7 @@ Subscribes to process events. This callback is invoked by [emit](#emit10). | Name | Type | Mandatory| Description | | ------------ | --------------- | ---- | ------------------------------------------------------------ | -| event | string | Yes | Event name to observe. | +| event | string | Yes | Event name, which must match the event type in **emit**. | | interProcess | boolean | Yes | Type of the data to observe.
The value **true** means inter-process events.
The value **false** means intra-process events.| | observer | Callback\ | Yes | Callback used to return the result. | @@ -6477,7 +6728,7 @@ let storeObserver = () => { } try { - if(store != undefined) { + if (store != undefined) { (store as relationalStore.RdbStore).on('storeObserver', false, storeObserver); } } catch (err) { @@ -6522,7 +6773,7 @@ let progressDetail = (progressDetail: relationalStore.ProgressDetails) => { } try { - if(store != undefined) { + if (store != undefined) { (store as relationalStore.RdbStore).on('autoSyncProgress', progressDetail) } } catch (err) { @@ -6572,7 +6823,7 @@ let sqlExecutionInfo = (sqlExecutionInfo: relationalStore.SqlExecutionInfo) => { } try { - if(store != undefined) { + if (store != undefined) { (store as relationalStore.RdbStore).on('statistics', sqlExecutionInfo); } } catch (err) { @@ -6593,7 +6844,7 @@ try { 'SALARY': value3, 'CODES': value4, }; - if(store != undefined) { + if (store != undefined) { (store as relationalStore.RdbStore).insert('test', valueBucket); } } catch (err) { @@ -6652,7 +6903,7 @@ try { } try { - if(store != undefined) { + if (store != undefined) { (store as relationalStore.RdbStore).off('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver); } } catch (err) { @@ -6704,7 +6955,7 @@ let storeObserver = (devices: Array) => { } try { - if(store != undefined) { + if (store != undefined) { (store as relationalStore.RdbStore).on('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver); } } catch (err) { @@ -6714,7 +6965,7 @@ try { } try { - if(store != undefined) { + if (store != undefined) { (store as relationalStore.RdbStore).off('dataChange', relationalStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver); } } catch (err) { @@ -6736,7 +6987,7 @@ Unsubscribes from process events. | Name | Type | Mandatory| Description | | ------------ | --------------- | ---- | ------------------------------------------------------------ | -| event | string | Yes | Name of the event. | +| event | string | Yes | Event name, which must match the event type in **on()**.| | interProcess | boolean | Yes | Type of the data to observe.
The value **true** means inter-process events.
The value **false** means intra-process events.| | observer | Callback\ | No | Callback to unregister. If this parameter is not specified, this API unregisters all callbacks for the specified event.| @@ -6762,7 +7013,7 @@ let storeObserver = () => { } try { - if(store != undefined) { + if (store != undefined) { (store as relationalStore.RdbStore).on('storeObserver', false, storeObserver); } } catch (err) { @@ -6772,7 +7023,7 @@ try { } try { - if(store != undefined) { + if (store != undefined) { (store as relationalStore.RdbStore).off('storeObserver', false, storeObserver); } } catch (err) { @@ -6817,7 +7068,7 @@ let progressDetail = (progressDetail: relationalStore.ProgressDetails) => { } try { - if(store != undefined) { + if (store != undefined) { (store as relationalStore.RdbStore).on('autoSyncProgress', progressDetail) } } catch (err) { @@ -6827,7 +7078,7 @@ try { } try { - if(store != undefined) { + if (store != undefined) { (store as relationalStore.RdbStore).off('autoSyncProgress', progressDetail); } } catch (err) { @@ -6868,7 +7119,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ import { BusinessError } from '@kit.BasicServicesKit'; try { - if(store != undefined) { + if (store != undefined) { (store as relationalStore.RdbStore).off('statistics'); } } catch (err) { @@ -6890,7 +7141,7 @@ Triggers the inter-process or intra-process event listener registered in [on](#o | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------- | -| event | string | Yes | Name of the event.| +| event | string | Yes | Event name. Custom event names are allowed. However, the customized event name cannot be duplicate with the existing event names [dataChange](#ondatachange), [autoSyncProgress](#onautosyncprogress11) and [statistics](#onstatistics12).| **Error codes** @@ -6908,7 +7159,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).emit('storeObserver'); } ``` @@ -6959,7 +7210,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).cleanDirtyData('test_table', 100, (err) => { if (err) { console.error(`clean dirty data failed, code is ${err.code},message is ${err.message}`); @@ -7015,7 +7266,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).cleanDirtyData('test_table', (err) => { if (err) { console.error(`clean dirty data failed, code is ${err.code},message is ${err.message}`); @@ -7078,7 +7329,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts import { BusinessError } from '@kit.BasicServicesKit'; -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).cleanDirtyData('test_table', 100).then(() => { console.info('clean dirty data succeeded'); }).catch ((err: BusinessError) => { @@ -7150,7 +7401,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ // Attach a non-encrypted RDB store to a non-encrypted RDB store. import { BusinessError } from '@kit.BasicServicesKit'; -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).attach("/path/rdbstore1.db", "attachDB").then((number: number) => { console.info('attach succeeded'); }).catch ((err: BusinessError) => { @@ -7238,7 +7489,7 @@ relationalStore.getRdbStore(this.context, STORE_CONFIG1).then(async (rdbStore: r console.error(`Get RdbStore failed, code is ${err.code},message is ${err.message}`); }) -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).attach(this.context, STORE_CONFIG1, "attachDB").then((number: number) => { console.info(`attach succeeded, number is ${number}`); }).catch ((err: BusinessError) => { @@ -7268,7 +7519,7 @@ relationalStore.getRdbStore(this.context, STORE_CONFIG2).then(async (rdbStore: r console.error(`Get RdbStore failed, code is ${err.code},message is ${err.message}`); }) -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).attach(this.context, STORE_CONFIG2, "attachDB2", 10).then((number: number) => { console.info(`attach succeeded, number is ${number}`); }).catch ((err: BusinessError) => { @@ -7333,7 +7584,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts import { BusinessError } from '@kit.BasicServicesKit'; -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).detach("attachDB").then((number: number) => { console.info(`detach succeeded, number is ${number}`); }).catch ((err: BusinessError) => { @@ -7400,7 +7651,7 @@ import { BusinessError } from '@kit.BasicServicesKit'; let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Lisa"); -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).lockRow(predicates).then(() => { console.info(`Lock success`); }).catch((err: BusinessError) => { @@ -7467,7 +7718,7 @@ import { BusinessError } from '@kit.BasicServicesKit'; let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Lisa"); -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).unlockRow(predicates).then(() => { console.info(`Unlock success`); }).catch((err: BusinessError) => { @@ -7531,7 +7782,7 @@ import { BusinessError } from '@kit.BasicServicesKit'; let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Rose"); -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).queryLockedRow(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]).then((resultSet: relationalStore.ResultSet) => { console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); // resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0. @@ -7577,7 +7828,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts import { BusinessError } from '@kit.BasicServicesKit'; -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).close().then(() => { console.info(`close succeeded`); }).catch ((err: BusinessError) => { @@ -7596,35 +7847,73 @@ Obtain the **resultSet** object first. **Example** - ```ts -let resultSet: relationalStore.ResultSet | undefined = undefined; -let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); -predicates.equalTo("AGE", 18); -if(store != undefined) { - (store as relationalStore.RdbStore).query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]).then((result: relationalStore.ResultSet) => { - resultSet = result; - console.info(`resultSet columnNames: ${resultSet.columnNames}`); - console.info(`resultSet columnCount: ${resultSet.columnCount}`); - }); -} -``` - -### Properties +import { UIAbility } from '@kit.AbilityKit'; +import { BusinessError } from '@kit.BasicServicesKit'; +import { window } from '@kit.ArkUI'; -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core +let store: relationalStore.RdbStore | undefined = undefined; -| Name | Type | Mandatory| Description | -| ------------ | ------------------- | ---- | -------------------------------- | +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + const STORE_CONFIG: relationalStore.StoreConfig = { + name: "RdbTest.db", + securityLevel: relationalStore.SecurityLevel.S3, + }; + + relationalStore.getRdbStore(this.context, STORE_CONFIG).then(async (rdbStore: relationalStore.RdbStore) => { + store = rdbStore; + const asset: relationalStore.Asset = { + name: "name", + uri: "uri", + createTime: "createTime", + modifyTime: "modifyTime", + size: "size", + path: "path", + }; + const assets: relationalStore.Assets = [asset]; + const valueBucket: relationalStore.ValuesBucket = { + "NAME": "hello world", + "AGE": 3, + "SALARY": 0.5, + "CODES": new Uint8Array([1, 2, 3]), + "IDENTITY":100n, + "ASSETDATA":asset, + "ASSETSDATA":assets, + "FLOATARRAY":new Float32Array([1.5, 2.5]), + }; + (store as relationalStore.RdbStore).insertSync("EMPLOYEE", valueBucket); + let resultSet: relationalStore.ResultSet | undefined = undefined; + let predicates: relationalStore.RdbPredicates = new relationalStore.RdbPredicates("EMPLOYEE"); + let columns: Array = ["ID", "NAME", "AGE", "SALARY", "CODES", "IDENTITY", "ASSETDATA", "ASSETSDATA", "FLOATARRAY"]; + await (store as relationalStore.RdbStore).query(predicates, columns).then(async (result: relationalStore.ResultSet) => { + resultSet = result; + console.info(`resultSet columnNames: ${resultSet.columnNames}`); + console.info(`resultSet columnCount: ${resultSet.columnCount}`); + }); + console.info('Get RdbStore successfully.'); + }).catch((err: BusinessError) => { + console.error(`Get RdbStore failed, code is ${err.code},message is ${err.message}`); + }) + } +} +``` + +### Properties + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Type | Mandatory| Description | +| ------------ | ------------------- | ---- | -------------------------------- | | columnNames | Array<string> | Yes | Names of all columns in the result set. | | columnCount | number | Yes | Number of columns in the result set. | | rowCount | number | Yes | Number of rows in the result set. | -| rowIndex | number | Yes | Index of the current row in the result set. | -| isAtFirstRow | boolean | Yes | Whether the cursor is in the first row of the result set. | -| isAtLastRow | boolean | Yes | Whether the cursor is in the last row of the result set. | -| isEnded | boolean | Yes | Whether the cursor is after the last row of the result set.| -| isStarted | boolean | Yes | Whether the cursor has been moved. | -| isClosed | boolean | Yes | Whether the result set is closed. | +| rowIndex | number | Yes | Index of the current row in the result set.
Default value: **-1**. The index position starts from **0**.| +| isAtFirstRow | boolean | Yes | Whether the result set pointer is in the first row (the row index is **0**). The value **true** means the result set pointer is in the first row.| +| isAtLastRow | boolean | Yes | Whether the result set pointer is in the last row. The value **true** means the pointer is in the last row.| +| isEnded | boolean | Yes | Whether the result set pointer is after the last row. The value **true** means the pointer is after the last row.| +| isStarted | boolean | Yes | Whether the result set pointer is moved. The value **true** means the pointer is moved. | +| isClosed | boolean | Yes | Whether the result set is closed. The value **true** means the result set is closed. | ### getColumnIndex @@ -7676,7 +7965,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -if(resultSet != undefined) { +if (resultSet != undefined) { const id = (resultSet as relationalStore.ResultSet).getLong((resultSet as relationalStore.ResultSet).getColumnIndex("ID")); const name = (resultSet as relationalStore.ResultSet).getString((resultSet as relationalStore.ResultSet).getColumnIndex("NAME")); const age = (resultSet as relationalStore.ResultSet).getLong((resultSet as relationalStore.ResultSet).getColumnIndex("AGE")); @@ -7734,18 +8023,146 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -if(resultSet != undefined) { +if (resultSet != undefined) { const id = (resultSet as relationalStore.ResultSet).getColumnName(0); const name = (resultSet as relationalStore.ResultSet).getColumnName(1); const age = (resultSet as relationalStore.ResultSet).getColumnName(2); } ``` +### getColumnType18+ + +getColumnType(columnIdentifier: number | string): Promise\ + +Obtains the column data type based on the specified column index or column name. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------------- | ---------------- | ---- | ------------------------------------------------------------ | +| columnIdentifier | number \| string | Yes | Index or name of column in a result set. The index must be a non-negative integer and cannot exceed the length of **columnNames**. The column name must be a name in **columnNames**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | ----------------------------------- | +| Promise<[ColumnType](#columntype18)> | Promise used to return the data type obtained.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 14800000 | Inner error. | +| 14800011 | Database corrupted. | +| 14800012 | Row out of bounds. | +| 14800013 | Column out of bounds. | +| 14800014 | Already closed. | +| 14800019 | The SQL must be a query statement. | +| 14800021 | SQLite: Generic error. | +| 14800022 | SQLite: Callback routine requested an abort. | +| 14800023 | SQLite: Access permission denied. | +| 14800024 | SQLite: The database file is locked. | +| 14800025 | SQLite: A table in the database is locked. | +| 14800026 | SQLite: The database is out of memory. | +| 14800027 | SQLite: Attempt to write a readonly database. | +| 14800028 | SQLite: Some kind of disk I/O error occurred. | +| 14800029 | SQLite: The database is full. | +| 14800030 | SQLite: Unable to open the database file. | +| 14800031 | SQLite: TEXT or BLOB exceeds size limit. | +| 14800032 | SQLite: Abort due to constraint violation. | +| 14800033 | SQLite: Data type mismatch. | +| 14800034 | SQLite: Library used incorrectly. | + +**Example** + +```ts +if (resultSet != undefined) { + let idType = await (resultSet as relationalStore.ResultSet).getColumnType("ID") as relationalStore.ColumnType; + let nameType = await (resultSet as relationalStore.ResultSet).getColumnType("NAME") as relationalStore.ColumnType; + let ageType = await (resultSet as relationalStore.ResultSet).getColumnType("AGE") as relationalStore.ColumnType; + let salaryType = await (resultSet as relationalStore.ResultSet).getColumnType("SALARY") as relationalStore.ColumnType; + let codesType = await (resultSet as relationalStore.ResultSet).getColumnType("CODES") as relationalStore.ColumnType; + let identityType = await (resultSet as relationalStore.ResultSet).getColumnType(5) as relationalStore.ColumnType; + let assetDataType = await (resultSet as relationalStore.ResultSet).getColumnType(6) as relationalStore.ColumnType; + let assetsDataType = await (resultSet as relationalStore.ResultSet).getColumnType(7) as relationalStore.ColumnType; + let floatArrayType = await (resultSet as relationalStore.ResultSet).getColumnType(8) as relationalStore.ColumnType; +} +``` + +### getColumnTypeSync18+ + +getColumnTypeSync(columnIdentifier: number | string): ColumnType + +Obtains the column data type based on the specified column index or column name. This API returns the result synchronously. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------------- | ---------------- | ---- | ------------------------------------------------------------ | +| columnIdentifier | number \| string | Yes | Index or name of column in a result set. The index must be a non-negative integer and cannot exceed the length of **columnNames**. The column name must be a name in **columnNames**.| + +**Return value** + +| Type | Description | +| --------------------------- | ---------------------- | +| [ColumnType](#columntype18) | Data type obtained.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 14800000 | Inner error. | +| 14800011 | Database corrupted. | +| 14800012 | Row out of bounds. | +| 14800013 | Column out of bounds. | +| 14800014 | Already closed. | +| 14800019 | The SQL must be a query statement. | +| 14800021 | SQLite: Generic error. | +| 14800022 | SQLite: Callback routine requested an abort. | +| 14800023 | SQLite: Access permission denied. | +| 14800024 | SQLite: The database file is locked. | +| 14800025 | SQLite: A table in the database is locked. | +| 14800026 | SQLite: The database is out of memory. | +| 14800027 | SQLite: Attempt to write a readonly database. | +| 14800028 | SQLite: Some kind of disk I/O error occurred. | +| 14800029 | SQLite: The database is full. | +| 14800030 | SQLite: Unable to open the database file. | +| 14800031 | SQLite: TEXT or BLOB exceeds size limit. | +| 14800032 | SQLite: Abort due to constraint violation. | +| 14800033 | SQLite: Data type mismatch. | +| 14800034 | SQLite: Library used incorrectly. | + +**Example** + +```ts +if (resultSet != undefined) { + let idType = (resultSet as relationalStore.ResultSet).getColumnTypeSync("ID") as relationalStore.ColumnType; + let nameType = (resultSet as relationalStore.ResultSet).getColumnTypeSync("NAME") as relationalStore.ColumnType; + let ageType = (resultSet as relationalStore.ResultSet).getColumnTypeSync("AGE") as relationalStore.ColumnType; + let salaryType = (resultSet as relationalStore.ResultSet).getColumnTypeSync("SALARY") as relationalStore.ColumnType; + let codesType = (resultSet as relationalStore.ResultSet).getColumnTypeSync("CODES") as relationalStore.ColumnType; + let identityType = (resultSet as relationalStore.ResultSet).getColumnTypeSync(5) as relationalStore.ColumnType; + let assetDataType = (resultSet as relationalStore.ResultSet).getColumnTypeSync(6) as relationalStore.ColumnType; + let assetsDataType = (resultSet as relationalStore.ResultSet).getColumnTypeSync(7) as relationalStore.ColumnType; + let floatArrayType = (resultSet as relationalStore.ResultSet).getColumnTypeSync(8) as relationalStore.ColumnType; +} +``` + ### goTo goTo(offset:number): boolean -Moves the cursor to the row based on the specified offset. +Moves the result set pointer based on the offset specified. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -7753,7 +8170,7 @@ Moves the cursor to the row based on the specified offset. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------------------- | -| offset | number | Yes | Offset relative to the current position.| +| offset | number | Yes | Offset relative to the position of the current result set pointer. A positive value means to move the pointer backward, and a negative value means to move the pointer forward.| **Return value** @@ -7791,7 +8208,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -if(resultSet != undefined) { +if (resultSet != undefined) { (resultSet as relationalStore.ResultSet).goTo(1); } ``` @@ -7846,7 +8263,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -if(resultSet != undefined) { +if (resultSet != undefined) { (resultSet as relationalStore.ResultSet).goToRow(5); } ``` @@ -7895,7 +8312,7 @@ For details about the error codes, see [RDB Error Codes](errorcode-data-rdb.md). **Example** ```ts -if(resultSet != undefined) { +if (resultSet != undefined) { (resultSet as relationalStore.ResultSet).goToFirstRow(); } ``` @@ -7943,7 +8360,7 @@ For details about the error codes, see [RDB Error Codes](errorcode-data-rdb.md). **Example** ```ts -if(resultSet != undefined) { +if (resultSet != undefined) { (resultSet as relationalStore.ResultSet).goToLastRow(); } ``` @@ -7991,7 +8408,7 @@ For details about the error codes, see [RDB Error Codes](errorcode-data-rdb.md). **Example** ```ts -if(resultSet != undefined) { +if (resultSet != undefined) { (resultSet as relationalStore.ResultSet).goToNextRow(); } ``` @@ -8039,7 +8456,7 @@ For details about the error codes, see [RDB Error Codes](errorcode-data-rdb.md). **Example** ```ts -if(resultSet != undefined) { +if (resultSet != undefined) { (resultSet as relationalStore.ResultSet).goToPreviousRow(); } ``` @@ -8094,7 +8511,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -if(resultSet != undefined) { +if (resultSet != undefined) { const codes = (resultSet as relationalStore.ResultSet).getValue((resultSet as relationalStore.ResultSet).getColumnIndex("BIGINT_COLUMN")); } ``` @@ -8150,7 +8567,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -if(resultSet != undefined) { +if (resultSet != undefined) { const codes = (resultSet as relationalStore.ResultSet).getBlob((resultSet as relationalStore.ResultSet).getColumnIndex("CODES")); } ``` @@ -8205,7 +8622,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -if(resultSet != undefined) { +if (resultSet != undefined) { const name = (resultSet as relationalStore.ResultSet).getString((resultSet as relationalStore.ResultSet).getColumnIndex("NAME")); } ``` @@ -8260,9 +8677,9 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -if(resultSet != undefined) { +if (resultSet != undefined) { const age = (resultSet as relationalStore.ResultSet).getLong((resultSet as relationalStore.ResultSet).getColumnIndex("AGE")); - } +} ``` ### getDouble @@ -8315,7 +8732,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -if(resultSet != undefined) { +if (resultSet != undefined) { const salary = (resultSet as relationalStore.ResultSet).getDouble((resultSet as relationalStore.ResultSet).getColumnIndex("SALARY")); } ``` @@ -8370,7 +8787,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -if(resultSet != undefined) { +if (resultSet != undefined) { const doc = (resultSet as relationalStore.ResultSet).getAsset((resultSet as relationalStore.ResultSet).getColumnIndex("DOC")); } ``` @@ -8425,7 +8842,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -if(resultSet != undefined) { +if (resultSet != undefined) { const docs = (resultSet as relationalStore.ResultSet).getAssets((resultSet as relationalStore.ResultSet).getColumnIndex("DOCS")); } ``` @@ -8473,12 +8890,12 @@ For details about the error codes, see [RDB Error Codes](errorcode-data-rdb.md). **Example** ```ts -if(resultSet != undefined) { +if (resultSet != undefined) { const row = (resultSet as relationalStore.ResultSet).getRow(); } ``` -### getRows16+ +### getRows18+ getRows(maxCount: number, position?: number): Promise> @@ -8491,7 +8908,7 @@ Obtains a specified amount of data from the result set. This API uses a promise | Name | Type | Mandatory| Description | | ----------- | ------ | ---- | ----------------------- | | maxCount | number | Yes | Number of rows to obtain. The value is a positive integer. If the value is not a positive integer, error 401 will be thrown.| -| position | number | No | Start position for obtaining data from the result set. The value is a non-negative integer. If this parameter is not specified, data is obtained from the current row of the result set (by default, it is the first row of the current result set when data is obtained for the first time). If it is not a non-negative integer, error 401 will be thrown.| +| position | number | No | Start position for obtaining data from the result set. The value is a non-negative integer. If this parameter is not specified, data is obtained from the current row of the result set (by default, it is the first row of the result set when data is obtained for the first time). If it is not a non-negative integer, error code 401 will be thrown.| **Return value** @@ -8620,19 +9037,19 @@ async function getDataByName(name: string, context: ctx.UIAbilityContext) { } } -async function run() { - const task = new taskpool.Task(getDataByName, 'Lisa', getContext()); - const sendableValuesBucket = await taskpool.execute(task) as sendableRelationalStore.ValuesBucket; - - if (sendableValuesBucket) { - const columnCount = sendableValuesBucket.size; - const age = sendableValuesBucket.get('age'); - const name = sendableValuesBucket.get('name'); - console.info(`Query data in taskpool succeeded, name is "${name}", age is "${age}"`) +class EntryAbility extends UIAbility { + async onWindowStageCreate(windowStage: window.WindowStage) { + const task = new taskpool.Task(getDataByName, 'Lisa', getContext()); + const sendableValuesBucket = await taskpool.execute(task) as sendableRelationalStore.ValuesBucket; + + if (sendableValuesBucket) { + const columnCount = sendableValuesBucket.size; + const age = sendableValuesBucket.get('age'); + const name = sendableValuesBucket.get('name'); + console.info(`Query data in taskpool succeeded, name is "${name}", age is "${age}"`) + } } } - -run() ``` ### isColumnNull @@ -8685,7 +9102,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -if(resultSet != undefined) { +if (resultSet != undefined) { const isColumnNull = (resultSet as relationalStore.ResultSet).isColumnNull((resultSet as relationalStore.ResultSet).getColumnIndex("CODES")); } ``` @@ -8701,7 +9118,7 @@ Closes this **resultSet** to release memory. If the **resultSet** is not closed, **Example** ```ts -if(resultSet != undefined) { +if (resultSet != undefined) { (resultSet as relationalStore.ResultSet).close(); } ``` @@ -8728,16 +9145,35 @@ When the number of concurrent transactions is large and the write transaction du **Example** ```ts +import { UIAbility } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit'; +import { window } from '@kit.ArkUI'; let store: relationalStore.RdbStore | undefined = undefined; -if(store != undefined) { - (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { - console.info(`createTransaction success`); - }).catch((err: BusinessError) => { - console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); - }); +class EntryAbility extends UIAbility { + async onWindowStageCreate(windowStage: window.WindowStage) { + const STORE_CONFIG: relationalStore.StoreConfig = { + name: "RdbTest.db", + securityLevel: relationalStore.SecurityLevel.S3, + }; + + await relationalStore.getRdbStore(this.context, STORE_CONFIG).then(async (rdbStore: relationalStore.RdbStore) => { + store = rdbStore; + console.info('Get RdbStore successfully.') + }).catch((err: BusinessError) => { + console.error(`Get RdbStore failed, code is ${err.code},message is ${err.message}`); + }) + + if (store != undefined) { + (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { + console.info(`createTransaction success`); + // Perform subsequent operations after the transaction instance is successfully obtained. + }).catch((err: BusinessError) => { + console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); + }); + } + } } ``` @@ -8779,7 +9215,7 @@ let value2 = 18; let value3 = 100.5; let value4 = new Uint8Array([1, 2, 3]); -if(store != undefined) { +if (store != undefined) { const valueBucket: relationalStore.ValuesBucket = { 'NAME': value1, 'AGE': value2, @@ -8832,7 +9268,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { transaction.execute("DELETE FROM TEST WHERE age = ? OR age = ?", ["18", "20"]).then(() => { transaction.commit(); @@ -8861,7 +9297,7 @@ Inserts a row of data into a table. This API uses a promise to return the result | -------- | ------------------------------------------- | ---- | -------------------------- | | table | string | Yes | Name of the target table. | | values | [ValuesBucket](#valuesbucket) | Yes | Row of data to insert.| -| conflict | [ConflictResolution](#conflictresolution10) | No | Resolution used to resolve the conflict. The default value is **relationalStore.ConflictResolution.ON_CONFLICT_NONE**. | +| conflict | [ConflictResolution](#conflictresolution10) | No | Resolution used to resolve the conflict.
Default value: **relationalStore.ConflictResolution.ON_CONFLICT_NONE**. | **Return value** @@ -8919,7 +9355,7 @@ const valueBucket3: relationalStore.ValuesBucket = { "CODES": value4, }; -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { transaction.insert("EMPLOYEE", valueBucket1, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE).then((rowId: number) => { transaction.commit(); @@ -8948,7 +9384,7 @@ Inserts a row of data into a table. Due to the limit of the shared memory (max. | -------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | | table | string | Yes | Name of the target table. | | values | [ValuesBucket](#valuesbucket) \| [sendableRelationalStore.ValuesBucket](./js-apis-data-sendableRelationalStore.md#valuesbucket) | Yes | Row of data to insert. | -| conflict | [ConflictResolution](#conflictresolution10) | No | Resolution used to resolve the conflict. The default value is **relationalStore.ConflictResolution.ON_CONFLICT_NONE**.| +| conflict | [ConflictResolution](#conflictresolution10) | No | Resolution used to resolve the conflict.
Default value: **relationalStore.ConflictResolution.ON_CONFLICT_NONE**.| **Return value** @@ -9006,13 +9442,13 @@ const valueBucket3: relationalStore.ValuesBucket = { "CODES": value4, }; -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { try { let rowId: number = (transaction as relationalStore.Transaction).insertSync("EMPLOYEE", valueBucket1, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE); transaction.commit(); console.info(`Insert is successful, rowId = ${rowId}`); - } catch (e: BusinessError) { + } catch (e) { transaction.rollback(); console.error(`Insert is failed, code is ${e.code},message is ${e.message}`); }; @@ -9026,7 +9462,7 @@ if(store != undefined) { batchInsert(table: string, values: Array<ValuesBucket>): Promise<number> -Batch inserts data into a table. This API uses a promise to return the result. +Inserts a batch of data into a table. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -9101,7 +9537,7 @@ const valueBucket3: relationalStore.ValuesBucket = { }; let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { transaction.batchInsert("EMPLOYEE", valueBuckets).then((insertNum: number) => { transaction.commit(); @@ -9120,7 +9556,7 @@ if(store != undefined) { batchInsertSync(table: string, values: Array<ValuesBucket>): number -Inserts a group of data into a table. +Inserts a batch of data into a table. This API returns the result synchronously. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -9195,7 +9631,7 @@ const valueBucket3: relationalStore.ValuesBucket = { }; let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { try { let insertNum: number = (transaction as relationalStore.Transaction).batchInsertSync("EMPLOYEE", valueBuckets); @@ -9211,6 +9647,203 @@ if(store != undefined) { } ``` +### batchInsertWithConflictResolution18+ + +batchInsertWithConflictResolution(table: string, values: Array<ValuesBucket>, conflict: ConflictResolution): Promise<number> + +Inserts a batch of data into a table. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------ | ---- | ---------------------------- | +| table | string | Yes | Name of the target table. | +| values | Array<[ValuesBucket](#valuesbucket)> | Yes | An array of data to insert.| +| conflict | [ConflictResolution](#conflictresolution10) | Yes | Resolution used to resolve the conflict. If **ON_CONFLICT_ROLLBACK** is used, the transaction will be rolled back when a conflict occurs.| + +**Return value** + +| Type | Description | +| --------------------- | ----------------------------------------------------------- | +| Promise<number> | Promise used to return the result. If the operation is successful, the number of inserted data records is returned. Otherwise, **-1** is returned.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). + +| **ID**| **Error Message** | +|-----------| ------------------------------------------------------------ | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 14800000 | Inner error. | +| 14800011 | Database corrupted. | +| 14800014 | Already closed. | +| 14800021 | SQLite: Generic error. | +| 14800022 | SQLite: Callback routine requested an abort. | +| 14800023 | SQLite: Access permission denied. | +| 14800024 | SQLite: The database file is locked. | +| 14800025 | SQLite: A table in the database is locked. | +| 14800026 | SQLite: The database is out of memory. | +| 14800027 | SQLite: Attempt to write a readonly database. | +| 14800028 | SQLite: Some kind of disk I/O error occurred. | +| 14800029 | SQLite: The database is full. | +| 14800031 | SQLite: TEXT or BLOB exceeds size limit. | +| 14800032 | SQLite: Abort due to constraint violation. | +| 14800033 | SQLite: Data type mismatch. | +| 14800034 | SQLite: Library used incorrectly. | +| 14800047 | The WAL file size exceeds the default limit. | + +**Example** + +```ts +let value1 = "Lisa"; +let value2 = 18; +let value3 = 100.5; +let value4 = new Uint8Array([1, 2, 3, 4, 5]); +let value5 = "Jack"; +let value6 = 19; +let value7 = 101.5; +let value8 = new Uint8Array([6, 7, 8, 9, 10]); +let value9 = "Tom"; +let value10 = 20; +let value11 = 102.5; +let value12 = new Uint8Array([11, 12, 13, 14, 15]); + +const valueBucket1: relationalStore.ValuesBucket = { + 'NAME': value1, + 'AGE': value2, + 'SALARY': value3, + 'CODES': value4, +}; +const valueBucket2: relationalStore.ValuesBucket = { + 'NAME': value5, + 'AGE': value6, + 'SALARY': value7, + 'CODES': value8, +}; +const valueBucket3: relationalStore.ValuesBucket = { + 'NAME': value9, + 'AGE': value10, + 'SALARY': value11, + 'CODES': value12, +}; + +let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); +if (store != undefined) { + (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { + transaction.batchInsertWithConflictResolution("EMPLOYEE", valueBuckets, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE).then((insertNum: number) => { + transaction.commit(); + console.info(`batchInsert is successful, the number of values that were inserted = ${insertNum}`); + }).catch((e: BusinessError) => { + transaction.rollback(); + console.error(`batchInsert is failed, code is ${e.code},message is ${e.message}`); + }); + }).catch((err: BusinessError) => { + console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); + }); +} +``` + +### batchInsertWithConflictResolutionSync18+ + +batchInsertWithConflictResolutionSync(table: string, values: Array<ValuesBucket>, conflict: ConflictResolution): number + +Inserts a batch of data into a table. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------ | ---- | ---------------------------- | +| table | string | Yes | Name of the target table. | +| values | Array<[ValuesBucket](#valuesbucket)> | Yes | An array of data to insert.| +| conflict | [ConflictResolution](#conflictresolution10) | Yes | Resolution used to resolve the conflict. If **ON_CONFLICT_ROLLBACK** is used, the transaction will be rolled back when a conflict occurs.| + +**Return value** + +| Type | Description | +| ------ | ---------------------------------------------- | +| number | If the operation is successful, the number of inserted data records is returned. Otherwise, **-1** is returned.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | +| 14800000 | Inner error. | +| 14800011 | Database corrupted. | +| 14800014 | Already closed. | +| 14800021 | SQLite: Generic error. | +| 14800022 | SQLite: Callback routine requested an abort. | +| 14800023 | SQLite: Access permission denied. | +| 14800024 | SQLite: The database file is locked. | +| 14800025 | SQLite: A table in the database is locked. | +| 14800026 | SQLite: The database is out of memory. | +| 14800027 | SQLite: Attempt to write a readonly database. | +| 14800028 | SQLite: Some kind of disk I/O error occurred. | +| 14800029 | SQLite: The database is full. | +| 14800031 | SQLite: TEXT or BLOB exceeds size limit. | +| 14800032 | SQLite: Abort due to constraint violation. | +| 14800033 | SQLite: Data type mismatch. | +| 14800034 | SQLite: Library used incorrectly. | +| 14800047 | The WAL file size exceeds the default limit. | + +**Example** + +```ts +let value1 = "Lisa"; +let value2 = 18; +let value3 = 100.5; +let value4 = new Uint8Array([1, 2, 3, 4, 5]); +let value5 = "Jack"; +let value6 = 19; +let value7 = 101.5; +let value8 = new Uint8Array([6, 7, 8, 9, 10]); +let value9 = "Tom"; +let value10 = 20; +let value11 = 102.5; +let value12 = new Uint8Array([11, 12, 13, 14, 15]); + +const valueBucket1: relationalStore.ValuesBucket = { + 'NAME': value1, + 'AGE': value2, + 'SALARY': value3, + 'CODES': value4, +}; +const valueBucket2: relationalStore.ValuesBucket = { + 'NAME': value5, + 'AGE': value6, + 'SALARY': value7, + 'CODES': value8, +}; +const valueBucket3: relationalStore.ValuesBucket = { + 'NAME': value9, + 'AGE': value10, + 'SALARY': value11, + 'CODES': value12, +}; + +let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); +if (store != undefined) { + (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { + try { + let insertNum: number = (transaction as relationalStore.Transaction).batchInsertWithConflictResolutionSync("EMPLOYEE", valueBuckets, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE); + transaction.commit(); + console.info(`batchInsert is successful, the number of values that were inserted = ${insertNum}`); + } catch (e) { + transaction.rollback(); + console.error(`batchInsert is failed, code is ${e.code},message is ${e.message}`); + }; + }).catch((err: BusinessError) => { + console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`); + }); +} +``` + ### update14+ update(values: ValuesBucket, predicates: RdbPredicates, conflict?: ConflictResolution): Promise<number> @@ -9225,7 +9858,7 @@ Updates data based on the specified **RdbPredicates** object. This API uses a pr | ---------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | | values | [ValuesBucket](#valuesbucket) | Yes | Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| | predicates | [RdbPredicates](#rdbpredicates) | Yes | Update conditions specified by the **RdbPredicates** object. | -| conflict | [ConflictResolution](#conflictresolution10) | No | Resolution used to resolve the conflict. The default value is **relationalStore.ConflictResolution.ON_CONFLICT_NONE**. | +| conflict | [ConflictResolution](#conflictresolution10) | No | Resolution used to resolve the conflict.
Default value: **relationalStore.ConflictResolution.ON_CONFLICT_NONE**. | **Return value** @@ -9286,7 +9919,7 @@ const valueBucket3: relationalStore.ValuesBucket = { let predicates = new relationalStore.RdbPredicates('EMPLOYEE'); predicates.equalTo("NAME", "Lisa"); -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { transaction.update(valueBucket1, predicates, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE).then(async (rows: Number) => { transaction.commit(); @@ -9315,7 +9948,7 @@ Updates data in the database based on the specified **RdbPredicates** instance. | ---------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | | values | [ValuesBucket](#valuesbucket) | Yes | Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| | predicates | [RdbPredicates](#rdbpredicates) | Yes | Update conditions specified by the **RdbPredicates** object. | -| conflict | [ConflictResolution](#conflictresolution10) | No | Resolution used to resolve the conflict. The default value is **relationalStore.ConflictResolution.ON_CONFLICT_NONE**.| +| conflict | [ConflictResolution](#conflictresolution10) | No | Resolution used to resolve the conflict.
Default value: **relationalStore.ConflictResolution.ON_CONFLICT_NONE**.| **Return value** @@ -9376,7 +10009,7 @@ const valueBucket3: relationalStore.ValuesBucket = { let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Lisa"); -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { try { let rows: Number = (transaction as relationalStore.Transaction).updateSync(valueBucket1, predicates, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE); @@ -9440,7 +10073,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Lisa"); -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { transaction.delete(predicates).then((rows: Number) => { transaction.commit(); @@ -9503,7 +10136,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Lisa"); -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { try { let rows: Number = (transaction as relationalStore.Transaction).deleteSync(predicates); @@ -9563,7 +10196,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Rose"); -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { transaction.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]).then((resultSet: relationalStore.ResultSet) => { console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); @@ -9601,7 +10234,7 @@ Queries data in a database based on specified conditions. This API returns the r | Name | Type | Mandatory| Description | | ---------- | ------------------------------- | ---- | ------------------------------------------------------------ | | predicates | [RdbPredicates](#rdbpredicates) | Yes | Query conditions specified by the **RdbPredicates** object. | -| columns | Array<string> | No | Columns to query. If this parameter is not specified, the query applies to all columns. The default value is null.| +| columns | Array<string> | No | Columns to query. If this parameter is not specified, the query applies to all columns.
Default value: null.| **Error codes** @@ -9633,7 +10266,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); predicates.equalTo("NAME", "Rose"); -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { try { let resultSet: relationalStore.ResultSet = (transaction as relationalStore.Transaction).querySync(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); @@ -9701,7 +10334,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { transaction.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = 'sanguo'").then((resultSet: relationalStore.ResultSet) => { console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); @@ -9739,7 +10372,7 @@ Queries data in the RDB store using the specified SQL statement. The number of r | Name | Type | Mandatory| Description | | -------- | ------------------------------------ | ---- | ------------------------------------------------------------ | | sql | string | Yes | SQL statement to run. | -| args | Array<[ValueType](#valuetype)> | No | Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If the SQL parameter statement is complete, leave this parameter blank. The default value is null.| +| args | Array<[ValueType](#valuetype)> | No | Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If the SQL parameter statement is complete, leave this parameter blank.
Default value: null.| **Return value** @@ -9768,7 +10401,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { try { let resultSet: relationalStore.ResultSet = (transaction as relationalStore.Transaction).querySqlSync("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = 'sanguo'"); @@ -9848,7 +10481,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts // Delete all data from the table. -if(store != undefined) { +if (store != undefined) { const SQL_DELETE_TABLE = 'DELETE FROM test'; (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { transaction.execute(SQL_DELETE_TABLE).then((data) => { @@ -9883,7 +10516,7 @@ Statements separated by semicolons (\;) are not supported. | Name| Type | Mandatory| Description | | ------ | ------------------------------------ | ---- | ------------------------------------------------------------ | | sql | string | Yes | SQL statement to run. | -| args | Array<[ValueType](#valuetype)> | No | Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If this parameter is left blank or set to **null** or **undefined**, the SQL statement is complete. The default value is null.| +| args | Array<[ValueType](#valuetype)> | No | Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If this parameter is left blank or set to **null** or **undefined**, the SQL statement is complete.
Default value: null.| **Return value** @@ -9918,7 +10551,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts // Delete all data from the table. -if(store != undefined) { +if (store != undefined) { (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => { const SQL_DELETE_TABLE = 'DELETE FROM test'; try { diff --git a/en/application-dev/reference/apis-arkdata/js-apis-data-sendablePreferences.md b/en/application-dev/reference/apis-arkdata/js-apis-data-sendablePreferences.md index 5f19adc494151bf68a88fb4a0d20ae2f40e2b010..201276a21a5a61b6a1889d50d01a4be75e0fc539 100644 --- a/en/application-dev/reference/apis-arkdata/js-apis-data-sendablePreferences.md +++ b/en/application-dev/reference/apis-arkdata/js-apis-data-sendablePreferences.md @@ -5,7 +5,7 @@ The **sendablePreferences** module provides APIs for processing data in the form In the KV pairs, the key must be a string, and the value can be a number, a string, a Boolean value, a bigint, or a serializable object. -The default encryption level of sendable preferences is EL2, and the persistent files are stored in the corresponding **el2/** directory. If there is no lock screen password, the sendable preferences can be directly accessed after the device is powered on. If there is a lock screen password, the data can be accessed only after at least one successful unlock operation (by PIN, fingerprint, or facial authentication). For security purposes, avoid direct access to sendable preferences without the screen unlock operation. For details about how to modify the encryption level, see [Obtaining and Modifying Encryption Levels](../../../application-dev/application-models/application-context-stage.md#obtaining-and-modifying-encryption-levels). +The persistent files of the shared user preferences are stored in the [preferencesDir](../../application-models/application-context-stage.md#obtaining-application-file-path) directory. Before creating a preferences object, ensure that the **preferencesDir** directory is readable and writeable. The [encryption level](../apis-ability-kit/js-apis-app-ability-contextConstant.md#areamode) of the persistent file directory determines the access to the files. For details, see [Application File Directory and Application File Path](../../file-management/app-sandbox-directory.md#application-file-directory-and-application-file-path). Sendable preferences can be passed between concurrent ArkTS instances (including the main thread and TaskPool or Worker threads) by reference. It allows for higher performance than [user preferences](js-apis-data-preferences.md). For more information, see [Using Sendable Objects](../../arkts-utils/sendable-guide.md). @@ -61,7 +61,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 801 | Capability not supported. | | 15500000 | Inner error. | | 15501001 | The operations is supported in stage mode only. | @@ -119,7 +119,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 801 | Capability not supported. | | 15500000 | Inner error. | | 15501001 | The operations is supported in stage mode only. | @@ -172,7 +172,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 801 | Capability not supported. | | 15500000 | Inner error. | | 15500010 | Failed to delete the user preferences persistence file. | @@ -230,7 +230,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 801 | Capability not supported. | | 15500000 | Inner error. | | 15501001 | The operations is supported in stage mode only. | @@ -281,7 +281,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 801 | Capability not supported. | | 15500000 | Inner error. | | 15501001 | The operations is supported in stage mode only. | @@ -350,7 +350,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | **Example** @@ -397,7 +397,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | **Example** @@ -517,7 +517,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | **Example** @@ -562,7 +562,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | **Example** @@ -599,7 +599,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | **Example** @@ -647,7 +647,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | **Example** @@ -689,7 +689,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | **Example** @@ -727,7 +727,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | **Example** @@ -893,7 +893,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | **Example** @@ -944,7 +944,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | -------------------------------------- | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | | 15500019 | Failed to obtain the subscription service. | @@ -993,7 +993,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | **Example** @@ -1039,7 +1039,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | **Example** @@ -1085,7 +1085,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | **Example** @@ -1129,7 +1129,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2. Incorrect parameter types;
3. Parameter verification failed. | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 15500000 | Inner error. | **Example** diff --git a/en/application-dev/reference/apis-arkdata/js-apis-data-sendableRelationalStore.md b/en/application-dev/reference/apis-arkdata/js-apis-data-sendableRelationalStore.md index e16338ad1c9eb927378f539caecdd3940c57ccb1..09e6fa22a7ece9c1321b1ad0c2868e97481523b8 100644 --- a/en/application-dev/reference/apis-arkdata/js-apis-data-sendableRelationalStore.md +++ b/en/application-dev/reference/apis-arkdata/js-apis-data-sendableRelationalStore.md @@ -16,27 +16,27 @@ import { sendableRelationalStore } from '@kit.ArkData'; toSendableValuesBucket(valuesBucket: NonSendableBucket): ValuesBucket -Converts a key-value (KV) pair that cannot be transferred across threads into the data that can be transferred across threads. +Converts a key-value (KV) pair that cannot be passed across threads into the data that can be passed across threads. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ------------ | --------------------------------------- | ---- | :--------------------------------- | -| valuesBucket | [NonSendableBucket](#nonsendablebucket) | Yes | Data that cannot be transferred across threads. | +| valuesBucket | [NonSendableBucket](#nonsendablebucket) | Yes | Data that cannot be passed across threads. | **Return value** | Type | Description | | ----------------------------- | ------------------------------------ | -| [ValuesBucket](#valuesbucket) | Data that can be transferred across threads. | +| [ValuesBucket](#valuesbucket) | Data that can be passed across threads. | **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). -| **Error Code** | **Error Message** | +| **Error Code**| **Error Message** | | ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 14800000 | Inner error. | @@ -79,27 +79,27 @@ const sendableValuesBucket = sendableRelationalStore.toSendableValuesBucket(valu fromSendableValuesBucket(valuesBucket: ValuesBucket): NonSendableBucket -Converts a KV pair that can be transferred across threads into the data that cannot be transferred across threads. +Converts a KV pair that can be passed across threads into the data that cannot be passed across threads. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ------------ | ----------------------------- | ---- | :----------------------------------- | -| valuesBucket | [ValuesBucket](#valuesbucket) | Yes | Data that can be transferred across threads. | +| valuesBucket | [ValuesBucket](#valuesbucket) | Yes | Data that can be passed across threads. | **Return value** | Type | Description | | --------------------------------------- | ---------------------------------- | -| [NonSendableBucket](#nonsendablebucket) | Data that cannot be transferred across threads. | +| [NonSendableBucket](#nonsendablebucket) | Data that cannot be passed across threads. | **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). -| **Error Code** | **Error Message** | +| **Error Code**| **Error Message** | | ------------ | ------------------------------------------------------------------------------------------------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 14800000 | Inner error. | @@ -142,25 +142,25 @@ const nonSendableBucket = sendableRelationalStore.fromSendableValuesBucket(senda function toSendableAsset(asset: NonSendableAsset): Asset -Converts the asset data that cannot be transferred across threads into the data that can be transferred across threads. +Converts the asset data that cannot be passed across threads into the data that can be passed across threads. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type | Mandatory| Description | | ------ | -------------------------------------- | ---- | :-------------------------- | -| asset | [NonSendableAsset](#nonsendablebucket) | Yes | Asset data that cannot be transferred across threads. | +| asset | [NonSendableAsset](#nonsendablebucket) | Yes | Asset data that cannot be passed across threads. | **Return value** | Type | Description | | --------------- | ------------------------- | -| [Asset](#asset) | Asset data that can be transferred across threads. | +| [Asset](#asset) | Asset data that can be passed across threads. | For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). -| **Error Code** | **Error Message** | +| **Error Code**| **Error Message** | | ------------ | ------------------------------------------------------------------------------------------------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 14800000 | Inner error. | @@ -183,26 +183,26 @@ const sendableAsset = sendableRelationalStore.toSendableAsset(asset1); function fromSendableAsset(asset: Asset): NonSendableAsset -Converts the asset data that can be transferred across threads into the data that cannot be transferred across threads. +Converts the asset data that can be passed across threads into the data that cannot be passed across threads. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type | Mandatory| Description | | ------ | --------------- | ---- | :------------------------ | -| asset | [Asset](#asset) | Yes | Asset data that can be transferred across threads. | +| asset | [Asset](#asset) | Yes | Asset data that can be passed across threads. | **Return value** | Type | Description | | -------------------------------------- | --------------------------- | -| [NonSendableAsset](#nonsendablebucket) | Asset data that cannot be transferred across threads. | +| [NonSendableAsset](#nonsendablebucket) | Asset data that cannot be passed across threads. | For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). -| **Error Code** | **Error Message** | +| **Error Code**| **Error Message** | | ------------ | ------------------------------------------------------------------------------------------------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | | 14800000 | Inner error. | @@ -224,11 +224,11 @@ const normalAsset = sendableRelationalStore.fromSendableAsset(sendableAsset); ## Asset -Represent information about an asset (such as a document, image, and video). **Asset** inherits from [lang.ISendable](../apis-arkts/js-apis-arkts-lang.md#langisendable) and is used to implement cross-thread transfer of asset data. The asset data does not support **Datashare** APIs. Use [sendableRelationalStore.toSendableAsset](#sendablerelationalstoretosendableasset) to create an **Asset** instance. +Represent information about an asset (such as a document, image, or video). **Asset** inherits from [lang.ISendable](../apis-arkts/js-apis-arkts-lang.md#langisendable) and is used to implement cross-thread transfer of asset data. The asset data does not support **Datashare** APIs. Use [sendableRelationalStore.toSendableAsset](#sendablerelationalstoretosendableasset) to create an **Asset** instance. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -| Name | Type | Read-Only | Optional | Description | +| Name | Type | Read-Only| Optional| Description | | ---------- | ------ | --- | ---- | ---------------------------------- | | name | string | No | No | Asset name. | | uri | string | No | No | Asset URI, which is an absolute path in the system. | @@ -243,19 +243,19 @@ Represent information about an asset (such as a document, image, and video). **A type Assets = collections.Array\ -Represent an array of [Assets](#asset), which allows assets to be transferred across threads. +Represent an array of [Assets](#asset), which allows assets to be passed across threads. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core | Type | Description | | -------------------------------------------------------------------------------------------------- | --------------------------------- | -| [collections.Array](../apis-arkts/js-apis-arkts-collections.md#collectionsarray)\<[Asset](#asset)> | Array of assets. | +| [collections.Array](../apis-arkts/js-apis-arkts-collections.md#collectionsarray)\<[Asset](#asset)> | Array of assets.| ## ValueType type ValueType = null | number | string | boolean | collection.Uint8Array | Asset | Assets | collection.Float32Array | bigint -Enumerates the types of the value in a KV pair. The type varies with the parameter function. +Defines the types of the value in a KV pair. The type varies with the parameter function. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -263,46 +263,46 @@ Enumerates the types of the value in a KV pair. The type varies with the paramet | ------- | -------------------- | | null | The value is null. | | number | The value is a number. | -| string | The value is a string. | -| boolean | The value is **true** or **false**. | +| string | The value is a string.| +| boolean | The value is **true** or **false**.| | [collection.Uint8Array](../apis-arkts/js-apis-arkts-collections.md#collectionstypedarray) | The value is a Uint8 array.| | [Asset](#asset) | The value is an asset.
If the value type is **Asset**, the type in the SQL statement for creating a table must be **ASSET**. | -| [Assets](#assets) | The value is an array of assets.
If the value type is **Assets**, the type in the SQL statement for creating a table must be **ASSETS**. | -| [collection.Float32Array](../apis-arkts/js-apis-arkts-collections.md#collectionstypedarray) | The value is an array of 32-bit floating-point numbers.
If the value type is **collection.Float32Array**, the type in the SQL statement for creating a table must be **floatvector(128)**. | -| bigint | The value is an integer of any length.
If the value type is **bigint**, the type in the SQL statement for creating a table must be **UNLIMITED INT**. For details, see [Persisting RDB Store Data](../../database/data-persistence-by-rdb-store.md).
**NOTE**
The bigint type does not support value comparison and cannot be used with the following predicates: **between**, **notBetween**, **greaterThanlessThan**, **greaterThanOrEqualTo**, **lessThanOrEqualTo**, **orderByAsc**, and **orderByDesc**
To write a value of bigint type, use **BigInt()** or add **n** to the end of the value, for example,'let data = BigInt(1234)' or 'let data = 1234n'.
If data of the number type is written to a bigint field, the type of the return value obtained (queried) is number but not bigint. | +| [Assets](#assets) | The value is an array of assets.
If the value type is **Assets**, the type in the SQL statement for creating a table must be **ASSETS**.| +| [collection.Float32Array](../apis-arkts/js-apis-arkts-collections.md#collectionstypedarray) | The value is an array of 32-bit floating-point numbers.
If the value type is **collection.Float32Array**, the type in the SQL statement for creating a table must be **floatvector(128)**.| +| bigint | The value is an integer of any length.
If the value type is bigint, the type in the SQL statement for creating a table must be **UNLIMITED INT**. For details, see [Persisting RDB Store Data](../../database/data-persistence-by-rdb-store.md).
**NOTE**

The bigint type does not support value comparison and cannot be used with the following predicates: **between**, **notBetween**, **greaterThanlessThan**, **greaterThanOrEqualTo**, **lessThanOrEqualTo**, **orderByAsc**, and **orderByDesc**
To write a value of bigint type, use **BigInt()** or add **n** to the end of the value, for example, 'let data = BigInt(1234)' or 'let data = 1234n'.
If data of the number type is written to a bigint field, the type of the return value obtained (queried) is number but not bigint. | ## ValuesBucket type ValuesBucket = collections.Map -Represents the KV pair that can be transferred across threads. +Represents the KV pair that can be passed across threads. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -| Type | Description | -| ------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | -| [collections.Map](../apis-arkts/js-apis-arkts-collections.md#collectionsmap) | KV pair that can be transferred across threads. The key must be a string, and the value is of the **ValueType** type. | +| Type | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| [collections.Map](../apis-arkts/js-apis-arkts-collections.md#collectionsmap) | KV pair that can be passed across threads. The key must be a string, and the value is of the **ValueType** type. | ## NonSendableBucket type NonSendableBucket = relationalStore.ValuesBucket -Represents the KV pair that cannot be transferred across threads +Represents the KV pair that cannot be passed across threads. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core | Type | Description | | ------------------------------------------------------------------------------ | ---------------------------- | -| [relationalStore.ValuesBucket](./js-apis-data-relationalStore.md#valuesbucket) | KV pair that cannot be transferred across threads. | +| [relationalStore.ValuesBucket](./js-apis-data-relationalStore.md#valuesbucket) | KV pair that cannot be passed across threads. | ## NonSendableAsset type NonSendableAsset = relationalStore.Asset -Represent the asset (such as a document, image, and video) that cannot be transferred across threads +Represent the asset (such as a document, image, or video) that cannot be passed across threads. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core | Type | Description | | ------------------------------------------------------------------ | ------------------------------ | -| [relationalStore.Asset](./js-apis-data-relationalStore.md#asset10) | Asset that cannot be transferred across threads. | +| [relationalStore.Asset](./js-apis-data-relationalStore.md#asset10) | Asset that cannot be passed across threads. | diff --git a/en/application-dev/reference/apis-arkdata/js-apis-data-unifiedDataChannel.md b/en/application-dev/reference/apis-arkdata/js-apis-data-unifiedDataChannel.md index 333161b2f7ff7d565c3be5dd4667436eff04263d..bdf8769bce68602ae8bb407ae65d1409939c8cac 100644 --- a/en/application-dev/reference/apis-arkdata/js-apis-data-unifiedDataChannel.md +++ b/en/application-dev/reference/apis-arkdata/js-apis-data-unifiedDataChannel.md @@ -506,6 +506,261 @@ let hyperlinkRecord = new unifiedDataChannel.UnifiedRecord(uniformTypeDescriptor let hyperlinkValue = hyperlinkRecord.getValue(); ``` +### addEntry15+ + +addEntry(type: string, value: ValueType): void + +Adds data to the current data record. + +**Atomic service API**: This API can be used in atomic services since API version 15. + +**System capability**: SystemCapability.DistributedDataManager.UDMF.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------- | ---- |-----------------------------------------| +| type | string | Yes | Type of the data to add. For details, see [UniformDataType](js-apis-data-uniformTypeDescriptor.md#uniformdatatype).| +| value | [ValueType](#valuetype12) | Yes | Value of the data to add.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------- | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types. | + +**Example** + +```ts +import { uniformDataStruct, uniformTypeDescriptor } from '@kit.ArkData'; + +let fileUriDetails : Record = { + 'attr1': 'value1', + 'attr2': 'value2', +} +let fileUri : uniformDataStruct.FileUri = { + uniformDataType : 'general.file-uri', + oriUri : 'file://data/image/1.png', + fileType : 'general.image', + details : fileUriDetails, +} +let formDetails : Record = { + 'attr1': 'value1', + 'attr2': 'value2', +} +let form : uniformDataStruct.Form = { + uniformDataType : 'openharmony.form', + formId : 1, + formName : 'form', + bundleName : 'com.xx.app', + abilityName : 'ability', + module : 'module', + details : formDetails, +} + +let unifiedData = new unifiedDataChannel.UnifiedData(); +let record = new unifiedDataChannel.UnifiedRecord(uniformTypeDescriptor.UniformDataType.OPENHARMONY_FORM, form); +record.addEntry(uniformTypeDescriptor.UniformDataType.FILE_URI, fileUri); +unifiedData.addRecord(record); +``` + +### getEntry15+ + +getEntry(type: string): ValueType + +Obtains data of the specified type from the current data record. + +**Atomic service API**: This API can be used in atomic services since API version 15. + +**System capability**: SystemCapability.DistributedDataManager.UDMF.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------- | ---- |-----------------------------------------| +| type | string | Yes | Type of the data to obtain. For details, see [UniformDataType](js-apis-data-uniformTypeDescriptor.md#uniformdatatype).| + +**Return value** + +| Type | Description | +| ------ |------------------------------------------------------| +| [ValueType](#valuetype12) | Value obtained.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------- | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types. | + +**Example** + +```ts +import { uniformDataStruct, uniformTypeDescriptor } from '@kit.ArkData'; + +let fileUriDetails : Record = { + 'attr1': 'value1', + 'attr2': 'value2', +} +let fileUri : uniformDataStruct.FileUri = { + uniformDataType : 'general.file-uri', + oriUri : 'file://data/image/1.png', + fileType : 'general.image', + details : fileUriDetails, +} +let formDetails : Record = { + 'attr1': 'value1', + 'attr2': 'value2', +} +let form : uniformDataStruct.Form = { + uniformDataType : 'openharmony.form', + formId : 1, + formName : 'form', + bundleName : 'com.xx.app', + abilityName : 'ability', + module : 'module', + details : formDetails, +} + +let unifiedData = new unifiedDataChannel.UnifiedData(); +let record = new unifiedDataChannel.UnifiedRecord(uniformTypeDescriptor.UniformDataType.OPENHARMONY_FORM, form); +record.addEntry(uniformTypeDescriptor.UniformDataType.FILE_URI, fileUri); +unifiedData.addRecord(record); + +let records = unifiedData.getRecords(); +for (let i = 0; i < records.length; i++) { + let unifiedDataRecord = records[i] as unifiedDataChannel.UnifiedRecord; + let fileUriRead : uniformDataStruct.FileUri = unifiedDataRecord.getEntry(uniformTypeDescriptor.UniformDataType.FILE_URI) as uniformDataStruct.FileUri + if (fileUriRead != undefined) { + console.info(`oriUri: ${fileUriRead.oriUri}`); + } +} +``` + +### getEntries15+ + +getEntries(): Record + +Obtains all the data in the current data record. + +**Atomic service API**: This API can be used in atomic services since API version 15. + +**System capability**: SystemCapability.DistributedDataManager.UDMF.Core + +**Return value** + +| Type | Description | +| ------ |------------------------------------------------------| +| Record | Values and types obtained.| + +**Example** + +```ts +import { uniformDataStruct, uniformTypeDescriptor } from '@kit.ArkData'; + +let fileUriDetails : Record = { + 'attr1': 'value1', + 'attr2': 'value2', +} +let fileUri : uniformDataStruct.FileUri = { + uniformDataType : 'general.file-uri', + oriUri : 'file://data/image/1.png', + fileType : 'general.image', + details : fileUriDetails, +} +let formDetails : Record = { + 'attr1': 'value1', + 'attr2': 'value2', +} +let form : uniformDataStruct.Form = { + uniformDataType : 'openharmony.form', + formId : 1, + formName : 'form', + bundleName : 'com.xx.app', + abilityName : 'ability', + module : 'module', + details : formDetails, +} + +let unifiedData = new unifiedDataChannel.UnifiedData(); +let record = new unifiedDataChannel.UnifiedRecord(uniformTypeDescriptor.UniformDataType.OPENHARMONY_FORM, form); +record.addEntry(uniformTypeDescriptor.UniformDataType.FILE_URI, fileUri); +unifiedData.addRecord(record); + +let records = unifiedData.getRecords(); +for (let i = 0; i < records.length; i++) { + let unifiedDataRecord = records[i] as unifiedDataChannel.UnifiedRecord; + let entries : Record = unifiedDataRecord.getEntries(); + let formRead : uniformDataStruct.Form = entries[uniformTypeDescriptor.UniformDataType.OPENHARMONY_FORM] as uniformDataStruct.Form + if (formRead != undefined) { + console.info(`formName: ${formRead.formName}`); + } +} +``` + +### getTypes15+ + +getTypes(): Array\ + +Obtains all the data types in the current data record. You can call this API with a **UnifiedRecord** instance to obtain all types of data in the record. + +**Atomic service API**: This API can be used in atomic services since API version 15. + +**System capability**: SystemCapability.DistributedDataManager.UDMF.Core + +**Return value** + +| Type | Description | +| ---------------------------------------- |-------------------------| +| Array\ | Array of [UniformDataType](js-apis-data-uniformTypeDescriptor.md#uniformdatatype)s obtained.| + +**Example** + +```ts +import { uniformDataStruct, uniformTypeDescriptor } from '@kit.ArkData'; + +let fileUriDetails : Record = { + 'attr1': 'value1', + 'attr2': 'value2', +} +let fileUri : uniformDataStruct.FileUri = { + uniformDataType : 'general.file-uri', + oriUri : 'file://data/image/1.png', + fileType : 'general.image', + details : fileUriDetails, +} +let formDetails : Record = { + 'attr1': 'value1', + 'attr2': 'value2', +} +let form : uniformDataStruct.Form = { + uniformDataType : 'openharmony.form', + formId : 1, + formName : 'form', + bundleName : 'com.xx.app', + abilityName : 'ability', + module : 'module', + details : formDetails, +} + +let unifiedData = new unifiedDataChannel.UnifiedData(); +let record = new unifiedDataChannel.UnifiedRecord(uniformTypeDescriptor.UniformDataType.OPENHARMONY_FORM, form); +record.addEntry(uniformTypeDescriptor.UniformDataType.FILE_URI, fileUri); +unifiedData.addRecord(record); + +let records = unifiedData.getRecords(); +for (let i = 0; i < records.length; i++) { + let unifiedDataRecord = records[i] as unifiedDataChannel.UnifiedRecord; + let types : Array = unifiedDataRecord.getTypes(); + if (types.includes(uniformTypeDescriptor.UniformDataType.OPENHARMONY_FORM)) { + console.info(`types include: ${uniformTypeDescriptor.UniformDataType.OPENHARMONY_FORM}`); + } +} +``` + ## Text Represents the text data. It is a child class of [UnifiedRecord](#unifiedrecord) and a base class of text data. You are advised to use the child class of **Text**, for example, [PlainText](#plaintext), [Hyperlink](#hyperlink), and [HTML](#html), to describe data. @@ -879,18 +1134,111 @@ Enumerates the data channel types supported by the UDMF. It is used to identify type Options = { intention?: Intention; key?: string; } -Defines the data operation performed by the UDMF. It includes two optional parameters: **intention** and **key**. The two parameters have no default value, and can be left unspecified. For details, see the parameter description of the specific API. +Defines the data operation performed by the UDMF. It includes two optional parameters: **intention** and **key**. The two parameters can be left unspecified. For details, see the parameter description of the specific API. **Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.DistributedDataManager.UDMF.Core - | Name | Type | Mandatory| Description | | --------- | ----------------------- | ---- | ------------------------------------------------------------ | | intention | [Intention](#intention) | No | Type of the data channel related to the data operation. | | key | string | No | Unique identifier of the data object in the UDMF, which can be obtained from the value returned by [insertData](#unifieddatachannelinsertdata).
The key consists of **udmf:/**, **intention**, **bundleName**, and **groupId** with a (/) in between, for example, **udmf://DataHub/com.ohos.test/0123456789**.
**udmf:/** is fixed, **DataHub** is an enum of **intention**, **com.ohos.test** is the bundle name, and **0123456789** is a group ID randomly generated.| +## FileConflictOptions15+ + +Enumerates the options for resolving file copy conflicts. + +**Atomic service API**: This API can be used in atomic services since API version 15. + +**System capability**: SystemCapability.DistributedDataManager.UDMF.Core + +| Name | Value | Description | +| --------- | ---- |----------------| +| OVERWRITE | 0 | Overwrite the file with the same name in the destination directory.| +| SKIP | 1 | Skip the file if there is a file with the same name in the destination directory.| + +## ProgressIndicator15+ + +Enumerates the progress indicator options. + +**Atomic service API**: This API can be used in atomic services since API version 15. + +**System capability**: SystemCapability.DistributedDataManager.UDMF.Core + +| Name | Value | Description | +| ------- | ---- |------------------------------------| +| NONE | 0 | Do not use the default progress indicator. | +| DEFAULT | 1 | Use the default progress indicator. If data is obtained within 500 ms, the default progress bar is not started.| + +## ListenerStatus15+ + +Enumerates the status codes returned when data is obtained from the UDMF. + +**Atomic service API**: This API can be used in atomic services since API version 15. + +**System capability**: SystemCapability.DistributedDataManager.UDMF.Core + +| Name | Value | Description | +| ------- |-----|----------------------------------------------| +| FINISHED | 0 | The task is completed. | +| PROCESSING | 1 | The task is being processed. | +| CANCELED | 2 | The task is canceled. | +| INNER_ERROR | 200 | An internal error occurs. | +| INVALID_PARAMETERS | 201 | [GetDataParams](#getdataparams15) contains invalid parameters.| +| DATA_NOT_FOUND | 202 | No data is obtained. | +| SYNC_FAILED | 203 | Failed to sync data. | +| COPY_FILE_FAILED | 204 | Failed to copy data. | + +## ProgressInfo15+ + +Represents the progress information. + +**Atomic service API**: This API can be used in atomic services since API version 15. + +**System capability**: SystemCapability.DistributedDataManager.UDMF.Core + +| Name | Type | Readable| Writable| Description | +| -------- |-------------------------------------| ---- | ---- |----------------------------------------------------------------| +| progress | number | Yes | No | Progress of the drag task, in percentage.
The value is an integer ranging from -1 to 100. The value **-1** indicates a failure to obtain data, and the value **100** indicates data is obtained.| +| status | [ListenerStatus](#listenerstatus15) | Yes | No | Status code of the drag task reported by the system. | + +## DataProgressListener15+ + +type DataProgressListener = (progressInfo: ProgressInfo, data: UnifiedData | null) => void + +Defines the callback used to return the data retrieval progress information and data obtained. + +**Atomic service API**: This API can be used in atomic services since API version 15. + +**System capability**: SystemCapability.DistributedDataManager.UDMF.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +|----------|-------------------------------|-------|--------------| +| progressInfo| [ProgressInfo](#progressinfo15) | Yes | Progress information to report.| +| data | [UnifiedData](#unifieddata) \| null | Yes | Data obtained when the progress reaches 100. If the progress does not reach 100, **null** is returned.| + +## GetDataParams15+ + +Represents the parameters for obtaining data from UDMF, including the destination directory, option for resolving file conflicts, and progress indicator type. + +For details, see [Obtaining Data Asynchronously Through Drag-and-Drop](../apis-arkui/arkui-ts/ts-universal-events-drag-drop.md#example-3-obtaining-data-asynchronously-through-drag-and-drop). + +**Atomic service API**: This API can be used in atomic services since API version 15. + +**System capability**: SystemCapability.DistributedDataManager.UDMF.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +|----------------------|-------------------------------------------------| ---- |----------------------------------------------------------------------------------------------------------------------------------------------------| +| progressIndicator | [ProgressIndicator](#progressindicator15) | Yes| Progress indicator options. You can use the default progress indicator as required. | +| dataProgressListener | [DataProgressListener](#dataprogresslistener15) | Yes| Callback used to return the data retrieval progress and data obtained. | +| destUri | string | No| Destination directory for the file copied. If file processing is not supported, leave this parameter unspecified, which is the default value of this parameter. If file processing is supported, pass in an existing directory. If complex file processing policies are involved or multipathing file storage is required, you are advised to leave this parameter unspecified and let the application handle file copying. If this parameter is not specified, the source URI is obtained. If this parameter is specified, the specified destination URI is obtained.| +| fileConflictOptions | [FileConflictOptions](#fileconflictoptions15) | No | Option for resolving file copy conflicts. The default value is **OVERWRITE**. | + ## unifiedDataChannel.insertData insertData(options: Options, data: UnifiedData, callback: AsyncCallback<string>): void @@ -905,7 +1253,7 @@ Inserts data to the UDMF public data channel. This API uses an asynchronous call | Name | Type | Mandatory| Description | |----------|----------------------------|----|------------------------------| -| options | [Options](#options) | Yes | Configuration parameters. Only the **intention** is required. | +| options | [Options](#options) | Yes | Configuration for the data insertion operation. The **intention** field is mandatory. If it is not specified, error code 401 will be returned. The settings of other parameters do not affect the use of this API. | | data | [UnifiedData](#unifieddata) | Yes | Data to insert. | | callback | AsyncCallback<string> | Yes | Callback used to return the key (unique identifier) of the data inserted.| @@ -959,7 +1307,7 @@ Inserts data to the UDMF public data channel. This API uses a promise to return | Name | Type | Mandatory| Description | |---------|-----------------------------|----|-----------------------| -| options | [Options](#options) | Yes | Configuration parameters. Only the **intention** is required.| +| options | [Options](#options) | Yes | Configuration for the data insertion operation. The **intention** field is mandatory. If it is not specified, error code 401 will be returned. The settings of other parameters do not affect the use of this API.| | data | [UnifiedData](#unifieddata) | Yes | Data to insert. | **Return value** @@ -1015,7 +1363,7 @@ Updates the data in the UDMF public data channel. This API uses an asynchronous | Name | Type | Mandatory| Description | |----------|-----------------------------|----|-------------------------------------| -| options | [Options](#options) | Yes | Configuration parameters. Only the value of **key** is required. | +| options | [Options](#options) | Yes | Configuration for the data update operation. The **key** field is mandatory. If it is not specified, error code 401 will be returned. The settings of other parameters do not affect the use of this API. | | data | [UnifiedData](#unifieddata) | Yes | New data. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. If the data is updated successfully, **err** is **undefined**. Otherwise, **err** is an error object.| @@ -1069,7 +1417,7 @@ Updates the data in the UDMF public data channel. This API uses a promise to ret | Name | Type | Mandatory| Description | |---------|-----------------------------|----|-----------------| -| options | [Options](#options) | Yes | Configuration parameters. Only the value of **key** is required.| +| options | [Options](#options) | Yes | Configuration for the data update operation. The **key** field is mandatory. If it is not specified, error code 401 will be returned. The settings of other parameters do not affect the use of this API.| | data | [UnifiedData](#unifieddata) | Yes | New data. | **Return value** diff --git a/en/application-dev/reference/apis-arkdata/js-apis-data-uniformDataStruct.md b/en/application-dev/reference/apis-arkdata/js-apis-data-uniformDataStruct.md index 1ab1215b19c44ca1ee2db4aea1a12c00a44a4064..a2a9b321f4da0df3b099e78b3a772a964ef746c7 100644 --- a/en/application-dev/reference/apis-arkdata/js-apis-data-uniformDataStruct.md +++ b/en/application-dev/reference/apis-arkdata/js-apis-data-uniformDataStruct.md @@ -178,3 +178,107 @@ let contentForm : uniformDataStruct.ContentForm = { } console.info('contentForm.uniformDataType: ' + contentForm.uniformDataType); ``` + +## Form15+ + +Represents data of the widget type defined by the system. + +**System capability**: SystemCapability.DistributedDataManager.UDMF.Core + +| Name | Type | Read-Only| Optional| Description | +|------------| ------ | ---- |----|--------------------------------------------------------------------------------------------------------------------------------| +| uniformDataType | 'openharmony.form'| Yes | No | Uniform data type, which has a fixed value of **openharmony.form**. For details, see [UniformDataType](js-apis-data-uniformTypeDescriptor.md#uniformdatatype). +| formId | number | No | No | Widget ID.| +| formName | string | No | No | Widget name.| +| bundleName | string | No | No | Bundle to which the widget belongs.| +| abilityName| string | No | No | Ability name corresponding to the widget.| +| module | string | No | No | Module to which the widget belongs.| +| details | Record | No | Yes | Object of the dictionary type used to describe the icon. The key is of the string type, and the value can be a number, a string, or a Uint8Array. By default, it is an empty dictionary object.| + + +**Example** + +```ts +let u8Array = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); +let formDetails : Record = { + 'formKey1': 123, + 'formKey2': 'formValue', + 'formKey3': u8Array, +} +let form : uniformDataStruct.Form = { + uniformDataType : 'openharmony.form', + formId : 1, + formName : 'formName', + bundleName : 'com.xx.app', + abilityName : 'abilityName', + module : 'module', + details : formDetails +} +console.info('form.uniformDataType: ' + form.uniformDataType); +``` + +## FileUri15+ + +Represents data of the file URI type. + +**System capability**: SystemCapability.DistributedDataManager.UDMF.Core + +| Name | Type | Read-Only| Optional| Description | +|------------| ------ | ---- |----|--------------------------------------------------------------------------------------------------------------------------------| +| uniformDataType | 'general.file-uri'| Yes | No | Uniform data type, which has a fixed value of **general.file-uri**. For details, see [UniformDataType](js-apis-data-uniformTypeDescriptor.md#uniformdatatype). +| oriUri | string | No | No | File URI.| +| fileType | string | No | No | File type.| +| details | Record | No | Yes | Object of the dictionary type used to describe the icon. The key is of the string type, and the value can be a number, a string, or a Uint8Array. By default, it is an empty dictionary object.| + + +**Example** + +```ts +let u8Array = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); +let fileUriDetails : Record = { + 'fileUriKey1': 123, + 'fileUriKey2': 'fileUriValue', + 'fileUriKey3': u8Array, +} +let fileUri : uniformDataStruct.FileUri = { + uniformDataType : 'general.file-uri', + oriUri : 'www.xx.com', + fileType : 'general.image', + details : fileUriDetails +} +console.info('fileUri.uniformDataType: ' + fileUri.uniformDataType); +``` + +## PixelMap15+ + +Represents data of the pixel map type defined by the system. + +**System capability**: SystemCapability.DistributedDataManager.UDMF.Core + +| Name | Type | Read-Only| Optional| Description | +|------------| ------ | ---- |----|--------------------------------------------------------------------------------------------------------------------------------| +| uniformDataType | 'openharmony.pixel-map'| Yes | No | Uniform data type, which has a fixed value of **openharmony.pixel-map**. For details, see [UniformDataType](js-apis-data-uniformTypeDescriptor.md#uniformdatatype). +| pixelMap | image.PixelMap | No | No | Binary data of the pixel map.| +| details | Record | No | Yes | Object of the dictionary type used to describe the icon. The key is of the string type, and the value can be a number, a string, or a Uint8Array. By default, it is an empty dictionary object.| + + +**Example** + +```ts +import image from '@ohos.multimedia.image'; + +let u8Array = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); +let arrayBuffer = new ArrayBuffer(4*200*200); +let opt : image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 200, width: 200 }, alphaType: 3 }; +let pixelMapDetails : Record = { + 'pixelMapKey1': 123, + 'pixelMapKey2': 'pixelMapValue', + 'pixelMapKey3': u8Array, +} +let pixelMap : uniformDataStruct.PixelMap = { + uniformDataType : 'openharmony.pixel-map', + pixelMap : image.createPixelMapSync(arrayBuffer, opt), + details : pixelMapDetails +} +console.info('pixelMap.uniformDataType: ' + pixelMap.uniformDataType); +``` diff --git a/en/application-dev/reference/apis-arkdata/js-apis-data-uniformTypeDescriptor.md b/en/application-dev/reference/apis-arkdata/js-apis-data-uniformTypeDescriptor.md index 0df02077e1cb0401f88e85612fbe9ccf29ded73c..36202c39a123b56b63babb875ca78ee8ed04f4a8 100644 --- a/en/application-dev/reference/apis-arkdata/js-apis-data-uniformTypeDescriptor.md +++ b/en/application-dev/reference/apis-arkdata/js-apis-data-uniformTypeDescriptor.md @@ -196,6 +196,8 @@ Enumerates the uniform data types. Some data types are related. For example, the | OFD12+ | 'general.ofd' | Open Fixed-layout Document (OFD).
This type belongs to **COMPOSITE_OBJECT**. | | CAD12+ | 'general.cad' | Generic type of all computer-aided design types.
This type belongs to **OBJECT**. | | OCTET_STREAM12+ | 'general.octet-stream' | Any binary data type.
This type belongs to **OBJECT**. | +| FILE_URI15+ | 'general.file-uri' | File address type.
This type belongs to **TEXT**. | +| CONTENT_FORM15+ | 'general.content-form' | Content widget type.
This type belongs to **OBJECT**. | ## TypeDescriptor11+ @@ -234,7 +236,7 @@ Checks whether this data type belongs to the specified uniform data type. | Type | Description | | ------- | ------------------------------------------------------------ | -| boolean | Returns **true** if the data type belongs to or is the same as the specified uniform data type; returns **false** if they are not related. | +| boolean | Returns **true** if the data type belongs to or is the same as the specified uniform data type; returns **false** if they are not related.| **Error codes** @@ -280,7 +282,7 @@ Checks whether this data type is a lower-level type of the specified uniform dat | Type | Description | | ------- | ------------------------------------------------------------ | -| boolean | Returns **true** if the data type is a lower-level type of the specified uniform data type; returns **false** otherwise. | +| boolean | Returns **true** if the data type is a lower-level type of the specified uniform data type; returns **false** otherwise.| **Error codes** @@ -326,7 +328,7 @@ Checks whether this data type is a higher-level type of the specified uniform da | Type | Description | | ------- | ------------------------------------------------------------ | -| boolean | Returns **true** if this data type is a higher-level type of the specified uniform data type; returns **false** otherwise.| +| boolean | Returns **true** if the data type is a higher-level type of the specified uniform data type; returns **false** otherwise.| **Error codes** @@ -412,7 +414,7 @@ Obtains the **TypeDescriptor** object based on the uniform data type ID. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| typeId | string | Yes |ID of the uniform data type. | +| typeId | string | Yes |[Uniform data type ID](../../database/uniform-data-type-list.md#generic-utds). | **Return value** @@ -467,7 +469,7 @@ Obtains the uniform data type ID based on the given file name extension and data | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | filenameExtension | string | Yes |File name extension. | -| belongsTo | string | No |ID of the uniform data type to which the target data type belongs. If this parameter is not specified, the uniform data type ID is obtained based on the file name extension. | +| belongsTo | string | No |ID of the uniform data type, to which the data type to be obtained belongs. If this parameter is not specified, the [uniform data type ID](../../database/uniform-data-type-list.md#generic-utds) is queried based on the file name extension. | **Return value** @@ -524,7 +526,7 @@ Obtains the uniform data type ID based on the given MIME type and data type. If | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | mimeType | string | Yes |MIME type. | -| belongsTo | string | No |ID of the uniform data type to which the target data type belongs. If this parameter is not specified, the uniform data type ID is queried based on the MIME type. | +| belongsTo | string | No |ID of the uniform data type, to which the data type to be obtained belongs. This parameter has no default value. If it is not specified, the uniform data type ID (../../database/uniform-data-type-list.md#generic-utds) is queried based on the specified MIME type. | **Return value** @@ -581,7 +583,7 @@ Obtains the uniform data type IDs based on the given file name extension and dat | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | filenameExtension | string | Yes |File name extension. | -| belongsTo | string | No |ID of the uniform data type to which the target data type belongs. If this parameter is not specified, the uniform data type ID is queried based on the file name extension. | +| belongsTo | string | No |ID of the uniform data type, to which the data type to be obtained belongs. If this parameter is not specified, the [uniform data type ID](../../database/uniform-data-type-list.md#generic-utds) is queried based on the file name extension. | **Return value** @@ -638,7 +640,7 @@ Obtains the uniform data type IDs based on the given MIME type and data type. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | mimeType | string | Yes |MIME type. | -| belongsTo | string | No |ID of the uniform data type to which the target data type belongs. If this parameter is not specified, the uniform data type ID is queried based on the MIME type. | +| belongsTo | string | No |ID of the uniform data type, to which the data type to be obtained belongs. This parameter has no default value. If it is not specified, the uniform data type ID (../../database/uniform-data-type-list.md#generic-utds) is queried based on the specified MIME type. | **Return value** diff --git a/en/application-dev/reference/apis-arkdata/js-apis-data-valuesBucket.md b/en/application-dev/reference/apis-arkdata/js-apis-data-valuesBucket.md index 47d8a4d6ea9f5f1523d93ec2cba6a93fd916e165..1d5f98ecf99f77afc5712ac7635bfa65fee1be26 100644 --- a/en/application-dev/reference/apis-arkdata/js-apis-data-valuesBucket.md +++ b/en/application-dev/reference/apis-arkdata/js-apis-data-valuesBucket.md @@ -1,6 +1,6 @@ # @ohos.data.ValuesBucket (Data Set) -The **ValuesBucket** module defines a data set in key-value (KV) format for inserting data into an RDB store. +**ValuesBucket** is a dataset in the form of key-value (KV) pairs that can be inserted in the database. > **NOTE** > @@ -19,7 +19,7 @@ import { ValueType, ValuesBucket } from '@kit.ArkData'; type ValueType = number | string | boolean -Enumerates the value types allowed by the database. +Defines the value types allowed in a **ValuesBucket** instance. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -33,10 +33,10 @@ Enumerates the value types allowed by the database. type ValuesBucket = Record -Defines the types of the key and value in a KV pair. This type is not multi-thread safe. If a **ValuesBucket** instance is operated by multiple threads at the same time in an application, use a lock for the instance. +Defines the types of the key and value in a KV pair. This type is not multi-thread safe. If a **ValuesBucket** instance is operated by multiple threads at the same time in an application, use a lock for it. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core | Type | Description | | ------------- | --------------------------------------------- | -| Record | Types of the key and value in a KV pair. The key type is string, and the value type is [ValueType](#valuetype), Uint8Array, or null. | +| Record | Types of the key and value in a KV pair. The key type is string, and the value type can be [ValueType](#valuetype), Uint8Array, or null. | diff --git a/en/application-dev/reference/apis-arkdata/js-apis-distributed-data.md b/en/application-dev/reference/apis-arkdata/js-apis-distributed-data.md index 2cb080c036845afd629d0811cf61cea7d2211198..29122d8883670e34c60d7506943380a9f3238cd2 100644 --- a/en/application-dev/reference/apis-arkdata/js-apis-distributed-data.md +++ b/en/application-dev/reference/apis-arkdata/js-apis-distributed-data.md @@ -111,7 +111,7 @@ try { ## KVManagerConfig -Defines the configuration of the **KVManager** object, including the bundle name and user information of the caller. +Represents the configuration of a **KVManager** instance, including the bundle name and user information of the caller. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -1223,7 +1223,7 @@ try { equalTo(field: string, value: number|string|boolean): Query -Creates a **Query** object to match the specified field whose value is equal to the given value. +Creates a **Query** object to search for the records with the specified field that are equal to the given value. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -1231,8 +1231,8 @@ Creates a **Query** object to match the specified field whose value is equal to | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| field | string | Yes |Field to match. It cannot contain '^'. | -| value | number\|string\|boolean | Yes | Value specified.| +| field | string | Yes |Field to query. It cannot contain '^'. | +| value | number\|string\|boolean | Yes | Value to match.| **Return value** @@ -1258,7 +1258,7 @@ try { notEqualTo(field: string, value: number|string|boolean): Query -Creates a **Query** object to match the specified field whose value is not equal to the specified value. +Creates a **Query** object to search for the records with the specified field that are not equal to the given value. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -1266,8 +1266,8 @@ Creates a **Query** object to match the specified field whose value is not equal | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| field | string | Yes |Field to match. It cannot contain '^'. | -| value | number\|string\|boolean | Yes | Value specified.| +| field | string | Yes |Field to query. It cannot contain '^'. | +| value | number\|string\|boolean | Yes | Value to match.| **Return value** @@ -1293,7 +1293,7 @@ try { greaterThan(field: string, value: number|string|boolean): Query -Creates a **Query** object to match the specified field whose value is greater than the specified value. +Creates a **Query** object to search for the records with the specified field that are greater than the given value. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -1301,8 +1301,8 @@ Creates a **Query** object to match the specified field whose value is greater t | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| field | string | Yes |Field to match. It cannot contain '^'. | -| value | number\|string\|boolean | Yes | Value specified.| +| field | string | Yes |Field to query. It cannot contain '^'. | +| value | number\|string\|boolean | Yes | Value to match.| **Return value** @@ -1328,7 +1328,7 @@ try { lessThan(field: string, value: number|string): Query -Creates a **Query** object to match the specified field whose value is less than the specified value. +Creates a **Query** object to search for the records with the specified field that are less than the given value. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -1336,8 +1336,8 @@ Creates a **Query** object to match the specified field whose value is less than | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| field | string | Yes |Field to match. It cannot contain '^'. | -| value | number\|string | Yes | Value specified.| +| field | string | Yes |Field to query. It cannot contain '^'. | +| value | number\|string | Yes | Value to match.| **Return value** @@ -1363,7 +1363,7 @@ try { greaterThanOrEqualTo(field: string, value: number|string): Query -Creates a **Query** object to match the specified field whose value is greater than or equal to the specified value. +Creates a **Query** object to search for the records with the specified field that are greater than or equal to the given value. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -1371,8 +1371,8 @@ Creates a **Query** object to match the specified field whose value is greater t | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| field | string | Yes |Field to match. It cannot contain '^'. | -| value | number\|string | Yes | Value specified.| +| field | string | Yes |Field to query. It cannot contain '^'. | +| value | number\|string | Yes | Value to match.| **Return value** @@ -1398,7 +1398,7 @@ try { lessThanOrEqualTo(field: string, value: number|string): Query -Creates a **Query** object to match the specified field whose value is less than or equal to the specified value. +Creates a **Query** object to search for the records with the specified field that are less than or equal to the given value. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -1406,8 +1406,8 @@ Creates a **Query** object to match the specified field whose value is less than | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| field | string | Yes |Field to match. It cannot contain '^'. | -| value | number\|string | Yes | Value specified.| +| field | string | Yes |Field to query. It cannot contain '^'. | +| value | number\|string | Yes | Value to match.| **Return value** @@ -1433,7 +1433,7 @@ try { isNull(field: string): Query -Creates a **Query** object to match the specified field whose value is **null**. +Creates a **Query** object to search for the records with the specified field that are **null**. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -1441,7 +1441,7 @@ Creates a **Query** object to match the specified field whose value is **null**. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| field | string | Yes |Field to match. It cannot contain '^'. | +| field | string | Yes |Field to query. It cannot contain '^'. | **Return value** @@ -1467,7 +1467,7 @@ try { inNumber(field: string, valueList: number[]): Query -Creates a **Query** object to match the specified field whose value is within the specified list of numbers. +Creates a **Query** object to search for the records with the specified field that are within the given number list. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -1476,8 +1476,8 @@ Creates a **Query** object to match the specified field whose value is within th | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| field | string | Yes |Field to match. It cannot contain '^'. | -| valueList | number[] | Yes | List of numbers.| +| field | string | Yes |Field to query. It cannot contain '^'. | +| valueList | number[] | Yes | List of numbers to match.| **Return value** @@ -1503,7 +1503,7 @@ try { inString(field: string, valueList: string[]): Query -Creates a **Query** object to match the specified field whose value is within the specified list of strings. +Creates a **Query** object to search for the records with the specified field that are within the given string list. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -1511,8 +1511,8 @@ Creates a **Query** object to match the specified field whose value is within th | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| field | string | Yes |Field to match. It cannot contain '^'. | -| valueList | string[] | Yes | List of strings.| +| field | string | Yes |Field to query. It cannot contain '^'. | +| valueList | string[] | Yes | List of strings to match.| **Return value** @@ -1538,7 +1538,7 @@ try { notInNumber(field: string, valueList: number[]): Query -Creates a **Query** object to match the specified field whose value is not within the specified list of numbers. +Creates a **Query** object to search for the records with the specified field that are not within the given number list. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -1546,8 +1546,8 @@ Creates a **Query** object to match the specified field whose value is not withi | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| field | string | Yes |Field to match. It cannot contain '^'. | -| valueList | number[] | Yes | List of numbers.| +| field | string | Yes |Field to query. It cannot contain '^'. | +| valueList | number[] | Yes | List of numbers to match.| **Return value** @@ -1573,7 +1573,7 @@ try { notInString(field: string, valueList: string[]): Query -Creates a **Query** object to match the specified field whose value is not within the specified list of strings. +Creates a **Query** object to search for the records with the specified field that are not within the given string list. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -1581,8 +1581,8 @@ Creates a **Query** object to match the specified field whose value is not withi | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| field | string | Yes |Field to match. It cannot contain '^'. | -| valueList | string[] | Yes | List of strings.| +| field | string | Yes |Field to query. It cannot contain '^'. | +| valueList | string[] | Yes | List of strings to match.| **Return value** @@ -1608,7 +1608,7 @@ try { like(field: string, value: string): Query -Creates a **Query** object to match the specified field whose value is similar to the specified string. +Creates a **Query** object to search for the records with the specified field that are similar to the given string. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -1616,8 +1616,8 @@ Creates a **Query** object to match the specified field whose value is similar t | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| field | string | Yes |Field to match. It cannot contain '^'. | -| value | string | Yes | String specified.| +| field | string | Yes |Field to query. It cannot contain '^'. | +| value | string | Yes | String to match.| **Return value** @@ -1643,7 +1643,7 @@ try { unlike(field: string, value: string): Query -Creates a **Query** object to match the specified field whose value is not similar to the specified string. +Creates a **Query** object to search for the records with the specified field that are not similar to the given string. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -1651,8 +1651,8 @@ Creates a **Query** object to match the specified field whose value is not simil | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| field | string | Yes |Field to match. It cannot contain '^'. | -| value | string | Yes | String specified.| +| field | string | Yes |Field to query. It cannot contain '^'. | +| value | string | Yes | String to match.| **Return value** @@ -1746,7 +1746,7 @@ Creates a **Query** object to sort the query results in ascending order. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| field | string | Yes |Field to match. It cannot contain '^'. | +| field | string | Yes |Field to query. It cannot contain '^'. | **Return value** @@ -1781,7 +1781,7 @@ Creates a **Query** object to sort the query results in descending order. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| field | string | Yes |Field to match. It cannot contain '^'. | +| field | string | Yes |Field to query. It cannot contain '^'. | **Return value** @@ -1808,7 +1808,7 @@ try { limit(total: number, offset: number): Query -Creates a **Query** object to specify the number of results and where to start. +Creates a **Query** object to specify the number of records in the query result and the start position. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -1816,8 +1816,8 @@ Creates a **Query** object to specify the number of results and where to start. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| total | number | Yes |Number of results to query. | -| offset | number | Yes |Start position for query. | +| total | number | Yes |Number of records in the query result. | +| offset | number | Yes |Start position. | **Return value** @@ -1846,7 +1846,7 @@ try { isNotNull(field: string): Query -Creates a **Query** object to match the specified field whose value is not **null**. +Creates a **Query** object to search for the records whose value is not **null**. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -1854,7 +1854,7 @@ Creates a **Query** object to match the specified field whose value is not **nul | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| field | string | Yes |Field to match. It cannot contain '^'. | +| field | string | Yes |Field to query. It cannot contain '^'. | **Return value** @@ -2056,7 +2056,7 @@ Obtains the query statement of the **Query** object. | Type | Description | | ------ | ------- | -| string |Returns the query statement obtained.| +| string |Query statement obtained.| **Example** @@ -2262,7 +2262,7 @@ kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, fun on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void -Subscribes to sync complete events. +Subscribes to sync completion events. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2270,8 +2270,8 @@ Subscribes to sync complete events. | Name | Type | Mandatory| Description | | ------------ | --------------------------------------------- | ---- | ------------------------------------------------------ | -| event | string | Yes | Event type. The value is **syncComplete**, which indicates a sync complete event.| -| syncCallback | Callback<Array<[string, number]>> | Yes | Callback used to return a sync complete event. | +| event | string | Yes | Event type. The value is **syncComplete**, which indicates a sync completion event.| +| syncCallback | Callback<Array<[string, number]>> | Yes | Callback used to return a sync completion event. | **Example** @@ -2324,7 +2324,7 @@ class KvstoreModel { off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void -Unsubscribes from sync complete events. +Unsubscribes from sync completion events. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2332,8 +2332,8 @@ Unsubscribes from sync complete events. | Name | Type | Mandatory| Description | | ------------ | --------------------------------------------- | ---- | ---------------------------------------------------------- | -| event | string | Yes | Event type. The value is **syncComplete**, which indicates a sync complete event.| -| syncCallback | Callback<Array<[string, number]>> | No | Callback to unregister. If this parameter is not specified, all callbacks for the sync complete event will be unregistered.| +| event | string | Yes | Event type. The value is **syncComplete**, which indicates a sync completion event.| +| syncCallback | Callback<Array<[string, number]>> | No | Callback to unregister. If this parameter is not specified, all callbacks for the sync completion event will be unregistered.| **Example** @@ -3851,7 +3851,7 @@ kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, fun on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void -Subscribes to sync complete events. +Subscribes to sync completion events. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3859,8 +3859,8 @@ Subscribes to sync complete events. | Name | Type | Mandatory| Description | | ------------ | --------------------------------------------- | ---- | ------------------------------------------------------ | -| event | string | Yes | Event type. The value is **syncComplete**, which indicates a sync complete event.| -| syncCallback | Callback<Array<[string, number]>> | Yes | Callback used to return a sync complete event. | +| event | string | Yes | Event type. The value is **syncComplete**, which indicates a sync completion event.| +| syncCallback | Callback<Array<[string, number]>> | Yes | Callback used to return a sync completion event. | **Example** @@ -3922,7 +3922,7 @@ class KvstoreModel { off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void -Unsubscribes from sync complete events. +Unsubscribes from sync completion events. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3930,8 +3930,8 @@ Unsubscribes from sync complete events. | Name | Type | Mandatory| Description | | ------------ | --------------------------------------------- | ---- | ---------------------------------------------------------- | -| event | string | Yes | Event type. The value is **syncComplete**, which indicates a sync complete event.| -| syncCallback | Callback<Array<[string, number]>> | No | Callback to unregister. If this parameter is not specified, all callbacks for the sync complete event will be unregistered. | +| event | string | Yes | Event type. The value is **syncComplete**, which indicates a sync completion event.| +| syncCallback | Callback<Array<[string, number]>> | No | Callback to unregister. If this parameter is not specified, all callbacks for the sync completion event will be unregistered. | **Example** @@ -5329,7 +5329,7 @@ kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, fun on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void -Subscribes to sync complete events. +Subscribes to sync completion events. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -5337,8 +5337,8 @@ Subscribes to sync complete events. | Name | Type | Mandatory| Description | | ------------ | --------------------------------------------- | ---- | ------------------------------------------------------ | -| event | string | Yes | Event type. The value is **syncComplete**, which indicates a sync complete event.| -| syncCallback | Callback<Array<[string, number]>> | Yes | Callback used to return a sync complete event. | +| event | string | Yes | Event type. The value is **syncComplete**, which indicates a sync completion event.| +| syncCallback | Callback<Array<[string, number]>> | Yes | Callback used to return a sync completion event. | **Example** @@ -5400,7 +5400,7 @@ class KvstoreModel { off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void -Unsubscribes from sync complete events. +Unsubscribes from sync completion events. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -5408,8 +5408,8 @@ Unsubscribes from sync complete events. | Name | Type | Mandatory| Description | | ------------ | --------------------------------------------- | ---- | ---------------------------------------------------------- | -| event | string | Yes | Event type. The value is **syncComplete**, which indicates a sync complete event.| -| syncCallback | Callback<Array<[string, number]>> | No | Callback to unregister. If this parameter is not specified, all callbacks for the sync complete event will be unregistered. | +| event | string | Yes | Event type. The value is **syncComplete**, which indicates a sync completion event.| +| syncCallback | Callback<Array<[string, number]>> | No | Callback to unregister. If this parameter is not specified, all callbacks for the sync completion event will be unregistered. | **Example** diff --git a/en/application-dev/reference/apis-arkdata/js-apis-distributedKVStore-sys.md b/en/application-dev/reference/apis-arkdata/js-apis-distributedKVStore-sys.md index 6d4a60c8f4260ffeaec76dc11bce2c31c8c2e9dd..2014ddc7b24dbee665bbaaba0583c3df75e4fb1e 100644 --- a/en/application-dev/reference/apis-arkdata/js-apis-distributedKVStore-sys.md +++ b/en/application-dev/reference/apis-arkdata/js-apis-distributedKVStore-sys.md @@ -315,7 +315,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](errorc | ------------ | -------------------------------------- | | 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| | 202 | Permission verification failed, application which is not a system application uses system API.| -| 15100001 | Upper limit exceeded. | +| 15100001 | Over max limits. | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -368,7 +368,7 @@ Obtains a **KVStoreResultSet** object that matches the specified conditions. Thi | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | -| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the KV pairs to delete. If this parameter is **null**, define the processing logic.| +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic.| **Return value** @@ -384,7 +384,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](errorc | ------------ | -------------------------------------- | | 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| | 202 | Permission verification failed, application which is not a system application uses system API.| -| 15100001 | Upper limit exceeded. | +| 15100001 | Over max limits. | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -444,7 +444,7 @@ Obtains a **KVStoreResultSet** object that matches the specified conditions for | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic. | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic. | | callback | AsyncCallback<[KVStoreResultSet](js-apis-distributedKVStore.md#kvstoreresultset)> | Yes | Callback used to return the **KVStoreResultSet** object obtained.| **Error codes** @@ -455,7 +455,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](errorc | ------------ | -------------------------------------- | | 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| | 202 | Permission verification failed, application which is not a system application uses system API.| -| 15100001 | Upper limit exceeded. | +| 15100001 | Over max limits. | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -508,7 +508,7 @@ Obtains a **KVStoreResultSet** object that matches the specified conditions for | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | -| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the KV pairs to delete. If this parameter is **null**, define the processing logic.| +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic. | **Return value** @@ -524,7 +524,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](errorc | ------------ | -------------------------------------- | | 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| | 202 | Permission verification failed, application which is not a system application uses system API.| -| 15100001 | Upper limit exceeded. | +| 15100001 | Over max limits. | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -578,7 +578,7 @@ Obtains a **KVStoreResultSet** object that matches the specified conditions for | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | deviceId | string | Yes | ID of the target device. | -| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic. | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic. | | callback | AsyncCallback<[KVStoreResultSet](js-apis-distributedKVStore.md#kvstoreresultset)> | Yes | Callback used to return the **KVStoreResultSet** object obtained.| **Error codes** @@ -589,7 +589,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](errorc | ------------ | -------------------------------------- | | 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| | 202 | Permission verification failed, application which is not a system application uses system API.| -| 15100001 | Upper limit exceeded. | +| 15100001 | Over max limits. | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -647,7 +647,7 @@ Obtains a **KVStoreResultSet** object that matches the specified conditions for | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | | deviceId | string | Yes | ID of the target device. | -| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the KV pairs to delete. If this parameter is **null**, define the processing logic.| +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic. | **Return value** @@ -663,7 +663,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](errorc | ------------ | -------------------------------------- | | 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| | 202 | Permission verification failed, application which is not a system application uses system API.| -| 15100001 | Upper limit exceeded. | +| 15100001 | Over max limits. | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | diff --git a/en/application-dev/reference/apis-arkdata/js-apis-distributedKVStore.md b/en/application-dev/reference/apis-arkdata/js-apis-distributedKVStore.md index 4ec9c8ad4465c35eab43393bbb2e692ef4d1d98a..d24402abeb172c83ec02759d4f02c4c9cd62b0f8 100644 --- a/en/application-dev/reference/apis-arkdata/js-apis-distributedKVStore.md +++ b/en/application-dev/reference/apis-arkdata/js-apis-distributedKVStore.md @@ -1,14 +1,14 @@ # @ohos.data.distributedKVStore (Distributed KV Store) -The **distributedKVStore** module implements collaboration between databases for different devices that forms a Super Device. You can use the APIs provided by this module to save application data to a distributed key-value (KV) store and perform operations, such as adding, deleting, modifying, querying, and synchronizing data in distributed KV stores. +The **distributedKVStore** module implements collaboration between databases for different devices that forms a Super Device. You can use the APIs provided by this module to save application data to a distributed key-value (KV) store and perform operations, such as adding, deleting, modifying, and querying data, and synchronizing data across devices. The **distributedKVStore** module provides the following functionalities: - [KVManager](#kvmanager): provides a **KVManager** instance to obtain KV store information. - [KVStoreResultSet](#kvstoreresultset): provides APIs for accessing the results obtained from a KV store. - [Query](#query): provides APIs for setting predicates for data query. -- [SingleKVStore](#singlekvstore): provides APIs for querying and synchronizing data in single KV stores. The single KV stores manage data without distinguishing devices. -- [DeviceKVStore](#devicekvstore): provides APIs for querying and synchronizing data in device KV stores. This class inherits from [SingleKVStore](#singlekvstore). The device KV stores manage data by device. +- [SingleKVStore](#singlekvstore): provides APIs for querying data in single KV stores and synchronizing data across devices. The single KV stores manage data without distinguishing devices. +- [DeviceKVStore](#devicekvstore): provides APIs for querying data in device KV stores and synchronizing data across devices. This class inherits from [SingleKVStore](#singlekvstore). The device KV stores manage data by device. > **NOTE** > @@ -52,14 +52,14 @@ Enumerates the types of the value in a KV pair. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core -| Name | Description | -| ---------- | ---------------------- | -| STRING | String. | -| INTEGER | Integer. | -| FLOAT | Float (single-precision floating point). | -| BYTE_ARRAY | Byte array.| -| BOOLEAN | Boolean. | -| DOUBLE | Double (double-precision floating point).| +| Name | Value| Description | +| ---------- | - | -------------------- | +| STRING | 0 | String. | +| INTEGER | 1 | Integer. | +| FLOAT | 2 | Float (single-precision floating point). | +| BYTE_ARRAY | 3 | Byte array.| +| BOOLEAN | 4 | Boolean. | +| DOUBLE | 5 | Double (double-precision floating point).| ## Value @@ -102,11 +102,11 @@ Enumerates the sync modes. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core -| Name | Description | -| --------- | ---------------------------------------------------- | -| PULL_ONLY | Pull data from the peer end to the local end only. | -| PUSH_ONLY | Push data from the local end to the peer end only. | -| PUSH_PULL | Push data from the local end to the peer end and then pull data from the peer end to the local end.| +| Name | Value| Description | +| --------- | - | ---------------------------------------------- | +| PULL_ONLY | 0 | Pull data from the peer end to the local end only. | +| PUSH_ONLY | 1 | Push data from the local end to the peer end only. | +| PUSH_PULL | 2 | Push data from the local end to the peer end and then pull data from the peer end to the local end.| ## SubscribeType @@ -114,20 +114,20 @@ Enumerates the subscription types. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core -| Name | Description | -| --------------------- | ---------------------------- | -| SUBSCRIBE_TYPE_LOCAL | Local data changes. | -| SUBSCRIBE_TYPE_REMOTE | Remote data changes. | -| SUBSCRIBE_TYPE_ALL | Local and remote data changes.| +| Name | Value| Description | +| --------------------- | - | ---------------------------- | +| SUBSCRIBE_TYPE_LOCAL | 0 | Local data changes. | +| SUBSCRIBE_TYPE_REMOTE | 1 | Remote data changes. | +| SUBSCRIBE_TYPE_ALL | 2 | Local and remote data changes. | ## KVStoreType Enumerates the distributed KV store types. -| Name | Description | -| -------------------- | ------------------------------------------------------------ | -| DEVICE_COLLABORATION | Device KV store.
The device KV store manages data by device, which eliminates conflicts. Data can be queried by device.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore| -| SINGLE_VERSION | Single KV store.
The single KV store does not differentiate data by device. If entries with the same key are modified on different devices, the value will be overwritten.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| +| Name | Value| Description | +| -------------------- | - | ------------------------------------------------------------ | +| DEVICE_COLLABORATION | 0 | Device KV store.
The device KV store manages data by device, which eliminates conflicts. Data can be queried by device.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore| +| SINGLE_VERSION | 1 | Single KV store.
The single KV store does not differentiate data by device. If entries with the same key are modified on different devices, the value will be overwritten.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| ## SecurityLevel @@ -141,12 +141,12 @@ Enumerates the KV store security levels. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core -| Name | Description | -| -------: | ------------------------------------------------------------ | -| S1 | Low security level. Disclosure, tampering, corruption, or loss of the data may cause minor impact on an individual or group.
Examples: gender and nationality information, and user application records| -| S2 | Medium security level. Disclosure, tampering, corruption, or loss of the data may cause major impact on an individual or group.
Examples: individual mailing addresses and nicknames| -| S3 | High security level. Disclosure, tampering, corruption, or loss of the data may cause critical impact on an individual or group.
Examples: real-time precise positioning information and movement trajectory | -| S4 | Critical security level. Disclosure, tampering, corruption, or loss of the data may cause significant adverse impact on an individual or group.
Examples: political opinions, religious and philosophical belief, trade union membership, genetic data, biological information, health and sexual life status, sexual orientation, device authentication, and personal credit card information| +| Name | Value| Description | +| -------: | - | ------------------------------------------------------------ | +| S1 | 2 | Low security level. Disclosure, tampering, corruption, or loss of the data may cause minor impact on an individual or group.
Examples: gender and nationality information, and user application records| +| S2 | 3 | Medium security level. Disclosure, tampering, corruption, or loss of the data may cause major impact on an individual or group.
Examples: individual mailing addresses and nicknames| +| S3 | 5 | High security level. Disclosure, tampering, corruption, or loss of the data may cause critical impact on an individual or group.
Examples: real-time precise positioning information and movement trajectory | +| S4 | 6 | Critical security level. Disclosure, tampering, corruption, or loss of the data may cause significant adverse impact on an individual or group.

Examples: political opinions, religious and philosophical belief, trade union membership, genetic data, biological information, health and sexual life status, sexual orientation, device authentication, and personal credit card information| ## Options @@ -393,7 +393,7 @@ Creates and obtains a distributed KV store based on the specified **options** an > **NOTE** > -> If the database file cannot be opened (for example, the file header is damaged) when an existing distributed KV store is obtained, the automatic rebuild logic will be triggered to return a newly created distributed KV store instance. For important data that cannot be regenerated, you are advised to use the backup and restore feature to prevent data loss. For details, see [Database Backup and Restoration](../../database/data-backup-and-restore.md). +> If the database file cannot be opened (for example, the file header is damaged) when an existing distributed KV store is obtained, the automatic rebuild logic will be triggered to return a newly created distributed KV store instance. For important data that cannot be regenerated, you are advised to use the backup and restore feature to prevent data loss. For details, see [Database Backup and Restore](../../database/data-backup-and-restore.md). **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -412,7 +412,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](errorc | ID| **Error Message** | | ------------ | ------------------------------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types; 3. Parameter verification failed. | -| 15100002 | The options configuration changes when the API is called to obtain a KV store. | +| 15100002 | Open existed database with changed options. | | 15100003 | Database corrupted. | | 15100006 | Unable to open the database file. | @@ -458,7 +458,7 @@ Creates and obtains a distributed KV store based on the specified **options** an > **NOTE** > -> If the database file cannot be opened (for example, the file header is damaged) when an existing distributed KV store is obtained, the automatic rebuild logic will be triggered to return a newly created distributed KV store instance. For important data that cannot be regenerated, you are advised to use the backup and restore feature to prevent data loss. For details, see [Database Backup and Restoration](../../database/data-backup-and-restore.md). +> If the database file cannot be opened (for example, the file header is damaged) when an existing distributed KV store is obtained, the automatic rebuild logic will be triggered to return a newly created distributed KV store instance. For important data that cannot be regenerated, you are advised to use the backup and restore feature to prevent data loss. For details, see [Database Backup and Restore](../../database/data-backup-and-restore.md). **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -482,7 +482,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](errorc | ID| **Error Message** | | ------------ | ------------------------------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types; 3. Parameter verification failed.| -| 15100002 | The options configuration changes when the API is called to obtain a KV store. | +| 15100002 | Open existed database with changed options. | | 15100003 | Database corrupted. | | 15100006 | Unable to open the database file. | @@ -664,7 +664,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](errorc | ID| **Error Message**| | ------------ | ------------ | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Parameter verification failed.| -| 15100004 | Data not found. | +| 15100004 | Not found. | **Example** @@ -734,7 +734,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](errorc | ID| **Error Message**| | ------------ | ------------ | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Parameter verification failed.| -| 15100004 | Data not found. | +| 15100004 | Not found. | **Example** @@ -866,7 +866,7 @@ try { on(event: 'distributedDataServiceDie', deathCallback: Callback<void>): void -Subscribes to the termination (death) of the distributed data service. If the service is terminated, you need to register the callbacks for data change notifications and sync complete notifications again. In addition, an error will be returned for a sync operation. +Subscribes to the termination (death) of the distributed data service. If the service is terminated, you need to register the callbacks for data change notifications and cross-device sync completion notifications again. In addition, an error will be returned for a sync operation. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -948,6 +948,10 @@ Provides APIs for obtaining the distributed KV store result sets. A maximum of e Before calling any API in **KVStoreResultSet**, you must use **[getKVStore](#getkvstore)** to construct a **SingleKVStore** or **DeviceKVStore** instance. +> **NOTE** +> +> The cursor start position of **KVStoreResultSet** is **-1**. + ### getCount getCount(): number @@ -1173,7 +1177,7 @@ Moves the data read position with the specified offset from the current position | Name| Type| Mandatory| Description | | ------ | -------- | ---- | ------------------------------------------------------------ | -| offset | number | Yes | Offset to move the data read position. A negative value means to move backward, and a positive value means to move forward.| +| offset | number | Yes | Offset to move the data read position. A positive value means to move forward; a negative value means to move backward. If the cursor is beyond the start or end position of the result set, **false** is returned.| **Return value** @@ -1223,7 +1227,7 @@ Moves the data read position from 0 to an absolute position. | Name | Type| Mandatory| Description | | -------- | -------- | ---- | -------------- | -| position | number | Yes | Absolute position to move to.| +| position | number | Yes | Absolute position to move to. If the absolute position exceeds the start or end position of the result set, **false** is returned.| **Return value** @@ -2229,7 +2233,7 @@ Creates a **Query** object to specify the number of records of the query result | Name| Type| Mandatory| Description | | ------ | -------- | ---- | ------------------ | | total | number | Yes | Number of results to query.| -| offset | number | Yes | Start position for query. | +| offset | number | Yes | Start position of the query result. By default, the start position is the beginning of the result set. If **offset** is a negative number, the start position is the beginning of the result set. If **offset** exceeds the end of the result set, the query result is empty.| **Return value** @@ -2427,7 +2431,7 @@ Creates a **Query** object with an index preferentially used for query. | Name| Type| Mandatory| Description | | ------ | -------- | ---- | ------------------ | -| index | string | Yes | Index preferentially used for query. It cannot contain '^'. If the value contains '^', the predicate becomes invalid and all data in the KV store will be returned.| +| index | string | Yes | Index to set, which cannot contain '^'. If the value contains '^', the predicate becomes invalid and all data in the KV store will be returned.| **Return value** @@ -2537,7 +2541,7 @@ try { ## SingleKVStore -Implements data management in a single KV store, such as adding data, deleting data, and subscribing to data changes or data sync completion. +Provides APIs for data management in a single KV store, such as adding data, deleting data, and subscribing to data changes or across-device data sync completion events. Before calling any method in **SingleKVStore**, you must use [getKVStore](#getkvstore) to obtain a **SingleKVStore** instance. @@ -3217,7 +3221,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](errorc | ------------ | -------------------------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types; 3. Parameter verification failed. | | 15100003 | Database corrupted. | -| 15100004 | Data not found. | +| 15100004 | Not found. | | 15100005 | Database or result set already closed. | **Example** @@ -3279,7 +3283,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](errorc | ------------ | -------------------------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types; 3. Parameter verification failed. | | 15100003 | Database corrupted. | -| 15100004 | Data not found. | +| 15100004 | Not found. | | 15100005 | Database or result set already closed. | **Example** @@ -3606,7 +3610,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](errorc | ID| **Error Message** | | ------------ | -------------------------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types. | -| 15100001 | Upper limit exceeded. | +| 15100001 | Over max limits. | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -3689,7 +3693,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](errorc | ID| **Error Message** | | ------------ | -------------------------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types.| -| 15100001 | Upper limit exceeded. | +| 15100001 | Over max limits. | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -3758,7 +3762,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](errorc | ID| **Error Message** | | ------------ | -------------------------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types.| -| 15100001 | Upper limit exceeded. | +| 15100001 | Over max limits. | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -3832,7 +3836,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](errorc | ID| **Error Message** | | ------------ | -------------------------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types.| -| 15100001 | Upper limit exceeded. | +| 15100001 | Over max limits. | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -4679,7 +4683,7 @@ try { enableSync(enabled: boolean, callback: AsyncCallback<void>): void -Sets data sync, which can be enabled or disabled. This API uses an asynchronous callback to return the result. +Sets cross-device data sync, which can be enabled or disabled. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -4687,7 +4691,7 @@ Sets data sync, which can be enabled or disabled. This API uses an asynchronous | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | --------------------------------------------------------- | -| enabled | boolean | Yes | Whether to enable data sync. The value **true** means to enable data sync, and **false** means the opposite.| +| enabled | boolean | Yes | Whether to enable data sync across devices. The value **true** means to enable data sync across devices, and the value **false** means the opposite.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. | **Error codes** @@ -4721,7 +4725,7 @@ try { enableSync(enabled: boolean): Promise<void> -Sets data sync, which can be enabled or disabled. This API uses a promise to return the result. +Sets cross-device data sync, which can be enabled or disabled. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -4729,7 +4733,7 @@ Sets data sync, which can be enabled or disabled. This API uses a promise to ret | Name | Type| Mandatory| Description | | ------- | -------- | ---- | --------------------------------------------------------- | -| enabled | boolean | Yes | Whether to enable data sync. The value **true** means to enable data sync, and **false** means the opposite.| +| enabled | boolean | Yes | Whether to enable data sync across devices. The value **true** means to enable data sync across devices, and the value **false** means the opposite.| **Return value** @@ -4859,7 +4863,11 @@ try { setSyncParam(defaultAllowedDelayMs: number, callback: AsyncCallback<void>): void -Sets the default delay allowed for KV store sync. This API uses an asynchronous callback to return the result. +Sets the default delay for cross-device data sync. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> After the default delay is set, calling [sync](#sync) will not trigger the cross-device data sync immediately. Instead, the data sync will be executed only after the specified delay duration. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -4867,7 +4875,7 @@ Sets the default delay allowed for KV store sync. This API uses an asynchronous | Name | Type | Mandatory| Description | | --------------------- | ------------------------- | ---- | -------------------------------------------- | -| defaultAllowedDelayMs | number | Yes | Default delay allowed for database sync, in ms.| +| defaultAllowedDelayMs | number | Yes | Delay time to set, in ms.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| **Error codes** @@ -4902,7 +4910,11 @@ try { setSyncParam(defaultAllowedDelayMs: number): Promise<void> -Sets the default delay allowed for KV store sync. This API uses a promise to return the result. +Sets the default delay for cross-device data sync. This API uses a promise to return the result. + +> **NOTE** +> +> After the default delay is set, calling [sync](#sync) will not trigger the cross-device data sync immediately. Instead, the data sync will be executed only after the specified delay duration. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -4910,7 +4922,7 @@ Sets the default delay allowed for KV store sync. This API uses a promise to ret | Name | Type| Mandatory| Description | | --------------------- | -------- | ---- | -------------------------------------------- | -| defaultAllowedDelayMs | number | Yes | Default delay allowed for database sync, in ms.| +| defaultAllowedDelayMs | number | Yes | Delay time to set, in ms.| **Return value** @@ -4948,7 +4960,7 @@ try { sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void -Synchronizes the KV store manually. For details about the sync modes of KV stores, see [Cross-Device Synchronization of KV Stores](../../database/data-sync-of-kv-store.md). +Starts cross-device data sync manually. For details about the sync modes of KV stores, see [Cross-Device Synchronization of KV Stores](../../database/data-sync-of-kv-store.md). > **NOTE** > > **deviceIds** is **networkId** in [DeviceBasicInfo](../apis-distributedservice-kit/js-apis-distributedDeviceManager.md#devicebasicinfo), which can be obtained by [deviceManager.getAvailableDeviceListSync](../apis-distributedservice-kit/js-apis-distributedDeviceManager.md#getavailabledevicelistsync). @@ -4963,7 +4975,7 @@ Synchronizes the KV store manually. For details about the sync modes of KV store | --------- | --------------------- | ---- | ---------------------------------------------- | | deviceIds | string[] | Yes | List of **networkId**s of the devices in the same networking environment to be synchronized.| | mode | [SyncMode](#syncmode) | Yes | Sync mode. | -| delayMs | number | No | Delay time allowed, in ms. The default value is **0**. | +| delayMs | number | No | Delay time allowed, in ms. The default value is **0**. If **delayMs** is set, data sync will be executed **delayMs** after **sync()** is called. If **delayMs** is not set, the delay set in [setSyncParam](#setsyncparam) is used.| **Error codes** @@ -4973,7 +4985,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](errorc | ------------ | ------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types.| | 15100003 | Database corrupted. | -| 15100004 | Data not found. | +| 15100004 | Not found. | **Example** @@ -5034,7 +5046,7 @@ export default class EntryAbility extends UIAbility { sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void -Synchronizes the KV store manually. This API returns the result synchronously. For details about the sync modes of KV stores, see [Cross-Device Synchronization of KV Stores](../../database/data-sync-of-kv-store.md). +Starts cross-device data sync manually. This API returns the result synchronously. For details about the sync modes of KV stores, see [Cross-Device Synchronization of KV Stores](../../database/data-sync-of-kv-store.md). > **NOTE** > > **deviceIds** is **networkId** in [DeviceBasicInfo](../apis-distributedservice-kit/js-apis-distributedDeviceManager.md#devicebasicinfo), which can be obtained by [deviceManager.getAvailableDeviceListSync](../apis-distributedservice-kit/js-apis-distributedDeviceManager.md#getavailabledevicelistsync). @@ -5050,7 +5062,7 @@ Synchronizes the KV store manually. This API returns the result synchronously. F | deviceIds | string[] | Yes | List of **networkId**s of the devices in the same networking environment to be synchronized.| | mode | [SyncMode](#syncmode) | Yes | Sync mode. | | query | [Query](#query) | Yes | **Query** object to match. | -| delayMs | number | No | Delay time allowed, in ms. The default value is **0**. | +| delayMs | number | No | Delay time allowed, in ms. The default value is **0**. If **delayMs** is set, data sync will be executed **delayMs** after **sync()** is called. If **delayMs** is not set, the delay set in [setSyncParam](#setsyncparam) is used.| **Error codes** @@ -5060,7 +5072,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](errorc | ------------ | ------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types.| | 15100003 | Database corrupted. | -| 15100004 | Data not found. | +| 15100004 | Not found. | **Example** @@ -5132,9 +5144,9 @@ Subscribes to data changes of the specified type. | Name | Type | Mandatory| Description | | -------- | --------------------------------------------------------- | ---- | ---------------------------------------------------- | -| event | string | Yes | Event type. The value is **dataChange**, which indicates data changes.| +| event | string | Yes | Event type. The value is **dataChange**, which indicates a data change event.| | type | [SubscribeType](#subscribetype) | Yes | Type of data change. | -| listener | Callback<[ChangeNotification](#changenotification)> | Yes | Callback used to return the data change. | +| listener | Callback<[ChangeNotification](#changenotification)> | Yes | Callback used to return the object to be notified when the data changes.| **Error codes** @@ -5143,7 +5155,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](errorc | ID| **Error Message** | | ------------ | -------------------------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types. | -| 15100001 | Upper limit exceeded. | +| 15100001 | Over max limits. | | 15100005 | Database or result set already closed. | **Example** @@ -5165,7 +5177,7 @@ try { on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void -Subscribes to sync complete events. +Subscribes to the cross-device data sync completion events. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -5173,8 +5185,8 @@ Subscribes to sync complete events. | Name | Type | Mandatory| Description | | ------------ | --------------------------------------------- | ---- | ------------------------------------------------------ | -| event | string | Yes | Event type. The value is **syncComplete**, which indicates a sync complete event.| -| syncCallback | Callback<Array<[string, number]>> | Yes | Callback used to return the sync complete event. | +| event | string | Yes | Event type. The value is **syncComplete**, which indicates the sync completion event.| +| syncCallback | Callback<Array<[string, number]>> | Yes | Callback used to return the sync completion event. | **Error codes** @@ -5269,7 +5281,7 @@ class KvstoreModel { off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void -Unsubscribes from sync complete events. +Unsubscribes from the cross-device data sync completion events. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -5277,8 +5289,8 @@ Unsubscribes from sync complete events. | Name | Type | Mandatory| Description | | ------------ | --------------------------------------------- | ---- | ---------------------------------------------------------- | -| event | string | Yes | Event type. The value is **syncComplete**, which indicates a sync complete event.| -| syncCallback | Callback<Array<[string, number]>> | No | Callback to unregister. If this parameter is not specified, this API unregisters all the callbacks for the sync complete event. | +| event | string | Yes | Event type. The value is **syncComplete**, which indicates a sync completion event.| +| syncCallback | Callback<Array<[string, number]>> | No | Callback to unregister. If this parameter is not specified, this API unregisters all callbacks for for the sync completion event. | **Error codes** @@ -5404,7 +5416,7 @@ try { ## DeviceKVStore -Provides APIs for querying and synchronizing data in a device KV store. This class inherits from **SingleKVStore**. The **SingleKVStore** APIs such as **put** and **putBatch** can be used. +Provides APIs for querying data in a device KV store and performing cross-device data sync. This class inherits from **SingleKVStore**. The **SingleKVStore** APIs such as **put** and **putBatch** can be used. Data is distinguished by device in a device KV store. Each device can only write and modify its own data. Data of other devices is read-only and cannot be modified. @@ -5435,7 +5447,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](errorc | ------------ | -------------------------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types; 3. Parameter verification failed. | | 15100003 | Database corrupted. | -| 15100004 | Data not found. | +| 15100004 | Not found. | | 15100005 | Database or result set already closed. | **Example** @@ -5496,7 +5508,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](errorc | ------------ | -------------------------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types; 3. Parameter verification failed. | | 15100003 | Database corrupted. | -| 15100004 | Data not found. | +| 15100004 | Not found. | | 15100005 | Database or result set already closed. | **Example** @@ -5542,7 +5554,7 @@ Obtains a string value that matches the specified device ID and key. This API us | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | deviceId |string | Yes |ID of the target device. | -| key |string | Yes |Key to match. It cannot be empty or exceed [MAX_KEY_LENGTH](#constants). | +| key |string | Yes |Key of the value to obtain. It cannot be empty or exceed [MAX_KEY_LENGTH](#constants). | | callback |AsyncCallback<boolean\|string\|number\|Uint8Array> | Yes |Callback used to return the value obtained. | **Error codes** @@ -5553,7 +5565,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](errorc | ------------ | -------------------------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types; 3. Parameter verification failed. | | 15100003 | Database corrupted. | -| 15100004 | Data not found. | +| 15100004 | Not found. | | 15100005 | Database or result set already closed. | **Example** @@ -5603,7 +5615,7 @@ Obtains a string value that matches the specified device ID and key. This API us | Name | Type| Mandatory| Description | | -------- | -------- | ---- | ------------------------ | | deviceId | string | Yes | ID of the target device.| -| key | string | Yes | Key to match. It cannot be empty or exceed [MAX_KEY_LENGTH](#constants). | +| key | string | Yes | Key of the value to obtain. It cannot be empty or exceed [MAX_KEY_LENGTH](#constants). | **Return value** @@ -5619,7 +5631,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](errorc | ------------ | -------------------------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types; 3. Parameter verification failed. | | 15100003 | Database corrupted. | -| 15100004 | Data not found. | +| 15100004 | Not found. | | 15100005 | Database or result set already closed. | **Example** @@ -6250,7 +6262,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](errorc | ID| **Error Message** | | ------------ | -------------------------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types.| -| 15100001 | Upper limit exceeded. | +| 15100001 | Over max limits. | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -6332,7 +6344,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](errorc | ID| **Error Message** | | ------------ | -------------------------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types.| -| 15100001 | Upper limit exceeded. | +| 15100001 | Over max limits. | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -6406,7 +6418,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](errorc | ID| **Error Message** | | ------------ | -------------------------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types.| -| 15100001 | Upper limit exceeded. | +| 15100001 | Over max limits. | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -6472,7 +6484,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](errorc | ID| **Error Message** | | ------------ | -------------------------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types.| -| 15100001 | Upper limit exceeded. | +| 15100001 | Over max limits. | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -6530,7 +6542,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](errorc | ID| **Error Message** | | ------------ | -------------------------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types.| -| 15100001 | Upper limit exceeded. | +| 15100001 | Over max limits. | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -6619,7 +6631,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](errorc | ID| **Error Message** | | ------------ | -------------------------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types.| -| 15100001 | Upper limit exceeded. | +| 15100001 | Over max limits. | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -6701,7 +6713,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](errorc | ID| **Error Message** | | ------------ | -------------------------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types.| -| 15100001 | Upper limit exceeded. | +| 15100001 | Over max limits. | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | @@ -6770,7 +6782,7 @@ For details about the error codes, see [Distributed KV Store Error Codes](errorc | ID| **Error Message** | | ------------ | -------------------------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types.| -| 15100001 | Upper limit exceeded. | +| 15100001 | Over max limits. | | 15100003 | Database corrupted. | | 15100005 | Database or result set already closed. | diff --git a/en/application-dev/reference/apis-arkdata/oh__data__value_8h.md b/en/application-dev/reference/apis-arkdata/oh__data__value_8h.md index d82189e162c0c4217476d2d4a6067b09ef8d1637..b7351bccabce5217523bf6d4547afef7180b6728 100644 --- a/en/application-dev/reference/apis-arkdata/oh__data__value_8h.md +++ b/en/application-dev/reference/apis-arkdata/oh__data__value_8h.md @@ -5,13 +5,15 @@ Defines APIs and enums related to a single data value. -**File to include**: <database/rdb/oh_data_value.h> +Since API version 18, **OH_ColumnType** is moved from **oh_cursor.h** to this file. This type is supported in versions earlier than API version 18 and can be used in all versions. + +**File to include**: <database/data/oh_data_value.h> **Library**: libnative_rdb_ndk.z.so **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -**Since**: 16 +**Since**: 18 **Related module**: [RDB](_r_d_b.md) diff --git a/en/application-dev/reference/apis-arkdata/oh__data__values_8h.md b/en/application-dev/reference/apis-arkdata/oh__data__values_8h.md index 7722890f28bc692b206f83e4a7f461a376b6ac39..30e1e8ae826818ab863d57c4f06c795f7ece3110 100644 --- a/en/application-dev/reference/apis-arkdata/oh__data__values_8h.md +++ b/en/application-dev/reference/apis-arkdata/oh__data__values_8h.md @@ -5,13 +5,13 @@ Defines APIs and enums related to multiple data values. -**File to include**: <database/rdb/oh_data_values.h> +**File to include**: <database/data/oh_data_values.h> **Library**: libnative_rdb_ndk.z.so **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -**Since**: 16 +**Since**: 18 **Related module**: [RDB](_r_d_b.md) diff --git a/en/application-dev/reference/apis-arkdata/oh__data__values__buckets_8h.md b/en/application-dev/reference/apis-arkdata/oh__data__values__buckets_8h.md index 3f85fde7655fb75681be5c3be1f907c6c18e49d2..050d81af339ea2adc9399e13d0e3ea865ce44139 100644 --- a/en/application-dev/reference/apis-arkdata/oh__data__values__buckets_8h.md +++ b/en/application-dev/reference/apis-arkdata/oh__data__values__buckets_8h.md @@ -5,13 +5,13 @@ Defines structs, APIs, and enums related to stored data values. -**File to include**: <database/rdb/oh_data_values_buckets.h> +**File to include**: <database/data/oh_data_values_buckets.h> **Library**: libnative_rdb_ndk.z.so **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -**Since**: 16 +**Since**: 18 **Related module**: [RDB](_r_d_b.md) diff --git a/en/application-dev/reference/apis-arkdata/oh__preferences_8h.md b/en/application-dev/reference/apis-arkdata/oh__preferences_8h.md index 1e1d5d108c4c5fd1950f942500c334056c4dc95d..50251104b1e274c73570dc189b6e6ec282c7b148 100644 --- a/en/application-dev/reference/apis-arkdata/oh__preferences_8h.md +++ b/en/application-dev/reference/apis-arkdata/oh__preferences_8h.md @@ -43,3 +43,4 @@ Related module: [Preferences](_preferences.md) | int [OH_Preferences_Delete](_preferences.md#oh_preferences_delete) ([OH_Preferences](_preferences.md#oh_preferences) \*preference, const char \*key) | Deletes a KV pair of the specified key from a **Preferences** object.| | int [OH_Preferences_RegisterDataObserver](_preferences.md#oh_preferences_registerdataobserver) ([OH_Preferences](_preferences.md#oh_preferences) \*preference, void \*context, [OH_PreferencesDataObserver](_preferences.md#oh_preferencesdataobserver) observer, const char \*keys[], uint32_t keyCount) | Subscribes to data changes of the specified key. If the value of the specified key changes, a callback will be invoked after **OH_Preferences_Close ()** is called.| | int [OH_Preferences_UnregisterDataObserver](_preferences.md#oh_preferences_unregisterdataobserver) ([OH_Preferences](_preferences.md#oh_preferences) \*preference, void \*context, [OH_PreferencesDataObserver](_preferences.md#oh_preferencesdataobserver) observer, const char \*keys[], uint32_t keyCount) | Unsubscribes from data changes of the specified key.| +| int [OH_Preferences_IsStorageTypeSupported](_preferences.md#oh_preferences_isstoragetypesupported) ([Preferences_StorageType](_preferences.md#preferences_storagetype) type, bool \*isSupported) | Checks whether the specified storage type is supported. | diff --git a/en/application-dev/reference/apis-arkdata/oh__preferences__option_8h.md b/en/application-dev/reference/apis-arkdata/oh__preferences__option_8h.md index 1c8c333abaed645ce2fc61a461eb3650f7550a87..0bd53d7454649186205b0fe51180cbe33efe16bd 100644 --- a/en/application-dev/reference/apis-arkdata/oh__preferences__option_8h.md +++ b/en/application-dev/reference/apis-arkdata/oh__preferences__option_8h.md @@ -24,12 +24,19 @@ Related module: [Preferences](_preferences.md) | Name| Description| | -------- | -------- | | typedef struct [OH_PreferencesOption](_preferences.md#oh_preferencesoption) [OH_PreferencesOption](_preferences.md#oh_preferencesoption) | Defines a **PreferencesOption** object.| +| typedef enum [Preferences_StorageType](_preferences.md#preferences_storagetype) [Preferences_StorageType](_preferences.md#preferences_storagetype) | Defines an enum for preferences storage types. | +### Enums + +| Name| Description| +| -------- | -------- | +| [Preferences_StorageType](_preferences.md#preferences_storagetype-1) { PREFERENCES_STORAGE_XML = 0, PREFERENCES_STORAGE_GSKV } | Enumerates the preferences storage types. | ### Functions | Name| Description| | -------- | -------- | +| int [OH_PreferencesOption_SetStorageType](_preferences.md#oh_preferencesoption_setstoragetype) ([OH_PreferencesOption](_preferences.md#oh_preferencesoption) \*option, [Preferences_StorageType](_preferences.md#preferences_storagetype) type) | Sets the storage type for a preferences instance. | | [OH_PreferencesOption](_preferences.md#oh_preferencesoption) \* [OH_PreferencesOption_Create](_preferences.md#oh_preferencesoption_create) (void) | Creates an [OH_PreferencesOption](_preferences.md#oh_preferencesoption) instance and a pointer to it. If this pointer is no longer required, use [OH_PreferencesOption_Destroy](_preferences.md#oh_preferencesoption_destroy) to destroy it. Otherwise, memory leaks may occur.| | int [OH_PreferencesOption_SetFileName](_preferences.md#oh_preferencesoption_setfilename) ([OH_PreferencesOption](_preferences.md#oh_preferencesoption) \*option, const char \*fileName) | Sets the file name for an [OH_PreferencesOption](_preferences.md#oh_preferencesoption) instance.| | int [OH_PreferencesOption_SetBundleName](_preferences.md#oh_preferencesoption_setbundlename) ([OH_PreferencesOption](_preferences.md#oh_preferencesoption) \*option, const char \*bundleName) | Sets the bundle name for an [OH_PreferencesOption](_preferences.md#oh_preferencesoption) instance.| diff --git a/en/application-dev/reference/apis-arkdata/oh__rdb__transaction_8h.md b/en/application-dev/reference/apis-arkdata/oh__rdb__transaction_8h.md index be99c2d0faaf0f9efdde191f255975369ad61583..dca028f9cb50ac4e2b75209d8f68f4df4bb98e1e 100644 --- a/en/application-dev/reference/apis-arkdata/oh__rdb__transaction_8h.md +++ b/en/application-dev/reference/apis-arkdata/oh__rdb__transaction_8h.md @@ -11,7 +11,7 @@ Defines APIs and enums related to database transactions. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core -**Since**: 16 +**Since**: 18 **Related module**: [RDB](_r_d_b.md) @@ -45,7 +45,7 @@ Defines APIs and enums related to database transactions. | int [OH_RdbTrans_Commit](_r_d_b.md#oh_rdbtrans_commit) ([OH_Rdb_Transaction](_r_d_b.md#oh_rdb_transaction) \*trans) | Commits a transaction.| | int [OH_RdbTrans_Rollback](_r_d_b.md#oh_rdbtrans_rollback) ([OH_Rdb_Transaction](_r_d_b.md#oh_rdb_transaction) \*trans) | Rolls back a transaction.| | int [OH_RdbTrans_Insert](_r_d_b.md#oh_rdbtrans_insert) ([OH_Rdb_Transaction](_r_d_b.md#oh_rdb_transaction) \*trans, const char \*table, const [OH_VBucket](_o_h___v_bucket.md) \*row, int64_t \*rowId) | Inserts a row of data into a table.| -| int [OH_RdbTrans_BatchInsert](_r_d_b.md#oh_rdbtrans_batchinsert) ([OH_Rdb_Transaction](_r_d_b.md#oh_rdb_transaction) \*trans, const char \*table, const [OH_Data_VBuckets](_r_d_b.md#oh_data_vbuckets) \*rows, int64_t \*changes) | Batch inserts data into a table.| +| int [OH_RdbTrans_BatchInsert](_r_d_b.md#oh_rdbtrans_batchinsert) ([OH_Rdb_Transaction](_r_d_b.md#oh_rdb_transaction) \*trans, const char \*table, const [OH_Data_VBuckets](_r_d_b.md#oh_data_vbuckets) \*rows, [Rdb_ConflictResolution](_r_d_b.md#rdb_conflictresolution) resolution, int64_t \*changes) | Inserts a batch of data into a table. | | int [OH_RdbTrans_Update](_r_d_b.md#oh_rdbtrans_update) ([OH_Rdb_Transaction](_r_d_b.md#oh_rdb_transaction) \*trans, const [OH_VBucket](_o_h___v_bucket.md) \*row, const [OH_Predicates](_o_h___predicates.md) \*predicates, int64_t \*changes) | Updates data in an RDB store based on specified conditions.| | int [OH_RdbTrans_Delete](_r_d_b.md#oh_rdbtrans_delete) ([OH_Rdb_Transaction](_r_d_b.md#oh_rdb_transaction) \*trans, const [OH_Predicates](_o_h___predicates.md) \*predicates, int64_t \*changes) | Deletes data from the database based on the specified conditions.| | [OH_Cursor](_o_h___cursor.md) \* [OH_RdbTrans_Query](_r_d_b.md#oh_rdbtrans_query) ([OH_Rdb_Transaction](_r_d_b.md#oh_rdb_transaction) \*trans, const [OH_Predicates](_o_h___predicates.md) \*predicates, const char \*columns[], int len) | Queries data in the database based on specified conditions.| diff --git a/en/application-dev/reference/apis-arkdata/oh__rdb__types_8h.md b/en/application-dev/reference/apis-arkdata/oh__rdb__types_8h.md new file mode 100644 index 0000000000000000000000000000000000000000..0e01ff7a0cf5dafdfee49e6fd3b3a795a8b2ffc7 --- /dev/null +++ b/en/application-dev/reference/apis-arkdata/oh__rdb__types_8h.md @@ -0,0 +1,31 @@ +# oh_rdb_types.h + + +## Overview + +Provides type definitions related to data values. + +**Library**: libnative_rdb_ndk.z.so + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Since**: 18 + +**Related module**: [RDB](_r_d_b.md) + + +## Summary + + +### Types + +| Name| Description| +| -------- | -------- | +| typedef enum [Rdb_ConflictResolution](_r_d_b.md#rdb_conflictresolution) [Rdb_ConflictResolution](_r_d_b.md#rdb_conflictresolution) | Defines an enum for conflict resolution policies. | + + +### Enums + +| Name| Description| +| -------- | -------- | +| [Rdb_ConflictResolution](_r_d_b.md#rdb_conflictresolution-1) {
RDB_CONFLICT_NONE = 1, RDB_CONFLICT_ROLLBACK, RDB_CONFLICT_ABORT, RDB_CONFLICT_FAIL,
RDB_CONFLICT_IGNORE, RDB_CONFLICT_REPLACE
} | Enumerates the conflict resolution policies. | diff --git a/en/application-dev/reference/apis-arkdata/relational__store_8h.md b/en/application-dev/reference/apis-arkdata/relational__store_8h.md index 31fd4cfb6f3dca03003855ece9b28a8430e31c8b..9867973ada77d2e2ed745f5ee424ebcd40281755 100644 --- a/en/application-dev/reference/apis-arkdata/relational__store_8h.md +++ b/en/application-dev/reference/apis-arkdata/relational__store_8h.md @@ -3,7 +3,7 @@ ## Overview -Provides APIs for managing data in a relational database (RDB) store. The APIs not marked as supporting vector stores support only RDB stores. +Provides APIs for managing data in a relational database (RDB) store. The APIs not marked as supporting vector stores are available only to RDB stores. **File to include**: @@ -21,18 +21,18 @@ Provides APIs for managing data in a relational database (RDB) store. The APIs n | Name| Description| | -------- | -------- | -| [OH_Rdb_Config](_o_h___rdb___config.md) | Defines the RDB store configuration.| -| [OH_Rdb_Store](_o_h___rdb___store.md) | Defines the RDB store type.| -| [Rdb_DistributedConfig](_rdb___distributed_config.md) | Defines the distributed configuration of a table.| -| [Rdb_KeyInfo](_rdb___key_info.md) | Defines the primary key or row number of the row that changes.| -| [Rdb_KeyInfo::Rdb_KeyData](union_rdb___key_info_1_1_rdb___key_data.md) | Defines the changed data.| -| [Rdb_ChangeInfo](_rdb___change_info.md) | Defines the details about the device-cloud sync process.| -| [Rdb_SubscribeCallback](union_rdb___subscribe_callback.md) | Defines the callback used to return the result.| -| [Rdb_DataObserver](_rdb___data_observer.md) | Defines the data observer.| -| [Rdb_Statistic](_rdb___statistic.md) | Defines the device-cloud sync statistics of a database table.| -| [Rdb_TableDetails](_rdb___table_details.md) | Defines the statistics of device-cloud upload and download tasks of a database table.| -| [Rdb_ProgressDetails](_rdb___progress_details.md) | Defines the statistics of the overall device-cloud upload and download tasks of an RDB store.| -| [Rdb_ProgressObserver](_rdb___progress_observer.md) | Defines the observer of the device-cloud sync progress.| +| [OH_Rdb_Config](_o_h___rdb___config.md) | Represents the RDB store configuration.| +| [OH_Rdb_Store](_o_h___rdb___store.md) | Represents the RDB store type.| +| [Rdb_DistributedConfig](_rdb___distributed_config.md) | Represents the distributed configuration of a table.| +| [Rdb_KeyInfo](_rdb___key_info.md) | Represents the primary key or row number of the row that changes.| +| [Rdb_KeyInfo::Rdb_KeyData](union_rdb___key_info_1_1_rdb___key_data.md) | Represents the changed data.| +| [Rdb_ChangeInfo](_rdb___change_info.md) | Represents the details about the device-cloud sync.| +| [Rdb_SubscribeCallback](union_rdb___subscribe_callback.md) | Represents a callback used to listen for data changes.| +| [Rdb_DataObserver](_rdb___data_observer.md) | Represents the data observer.| +| [Rdb_Statistic](_rdb___statistic.md) | Represents the device-cloud sync statistics of a table.| +| [Rdb_TableDetails](_rdb___table_details.md) | Represents the statistics of device-cloud upload and download tasks of a table.| +| [Rdb_ProgressDetails](_rdb___progress_details.md) | Represents the statistics of the overall device-cloud upload and download tasks of a database.| +| [Rdb_ProgressObserver](_rdb___progress_observer.md) | Represents the observer of the device-cloud sync progress.| ### Macros @@ -49,7 +49,7 @@ Provides APIs for managing data in a relational database (RDB) store. The APIs n | Name| Description| | -------- | -------- | | [OH_Rdb_SecurityLevel](_r_d_b.md#oh_rdb_securitylevel) | Defines an enum for RDB store security levels.| -| [Rdb_SecurityArea](_r_d_b.md#rdb_securityarea) | Defines an enum for security area levels of an RDB store.| +| [Rdb_SecurityArea](_r_d_b.md#rdb_securityarea) | Defines an enum for database directory encryption levels.| | typedef struct [OH_Rdb_ConfigV2](_r_d_b.md#oh_rdb_configv2) [OH_Rdb_ConfigV2](_r_d_b.md#oh_rdb_configv2) | Defines a struct for the RDB store configuration. Different from [OH_Rdb_Config](_o_h___rdb___config.md), this struct does not expose its member variables externally. Methods are used to configure the properties of this struct. It supports vector stores.| | typedef enum [Rdb_DBType](_r_d_b.md#rdb_dbtype) [Rdb_DBType](_r_d_b.md#rdb_dbtype) | Defines an enum for the database kernel types.| | [Rdb_DistributedType](_r_d_b.md#rdb_distributedtype) | Defines an enum for distributed types.| @@ -62,7 +62,7 @@ Provides APIs for managing data in a relational database (RDB) store. The APIs n | [Rdb_DetailsObserver](_r_d_b.md#rdb_detailsobserver) | Defines a callback used to return the details about the device-cloud data change.| | [Rdb_SubscribeCallback](union_rdb___subscribe_callback.md) | Defines a callback used to return the subscribed event.| | [Rdb_DataObserver](_rdb___data_observer.md) | Defines a struct for the data observer.| -| [Rdb_SyncMode](_r_d_b.md#rdb_syncmode) | Defines an enum for RDB sync modes.| +| [Rdb_SyncMode](_r_d_b.md#rdb_syncmode) | Defines an enum for RDB store sync modes.| | [Rdb_Statistic](_r_d_b.md#rdb_statistic) | Defines a struct for device-cloud sync statistics of a database table.| | [Rdb_TableDetails](_r_d_b.md#rdb_tabledetails) | Defines a struct for statistics of device-cloud upload and download tasks of a database table.| | [Rdb_Progress](_r_d_b.md#rdb_progress) | Defines an enum for device-cloud sync progresses.| @@ -78,12 +78,12 @@ Provides APIs for managing data in a relational database (RDB) store. The APIs n | Name| Description| | -------- | -------- | | [OH_Rdb_SecurityLevel](_r_d_b.md#oh_rdb_securitylevel-1) { S1 = 1, S2, S3, S4} | Enumerates the RDB store security levels.| -| [Rdb_SecurityArea](_r_d_b.md#rdb_securityarea-1) { RDB_SECURITY_AREA_EL1 = 1, RDB_SECURITY_AREA_EL2, RDB_SECURITY_AREA_EL3, RDB_SECURITY_AREA_EL4 } | Enumerates the security area levels of an RDB store.| +| [Rdb_SecurityArea](_r_d_b.md#rdb_securityarea-1) { RDB_SECURITY_AREA_EL1 = 1, RDB_SECURITY_AREA_EL2, RDB_SECURITY_AREA_EL3, RDB_SECURITY_AREA_EL4 } | Enumerates the database directory encryption levels.| | [Rdb_DBType](_r_d_b.md#rdb_dbtype-1) { RDB_SQLITE = 1, RDB_CAYLEY = 2, DBTYPE_BUTT = 64 } | Enumerates the database kernel types.| | [Rdb_DistributedType](_r_d_b.md#rdb_distributedtype-1) { RDB_DISTRIBUTED_CLOUD } | Enumerates the distributed types.| | [Rdb_ChangeType](_r_d_b.md#rdb_changetype-1) { RDB_DATA_CHANGE, RDB_ASSET_CHANGE } | Enumerates the data change types.| | [Rdb_SubscribeType](_r_d_b.md#rdb_subscribetype-1) { RDB_SUBSCRIBE_TYPE_CLOUD, RDB_SUBSCRIBE_TYPE_CLOUD_DETAILS, RDB_SUBSCRIBE_TYPE_LOCAL_DETAILS } | Enumerates the subscription types.| -| [Rdb_SyncMode](_r_d_b.md#rdb_syncmode-1) { RDB_SYNC_MODE_TIME_FIRST, RDB_SYNC_MODE_NATIVE_FIRST, RDB_SYNC_MODE_CLOUD_FIRST } | Enumerates the RDB sync modes.| +| [Rdb_SyncMode](_r_d_b.md#rdb_syncmode-1) { RDB_SYNC_MODE_TIME_FIRST, RDB_SYNC_MODE_NATIVE_FIRST, RDB_SYNC_MODE_CLOUD_FIRST } | Enumerates the RDB store sync modes.| | [Rdb_Progress](_r_d_b.md#rdb_progress-1) { RDB_SYNC_BEGIN, RDB_SYNC_IN_PROGRESS, RDB_SYNC_FINISH } | Enumerates the device-cloud sync progresses.| | [Rdb_ProgressCode](_r_d_b.md#rdb_progresscode-1) {
RDB_SUCCESS, RDB_UNKNOWN_ERROR, RDB_NETWORK_ERROR, RDB_CLOUD_DISABLED,
RDB_LOCKED_BY_OTHERS, RDB_RECORD_LIMIT_EXCEEDED, RDB_NO_SPACE_FOR_ASSET
} | Enumerates the states in the device-cloud sync process.| @@ -92,9 +92,11 @@ Provides APIs for managing data in a relational database (RDB) store. The APIs n | Name| Description| | -------- | -------- | +| int [OH_Rdb_SetPersistent](_r_d_b.md#oh_rdb_setpersistent) ([OH_Rdb_ConfigV2](_r_d_b.md#oh_rdb_configv2) \*config, bool isPersistent) | Sets whether to persist an RDB store. | +| int [OH_Rdb_BatchInsert](_r_d_b.md#oh_rdb_batchinsert) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const char \*table, const [OH_Data_VBuckets](_r_d_b.md#oh_data_vbuckets) \*rows, [Rdb_ConflictResolution](_r_d_b.md#rdb_conflictresolution) resolution, int64_t \*changes) | Inserts a batch of data into a table. | | int [OH_Rdb_CreateTransaction](_r_d_b.md#oh_rdb_createtransaction) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const [OH_RDB_TransOptions](_r_d_b.md#oh_rdb_transoptions) \*options, [OH_Rdb_Transaction](_r_d_b.md#oh_rdb_transaction) \*\*trans) | Creates a transaction object.| -| int [OH_Rdb_ExecuteV2](_r_d_b.md#oh_rdb_executev2) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const char \*sql, const [OH_Data_Values](_r_d_b.md#oh_data_values) \*args, [OH_Data_Value](_r_d_b.md#oh_data_value) \*\*result) | Executes an SQL statement with a return value. This API supports vector stores.| -| [OH_Cursor](_o_h___cursor.md) \* [OH_Rdb_ExecuteQueryV2](_r_d_b.md#oh_rdb_executequeryv2) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const char \*sql, const [OH_Data_Values](_r_d_b.md#oh_data_values) \*args) | Queries data in the database using the specified SQL statement. This API supports vector stores.| +| int [OH_Rdb_ExecuteV2](_r_d_b.md#oh_rdb_executev2) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const char \*sql, const [OH_Data_Values](_r_d_b.md#oh_data_values) \*args, [OH_Data_Value](_r_d_b.md#oh_data_value) \*\*result) | Executes an SQL statement with a return value. This API supports vector stores.| +| [OH_Cursor](_o_h___cursor.md) \* [OH_Rdb_ExecuteQueryV2](_r_d_b.md#oh_rdb_executequeryv2) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const char \*sql, const [OH_Data_Values](_r_d_b.md#oh_data_values) \*args) | Queries data in the database using the specified SQL statement. This API supports vector stores.| | int [OH_Rdb_IsTokenizerSupported](_r_d_b.md#oh_rdb_istokenizersupported) ([Rdb_Tokenizer](_r_d_b.md#rdb_tokenizer) tokenizer, bool \*isSupported) | Checks whether the specified tokenizer is supported.| | int [OH_Rdb_SetTokenizer](_r_d_b.md#oh_rdb_settokenizer) ([OH_Rdb_ConfigV2](_r_d_b.md#oh_rdb_configv2) \*config, [Rdb_Tokenizer](_r_d_b.md#rdb_tokenizer) tokenizer) | Sets a tokenizer for a database file.| | [OH_Rdb_ConfigV2](_r_d_b.md#oh_rdb_configv2) \* [OH_Rdb_CreateConfig](_r_d_b.md#oh_rdb_createconfig) () | Creates an [OH_Rdb_ConfigV2](_r_d_b.md#oh_rdb_configv2) instance.| @@ -104,15 +106,15 @@ Provides APIs for managing data in a relational database (RDB) store. The APIs n | int [OH_Rdb_SetBundleName](_r_d_b.md#oh_rdb_setbundlename) ([OH_Rdb_ConfigV2](_r_d_b.md#oh_rdb_configv2) \*config, const char \*bundleName) | Sets the application bundle name for an [OH_Rdb_ConfigV2](_r_d_b.md#oh_rdb_configv2) instance.| | int [OH_Rdb_SetModuleName](_r_d_b.md#oh_rdb_setmodulename) ([OH_Rdb_ConfigV2](_r_d_b.md#oh_rdb_configv2) \*config, const char \*moduleName) | Sets the module name for an [OH_Rdb_ConfigV2](_r_d_b.md#oh_rdb_configv2) instance.| | int [OH_Rdb_SetEncrypted](_r_d_b.md#oh_rdb_setencrypted) ([OH_Rdb_ConfigV2](_r_d_b.md#oh_rdb_configv2) \*config, bool isEncrypted) | Sets whether to encrypt the database for an [OH_Rdb_ConfigV2](_r_d_b.md#oh_rdb_configv2) instance.| -| int [OH_Rdb_SetSecurityLevel](_r_d_b.md#oh_rdb_setsecuritylevel) ([OH_Rdb_ConfigV2](_r_d_b.md#oh_rdb_configv2) \*config, int securityLevel) | Sets the database security level ([OH_Rdb_SecurityLevel](_r_d_b.md#oh_rdb_securitylevel))for an [OH_Rdb_ConfigV2](_r_d_b.md#oh_rdb_configv2) instance.| +| int [OH_Rdb_SetSecurityLevel](_r_d_b.md#oh_rdb_setsecuritylevel) ([OH_Rdb_ConfigV2](_r_d_b.md#oh_rdb_configv2) \*config, int securityLevel) | Sets the database security level ([OH_Rdb_SecurityLevel](_r_d_b.md#oh_rdb_securitylevel)) for an [OH_Rdb_ConfigV2](_r_d_b.md#oh_rdb_configv2) instance.| | int [OH_Rdb_SetArea](_r_d_b.md#oh_rdb_setarea) ([OH_Rdb_ConfigV2](_r_d_b.md#oh_rdb_configv2) \*config, int area) | Sets the security area level ([Rdb_SecurityArea](_r_d_b.md#rdb_securityarea)) for an [OH_Rdb_ConfigV2](_r_d_b.md#oh_rdb_configv2) instance.| | int [OH_Rdb_SetDbType](_r_d_b.md#oh_rdb_setdbtype) ([OH_Rdb_ConfigV2](_r_d_b.md#oh_rdb_configv2) \*config, int dbType) | Sets the database type ([Rdb_DBType](_r_d_b.md#rdb_dbtype)) for an [OH_Rdb_ConfigV2](_r_d_b.md#oh_rdb_configv2) instance.| | const int \* [OH_Rdb_GetSupportedDbType](_r_d_b.md#oh_rdb_getsupporteddbtype) (int \*typeCount) | Obtains the supported database type [Rdb_DBType](_r_d_b.md#rdb_dbtype).| | [OH_Rdb_Store](_o_h___rdb___store.md) \* [OH_Rdb_CreateOrOpen](_r_d_b.md#oh_rdb_createoropen) (const [OH_Rdb_ConfigV2](_r_d_b.md#oh_rdb_configv2) \*config, int \*errCode) | Creates or opens an [OH_Rdb_Store](_o_h___rdb___store.md) instance based on the given [OH_Rdb_ConfigV2](_r_d_b.md#oh_rdb_configv2).| -| int [OH_Rdb_ExecuteByTrxId](_r_d_b.md#oh_rdb_executebytrxid) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, int64_t trxId, const char \*sql) | Executes an SQL statement that returns no value based on the specified transaction ID.| -| int [OH_Rdb_BeginTransWithTrxId](_r_d_b.md#oh_rdb_begintranswithtrxid) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, int64_t \*trxId) | Begins a transaction and obtains the transaction ID before executing an SQL statement. This API supports vector stores.| -| int [OH_Rdb_RollBackByTrxId](_r_d_b.md#oh_rdb_rollbackbytrxid) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, int64_t trxId) | Rolls back the executed SQL statement based on the specified transaction ID. This API supports vector stores.| -| int [OH_Rdb_CommitByTrxId](_r_d_b.md#oh_rdb_commitbytrxid) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, int64_t trxId) | Commits the executed SQL statement based on the specified transaction ID. This API supports vector stores.| +| int [OH_Rdb_ExecuteByTrxId](_r_d_b.md#oh_rdb_executebytrxid) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, int64_t trxId, const char \*sql) | Executes an SQL statement that returns no value based on the specified transaction ID. This API supports vector stores.| +| int [OH_Rdb_BeginTransWithTrxId](_r_d_b.md#oh_rdb_begintranswithtrxid) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, int64_t \*trxId) | Begins a transaction. This API returns a transaction ID. This API supports vector stores.| +| int [OH_Rdb_RollBackByTrxId](_r_d_b.md#oh_rdb_rollbackbytrxid) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, int64_t trxId) | Rolls back the executed SQL statements based on the specified transaction ID. This API supports vector stores.| +| int [OH_Rdb_CommitByTrxId](_r_d_b.md#oh_rdb_commitbytrxid) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, int64_t trxId) | Commits the executed SQL statements based on the specified transaction ID. This API supports vector stores.| | [OH_Rdb_CreateValueObject](_r_d_b.md#oh_rdb_createvalueobject) (void) | Creates an [OH_VObject](_o_h___v_object.md) instance.| | [OH_Rdb_CreateValuesBucket](_r_d_b.md#oh_rdb_createvaluesbucket) (void) | Creates an [OH_VBucket](_o_h___v_bucket.md) instance.| | [OH_Rdb_CreatePredicates](_r_d_b.md#oh_rdb_createpredicates) (const char \*table) | Creates an [OH_Predicates](_o_h___predicates.md) instance.| @@ -123,10 +125,10 @@ Provides APIs for managing data in a relational database (RDB) store. The APIs n | [OH_Rdb_Insert](_r_d_b.md#oh_rdb_insert) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const char \*table, [OH_VBucket](_o_h___v_bucket.md) \*valuesBucket) | Inserts a row of data into a table.| | [OH_Rdb_Update](_r_d_b.md#oh_rdb_update) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, [OH_VBucket](_o_h___v_bucket.md) \*valuesBucket, [OH_Predicates](_o_h___predicates.md) \*predicates) | Updates data in an RDB store based on specified conditions.| | [OH_Rdb_Delete](_r_d_b.md#oh_rdb_delete) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, [OH_Predicates](_o_h___predicates.md) \*predicates) | Deletes data from an RDB store based on specified conditions.| -| [OH_Rdb_Query](_r_d_b.md#oh_rdb_query) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, [OH_Predicates](_o_h___predicates.md) \*predicates, const char \*const \*columnNames, int length) | Queries data in an RDB store based on specified conditions.| +| [OH_Rdb_Query](_r_d_b.md#oh_rdb_query) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, [OH_Predicates](_o_h___predicates.md) \*predicates, const char \*const \*columnNames, int length) | Queries data in an RDB store.| | [OH_Rdb_Execute](_r_d_b.md#oh_rdb_execute) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const char \*sql) | Executes the SQL statement that returns no value.| | [OH_Rdb_ExecuteQuery](_r_d_b.md#oh_rdb_executequery) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const char \*sql) | Queries data in the database using the specified SQL statement. This API supports vector stores.| -| [OH_Rdb_BeginTransaction](_r_d_b.md#oh_rdb_begintransaction) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store) | Starts the transaction before executing the SQL statements.| +| [OH_Rdb_BeginTransaction](_r_d_b.md#oh_rdb_begintransaction) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store) | Begins the transaction before executing the SQL statements.| | [OH_Rdb_RollBack](_r_d_b.md#oh_rdb_rollback) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store) | Rolls back the SQL statements that have been executed.| | [OH_Rdb_Commit](_r_d_b.md#oh_rdb_commit) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store) | Commits the executed SQL statements.| | [OH_Rdb_Backup](_r_d_b.md#oh_rdb_backup) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const char \*databasePath) | Backs up an RDB store using the backup file of the specified path. This API supports vector stores.| diff --git a/en/application-dev/reference/apis-arkdata/relational__store__error__code_8h.md b/en/application-dev/reference/apis-arkdata/relational__store__error__code_8h.md index ff6a9bb21319f44178f2bf01072cce7367595972..1f050f75212f1ebc553cdae0b89358a9e13848f4 100644 --- a/en/application-dev/reference/apis-arkdata/relational__store__error__code_8h.md +++ b/en/application-dev/reference/apis-arkdata/relational__store__error__code_8h.md @@ -28,4 +28,4 @@ Declares the error codes used for relational database (RDB) stores. | Name| Description| | -------- | -------- | -| [OH_Rdb_ErrCode](_r_d_b.md#oh_rdb_errcode-1) {
RDB_ERR = -1, RDB_OK = 0, E_BASE = 14800000, RDB_E_NOT_SUPPORTED = 801,
RDB_E_ERROR = E_BASE, RDB_E_INVALID_ARGS = (E_BASE + 1), RDB_E_CANNOT_UPDATE_READONLY = (E_BASE + 2), RDB_E_REMOVE_FILE = (E_BASE + 3),
RDB_E_EMPTY_TABLE_NAME = (E_BASE + 5), RDB_E_EMPTY_VALUES_BUCKET = (E_BASE + 6), RDB_E_EXECUTE_IN_STEP_QUERY = (E_BASE + 7), RDB_E_INVALID_COLUMN_INDEX = (E_BASE + 8),
RDB_E_INVALID_COLUMN_TYPE = (E_BASE + 9), RDB_E_EMPTY_FILE_NAME = (E_BASE + 10), RDB_E_INVALID_FILE_PATH = (E_BASE + 11), RDB_E_TRANSACTION_IN_EXECUTE = (E_BASE + 12),
RDB_E_INVALID_STATEMENT = (E_BASE + 13), RDB_E_EXECUTE_WRITE_IN_READ_CONNECTION = (E_BASE + 14), RDB_E_BEGIN_TRANSACTION_IN_READ_CONNECTION = (E_BASE + 15), RDB_E_NO_TRANSACTION_IN_SESSION = (E_BASE + 16),
RDB_E_MORE_STEP_QUERY_IN_ONE_SESSION = (E_BASE + 17), RDB_E_NO_ROW_IN_QUERY = (E_BASE + 18), RDB_E_INVALID_BIND_ARGS_COUNT = (E_BASE + 19), RDB_E_INVALID_OBJECT_TYPE = (E_BASE + 20),
RDB_E_INVALID_CONFLICT_FLAG = (E_BASE + 21), RDB_E_HAVING_CLAUSE_NOT_IN_GROUP_BY = (E_BASE + 22), RDB_E_NOT_SUPPORTED_BY_STEP_RESULT_SET = (E_BASE + 23), RDB_E_STEP_RESULT_SET_CROSS_THREADS = (E_BASE + 24),
RDB_E_STEP_RESULT_QUERY_NOT_EXECUTED = (E_BASE + 25), RDB_E_STEP_RESULT_IS_AFTER_LAST = (E_BASE + 26), RDB_E_STEP_RESULT_QUERY_EXCEEDED = (E_BASE + 27), RDB_E_STATEMENT_NOT_PREPARED = (E_BASE + 28),
RDB_E_EXECUTE_RESULT_INCORRECT = (E_BASE + 29), RDB_E_STEP_RESULT_CLOSED = (E_BASE + 30), RDB_E_RELATIVE_PATH = (E_BASE + 31), RDB_E_EMPTY_NEW_ENCRYPT_KEY = (E_BASE + 32),
RDB_E_CHANGE_UNENCRYPTED_TO_ENCRYPTED = (E_BASE + 33), RDB_E_CHANGE_ENCRYPT_KEY_IN_BUSY = (E_BASE + 34), RDB_E_STEP_STATEMENT_NOT_INIT = (E_BASE + 35), RDB_E_NOT_SUPPORTED_ATTACH_IN_WAL_MODE = (E_BASE + 36),
RDB_E_CREATE_FOLDER_FAIL = (E_BASE + 37), RDB_E_SQLITE_SQL_BUILDER_NORMALIZE_FAIL = (E_BASE + 38), RDB_E_STORE_SESSION_NOT_GIVE_CONNECTION_TEMPORARILY = (E_BASE + 39), RDB_E_STORE_SESSION_NO_CURRENT_TRANSACTION = (E_BASE + 40),
RDB_E_NOT_SUPPORT = (E_BASE + 41), RDB_E_INVALID_PARCEL = (E_BASE + 42), RDB_E_QUERY_IN_EXECUTE = (E_BASE + 43), RDB_E_SET_PERSIST_WAL = (E_BASE + 44),
RDB_E_DB_NOT_EXIST = (E_BASE + 45), RDB_E_ARGS_READ_CON_OVERLOAD = (E_BASE + 46), RDB_E_WAL_SIZE_OVER_LIMIT = (E_BASE + 47), RDB_E_CON_OVER_LIMIT = (E_BASE + 48),
RDB_E_ALREADY_CLOSED = (E_BASE + 51), RDB_E_DATABASE_BUSY = (E_BASE + 52), RDB_E_NOT_SUPPORT_THE_SQL = (E_BASE + 53), RDB_E_SQLITE_CORRUPT = (E_BASE + 54),
RDB_E_SQLITE_PERM = (E_BASE + 55), RDB_E_SQLITE_BUSY = (E_BASE + 56), RDB_E_SQLITE_LOCKED = (E_BASE + 57), RDB_E_SQLITE_NOMEM = (E_BASE + 58),
RDB_E_SQLITE_READONLY = (E_BASE + 59), RDB_E_SQLITE_IOERR = (E_BASE + 60), RDB_E_SQLITE_FULL = (E_BASE + 61), RDB_E_SQLITE_CANT_OPEN = (E_BASE + 62),
RDB_E_SQLITE_TOO_BIG = (E_BASE + 63), RDB_E_SQLITE_MISMATCH = (E_BASE + 64)
} | Enumerates the error codes.| +| [OH_Rdb_ErrCode](_r_d_b.md#oh_rdb_errcode-1) {
RDB_ERR = -1, RDB_OK = 0, E_BASE = 14800000, RDB_E_NOT_SUPPORTED = 801,
RDB_E_ERROR = E_BASE, RDB_E_INVALID_ARGS = (E_BASE + 1), RDB_E_CANNOT_UPDATE_READONLY = (E_BASE + 2), RDB_E_REMOVE_FILE = (E_BASE + 3),
RDB_E_EMPTY_TABLE_NAME = (E_BASE + 5), RDB_E_EMPTY_VALUES_BUCKET = (E_BASE + 6), RDB_E_EXECUTE_IN_STEP_QUERY = (E_BASE + 7), RDB_E_INVALID_COLUMN_INDEX = (E_BASE + 8),
RDB_E_INVALID_COLUMN_TYPE = (E_BASE + 9), RDB_E_EMPTY_FILE_NAME = (E_BASE + 10), RDB_E_INVALID_FILE_PATH = (E_BASE + 11), RDB_E_TRANSACTION_IN_EXECUTE = (E_BASE + 12),
RDB_E_INVALID_STATEMENT = (E_BASE + 13), RDB_E_EXECUTE_WRITE_IN_READ_CONNECTION = (E_BASE + 14), RDB_E_BEGIN_TRANSACTION_IN_READ_CONNECTION = (E_BASE + 15), RDB_E_NO_TRANSACTION_IN_SESSION = (E_BASE + 16),
RDB_E_MORE_STEP_QUERY_IN_ONE_SESSION = (E_BASE + 17), RDB_E_NO_ROW_IN_QUERY = (E_BASE + 18), RDB_E_INVALID_BIND_ARGS_COUNT = (E_BASE + 19), RDB_E_INVALID_OBJECT_TYPE = (E_BASE + 20),
RDB_E_INVALID_CONFLICT_FLAG = (E_BASE + 21), RDB_E_HAVING_CLAUSE_NOT_IN_GROUP_BY = (E_BASE + 22), RDB_E_NOT_SUPPORTED_BY_STEP_RESULT_SET = (E_BASE + 23), RDB_E_STEP_RESULT_SET_CROSS_THREADS = (E_BASE + 24),
RDB_E_STEP_RESULT_QUERY_NOT_EXECUTED = (E_BASE + 25), RDB_E_STEP_RESULT_IS_AFTER_LAST = (E_BASE + 26), RDB_E_STEP_RESULT_QUERY_EXCEEDED = (E_BASE + 27), RDB_E_STATEMENT_NOT_PREPARED = (E_BASE + 28),
RDB_E_EXECUTE_RESULT_INCORRECT = (E_BASE + 29), RDB_E_STEP_RESULT_CLOSED = (E_BASE + 30), RDB_E_RELATIVE_PATH = (E_BASE + 31), RDB_E_EMPTY_NEW_ENCRYPT_KEY = (E_BASE + 32),
RDB_E_CHANGE_UNENCRYPTED_TO_ENCRYPTED = (E_BASE + 33), RDB_E_CHANGE_ENCRYPT_KEY_IN_BUSY = (E_BASE + 34), RDB_E_STEP_STATEMENT_NOT_INIT = (E_BASE + 35), RDB_E_NOT_SUPPORTED_ATTACH_IN_WAL_MODE = (E_BASE + 36),
RDB_E_CREATE_FOLDER_FAIL = (E_BASE + 37), RDB_E_SQLITE_SQL_BUILDER_NORMALIZE_FAIL = (E_BASE + 38), RDB_E_STORE_SESSION_NOT_GIVE_CONNECTION_TEMPORARILY = (E_BASE + 39), RDB_E_STORE_SESSION_NO_CURRENT_TRANSACTION = (E_BASE + 40),
RDB_E_NOT_SUPPORT = (E_BASE + 41), RDB_E_INVALID_PARCEL = (E_BASE + 42), RDB_E_QUERY_IN_EXECUTE = (E_BASE + 43), RDB_E_SET_PERSIST_WAL = (E_BASE + 44),
RDB_E_DB_NOT_EXIST = (E_BASE + 45), RDB_E_ARGS_READ_CON_OVERLOAD = (E_BASE + 46), RDB_E_WAL_SIZE_OVER_LIMIT = (E_BASE + 47), RDB_E_CON_OVER_LIMIT = (E_BASE + 48),
RDB_E_ALREADY_CLOSED = (E_BASE + 50), RDB_E_DATABASE_BUSY = (E_BASE + 51), RDB_E_SQLITE_CORRUPT = (E_BASE + 52), RDB_E_SQLITE_PERM = (E_BASE + 53),
RDB_E_SQLITE_BUSY = (E_BASE + 54), RDB_E_SQLITE_LOCKED = (E_BASE + 55), RDB_E_SQLITE_NOMEM = (E_BASE + 56), RDB_E_SQLITE_READONLY = (E_BASE + 57),
RDB_E_SQLITE_IOERR = (E_BASE + 58), RDB_E_SQLITE_FULL = (E_BASE + 59), RDB_E_SQLITE_CANT_OPEN = (E_BASE + 60), RDB_E_SQLITE_TOO_BIG = (E_BASE + 61),
RDB_E_SQLITE_MISMATCH = (E_BASE + 62), RDB_E_DATA_TYPE_NULL = (E_BASE + 63), RDB_E_TYPE_MISMATCH = (E_BASE + 64), RDB_E_SQLITE_CONSTRAINT = (E_BASE + 65)
} | Enumerates the error codes.| diff --git a/en/application-dev/reference/apis-arkdata/udmf_8h.md b/en/application-dev/reference/apis-arkdata/udmf_8h.md index 3315c895e25f0f18829d7fc3f0810b266e51f27f..1d879d632d6fc77dde4a4014d0b204e129f5110e 100644 --- a/en/application-dev/reference/apis-arkdata/udmf_8h.md +++ b/en/application-dev/reference/apis-arkdata/udmf_8h.md @@ -23,81 +23,96 @@ Defines the APIs, data structs, and enums for accessing the UDMF. | Name| Description| | -------- | -------- | -| [UDMF_KEY_BUFFER_LEN](_u_d_m_f.md#udmf_key_buffer_len)   (512) | Minimum length of the buffer that holds the key (unique identifier) of a uniform data object.| +| [UDMF_KEY_BUFFER_LEN](_u_d_m_f.md#udmf_key_buffer_len)   (512) | Minimum length of the buffer that holds the key (unique identifier) of a uniform data object. | ### Types | Name| Description| | -------- | -------- | -| typedef enum [Udmf_Intention](_u_d_m_f.md#udmf_intention) [Udmf_Intention](_u_d_m_f.md#udmf_intention) | Defines an enum for UDMF data channel types.| +| typedef enum [Udmf_Intention](_u_d_m_f.md#udmf_intention) [Udmf_Intention](_u_d_m_f.md#udmf_intention) | Defines an enum for UDMF data channel types. | | typedef enum [Udmf_ShareOption](_u_d_m_f.md#udmf_shareoption) [Udmf_ShareOption](_u_d_m_f.md#udmf_shareoption) | Defines an enum for the scopes of the uniform data to be used on a device.| -| typedef struct [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) | Defines a struct for a uniform data object.| -| typedef struct [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) | Defines a struct for a data record in a uniform data object.| -| typedef struct [OH_UdmfRecordProvider](_u_d_m_f.md#oh_udmfrecordprovider) [OH_UdmfRecordProvider](_u_d_m_f.md#oh_udmfrecordprovider) | Defines a struct for the data record provider in a uniform data object.| -| typedef struct [OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) [OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) | Defines a struct for a data record property in a uniform data object.| -| typedef void(\* [UdmfData_Finalize](_u_d_m_f.md#udmfdata_finalize)) (void \*context) | Defines a callback function used to release the context. This callback is invoked when the **OH_UdmfRecordProvider** instance is destroyed.| -| typedef void \*(\* [OH_UdmfRecordProvider_GetData](_u_d_m_f.md#oh_udmfrecordprovider_getdata)) (void \*context, const char \*type) | Defines a callback function used to obtain data by type. This callback is invoked when data is obtained from **OH_UdmfRecord**. It returns the data obtained.| +| typedef enum [Udmf_FileConflictOptions](_u_d_m_f.md#udmf_fileconflictoptions) [Udmf_FileConflictOptions](_u_d_m_f.md#udmf_fileconflictoptions) | Defines an enum for the options used to resolve file copy conflicts. | +| typedef enum [Udmf_ProgressIndicator](_u_d_m_f.md#udmf_progressindicator) [Udmf_ProgressIndicator](_u_d_m_f.md#udmf_progressindicator) | Defines an enum for the progress indicator options. | +| typedef struct [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) | Defines a struct for a uniform data object. | +| typedef struct [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) | Defines a struct for a data record in a uniform data object. | +| typedef struct [OH_UdmfRecordProvider](_u_d_m_f.md#oh_udmfrecordprovider) [OH_UdmfRecordProvider](_u_d_m_f.md#oh_udmfrecordprovider) | Defines a struct for the data record provider in a uniform data object. | +| typedef struct [OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) [OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) | Defines a struct for a data record property in a uniform data object. | +| typedef struct [OH_Udmf_ProgressInfo](_u_d_m_f.md#oh_udmf_progressinfo) [OH_Udmf_ProgressInfo](_u_d_m_f.md#oh_udmf_progressinfo) | Defines a struct for progress information. | +| typedef struct [OH_UdmfGetDataParams](_u_d_m_f.md#oh_udmfgetdataparams) [OH_UdmfGetDataParams](_u_d_m_f.md#oh_udmfgetdataparams) | Defines a struct for parameters used to obtain UDMF data asynchronously. | +| typedef void(\* [OH_Udmf_DataProgressListener](_u_d_m_f.md#oh_udmf_dataprogresslistener)) ([OH_Udmf_ProgressInfo](_u_d_m_f.md#oh_udmf_progressinfo) \*progressInfo, [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) \*data) | Defines the callback used to return the data retrieval progress information and data obtained.
A null pointer is returned if the progress is not 100. The data obtained is returned only when the progress reaches 100.| +| typedef void(\* [UdmfData_Finalize](_u_d_m_f.md#udmfdata_finalize)) (void \*context) | Defines a callback function used to release the context. This callback is invoked when the **OH_UdmfRecordProvider** instance is destroyed. | +| typedef void \*(\* [OH_UdmfRecordProvider_GetData](_u_d_m_f.md#oh_udmfrecordprovider_getdata)) (void \*context, const char \*type) | Defines a callback function used to obtain data by type. This callback is invoked when data is obtained from **OH_UdmfRecord**. It returns the data obtained. | ### Enums | Name| Description| | -------- | -------- | -| [Udmf_Intention](_u_d_m_f.md#udmf_intention-1) { UDMF_INTENTION_DRAG, UDMF_INTENTION_PASTEBOARD } | Enumerates the UDMF data channel types.| +| [Udmf_Intention](_u_d_m_f.md#udmf_intention-1) { UDMF_INTENTION_DRAG, UDMF_INTENTION_PASTEBOARD } | Enumerates the UDMF data channel types. | | [Udmf_ShareOption](_u_d_m_f.md#udmf_shareoption-1) { SHARE_OPTIONS_INVALID, SHARE_OPTIONS_IN_APP, SHARE_OPTIONS_CROSS_APP } | Enumerates the scopes of the uniform data to be used on a device.| +| [Udmf_FileConflictOptions](_u_d_m_f.md#udmf_fileconflictoptions-1) { UDMF_OVERWRITE = 0, UDMF_SKIP = 1 } | Enumerates the options used to resolve file copy conflicts. | +| [Udmf_ProgressIndicator](_u_d_m_f.md#udmf_progressindicator-1) { UDMF_NONE = 0, UDMF_DEFAULT = 1 } | Enumerates the progress indicator options. | ### Functions | Name| Description| | -------- | -------- | -| int [OH_UdmfRecord_AddContentForm](_u_d_m_f.md#oh_udmfrecord_addcontentform) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis, [OH_UdsContentForm](_u_d_m_f.md#oh_udscontentform) \*contentForm) | Adds data of the [OH_UdsContentForm](_u_d_m_f.md#oh_udscontentform) type to an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance.| -| int [OH_UdmfRecord_GetContentForm](_u_d_m_f.md#oh_udmfrecord_getcontentform) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis, [OH_UdsContentForm](_u_d_m_f.md#oh_udscontentform) \*contentForm) | Obtains data of the [OH_UdsContentForm](_u_d_m_f.md#oh_udscontentform) type from an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance.| -| [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) \* [OH_UdmfData_Create](_u_d_m_f.md#oh_udmfdata_create) () | Creates an [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) instance and a pointer to it. If this pointer is no longer required, use [OH_UdmfData_Destroy](_u_d_m_f.md#oh_udmfdata_destroy) to destroy it. Otherwise, memory leaks may occur.| -| void [OH_UdmfData_Destroy](_u_d_m_f.md#oh_udmfdata_destroy) ([OH_UdmfData](_u_d_m_f.md#oh_udmfdata) \*pThis) | Destroys an [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) instance.| -| int [OH_UdmfData_AddRecord](_u_d_m_f.md#oh_udmfdata_addrecord) ([OH_UdmfData](_u_d_m_f.md#oh_udmfdata) \*pThis, [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*record) | Adds an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) to an [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) instance.| -| bool [OH_UdmfData_HasType](_u_d_m_f.md#oh_udmfdata_hastype) ([OH_UdmfData](_u_d_m_f.md#oh_udmfdata) \*pThis, const char \*type) | Checks whether the specified type exists in an [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) instance.| -| char \*\* [OH_UdmfData_GetTypes](_u_d_m_f.md#oh_udmfdata_gettypes) ([OH_UdmfData](_u_d_m_f.md#oh_udmfdata) \*pThis, unsigned int \*count) | Obtains all data types in an [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) instance.| -| [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*\* [OH_UdmfData_GetRecords](_u_d_m_f.md#oh_udmfdata_getrecords) ([OH_UdmfData](_u_d_m_f.md#oh_udmfdata) \*pThis, unsigned int \*count) | Obtains all records contained in an [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) instance.| -| [OH_UdmfRecordProvider](_u_d_m_f.md#oh_udmfrecordprovider) \* [OH_UdmfRecordProvider_Create](_u_d_m_f.md#oh_udmfrecordprovider_create) () | Creates an [OH_UdmfRecordProvider](_u_d_m_f.md#oh_udmfrecordprovider) instance. If this pointer is no longer required, use [OH_UdmfRecordProvider_Destroy](_u_d_m_f.md#oh_udmfrecordprovider_destroy) to destroy it. Otherwise, memory leaks may occur.| -| int [OH_UdmfRecordProvider_Destroy](_u_d_m_f.md#oh_udmfrecordprovider_destroy) ([OH_UdmfRecordProvider](_u_d_m_f.md#oh_udmfrecordprovider) \*provider) | Destroys an [OH_UdmfRecordProvider](_u_d_m_f.md#oh_udmfrecordprovider) instance.| -| int [OH_UdmfRecordProvider_SetData](_u_d_m_f.md#oh_udmfrecordprovider_setdata) ([OH_UdmfRecordProvider](_u_d_m_f.md#oh_udmfrecordprovider) \*provider, void \*context, const [OH_UdmfRecordProvider_GetData](_u_d_m_f.md#oh_udmfrecordprovider_getdata) callback, const [UdmfData_Finalize](_u_d_m_f.md#udmfdata_finalize) finalize) | Sets a callback for an **OH_UdmfRecordProvider** instance to provide data.| -| [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \* [OH_UdmfRecord_Create](_u_d_m_f.md#oh_udmfrecord_create) () | Creates an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance and a pointer to it. If this pointer is no longer required, use [OH_UdmfRecord_Destroy](_u_d_m_f.md#oh_udmfrecord_destroy) to destroy it. Otherwise, memory leaks may occur.| -| void [OH_UdmfRecord_Destroy](_u_d_m_f.md#oh_udmfrecord_destroy) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis) | Destroys an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance.| -| int [OH_UdmfRecord_AddGeneralEntry](_u_d_m_f.md#oh_udmfrecord_addgeneralentry) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis, const char \*typeId, unsigned char \*entry, unsigned int count) | Adds customized uniform data to an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance.| -| int [OH_UdmfRecord_AddPlainText](_u_d_m_f.md#oh_udmfrecord_addplaintext) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis, [OH_UdsPlainText](_u_d_m_f.md#oh_udsplaintext) \*plainText) | Adds data of the [OH_UdsPlainText](_u_d_m_f.md#oh_udsplaintext) type to an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance.| -| int [OH_UdmfRecord_AddHyperlink](_u_d_m_f.md#oh_udmfrecord_addhyperlink) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis, [OH_UdsHyperlink](_u_d_m_f.md#oh_udshyperlink) \*hyperlink) | Adds data of the hyperlink type [OH_UdsHyperlink](_u_d_m_f.md#oh_udshyperlink) type to an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance.| -| int [OH_UdmfRecord_AddHtml](_u_d_m_f.md#oh_udmfrecord_addhtml) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis, [OH_UdsHtml](_u_d_m_f.md#oh_udshtml) \*html) | Adds data of the [OH_UdsHtml](_u_d_m_f.md#oh_udshtml) type to an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance.| -| int [OH_UdmfRecord_AddAppItem](_u_d_m_f.md#oh_udmfrecord_addappitem) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis, [OH_UdsAppItem](_u_d_m_f.md#oh_udsappitem) \*appItem) | Adds data of the [OH_UdsAppItem](_u_d_m_f.md#oh_udsappitem) type to an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance.| -| int [OH_UdmfRecord_AddFileUri](_u_d_m_f.md#oh_udmfrecord_addfileuri) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis, [OH_UdsFileUri](_u_d_m_f.md#oh_udsfileuri) \*fileUri) | Adds a data record of the [OH_UdsFileUri](_u_d_m_f.md#oh_udsfileuri) type to an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance.| -| int [OH_UdmfRecord_AddPixelMap](_u_d_m_f.md#oh_udmfrecord_addpixelmap) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis, [OH_UdsPixelMap](_u_d_m_f.md#oh_udspixelmap) \*pixelMap) | Adds a data record of the [OH_UdsPixelMap](_u_d_m_f.md#oh_udspixelmap) type to an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance.| -| int [OH_UdmfRecord_AddArrayBuffer](_u_d_m_f.md#oh_udmfrecord_addarraybuffer) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*record, const char \*type, [OH_UdsArrayBuffer](_u_d_m_f.md#oh_udsarraybuffer) \*buffer) | Adds a data record of the [OH_UdsArrayBuffer](_u_d_m_f.md#oh_udsarraybuffer) type to an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance.| -| char \*\* [OH_UdmfRecord_GetTypes](_u_d_m_f.md#oh_udmfrecord_gettypes) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis, unsigned int \*count) | Obtains all data types in an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance.| -| int [OH_UdmfRecord_GetGeneralEntry](_u_d_m_f.md#oh_udmfrecord_getgeneralentry) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis, const char \*typeId, unsigned char \*\*entry, unsigned int \*count) | Obtains the data of the specified type in an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance.| -| int [OH_UdmfRecord_GetPlainText](_u_d_m_f.md#oh_udmfrecord_getplaintext) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis, [OH_UdsPlainText](_u_d_m_f.md#oh_udsplaintext) \*plainText) | Obtains [OH_UdsPlainText](_u_d_m_f.md#oh_udsplaintext) data from an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance.| -| int [OH_UdmfRecord_GetHyperlink](_u_d_m_f.md#oh_udmfrecord_gethyperlink) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis, [OH_UdsHyperlink](_u_d_m_f.md#oh_udshyperlink) \*hyperlink) | Obtains [OH_UdsHyperlink](_u_d_m_f.md#oh_udshyperlink) data from an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance.| -| int [OH_UdmfRecord_GetHtml](_u_d_m_f.md#oh_udmfrecord_gethtml) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis, [OH_UdsHtml](_u_d_m_f.md#oh_udshtml) \*html) | Obtains [OH_UdsHtml](_u_d_m_f.md#oh_udshtml) data from an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance.| -| int [OH_UdmfRecord_GetAppItem](_u_d_m_f.md#oh_udmfrecord_getappitem) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis, [OH_UdsAppItem](_u_d_m_f.md#oh_udsappitem) \*appItem) | Obtains [OH_UdsAppItem](_u_d_m_f.md#oh_udsappitem) data from an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance.| -| int [OH_UdmfRecord_SetProvider](_u_d_m_f.md#oh_udmfrecord_setprovider) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis, const char \*const \*types, unsigned int count, [OH_UdmfRecordProvider](_u_d_m_f.md#oh_udmfrecordprovider) \*provider) | Sets the [OH_UdmfRecordProvider](_u_d_m_f.md#oh_udmfrecordprovider) in an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance.| -| int [OH_UdmfRecord_GetFileUri](_u_d_m_f.md#oh_udmfrecord_getfileuri) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis, [OH_UdsFileUri](_u_d_m_f.md#oh_udsfileuri) \*fileUri) | Obtain the [OH_UdsFileUri](_u_d_m_f.md#oh_udsfileuri) data from an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance.| -| int [OH_UdmfRecord_GetPixelMap](_u_d_m_f.md#oh_udmfrecord_getpixelmap) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis, [OH_UdsPixelMap](_u_d_m_f.md#oh_udspixelmap) \*pixelMap) | Obtains the [OH_UdsPixelMap](_u_d_m_f.md#oh_udspixelmap) data from an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance.| -| int [OH_UdmfRecord_GetArrayBuffer](_u_d_m_f.md#oh_udmfrecord_getarraybuffer) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*record, const char \*type, [OH_UdsArrayBuffer](_u_d_m_f.md#oh_udsarraybuffer) \*buffer) | Obtains the [OH_UdsArrayBuffer](_u_d_m_f.md#oh_udsarraybuffer) data from an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance.| -| int [OH_UdmfData_GetPrimaryPlainText](_u_d_m_f.md#oh_udmfdata_getprimaryplaintext) ([OH_UdmfData](_u_d_m_f.md#oh_udmfdata) \*data, [OH_UdsPlainText](_u_d_m_f.md#oh_udsplaintext) \*plainText) | Obtains the first [OH_UdsPlainText](_u_d_m_f.md#oh_udsplaintext) data from an [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) instance.| -| int [OH_UdmfData_GetPrimaryHtml](_u_d_m_f.md#oh_udmfdata_getprimaryhtml) ([OH_UdmfData](_u_d_m_f.md#oh_udmfdata) \*data, [OH_UdsHtml](_u_d_m_f.md#oh_udshtml) \*html) | Obtain the first [OH_UdsHtml](_u_d_m_f.md#oh_udshtml) data from an [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) instance.| -| int [OH_UdmfData_GetRecordCount](_u_d_m_f.md#oh_udmfdata_getrecordcount) ([OH_UdmfData](_u_d_m_f.md#oh_udmfdata) \*data) | Obtains the number of data records contained in an [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) instance.| -| [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \* [OH_UdmfData_GetRecord](_u_d_m_f.md#oh_udmfdata_getrecord) ([OH_UdmfData](_u_d_m_f.md#oh_udmfdata) \*data, unsigned int index) | Obtain the specified data record from an [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) instance.| -| bool [OH_UdmfData_IsLocal](_u_d_m_f.md#oh_udmfdata_islocal) ([OH_UdmfData](_u_d_m_f.md#oh_udmfdata) \*data) | Check whether an [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) instance is from the local device.| -| [OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) \* [OH_UdmfProperty_Create](_u_d_m_f.md#oh_udmfproperty_create) ([OH_UdmfData](_u_d_m_f.md#oh_udmfdata) \*unifiedData) | Creates an [OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) instance and a pointer to it. If this pointer is no longer required, use [OH_UdmfProperty_Destroy](_u_d_m_f.md#oh_udmfproperty_destroy) to destroy it. Otherwise, memory leaks may occur.| -| void [OH_UdmfProperty_Destroy](_u_d_m_f.md#oh_udmfproperty_destroy) ([OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) \*pThis) | Destroys an [OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) instance.| -| const char \* [OH_UdmfProperty_GetTag](_u_d_m_f.md#oh_udmfproperty_gettag) ([OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) \*pThis) | Obtains the custom tag value from an [OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) instance.| -| int64_t [OH_UdmfProperty_GetTimestamp](_u_d_m_f.md#oh_udmfproperty_gettimestamp) ([OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) \*pThis) | Obtains the timestamp from an [OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) instance.| -| [Udmf_ShareOption](_u_d_m_f.md#udmf_shareoption)[OH_UdmfProperty_GetShareOption](_u_d_m_f.md#oh_udmfproperty_getshareoption) ([OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) \*pThis) | Obtains the share option from an [OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) instance.| -| int [OH_UdmfProperty_GetExtrasIntParam](_u_d_m_f.md#oh_udmfproperty_getextrasintparam) ([OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) \*pThis, const char \*key, int defaultValue) | Obtains the customized extra integer parameter from an [OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) instance.| -| const char \* [OH_UdmfProperty_GetExtrasStringParam](_u_d_m_f.md#oh_udmfproperty_getextrasstringparam) ([OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) \*pThis, const char \*key) | Obtains the customized extra string parameter from an [OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) instance.| -| int [OH_UdmfProperty_SetTag](_u_d_m_f.md#oh_udmfproperty_settag) ([OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) \*pThis, const char \*tag) | Sets the tag value for an [OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) instance.| +| [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) \* [OH_UdmfData_Create](_u_d_m_f.md#oh_udmfdata_create) () | Creates an [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) instance and a pointer to it. If this pointer is no longer required, use [OH_UdmfData_Destroy](_u_d_m_f.md#oh_udmfdata_destroy) to destroy it. Otherwise, memory leaks may occur. | +| void [OH_UdmfData_Destroy](_u_d_m_f.md#oh_udmfdata_destroy) ([OH_UdmfData](_u_d_m_f.md#oh_udmfdata) \*pThis) | Destroys an [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) instance. | +| int [OH_UdmfData_AddRecord](_u_d_m_f.md#oh_udmfdata_addrecord) ([OH_UdmfData](_u_d_m_f.md#oh_udmfdata) \*pThis, [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*record) | Adds an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) to an [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) instance. | +| bool [OH_UdmfData_HasType](_u_d_m_f.md#oh_udmfdata_hastype) ([OH_UdmfData](_u_d_m_f.md#oh_udmfdata) \*pThis, const char \*type) | Checks whether the specified type exists in an [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) instance. | +| char \*\* [OH_UdmfData_GetTypes](_u_d_m_f.md#oh_udmfdata_gettypes) ([OH_UdmfData](_u_d_m_f.md#oh_udmfdata) \*pThis, unsigned int \*count) | Obtains all data types in an [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) instance. | +| [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*\* [OH_UdmfData_GetRecords](_u_d_m_f.md#oh_udmfdata_getrecords) ([OH_UdmfData](_u_d_m_f.md#oh_udmfdata) \*pThis, unsigned int \*count) | Obtains all records contained in an [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) instance. | +| [OH_UdmfRecordProvider](_u_d_m_f.md#oh_udmfrecordprovider) \* [OH_UdmfRecordProvider_Create](_u_d_m_f.md#oh_udmfrecordprovider_create) () | Creates an [OH_UdmfRecordProvider](_u_d_m_f.md#oh_udmfrecordprovider) instance. If this pointer is no longer required, use [OH_UdmfRecordProvider_Destroy](_u_d_m_f.md#oh_udmfrecordprovider_destroy) to destroy it. Otherwise, memory leaks may occur. | +| int [OH_UdmfRecordProvider_Destroy](_u_d_m_f.md#oh_udmfrecordprovider_destroy) ([OH_UdmfRecordProvider](_u_d_m_f.md#oh_udmfrecordprovider) \*provider) | Destroys an [OH_UdmfRecordProvider](_u_d_m_f.md#oh_udmfrecordprovider) instance. | +| int [OH_UdmfRecordProvider_SetData](_u_d_m_f.md#oh_udmfrecordprovider_setdata) ([OH_UdmfRecordProvider](_u_d_m_f.md#oh_udmfrecordprovider) \*provider, void \*context, const [OH_UdmfRecordProvider_GetData](_u_d_m_f.md#oh_udmfrecordprovider_getdata) callback, const [UdmfData_Finalize](_u_d_m_f.md#udmfdata_finalize) finalize) | Sets a callback for an **OH_UdmfRecordProvider** instance to provide data. | +| [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \* [OH_UdmfRecord_Create](_u_d_m_f.md#oh_udmfrecord_create) () | Creates an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance and a pointer to it. If this pointer is no longer required, use [OH_UdmfRecord_Destroy](_u_d_m_f.md#oh_udmfrecord_destroy) to destroy it. Otherwise, memory leaks may occur. | +| void [OH_UdmfRecord_Destroy](_u_d_m_f.md#oh_udmfrecord_destroy) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis) | Destroys an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance. | +| int [OH_UdmfRecord_AddGeneralEntry](_u_d_m_f.md#oh_udmfrecord_addgeneralentry) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis, const char \*typeId, unsigned char \*entry, unsigned int count) | Adds customized uniform data to an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance. This API cannot be used to add data of UDS types (such as PlainText, Link, and Pixelmap). | +| int [OH_UdmfRecord_AddPlainText](_u_d_m_f.md#oh_udmfrecord_addplaintext) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis, [OH_UdsPlainText](_u_d_m_f.md#oh_udsplaintext) \*plainText) | Adds data of the [OH_UdsPlainText](_u_d_m_f.md#oh_udsplaintext) type to an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance. | +| int [OH_UdmfRecord_AddHyperlink](_u_d_m_f.md#oh_udmfrecord_addhyperlink) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis, [OH_UdsHyperlink](_u_d_m_f.md#oh_udshyperlink) \*hyperlink) | Adds data of the hyperlink type [OH_UdsHyperlink](_u_d_m_f.md#oh_udshyperlink) type to an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance. | +| int [OH_UdmfRecord_AddHtml](_u_d_m_f.md#oh_udmfrecord_addhtml) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis, [OH_UdsHtml](_u_d_m_f.md#oh_udshtml) \*html) | Adds data of the [OH_UdsHtml](_u_d_m_f.md#oh_udshtml) type to an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance. | +| int [OH_UdmfRecord_AddAppItem](_u_d_m_f.md#oh_udmfrecord_addappitem) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis, [OH_UdsAppItem](_u_d_m_f.md#oh_udsappitem) \*appItem) | Adds data of the [OH_UdsAppItem](_u_d_m_f.md#oh_udsappitem) type to an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance. | +| int [OH_UdmfRecord_AddFileUri](_u_d_m_f.md#oh_udmfrecord_addfileuri) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis, [OH_UdsFileUri](_u_d_m_f.md#oh_udsfileuri) \*fileUri) | Adds a data record of the [OH_UdsFileUri](_u_d_m_f.md#oh_udsfileuri) type to an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance. | +| int [OH_UdmfRecord_AddPixelMap](_u_d_m_f.md#oh_udmfrecord_addpixelmap) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis, [OH_UdsPixelMap](_u_d_m_f.md#oh_udspixelmap) \*pixelMap) | Adds a data record of the [OH_UdsPixelMap](_u_d_m_f.md#oh_udspixelmap) type to an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance. | +| int [OH_UdmfRecord_AddArrayBuffer](_u_d_m_f.md#oh_udmfrecord_addarraybuffer) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*record, const char \*type, [OH_UdsArrayBuffer](_u_d_m_f.md#oh_udsarraybuffer) \*buffer) | Adds a data record of the [OH_UdsArrayBuffer](_u_d_m_f.md#oh_udsarraybuffer) type to an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance. | +| int [OH_UdmfRecord_AddContentForm](_u_d_m_f.md#oh_udmfrecord_addcontentform) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis, [OH_UdsContentForm](_u_d_m_f.md#oh_udscontentform) \*contentForm) | Adds data of the [OH_UdsContentForm](_u_d_m_f.md#oh_udscontentform) type to an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance. | +| char \*\* [OH_UdmfRecord_GetTypes](_u_d_m_f.md#oh_udmfrecord_gettypes) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis, unsigned int \*count) | Obtains all data types in an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance. | +| int [OH_UdmfRecord_GetGeneralEntry](_u_d_m_f.md#oh_udmfrecord_getgeneralentry) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis, const char \*typeId, unsigned char \*\*entry, unsigned int \*count) | Obtains the data of the specified type in an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance. | +| int [OH_UdmfRecord_GetPlainText](_u_d_m_f.md#oh_udmfrecord_getplaintext) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis, [OH_UdsPlainText](_u_d_m_f.md#oh_udsplaintext) \*plainText) | Obtains [OH_UdsPlainText](_u_d_m_f.md#oh_udsplaintext) data from an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance. | +| int [OH_UdmfRecord_GetHyperlink](_u_d_m_f.md#oh_udmfrecord_gethyperlink) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis, [OH_UdsHyperlink](_u_d_m_f.md#oh_udshyperlink) \*hyperlink) | Obtains [OH_UdsHyperlink](_u_d_m_f.md#oh_udshyperlink) data from an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance. | +| int [OH_UdmfRecord_GetHtml](_u_d_m_f.md#oh_udmfrecord_gethtml) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis, [OH_UdsHtml](_u_d_m_f.md#oh_udshtml) \*html) | Obtains [OH_UdsHtml](_u_d_m_f.md#oh_udshtml) data from an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance. | +| int [OH_UdmfRecord_GetAppItem](_u_d_m_f.md#oh_udmfrecord_getappitem) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis, [OH_UdsAppItem](_u_d_m_f.md#oh_udsappitem) \*appItem) | Obtains [OH_UdsAppItem](_u_d_m_f.md#oh_udsappitem) data from an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance. | +| int [OH_UdmfRecord_SetProvider](_u_d_m_f.md#oh_udmfrecord_setprovider) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis, const char \*const \*types, unsigned int count, [OH_UdmfRecordProvider](_u_d_m_f.md#oh_udmfrecordprovider) \*provider) | Sets the [OH_UdmfRecordProvider](_u_d_m_f.md#oh_udmfrecordprovider) in an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance. | +| int [OH_UdmfRecord_GetFileUri](_u_d_m_f.md#oh_udmfrecord_getfileuri) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis, [OH_UdsFileUri](_u_d_m_f.md#oh_udsfileuri) \*fileUri) | Obtains the [OH_UdsFileUri](_u_d_m_f.md#oh_udsfileuri) data from an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance. | +| int [OH_UdmfRecord_GetPixelMap](_u_d_m_f.md#oh_udmfrecord_getpixelmap) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis, [OH_UdsPixelMap](_u_d_m_f.md#oh_udspixelmap) \*pixelMap) | Obtains the [OH_UdsPixelMap](_u_d_m_f.md#oh_udspixelmap) data from an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance. | +| int [OH_UdmfRecord_GetArrayBuffer](_u_d_m_f.md#oh_udmfrecord_getarraybuffer) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*record, const char \*type, [OH_UdsArrayBuffer](_u_d_m_f.md#oh_udsarraybuffer) \*buffer) | Obtains the [OH_UdsArrayBuffer](_u_d_m_f.md#oh_udsarraybuffer) data from an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance. | +| int [OH_UdmfRecord_GetContentForm](_u_d_m_f.md#oh_udmfrecord_getcontentform) ([OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \*pThis, [OH_UdsContentForm](_u_d_m_f.md#oh_udscontentform) \*contentForm) | Obtains data of the [OH_UdsContentForm](_u_d_m_f.md#oh_udscontentform) type from an [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) instance. | +| int [OH_UdmfData_GetPrimaryPlainText](_u_d_m_f.md#oh_udmfdata_getprimaryplaintext) ([OH_UdmfData](_u_d_m_f.md#oh_udmfdata) \*data, [OH_UdsPlainText](_u_d_m_f.md#oh_udsplaintext) \*plainText) | Obtains the first [OH_UdsPlainText](_u_d_m_f.md#oh_udsplaintext) data from an [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) instance. | +| int [OH_UdmfData_GetPrimaryHtml](_u_d_m_f.md#oh_udmfdata_getprimaryhtml) ([OH_UdmfData](_u_d_m_f.md#oh_udmfdata) \*data, [OH_UdsHtml](_u_d_m_f.md#oh_udshtml) \*html) | Obtains the first [OH_UdsHtml](_u_d_m_f.md#oh_udshtml) data from an [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) instance. | +| int [OH_UdmfData_GetRecordCount](_u_d_m_f.md#oh_udmfdata_getrecordcount) ([OH_UdmfData](_u_d_m_f.md#oh_udmfdata) \*data) | Obtains the number of data records contained in an [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) instance. | +| [OH_UdmfRecord](_u_d_m_f.md#oh_udmfrecord) \* [OH_UdmfData_GetRecord](_u_d_m_f.md#oh_udmfdata_getrecord) ([OH_UdmfData](_u_d_m_f.md#oh_udmfdata) \*data, unsigned int index) | Obtains the specified data record from an [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) instance. | +| bool [OH_UdmfData_IsLocal](_u_d_m_f.md#oh_udmfdata_islocal) ([OH_UdmfData](_u_d_m_f.md#oh_udmfdata) \*data) | Checks whether an [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) instance is from the local device. | +| [OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) \* [OH_UdmfProperty_Create](_u_d_m_f.md#oh_udmfproperty_create) ([OH_UdmfData](_u_d_m_f.md#oh_udmfdata) \*unifiedData) | Creates an [OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) instance and a pointer to it. If this pointer is no longer required, use [OH_UdmfProperty_Destroy](_u_d_m_f.md#oh_udmfproperty_destroy) to destroy it. Otherwise, memory leaks may occur. | +| void [OH_UdmfProperty_Destroy](_u_d_m_f.md#oh_udmfproperty_destroy) ([OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) \*pThis) | Destroys an [OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) instance. | +| const char \* [OH_UdmfProperty_GetTag](_u_d_m_f.md#oh_udmfproperty_gettag) ([OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) \*pThis) | Obtains the custom tag value from an [OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) instance. | +| int64_t [OH_UdmfProperty_GetTimestamp](_u_d_m_f.md#oh_udmfproperty_gettimestamp) ([OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) \*pThis) | Obtains the timestamp from an [OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) instance. | +| [Udmf_ShareOption](_u_d_m_f.md#udmf_shareoption) [OH_UdmfProperty_GetShareOption](_u_d_m_f.md#oh_udmfproperty_getshareoption) ([OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) \*pThis) | Obtains the share option from an [OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) instance. | +| int [OH_UdmfProperty_GetExtrasIntParam](_u_d_m_f.md#oh_udmfproperty_getextrasintparam) ([OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) \*pThis, const char \*key, int defaultValue) | Obtains the customized extra integer parameter from an [OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) instance. | +| const char \* [OH_UdmfProperty_GetExtrasStringParam](_u_d_m_f.md#oh_udmfproperty_getextrasstringparam) ([OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) \*pThis, const char \*key) | Obtains the customized extra string parameter from an [OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) instance. | +| int [OH_UdmfProperty_SetTag](_u_d_m_f.md#oh_udmfproperty_settag) ([OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) \*pThis, const char \*tag) | Sets the tag value for an [OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) instance. | | int [OH_UdmfProperty_SetShareOption](_u_d_m_f.md#oh_udmfproperty_setshareoption) ([OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) \*pThis, [Udmf_ShareOption](_u_d_m_f.md#udmf_shareoption) option) | Sets **OH_Udmf_ShareOption** for an [OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) instance.| -| int [OH_UdmfProperty_SetExtrasIntParam](_u_d_m_f.md#oh_udmfproperty_setextrasintparam) ([OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) \*pThis, const char \*key, int param) | Sets the extra integer parameter for an [OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) instance.| -| int [OH_UdmfProperty_SetExtrasStringParam](_u_d_m_f.md#oh_udmfproperty_setextrasstringparam) ([OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) \*pThis, const char \*key, const char \*param) | Sets the extra string parameter for an [OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) instance.| -| int [OH_Udmf_GetUnifiedData](_u_d_m_f.md#oh_udmf_getunifieddata) (const char \*key, [Udmf_Intention](_u_d_m_f.md#udmf_intention) intention, [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) \*unifiedData) | Obtains an [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) instance from the UDMF database.| -| int [OH_Udmf_SetUnifiedData](_u_d_m_f.md#oh_udmf_setunifieddata) ([Udmf_Intention](_u_d_m_f.md#udmf_intention) intention, [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) \*unifiedData, char \*key, unsigned int keyLen) | Sets an [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) instance in the UDMF database.| +| int [OH_UdmfProperty_SetExtrasIntParam](_u_d_m_f.md#oh_udmfproperty_setextrasintparam) ([OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) \*pThis, const char \*key, int param) | Sets the extra integer parameter for an [OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) instance. | +| int [OH_UdmfProperty_SetExtrasStringParam](_u_d_m_f.md#oh_udmfproperty_setextrasstringparam) ([OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) \*pThis, const char \*key, const char \*param) | Sets the extra string parameter for an [OH_UdmfProperty](_u_d_m_f.md#oh_udmfproperty) instance. | +| int [OH_Udmf_GetUnifiedData](_u_d_m_f.md#oh_udmf_getunifieddata) (const char \*key, [Udmf_Intention](_u_d_m_f.md#udmf_intention) intention, [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) \*unifiedData) | Obtains an [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) instance from the UDMF database. | +| int [OH_Udmf_SetUnifiedData](_u_d_m_f.md#oh_udmf_setunifieddata) ([Udmf_Intention](_u_d_m_f.md#udmf_intention) intention, [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) \*unifiedData, char \*key, unsigned int keyLen) | Sets an [OH_UdmfData](_u_d_m_f.md#oh_udmfdata) instance in the UDMF database. | +| int [OH_UdmfProgressInfo_GetProgress](_u_d_m_f.md#oh_udmfprogressinfo_getprogress) ([OH_Udmf_ProgressInfo](_u_d_m_f.md#oh_udmf_progressinfo) \*progressInfo) | Obtains the progress information from [OH_Udmf_ProgressInfo](_u_d_m_f.md#oh_udmf_progressinfo). | +| int [OH_UdmfProgressInfo_GetStatus](_u_d_m_f.md#oh_udmfprogressinfo_getstatus) ([OH_Udmf_ProgressInfo](_u_d_m_f.md#oh_udmf_progressinfo) \*progressInfo) | Obtains the status information from [OH_Udmf_ProgressInfo](_u_d_m_f.md#oh_udmf_progressinfo). | +| [OH_UdmfGetDataParams](_u_d_m_f.md#oh_udmfgetdataparams) \* [OH_UdmfGetDataParams_Create](_u_d_m_f.md#oh_udmfgetdataparams_create) () | Creates an [OH_UdmfGetDataParams](_u_d_m_f.md#oh_udmfgetdataparams) instance for asynchronously obtaining UDMF data.
If this pointer is no longer required, use [OH_UdmfGetDataParams_Destroy](_u_d_m_f.md#oh_udmfgetdataparams_destroy) to destroy it. Otherwise, memory leaks may occur.| +| void [OH_UdmfGetDataParams_Destroy](_u_d_m_f.md#oh_udmfgetdataparams_destroy) ([OH_UdmfGetDataParams](_u_d_m_f.md#oh_udmfgetdataparams) \*pThis) | Destroys an [OH_UdmfGetDataParams](_u_d_m_f.md#oh_udmfgetdataparams) instance. | +| void [OH_UdmfGetDataParams_SetDestUri](_u_d_m_f.md#oh_udmfgetdataparams_setdesturi) ([OH_UdmfGetDataParams](_u_d_m_f.md#oh_udmfgetdataparams) \*params, const char \*destUri) | Sets the destination directory in an [OH_UdmfGetDataParams](_u_d_m_f.md#oh_udmfgetdataparams) instance.
If the destination directory is set, data of the file type will be copied to the specified directory. The file type data obtained in the callback will be replaced with the URI of the destination directory.
If the destination directory is not specified, the file will not be copied. The file type data obtained in the callback is the URI of the source directory.
If the application involves complex file processing or files need to be copied to multiple directories, you are advised to leave this parameter unspecified and let the application to handle the file copy.| +| void [OH_UdmfGetDataParams_SetFileConflictOptions](_u_d_m_f.md#oh_udmfgetdataparams_setfileconflictoptions) ([OH_UdmfGetDataParams](_u_d_m_f.md#oh_udmfgetdataparams) \*params, const [Udmf_FileConflictOptions](_u_d_m_f.md#udmf_fileconflictoptions) options) | Sets the policy for resolving file conflicts in an [OH_UdmfGetDataParams](_u_d_m_f.md#oh_udmfgetdataparams) instance. | +| void [OH_UdmfGetDataParams_SetProgressIndicator](_u_d_m_f.md#oh_udmfgetdataparams_setprogressindicator) ([OH_UdmfGetDataParams](_u_d_m_f.md#oh_udmfgetdataparams) \*params, const [Udmf_ProgressIndicator](_u_d_m_f.md#udmf_progressindicator) progressIndicator) | Sets the progress indicator in an [OH_UdmfGetDataParams](_u_d_m_f.md#oh_udmfgetdataparams) instance. | +| void [OH_UdmfGetDataParams_SetDataProgressListener](_u_d_m_f.md#oh_udmfgetdataparams_setdataprogresslistener) ([OH_UdmfGetDataParams](_u_d_m_f.md#oh_udmfgetdataparams) \*params, const [OH_Udmf_DataProgressListener](_u_d_m_f.md#oh_udmf_dataprogresslistener) dataProgressListener) | Sets the callback used to return the data obtained in an [OH_UdmfGetDataParams](_u_d_m_f.md#oh_udmfgetdataparams) instance. | diff --git a/en/application-dev/reference/apis-arkdata/udmf__err__code_8h.md b/en/application-dev/reference/apis-arkdata/udmf__err__code_8h.md index 3083bf0867100cf70ca1f35b30a7b47d08b720e8..0c0faf916a2dd17fdfb211b58b2941cd81e13ecb 100644 --- a/en/application-dev/reference/apis-arkdata/udmf__err__code_8h.md +++ b/en/application-dev/reference/apis-arkdata/udmf__err__code_8h.md @@ -21,13 +21,15 @@ Declares the error codes used in the UDMF. ### Types -| Name | Description | +| Name| Description| | -------- | -------- | -| typedef enum [Udmf_ErrCode](_u_d_m_f.md#udmf_errcode) [Udmf_ErrCode](_u_d_m_f.md#udmf_errcode) | Defines an enum for error codes. | +| typedef enum [Udmf_ErrCode](_u_d_m_f.md#udmf_errcode) [Udmf_ErrCode](_u_d_m_f.md#udmf_errcode) | Defines an enum for error codes.| +| typedef enum [Udmf_ListenerStatus](_u_d_m_f.md#udmf_listenerstatus) [Udmf_ListenerStatus](_u_d_m_f.md#udmf_listenerstatus) | Defines an enum for the status codes returned when data is obtained asynchronously.| ### Enums -| Name | Description | +| Name| Description| | -------- | -------- | -| [Udmf_ErrCode](_u_d_m_f.md#udmf_errcode) { UDMF_E_OK = 0, UDMF_ERR = 20400000, UDMF_E_INVALID_PARAM = (UDMF_ERR + 1) } | Enumerates the error codes. | +| [Udmf_ErrCode](_u_d_m_f.md#udmf_errcode-1) { UDMF_E_OK = 0, UDMF_ERR = 20400000, UDMF_E_INVALID_PARAM = (UDMF_ERR + 1) } | Enumerates the error codes.| +| [Udmf_ListenerStatus](_u_d_m_f.md#udmf_listenerstatus-1) {
UDMF_FINISHED = 0, UDMF_PROCESSING, UDMF_CANCELED, UDMF_INNER_ERROR = 200,
UDMF_INVALID_PARAMETERS, UDMF_DATA_NOT_FOUND, UDMF_SYNC_FAILED, UDMF_COPY_FILE_FAILED
} | Enumerates the status codes returned when data is obtained asynchronously.| diff --git a/en/application-dev/reference/apis-arkgraphics2d/Readme-EN.md b/en/application-dev/reference/apis-arkgraphics2d/Readme-EN.md index f8b7f8b3f48485a3808fc3d73a98803a47f1bb22..e8c820373e4ba735e1ae6229639dadccb267de98 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/Readme-EN.md +++ b/en/application-dev/reference/apis-arkgraphics2d/Readme-EN.md @@ -1,6 +1,6 @@ # ArkGraphics 2D -- ArkTS APIs +- ArkTS APIs - [@ohos.effectKit (Image Effects)](js-apis-effectKit.md) - [@ohos.graphics.colorSpaceManager (Color Space Management)](js-apis-colorSpaceManager.md) - [@ohos.graphics.sendableColorSpaceManager (Sendable Color Space Management)](js-apis-sendableColorSpaceManager.md) @@ -10,9 +10,11 @@ - [@ohos.graphics.hdrCapability (HDR Capability)](js-apis-hdrCapability.md) - [@ohos.graphics.text (Text)](js-apis-graphics-text.md) - [@ohos.graphics.uiEffect (Cascading Effect)](js-apis-uiEffect.md) + - [@ohos.graphics.uiEffect (Cascading Effect) (System API)](js-apis-uiEffect-sys.md) -- C APIs - - Modules + +- C APIs + - Modules - [Drawing](_drawing.md) - [EffectKit](effect_kit.md) - [NativeDisplaySoloist](_native_display_soloist.md) @@ -21,7 +23,7 @@ - [OH_NativeBuffer](_o_h___native_buffer.md) - [OH_NativeImage](_o_h___native_image.md) - [NativeColorSpaceManager](_native_color_space_manager.md) - - Header Files + - Header Files - [drawing_bitmap.h](drawing__bitmap_8h.md) - [drawing_brush.h](drawing__brush_8h.md) - [drawing_canvas.h](drawing__canvas_8h.md) @@ -64,13 +66,15 @@ - [drawing_types.h](drawing__types_8h.md) - [effect_filter.h](effect__filter_8h.md) - [effect_types.h](effect__types_8h.md) + - [buffer_handle.h](buffer__handle_8h.md) - [external_window.h](external__window_8h.md) + - [buffer_common.h](buffer__common_8h.md) - [native_buffer.h](native__buffer_8h.md) - [native_display_soloist.h](native__display__soloist_8h.md) - [native_image.h](native__image_8h.md) - [native_vsync.h](native__vsync_8h.md) - [native_color_space_manager.h](native__color__space__manager_8h.md) - - Structs + - Structs - [DisplaySoloist_ExpectedRateRange](_display_soloist___expected_rate_range.md) - [OH_Drawing_BitmapFormat](_o_h___drawing___bitmap_format.md) - [OH_Drawing_Font_Metrics](_o_h___drawing___font___metrics.md) @@ -103,11 +107,12 @@ - [OH_NativeBuffer_Smpte2086](_o_h___native_buffer___smpte2086.md) - [OH_NativeBuffer_StaticMetadata](_o_h___native_buffer___static_metadata.md) - [OH_OnFrameAvailableListener](_o_h___on_frame_available_listener.md) + - [BufferHandle](_buffer_handle.md) - [OHExtDataHandle](_o_h_ext_data_handle.md) - [OHHDRMetaData](_o_h_h_d_r_meta_data.md) - [Region](_region.md) - [Rect](_rect.md) - [ColorSpacePrimaries](_color_space_primaries.md) - [WhitePointArray](_white_point_array.md) -- Error Codes +- Error Codes - [colorSpaceManager Error Codes](errorcode-colorspace-manager.md) diff --git a/en/application-dev/reference/apis-arkgraphics2d/_buffer_handle.md b/en/application-dev/reference/apis-arkgraphics2d/_buffer_handle.md new file mode 100644 index 0000000000000000000000000000000000000000..b8a082aa40e416389da4982041837b399a766499 --- /dev/null +++ b/en/application-dev/reference/apis-arkgraphics2d/_buffer_handle.md @@ -0,0 +1,178 @@ +# BufferHandle + + +## Overview + +The BufferHandle struct describes the buffer handle, which is used to transfer and obtain buffer information. The handle contains the file descriptor, size, format, usage, virtual address, shared memory key, physical address, and custom data of the buffer. + +**Since**: 8 + +**Related module**: [NativeWindow](_native_window.md) + + +## Summary + + +### Member Variables + +| Name| Description| +| -------- | -------- | +| int32_t [fd](#fd) | File descriptor of the buffer. The value **-1** means that the buffer is not supported. | +| int32_t [width](#width) | Width of the buffer memory, in pixels. | +| int32_t [stride](#stride) | Stride of the buffer memory, in bytes. | +| int32_t [height](#height) | Height of the buffer memory, in pixels. | +| int32_t [size](#size) | Size of the buffer memory, in bytes. | +| int32_t [format](#format) | Format of the buffer memory. For details about available options, see [OH_NativeBuffer_Format](_o_h___native_buffer.md#oh_nativebuffer_format-1). | +| uint64_t [usage](#usage) | Usage of the buffer memory, represented as bit flags. For details about available options, see [OH_NativeBuffer_Usage](_o_h___native_buffer.md#oh_nativebuffer_usage-1). | +| void \* [virAddr](#viraddr) | Virtual address of the buffer memory. | +| int32_t [key](#key) | Shared memory key of the buffer memory. | +| uint64_t [phyAddr](#phyaddr) | Physical address of the buffer memory. | +| uint32_t [reserveFds](#reservefds) | Number of file descriptors for extra data. | +| uint32_t [reserveInts](#reserveints) | Number of integer values for extra data. | +| int32_t [reserve](#reserve) [0] | Extra data. | + + +## Member Variable Description + + +### fd + +``` +int32_t BufferHandle::fd +``` + +**Description** + +File descriptor of the buffer. The value **-1** means that the buffer is not supported. + + +### format + +``` +int32_t BufferHandle::format +``` + +**Description** + +Format of the buffer memory. For details about available options, see [OH_NativeBuffer_Format](_o_h___native_buffer.md#oh_nativebuffer_format-1). + + +### height + +``` +int32_t BufferHandle::height +``` + +**Description** + +Height of the buffer memory, in pixels. + + +### key + +``` +int32_t BufferHandle::key +``` + +**Description** + +Shared memory key of the buffer memory. + + +### phyAddr + +``` +uint64_t BufferHandle::phyAddr +``` + +**Description** + +Physical address of the buffer memory. + + +### reserve + +``` +int32_t BufferHandle::reserve[0] +``` + +**Description** + +Extra data. + + +### reserveFds + +``` +uint32_t BufferHandle::reserveFds +``` + +**Description** + +Number of file descriptors for extra data. + + +### reserveInts + +``` +uint32_t BufferHandle::reserveInts +``` + +**Description** + +Number of integer values for extra data. + + +### size + +``` +int32_t BufferHandle::size +``` + +**Description** + +Size of the buffer memory, in bytes. + + +### stride + +``` +int32_t BufferHandle::stride +``` + +**Description** + +Stride of the buffer memory, in bytes. + + +### usage + +``` +uint64_t BufferHandle::usage +``` + +**Description** + +Usage of the buffer memory, represented as bit flags. For details about available options, see [OH_NativeBuffer_Usage](_o_h___native_buffer.md#oh_nativebuffer_usage-1). + + +### virAddr + +``` +void* BufferHandle::virAddr +``` + +**Description** + +Virtual address of the buffer memory. + + +### width + +``` +int32_t BufferHandle::width +``` + +**Description** + +Width of the buffer memory, in pixels. diff --git a/en/application-dev/reference/apis-arkgraphics2d/_drawing.md b/en/application-dev/reference/apis-arkgraphics2d/_drawing.md index e457880c74c1bfd5164cc2a5a1a8ebd24e368848..877406590a64c51a6d943a6cbcb03c1a364658b0 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/_drawing.md +++ b/en/application-dev/reference/apis-arkgraphics2d/_drawing.md @@ -52,7 +52,7 @@ The Drawing module provides the functions for 2D graphics rendering, text drawin | [drawing_text_declaration.h](drawing__text__declaration_8h.md) | Declares the structs related to text in 2D drawing.| | [drawing_text_font_descriptor.h](drawing__text__font__descriptor_8h.md) | Declares the capabilities of font information, such as obtaining font information and searching for a font.| | [drawing_text_line.h](drawing__text__line_8h.md) | Declares the capabilities for obtaining the character position in a text line, obtaining the run information, and truncating text by line.| -| [drawing_text_lineTypography.h](drawing__text__line_typography_8h.md) | Declares the functions related to line typography, including functions to determine the number of characters that can be formatted from a given position within the text. | +| [drawing_text_lineTypography.h](drawing__text__line_typography_8h.md) | Declares the functions related to line typography, including functions to determine the number of characters that can be formatted from a given position within the text.| | [drawing_text_run.h](drawing__text__run_8h.md) | Declares the capabilities of runs, such as obtaining the typographic boundary and drawing. | | [drawing_text_typography.h](drawing__text__typography_8h.md) | Declares the functions related to typography in the drawing module.| | [drawing_typeface.h](drawing__typeface_8h.md) | Declares the functions related to the typeface in the drawing module. Different platforms have their own default typefaces. You can also parse the .ttf file to obtain the typefaces specified by the third party, such as SimSun and SimHei.| @@ -90,13 +90,14 @@ The Drawing module provides the functions for 2D graphics rendering, text drawin | Name| Description| | -------- | -------- | +| typedef enum [OH_Drawing_PathDashStyle](#oh_drawing_pathdashstyle) [OH_Drawing_PathDashStyle](#oh_drawing_pathdashstyle) | Defines an enum for the drawing styles for path effects. | | typedef struct [OH_Drawing_String](_o_h___drawing___string.md) [OH_Drawing_String](#oh_drawing_string) | Defines a struct for a string of characters encoded in UTF-16.| | typedef enum [OH_Drawing_SystemFontType](#oh_drawing_systemfonttype) [OH_Drawing_SystemFontType](#oh_drawing_systemfonttype) | Defines an enum for the system font types.| | typedef bool(\* [Drawing_CaretOffsetsCallback](#drawing_caretoffsetscallback)) (double offset, int32_t index, bool leadingEdge) | Defines a custom callback used to receive the offset and index of each character in a text line object as its parameters.| | typedef struct [OH_Drawing_LineTypography](#oh_drawing_linetypography) [OH_Drawing_LineTypography](#oh_drawing_linetypography) | Defines a struct used to extract a single line of data from a piece of text for typography.| | typedef struct [OH_Drawing_TextTab](#oh_drawing_texttab) [OH_Drawing_TextTab](#oh_drawing_texttab) | Defines a struct used to manage text tabs.| -| typedef struct [OH_Drawing_TextLine](#oh_drawing_textline) [OH_Drawing_TextLine](#oh_drawing_textline) | Defines a struct used to manage text lines. | -| typedef struct [OH_Drawing_Run](#oh_drawing_run) [OH_Drawing_Run](#oh_drawing_run) | Defines a struct used to manage runs. | +| typedef struct [OH_Drawing_TextLine](#oh_drawing_textline) [OH_Drawing_TextLine](#oh_drawing_textline) | Defines a struct used to manage text lines.| +| typedef struct [OH_Drawing_Run](#oh_drawing_run) [OH_Drawing_Run](#oh_drawing_run) | Defines a struct used to manage runs.| | typedef struct [OH_Drawing_Array](#oh_drawing_array) [OH_Drawing_Array](#oh_drawing_array) | Defines a struct for an array object, which is used to store multiple objects of the same type.| | typedef struct [OH_Drawing_FontArguments](#oh_drawing_fontarguments) [OH_Drawing_FontArguments](#oh_drawing_fontarguments) | Defines a struct for font arguments.| | typedef struct [OH_Drawing_RecordCmdUtils](#oh_drawing_recordcmdutils) [OH_Drawing_RecordCmdUtils](#oh_drawing_recordcmdutils) | Defines the recording command tool, which is used to generate recording commands.| @@ -135,13 +136,13 @@ The Drawing module provides the functions for 2D graphics rendering, text drawin | typedef struct [OH_Drawing_TypographyCreate](#oh_drawing_typographycreate) [OH_Drawing_TypographyCreate](#oh_drawing_typographycreate) | Defines a struct used to create an [OH_Drawing_Typography](#oh_drawing_typography) object.| | typedef struct [OH_Drawing_TextBox](#oh_drawing_textbox) [OH_Drawing_TextBox](#oh_drawing_textbox) | Defines a struct for a text box, which is used to receive the rectangle size, direction, and quantity.| | typedef struct [OH_Drawing_PositionAndAffinity](#oh_drawing_positionandaffinity) [OH_Drawing_PositionAndAffinity](#oh_drawing_positionandaffinity) | Defines a struct used to receive the position and affinity of a glyph.| -| typedef struct [OH_Drawing_Range](#oh_drawing_range) [OH_Drawing_Range](#oh_drawing_range) | Defines a struct for a range, which is used to receive the start position and end position of a glyph.| +| typedef struct [OH_Drawing_Range](#oh_drawing_range) [OH_Drawing_Range](#oh_drawing_range) | Defines a struct used to receive the start position and end position of a glyph.| | typedef struct [OH_Drawing_TextShadow](#oh_drawing_textshadow) [OH_Drawing_TextShadow](#oh_drawing_textshadow) | Defines a struct used to manage text shadows.| | typedef struct [OH_Drawing_FontParser](#oh_drawing_fontparser) [OH_Drawing_FontParser](#oh_drawing_fontparser) | Defines a struct used to parse system font files.| | typedef enum [OH_Drawing_PlaceholderVerticalAlignment](#oh_drawing_placeholderverticalalignment) [OH_Drawing_PlaceholderVerticalAlignment](#oh_drawing_placeholderverticalalignment) | Defines an enum for the vertical alignment modes of placeholders.| | typedef struct [OH_Drawing_PlaceholderSpan](_o_h___drawing___placeholder_span.md) [OH_Drawing_PlaceholderSpan](#oh_drawing_placeholderspan) | Defines a struct for the placeholder that acts as a span.| | typedef enum [OH_Drawing_TextDecorationStyle](#oh_drawing_textdecorationstyle) [OH_Drawing_TextDecorationStyle](#oh_drawing_textdecorationstyle) | Defines an enum for the text decoration styles.| -| typedef enum [OH_Drawing_EllipsisModal](#oh_drawing_ellipsismodal) [OH_Drawing_EllipsisModal](#oh_drawing_ellipsismodal) | Defines an enum for the text ellipsis styles.| +| typedef enum [OH_Drawing_EllipsisModal](#oh_drawing_ellipsismodal) [OH_Drawing_EllipsisModal](#oh_drawing_ellipsismodal) | Defines an enum for the ellipsis styles.| | typedef enum [OH_Drawing_BreakStrategy](#oh_drawing_breakstrategy) [OH_Drawing_BreakStrategy](#oh_drawing_breakstrategy) | Defines an enum for the text break strategies.| | typedef enum [OH_Drawing_WordBreakType](#oh_drawing_wordbreaktype) [OH_Drawing_WordBreakType](#oh_drawing_wordbreaktype) | Defines an enum for the word break types.| | typedef enum [OH_Drawing_RectHeightStyle](#oh_drawing_rectheightstyle) [OH_Drawing_RectHeightStyle](#oh_drawing_rectheightstyle) | Defines an enum for the rectangle height styles.| @@ -175,7 +176,7 @@ The Drawing module provides the functions for 2D graphics rendering, text drawin | typedef struct [OH_Drawing_ShaderEffect](#oh_drawing_shadereffect) [OH_Drawing_ShaderEffect](#oh_drawing_shadereffect) | Defines a struct for a shader effect, which is used to describe the source color of the drawn content.| | typedef struct [OH_Drawing_ShadowLayer](#oh_drawing_shadowlayer) [OH_Drawing_ShadowLayer](#oh_drawing_shadowlayer) | Defines a struct for a shadow, which is used to describe the shadow layer of the drawn content.| | typedef struct [OH_Drawing_Filter](#oh_drawing_filter) [OH_Drawing_Filter](#oh_drawing_filter) | Defines a struct for a filter, which consists of a color filter and mask filter.| -| typedef struct [OH_Drawing_MaskFilter](#oh_drawing_maskfilter) [OH_Drawing_MaskFilter](#oh_drawing_maskfilter) | Defines a struct for a mask filter, which is used to convert a mask into a new one.| +| typedef struct [OH_Drawing_MaskFilter](#oh_drawing_maskfilter) [OH_Drawing_MaskFilter](#oh_drawing_maskfilter) | Defines a struct for a mask filter.| | typedef struct [OH_Drawing_ColorFilter](#oh_drawing_colorfilter) [OH_Drawing_ColorFilter](#oh_drawing_colorfilter) | Defines a struct for a color filter, which is used to convert a color into a new one.| | typedef struct [OH_Drawing_Font](#oh_drawing_font) [OH_Drawing_Font](#oh_drawing_font) | Defines a struct for a font.| | typedef struct [OH_Drawing_MemoryStream](#oh_drawing_memorystream) [OH_Drawing_MemoryStream](#oh_drawing_memorystream) | Defines a struct for a memory stream.| @@ -188,7 +189,7 @@ The Drawing module provides the functions for 2D graphics rendering, text drawin | typedef struct [OH_Drawing_Surface](#oh_drawing_surface) [OH_Drawing_Surface](#oh_drawing_surface) | Defines a struct for a surface, which is used to manage the content drawn on the canvas.| | typedef enum [OH_Drawing_ColorFormat](#oh_drawing_colorformat) [OH_Drawing_ColorFormat](#oh_drawing_colorformat) | Defines an enum for the storage formats of bitmap pixels.| | typedef enum [OH_Drawing_AlphaFormat](#oh_drawing_alphaformat) [OH_Drawing_AlphaFormat](#oh_drawing_alphaformat) | Defines an enum for the alpha formats of bitmap pixels.| -| typedef enum [OH_Drawing_BlendMode](#oh_drawing_blendmode) [OH_Drawing_BlendMode](#oh_drawing_blendmode) | Defines an enum for the blend modes. In blend mode, each operation generates a new color from two colors (source color and target color). These operations are the same on the four channels (red, green, blue, and alpha). The operations for the alpha channel are used as examples.| +| typedef enum [OH_Drawing_BlendMode](#oh_drawing_blendmode) [OH_Drawing_BlendMode](#oh_drawing_blendmode) | Defines an enum for the blend modes. In blend mode, each operation generates a new color from two colors (source color and target color). These operations are the same for the red, green, and blue color channels (the alpha channel follows a different rule).| | typedef struct [OH_Drawing_Image_Info](_o_h___drawing___image___info.md) [OH_Drawing_Image_Info](#oh_drawing_image_info) | Defines a struct for the image information.| | typedef struct [OH_Drawing_RectStyle_Info](_o_h___drawing___rect_style___info.md) [OH_Drawing_RectStyle_Info](#oh_drawing_rectstyle_info) | Defines a struct for the style of a rectangle.| | typedef enum [OH_Drawing_TextEncoding](#oh_drawing_textencoding) [OH_Drawing_TextEncoding](#oh_drawing_textencoding) | Defines an enum for the text encoding types.| @@ -200,6 +201,7 @@ The Drawing module provides the functions for 2D graphics rendering, text drawin | Name| Description| | -------- | -------- | +| [OH_Drawing_PathDashStyle](#oh_drawing_pathdashstyle-1) { DRAWING_PATH_DASH_STYLE_TRANSLATE, DRAWING_PATH_DASH_STYLE_ROTATE, DRAWING_PATH_DASH_STYLE_MORPH } | Enumerates the drawing styles for path effects. | | [OH_Drawing_SystemFontType](#oh_drawing_systemfonttype-1) { ALL = 1 << 0, GENERIC = 1 << 1, STYLISH = 1 << 2, INSTALLED = 1 << 3, CUSTOMIZED = 1 << 4 } | Enumerates the system font types.| | [OH_Drawing_ErrorCode](#oh_drawing_errorcode-1) { OH_DRAWING_SUCCESS = 0, OH_DRAWING_ERROR_NO_PERMISSION = 201, OH_DRAWING_ERROR_INVALID_PARAMETER = 401, OH_DRAWING_ERROR_PARAMETER_OUT_OF_RANGE = 26200001,OH_DRAWING_ERROR_ALLOCATION_FAILED = 26200002 } | Enumerates the error codes that may be generated by the module.| | [OH_Drawing_PathOpMode](#oh_drawing_pathopmode-1) {
PATH_OP_MODE_DIFFERENCE, PATH_OP_MODE_INTERSECT, PATH_OP_MODE_UNION, PATH_OP_MODE_XOR,
PATH_OP_MODE_REVERSE_DIFFERENCE
} | Enumerates the operation modes available for a path.| @@ -230,9 +232,9 @@ The Drawing module provides the functions for 2D graphics rendering, text drawin | [OH_Drawing_FontStyle](#oh_drawing_fontstyle) { FONT_STYLE_NORMAL, FONT_STYLE_ITALIC, FONT_STYLE_OBLIQUE } | Enumerates the font styles.| | [OH_Drawing_PlaceholderVerticalAlignment](#oh_drawing_placeholderverticalalignment-1) {
ALIGNMENT_OFFSET_AT_BASELINE, ALIGNMENT_ABOVE_BASELINE, ALIGNMENT_BELOW_BASELINE, ALIGNMENT_TOP_OF_ROW_BOX,
ALIGNMENT_BOTTOM_OF_ROW_BOX, ALIGNMENT_CENTER_OF_ROW_BOX
} | Enumerates the vertical alignment modes of placeholders.| | [OH_Drawing_TextDecorationStyle](#oh_drawing_textdecorationstyle-1) {
TEXT_DECORATION_STYLE_SOLID, TEXT_DECORATION_STYLE_DOUBLE, TEXT_DECORATION_STYLE_DOTTED, TEXT_DECORATION_STYLE_DASHED,
TEXT_DECORATION_STYLE_WAVY
} | Enumerates the text decoration styles.| -| [OH_Drawing_EllipsisModal](#oh_drawing_ellipsismodal-1) { ELLIPSIS_MODAL_HEAD = 0, ELLIPSIS_MODAL_MIDDLE = 1, ELLIPSIS_MODAL_TAIL = 2 } | Enumerates the text ellipsis styles.| +| [OH_Drawing_EllipsisModal](#oh_drawing_ellipsismodal-1) { ELLIPSIS_MODAL_HEAD = 0, ELLIPSIS_MODAL_MIDDLE = 1, ELLIPSIS_MODAL_TAIL = 2 } | Enumerates the ellipsis styles.| | [OH_Drawing_BreakStrategy](#oh_drawing_breakstrategy-1) { BREAK_STRATEGY_GREEDY = 0, BREAK_STRATEGY_HIGH_QUALITY = 1, BREAK_STRATEGY_BALANCED = 2 } | Enumerates the text break strategies.| -| [OH_Drawing_WordBreakType](#oh_drawing_wordbreaktype-1) { WORD_BREAK_TYPE_NORMAL = 0, WORD_BREAK_TYPE_BREAK_ALL = 1, WORD_BREAK_TYPE_BREAK_WORD = 2 } | Enumerates the word break types.| +| [OH_Drawing_WordBreakType](#oh_drawing_wordbreaktype-1) { WORD_BREAK_TYPE_NORMAL = 0, WORD_BREAK_TYPE_BREAK_ALL = 1, WORD_BREAK_TYPE_BREAK_WORD = 2, WORD_BREAK_TYPE_BREAK_HYPHEN = 3 } | Enumerates the word break types.| | [OH_Drawing_RectHeightStyle](#oh_drawing_rectheightstyle-1) {
RECT_HEIGHT_STYLE_TIGHT, RECT_HEIGHT_STYLE_MAX, RECT_HEIGHT_STYLE_INCLUDELINESPACEMIDDLE, RECT_HEIGHT_STYLE_INCLUDELINESPACETOP,
RECT_HEIGHT_STYLE_INCLUDELINESPACEBOTTOM, RECT_HEIGHT_STYLE_STRUCT
} | Enumerates the rectangle height styles.| | [OH_Drawing_RectWidthStyle](#oh_drawing_rectwidthstyle-1) { RECT_WIDTH_STYLE_TIGHT, RECT_WIDTH_STYLE_MAX } | Enumerates the rectangle width styles.| | [OH_Drawing_FontConfigInfoErrorCode](#oh_drawing_fontconfiginfoerrorcode) {
SUCCESS_FONT_CONFIG_INFO = 0, ERROR_FONT_CONFIG_INFO_UNKNOWN = 1, ERROR_FONT_CONFIG_INFO_PARSE_FILE = 2, ERROR_FONT_CONFIG_INFO_ALLOC_MEMORY = 3,
ERROR_FONT_CONFIG_INFO_COPY_STRING_DATA = 4
} | Enumerates the error codes that may be used during the obtaining of system font configurations.| @@ -241,7 +243,7 @@ The Drawing module provides the functions for 2D graphics rendering, text drawin | [OH_Drawing_TextStyleType](#oh_drawing_textstyletype) {
TEXT_STYLE_NONE, TEXT_STYLE_ALL_ATTRIBUTES, TEXT_STYLE_FONT, TEXT_STYLE_FOREGROUND,
TEXT_STYLE_BACKGROUND, TEXT_STYLE_SHADOW, TEXT_STYLE_DECORATIONS, TEXT_STYLE_LETTER_SPACING,
TEXT_STYLE_WORD_SPACING
} | Enumerates the text style types.| | [OH_Drawing_ColorFormat](#oh_drawing_colorformat-1) {
COLOR_FORMAT_UNKNOWN, COLOR_FORMAT_ALPHA_8, COLOR_FORMAT_RGB_565, COLOR_FORMAT_ARGB_4444,
COLOR_FORMAT_RGBA_8888, COLOR_FORMAT_BGRA_8888
} | Enumerates the storage formats of bitmap pixels.| | [OH_Drawing_AlphaFormat](#oh_drawing_alphaformat-1) { ALPHA_FORMAT_UNKNOWN, ALPHA_FORMAT_OPAQUE, ALPHA_FORMAT_PREMUL, ALPHA_FORMAT_UNPREMUL } | Enumerates the alpha formats of bitmap pixels.| -| [OH_Drawing_BlendMode](#oh_drawing_blendmode-1) {
BLEND_MODE_CLEAR, BLEND_MODE_SRC, BLEND_MODE_DST, BLEND_MODE_SRC_OVER,
BLEND_MODE_DST_OVER, BLEND_MODE_SRC_IN, BLEND_MODE_DST_IN, BLEND_MODE_SRC_OUT,
BLEND_MODE_DST_OUT, BLEND_MODE_SRC_ATOP, BLEND_MODE_DST_ATOP, BLEND_MODE_XOR,
BLEND_MODE_PLUS, BLEND_MODE_MODULATE, BLEND_MODE_SCREEN, BLEND_MODE_OVERLAY,
BLEND_MODE_DARKEN, BLEND_MODE_LIGHTEN, BLEND_MODE_COLOR_DODGE, BLEND_MODE_COLOR_BURN,
BLEND_MODE_HARD_LIGHT, BLEND_MODE_SOFT_LIGHT, BLEND_MODE_DIFFERENCE, BLEND_MODE_EXCLUSION,
BLEND_MODE_MULTIPLY, BLEND_MODE_HUE, BLEND_MODE_SATURATION, BLEND_MODE_COLOR,
BLEND_MODE_LUMINOSITY
} | Enumerates the blend modes. In blend mode, each operation generates a new color from two colors (source color and target color). These operations are the same on the four channels (red, green, blue, and alpha). The operations for the alpha channel are used as examples.| +| [OH_Drawing_BlendMode](#oh_drawing_blendmode-1) {
BLEND_MODE_CLEAR, BLEND_MODE_SRC, BLEND_MODE_DST, BLEND_MODE_SRC_OVER,
BLEND_MODE_DST_OVER, BLEND_MODE_SRC_IN, BLEND_MODE_DST_IN, BLEND_MODE_SRC_OUT,
BLEND_MODE_DST_OUT, BLEND_MODE_SRC_ATOP, BLEND_MODE_DST_ATOP, BLEND_MODE_XOR,
BLEND_MODE_PLUS, BLEND_MODE_MODULATE, BLEND_MODE_SCREEN, BLEND_MODE_OVERLAY,
BLEND_MODE_DARKEN, BLEND_MODE_LIGHTEN, BLEND_MODE_COLOR_DODGE, BLEND_MODE_COLOR_BURN,
BLEND_MODE_HARD_LIGHT, BLEND_MODE_SOFT_LIGHT, BLEND_MODE_DIFFERENCE, BLEND_MODE_EXCLUSION,
BLEND_MODE_MULTIPLY, BLEND_MODE_HUE, BLEND_MODE_SATURATION, BLEND_MODE_COLOR,
BLEND_MODE_LUMINOSITY
} | Enumerates the blend modes. In blend mode, each operation generates a new color from two colors (source color and target color). These operations are the same for the red, green, and blue color channels (the alpha channel follows a different rule).| | [OH_Drawing_TextEncoding](#oh_drawing_textencoding-1) { TEXT_ENCODING_UTF8, TEXT_ENCODING_UTF16, TEXT_ENCODING_UTF32, TEXT_ENCODING_GLYPH_ID } | Enumerates the text encoding types.| | [OH_Drawing_CanvasShadowFlags](#oh_drawing_canvasshadowflags-1) { SHADOW_FLAGS_NONE, SHADOW_FLAGS_TRANSPARENT_OCCLUDER, SHADOW_FLAGS_GEOMETRIC_ONLY, SHADOW_FLAGS_ALL } | Enumerates the shadow flags.| @@ -249,6 +251,21 @@ The Drawing module provides the functions for 2D graphics rendering, text drawin | Name| Description| | -------- | -------- | +| [OH_Drawing_ErrorCode](#oh_drawing_errorcode) [OH_Drawing_PathGetSegment](#oh_drawing_pathgetsegment) ([OH_Drawing_Path](#oh_drawing_path) \*path, bool forceClosed, float start, float stop, bool startWithMoveTo, [OH_Drawing_Path](#oh_drawing_path) \*dst, bool \*result) | Extracts a segment of a path and appends it to a destination path. | +| [OH_Drawing_PathEffect](#oh_drawing_patheffect) \* [OH_Drawing_CreateSumPathEffect](#oh_drawing_createsumpatheffect) ([OH_Drawing_PathEffect](#oh_drawing_patheffect) \*firstPathEffect, [OH_Drawing_PathEffect](#oh_drawing_patheffect) \*secondPathEffect) | Creates an overlay path effect based on two distinct path effects that take effect separately. | +| [OH_Drawing_PathEffect](#oh_drawing_patheffect) \* [OH_Drawing_CreatePathDashEffect](#oh_drawing_createpathdasheffect) (const [OH_Drawing_Path](#oh_drawing_path) \*path, float advance, float phase, [OH_Drawing_PathDashStyle](#oh_drawing_pathdashstyle) type) | Creates a dashed path effect. | +| [OH_Drawing_PathEffect](#oh_drawing_patheffect) \* [OH_Drawing_CreateDiscretePathEffect](#oh_drawing_creatediscretepatheffect) (float segLength, float deviation) | Creates a path effect that segments the path and scatters the segments in an irregular pattern along the path. | +| [OH_Drawing_PathEffect](#oh_drawing_patheffect) \* [OH_Drawing_CreateCornerPathEffect](#oh_drawing_createcornerpatheffect) (float radius) | Creates a path effect that transforms the sharp angle between line segments into a rounded corner with the specified radius. | +| [OH_Drawing_PathEffect](#oh_drawing_patheffect) \* [OH_Drawing_CreateComposePathEffect](#oh_drawing_createcomposepatheffect) ([OH_Drawing_PathEffect](#oh_drawing_patheffect) \*outer, [OH_Drawing_PathEffect](#oh_drawing_patheffect) \*inner) | Creates a path effect by sequentially applying the inner effect and then the outer effect. | +| [OH_Drawing_GpuContext](#oh_drawing_gpucontext) \* [OH_Drawing_GpuContextCreate](#oh_drawing_gpucontextcreate) (void) | Creates an **OH_Drawing_GpuContext** object, for which the backend type depends on the device. | +| [OH_Drawing_ErrorCode](#oh_drawing_errorcode) [OH_Drawing_CanvasDrawArcWithCenter](#oh_drawing_canvasdrawarcwithcenter) ([OH_Drawing_Canvas](#oh_drawing_canvas) \*canvas, const [OH_Drawing_Rect](#oh_drawing_rect) \*rect, float startAngle, float sweepAngle, bool useCenter) | Draws an arc. It enables you to define the starting angle, sweep angle, and whether the arc's endpoints should connect to its center. | +| [OH_Drawing_ErrorCode](#oh_drawing_errorcode) [OH_Drawing_CanvasDrawNestedRoundRect](#oh_drawing_canvasdrawnestedroundrect) ([OH_Drawing_Canvas](#oh_drawing_canvas) \*canvas, const [OH_Drawing_RoundRect](#oh_drawing_roundrect) \*outer, const [OH_Drawing_RoundRect](#oh_drawing_roundrect) \*inner) | Draws two nested rounded rectangles. The outer rectangle boundary must contain the inner rectangle boundary. Otherwise, there is no drawing effect.| +| [OH_Drawing_ErrorCode](#oh_drawing_errorcode) [OH_Drawing_CanvasQuickRejectPath](#oh_drawing_canvasquickrejectpath) ([OH_Drawing_Canvas](#oh_drawing_canvas) \*canvas, const [OH_Drawing_Path](#oh_drawing_path) \*path, bool \*quickReject) | Checks whether the path is not intersecting with the canvas area. The canvas area includes its boundaries. | +| [OH_Drawing_ErrorCode](#oh_drawing_errorcode) [OH_Drawing_CanvasQuickRejectRect](#oh_drawing_canvasquickrejectrect) ([OH_Drawing_Canvas](#oh_drawing_canvas) \*canvas, const [OH_Drawing_Rect](#oh_drawing_rect) \*rect, bool \*quickReject) | Checks whether the rectangle is not intersecting with the canvas area. The canvas area includes its boundaries. | +| [OH_Drawing_ErrorCode](#oh_drawing_errorcode) [OH_Drawing_CanvasDrawPixelMapNine](#oh_drawing_canvasdrawpixelmapnine) ([OH_Drawing_Canvas](#oh_drawing_canvas) \*canvas, [OH_Drawing_PixelMap](#oh_drawing_pixelmap) \*pixelMap, const [OH_Drawing_Rect](#oh_drawing_rect) \*center, const [OH_Drawing_Rect](#oh_drawing_rect) \*dst, [OH_Drawing_FilterMode](#oh_drawing_filtermode) mode) | Splits a PixelMap into nine sections using two horizontal and two vertical lines: four edge sections, four corner sections, and a central section. If the four corner sections are smaller than the target rectangle, they will be drawn in the target rectangle without scaling. Otherwise, they will be scaled to fit the target rectangle. Any remaining space will be filled by stretching or compressing the other five sections to cover the entire target rectangle. | +| [OH_Drawing_Surface](#oh_drawing_surface) \* [OH_Drawing_SurfaceCreateOnScreen](#oh_drawing_surfacecreateonscreen) ([OH_Drawing_GpuContext](#oh_drawing_gpucontext) \*gpuContext, [OH_Drawing_Image_Info](_o_h___drawing___image___info.md) imageInfo, void \*window) | Creates an **OH_Drawing_Surface** object bound to the window using the GPU context to manage the content drawn on the canvas. | +| [OH_Drawing_ErrorCode](#oh_drawing_errorcode) [OH_Drawing_SurfaceFlush](#oh_drawing_surfaceflush) ([OH_Drawing_Surface](#oh_drawing_surface) \*surface) | Pushes the drawing content from an **OH_Drawing_Surface** object to the GPU for rendering. | +| void [OH_Drawing_ErrorCodeReset](#oh_drawing_errorcodereset) (void) | Resets the error code of this module to **OH_DRAWING_SUCCESS**.
When a function that does not return an error code fails, the error code obtained through [OH_Drawing_ErrorCodeGet](#oh_drawing_errorcodeget) is reset to the corresponding error number. However, it is not reset to **OH_DRAWING_SUCCESS** for a successful operation.
By calling this function, you can manually reset the error code to **OH_DRAWING_SUCCESS**, avoiding interference between different functions and simplifying the debugging process.| | [OH_Drawing_ErrorCode](#oh_drawing_errorcode) [OH_Drawing_FontSetThemeFontFollowed](#oh_drawing_fontsetthemefontfollowed) ([OH_Drawing_Font](#oh_drawing_font) \*font, bool followed) | Sets whether to follow the theme font. When **followed** is set to **true**, the theme font is used if it is enabled by the system and no typeface is set.| | [OH_Drawing_ErrorCode](#oh_drawing_errorcode) [OH_Drawing_FontIsThemeFontFollowed](#oh_drawing_fontisthemefontfollowed) (const [OH_Drawing_Font](#oh_drawing_font) \*font, bool \*followed) | Checks whether the font follows the theme font. By default, the theme font is not followed.| | OH_Drawing_FontCollection \* [OH_Drawing_GetFontCollectionGlobalInstance](#oh_drawing_getfontcollectionglobalinstance) (void) | Obtains the global **OH_Drawing_FontCollection** object, which can be used to sense the theme font information. Do not release the object. | @@ -281,11 +298,11 @@ The Drawing module provides the functions for 2D graphics rendering, text drawin | [OH_Drawing_Canvas](#oh_drawing_canvas) \* [OH_Drawing_CanvasCreate](#oh_drawing_canvascreate) (void) | Creates an **OH_Drawing_Canvas** object.| | void [OH_Drawing_CanvasDestroy](#oh_drawing_canvasdestroy) ([OH_Drawing_Canvas](#oh_drawing_canvas) \*) | Destroys an **OH_Drawing_Canvas** object and reclaims the memory occupied by the object.| | void [OH_Drawing_CanvasBind](#oh_drawing_canvasbind) ([OH_Drawing_Canvas](#oh_drawing_canvas) \*, [OH_Drawing_Bitmap](#oh_drawing_bitmap) \*) | Binds a bitmap to a canvas so that the content drawn on the canvas is output to the bitmap. (This process is called CPU rendering.)| -| void [OH_Drawing_CanvasAttachPen](#oh_drawing_canvasattachpen) ([OH_Drawing_Canvas](#oh_drawing_canvas) \*, const [OH_Drawing_Pen](#oh_drawing_pen) \*) | Attaches a pen to a canvas so that the canvas can use the style and color of the pen to outline a shape.| +| void [OH_Drawing_CanvasAttachPen](#oh_drawing_canvasattachpen) ([OH_Drawing_Canvas](#oh_drawing_canvas) \*, const [OH_Drawing_Pen](#oh_drawing_pen) \*) | Attaches a pen to a canvas so that the canvas can use the style and color of the pen to outline a shape. If the pen effect changes after this function is called, you must call the function again to use the new effect in the subsequent drawing.| | void [OH_Drawing_CanvasDetachPen](#oh_drawing_canvasdetachpen) ([OH_Drawing_Canvas](#oh_drawing_canvas) \*) | Detaches the pen from a canvas so that the canvas can no longer use the style and color of the pen to outline a shape.| -| void [OH_Drawing_CanvasAttachBrush](#oh_drawing_canvasattachbrush) ([OH_Drawing_Canvas](#oh_drawing_canvas) \*, const [OH_Drawing_Brush](#oh_drawing_brush) \*) | Attaches a brush to a canvas so that the canvas can use the style and color of the brush to fill in a shape.| +| void [OH_Drawing_CanvasAttachBrush](#oh_drawing_canvasattachbrush) ([OH_Drawing_Canvas](#oh_drawing_canvas) \*, const [OH_Drawing_Brush](#oh_drawing_brush) \*) | Attaches a brush to a canvas so that the canvas can use the style and color of the brush to fill in a shape. If the brush effect changes after this function is called, you must call the function again to use the new effect in the subsequent drawing.| | void [OH_Drawing_CanvasDetachBrush](#oh_drawing_canvasdetachbrush) ([OH_Drawing_Canvas](#oh_drawing_canvas) \*) | Detaches the brush from a canvas so that the canvas can no longer use the previously set brush to fill in a shape.| -| void [OH_Drawing_CanvasSave](#oh_drawing_canvassave) ([OH_Drawing_Canvas](#oh_drawing_canvas) \*) | Saves the current canvas status (canvas matrix) to the top of the stack.| +| void [OH_Drawing_CanvasSave](#oh_drawing_canvassave) ([OH_Drawing_Canvas](#oh_drawing_canvas) \*) | Saves the current canvas status (canvas matrix) to the top of the stack. This function must be used in pair with [OH_Drawing_CanvasRestore](#oh_drawing_canvasrestore).| | void [OH_Drawing_CanvasSaveLayer](#oh_drawing_canvassavelayer) ([OH_Drawing_Canvas](#oh_drawing_canvas) \*, const [OH_Drawing_Rect](#oh_drawing_rect) \*, const [OH_Drawing_Brush](#oh_drawing_brush) \*) | Saves the matrix and cropping region, and allocates a bitmap for subsequent drawing. If you call [OH_Drawing_CanvasRestore](#oh_drawing_canvasrestore), the changes made to the matrix and clipping region are discarded, and the bitmap is drawn.| | void [OH_Drawing_CanvasRestore](#oh_drawing_canvasrestore) ([OH_Drawing_Canvas](#oh_drawing_canvas) \*) | Restores the canvas status (canvas matrix) saved on the top of the stack.| | uint32_t [OH_Drawing_CanvasGetSaveCount](#oh_drawing_canvasgetsavecount) ([OH_Drawing_Canvas](#oh_drawing_canvas) \*) | Obtains the number of canvas statuses (canvas matrices) saved in the stack.| @@ -312,7 +329,7 @@ The Drawing module provides the functions for 2D graphics rendering, text drawin | void [OH_Drawing_CanvasDrawCircle](#oh_drawing_canvasdrawcircle) ([OH_Drawing_Canvas](#oh_drawing_canvas) \*, const [OH_Drawing_Point](#oh_drawing_point) \*, float radius) | Draws a circle.| | [OH_Drawing_ErrorCode](#oh_drawing_errorcode) [OH_Drawing_CanvasDrawColor](#oh_drawing_canvasdrawcolor) ([OH_Drawing_Canvas](#oh_drawing_canvas) \*canvas, uint32_t color, [OH_Drawing_BlendMode](#oh_drawing_blendmode) blendMode) | Fills the entire canvas with the specified color and blend mode.| | void [OH_Drawing_CanvasDrawOval](#oh_drawing_canvasdrawoval) ([OH_Drawing_Canvas](#oh_drawing_canvas) \*, const [OH_Drawing_Rect](#oh_drawing_rect) \*) | Draws an oval.| -| void [OH_Drawing_CanvasDrawArc](#oh_drawing_canvasdrawarc) ([OH_Drawing_Canvas](#oh_drawing_canvas) \*, const [OH_Drawing_Rect](#oh_drawing_rect) \*, float startAngle, float sweepAngle) | Draws an arc.| +| void [OH_Drawing_CanvasDrawArc](#oh_drawing_canvasdrawarc) ([OH_Drawing_Canvas](#oh_drawing_canvas) \*, const [OH_Drawing_Rect](#oh_drawing_rect) \*, float startAngle, float sweepAngle) | Draws an arc. If the absolute value of the sweep angle exceeds 360 degrees, an ellipse is drawn.| | void [OH_Drawing_CanvasDrawRoundRect](#oh_drawing_canvasdrawroundrect) ([OH_Drawing_Canvas](#oh_drawing_canvas) \*, const [OH_Drawing_RoundRect](#oh_drawing_roundrect) \*) | Draws a rounded rectangle.| | [OH_Drawing_ErrorCode](#oh_drawing_errorcode) [OH_Drawing_CanvasDrawSingleCharacter](#oh_drawing_canvasdrawsinglecharacter) ([OH_Drawing_Canvas](#oh_drawing_canvas) \*canvas, const char \*str, const [OH_Drawing_Font](#oh_drawing_font) \*font, float x, float y) | Draws a single character. If the typeface of the current font does not support the character to draw, the system typeface is used to draw the character.| | void [OH_Drawing_CanvasDrawTextBlob](#oh_drawing_canvasdrawtextblob) ([OH_Drawing_Canvas](#oh_drawing_canvas) \*, const [OH_Drawing_TextBlob](#oh_drawing_textblob) \*, float x, float y) | Draws a text blob. If the typeface used to construct **OH_Drawing_TextBlob** does not support a character, that character will not be drawn.| @@ -343,9 +360,9 @@ The Drawing module provides the functions for 2D graphics rendering, text drawin | void [OH_Drawing_FontSetSubpixel](#oh_drawing_fontsetsubpixel) ([OH_Drawing_Font](#oh_drawing_font) \*, bool isSubpixel) | Sets whether to use sub-pixel rendering for a font.| | bool [OH_Drawing_FontIsSubpixel](#oh_drawing_fontissubpixel) (const [OH_Drawing_Font](#oh_drawing_font) \*) | Checks whether sub-pixel rendering is used for a font.| | [OH_Drawing_Font](#oh_drawing_font) \* [OH_Drawing_FontCreate](#oh_drawing_fontcreate) (void) | Creates an **OH_Drawing_Font** object.| -| void [OH_Drawing_FontSetTypeface](#oh_drawing_fontsettypeface) ([OH_Drawing_Font](#oh_drawing_font) \*, [OH_Drawing_Typeface](#oh_drawing_typeface) \*) | Sets the typeface for a font.| +| void [OH_Drawing_FontSetTypeface](#oh_drawing_fontsettypeface) ([OH_Drawing_Font](#oh_drawing_font) \*, [OH_Drawing_Typeface](#oh_drawing_typeface) \*) | Sets a typeface for a font.| | [OH_Drawing_Typeface](#oh_drawing_typeface) \* [OH_Drawing_FontGetTypeface](#oh_drawing_fontgettypeface) ([OH_Drawing_Font](#oh_drawing_font) \*) | Obtains the typeface of a font.| -| void [OH_Drawing_FontSetTextSize](#oh_drawing_fontsettextsize) ([OH_Drawing_Font](#oh_drawing_font) \*, float textSize) | Sets the font size.| +| void [OH_Drawing_FontSetTextSize](#oh_drawing_fontsettextsize) ([OH_Drawing_Font](#oh_drawing_font) \*, float textSize) | Sets the text size for a font.| | float [OH_Drawing_FontGetTextSize](#oh_drawing_fontgettextsize) (const [OH_Drawing_Font](#oh_drawing_font) \*) | Obtains the text size.| | int [OH_Drawing_FontCountText](#oh_drawing_fontcounttext) ([OH_Drawing_Font](#oh_drawing_font) \*, const void \*text, size_t byteLength, [OH_Drawing_TextEncoding](#oh_drawing_textencoding) encoding) | Obtains the number of glyphs represented by text.| | uint32_t [OH_Drawing_FontTextToGlyphs](#oh_drawing_fonttexttoglyphs) (const [OH_Drawing_Font](#oh_drawing_font) \*, const void \*text, uint32_t byteLength, [OH_Drawing_TextEncoding](#oh_drawing_textencoding) encoding, uint16_t \*glyphs, int maxGlyphCount) | Converts text into glyph indices.| @@ -371,11 +388,11 @@ The Drawing module provides the functions for 2D graphics rendering, text drawin | [OH_Drawing_ErrorCode](#oh_drawing_errorcode) [OH_Drawing_FontGetTextPath](#oh_drawing_fontgettextpath) (const [OH_Drawing_Font](#oh_drawing_font) \*font, const void \*text, size_t byteLength, [OH_Drawing_TextEncoding](#oh_drawing_textencoding) encoding, float x, float y, [OH_Drawing_Path](#oh_drawing_path) \*path) | Obtains the text outline path.| | [OH_Drawing_FontCollection](#oh_drawing_fontcollection) \* [OH_Drawing_CreateFontCollection](#oh_drawing_createfontcollection) (void) | Creates an [OH_Drawing_FontCollection](#oh_drawing_fontcollection) object.| | void [OH_Drawing_DestroyFontCollection](#oh_drawing_destroyfontcollection) ([OH_Drawing_FontCollection](#oh_drawing_fontcollection) \*) | Destroys an **OH_Drawing_FontCollection** object and reclaims the memory occupied by the object.| -| void [OH_Drawing_DisableFontCollectionFallback](#oh_drawing_disablefontcollectionfallback) ([OH_Drawing_FontCollection](#oh_drawing_fontcollection) \*fontCollection) | Disables the alternate fonts.| +| void [OH_Drawing_DisableFontCollectionFallback](#oh_drawing_disablefontcollectionfallback) ([OH_Drawing_FontCollection](#oh_drawing_fontcollection) \*fontCollection) | Disables the system fonts.| | void [OH_Drawing_DisableFontCollectionSystemFont](#oh_drawing_disablefontcollectionsystemfont) ([OH_Drawing_FontCollection](#oh_drawing_fontcollection) \*fontCollection) | Disables the system fonts.| | [OH_Drawing_FontCollection](#oh_drawing_fontcollection) \* [OH_Drawing_CreateSharedFontCollection](#oh_drawing_createsharedfontcollection) (void) | Creates an [OH_Drawing_FontCollection](#oh_drawing_fontcollection) object that is shareable.| | void [OH_Drawing_ClearFontCaches](#oh_drawing_clearfontcaches) ([OH_Drawing_FontCollection](#oh_drawing_fontcollection) \*) | Clears the font cache. (The font cache has a memory limit and a clearing mechanism. It occupies limited memory. You are not advised to clear it unless otherwise required.)| -| [OH_Drawing_FontMgr](#oh_drawing_fontmgr) \* [OH_Drawing_FontMgrCreate](#oh_drawing_fontmgrcreate) (void) | Creates an **OH_Drawing_FontMgr** object.| +| [OH_Drawing_FontMgr](#oh_drawing_fontmgr) \* [OH_Drawing_FontMgrCreate](#oh_drawing_fontmgrcreate) (void) | Creates an **OH_Drawing_FontMgr** object, which can be used only to manage system fonts.| | void [OH_Drawing_FontMgrDestroy](#oh_drawing_fontmgrdestroy) ([OH_Drawing_FontMgr](#oh_drawing_fontmgr) \*) | Destroys an **OH_Drawing_FontMgr** object and reclaims the memory occupied by the object.| | int [OH_Drawing_FontMgrGetFamilyCount](#oh_drawing_fontmgrgetfamilycount) ([OH_Drawing_FontMgr](#oh_drawing_fontmgr) \*) | Obtains the number of font families.| | char \* [OH_Drawing_FontMgrGetFamilyName](#oh_drawing_fontmgrgetfamilyname) ([OH_Drawing_FontMgr](#oh_drawing_fontmgr) \*, int index) | Obtains the font family name based on an index.| @@ -384,7 +401,7 @@ The Drawing module provides the functions for 2D graphics rendering, text drawin | void [OH_Drawing_FontMgrDestroyFontStyleSet](#oh_drawing_fontmgrdestroyfontstyleset) ([OH_Drawing_FontStyleSet](#oh_drawing_fontstyleset) \*) | Reclaims the memory occupied by a font style set.| | [OH_Drawing_FontStyleSet](#oh_drawing_fontstyleset) \* [OH_Drawing_FontMgrMatchFamily](#oh_drawing_fontmgrmatchfamily) ([OH_Drawing_FontMgr](#oh_drawing_fontmgr) \*, const char \*familyName) | Obtains a font style set based on a font family name.| | [OH_Drawing_Typeface](#oh_drawing_typeface) \* [OH_Drawing_FontMgrMatchFamilyStyle](#oh_drawing_fontmgrmatchfamilystyle) ([OH_Drawing_FontMgr](#oh_drawing_fontmgr) \*, const char \*familyName, [OH_Drawing_FontStyleStruct](_o_h___drawing___font_style_struct.md)) | Obtains a typeface based on the font style information and font family name.| -| [OH_Drawing_Typeface](#oh_drawing_typeface) \* [OH_Drawing_FontMgrMatchFamilyStyleCharacter](#oh_drawing_fontmgrmatchfamilystylecharacter) ([OH_Drawing_FontMgr](#oh_drawing_fontmgr) \*, const char \*familyName, [OH_Drawing_FontStyleStruct](_o_h___drawing___font_style_struct.md), const char \*bcp47[], int bcp47Count, int32_t character) | Obtains a typeface for the specified character.| +| [OH_Drawing_Typeface](#oh_drawing_typeface) \* [OH_Drawing_FontMgrMatchFamilyStyleCharacter](#oh_drawing_fontmgrmatchfamilystylecharacter) ([OH_Drawing_FontMgr](#oh_drawing_fontmgr) \*, const char \*familyName, [OH_Drawing_FontStyleStruct](_o_h___drawing___font_style_struct.md), const char \*bcp47[], int bcp47Count, int32_t character) | Obtains a typeface for the specified character. A null pointer is returned only when no typeface corresponding to the input UTF-8 character is found in the **OH_Drawing_FontMgr** object.| | [OH_Drawing_Typeface](#oh_drawing_typeface) \* [OH_Drawing_FontStyleSetCreateTypeface](#oh_drawing_fontstylesetcreatetypeface) ([OH_Drawing_FontStyleSet](#oh_drawing_fontstyleset) \*, int index) | Creates a typeface for the specified index.| | [OH_Drawing_FontStyleStruct](_o_h___drawing___font_style_struct.md) [OH_Drawing_FontStyleSetGetStyle](#oh_drawing_fontstylesetgetstyle) ([OH_Drawing_FontStyleSet](#oh_drawing_fontstyleset) \*, int32_t index, char \*\*styleName) | Obtains the font style.| | void [OH_Drawing_FontStyleSetFreeStyleName](#oh_drawing_fontstylesetfreestylename) (char \*\*styleName) | Reclaims the memory occupied by a font style.| @@ -401,7 +418,7 @@ The Drawing module provides the functions for 2D graphics rendering, text drawin | [OH_Drawing_ImageFilter](#oh_drawing_imagefilter) \* [OH_Drawing_ImageFilterCreateBlur](#oh_drawing_imagefiltercreateblur) (float sigmaX, float sigmaY, [OH_Drawing_TileMode](#oh_drawing_tilemode), [OH_Drawing_ImageFilter](#oh_drawing_imagefilter) \*input) | Creates an **OH_Drawing_ImageFilter** object with a given blur type.| | [OH_Drawing_ImageFilter](#oh_drawing_imagefilter) \* [OH_Drawing_ImageFilterCreateFromColorFilter](#oh_drawing_imagefiltercreatefromcolorfilter) ([OH_Drawing_ColorFilter](#oh_drawing_colorfilter) \*colorFilter, [OH_Drawing_ImageFilter](#oh_drawing_imagefilter) \*input) | Creates an **OH_Drawing_ImageFilter** object with a color filter effect.| | void [OH_Drawing_ImageFilterDestroy](#oh_drawing_imagefilterdestroy) ([OH_Drawing_ImageFilter](#oh_drawing_imagefilter) \*) | Destroys an **OH_Drawing_ImageFilter** object and reclaims the memory occupied by the object.| -| [OH_Drawing_MaskFilter](#oh_drawing_maskfilter) \* [OH_Drawing_MaskFilterCreateBlur](#oh_drawing_maskfiltercreateblur) ([OH_Drawing_BlurType](#oh_drawing_blurtype) blurType, float sigma, bool respectCTM) | Creates an **OH_Drawing_MaskFilter** object with a given blur type.| +| [OH_Drawing_MaskFilter](#oh_drawing_maskfilter) \* [OH_Drawing_MaskFilterCreateBlur](#oh_drawing_maskfiltercreateblur) ([OH_Drawing_BlurType](#oh_drawing_blurtype) blurType, float sigma, bool respectCTM) | Creates an **OH_Drawing_MaskFilter** object with a blur type.| | void [OH_Drawing_MaskFilterDestroy](#oh_drawing_maskfilterdestroy) ([OH_Drawing_MaskFilter](#oh_drawing_maskfilter) \*) | Destroys an **OH_Drawing_MaskFilter** object and reclaims the memory occupied by the object.| | [OH_Drawing_Matrix](#oh_drawing_matrix) \* [OH_Drawing_MatrixCreate](#oh_drawing_matrixcreate) (void) | Creates an **OH_Drawing_Matrix** object.| | [OH_Drawing_Matrix](#oh_drawing_matrix) \* [OH_Drawing_MatrixCreateRotation](#oh_drawing_matrixcreaterotation) (float deg, float x, float y) | Creates an **OH_Drawing_Matrix** with the rotation attribute. The matrix is obtained by rotating an identity matrix by a given degree around the rotation point (x, y).| @@ -409,13 +426,13 @@ The Drawing module provides the functions for 2D graphics rendering, text drawin | [OH_Drawing_Matrix](#oh_drawing_matrix) \* [OH_Drawing_MatrixCreateTranslation](#oh_drawing_matrixcreatetranslation) (float dx, float dy) | Creates an **OH_Drawing_Matrix** with the translation attribute. The matrix is obtained by translating the identity matrix by the distance (dx, dy).| | void [OH_Drawing_MatrixSetMatrix](#oh_drawing_matrixsetmatrix) ([OH_Drawing_Matrix](#oh_drawing_matrix) \*, float scaleX, float skewX, float transX, float skewY, float scaleY, float transY, float persp0, float persp1, float persp2) | Sets matrix parameters for an **OH_Drawing_Matrix** object.| | bool [OH_Drawing_MatrixSetRectToRect](#oh_drawing_matrixsetrecttorect) ([OH_Drawing_Matrix](#oh_drawing_matrix) \*, const [OH_Drawing_Rect](#oh_drawing_rect) \*src, const [OH_Drawing_Rect](#oh_drawing_rect) \*dst, [OH_Drawing_ScaleToFit](#oh_drawing_scaletofit) stf) | Scales a matrix to map a source rectangle to a destination rectangle.| -| void [OH_Drawing_MatrixPreRotate](#oh_drawing_matrixprerotate) ([OH_Drawing_Matrix](#oh_drawing_matrix) \*, float degree, float px, float py) | Premultiplies a matrix by an identity matrix that rotates by a given degree around the rotation point (px, py). | -| void [OH_Drawing_MatrixPreScale](#oh_drawing_matrixprescale) ([OH_Drawing_Matrix](#oh_drawing_matrix) \*, float sx, float sy, float px, float py) | Premultiplies a matrix by an identity matrix that scales with the factor (sx, sy) at the scale point (px, py). | -| void [OH_Drawing_MatrixPreTranslate](#oh_drawing_matrixpretranslate) ([OH_Drawing_Matrix](#oh_drawing_matrix) \*, float dx, float dy) | Premultiplies a matrix by an identity matrix that translates by a given distance (dx, dy). | -| void [OH_Drawing_MatrixPostRotate](#oh_drawing_matrixpostrotate) ([OH_Drawing_Matrix](#oh_drawing_matrix) \*, float degree, float px, float py) | Post multiplies a matrix by an identity matrix that rotates a given degree around the rotation point (px, py). | -| void [OH_Drawing_MatrixPostScale](#oh_drawing_matrixpostscale) ([OH_Drawing_Matrix](#oh_drawing_matrix) \*, float sx, float sy, float px, float py) | Post multiplies a matrix by an identity matrix that scales with the factor (sx, sy) at the scale point (px, py). | -| void [OH_Drawing_MatrixPostTranslate](#oh_drawing_matrixposttranslate) ([OH_Drawing_Matrix](#oh_drawing_matrix) \*, float dx, float dy) | Post multiplies a matrix by an identity matrix that translates by a given distance (dx, dy). | -| void [OH_Drawing_MatrixReset](#oh_drawing_matrixreset) ([OH_Drawing_Matrix](#oh_drawing_matrix) \*) | Resets a matrix to an identity matrix: \| 1 0 0 \| \| 0 1 0 \| \| 0 0 1 \| | +| void [OH_Drawing_MatrixPreRotate](#oh_drawing_matrixprerotate) ([OH_Drawing_Matrix](#oh_drawing_matrix) \*, float degree, float px, float py) | Premultiplies a matrix by an identity matrix that rotates by a given degree around the rotation point (px, py).| +| void [OH_Drawing_MatrixPreScale](#oh_drawing_matrixprescale) ([OH_Drawing_Matrix](#oh_drawing_matrix) \*, float sx, float sy, float px, float py) | Premultiplies a matrix by an identity matrix that scales with the factor (sx, sy) at the scale point (px, py).| +| void [OH_Drawing_MatrixPreTranslate](#oh_drawing_matrixpretranslate) ([OH_Drawing_Matrix](#oh_drawing_matrix) \*, float dx, float dy) | Premultiplies a matrix by an identity matrix that translates by a given distance (dx, dy).| +| void [OH_Drawing_MatrixPostRotate](#oh_drawing_matrixpostrotate) ([OH_Drawing_Matrix](#oh_drawing_matrix) \*, float degree, float px, float py) | Post multiplies a matrix by an identity matrix that rotates a given degree around the rotation point (px, py).| +| void [OH_Drawing_MatrixPostScale](#oh_drawing_matrixpostscale) ([OH_Drawing_Matrix](#oh_drawing_matrix) \*, float sx, float sy, float px, float py) | Post multiplies a matrix by an identity matrix that scales with the factor (sx, sy) at the scale point (px, py).| +| void [OH_Drawing_MatrixPostTranslate](#oh_drawing_matrixposttranslate) ([OH_Drawing_Matrix](#oh_drawing_matrix) \*, float dx, float dy) | Post multiplies a matrix by an identity matrix that translates by a given distance (dx, dy).| +| void [OH_Drawing_MatrixReset](#oh_drawing_matrixreset) ([OH_Drawing_Matrix](#oh_drawing_matrix) \*) | Resets a matrix to an identity matrix.| | void [OH_Drawing_MatrixConcat](#oh_drawing_matrixconcat) ([OH_Drawing_Matrix](#oh_drawing_matrix) \*total, const [OH_Drawing_Matrix](#oh_drawing_matrix) \*a, const [OH_Drawing_Matrix](#oh_drawing_matrix) \*b) | Multiplies two matrices to produce a new matrix. For example, if a given matrix a and a given matrix b are shown as follows:\| A B C \| \| J K L \| a = \| D E F \|, b = \| M N O \| \| G H I \| \| P Q R \| then the final matrix total is as follows:\| A B C \| \| J K L \| \| AJ+BM+CP AK+BN+CQ AL+BO+CR \| total = a \* b = \| D E F \| \* \| M N O \| = \| DJ+EM+FP DK+EN+FQ DL+EO+FR \| \| G H I \| \| P Q R \| \| GJ+HM+IP GK+HN+IQ GL+HO+IR \| | | [OH_Drawing_ErrorCode](#oh_drawing_errorcode) [OH_Drawing_MatrixGetAll](#oh_drawing_matrixgetall) ([OH_Drawing_Matrix](#oh_drawing_matrix) \*matrix, float value[9]) | Obtains all element values of a matrix.| | float [OH_Drawing_MatrixGetValue](#oh_drawing_matrixgetvalue) ([OH_Drawing_Matrix](#oh_drawing_matrix) \*, int index) | Obtains a matrix value of a given index, which ranges from 0 to 8.| @@ -427,7 +444,7 @@ The Drawing module provides the functions for 2D graphics rendering, text drawin | void [OH_Drawing_MatrixMapPoints](#oh_drawing_matrixmappoints) (const [OH_Drawing_Matrix](#oh_drawing_matrix) \*, const [OH_Drawing_Point2D](_o_h___drawing___point2_d.md) \*src, [OH_Drawing_Point2D](_o_h___drawing___point2_d.md) \*dst, int count) | Maps a source point array to a destination point array by means of matrix transformation.| | bool [OH_Drawing_MatrixMapRect](#oh_drawing_matrixmaprect) (const [OH_Drawing_Matrix](#oh_drawing_matrix) \*, const [OH_Drawing_Rect](#oh_drawing_rect) \*src, [OH_Drawing_Rect](#oh_drawing_rect) \*dst) | Maps a rectangle to the smallest rectangle that can enclose the vertices to which the four source vertices are mapped by means of matrix transformation.| | bool [OH_Drawing_MatrixIsEqual](#oh_drawing_matrixisequal) ([OH_Drawing_Matrix](#oh_drawing_matrix) \*, [OH_Drawing_Matrix](#oh_drawing_matrix) \*other) | Checks whether two **OH_Drawing_Matrix** objects are equal.| -| bool [OH_Drawing_MatrixIsIdentity](#oh_drawing_matrixisidentity) ([OH_Drawing_Matrix](#oh_drawing_matrix) \*) | Checks whether an **OH_Drawing_Matrix** object is an identity matrix: \| 1 0 0 \| \| 0 1 0 \| \| 0 0 1 \| | +| bool [OH_Drawing_MatrixIsIdentity](#oh_drawing_matrixisidentity) ([OH_Drawing_Matrix](#oh_drawing_matrix) \*) | Checks whether an **OH_Drawing_Matrix** object is an identity matrix.| | void [OH_Drawing_MatrixDestroy](#oh_drawing_matrixdestroy) ([OH_Drawing_Matrix](#oh_drawing_matrix) \*) | Destroys an **OH_Drawing_Matrix** object and reclaims the memory occupied by the object.| | [OH_Drawing_MemoryStream](#oh_drawing_memorystream) \* [OH_Drawing_MemoryStreamCreate](#oh_drawing_memorystreamcreate) (const void \*data, size_t length, bool copyData) | Creates an **OH_Drawing_MemoryStream** object.| | void [OH_Drawing_MemoryStreamDestroy](#oh_drawing_memorystreamdestroy) ([OH_Drawing_MemoryStream](#oh_drawing_memorystream) \*) | Destroys an **OH_Drawing_MemoryStream** object and reclaims the memory occupied by the object.| @@ -445,9 +462,9 @@ The Drawing module provides the functions for 2D graphics rendering, text drawin | void [OH_Drawing_PathRQuadTo](#oh_drawing_pathrquadto) ([OH_Drawing_Path](#oh_drawing_path) \*, float ctrlX, float ctrlY, float endX, float endY) | Draws a quadratic Bezier curve from the last point of a path to a point relative to the last point. If the path is empty, the start point (0, 0) is used.| | void [OH_Drawing_PathRConicTo](#oh_drawing_pathrconicto) ([OH_Drawing_Path](#oh_drawing_path) \*, float ctrlX, float ctrlY, float endX, float endY, float weight) | Draws a conic curve from the last point of a path to a point relative to the last point. If the path is empty, the start point (0, 0) is used.| | void [OH_Drawing_PathRCubicTo](#oh_drawing_pathrcubicto) ([OH_Drawing_Path](#oh_drawing_path) \*, float ctrlX1, float ctrlY1, float ctrlX2, float ctrlY2, float endX, float endY) | Draws a cubic Bezier curve from the last point of a path to a point relative to the last point. If the path is empty, the start point (0, 0) is used.| -| void [OH_Drawing_PathAddRect](#oh_drawing_pathaddrect) ([OH_Drawing_Path](#oh_drawing_path) \*, float left, float top, float right, float bottom, [OH_Drawing_PathDirection](#oh_drawing_pathdirection)) | Adds a rectangle contour to a path in the specified direction.| +| void [OH_Drawing_PathAddRect](#oh_drawing_pathaddrect) ([OH_Drawing_Path](#oh_drawing_path) \*, float left, float top, float right, float bottom, [OH_Drawing_PathDirection](#oh_drawing_pathdirection)) | Adds a rectangle to a path in the specified direction. The start point is the upper left corner of the rectangle.| | void [OH_Drawing_PathAddRectWithInitialCorner](#oh_drawing_pathaddrectwithinitialcorner) ([OH_Drawing_Path](#oh_drawing_path) \*, const [OH_Drawing_Rect](#oh_drawing_rect) \*, [OH_Drawing_PathDirection](#oh_drawing_pathdirection), uint32_t start) | Adds a rectangle contour to a path in the specified direction.| -| void [OH_Drawing_PathAddRoundRect](#oh_drawing_pathaddroundrect) ([OH_Drawing_Path](#oh_drawing_path) \*, const [OH_Drawing_RoundRect](#oh_drawing_roundrect) \*roundRect, [OH_Drawing_PathDirection](#oh_drawing_pathdirection)) | Adds a rounded rectangle to a path in the specified direction.| +| void [OH_Drawing_PathAddRoundRect](#oh_drawing_pathaddroundrect) ([OH_Drawing_Path](#oh_drawing_path) \*, const [OH_Drawing_RoundRect](#oh_drawing_roundrect) \*roundRect, [OH_Drawing_PathDirection](#oh_drawing_pathdirection)) | Adds a rounded rectangle to a path in the specified direction. When the path direction is clockwise, the start point is at the intersection of the rounded rectangle's left boundary and its lower left corner. When the path direction is counterclockwise, the start point is at the intersection point between the left boundary and the upper left corner.| | void [OH_Drawing_PathAddOvalWithInitialPoint](#oh_drawing_pathaddovalwithinitialpoint) ([OH_Drawing_Path](#oh_drawing_path) \*, const [OH_Drawing_Rect](#oh_drawing_rect) \*, uint32_t start, [OH_Drawing_PathDirection](#oh_drawing_pathdirection)) | Adds an oval to a path. **OH_Drawing_Rect** specifies the outer tangent rectangle of the oval, and **OH_Drawing_PathDirection** specifies whether the drawing is clockwise or anticlockwise.| | void [OH_Drawing_PathAddArc](#oh_drawing_pathaddarc) ([OH_Drawing_Path](#oh_drawing_path) \*, const [OH_Drawing_Rect](#oh_drawing_rect) \*, float startAngle, float sweepAngle) | Adds an arc to a path as the start of a new contour. The arc added is part of the inscribed ellipse of the rectangle, from the start angle through the sweep angle. If the sweep angle is less than or equal to -360°, or if the sweep angle is greater than or equal to 360°, and start angle modulo 90 is nearly zero, an oval instead of an ellipse is added.| | void [OH_Drawing_PathAddPath](#oh_drawing_pathaddpath) ([OH_Drawing_Path](#oh_drawing_path) \*, const [OH_Drawing_Path](#oh_drawing_path) \*src, const [OH_Drawing_Matrix](#oh_drawing_matrix) \*) | Transforms the points in a **src** path by a matrix and adds the new one to the current path.| @@ -461,7 +478,7 @@ The Drawing module provides the functions for 2D graphics rendering, text drawin | bool [OH_Drawing_PathContains](#oh_drawing_pathcontains) ([OH_Drawing_Path](#oh_drawing_path) \*, float x, float y) | Checks whether a coordinate point is included in this path. For details, see [OH_Drawing_PathFillType](#oh_drawing_pathfilltype).| | void [OH_Drawing_PathTransform](#oh_drawing_pathtransform) ([OH_Drawing_Path](#oh_drawing_path) \*, const [OH_Drawing_Matrix](#oh_drawing_matrix) \*) | Transforms the points in a path by a matrix.| | void [OH_Drawing_PathTransformWithPerspectiveClip](#oh_drawing_pathtransformwithperspectiveclip) ([OH_Drawing_Path](#oh_drawing_path) \*src, const [OH_Drawing_Matrix](#oh_drawing_matrix) \*, [OH_Drawing_Path](#oh_drawing_path) \*dst, bool applyPerspectiveClip) | Transforms the points in a **src** path by a matrix and uses the new one to replace the **dst** path. If **dst** is NULL, the **src** path is replaced.| -| void [OH_Drawing_PathSetFillType](#oh_drawing_pathsetfilltype) ([OH_Drawing_Path](#oh_drawing_path) \*, [OH_Drawing_PathFillType](#oh_drawing_pathfilltype)) | Sets the fill type for a path.| +| void [OH_Drawing_PathSetFillType](#oh_drawing_pathsetfilltype) ([OH_Drawing_Path](#oh_drawing_path) \*, [OH_Drawing_PathFillType](#oh_drawing_pathfilltype)) | Sets the fill type for a path. The fill type determines how "inside" of the path is drawn.| | float [OH_Drawing_PathGetLength](#oh_drawing_pathgetlength) ([OH_Drawing_Path](#oh_drawing_path) \*, bool forceClosed) | Obtains the length of a path.| | void [OH_Drawing_PathGetBounds](#oh_drawing_pathgetbounds) ([OH_Drawing_Path](#oh_drawing_path) \*, [OH_Drawing_Rect](#oh_drawing_rect) \*) | Obtains the minimum bounds that enclose a path.| | void [OH_Drawing_PathClose](#oh_drawing_pathclose) ([OH_Drawing_Path](#oh_drawing_path) \*) | Closes a path by drawing a line segment from the current point to the start point of the path.| @@ -526,7 +543,7 @@ The Drawing module provides the functions for 2D graphics rendering, text drawin | void [OH_Drawing_RectSetBottom](#oh_drawing_rectsetbottom) ([OH_Drawing_Rect](#oh_drawing_rect) \*rect, float bottom) | Sets the vertical coordinate of the lower right corner of a rectangle.| | void [OH_Drawing_RectCopy](#oh_drawing_rectcopy) ([OH_Drawing_Rect](#oh_drawing_rect) \*sRect, [OH_Drawing_Rect](#oh_drawing_rect) \*dRect) | Copies a source rectangle to create a new one.| | void [OH_Drawing_RectDestroy](#oh_drawing_rectdestroy) ([OH_Drawing_Rect](#oh_drawing_rect) \*) | Destroys an **OH_Drawing_Rect** object and reclaims the memory occupied by the object.| -| [OH_Drawing_Array](#oh_drawing_array) \* [OH_Drawing_RectCreateArray](#oh_drawing_rectcreatearray) (size_t size) | Creates a rectangle array object to store multiple rectangle objects.| +| [OH_Drawing_Array](#oh_drawing_array) \* [OH_Drawing_RectCreateArray](#oh_drawing_rectcreatearray) (size_t size) | Creates a rectangle array object to store multiple rectangle objects. When [OH_Drawing_Array](#oh_drawing_array) is no longer required, call [OH_Drawing_RectDestroyArray](#oh_drawing_rectdestroyarray) to release the pointer to the object.| | [OH_Drawing_ErrorCode](#oh_drawing_errorcode) [OH_Drawing_RectGetArraySize](#oh_drawing_rectgetarraysize) ([OH_Drawing_Array](#oh_drawing_array) \*rectArray, size_t \*pSize) | Obtains the size of a rectangle array, which is an [OH_Drawing_Array](#oh_drawing_array) object.| | [OH_Drawing_ErrorCode](#oh_drawing_errorcode) [OH_Drawing_RectGetArrayElement](#oh_drawing_rectgetarrayelement) ([OH_Drawing_Array](#oh_drawing_array) \*rectArray, size_t index, [OH_Drawing_Rect](#oh_drawing_rect) \*\*rect) | Obtains the rectangle with the specified index in a rectangle array.| | [OH_Drawing_ErrorCode](#oh_drawing_errorcode) [OH_Drawing_RectDestroyArray](#oh_drawing_rectdestroyarray) ([OH_Drawing_Array](#oh_drawing_array) \*rectArray) | Destroys an **OH_Drawing_Array** object and reclaims the memory occupied by the object.| @@ -569,13 +586,13 @@ The Drawing module provides the functions for 2D graphics rendering, text drawin | [OH_Drawing_TextBlob](#oh_drawing_textblob) \* [OH_Drawing_TextBlobBuilderMake](#oh_drawing_textblobbuildermake) ([OH_Drawing_TextBlobBuilder](#oh_drawing_textblobbuilder) \*) | Makes an **OH_Drawing_TextBlob** object from an **OH_Drawing_TextBlobBuilder**.| | void [OH_Drawing_TextBlobDestroy](#oh_drawing_textblobdestroy) ([OH_Drawing_TextBlob](#oh_drawing_textblob) \*) | Destroys an **OH_Drawing_TextBlob** object and reclaims the memory occupied by the object.| | void [OH_Drawing_TextBlobBuilderDestroy](#oh_drawing_textblobbuilderdestroy) ([OH_Drawing_TextBlobBuilder](#oh_drawing_textblobbuilder) \*) | Destroys an **OH_Drawing_TextBlobBuilder** object and reclaims the memory occupied by the object.| -| [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) \* [OH_Drawing_MatchFontDescriptors](#oh_drawing_matchfontdescriptors) ([OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) \*, size_t \*) | Obtains all system font descriptors that match a font descriptor. In the [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) struct, the **path** field is not used for matching, and other fields are valid only when they are not set to their default values. If all fields in [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) are set to their default values, all system font descriptors are returned. If no matching is found, NULL is returned.| +| [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) \* [OH_Drawing_MatchFontDescriptors](#oh_drawing_matchfontdescriptors) ([OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) \*, size_t \*) | Obtains all system font descriptors that match a font descriptor. In the [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) struct, the **path** field is not used for matching, and other fields are valid only when they are not set to their default values. If all fields in [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) are set to their default values, all system font descriptors are returned. If no matching is found, NULL is returned. When [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) is no longer required, call [OH_Drawing_DestroyFontDescriptors](_drawing.md#oh_drawing_destroyfontdescriptors) to release the pointer to the object.| | void [OH_Drawing_DestroyFontDescriptors](#oh_drawing_destroyfontdescriptors) ([OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) \*, size_t) | Releases an array of [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) objects.| | [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) \* [OH_Drawing_GetFontDescriptorByFullName](#oh_drawing_getfontdescriptorbyfullname) (const [OH_Drawing_String](_o_h___drawing___string.md) \*, [OH_Drawing_SystemFontType](#oh_drawing_systemfonttype)) | Obtains a font descriptor based on the font name and type. System fonts, style fonts, and user-installed fonts are supported. A font descriptor is a data structure that describes font features. It contains details of the font appearance and properties.| | [OH_Drawing_Array](#oh_drawing_array) \* [OH_Drawing_GetSystemFontFullNamesByType](#oh_drawing_getsystemfontfullnamesbytype) ([OH_Drawing_SystemFontType](#oh_drawing_systemfonttype)) | Obtains an array of font names by font type.| | const [OH_Drawing_String](_o_h___drawing___string.md) \* [OH_Drawing_GetSystemFontFullNameByIndex](#oh_drawing_getsystemfontfullnamebyindex) ([OH_Drawing_Array](#oh_drawing_array) \*, size_t) | Obtains the font name with the specified index in the font name array.| | void [OH_Drawing_DestroySystemFontFullNames](#oh_drawing_destroysystemfontfullnames) ([OH_Drawing_Array](#oh_drawing_array) \*) | Releases the memory occupied by the font name array obtained by font type.| -| [OH_Drawing_Array](#oh_drawing_array) \* [OH_Drawing_TypographyGetTextLines](#oh_drawing_typographygettextlines) ([OH_Drawing_Typography](#oh_drawing_typography) \*typography) | Obtains the array of text lines in a typography object. This array contains one or more text line objects.| +| [OH_Drawing_Array](#oh_drawing_array) \* [OH_Drawing_TypographyGetTextLines](#oh_drawing_typographygettextlines) ([OH_Drawing_Typography](#oh_drawing_typography) \*typography) | Obtains the array of text lines in a typography object. This array contains one or more text line objects. When [OH_Drawing_Array](#oh_drawing_array) is no longer required, call [OH_Drawing_DestroyTextLines](#oh_drawing_destroytextlines) to release the pointer to the object.| | void [OH_Drawing_DestroyTextLines](#oh_drawing_destroytextlines) ([OH_Drawing_Array](#oh_drawing_array) \*lines) | Releases the memory occupied by a text line array.| | void [OH_Drawing_DestroyTextLine](#oh_drawing_destroytextline) (OH_Drawing_TextLine \*line) | Releases the memory occupied by a text line object. This is applicable only to text line objects that have requested memory on their own and not to a particular text line object within a text line array.| | OH_Drawing_TextLine \* [OH_Drawing_GetTextLineByIndex](#oh_drawing_gettextlinebyindex) ([OH_Drawing_Array](#oh_drawing_array) \*lines, size_t index) | Obtains the text line object with the specified index in a text line array.| @@ -593,7 +610,7 @@ The Drawing module provides the functions for 2D graphics rendering, text drawin | double [OH_Drawing_TextLineGetOffsetForStringIndex](#oh_drawing_textlinegetoffsetforstringindex) (OH_Drawing_TextLine \*line, int32_t index) | Obtains the offset of a string with the specified index in a text line object.| | void [OH_Drawing_TextLineEnumerateCaretOffsets](#oh_drawing_textlineenumeratecaretoffsets) (OH_Drawing_TextLine \*line, [Drawing_CaretOffsetsCallback](#drawing_caretoffsetscallback) callback) | Enumerates the offset and index of each character in a text line object and passes them to a custom callback function. You can use the offset and index array for other operations.| | double [OH_Drawing_TextLineGetAlignmentOffset](#oh_drawing_textlinegetalignmentoffset) (OH_Drawing_TextLine \*line, double alignmentFactor, double alignmentWidth) | Obtains the offset of a text line object after alignment based on the alignment factor and alignment width.| -| [OH_Drawing_Array](#oh_drawing_array) \* [OH_Drawing_GetRunStringIndices](#oh_drawing_getrunstringindices) (OH_Drawing_Run \*run, int64_t start, int64_t length) | Obtains character indices of glyphs within a specified range of a run, where the indices are offsets relative to the entire paragraph.| +| [OH_Drawing_Array](#oh_drawing_array) \* [OH_Drawing_GetRunStringIndices](#oh_drawing_getrunstringindices) (OH_Drawing_Run \*run, int64_t start, int64_t length) | Obtains an array of character indices of glyphs within a specified range of a run, where the indices are offsets relative to the entire paragraph.| | uint64_t [OH_Drawing_GetRunStringIndicesByIndex](#oh_drawing_getrunstringindicesbyindex) ([OH_Drawing_Array](#oh_drawing_array) \*stringIndices, size_t index) | Obtains character indices of glyphs in a run by index.| | void [OH_Drawing_DestroyRunStringIndices](#oh_drawing_destroyrunstringindices) ([OH_Drawing_Array](#oh_drawing_array) \*stringIndices) | Releases the pointer to a character index array.| | void [OH_Drawing_GetRunStringRange](#oh_drawing_getrunstringrange) (OH_Drawing_Run \*run, uint64_t \*location, uint64_t \*length) | Obtains the range of glyphs generated by a run.| @@ -608,20 +625,20 @@ The Drawing module provides the functions for 2D graphics rendering, text drawin | [OH_Drawing_Point](#oh_drawing_point) \* [OH_Drawing_GetRunPositionsByIndex](#oh_drawing_getrunpositionsbyindex) ([OH_Drawing_Array](#oh_drawing_array) \*positions, size_t index) | Obtains the positions of individual glyphs in a run by index.| | void [OH_Drawing_DestroyRunPositions](#oh_drawing_destroyrunpositions) ([OH_Drawing_Array](#oh_drawing_array) \*positions) | Releases the pointer to a glyph position array in a run.| | uint32_t [OH_Drawing_GetRunGlyphCount](#oh_drawing_getrunglyphcount) (OH_Drawing_Run \*run) | Obtains the number of glyphs in a run.| -| [OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \* [OH_Drawing_CreateTypographyStyle](#oh_drawing_createtypographystyle) (void) | Creates an **OH_Drawing_TypographyStyle** object.| +| [OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \* [OH_Drawing_CreateTypographyStyle](#oh_drawing_createtypographystyle) (void) | Creates an **OH_Drawing_TypographyStyle** object. When [OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) is no longer required, call [OH_Drawing_DestroyTypographyStyle](#oh_drawing_destroytypographystyle) to release the pointer to the object.| | void [OH_Drawing_DestroyTypographyStyle](#oh_drawing_destroytypographystyle) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*) | Destroys an **OH_Drawing_TypographyStyle** object and reclaims the memory occupied by the object.| -| void [OH_Drawing_SetTypographyTextDirection](#oh_drawing_settypographytextdirection) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*, int) | Sets the text direction.| +| void [OH_Drawing_SetTypographyTextDirection](#oh_drawing_settypographytextdirection) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*, int) | Sets the text direction in a typography style.| | void [OH_Drawing_SetTypographyTextAlign](#oh_drawing_settypographytextalign) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*, int) | Sets the text alignment mode.| | int [OH_Drawing_TypographyGetEffectiveAlignment](#oh_drawing_typographygeteffectivealignment) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*style) | Obtains the text alignment mode.| | void [OH_Drawing_SetTypographyTextMaxLines](#oh_drawing_settypographytextmaxlines) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*, int) | Sets the maximum number of lines in the text.| | [OH_Drawing_TextStyle](#oh_drawing_textstyle) \* [OH_Drawing_CreateTextStyle](#oh_drawing_createtextstyle) (void) | Creates an **OH_Drawing_TextStyle** object.| -| [OH_Drawing_TextStyle](#oh_drawing_textstyle) \* [OH_Drawing_TypographyGetTextStyle](#oh_drawing_typographygettextstyle) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*style) | Obtains the text style of a typography style.| +| [OH_Drawing_TextStyle](#oh_drawing_textstyle) \* [OH_Drawing_TypographyGetTextStyle](#oh_drawing_typographygettextstyle) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*style) | Obtains the default text style of a typography style.| | void [OH_Drawing_DestroyTextStyle](#oh_drawing_destroytextstyle) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*) | Destroys an **OH_Drawing_TextStyle** object and reclaims the memory occupied by the object.| | void [OH_Drawing_SetTextStyleColor](#oh_drawing_settextstylecolor) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*, uint32_t) | Sets the color for a text style.| | void [OH_Drawing_SetTextStyleFontSize](#oh_drawing_settextstylefontsize) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*, double) | Sets the font size for a text style.| | void [OH_Drawing_SetTextStyleFontWeight](#oh_drawing_settextstylefontweight) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*, int) | Sets the font weight for a text style. Currently, only the default system font supports font weight adjustment. For other fonts, if the weight is less than semi-bold, there is no variation in stroke thickness. If the weight is greater than or equal to semi-bold, it might result in a fake bold effect.| | void [OH_Drawing_SetTextStyleBaseLine](#oh_drawing_settextstylebaseline) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*, int) | Sets the baseline for a text style.| -| void [OH_Drawing_SetTextStyleDecoration](#oh_drawing_settextstyledecoration) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*, int) | Sets the decoration for a text style.| +| void [OH_Drawing_SetTextStyleDecoration](#oh_drawing_settextstyledecoration) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*, int) | Sets the decoration for a text style. Only one decoration can be set. To add multiple decorations, use [OH_Drawing_AddTextStyleDecoration](#oh_drawing_addtextstyledecoration).| | void [OH_Drawing_AddTextStyleDecoration](#oh_drawing_addtextstyledecoration) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*, int) | Adds the decoration for a text style. Multiple decoration lines can be displayed.| | void [OH_Drawing_RemoveTextStyleDecoration](#oh_drawing_removetextstyledecoration) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*, int) | Removes the decoration for a text style.| | void [OH_Drawing_SetTextStyleDecorationColor](#oh_drawing_settextstyledecorationcolor) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*, uint32_t) | Sets the decoration color for a text style.| @@ -637,28 +654,28 @@ The Drawing module provides the functions for 2D graphics rendering, text drawin | void [OH_Drawing_TextStyleGetBackgroundBrush](#oh_drawing_textstylegetbackgroundbrush) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*, [OH_Drawing_Brush](#oh_drawing_brush) \*) | Obtains the background brush of a text style.| | void [OH_Drawing_SetTextStyleBackgroundPen](#oh_drawing_settextstylebackgroundpen) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*, [OH_Drawing_Pen](#oh_drawing_pen) \*) | Sets the background pen for a text style.| | void [OH_Drawing_TextStyleGetBackgroundPen](#oh_drawing_textstylegetbackgroundpen) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*, [OH_Drawing_Pen](#oh_drawing_pen) \*) | Obtains the background pen of a text style.| -| [OH_Drawing_TypographyCreate](#oh_drawing_typographycreate) \* [OH_Drawing_CreateTypographyHandler](#oh_drawing_createtypographyhandler) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*, [OH_Drawing_FontCollection](#oh_drawing_fontcollection) \*) | Creates an **OH_Drawing_TypographyCreate** object.| +| [OH_Drawing_TypographyCreate](#oh_drawing_typographycreate) \* [OH_Drawing_CreateTypographyHandler](#oh_drawing_createtypographyhandler) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*, [OH_Drawing_FontCollection](#oh_drawing_fontcollection) \*) | Creates an **OH_Drawing_TypographyCreate** object. When [OH_Drawing_TypographyCreate](#oh_drawing_typographycreate) is no longer required, call [OH_Drawing_DestroyTypographyHandler](#oh_drawing_destroytypographyhandler) to release the pointer to the object.| | void [OH_Drawing_DestroyTypographyHandler](#oh_drawing_destroytypographyhandler) ([OH_Drawing_TypographyCreate](#oh_drawing_typographycreate) \*) | Destroys an **OH_Drawing_TypographyCreate** object and reclaims the memory occupied by the object.| -| void [OH_Drawing_TypographyHandlerPushTextStyle](#oh_drawing_typographyhandlerpushtextstyle) ([OH_Drawing_TypographyCreate](#oh_drawing_typographycreate) \*, [OH_Drawing_TextStyle](#oh_drawing_textstyle) \*) | Pushes the text style.| +| void [OH_Drawing_TypographyHandlerPushTextStyle](#oh_drawing_typographyhandlerpushtextstyle) ([OH_Drawing_TypographyCreate](#oh_drawing_typographycreate) \*, [OH_Drawing_TextStyle](#oh_drawing_textstyle) \*) | Pushes a text style into the text style stack. Any text added afterward will use the style currently on top of the stack.| | void [OH_Drawing_TypographyHandlerAddText](#oh_drawing_typographyhandleraddtext) ([OH_Drawing_TypographyCreate](#oh_drawing_typographycreate) \*, const char \*) | Adds text.| -| void [OH_Drawing_TypographyHandlerPopTextStyle](#oh_drawing_typographyhandlerpoptextstyle) ([OH_Drawing_TypographyCreate](#oh_drawing_typographycreate) \*) | Removes the topmost text style in the stack, leaving the remaining styles in effect.| -| [OH_Drawing_Typography](#oh_drawing_typography) \* [OH_Drawing_CreateTypography](#oh_drawing_createtypography) ([OH_Drawing_TypographyCreate](#oh_drawing_typographycreate) \*) | Creates an **OH_Drawing_Typography** object.| +| void [OH_Drawing_TypographyHandlerPopTextStyle](#oh_drawing_typographyhandlerpoptextstyle) ([OH_Drawing_TypographyCreate](#oh_drawing_typographycreate) \*) | Pops the top text style out of the text style stack.| +| [OH_Drawing_Typography](#oh_drawing_typography) \* [OH_Drawing_CreateTypography](#oh_drawing_createtypography) ([OH_Drawing_TypographyCreate](#oh_drawing_typographycreate) \*) | Creates an **OH_Drawing_Typography** object. When [OH_Drawing_Typography](#oh_drawing_typography) is no longer required, call [OH_Drawing_DestroyTypography](#oh_drawing_destroytypography) to release the pointer to the object.| | void [OH_Drawing_DestroyTypography](#oh_drawing_destroytypography) ([OH_Drawing_Typography](#oh_drawing_typography) \*) | Destroys an **OH_Drawing_Typography** object and reclaims the memory occupied by the object.| | void [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) ([OH_Drawing_Typography](#oh_drawing_typography) \*, double) | Lays out the typography.| -| void [OH_Drawing_TypographyPaint](#oh_drawing_typographypaint) ([OH_Drawing_Typography](#oh_drawing_typography) \*, [OH_Drawing_Canvas](#oh_drawing_canvas) \*, double, double) | Paints text on the canvas.| +| void [OH_Drawing_TypographyPaint](#oh_drawing_typographypaint) ([OH_Drawing_Typography](#oh_drawing_typography) \*, [OH_Drawing_Canvas](#oh_drawing_canvas) \*, double, double) | Draws text from the upper left corner at a specified position. This function must be called after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called and applied.| | void [OH_Drawing_TypographyPaintOnPath](#oh_drawing_typographypaintonpath) ([OH_Drawing_Typography](#oh_drawing_typography) \*, [OH_Drawing_Canvas](#oh_drawing_canvas) \*, [OH_Drawing_Path](#oh_drawing_path) \*, double, double) | Draws text along a path.| -| double [OH_Drawing_TypographyGetMaxWidth](#oh_drawing_typographygetmaxwidth) ([OH_Drawing_Typography](#oh_drawing_typography) \*) | Obtains the maximum width.| -| double [OH_Drawing_TypographyGetHeight](#oh_drawing_typographygetheight) ([OH_Drawing_Typography](#oh_drawing_typography) \*) | Obtains the height.| -| double [OH_Drawing_TypographyGetLongestLine](#oh_drawing_typographygetlongestline) ([OH_Drawing_Typography](#oh_drawing_typography) \*) | Obtains the width of the longest line. You are advised to round up the return value in actual use. When the text content is empty, the minimum float value, that is, -340282346638528859811704183484516925440.000000, is returned.| -| double [OH_Drawing_TypographyGetLongestLineWithIndent](#oh_drawing_typographygetlongestlinewithindent) ([OH_Drawing_Typography](#oh_drawing_typography) \*) | Obtains the width of the longest line, including its indentation. You are advised to round up the return value in actual use. If the text content is empty, **0.0** is returned.| -| double [OH_Drawing_TypographyGetMinIntrinsicWidth](#oh_drawing_typographygetminintrinsicwidth) ([OH_Drawing_Typography](#oh_drawing_typography) \*) | Obtains the minimum intrinsic width.| -| double [OH_Drawing_TypographyGetMaxIntrinsicWidth](#oh_drawing_typographygetmaxintrinsicwidth) ([OH_Drawing_Typography](#oh_drawing_typography) \*) | Obtains the maximum intrinsic width.| -| double [OH_Drawing_TypographyGetAlphabeticBaseline](#oh_drawing_typographygetalphabeticbaseline) ([OH_Drawing_Typography](#oh_drawing_typography) \*) | Obtains the alphabetic baseline.| -| double [OH_Drawing_TypographyGetIdeographicBaseline](#oh_drawing_typographygetideographicbaseline) ([OH_Drawing_Typography](#oh_drawing_typography) \*) | Obtains the ideographic baseline.| +| double [OH_Drawing_TypographyGetMaxWidth](#oh_drawing_typographygetmaxwidth) ([OH_Drawing_Typography](#oh_drawing_typography) \*) | Obtains the typography width set by the user. This function must be called after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called.| +| double [OH_Drawing_TypographyGetHeight](#oh_drawing_typographygetheight) ([OH_Drawing_Typography](#oh_drawing_typography) \*) | Obtains the overall height of a typography object. This function must be called after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called.| +| double [OH_Drawing_TypographyGetLongestLine](#oh_drawing_typographygetlongestline) ([OH_Drawing_Typography](#oh_drawing_typography) \*) | Obtains the width of the longest line in a typography object. This function must be called after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called. You are advised to round up the return value. If the text content is empty, **0.0** is returned.| +| double [OH_Drawing_TypographyGetLongestLineWithIndent](#oh_drawing_typographygetlongestlinewithindent) ([OH_Drawing_Typography](#oh_drawing_typography) \*) | Obtains the width of the longest line of a typography object, including its indentation. This function must be called after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called. You are advised to round up the return value. If the text content is empty, **0.0** is returned.| +| double [OH_Drawing_TypographyGetMinIntrinsicWidth](#oh_drawing_typographygetminintrinsicwidth) ([OH_Drawing_Typography](#oh_drawing_typography) \*) | Obtains the minimum intrinsic width in a typography object. This function must be called after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called.| +| double [OH_Drawing_TypographyGetMaxIntrinsicWidth](#oh_drawing_typographygetmaxintrinsicwidth) ([OH_Drawing_Typography](#oh_drawing_typography) \*) | Obtains the maximum intrinsic width in a typography object. This function must be called after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called.| +| double [OH_Drawing_TypographyGetAlphabeticBaseline](#oh_drawing_typographygetalphabeticbaseline) ([OH_Drawing_Typography](#oh_drawing_typography) \*) | Obtains the alphabetic baseline in a typography object.| +| double [OH_Drawing_TypographyGetIdeographicBaseline](#oh_drawing_typographygetideographicbaseline) ([OH_Drawing_Typography](#oh_drawing_typography) \*) | Obtains the ideographic baseline in a typography object.| | void [OH_Drawing_TypographyHandlerAddPlaceholder](#oh_drawing_typographyhandleraddplaceholder) ([OH_Drawing_TypographyCreate](#oh_drawing_typographycreate) \*, [OH_Drawing_PlaceholderSpan](_o_h___drawing___placeholder_span.md) \*) | Adds a placeholder.| -| bool [OH_Drawing_TypographyDidExceedMaxLines](#oh_drawing_typographydidexceedmaxlines) ([OH_Drawing_Typography](#oh_drawing_typography) \*) | Checks whether the maximum number of lines is exceeded.| -| [OH_Drawing_TextBox](#oh_drawing_textbox) \* [OH_Drawing_TypographyGetRectsForRange](#oh_drawing_typographygetrectsforrange) ([OH_Drawing_Typography](#oh_drawing_typography) \*, size_t, size_t, [OH_Drawing_RectHeightStyle](#oh_drawing_rectheightstyle), [OH_Drawing_RectWidthStyle](#oh_drawing_rectwidthstyle)) | Obtains text boxes in a given range.| -| [OH_Drawing_TextBox](#oh_drawing_textbox) \* [OH_Drawing_TypographyGetRectsForPlaceholders](#oh_drawing_typographygetrectsforplaceholders) ([OH_Drawing_Typography](#oh_drawing_typography) \*) | Obtains text boxes for placeholders.| +| bool [OH_Drawing_TypographyDidExceedMaxLines](#oh_drawing_typographydidexceedmaxlines) ([OH_Drawing_Typography](#oh_drawing_typography) \*) | Checks whether the maximum number of lines of a typography object is exceeded. This function must be called after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called. If the maximum number of lines is not set by calling [OH_Drawing_SetTypographyTextMaxLines](#oh_drawing_settypographytextmaxlines), **false** is returned.| +| [OH_Drawing_TextBox](#oh_drawing_textbox) \* [OH_Drawing_TypographyGetRectsForRange](#oh_drawing_typographygetrectsforrange) ([OH_Drawing_Typography](#oh_drawing_typography) \*, size_t, size_t, [OH_Drawing_RectHeightStyle](#oh_drawing_rectheightstyle), [OH_Drawing_RectWidthStyle](#oh_drawing_rectwidthstyle)) | Obtains text boxes in a given range of a typography object. This function must be called after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called. When [OH_Drawing_TextBox](#oh_drawing_textbox) is no longer required, call [OH_Drawing_TypographyDestroyTextBox](#oh_drawing_typographydestroytextbox) to release the pointer to the object.| +| [OH_Drawing_TextBox](#oh_drawing_textbox) \* [OH_Drawing_TypographyGetRectsForPlaceholders](#oh_drawing_typographygetrectsforplaceholders) ([OH_Drawing_Typography](#oh_drawing_typography) \*) | Obtains text boxes for placeholders in a typography object. This function must be called after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called. When [OH_Drawing_TextBox](#oh_drawing_textbox) is no longer required, call [OH_Drawing_TypographyDestroyTextBox](#oh_drawing_typographydestroytextbox) to release the pointer to the object.| | float [OH_Drawing_GetLeftFromTextBox](#oh_drawing_getleftfromtextbox) ([OH_Drawing_TextBox](#oh_drawing_textbox) \*, int) | Obtains the left position of a text box.| | float [OH_Drawing_GetRightFromTextBox](#oh_drawing_getrightfromtextbox) ([OH_Drawing_TextBox](#oh_drawing_textbox) \*, int) | Obtains the right position of a text box.| | float [OH_Drawing_GetTopFromTextBox](#oh_drawing_gettopfromtextbox) ([OH_Drawing_TextBox](#oh_drawing_textbox) \*, int) | Obtains the top position of a text box.| @@ -669,10 +686,10 @@ The Drawing module provides the functions for 2D graphics rendering, text drawin | [OH_Drawing_PositionAndAffinity](#oh_drawing_positionandaffinity) \* [OH_Drawing_TypographyGetGlyphPositionAtCoordinateWithCluster](#oh_drawing_typographygetglyphpositionatcoordinatewithcluster) ([OH_Drawing_Typography](#oh_drawing_typography) \*, double, double) | Obtains the position and affinity of the glyph cluster to which the glyph at the given coordinates belongs. The glyph cluster is a container that holds one or more glyphs.| | size_t [OH_Drawing_GetPositionFromPositionAndAffinity](#oh_drawing_getpositionfrompositionandaffinity) ([OH_Drawing_PositionAndAffinity](#oh_drawing_positionandaffinity) \*) | Obtains the position attribute of an **OH_Drawing_PositionAndAffinity** object.| | int [OH_Drawing_GetAffinityFromPositionAndAffinity](#oh_drawing_getaffinityfrompositionandaffinity) ([OH_Drawing_PositionAndAffinity](#oh_drawing_positionandaffinity) \*) | Obtains the affinity attribute of an **OH_Drawing_PositionAndAffinity** object. The affinity determines whether the font is close to the front text or rear text.| -| [OH_Drawing_Range](#oh_drawing_range) \* [OH_Drawing_TypographyGetWordBoundary](#oh_drawing_typographygetwordboundary) ([OH_Drawing_Typography](#oh_drawing_typography) \*, size_t) | Obtains the word boundary.| +| [OH_Drawing_Range](#oh_drawing_range) \* [OH_Drawing_TypographyGetWordBoundary](#oh_drawing_typographygetwordboundary) ([OH_Drawing_Typography](#oh_drawing_typography) \*, size_t) | Obtains the word boundary in a typography object.| | size_t [OH_Drawing_GetStartFromRange](#oh_drawing_getstartfromrange) ([OH_Drawing_Range](#oh_drawing_range) \*) | Obtains the start position of an **OH_Drawing_Range** object.| | size_t [OH_Drawing_GetEndFromRange](#oh_drawing_getendfromrange) ([OH_Drawing_Range](#oh_drawing_range) \*) | Obtains the end position of an **OH_Drawing_Range** object.| -| size_t [OH_Drawing_TypographyGetLineCount](#oh_drawing_typographygetlinecount) ([OH_Drawing_Typography](#oh_drawing_typography) \*) | Obtains the number of lines.| +| size_t [OH_Drawing_TypographyGetLineCount](#oh_drawing_typographygetlinecount) ([OH_Drawing_Typography](#oh_drawing_typography) \*) | Obtains the number of lines in a typography object. This function must be called after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called.| | void [OH_Drawing_SetTextStyleDecorationStyle](#oh_drawing_settextstyledecorationstyle) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*, int) | Sets the decoration style for a text style.| | void [OH_Drawing_SetTextStyleDecorationThicknessScale](#oh_drawing_settextstyledecorationthicknessscale) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*, double) | Sets the thickness scale factor for the decoration style of a text style.| | void [OH_Drawing_SetTextStyleLetterSpacing](#oh_drawing_settextstyleletterspacing) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*, double) | Sets the letter spacing for a text style.| @@ -682,75 +699,75 @@ The Drawing module provides the functions for 2D graphics rendering, text drawin | void [OH_Drawing_SetTextStyleEllipsisModal](#oh_drawing_settextstyleellipsismodal) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*, int) | Sets the ellipsis style for a text style.| | void [OH_Drawing_SetTypographyTextBreakStrategy](#oh_drawing_settypographytextbreakstrategy) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*, int) | Sets the text break strategy.| | void [OH_Drawing_SetTypographyTextWordBreakType](#oh_drawing_settypographytextwordbreaktype) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*, int) | Sets the word break type.| -| void [OH_Drawing_SetTypographyTextEllipsisModal](#oh_drawing_settypographytextellipsismodal) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*, int) | Sets the text ellipsis style.| -| void [OH_Drawing_SetTypographyTextEllipsis](#oh_drawing_settypographytextellipsis) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*style, const char \*ellipsis) | Sets the text ellipsis content.| -| double [OH_Drawing_TypographyGetLineHeight](#oh_drawing_typographygetlineheight) ([OH_Drawing_Typography](#oh_drawing_typography) \*, int) | Obtains the line height.| -| double [OH_Drawing_TypographyGetLineWidth](#oh_drawing_typographygetlinewidth) ([OH_Drawing_Typography](#oh_drawing_typography) \*, int) | Obtains the line width.| +| void [OH_Drawing_SetTypographyTextEllipsisModal](#oh_drawing_settypographytextellipsismodal) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*, int) | Sets the text ellipsis style for a typography style.| +| void [OH_Drawing_SetTypographyTextEllipsis](#oh_drawing_settypographytextellipsis) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*style, const char \*ellipsis) | Sets the ellipsis text for a typography style.| +| double [OH_Drawing_TypographyGetLineHeight](#oh_drawing_typographygetlineheight) ([OH_Drawing_Typography](#oh_drawing_typography) \*, int) | Obtains the line height in a typography object. This function must be called after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called.| +| double [OH_Drawing_TypographyGetLineWidth](#oh_drawing_typographygetlinewidth) ([OH_Drawing_Typography](#oh_drawing_typography) \*, int) | Obtains the line width in a typography object. This function must be called after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called.| | void [OH_Drawing_SetTypographyTextSplitRatio](#oh_drawing_settypographytextsplitratio) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*style, float textSplitRatio) | Sets the text split ratio.| | bool [OH_Drawing_TypographyIsLineUnlimited](#oh_drawing_typographyislineunlimited) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*style) | Checks whether the maximum number of lines is limited for text.| -| bool [OH_Drawing_TypographyIsEllipsized](#oh_drawing_typographyisellipsized) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*style) | Checks whether the text has an ellipsis.| -| void [OH_Drawing_SetTypographyTextLocale](#oh_drawing_settypographytextlocale) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*style, const char \*locale) | Sets the locale for text.| +| bool [OH_Drawing_TypographyIsEllipsized](#oh_drawing_typographyisellipsized) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*style) | Checks whether an ellipsis is configured for a typography style.| +| void [OH_Drawing_SetTypographyTextLocale](#oh_drawing_settypographytextlocale) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*style, const char \*locale) | Sets the locale for a typography style.| | bool [OH_Drawing_TextStyleGetFontMetrics](#oh_drawing_textstylegetfontmetrics) ([OH_Drawing_Typography](#oh_drawing_typography) \*, [OH_Drawing_TextStyle](#oh_drawing_textstyle) \*, [OH_Drawing_Font_Metrics](_o_h___drawing___font___metrics.md) \*) | Obtains the font metrics of a text style.| | void [OH_Drawing_SetTypographyTextStyle](#oh_drawing_settypographytextstyle) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*, [OH_Drawing_TextStyle](#oh_drawing_textstyle) \*) | Sets a text style.| | [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) \* [OH_Drawing_CreateFontDescriptor](#oh_drawing_createfontdescriptor) (void) | Creates an **OH_Drawing_FontDescriptor** object to describe the detailed information about a system font.| | void [OH_Drawing_DestroyFontDescriptor](#oh_drawing_destroyfontdescriptor) ([OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) \*) | Destroys an **OH_Drawing_FontDescriptor** object and reclaims the memory occupied by the object.| | [OH_Drawing_FontParser](#oh_drawing_fontparser) \* [OH_Drawing_CreateFontParser](#oh_drawing_createfontparser) (void) | Creates an **OH_Drawing_FontParser** object to parse a system font.| | void [OH_Drawing_DestroyFontParser](#oh_drawing_destroyfontparser) ([OH_Drawing_FontParser](#oh_drawing_fontparser) \*) | Destroys an **OH_Drawing_FontParser** object and reclaims the memory occupied by the object.| -| char \*\* [OH_Drawing_FontParserGetSystemFontList](#oh_drawing_fontparsergetsystemfontlist) ([OH_Drawing_FontParser](#oh_drawing_fontparser) \*, size_t \*) | Obtains the list of system fonts. This function can be used only on 2-in-1 devices.| +| char \*\* [OH_Drawing_FontParserGetSystemFontList](#oh_drawing_fontparsergetsystemfontlist) ([OH_Drawing_FontParser](#oh_drawing_fontparser) \*, size_t \*) | Obtains the list of system fonts. This function can be used only on 2-in-1 devices and phones.| | void [OH_Drawing_DestroySystemFontList](#oh_drawing_destroysystemfontlist) (char \*\*, size_t) | Reclaims the memory occupied by the system font list.| | [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) \* [OH_Drawing_FontParserGetFontByName](#oh_drawing_fontparsergetfontbyname) ([OH_Drawing_FontParser](#oh_drawing_fontparser) \*, const char \*) | Obtains the descriptor of a system font based on the font name.| -| [OH_Drawing_LineMetrics](_o_h___drawing___line_metrics.md) \* [OH_Drawing_TypographyGetLineMetrics](#oh_drawing_typographygetlinemetrics) ([OH_Drawing_Typography](#oh_drawing_typography) \*) | Obtains the line metrics.| +| [OH_Drawing_LineMetrics](_o_h___drawing___line_metrics.md) \* [OH_Drawing_TypographyGetLineMetrics](#oh_drawing_typographygetlinemetrics) ([OH_Drawing_Typography](#oh_drawing_typography) \*) | Obtains the line metrics in a typography object. This function must be called after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called. When [OH_Drawing_LineMetrics](_o_h___drawing___line_metrics.md) is no longer required, call [OH_Drawing_DestroyLineMetrics](#oh_drawing_destroylinemetrics) to release the pointer to the object.| | size_t [OH_Drawing_LineMetricsGetSize](#oh_drawing_linemetricsgetsize) ([OH_Drawing_LineMetrics](_o_h___drawing___line_metrics.md) \*) | Obtains the number of lines.| | void [OH_Drawing_DestroyLineMetrics](#oh_drawing_destroylinemetrics) ([OH_Drawing_LineMetrics](_o_h___drawing___line_metrics.md) \*) | Destroys an **OH_Drawing_LineMetrics** object and reclaims the memory occupied by the object.| -| bool [OH_Drawing_TypographyGetLineMetricsAt](#oh_drawing_typographygetlinemetricsat) ([OH_Drawing_Typography](#oh_drawing_typography) \*, int, [OH_Drawing_LineMetrics](_o_h___drawing___line_metrics.md) \*) | Obtains the metrics of a given line.| -| bool [OH_Drawing_TypographyGetLineInfo](#oh_drawing_typographygetlineinfo) ([OH_Drawing_Typography](#oh_drawing_typography) \*, int, bool, bool, [OH_Drawing_LineMetrics](_o_h___drawing___line_metrics.md) \*) | Obtains the metrics of a given line or the metrics of the first character in a given line.| -| void [OH_Drawing_SetTypographyTextFontWeight](#oh_drawing_settypographytextfontweight) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*, int) | Sets the font weight for text. Currently, only the default system font supports font weight adjustment. For other fonts, if the weight is less than semi-bold, there is no variation in stroke thickness. If the weight is greater than or equal to semi-bold, it might result in a fake bold effect.| -| void [OH_Drawing_SetTypographyTextFontStyle](#oh_drawing_settypographytextfontstyle) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*, int) | Sets the font style for text.| +| bool [OH_Drawing_TypographyGetLineMetricsAt](#oh_drawing_typographygetlinemetricsat) ([OH_Drawing_Typography](#oh_drawing_typography) \*, int, [OH_Drawing_LineMetrics](_o_h___drawing___line_metrics.md) \*) | Obtains the metrics of a given line in a typography object. For details, see [OH_Drawing_LineMetrics](_o_h___drawing___line_metrics.md). This function must be called after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called.| +| bool [OH_Drawing_TypographyGetLineInfo](#oh_drawing_typographygetlineinfo) ([OH_Drawing_Typography](#oh_drawing_typography) \*, int, bool, bool, [OH_Drawing_LineMetrics](_o_h___drawing___line_metrics.md) \*) | Obtains the metrics of a given line or the metrics of the first character in a given line in a typography object. This function must be called after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called.| +| void [OH_Drawing_SetTypographyTextFontWeight](#oh_drawing_settypographytextfontweight) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*, int) | Sets the default font weight for a typography style. Currently, only the default system font supports font weight adjustment. For other fonts, if the weight is less than semi-bold, there is no variation in stroke thickness. If the weight is greater than or equal to semi-bold, it might result in a fake bold effect.| +| void [OH_Drawing_SetTypographyTextFontStyle](#oh_drawing_settypographytextfontstyle) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*, int) | Sets the default font style for a typography style.| | void [OH_Drawing_SetTypographyTextFontFamily](#oh_drawing_settypographytextfontfamily) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*, const char \*) | Sets the font family name for text.| | void [OH_Drawing_SetTypographyTextFontSize](#oh_drawing_settypographytextfontsize) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*, double) | Sets the font size for text.| | void [OH_Drawing_SetTypographyTextFontHeight](#oh_drawing_settypographytextfontheight) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*, double) | Sets the font height for text.| | void [OH_Drawing_SetTypographyTextHalfLeading](#oh_drawing_settypographytexthalfleading) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*, bool) | Sets whether to enable half leading for text.| | void [OH_Drawing_SetTypographyTextUseLineStyle](#oh_drawing_settypographytextuselinestyle) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*, bool) | Sets whether to enable the text line style.| -| void [OH_Drawing_SetTypographyTextLineStyleFontWeight](#oh_drawing_settypographytextlinestylefontweight) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*, int) | Sets the font weight for a text line style. Currently, only the default system font supports font weight adjustment. For other fonts, if the weight is less than semi-bold, there is no variation in stroke thickness. If the weight is greater than or equal to semi-bold, it might result in a fake bold effect.| -| void [OH_Drawing_SetTypographyTextLineStyleFontStyle](#oh_drawing_settypographytextlinestylefontstyle) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*, int) | Sets the font style for a text line style.| +| void [OH_Drawing_SetTypographyTextLineStyleFontWeight](#oh_drawing_settypographytextlinestylefontweight) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*, int) | Sets the text font weight of the strut style in a typography style. Currently, only the default system font supports font weight adjustment. For other fonts, if the weight is less than semi-bold, there is no variation in stroke thickness. If the weight is greater than or equal to semi-bold, it might result in a fake bold effect.| +| void [OH_Drawing_SetTypographyTextLineStyleFontStyle](#oh_drawing_settypographytextlinestylefontstyle) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*, int) | Sets the font style of the strut style in a typography style.| | void [OH_Drawing_SetTypographyTextLineStyleFontFamilies](#oh_drawing_settypographytextlinestylefontfamilies) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*, int, const char \*fontFamilies[]) | Sets the font families for a text line style.| | void [OH_Drawing_SetTypographyTextLineStyleFontSize](#oh_drawing_settypographytextlinestylefontsize) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*, double) | Sets the font size for a text line style.| | void [OH_Drawing_SetTypographyTextLineStyleFontHeight](#oh_drawing_settypographytextlinestylefontheight) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*, double) | Sets the font height for a text line style.| -| void [OH_Drawing_SetTypographyTextLineStyleHalfLeading](#oh_drawing_settypographytextlinestylehalfleading) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*, bool) | Sets whether to enable half leading for a text line style.| +| void [OH_Drawing_SetTypographyTextLineStyleHalfLeading](#oh_drawing_settypographytextlinestylehalfleading) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*, bool) | Sets whether to enable half leading for the strut style in a typography style.| | void [OH_Drawing_SetTypographyTextLineStyleSpacingScale](#oh_drawing_settypographytextlinestylespacingscale) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*, double) | Sets the spacing scale factor for a text line style.| | void [OH_Drawing_SetTypographyTextLineStyleOnly](#oh_drawing_settypographytextlinestyleonly) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*, bool) | Sets whether to enable the text line style only.| -| [OH_Drawing_TextShadow](#oh_drawing_textshadow) \* [OH_Drawing_CreateTextShadow](#oh_drawing_createtextshadow) (void) | Creates an **OH_Drawing_TextShadow** object.| +| [OH_Drawing_TextShadow](#oh_drawing_textshadow) \* [OH_Drawing_CreateTextShadow](#oh_drawing_createtextshadow) (void) | Creates an **OH_Drawing_TextShadow** object. When [OH_Drawing_TextShadow](#oh_drawing_textshadow) is no longer required, call [OH_Drawing_DestroyTextShadow](#oh_drawing_destroytextshadow) to release the pointer to the object.| | void [OH_Drawing_DestroyTextShadow](#oh_drawing_destroytextshadow) ([OH_Drawing_TextShadow](#oh_drawing_textshadow) \*) | Destroys an **OH_Drawing_TextShadow** object and reclaims the memory occupied by the object.| -| [OH_Drawing_TextShadow](#oh_drawing_textshadow) \* [OH_Drawing_TextStyleGetShadows](#oh_drawing_textstylegetshadows) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*) | Obtains a text shadow container.| +| [OH_Drawing_TextShadow](#oh_drawing_textshadow) \* [OH_Drawing_TextStyleGetShadows](#oh_drawing_textstylegetshadows) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*) | Obtains a text shadow container. When [OH_Drawing_TextShadow](#oh_drawing_textshadow) is no longer required, call [OH_Drawing_DestroyTextShadows](#oh_drawing_destroytextshadows) to release the pointer to the object.| | int [OH_Drawing_TextStyleGetShadowCount](#oh_drawing_textstylegetshadowcount) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*) | Obtains the size of a text shadow container.| | void [OH_Drawing_TextStyleAddShadow](#oh_drawing_textstyleaddshadow) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*, const [OH_Drawing_TextShadow](#oh_drawing_textshadow) \*) | Adds a shadow to a text shadow container.| | void [OH_Drawing_TextStyleClearShadows](#oh_drawing_textstyleclearshadows) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*) | Clears all shadows in a text shadow container.| | [OH_Drawing_TextShadow](#oh_drawing_textshadow) \* [OH_Drawing_TextStyleGetShadowWithIndex](#oh_drawing_textstylegetshadowwithindex) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*, int) | Obtains a shadow with a given index in a text shadow container.| | void [OH_Drawing_TypographySetIndents](#oh_drawing_typographysetindents) ([OH_Drawing_Typography](#oh_drawing_typography) \*, int, const float indents[]) | Sets indents for typography. If this function is not called, texts will have no indentation applied.| -| float [OH_Drawing_TypographyGetIndentsWithIndex](#oh_drawing_typographygetindentswithindex) ([OH_Drawing_Typography](#oh_drawing_typography) \*, int) | Obtains indents with a given index.| -| [OH_Drawing_Range](#oh_drawing_range) \* [OH_Drawing_TypographyGetLineTextRange](#oh_drawing_typographygetlinetextrange) ([OH_Drawing_Typography](#oh_drawing_typography) \*, int, bool) | Obtains the line bounds.| +| float [OH_Drawing_TypographyGetIndentsWithIndex](#oh_drawing_typographygetindentswithindex) ([OH_Drawing_Typography](#oh_drawing_typography) \*, int) | Obtains indents with a given index in a typography object. The line index starts from 0.| +| [OH_Drawing_Range](#oh_drawing_range) \* [OH_Drawing_TypographyGetLineTextRange](#oh_drawing_typographygetlinetextrange) ([OH_Drawing_Typography](#oh_drawing_typography) \*, int, bool) | Obtains the line bounds in a typography object. This function must be called after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called. This function can only be used to obtain the bounds of existing lines. That is, the line index must start from 0, and the maximum index is [OH_Drawing_TypographyGetLineCount](#oh_drawing_typographygetlinecount) - 1.| | void [OH_Drawing_DestroyTextShadows](#oh_drawing_destroytextshadows) ([OH_Drawing_TextShadow](#oh_drawing_textshadow) \*) | Reclaims the memory occupied by the vector consisting of the **OH_Drawing_TextShadow** objects.| | [OH_Drawing_FontConfigInfo](_o_h___drawing___font_config_info.md) \* [OH_Drawing_GetSystemFontConfigInfo](#oh_drawing_getsystemfontconfiginfo) ([OH_Drawing_FontConfigInfoErrorCode](#oh_drawing_fontconfiginfoerrorcode) \*) | Obtains the system font configuration.| | void [OH_Drawing_DestroySystemFontConfigInfo](#oh_drawing_destroysystemfontconfiginfo) ([OH_Drawing_FontConfigInfo](_o_h___drawing___font_config_info.md) \*) | Reclaims the memory occupied by the system font configuration.| | void [OH_Drawing_SetTextStyleFontStyleStruct](#oh_drawing_settextstylefontstylestruct) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*drawingTextStyle, [OH_Drawing_FontStyleStruct](_o_h___drawing___font_style_struct.md) fontStyle) | Sets the font style, including the font weight, width, and slant, for a text style.| | [OH_Drawing_FontStyleStruct](_o_h___drawing___font_style_struct.md) [OH_Drawing_TextStyleGetFontStyleStruct](#oh_drawing_textstylegetfontstylestruct) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*drawingTextStyle) | Obtains the font style, including the font weight, width, and slant, of a text style.| -| void [OH_Drawing_SetTypographyStyleFontStyleStruct](#oh_drawing_settypographystylefontstylestruct) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*drawingStyle, [OH_Drawing_FontStyleStruct](_o_h___drawing___font_style_struct.md) fontStyle) | Sets the font style, including the font weight, width, and slant, for a typography style.| -| [OH_Drawing_FontStyleStruct](_o_h___drawing___font_style_struct.md) [OH_Drawing_TypographyStyleGetFontStyleStruct](#oh_drawing_typographystylegetfontstylestruct) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*drawingStyle) | Obtains the font style, including the font weight, width, and slant, of a typography style.| +| void [OH_Drawing_SetTypographyStyleFontStyleStruct](#oh_drawing_settypographystylefontstylestruct) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*drawingStyle, [OH_Drawing_FontStyleStruct](_o_h___drawing___font_style_struct.md) fontStyle) | Sets the font style, including the font weight, width, and slant, for the default text style of a typography style.| +| [OH_Drawing_FontStyleStruct](_o_h___drawing___font_style_struct.md) [OH_Drawing_TypographyStyleGetFontStyleStruct](#oh_drawing_typographystylegetfontstylestruct) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*drawingStyle) | Obtains the font style, including the font weight, width, and slant, of the default text style of a typography style.| | void [OH_Drawing_TextStyleSetBackgroundRect](#oh_drawing_textstylesetbackgroundrect) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*, const [OH_Drawing_RectStyle_Info](_o_h___drawing___rect_style___info.md) \*, int styleId) | Sets a background rectangle and style ID for a text style. The style ID is valid only when the background box is a rounded rectangle.| | void [OH_Drawing_TypographyHandlerAddSymbol](#oh_drawing_typographyhandleraddsymbol) ([OH_Drawing_TypographyCreate](#oh_drawing_typographycreate) \*, uint32_t symbol) | Adds the symbol to use in the typography creation process.| | void [OH_Drawing_TextStyleAddFontFeature](#oh_drawing_textstyleaddfontfeature) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*, const char \*tag, int value) | Adds a font feature for a text style.| | void [OH_Drawing_TextStyleAddFontVariation](#oh_drawing_textstyleaddfontvariation) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*, const char \*, const float) | Adds a font variation. This function takes effect only when the corresponding font file (.ttf file) supports variable adjustment. Otherwise, calling this function does not take effect.| -| [OH_Drawing_FontFeature](_o_h___drawing___font_feature.md) \* [OH_Drawing_TextStyleGetFontFeatures](#oh_drawing_textstylegetfontfeatures) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*) | Obtains all the contents in a font feature map container.| +| [OH_Drawing_FontFeature](_o_h___drawing___font_feature.md) \* [OH_Drawing_TextStyleGetFontFeatures](#oh_drawing_textstylegetfontfeatures) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*) | Obtains all the contents in a font feature map container of a text style.| | void [OH_Drawing_TextStyleDestroyFontFeatures](#oh_drawing_textstyledestroyfontfeatures) ([OH_Drawing_FontFeature](_o_h___drawing___font_feature.md) \*, size_t fontFeatureSize) | Reclaims the memory occupied by the struct array that holds all the font features.| -| size_t [OH_Drawing_TextStyleGetFontFeatureSize](#oh_drawing_textstylegetfontfeaturesize) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*) | Obtains the size of a font feature map container.| -| void [OH_Drawing_TextStyleClearFontFeature](#oh_drawing_textstyleclearfontfeature) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*) | Clears all the contents in a font feature map container.| +| size_t [OH_Drawing_TextStyleGetFontFeatureSize](#oh_drawing_textstylegetfontfeaturesize) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*) | Obtains the size of a font feature map container in a text style.| +| void [OH_Drawing_TextStyleClearFontFeature](#oh_drawing_textstyleclearfontfeature) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*) | Clears all the contents in a font feature map container of a text style.| | double [OH_Drawing_TextStyleGetBaselineShift](#oh_drawing_textstylegetbaselineshift) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*) | Obtains the baseline drift of a text style.| | void [OH_Drawing_TextStyleSetBaselineShift](#oh_drawing_textstylesetbaselineshift) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*, double lineShift) | Sets a baseline drift for a text style.| | void [OH_Drawing_TypographyTextSetHeightBehavior](#oh_drawing_typographytextsetheightbehavior) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*, [OH_Drawing_TextHeightBehavior](#oh_drawing_textheightbehavior) heightMode) | Sets a text height modifier pattern.| | [OH_Drawing_TextHeightBehavior](#oh_drawing_textheightbehavior) [OH_Drawing_TypographyTextGetHeightBehavior](#oh_drawing_typographytextgetheightbehavior) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*) | Obtains the text height modifier pattern.| -| [OH_Drawing_Font_Metrics](_o_h___drawing___font___metrics.md) \* [OH_Drawing_TypographyGetLineFontMetrics](#oh_drawing_typographygetlinefontmetrics) ([OH_Drawing_Typography](#oh_drawing_typography) \*, size_t lineNumber, size_t \*fontMetricsSize) | Obtains all font metrics from a given line.| +| [OH_Drawing_Font_Metrics](_o_h___drawing___font___metrics.md) \* [OH_Drawing_TypographyGetLineFontMetrics](#oh_drawing_typographygetlinefontmetrics) ([OH_Drawing_Typography](#oh_drawing_typography) \*, size_t lineNumber, size_t \*fontMetricsSize) | Obtains all font metrics from a given line in a typography object. This function must be called after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called. Otherwise, a null pointer is returned. When [OH_Drawing_Font_Metrics](_o_h___drawing___font___metrics.md) is no longer required, call [OH_Drawing_TypographyDestroyLineFontMetrics](#oh_drawing_typographydestroylinefontmetrics) to release the pointer to the object.| | void [OH_Drawing_TypographyDestroyLineFontMetrics](#oh_drawing_typographydestroylinefontmetrics) ([OH_Drawing_Font_Metrics](_o_h___drawing___font___metrics.md) \*) | Reclaims the memory occupied by the struct array that holds all the font metrics of a given line.| -| bool [OH_Drawing_TextStyleIsEqual](#oh_drawing_textstyleisequal) (const [OH_Drawing_TextStyle](#oh_drawing_textstyle) \*style, const [OH_Drawing_TextStyle](#oh_drawing_textstyle) \*comparedStyle) | Checks whether two text styles are equal.| +| bool [OH_Drawing_TextStyleIsEqual](#oh_drawing_textstyleisequal) (const [OH_Drawing_TextStyle](#oh_drawing_textstyle) \*style, const [OH_Drawing_TextStyle](#oh_drawing_textstyle) \*comparedStyle) | Checks whether two text styles are equal. The word width property is not involved in the comparison.| | bool [OH_Drawing_TextStyleIsEqualByFont](#oh_drawing_textstyleisequalbyfont) (const [OH_Drawing_TextStyle](#oh_drawing_textstyle) \*style, const [OH_Drawing_TextStyle](#oh_drawing_textstyle) \*comparedStyle) | Checks whether the font style properties of two text styles are equal.| | bool [OH_Drawing_TextStyleIsAttributeMatched](#oh_drawing_textstyleisattributematched) (const [OH_Drawing_TextStyle](#oh_drawing_textstyle) \*style, const [OH_Drawing_TextStyle](#oh_drawing_textstyle) \*comparedStyle, [OH_Drawing_TextStyleType](#oh_drawing_textstyletype) textStyleType) | Checks whether two text styles have the same text style type.| | void [OH_Drawing_TextStyleSetPlaceholder](#oh_drawing_textstylesetplaceholder) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*style) | Sets a placeholder for a text style.| @@ -763,12 +780,12 @@ The Drawing module provides the functions for 2D graphics rendering, text drawin | bool [OH_Drawing_TypographyStyleStrutStyleEquals](#oh_drawing_typographystylestrutstyleequals) ([OH_Drawing_StrutStyle](_o_h___drawing___strut_style.md) \*from, [OH_Drawing_StrutStyle](_o_h___drawing___strut_style.md) \*to) | Checks whether two strut styles are equal.| | void [OH_Drawing_TypographyStyleSetHintsEnabled](#oh_drawing_typographystylesethintsenabled) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*style, bool hintsEnabled) | Sets whether to enable font hinting for a typography style. Font hinting is used to improve the readability and appearance of small-sized text when rendering it.| | void [OH_Drawing_TypographyMarkDirty](#oh_drawing_typographymarkdirty) ([OH_Drawing_Typography](#oh_drawing_typography) \*) | Marks a typography object as dirty data. This function is used to initialize the typography state.| -| int32_t [OH_Drawing_TypographyGetUnresolvedGlyphsCount](#oh_drawing_typographygetunresolvedglyphscount) ([OH_Drawing_Typography](#oh_drawing_typography) \*) | Obtains the number of unresolved glyphs in a typography object.| +| int32_t [OH_Drawing_TypographyGetUnresolvedGlyphsCount](#oh_drawing_typographygetunresolvedglyphscount) ([OH_Drawing_Typography](#oh_drawing_typography) \*) | Obtains the number of unresolved glyphs in a typography object. This function can be called only after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called and applied.| | void [OH_Drawing_TypographyUpdateFontSize](#oh_drawing_typographyupdatefontsize) ([OH_Drawing_Typography](#oh_drawing_typography) \*, size_t from, size_t to, float fontSize) | Updates the font size in a typography object.| | bool [OH_Drawing_TypographyTextGetLineStyle](#oh_drawing_typographytextgetlinestyle) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*) | Checks whether the text line style is enabled for a typography style.| -| [OH_Drawing_FontWeight](#oh_drawing_fontweight) [OH_Drawing_TypographyTextlineStyleGetFontWeight](#oh_drawing_typographytextlinestylegetfontweight) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*) | Obtains the font weight of a text line style.| -| [OH_Drawing_FontStyle](#oh_drawing_fontstyle) [OH_Drawing_TypographyTextlineStyleGetFontStyle](#oh_drawing_typographytextlinestylegetfontstyle) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*) | Obtains the font style of a text line style.| -| char \*\* [OH_Drawing_TypographyTextlineStyleGetFontFamilies](#oh_drawing_typographytextlinestylegetfontfamilies) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*) | Obtains the font families of a text line style.| +| [OH_Drawing_FontWeight](#oh_drawing_fontweight) [OH_Drawing_TypographyTextlineStyleGetFontWeight](#oh_drawing_typographytextlinestylegetfontweight) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*) | Obtains the font weight of the strut style in a typography style.| +| [OH_Drawing_FontStyle](#oh_drawing_fontstyle) [OH_Drawing_TypographyTextlineStyleGetFontStyle](#oh_drawing_typographytextlinestylegetfontstyle) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*) | Obtains the font style of the strut style in a typography style.| +| char \*\* [OH_Drawing_TypographyTextlineStyleGetFontFamilies](#oh_drawing_typographytextlinestylegetfontfamilies) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*, size_t \*num) | Obtains the font families of the strut style in a typography style.| | void [OH_Drawing_TypographyTextlineStyleDestroyFontFamilies](#oh_drawing_typographytextlinestyledestroyfontfamilies) (char \*\*fontFamilies, size_t fontFamiliesNum) | Reclaims the memory occupied by the font families.| | double [OH_Drawing_TypographyTextlineStyleGetFontSize](#oh_drawing_typographytextlinestylegetfontsize) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*) | Obtains the font size of a text line style.| | double [OH_Drawing_TypographyTextlineStyleGetHeightScale](#oh_drawing_typographytextlinestylegetheightscale) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*) | Obtains the height scale factor of a text line style.| @@ -777,18 +794,18 @@ The Drawing module provides the functions for 2D graphics rendering, text drawin | double [OH_Drawing_TypographyTextlineStyleGetSpacingScale](#oh_drawing_typographytextlinestylegetspacingscale) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*) | Obtains the spacing scale factor of a text line style.| | bool [OH_Drawing_TypographyTextlineGetStyleOnly](#oh_drawing_typographytextlinegetstyleonly) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*) | Checks whether only the text line style is enabled for a typography style.| | [OH_Drawing_TextAlign](#oh_drawing_textalign) [OH_Drawing_TypographyGetTextAlign](#oh_drawing_typographygettextalign) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*) | Obtains the text alignment mode.| -| [OH_Drawing_TextDirection](#oh_drawing_textdirection) [OH_Drawing_TypographyGetTextDirection](#oh_drawing_typographygettextdirection) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*) | Obtains the text direction.| +| [OH_Drawing_TextDirection](#oh_drawing_textdirection) [OH_Drawing_TypographyGetTextDirection](#oh_drawing_typographygettextdirection) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*) | Obtains the text direction of a typography style.| | size_t [OH_Drawing_TypographyGetTextMaxLines](#oh_drawing_typographygettextmaxlines) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*) | Obtains the maximum number of lines.| -| char \* [OH_Drawing_TypographyGetTextEllipsis](#oh_drawing_typographygettextellipsis) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*) | Obtains the text ellipsis content.| +| char \* [OH_Drawing_TypographyGetTextEllipsis](#oh_drawing_typographygettextellipsis) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*) | Obtains the text ellipsis content of a typography style.| | void [OH_Drawing_TypographyDestroyEllipsis](#oh_drawing_typographydestroyellipsis) (char \*ellipsis) | Reclaims the memory occupied by the text ellipsis names.| -| bool [OH_Drawing_TypographyStyleEquals](#oh_drawing_typographystyleequals) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*from, [OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*to) | Checks whether two typography styles are the same.| +| bool [OH_Drawing_TypographyStyleEquals](#oh_drawing_typographystyleequals) ([OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*from, [OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) \*to) | Checks whether two typography styles are the same. The text height modifier mode [OH_Drawing_TextHeightBehavior](#oh_drawing_textheightbehavior) is not involved in the comparison.| | uint32_t [OH_Drawing_TextStyleGetColor](#oh_drawing_textstylegetcolor) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*) | Obtains the color of a text style.| | [OH_Drawing_TextDecorationStyle](#oh_drawing_textdecorationstyle) [OH_Drawing_TextStyleGetDecorationStyle](#oh_drawing_textstylegetdecorationstyle) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*) | Obtains the decoration style of a text style.| | [OH_Drawing_FontWeight](#oh_drawing_fontweight) [OH_Drawing_TextStyleGetFontWeight](#oh_drawing_textstylegetfontweight) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*) | Obtains the font weight of a text style.| | [OH_Drawing_FontStyle](#oh_drawing_fontstyle) [OH_Drawing_TextStyleGetFontStyle](#oh_drawing_textstylegetfontstyle) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*) | Obtains the font style of a text style.| | [OH_Drawing_TextBaseline](#oh_drawing_textbaseline) [OH_Drawing_TextStyleGetBaseline](#oh_drawing_textstylegetbaseline) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*) | Obtains the baseline of a text style.| | char \*\* [OH_Drawing_TextStyleGetFontFamilies](#oh_drawing_textstylegetfontfamilies) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*, size_t \*num) | Obtains the font families of a text style.| -| void [OH_Drawing_TextStyleDestroyFontFamilies](#oh_drawing_textstyledestroyfontfamilies) (char \*\*fontFamilies, size_t num) | Reclaims the memory occupied by the font families.| +| void [OH_Drawing_TextStyleDestroyFontFamilies](#oh_drawing_textstyledestroyfontfamilies) (char \*\*fontFamilies, size_t num) | Reclaims the memory occupied by the font families, where **num** specifies the number of font families.| | double [OH_Drawing_TextStyleGetFontSize](#oh_drawing_textstylegetfontsize) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*) | Obtains the font size of a text style.| | double [OH_Drawing_TextStyleGetLetterSpacing](#oh_drawing_textstylegetletterspacing) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*) | Obtains the letter spacing of a text style.| | double [OH_Drawing_TextStyleGetWordSpacing](#oh_drawing_textstylegetwordspacing) ([OH_Drawing_TextStyle](#oh_drawing_textstyle) \*) | Obtains the word spacing of a text style.| @@ -837,6 +854,17 @@ The Drawing module provides the functions for 2D graphics rendering, text drawin ## Type Description +### OH_Drawing_PathDashStyle + +``` +typedef enum OH_Drawing_PathDashStyle OH_Drawing_PathDashStyle +``` + +**Description** + +Defines an enum for the drawing styles for path effects. + +**Since**: 18 ### OH_Drawing_Array @@ -862,7 +890,7 @@ typedef struct OH_Drawing_LineTypography OH_Drawing_LineTypography Defines a struct used to extract a single line of data from a piece of text for typography. -**Since**: 16 +**Since**: 18 ### OH_Drawing_TextTab @@ -874,7 +902,7 @@ typedef struct OH_Drawing_TextTab OH_Drawing_TextTab Defines a struct used to manage text tabs. -**Since**: 16 +**Since**: 18 ### OH_Drawing_TextLine @@ -886,7 +914,7 @@ typedef struct OH_Drawing_TextLine OH_Drawing_TextLine Defines a struct used to manage text lines. -**Since**: 16 +**Since**: 18 ### OH_Drawing_Run @@ -898,7 +926,7 @@ typedef struct OH_Drawing_RunOH_Drawing_Run Defines a struct used to manage runs. -**Since**: 16 +**Since**: 18 ### Drawing_CaretOffsetsCallback @@ -912,7 +940,7 @@ Defines a custom callback used to receive the offset and index of each character **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 14 +**Since**: 18 **Parameters** @@ -1121,7 +1149,7 @@ typedef enum OH_Drawing_BlendMode OH_Drawing_BlendMode **Description** -Defines an enum for the blend modes. In blend mode, each operation generates a new color from two colors (source color and target color). These operations are the same on the four channels (red, green, blue, and alpha). The operations for the alpha channel are used as examples. +Defines an enum for the blend modes. In blend mode, each operation generates a new color from two colors (source color and target color). These operations are the same for the red, green, and blue color channels (the alpha channel follows a different rule). The operations for the alpha channel are used as examples. For brevity, the following abbreviations are used: @@ -1295,7 +1323,7 @@ typedef enum OH_Drawing_EllipsisModal OH_Drawing_EllipsisModal **Description** -Defines an enum for the text ellipsis styles. +Defines an enum for the ellipsis styles. **Since**: 11 @@ -1594,7 +1622,7 @@ typedef struct OH_Drawing_MaskFilter OH_Drawing_MaskFilter **Description** -Defines a struct for a mask filter, which is used to convert a mask into a new one. +Defines a struct for a mask filter. **Since**: 11 @@ -1854,7 +1882,7 @@ typedef struct OH_Drawing_Range OH_Drawing_Range **Description** -Defines a struct for a range, which is used to receive the start position and end position of a glyph. +Defines a struct used to receive the start position and end position of a glyph. **Since**: 11 @@ -2225,6 +2253,24 @@ Defines an enum for the word break types. ## Enum Description +### OH_Drawing_PathDashStyle + +``` +enum OH_Drawing_PathDashStyle +``` + +**Description** + +Enumerates the drawing styles for path effects. + +**Since**: 18 + +| Value| Description| +| -------- | -------- | +| DRAWING_PATH_DASH_STYLE_TRANSLATE | Translation effect.| +| DRAWING_PATH_DASH_STYLE_ROTATE | Rotation effect.| +| DRAWING_PATH_DASH_STYLE_MORPH | Morphing effect.| + ### OH_Drawing_SystemFontType ``` @@ -2245,7 +2291,7 @@ Enumerates the system font types. | GENERIC | System font type.| | STYLISH | Style font type.| | INSTALLED | User-installed font type.| -| CUSTOMIZED16+ | Custom font type.| +| CUSTOMIZED18+ | Custom font type.| ### OH_Drawing_ErrorCode @@ -2357,7 +2403,7 @@ enum OH_Drawing_BlendMode **Description** -Enumerates the blend modes. In blend mode, each operation generates a new color from two colors (source color and target color). These operations are the same on the four channels (red, green, blue, and alpha). The operations for the alpha channel are used as examples. +Enumerates the blend modes. In blend mode, each operation generates a new color from two colors (source color and target color). These operations are the same for the red, green, and blue color channels (the alpha channel follows a different rule). The operations for the alpha channel are used as examples. For brevity, the following abbreviations are used: @@ -2539,7 +2585,7 @@ enum OH_Drawing_EllipsisModal **Description** -Enumerates the text ellipsis styles. +Enumerates the ellipsis styles. **Since**: 11 @@ -2585,7 +2631,7 @@ Enumerates the error codes that may be used during the obtaining of system font | SUCCESS_FONT_CONFIG_INFO | Operation successful.| | ERROR_FONT_CONFIG_INFO_UNKNOWN | Unknown error.| | ERROR_FONT_CONFIG_INFO_PARSE_FILE | Failed to parse the system configuration file.| -| ERROR_FONT_CONFIG_INFO_ALLOC_MEMORY | Failed to apply for a buffer.| +| ERROR_FONT_CONFIG_INFO_ALLOC_MEMORY | Failed to allocate the memory.| | ERROR_FONT_CONFIG_INFO_COPY_STRING_DATA | Failed to copy the string data.| @@ -2642,7 +2688,7 @@ Enumerates the font styles. | -------- | -------- | | FONT_STYLE_NORMAL | Normal style.| | FONT_STYLE_ITALIC | Italic.| -| FONT_STYLE_OBLIQUE | Oblique.
Since:
12 | +| FONT_STYLE_OBLIQUE12+ | Oblique.| ### OH_Drawing_FontWeight @@ -3038,10 +3084,10 @@ Enumerates the text height modifier patterns. | Value| Description| | -------- | -------- | -| TEXT_HEIGHT_ALL | Enables ascent for the first and last rows of a paragraph.| -| TEXT_HEIGHT_DISABLE_FIRST_ASCENT | Disables ascent for the first row of a paragraph.| -| TEXT_HEIGHT_DISABLE_LAST_ASCENT | Disables ascent for the last row of a paragraph.| -| TEXT_HEIGHT_DISABLE_ALL | Disables ascent for the first and last rows of a paragraph.| +| TEXT_HEIGHT_ALL | Enables the height set by calling [OH_Drawing_SetTextStyleFontHeight](#oh_drawing_settextstylefontheight) for the top of the first line and the bottom of the last line in a paragraph.| +| TEXT_HEIGHT_DISABLE_FIRST_ASCENT | Disables the height set by calling [OH_Drawing_SetTextStyleFontHeight](#oh_drawing_settextstylefontheight) for the top of the first line in a paragraph.| +| TEXT_HEIGHT_DISABLE_LAST_ASCENT | Disables the height set by calling [OH_Drawing_SetTextStyleFontHeight](#oh_drawing_settextstylefontheight) for the bottom of the last line in a paragraph.| +| TEXT_HEIGHT_DISABLE_ALL | Disables the height set by calling [OH_Drawing_SetTextStyleFontHeight](#oh_drawing_settextstylefontheight) for both the top of the first line and the bottom of the last line in a paragraph.| ### OH_Drawing_TextStyleType @@ -3125,11 +3171,425 @@ Enumerates the word break types. | WORD_BREAK_TYPE_NORMAL | Normal mode.| | WORD_BREAK_TYPE_BREAK_ALL | Breaks the words at any character to prevent overflow.| | WORD_BREAK_TYPE_BREAK_WORD | Breaks the words at arbitrary points to prevent overflow.| +| WORD_BREAK_TYPE_BREAK_HYPHEN18+ | Uses a hyphen (-) to break a word at the end of each line. If adding a hyphen is not possible, it will behave the same as **WORD_BREAK_TYPE_BREAK_WORD**.| ## Function Description +### OH_Drawing_PathGetSegment() + +``` +OH_Drawing_ErrorCode OH_Drawing_PathGetSegment (OH_Drawing_Path* path, bool forceClosed, float start, float stop, bool startWithMoveTo, OH_Drawing_Path* dst, bool* result) +``` + +**Description** + +Extracts a segment of a path and appends it to a destination path. + +**System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing + +**Since**: 18 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| path | Pointer to an [OH_Drawing_Path](#oh_drawing_path) object. | +| forceClosed | Whether the path is measured as a closed path. The value **true** means that the path is considered closed during measurement, and **false** means that the path is measured based on the actual closed status. | +| start | Distance from the start point of the path to the start point of the segment. If it is less than 0, it defaults to 0. If it is greater than or equal to **stop**, the extraction fails. | +| stop | Distance from the start point of the path to the end point of the segment. If it is less than or equal to **start**, the extraction fails. If it is greater than the path length, it defaults to the path length. | +| startWithMoveTo | Whether to execute [OH_Drawing_PathMoveTo](#oh_drawing_pathmoveto) in the destination path to move to its start point. The value **true** means to move to the start point, and **false** means the opposite. | +| dst | Pointer to a destination path, which is an [OH_Drawing_Path](#oh_drawing_path) object. If the extraction succeeds, the segment is appended to the path. If the extraction fails, nothing changes. | +| result | Pointer to the extraction result. The value **true** means that the extraction is successful, and **false** means the opposite. | + +**Returns** + +Returns one of the following result codes: + +- **OH_DRAWING_SUCCESS** if the operation is successful. + +- **OH_DRAWING_ERROR_INVALID_PARAMETER** if at least one of the **path**, **dst**, and **result** parameters is a null pointer. + +### OH_Drawing_CreateSumPathEffect() + +``` +OH_Drawing_PathEffect* OH_Drawing_CreateSumPathEffect (OH_Drawing_PathEffect* firstPathEffect, OH_Drawing_PathEffect* secondPathEffect ) +``` + +**Description** + +Creates an overlay path effect based on two distinct path effects that take effect separately. + +**System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing + +**Since**: 18 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| firstPathEffect | Pointer to an [OH_Drawing_PathEffect](#oh_drawing_patheffect) object. | +| secondPathEffect | Pointer to an [OH_Drawing_PathEffect](#oh_drawing_patheffect) object. | + +**Returns** + +Returns the pointer to the [OH_Drawing_PathEffect](#oh_drawing_patheffect) object created. + +If a null pointer is returned, the creation fails. The possible failure cause is that **firstPathEffect** or **secondPathEffect** is a null pointer. + +### OH_Drawing_CreatePathDashEffect() + +``` +OH_Drawing_PathEffect* OH_Drawing_CreatePathDashEffect (const OH_Drawing_Path* path, float advance, float phase, OH_Drawing_PathDashStyle type ) +``` + +**Description** + +Creates an **OH_Drawing_PathEffect** object with a dashed line effect. + +**System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing + +**Since**: 18 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| path | Pointer to an [OH_Drawing_Path](#oh_drawing_path) object. | +| advance | Length of each dashed line segment. | +| phase | Offset of the pattern within the dash segment length. | +| type | Style of the dashed path effect. | + +**Returns** + +Returns the pointer to the [OH_Drawing_PathEffect](#oh_drawing_patheffect) object created. + +If a null pointer is returned, the creation fails. The possible failure cause is that **path** is a null pointer or **advance** is less than or equal to **0**. + +### OH_Drawing_CreateDiscretePathEffect() + +``` +OH_Drawing_PathEffect* OH_Drawing_CreateDiscretePathEffect (float segLength, float deviation ) +``` + +**Description** + +Creates a path effect that segments the path and scatters the segments in an irregular pattern along the path. + +**System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing + +**Since**: 18 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| segLength | Distance along the path at which each segment is fragmented. An effect is created when it is greater than 0. | +| deviation | Maximum amount by which the end points of the segments can be randomly displaced during rendering. | + +**Returns** + +Returns the pointer to the [OH_Drawing_PathEffect](#oh_drawing_patheffect) object created. + + +### OH_Drawing_CreateCornerPathEffect() + +``` +OH_Drawing_PathEffect* OH_Drawing_CreateCornerPathEffect (float radius) +``` + +**Description** + +Creates a path effect that transforms the sharp angle between line segments into a rounded corner with the specified radius. + +**System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing + +**Since**: 18 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| radius | Radius of the rounded corner. The value is valid only when it is greater than 0. | + +**Returns** + +Returns the pointer to the [OH_Drawing_PathEffect](#oh_drawing_patheffect) object created. + +If a null pointer is returned, the creation fails. The possible failure cause is that **radius** is less than or equal to **0**. + + + +### OH_Drawing_CreateComposePathEffect() + +``` +OH_Drawing_PathEffect* OH_Drawing_CreateComposePathEffect (OH_Drawing_PathEffect* outer, OH_Drawing_PathEffect* inner ) +``` + +**Description** + +Creates a path effect by sequentially applying the inner effect and then the outer effect. + +**System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing + +**Since**: 18 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| outer | Pointer to an outer effect, which is an [OH_Drawing_PathEffect](#oh_drawing_patheffect) object. | +| inner | Pointer to an inner effect, which is an [OH_Drawing_PathEffect](#oh_drawing_patheffect) object. | + +**Returns** + +Returns the pointer to the [OH_Drawing_PathEffect](#oh_drawing_patheffect) object created. + +If a null pointer is returned, the creation fails. The possible failure cause is that **inner** or **inner** is a null pointer. + +### OH_Drawing_GpuContextCreate() + +``` +OH_Drawing_GpuContext* OH_Drawing_GpuContextCreate (void) +``` + +**Description** + +Creates an **OH_Drawing_GpuContext** object, for which the backend type depends on the device. + +**System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing + +**Since**: 16 + +**Returns** + +Returns the pointer to the [OH_Drawing_GpuContext](#oh_drawing_gpucontext) object created. + + +### OH_Drawing_CanvasDrawArcWithCenter() + +``` +OH_Drawing_ErrorCode OH_Drawing_CanvasDrawArcWithCenter (OH_Drawing_Canvas* canvas, const OH_Drawing_Rect* rect, float startAngle, float sweepAngle, bool useCenter ) +``` + +**Description** + +Draws an arc. It enables you to define the starting angle, sweep angle, and whether the arc's endpoints should connect to its center. + +**System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing + +**Since**: 18 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| canvas | Pointer to an [OH_Drawing_Canvas](#oh_drawing_canvas) object. | +| rect | Pointer to an [OH_Drawing_Rect](#oh_drawing_rect) object. | +| startAngle | Start angle, in degrees. The value is a floating point number. When the degree is 0, the start point is located at the right end of the oval. A positive number indicates that the start point is placed clockwise, and a negative number indicates that the start point is placed counterclockwise. | +| sweepAngle | Angle to sweep, in degrees. The value is a floating point number. A positive number indicates a clockwise sweep, and a negative value indicates a counterclockwise swipe. The swipe angle can exceed 360 degrees, and a complete ellipse is drawn. | +| useCenter | Whether the start point and end point of the arc are connected to its center. The value **true** means that they are connected to the center; the value **false** means the opposite. | + +**Returns** + +Returns one of the following result codes: **OH_DRAWING_SUCCESS** if the operation is successful. **OH_DRAWING_ERROR_INVALID_PARAMETER** if either **canvas** or **inner** is NULL. + +### OH_Drawing_CanvasDrawNestedRoundRect() + +``` +OH_Drawing_ErrorCode OH_Drawing_CanvasDrawNestedRoundRect (OH_Drawing_Canvas* canvas, const OH_Drawing_RoundRect* outer, const OH_Drawing_RoundRect* inner ) +``` + +**Description** + +Draws two nested rounded rectangles. The outer rectangle boundary must contain the inner rectangle boundary. Otherwise, there is no drawing effect. + +**System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing + +**Since**: 18 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| canvas | Pointer to an [OH_Drawing_Canvas](#oh_drawing_canvas) object. | +| outer | Pointer to the outer rectangle boundary, which is an [OH_Drawing_RoundRect](#oh_drawing_roundrect) object. | +| inner | Pointer to the inner rectangle boundary, which is an [OH_Drawing_RoundRect](#oh_drawing_roundrect) object. | + +**Returns** + +Returns one of the following result codes: + +- **OH_DRAWING_SUCCESS** if the operation is successful. + +- **OH_DRAWING_ERROR_INVALID_PARAMETER** if **canvas**, **outer**, or **inner** is NULL. + +### OH_Drawing_CanvasQuickRejectPath() + +``` +OH_Drawing_ErrorCode OH_Drawing_CanvasQuickRejectPath (OH_Drawing_Canvas* canvas, const OH_Drawing_Path* path, bool* quickReject ) +``` + +**Description** + + +Checks whether the path is not intersecting with the canvas area. The canvas area includes its boundaries. + +**System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing + +**Since**: 18 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| canvas | Pointer to an [OH_Drawing_Canvas](#oh_drawing_canvas) object. | +| path | Pointer to an [OH_Drawing_Path](#oh_drawing_path) object. | +| quickReject | Pointer to the check result. The value **true** means that the path is not intersecting with the canvas area, and **false** means the opposite. | + +**Returns** + +Returns one of the following result codes: + +**OH_DRAWING_SUCCESS** if the operation is successful. + +**OH_DRAWING_ERROR_INVALID_PARAMETER** if **canvas**, **path**, or **quickReject** is NULL. + +### OH_Drawing_CanvasQuickRejectRect() + +``` +OH_Drawing_ErrorCode OH_Drawing_CanvasQuickRejectRect (OH_Drawing_Canvas* canvas, const OH_Drawing_Rect* rect, bool* quickReject ) +``` + +**Description** + +Checks whether the rectangle is not intersecting with the canvas area. The canvas area includes its boundaries. + +**System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing + +**Since**: 18 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| canvas | Pointer to an [OH_Drawing_Canvas](#oh_drawing_canvas) object. | +| rect | Pointer to an [OH_Drawing_Rect](#oh_drawing_rect) object. | +| quickReject | Pointer to the check result. The value **true** means that the rectangle is not intersecting with the canvas area, and **false** means the opposite. | + +**Returns** + +Returns one of the following result codes: + +- **OH_DRAWING_SUCCESS** if the operation is successful. + +- **OH_DRAWING_ERROR_INVALID_PARAMETER** if **canvas**, **rect**, or **quickReject** is NULL. + +### OH_Drawing_CanvasDrawPixelMapNine() + +``` +OH_Drawing_ErrorCode OH_Drawing_CanvasDrawPixelMapNine (OH_Drawing_Canvas* canvas, OH_Drawing_PixelMap* pixelMap, const OH_Drawing_Rect* center, const OH_Drawing_Rect* dst, OH_Drawing_FilterMode mode ) +``` + +**Description** + +Splits a PixelMap into nine sections using two horizontal and two vertical lines: four edge sections, four corner sections, and a central section. If the four corner sections are smaller than the target rectangle, they will be drawn in the target rectangle without scaling. Otherwise, they will be scaled to fit the target rectangle. Any remaining space will be filled by stretching or compressing the other five sections to cover the entire target rectangle. + +**System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing + +**Since**: 18 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| canvas | Pointer to an [OH_Drawing_Canvas](#oh_drawing_canvas) object. | +| pixelMap | Pointer to an [OH_Drawing_PixelMap](#oh_drawing_pixelmap) object. | +| center | Pointer to the central rectangle, which is an [OH_Drawing_Rect](#oh_drawing_rect) object. It divides the image into nine sections by extending its four edges. | +| dst | Pointer to the target rectangle, which is an [OH_Drawing_Rect](#oh_drawing_rect) object. | +| mode | Filter mode. For details about available options, see [OH_Drawing_FilterMode](#oh_drawing_filtermode-1). | + +**Returns** + +Returns one of the following result codes: + +- **OH_DRAWING_SUCCESS** if the operation is successful. + +- **OH_DRAWING_ERROR_INVALID_PARAMETER** if **canvas**, **pixelMap**, or **dst** is NULL. + +### OH_Drawing_SurfaceCreateOnScreen() + +``` +OH_Drawing_Surface* OH_Drawing_SurfaceCreateOnScreen (OH_Drawing_GpuContext* gpuContext, OH_Drawing_Image_Info imageInfo, void* window ) +``` +**Description** + +Creates an **OH_Drawing_Surface** object bound to the window using the GPU context to manage the content drawn on the canvas. + +Error codes may be generated in the call. You can view the error code by calling [OH_Drawing_ErrorCodeGet](#oh_drawing_errorcodeget). **OH_DRAWING_ERROR_INVALID_PARAMETER** if **gpuContext** or **window** is NULL. + +**System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing + +**Since**: 16 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| gpuContext | Pointer to an [OH_Drawing_GpuContext](#oh_drawing_gpucontext) object. This object must be created by [OH_Drawing_GpuContextCreate](#oh_drawing_gpucontextcreate). Otherwise, the **OH_Drawing_Surface** object fails to be created. | +| imageInfo | [OH_Drawing_Image_Info](_o_h___drawing___image___info.md) object. | +| window | Pointer to the window object. | + +**Returns** + +Returns the pointer to the [OH_Drawing_Surface](#oh_drawing_surface) object created. + +### OH_Drawing_SurfaceFlush() + +``` +OH_Drawing_ErrorCode OH_Drawing_SurfaceFlush (OH_Drawing_Surface* surface) +``` + +**Description** + +Pushes the drawing content from an **OH_Drawing_Surface** object to the GPU for rendering. + +**System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing + +**Since**: 16 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| surface | Pointer to the [OH_Drawing_Surface](#oh_drawing_surface) object created. This object must be created by calling [OH_Drawing_SurfaceCreateOnScreen](#oh_drawing_surfacecreateonscreen). Otherwise, calling the current API has no effect. | + +**Returns** + +Returns one of the following result codes: + +- **OH_DRAWING_SUCCESS** if the operation is successful. + +- **OH_DRAWING_ERROR_INVALID_PARAMETER** if **surface** is NULL. + +### OH_Drawing_ErrorCodeReset() + +``` +void OH_Drawing_ErrorCodeReset (void ) +``` + +**Description** + +Resets the error code of this module to **OH_DRAWING_SUCCESS**. + +When a function that does not return an error code fails, the error code obtained through [OH_Drawing_ErrorCodeGet](#oh_drawing_errorcodeget) is reset to the corresponding error number. However, it is not reset to **OH_DRAWING_SUCCESS** for a successful operation. + +By calling this function, you can manually reset the error code to **OH_DRAWING_SUCCESS**, avoiding interference between different functions and simplifying the debugging process. + +**System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing + +**Since**: 18 ### OH_Drawing_FontSetThemeFontFollowed() @@ -3143,7 +3603,7 @@ Sets whether to follow the theme font. When **followed** is set to **true**, the **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 15 **Parameters** @@ -3170,7 +3630,7 @@ Checks whether the font follows the theme font. By default, the theme font is no **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 15 **Parameters** @@ -3214,7 +3674,7 @@ Creates a pointer to an [OH_Drawing_LineTypography](#oh_drawing_linetypography) **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -3238,7 +3698,7 @@ Releases the memory occupied by an [OH_Drawing_LineTypography](#oh_drawing_linet **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -3258,7 +3718,7 @@ Obtains the number of characters that can fit in the layout from the specified p **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -3284,7 +3744,7 @@ Creates a pointer to an **OH_Drawing_TextLine** object based on the text content **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -3310,7 +3770,7 @@ Creates a text tab object. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -3335,7 +3795,7 @@ Releases the memory occupied by a text tab object. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -3355,7 +3815,7 @@ Obtains the alignment mode of a text tab. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -3365,7 +3825,7 @@ Obtains the alignment mode of a text tab. **Returns** -Returns the alignment mode. The value 1 means right alignment, 2 means center alignment, and 0 or other values mean left alignment. +Returns the text alignment mode. The value 1 means right alignment, 2 means center alignment, and 0 or other values mean left alignment. ### OH_Drawing_GetTextTabLocation() @@ -3379,7 +3839,7 @@ Obtains the location of a text tab. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -3403,7 +3863,7 @@ Sets the alignment mode and location of a text tab. When the text alignment mode **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -3424,7 +3884,7 @@ Obtains the rectangular bounding box for each glyph in the glyph array. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -3437,8 +3897,8 @@ Obtains the rectangular bounding box for each glyph in the glyph array. **Returns** -Returns one of the following result codes: -- **OH_DRAWING_SUCCESS** if the operation is successful. +Returns one of the following result codes: +- **OH_DRAWING_SUCCESS** if the operation is successful. - **OH_DRAWING_ERROR_INVALID_PARAMETER** if **font**, **glyphs**, or **bounds** is NULL or **count** is **0**. ### OH_Drawing_FontGetPathForGlyph() @@ -3453,7 +3913,7 @@ Obtains the path of a glyph. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -3477,11 +3937,11 @@ OH_Drawing_Array* OH_Drawing_RectCreateArray (size_t size) **Description** -Creates a rectangle array object to store multiple rectangle objects. +Creates a rectangle array object to store multiple rectangle objects. When [OH_Drawing_Array](#oh_drawing_array) is no longer required, call [OH_Drawing_RectDestroyArray](#oh_drawing_rectdestroyarray) to release the pointer to the object. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -3505,7 +3965,7 @@ Obtains the size of a rectangle array, which is an [OH_Drawing_Array](#oh_drawin **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -3532,7 +3992,7 @@ Obtains the rectangle with the specified index in a rectangle array. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -3560,7 +4020,7 @@ Destroys an **OH_Drawing_Array** object and reclaims the memory occupied by the **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -3582,11 +4042,11 @@ OH_Drawing_Array* OH_Drawing_TypographyGetTextLines (OH_Drawing_Typography* typo **Description** -Obtains the array of text lines in a typography object. This array contains one or more text line objects. +Obtains the array of text lines in a typography object. This array contains one or more text line objects. When [OH_Drawing_Array](#oh_drawing_array) is no longer required, call [OH_Drawing_DestroyTextLines](#oh_drawing_destroytextlines) to release the pointer to the object. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -3610,7 +4070,7 @@ Releases the memory occupied by a text line array. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -3630,7 +4090,7 @@ Releases the memory occupied by a text line object. This is applicable only to t **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -3650,7 +4110,7 @@ Obtains the text line object with the specified index in a text line array. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -3675,7 +4135,7 @@ Obtains the number of glyphs in a text line object. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -3699,7 +4159,7 @@ Obtains the range of the text in a text line object in the entire paragraph. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -3721,7 +4181,7 @@ Obtains the array of glyph runs in a text line object. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -3731,7 +4191,7 @@ Obtains the array of glyph runs in a text line object. **Returns** -Returns the pointer to the [OH_Drawing_Array](#oh_drawing_array), which holds multiple **OH_Drawing_Run** objects. +Returns the pointer to the [OH_Drawing_Array](#oh_drawing_array), which holds multiple **OH_Drawing_Run** objects. When [OH_Drawing_Array](#oh_drawing_array) is no longer required, call [OH_Drawing_DestroyRuns](#oh_drawing_destroyruns) to release the pointer to the object. ### OH_Drawing_DestroyRuns() @@ -3745,7 +4205,7 @@ Releases the memory occupied by a glyph run array. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -3765,7 +4225,7 @@ Obtains the glyph run object with the specified index in a glyph run array. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -3790,7 +4250,7 @@ Paints a text line on the canvas with the coordinate point (x, y) as the upper l **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -3813,7 +4273,7 @@ Creates a truncated text line object. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -3840,7 +4300,7 @@ Obtains the typographic boundary of a text line object. The typographic boundary **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -3869,7 +4329,7 @@ The image boundary, equivalent to a visual boundary, is related to the font, fon **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -3879,7 +4339,7 @@ The image boundary, equivalent to a visual boundary, is related to the font, fon **Returns** -Returns the pointer to the [OH_Drawing_Rect](#oh_drawing_rect) of the text line object. +Returns the pointer to [OH_Drawing_Rect](#oh_drawing_rect) of the text line object. When [OH_Drawing_Rect](#oh_drawing_rect) is no loner required, call [OH_Drawing_RectDestroy](#oh_drawing_rectdestroy) to release the pointer to the object. ### OH_Drawing_TextLineGetTrailingSpaceWidth() @@ -3893,7 +4353,7 @@ Obtains the width of the spaces at the end of a text line object. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -3917,7 +4377,7 @@ Obtains the index of a character at the specified position in a text line object **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -3942,7 +4402,7 @@ Obtains the offset of a character with the specified index in a text line object **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -3967,7 +4427,7 @@ Enumerates the offset and index of each character in a text line object and pass **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -3988,7 +4448,7 @@ Obtains the offset of a text line object after alignment based on the alignment **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -4014,7 +4474,7 @@ Adds the decoration for a text style. Multiple decoration lines can be displayed **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -4035,7 +4495,7 @@ Removes the decoration for a text style. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -4056,7 +4516,7 @@ Obtains the text outline path. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -4065,7 +4525,7 @@ Obtains the text outline path. | font | Pointer to an [OH_Drawing_Font](#oh_drawing_font) object.| | text | Pointer to the text string.| | byteLength | Length of the text path. If the length is greater than the length of the text string, undefined behavior occurs.| -| encoding | Text encoding format. UTF-8, UTF-16, UTF-32, and glyph indices are supported.| +| encoding | Text encoding format. UTF-8, UTF-16, UTF-32, and glyph indices are supported. For details about the format, see [OH_Drawing_TextEncoding](#oh_drawing_textencoding).| | x | X coordinate of the text in the drawing area, with the origin as the start point.| | y | Y coordinate of the text in the drawing area, with the origin as the start point.| | path | Pointer to the text outline path.| @@ -4107,11 +4567,11 @@ OH_Drawing_Array* OH_Drawing_GetRunStringIndices (OH_Drawing_Run* run, int64_t s **Description** -Obtains an array of character indices for glyphs within a specified range of a run, where the indices are offsets relative to the entire paragraph. +Obtains an array of character indices of glyphs within a specified range of a run, where the indices are offsets relative to the entire paragraph. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -4119,11 +4579,11 @@ Obtains an array of character indices for glyphs within a specified range of a r | -------- | -------- | | run | Pointer to an **OH_Drawing_Run** object.| | start | Start position in the run. If a negative number is passed, a null pointer is returned.| -| length | Length of the range in the run. If the length is 0, all character indexes of the run are obtained. If the length is less than 0, a null pointer is returned.| +| length | Length of the range in the run. If the length is 0, all character indices of the run are obtained. If the length is less than 0, a null pointer is returned.| **Returns** -Returns the character index array. +Returns the pointer to a character index array, which is an [OH_Drawing_Array](#oh_drawing_array) object. When [OH_Drawing_Array](#oh_drawing_array) is no longer required, call [OH_Drawing_DestroyRunStringIndices](#oh_drawing_destroyrunstringindices) to release the pointer to the object. ### OH_Drawing_GetRunStringIndicesByIndex() @@ -4138,7 +4598,7 @@ Obtains character indices of glyphs in a run by index. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -4164,7 +4624,7 @@ Releases the pointer to a character index array object. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -4185,7 +4645,7 @@ Obtains the range of glyphs generated by a run. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -4210,7 +4670,7 @@ The typographic boundary is related to the font and font size used for typograph **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -4238,7 +4698,7 @@ Paints the text contained in a run on the canvas. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -4264,7 +4724,7 @@ The image boundary is related to characters and is equivalent to the visual boun **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -4274,7 +4734,7 @@ The image boundary is related to characters and is equivalent to the visual boun **Returns** -Returns the pointer to an [OH_Drawing_Rect](#oh_drawing_rect) object, which describes the image boundary of the run. +Returns the pointer to an [OH_Drawing_Rect](#oh_drawing_rect) object, which describes the image boundary of the run. When [OH_Drawing_Rect](#oh_drawing_rect) is no longer required, call [OH_Drawing_DestroyRunImageBounds](#oh_drawing_destroyrunimagebounds) to release the pointer to the object. ### OH_Drawing_DestroyRunImageBounds() @@ -4289,7 +4749,7 @@ Releases the pointer to an image boundary object of a run. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -4310,7 +4770,7 @@ Obtains an array of glyphs within the specified range of a run. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -4322,7 +4782,7 @@ Obtains an array of glyphs within the specified range of a run. **Returns** -Returns the pointer to an [OH_Drawing_Array](#oh_drawing_array) object, which holds the glyphs. +Returns the pointer to an [OH_Drawing_Array](#oh_drawing_array) object, which holds the glyphs. When [OH_Drawing_Array](#oh_drawing_array) is no longer required, call [OH_Drawing_DestroyRunGlyphs](#oh_drawing_destroyrunglyphs) to release the pointer to the object. ### OH_Drawing_GetRunGlyphsByIndex() @@ -4337,7 +4797,7 @@ Obtains individual glyphs in a run by index. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -4363,7 +4823,7 @@ Releases the pointer to a glyph array in a run. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -4383,7 +4843,7 @@ Obtains the positions of glyphs within the specified range of a run. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -4395,7 +4855,7 @@ Obtains the positions of glyphs within the specified range of a run. **Returns** -Returns the pointer to an [OH_Drawing_Array](#oh_drawing_array) object, which holds the glyph positions. +Returns the pointer to an [OH_Drawing_Array](#oh_drawing_array) object, which holds the glyph positions. When [OH_Drawing_Array](#oh_drawing_array) is no longer required, call [OH_Drawing_DestroyRunPositions](#oh_drawing_destroyrunpositions) to release the pointer to the object. ### OH_Drawing_GetRunPositionsByIndex() @@ -4409,7 +4869,7 @@ Obtains the positions of individual glyphs in a run by index. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -4435,7 +4895,7 @@ Releases the pointer to a glyph position array in a run. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -4455,7 +4915,7 @@ Obtains the number of glyphs in a run. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -4475,17 +4935,17 @@ OH_Drawing_FontDescriptor* OH_Drawing_MatchFontDescriptors (OH_Drawing_FontDescr **Description** -Obtains all system font descriptors that match a font descriptor. In the [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) struct, the **path** field is not used for matching, and other fields are valid only when they are not set to their default values. If all fields in [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) are set to their default values, all system font descriptors are obtained. If no matching is found, NULL is returned. +Obtains all system font descriptors that match a font descriptor. In the [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) struct, the **path** field is not used for matching, and other fields are valid only when they are not set to their default values. If all fields in [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) are set to their default values, all system font descriptors are returned. If no matching is found, NULL is returned. When [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) is no longer required, call [OH_Drawing_DestroyFontDescriptors](_drawing.md#oh_drawing_destroyfontdescriptors) to release the pointer to the object. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** | Name | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) | Pointer to [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md). You are advised to use [OH_Drawing_CreateFontDescriptor](#oh_drawing_createfontdescriptor) to obtain a valid [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) instance. If you create a [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) instance, ensure that the fields that are not used for matching are set to their default values.| +| [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) | Pointer to [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md). You are advised to use [OH_Drawing_CreateFontDescriptor](#oh_drawing_createfontdescriptor) to obtain a valid [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) instance. If you want to create an [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) instance, maintain the default values for the fields that are not used for matching| | size_t | Pointer to the number of elements in the array. | **Returns** @@ -4504,7 +4964,7 @@ Releases an array of [OH_Drawing_FontDescriptor](_o_h___drawing___font_descripto **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing -**Since**: 16 +**Since**: 18 **Parameters** @@ -4580,7 +5040,7 @@ Obtains an array of font names by font type. **Returns** -Returns the pointer to an [OH_Drawing_Array](#oh_drawing_array), which holds the font names. +Returns the pointer to an [OH_Drawing_Array](#oh_drawing_array), which holds the font names. When [OH_Drawing_Array](#oh_drawing_array) is no longer required, call [OH_Drawing_DestroySystemFontFullNames](#oh_drawing_destroysystemfontfullnames) to release the pointer to the object. ### OH_Drawing_GetFontDescriptorByFullName() @@ -4605,7 +5065,7 @@ Obtains a font descriptor based on the font name and type. System fonts, style f **Returns** -Returns the pointer to an [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) object. +Returns the pointer to an [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) object. When [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) is no longer required, call [OH_Drawing_DestroyFontDescriptor](#oh_drawing_destroyfontdescriptor) to release the pointer to the object. ### OH_Drawing_TypefaceCreateFromFileWithArguments() @@ -4742,7 +5202,7 @@ double OH_Drawing_TypographyGetLongestLineWithIndent (OH_Drawing_Typography* ) **Description** -Obtains the width of the longest line, including its indentation. You are advised to round up the return value in actual use. If the text content is empty, **0.0** is returned. +Obtains the width of the longest line of a typography object, including its indentation. This function must be called after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called. You are advised to round up the return value. If the text content is empty, **0.0** is returned. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -5226,7 +5686,7 @@ Clips a rectangle. | -------- | -------- | | canvas | Pointer to an [OH_Drawing_Canvas](#oh_drawing_canvas) object.| | region | Pointer to an [OH_Drawing_Region](#oh_drawing_region) object.| -| clipOp | Clip mode.| +| clipOp | Clip mode. For details about the available options, see [OH_Drawing_CanvasClipOp](#oh_drawing_canvasclipop).| **Returns** @@ -5255,7 +5715,7 @@ Fills the entire canvas with the specified color and blend mode. | Name| Description| | -------- | -------- | | canvas | Pointer to an [OH_Drawing_Canvas](#oh_drawing_canvas) object.| -| color | Color.| +| color | Color, represented by a 32-bit (ARGB) variable.| | blendMode | Blend mode.| **Returns** @@ -5471,8 +5931,8 @@ Creates an **OH_Drawing_ImageFilter** object with a given blur type. | Name| Description| | -------- | -------- | -| sigmaX | Deviation of the Gaussian blur to apply along the X axis.| -| sigmaY | Deviation of the Gaussian blur to apply along the Y axis.| +| sigmaX | Standard deviation of the Gaussian blur to apply along the X axis. The value must be greater than 0.| +| sigmaY | Standard deviation of the Gaussian blur to apply along the Y axis. The value must be greater than 0.| | OH_Drawing_TileMode | Tile mode of the shader effect. For details about the available options, see [OH_Drawing_TileMode](#oh_drawing_tilemode).| | input | Pointer to the filter to which the image filter will be applied. If NULL is passed in, the image filter is directly applied to the original image.| @@ -5762,9 +6222,9 @@ If any of **path**, **position**, or **tangent** is NULL, **OH_DRAWING_ERROR_INV | -------- | -------- | | path | Pointer to an [OH_Drawing_Path](#oh_drawing_path) object.| | forceClosed | Whether the path is measured as a closed path. The value **true** means that the path is considered closed during measurement, and **false** means that the path is measured based on the actual closed status.| -| distance | Distance from the start point.| +| distance | Distance from the start point. If a negative number is passed in, the value **0** is used. If a value greater than the path length is passed in, the path length is used.| | position | Pointer to the coordinates.| -| tangent | Pointer to the tangent.| +| tangent | Pointer to the tangent, where **tangent.x** and **tangent.y** represent the cosine and sine of the tangent of the point, respectively.| **Returns** @@ -5830,7 +6290,7 @@ If **flag** is not set to one of the enumerated values, **OH_DRAWING_ERROR_PARAM | -------- | -------- | | path | Pointer to an [OH_Drawing_Path](#oh_drawing_path) object.| | forceClosed | Whether the path is measured as a closed path. The value **true** means that the path is considered closed during measurement, and **false** means that the path is measured based on the actual closed status.| -| distance | Distance from the start point.| +| distance | Distance from the start point. If a negative number is passed in, the value **0** is used. If a value greater than the path length is passed in, the path length is used.| | matrix | Pointer to the transformation matrix.| | flag | Type of the matrix information. For details about the available options, see [OH_Drawing_PathMeasureMatrixFlags](#oh_drawing_pathmeasurematrixflags).| @@ -5994,8 +6454,8 @@ If either **rect** or **other** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** | Name| Description| | -------- | -------- | -| rect | Pointer to an **OH_Drawing_Rect** object.| -| other | Pointer to an **OH_Drawing_Rect** object.| +| rect | Pointer to the first rectangle, which is an **OH_Drawing_Rect** object.| +| other | Pointer to the second rectangle, which is an **OH_Drawing_Rect** object.| **Returns** @@ -6115,7 +6575,7 @@ Creates an **OH_Drawing_ShaderEffect** object with a single color. | Name| Description| | -------- | -------- | -| color | Color of the shader.| +| color | Color in the ARGB format. The value is a 32-bit unsigned integer.| **Returns** @@ -6148,7 +6608,7 @@ If **OH_Drawing_TileMode** is not set to one of the enumerated values, **OH_DRAW | -------- | -------- | | startPt | Start point.| | endPt | End point.| -| colors | Colors to distribute between the two points.| +| colors | Colors to distribute.| | pos | Relative position of each color in the color array. If **pos** is NULL, colors are evenly distributed between the start point and end point.| | size | Number of colors and positions (if **pos** is not NULL).| | OH_Drawing_TileMode | Tile mode of the shader effect. For details about the available options, see [OH_Drawing_TileMode](#oh_drawing_tilemode).| @@ -6221,9 +6681,9 @@ If **OH_Drawing_TileMode** is not set to one of the enumerated values, **OH_DRAW | Name| Description| | -------- | -------- | | startPt | Pointer to the center of the start circle.| -| startRadius | Radius of the start circle.| +| startRadius | Start radius of the gradient. The value should be a non-negative number.| | endPt | Pointer to the center of the end circle.| -| endRadius | Radius of the end circle.| +| endRadius | End radius of the gradient. The value should be a non-negative number.| | colors | Colors to distribute between the two circles.| | pos | Relative position of each color in the color array. If **pos** is NULL, colors are evenly distributed between the two circles.| | size | Number of colors and positions (if **pos** is not NULL).| @@ -6393,7 +6853,7 @@ If **OH_Drawing_Font** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is return | Name| Description| | -------- | -------- | | OH_Drawing_Font | Pointer to an [OH_Drawing_Font](#oh_drawing_font) object.| -| baselineSnap | Whether to request that baselines be snapped to pixels. The value **true** means to request that baselines be snapped to pixels, and **false** means the opposite.| +| baselineSnap | Check result. The value **true** means to request that baselines be snapped to pixels, and **false** means the opposite.| ### OH_Drawing_FontIsBaselineSnap() @@ -6422,7 +6882,7 @@ If **OH_Drawing_Font** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is return **Returns** -Returns **true** if baselines are requested to be snapped to pixels when the current canvas matrix is axis aligned; returns **false** otherwise. +Returns **true** if the baselines are requested to be snapped to pixels; returns **false** otherwise. ### OH_Drawing_FontSetEdging() @@ -6506,7 +6966,7 @@ If **OH_Drawing_Font** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is return | Name| Description| | -------- | -------- | | OH_Drawing_Font | Pointer to an [OH_Drawing_Font](#oh_drawing_font) object.| -| isForceAutoHinting | Whether to forcibly use auto hinting. The value **true** means to forcibly use auto hinting, and **false** means the opposite.| +| isForceAutoHinting | Check result. The value **true** means to forcibly use auto hinting, and **false** means the opposite.| ### OH_Drawing_FontIsForceAutoHinting() @@ -6561,7 +7021,7 @@ If **OH_Drawing_Font** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is return | Name| Description| | -------- | -------- | | OH_Drawing_Font | Pointer to an [OH_Drawing_Font](#oh_drawing_font) object.| -| isSubpixel | Whether to use sub-pixel rendering for the font. The value **true** means to use sub-pixel rendering for the font, and **false** means the opposite.| +| isSubpixel | Check result. The value **true** means to use sub-pixel rendering for the font, and **false** means the opposite.| ### OH_Drawing_FontIsSubpixel() @@ -7009,7 +7469,7 @@ If either **OH_Drawing_Image_Info** or **pixels** is NULL or **rowBytes** is **0 | -------- | -------- | | OH_Drawing_Image_Info | Pointer to an [OH_Drawing_Image_Info](_o_h___drawing___image___info.md) object.| | pixels | Pointer to the start address of the memory for storing the bitmap pixels. You need to apply for the memory and ensure its validity.| -| rowBytes | Size of pixels per row.| +| rowBytes | Number of bytes in each row of pixels. The value is invalid if it is less than or equal to 0.| **Returns** @@ -7276,9 +7736,9 @@ Destroys an **OH_Drawing_Brush** object and reclaims the memory occupied by the **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Brush | Pointer to an **OH_Drawing_Brush** object.| +| Name | Description | +| ---------------- | ------------------------------------------ | +| OH_Drawing_Brush | Pointer to an **OH_Drawing_Brush** object. | ### OH_Drawing_BrushGetAlpha() @@ -7301,9 +7761,9 @@ If **OH_Drawing_Brush** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is retur **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Brush | Pointer to an **OH_Drawing_Brush** object.| +| Name | Description | +| ---------------- | ------------------------------------------ | +| OH_Drawing_Brush | Pointer to an **OH_Drawing_Brush** object. | **Returns** @@ -7330,9 +7790,9 @@ If **OH_Drawing_Brush** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is retur **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Brush | Pointer to an **OH_Drawing_Brush** object.| +| Name | Description | +| ---------------- | ------------------------------------------ | +| OH_Drawing_Brush | Pointer to an **OH_Drawing_Brush** object. | **Returns** @@ -7359,10 +7819,10 @@ If either **OH_Drawing_Brush** or **OH_Drawing_Filter** is NULL, **OH_DRAWING_ER **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Brush | Pointer to an [OH_Drawing_Brush](#oh_drawing_brush) object.| -| OH_Drawing_Filter | Pointer to the [OH_Drawing_Filter](#oh_drawing_filter) object obtained.| +| Name | Description | +| ----------------- | ------------------------------------------------------------ | +| OH_Drawing_Brush | Pointer to an [OH_Drawing_Brush](#oh_drawing_brush) object. | +| OH_Drawing_Filter | Pointer to the [OH_Drawing_Filter](#oh_drawing_filter) object obtained. | ### OH_Drawing_BrushIsAntiAlias() @@ -7385,9 +7845,9 @@ If **OH_Drawing_Brush** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is retur **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Brush | Pointer to an **OH_Drawing_Brush** object.| +| Name | Description | +| ---------------- | ------------------------------------------ | +| OH_Drawing_Brush | Pointer to an **OH_Drawing_Brush** object. | **Returns** @@ -7414,9 +7874,9 @@ If **OH_Drawing_Brush** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is retur **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Brush | Pointer to an [OH_Drawing_Brush](#oh_drawing_brush) object.| +| Name | Description | +| ---------------- | ----------------------------------------------------------- | +| OH_Drawing_Brush | Pointer to an [OH_Drawing_Brush](#oh_drawing_brush) object. | ### OH_Drawing_BrushSetAlpha() @@ -7439,10 +7899,10 @@ If **OH_Drawing_Brush** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is retur **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Brush | Pointer to an **OH_Drawing_Brush** object.| -| alpha | Alpha value, which is an 8-bit variable.| +| Name | Description | +| ---------------- | ------------------------------------------ | +| OH_Drawing_Brush | Pointer to an **OH_Drawing_Brush** object. | +| alpha | Alpha value, which is an 8-bit variable. | ### OH_Drawing_BrushSetAntiAlias() @@ -7465,10 +7925,10 @@ If **OH_Drawing_Brush** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is retur **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Brush | Pointer to an **OH_Drawing_Brush** object.| -| bool | Whether to enable anti-aliasing. The value **true** means to enable anti-aliasing, and **false** means the opposite.| +| Name | Description | +| ---------------- | ------------------------------------------------------------ | +| OH_Drawing_Brush | Pointer to an **OH_Drawing_Brush** object. | +| bool | Whether to enable anti-aliasing. The value **true** means to enable anti-aliasing, and **false** means the opposite. | ### OH_Drawing_BrushSetBlendMode() @@ -7493,10 +7953,10 @@ If **OH_Drawing_BlendMode** is not set to one of the enumerated values, **OH_DRA **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Brush | Pointer to an [OH_Drawing_Brush](#oh_drawing_brush) object.| -| OH_Drawing_BlendMode | Blend mode. For details about the available options, see [OH_Drawing_BlendMode](#oh_drawing_blendmode).| +| Name | Description | +| -------------------- | ------------------------------------------------------------ | +| OH_Drawing_Brush | Pointer to an [OH_Drawing_Brush](#oh_drawing_brush) object. | +| OH_Drawing_BlendMode | Blend mode. For details about the available options, see [OH_Drawing_BlendMode](#oh_drawing_blendmode). | ### OH_Drawing_BrushSetColor() @@ -7519,10 +7979,10 @@ If **OH_Drawing_Brush** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is retur **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Brush | Pointer to an **OH_Drawing_Brush** object.| -| color | Color, which is a 32-bit (ARGB) variable.| +| Name | Description | +| ---------------- | ------------------------------------------ | +| OH_Drawing_Brush | Pointer to an **OH_Drawing_Brush** object. | +| color | Color, which is a 32-bit (ARGB) variable. | ### OH_Drawing_BrushSetFilter() @@ -7545,10 +8005,10 @@ If **OH_Drawing_Brush** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is retur **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Brush | Pointer to an **OH_Drawing_Brush** object.| -| OH_Drawing_Filter | Pointer to an **OH_Drawing_Filter** object. If null is passed in, the filter will be cleared.| +| Name | Description | +| ----------------- | ------------------------------------------------------------ | +| OH_Drawing_Brush | Pointer to an **OH_Drawing_Brush** object. | +| OH_Drawing_Filter | Pointer to an **OH_Drawing_Filter** object. If null is passed in, the filter will be cleared. | ### OH_Drawing_BrushSetShaderEffect() @@ -7571,10 +8031,10 @@ If **OH_Drawing_Brush** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is retur **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Brush | Pointer to an **OH_Drawing_Brush** object.| -| OH_Drawing_ShaderEffect | Pointer to an **OH_Drawing_ShaderEffect** object. If NULL is passed in, the shader effect of the brush will be cleared.| +| Name | Description | +| ----------------------- | ------------------------------------------------------------ | +| OH_Drawing_Brush | Pointer to an **OH_Drawing_Brush** object. | +| OH_Drawing_ShaderEffect | Pointer to an **OH_Drawing_ShaderEffect** object. If NULL is passed in, the shader effect of the brush will be cleared. | ### OH_Drawing_CanvasAttachBrush() @@ -7585,7 +8045,7 @@ void OH_Drawing_CanvasAttachBrush (OH_Drawing_Canvas* , const OH_Drawing_Brush* **Description** -Attaches a brush to a canvas so that the canvas can use the style and color of the brush to fill in a shape. +Attaches a brush to a canvas so that the canvas can use the style and color of the brush to fill in a shape. If the brush effect changes after this function is called, you must call the function again to use the new effect in the subsequent drawing. Error codes may be generated in the call. You can view the error code by calling [OH_Drawing_ErrorCodeGet](#oh_drawing_errorcodeget). @@ -7597,10 +8057,10 @@ If either **OH_Drawing_Canvas** or **OH_Drawing_Brush** is NULL, **OH_DRAWING_ER **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object.| -| OH_Drawing_Brush | Pointer to an **OH_Drawing_Brush** object.| +| Name | Description | +| ----------------- | ------------------------------------------- | +| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object. | +| OH_Drawing_Brush | Pointer to an **OH_Drawing_Brush** object. | ### OH_Drawing_CanvasAttachPen() @@ -7611,7 +8071,7 @@ void OH_Drawing_CanvasAttachPen (OH_Drawing_Canvas* , const OH_Drawing_Pen* ) **Description** -Attaches a pen to a canvas so that the canvas can use the style and color of the pen to outline a shape. +Attaches a pen to a canvas so that the canvas can use the style and color of the pen to outline a shape. If the pen effect changes after this function is called, you must call the function again to use the new effect in the subsequent drawing. Error codes may be generated in the call. You can view the error code by calling [OH_Drawing_ErrorCodeGet](#oh_drawing_errorcodeget). @@ -7623,10 +8083,10 @@ If either **OH_Drawing_Canvas** or **OH_Drawing_Pen** is NULL, **OH_DRAWING_ERRO **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object.| -| OH_Drawing_Pen | Pointer to an **OH_Drawing_Pen** object.| +| Name | Description | +| ----------------- | ------------------------------------------- | +| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object. | +| OH_Drawing_Pen | Pointer to an **OH_Drawing_Pen** object. | ### OH_Drawing_CanvasBind() @@ -7649,10 +8109,10 @@ If either **OH_Drawing_Canvas** or **OH_Drawing_Bitmap** is NULL, **OH_DRAWING_E **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object.| -| OH_Drawing_Bitmap | Pointer to an **OH_Drawing_Bitmap** object.| +| Name | Description | +| ----------------- | ------------------------------------------- | +| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object. | +| OH_Drawing_Bitmap | Pointer to an **OH_Drawing_Bitmap** object. | ### OH_Drawing_CanvasClear() @@ -7675,10 +8135,10 @@ If **OH_Drawing_Canvas** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is retu **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object.| -| color | Color, which is a 32-bit (ARGB) variable.| +| Name | Description | +| ----------------- | ------------------------------------------- | +| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object. | +| color | Color, which is a 32-bit (ARGB) variable. | ### OH_Drawing_CanvasClipPath() @@ -7703,12 +8163,12 @@ If **clipOp** is not set to one of the enumerated values, **OH_DRAWING_ERROR_PAR **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object.| -| OH_Drawing_Path | Pointer to an **OH_Drawing_Path** object.| -| clipOp | Clip mode. For details about the available options, see [OH_Drawing_CanvasClipOp](#oh_drawing_canvasclipop).| -| doAntiAlias | Whether to enable anti-aliasing. The value **true** means to enable anti-aliasing, and **false** means the opposite.| +| Name | Description | +| ----------------- | ------------------------------------------------------------ | +| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object. | +| OH_Drawing_Path | Pointer to an **OH_Drawing_Path** object. | +| clipOp | Clip mode. For details about the available options, see [OH_Drawing_CanvasClipOp](#oh_drawing_canvasclipop). | +| doAntiAlias | Whether to enable anti-aliasing. The value **true** means to enable anti-aliasing, and **false** means the opposite. | ### OH_Drawing_CanvasClipRect() @@ -7733,12 +8193,12 @@ If **clipOp** is not set to one of the enumerated values, **OH_DRAWING_ERROR_PAR **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object.| -| OH_Drawing_Rect | Pointer to an **OH_Drawing_Rect** object.| -| clipOp | Clip mode. For details about the available options, see [OH_Drawing_CanvasClipOp](#oh_drawing_canvasclipop).| -| doAntiAlias | Whether to enable anti-aliasing. The value **true** means to enable anti-aliasing, and **false** means the opposite.| +| Name | Description | +| ----------------- | ------------------------------------------------------------ | +| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object. | +| OH_Drawing_Rect | Pointer to an **OH_Drawing_Rect** object. | +| clipOp | Clip mode. For details about the available options, see [OH_Drawing_CanvasClipOp](#oh_drawing_canvasclipop). | +| doAntiAlias | Whether to enable anti-aliasing. The value **true** means to enable anti-aliasing, and **false** means the opposite. | ### OH_Drawing_CanvasClipRoundRect() @@ -7762,12 +8222,12 @@ If **clipOp** is not set to one of the enumerated values, **OH_DRAWING_ERROR_PAR **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object.| -| OH_Drawing_RoundRect | Pointer to an **OH_Drawing_RoundRect** object.| -| clipOp | Clip mode. For details about the available options, see [OH_Drawing_CanvasClipOp](#oh_drawing_canvasclipop).| -| doAntiAlias | Whether to perform anti-aliasing. The value **true** means to perform anti-aliasing, and **false** means the opposite.| +| Name | Description | +| -------------------- | ------------------------------------------------------------ | +| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object. | +| OH_Drawing_RoundRect | Pointer to an **OH_Drawing_RoundRect** object. | +| clipOp | Clip mode. For details about the available options, see [OH_Drawing_CanvasClipOp](#oh_drawing_canvasclipop). | +| doAntiAlias | Whether to perform anti-aliasing. The value **true** means to perform anti-aliasing, and **false** means the opposite. | ### OH_Drawing_CanvasConcatMatrix() @@ -7789,10 +8249,10 @@ If either **OH_Drawing_Canvas** or **OH_Drawing_Matrix** is NULL, **OH_DRAWING_E **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an [OH_Drawing_Canvas](#oh_drawing_canvas) object.| -| OH_Drawing_Matrix | Pointer to an [OH_Drawing_Matrix](#oh_drawing_matrix) object.| +| Name | Description | +| ----------------- | ------------------------------------------------------------ | +| OH_Drawing_Canvas | Pointer to an [OH_Drawing_Canvas](#oh_drawing_canvas) object. | +| OH_Drawing_Matrix | Pointer to an [OH_Drawing_Matrix](#oh_drawing_matrix) object. | ### OH_Drawing_CanvasCreate() @@ -7830,9 +8290,9 @@ Destroys an **OH_Drawing_Canvas** object and reclaims the memory occupied by the **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object.| +| Name | Description | +| ----------------- | ------------------------------------------- | +| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object. | ### OH_Drawing_CanvasDetachBrush() @@ -7855,9 +8315,9 @@ If **OH_Drawing_Canvas** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is retu **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object.| +| Name | Description | +| ----------------- | ------------------------------------------- | +| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object. | ### OH_Drawing_CanvasDetachPen() @@ -7880,9 +8340,9 @@ If **OH_Drawing_Canvas** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is retu **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object.| +| Name | Description | +| ----------------- | ------------------------------------------- | +| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object. | ### OH_Drawing_CanvasDrawArc() @@ -7893,7 +8353,7 @@ void OH_Drawing_CanvasDrawArc (OH_Drawing_Canvas* , const OH_Drawing_Rect* , flo **Description** -Draws an arc. +Draws an arc. If the absolute value of the sweep angle exceeds 360 degrees, an ellipse is drawn. Error codes may be generated in the call. You can view the error code by calling [OH_Drawing_ErrorCodeGet](#oh_drawing_errorcodeget). @@ -7905,12 +8365,12 @@ If either **OH_Drawing_Canvas** or **OH_Drawing_Rect** is NULL, **OH_DRAWING_ERR **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object.| -| OH_Drawing_Rect | Pointer to an **OH_Drawing_Rect** object.| -| startAngle | Start angle of the arc.| -| sweepAngle | Sweep angle of the arc.| +| Name | Description | +| ----------------- | ------------------------------------------------------------ | +| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object. | +| OH_Drawing_Rect | Pointer to an **OH_Drawing_Rect** object. | +| startAngle | Start angle. When the degree is 0, the start point is located at the right end of the oval. A positive number indicates that the start point is placed clockwise, and a negative number indicates that the start point is placed counterclockwise. | +| sweepAngle | Angle to sweep, in degrees. A positive number indicates a clockwise sweep, and a negative value indicates a counterclockwise swipe. The valid range is from -360 degrees to 360 degrees. If the absolute value of the sweep angle exceeds 360 degrees, an ellipse is drawn. | ### OH_Drawing_CanvasDrawBackground() @@ -7933,10 +8393,10 @@ If either **OH_Drawing_Canvas** or **OH_Drawing_Brush** is NULL, **OH_DRAWING_ER **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object.| -| OH_Drawing_Brush | Pointer to an **OH_Drawing_Brush** object.| +| Name | Description | +| ----------------- | ------------------------------------------- | +| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object. | +| OH_Drawing_Brush | Pointer to an **OH_Drawing_Brush** object. | ### OH_Drawing_CanvasDrawBitmap() @@ -7959,12 +8419,12 @@ If either **OH_Drawing_Canvas** or **OH_Drawing_Bitmap** is NULL, **OH_DRAWING_E **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object.| -| OH_Drawing_Bitmap | Pointer to an **OH_Drawing_Bitmap** object.| -| left | X coordinate of the upper left corner of the bitmap.| -| top | Y coordinate of the upper left corner of the bitmap.| +| Name | Description | +| ----------------- | ---------------------------------------------------- | +| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object. | +| OH_Drawing_Bitmap | Pointer to an **OH_Drawing_Bitmap** object. | +| left | X coordinate of the upper left corner of the bitmap. | +| top | Y coordinate of the upper left corner of the bitmap. | ### OH_Drawing_CanvasDrawBitmapRect() @@ -7987,13 +8447,13 @@ If any of **OH_Drawing_Canvas**, **OH_Drawing_Bitmap**, and **dst** is NULL, **O **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an [OH_Drawing_Canvas](#oh_drawing_canvas) object.| -| OH_Drawing_Bitmap | Pointer to an [OH_Drawing_Bitmap](#oh_drawing_bitmap) object.| -| src | Pointer to a rectangle on the bitmap. If NULL is passed in, it refers to the entire bitmap.| -| dst | Pointer to a rectangle on the canvas.| -| OH_Drawing_SamplingOptions | Pointer to an [OH_Drawing_SamplingOptions](#oh_drawing_samplingoptions) object. If NULL is passed in, the default sampling options are used.| +| Name | Description | +| -------------------------- | ------------------------------------------------------------ | +| OH_Drawing_Canvas | Pointer to an [OH_Drawing_Canvas](#oh_drawing_canvas) object. | +| OH_Drawing_Bitmap | Pointer to an [OH_Drawing_Bitmap](#oh_drawing_bitmap) object. | +| src | Pointer to a rectangle on the bitmap. If NULL is passed in, it refers to the entire bitmap. | +| dst | Pointer to a rectangle on the canvas. | +| OH_Drawing_SamplingOptions | Pointer to an [OH_Drawing_SamplingOptions](#oh_drawing_samplingoptions) object. If NULL is passed in, the default sampling options are used. | ### OH_Drawing_CanvasDrawCircle() @@ -8018,11 +8478,11 @@ If **radius** is less than or equal to 0, **OH_DRAWING_ERROR_PARAMETER_OUT_OF_RA **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object.| -| OH_Drawing_Point | Pointer to an **OH_Drawing_Point** object, which indicates the center of the circle.| -| radius | Radius of the circle.| +| Name | Description | +| ----------------- | ------------------------------------------------------------ | +| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object. | +| OH_Drawing_Point | Pointer to an **OH_Drawing_Point** object, which indicates the center of the circle. | +| radius | Radius of the circle. The value is invalid if it is less than or equal to 0. | ### OH_Drawing_CanvasDrawImageRect() @@ -8045,12 +8505,12 @@ If any of **OH_Drawing_Canvas**, **OH_Drawing_Image**, and **dst** is NULL, **OH **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an [OH_Drawing_Canvas](#oh_drawing_canvas) object.| -| OH_Drawing_Image | Pointer to an [OH_Drawing_Image](#oh_drawing_image) object.| -| dst | Pointer to an [OH_Drawing_Rect](#oh_drawing_rect) object.| -| OH_Drawing_SamplingOptions | Pointer to an [OH_Drawing_SamplingOptions](#oh_drawing_samplingoptions) object. If NULL is passed in, the default sampling options are used.| +| Name | Description | +| -------------------------- | ------------------------------------------------------------ | +| OH_Drawing_Canvas | Pointer to an [OH_Drawing_Canvas](#oh_drawing_canvas) object. | +| OH_Drawing_Image | Pointer to an [OH_Drawing_Image](#oh_drawing_image) object. | +| dst | Pointer to an [OH_Drawing_Rect](#oh_drawing_rect) object. | +| OH_Drawing_SamplingOptions | Pointer to an [OH_Drawing_SamplingOptions](#oh_drawing_samplingoptions) object. If NULL is passed in, the default sampling options are used. | ### OH_Drawing_CanvasDrawImageRectWithSrc() @@ -8073,14 +8533,14 @@ If any of **OH_Drawing_Canvas**, **OH_Drawing_Image**, **src**, and **dst** is N **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an [OH_Drawing_Canvas](#oh_drawing_canvas) object.| -| OH_Drawing_Image | Pointer to an [OH_Drawing_Image](#oh_drawing_image) object.| -| src | Pointer to a source rectangle, which is an [OH_Drawing_Rect](#oh_drawing_rect) object.| -| dst | Pointer to a destination rectangle, which is an [OH_Drawing_Rect](#oh_drawing_rect) object.| -| OH_Drawing_SamplingOptions | Pointer to an [OH_Drawing_SamplingOptions](#oh_drawing_samplingoptions) object. If NULL is passed in, the default sampling options are used.| -| OH_Drawing_SrcRectConstraint | Constraint type. For details about the available options, see [OH_Drawing_SrcRectConstraint](#oh_drawing_srcrectconstraint-1).| +| Name | Description | +| ---------------------------- | ------------------------------------------------------------ | +| OH_Drawing_Canvas | Pointer to an [OH_Drawing_Canvas](#oh_drawing_canvas) object. | +| OH_Drawing_Image | Pointer to an [OH_Drawing_Image](#oh_drawing_image) object. | +| src | Pointer to a source rectangle, which is an [OH_Drawing_Rect](#oh_drawing_rect) object. | +| dst | Pointer to a destination rectangle, which is an [OH_Drawing_Rect](#oh_drawing_rect) object. | +| OH_Drawing_SamplingOptions | Pointer to an [OH_Drawing_SamplingOptions](#oh_drawing_samplingoptions) object. If NULL is passed in, the default sampling options are used. | +| OH_Drawing_SrcRectConstraint | Constraint type. For details about the available options, see [OH_Drawing_SrcRectConstraint](#oh_drawing_srcrectconstraint-1). | ### OH_Drawing_CanvasDrawLine() @@ -8103,13 +8563,13 @@ If **OH_Drawing_Canvas** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is retu **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object.| -| x1 | X coordinate of the start point of the line segment.| -| y1 | Y coordinate of the start point of the line segment.| -| x2 | X coordinate of the end point of the line segment.| -| y2 | Y coordinate of the end point of the line segment.| +| Name | Description | +| ----------------- | ---------------------------------------------------- | +| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object. | +| x1 | X coordinate of the start point of the line segment. | +| y1 | Y coordinate of the start point of the line segment. | +| x2 | X coordinate of the end point of the line segment. | +| y2 | Y coordinate of the end point of the line segment. | ### OH_Drawing_CanvasDrawOval() @@ -8132,10 +8592,10 @@ If either **OH_Drawing_Canvas** or **OH_Drawing_Rect** is NULL, **OH_DRAWING_ERR **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object.| -| OH_Drawing_Rect | Pointer to an **OH_Drawing_Rect** object.| +| Name | Description | +| ----------------- | ------------------------------------------- | +| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object. | +| OH_Drawing_Rect | Pointer to an **OH_Drawing_Rect** object. | ### OH_Drawing_CanvasDrawPath() @@ -8158,10 +8618,10 @@ If either **OH_Drawing_Canvas** or **OH_Drawing_Path** is NULL, **OH_DRAWING_ERR **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object.| -| OH_Drawing_Path | Pointer to an **OH_Drawing_Path** object.| +| Name | Description | +| ----------------- | ------------------------------------------- | +| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object. | +| OH_Drawing_Path | Pointer to an **OH_Drawing_Path** object. | ### OH_Drawing_CanvasDrawPixelMapRect() @@ -8184,13 +8644,13 @@ If any of **OH_Drawing_Canvas**, **OH_Drawing_PixelMap**, and **dst** is NULL, * **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an [OH_Drawing_Canvas](#oh_drawing_canvas) object.| -| OH_Drawing_PixelMap | Pointer to an [OH_Drawing_PixelMap](#oh_drawing_pixelmap) object.| -| src | Pointer to a rectangle on the pixel map. If NULL is passed in, it refers to the entire pixel map.| -| dst | Pointer to a rectangle on the canvas.| -| OH_Drawing_SamplingOptions | Pointer to an [OH_Drawing_SamplingOptions](#oh_drawing_samplingoptions) object. If NULL is passed in, the default sampling options are used.| +| Name | Description | +| -------------------------- | ------------------------------------------------------------ | +| OH_Drawing_Canvas | Pointer to an [OH_Drawing_Canvas](#oh_drawing_canvas) object. | +| OH_Drawing_PixelMap | Pointer to an [OH_Drawing_PixelMap](#oh_drawing_pixelmap) object. | +| src | Pointer to a rectangle on the pixel map. If NULL is passed in, it refers to the entire pixel map. | +| dst | Pointer to a rectangle on the canvas. | +| OH_Drawing_SamplingOptions | Pointer to an [OH_Drawing_SamplingOptions](#oh_drawing_samplingoptions) object. If NULL is passed in, the default sampling options are used. | ### OH_Drawing_CanvasDrawPoints() @@ -8215,12 +8675,12 @@ If **mode** is not set to one of the enumerated values, **OH_DRAWING_ERROR_PARAM **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object.| -| mode | Mode of drawing multiple points. For details about the available options, see [OH_Drawing_PointMode](#oh_drawing_pointmode).| -| count | Number of vertices, that is, the number of vertices in the vertex array.| -| [OH_Drawing_Point2D](_o_h___drawing___point2_d.md) | Pointer to an array holding the vertices.| +| Name | Description | +| -------------------------------------------------- | ------------------------------------------------------------ | +| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object. | +| mode | Mode of drawing multiple points. For details about the available options, see [OH_Drawing_PointMode](#oh_drawing_pointmode). | +| count | Number of vertices, that is, the number of vertices in the vertex array. | +| [OH_Drawing_Point2D](_o_h___drawing___point2_d.md) | Pointer to an array holding the vertices. | ### OH_Drawing_CanvasDrawRect() @@ -8243,10 +8703,10 @@ If either **OH_Drawing_Canvas** or **OH_Drawing_Rect** is NULL, **OH_DRAWING_ERR **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object.| -| OH_Drawing_Rect | Pointer to an **OH_Drawing_Rect** object.| +| Name | Description | +| ----------------- | ------------------------------------------- | +| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object. | +| OH_Drawing_Rect | Pointer to an **OH_Drawing_Rect** object. | ### OH_Drawing_CanvasDrawRegion() @@ -8269,10 +8729,10 @@ If either **OH_Drawing_Canvas** or **OH_Drawing_Region** is NULL, **OH_DRAWING_E **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object.| -| OH_Drawing_Region | Pointer to an **OH_Drawing_Region** object.| +| Name | Description | +| ----------------- | ------------------------------------------- | +| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object. | +| OH_Drawing_Region | Pointer to an **OH_Drawing_Region** object. | ### OH_Drawing_CanvasDrawRoundRect() @@ -8295,10 +8755,10 @@ If either **OH_Drawing_Canvas** or **OH_Drawing_RoundRect** is NULL, **OH_DRAWIN **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object.| -| OH_Drawing_RoundRect | Pointer to an **OH_Drawing_RoundRect** object.| +| Name | Description | +| -------------------- | ---------------------------------------------- | +| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object. | +| OH_Drawing_RoundRect | Pointer to an **OH_Drawing_RoundRect** object. | ### OH_Drawing_CanvasDrawShadow() @@ -8323,16 +8783,16 @@ If **flag** is not set to one of the enumerated values, **OH_DRAWING_ERROR_PARAM **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an [OH_Drawing_Canvas](#oh_drawing_canvas) object.| -| OH_Drawing_Path | Pointer to an [OH_Drawing_Path](#oh_drawing_path) object, which is used to generate the shadow.| -| planeParams | Value of the function that returns the Z axis of the occluding object from the canvas based on the X axis and Y axis.| -| devLightPos | Position of the light relative to the canvas.| -| lightRadius | Radius of the light.| -| ambientColor | Color of the ambient shadow.| -| spotColor | Color of the spot shadow.| -| flag | Shadow flag. For details about the available options, see [OH_Drawing_CanvasShadowFlags](#oh_drawing_canvasshadowflags).| +| Name | Description | +| ----------------- | ------------------------------------------------------------ | +| OH_Drawing_Canvas | Pointer to an [OH_Drawing_Canvas](#oh_drawing_canvas) object. | +| OH_Drawing_Path | Pointer to an [OH_Drawing_Path](#oh_drawing_path) object, which is used to generate the shadow. | +| planeParams | Z-axis offset of an occluder relative to the canvas, based on its x and y coordinates. | +| devLightPos | Position of the light relative to the canvas. | +| lightRadius | Radius of the light source. The value must be greater than or equal to 0. | +| ambientColor | Ambient shadow color, which is a 32-bit (ARGB) variable. | +| spotColor | Point shadow color, which is a 32-bit (ARGB) variable. | +| flag | Shadow flag. For details about the available options, see [OH_Drawing_CanvasShadowFlags](#oh_drawing_canvasshadowflags). | ### OH_Drawing_CanvasDrawTextBlob() @@ -8355,12 +8815,12 @@ If either **OH_Drawing_Canvas** or **OH_Drawing_TextBlob** is NULL, **OH_DRAWING **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object.| -| OH_Drawing_TextBlob | Pointer to an **OH_Drawing_TextBlob** object.| -| x | X coordinate of the lower left corner of the text blob.| -| y | Y coordinate of the lower left corner of the text blob.| +| Name | Description | +| ------------------- | ------------------------------------------------------- | +| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object. | +| OH_Drawing_TextBlob | Pointer to an **OH_Drawing_TextBlob** object. | +| x | X coordinate of the lower left corner of the text blob. | +| y | Y coordinate of the lower left corner of the text blob. | ### OH_Drawing_CanvasDrawVertices() @@ -8385,17 +8845,17 @@ If either **vertexMmode** or **mode** is not set to one of the enumerated values **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object.| -| vertexMmode | Vertex drawing mode. For details about the available options, see [OH_Drawing_VertexMode](#oh_drawing_vertexmode).| -| vertexCount | Number of elements in the vertex array. The value must be greater than or equal to 3.| -| positions | Pointer to the array that holds the position of every vertex. The array cannot be null and its length must be equal to the value of **vertexCount**.| -| texs | Pointer to the array that holds the texture space coordinate corresponding to each vertex. The array can be null. If the array is not null, its length must be equal to the value of **vertexCount**.| -| colors | Pointer to the array that holds the color corresponding to each vertex. It is used for interpolation in a triangle. The array can be null. If the array is not null, its length must be equal to the value of **vertexCount**.| -| indexCount | Number of indexes. The value can be 0 or a value greater than or equal to 3.| -| indices | Pointer to the array that holds the index of each vertex. The array can be null. If the array is not null, its length must be equal to the value of **indexCount**.| -| mode | Blend mode. For details about the available options, see [OH_Drawing_BlendMode](#oh_drawing_blendmode).| +| Name | Description | +| ----------------- | ------------------------------------------------------------ | +| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object. | +| vertexMmode | Vertex drawing mode. For details about the available options, see [OH_Drawing_VertexMode](#oh_drawing_vertexmode). | +| vertexCount | Number of elements in the vertex array. The value must be greater than or equal to 3. | +| positions | Pointer to the array that holds the position of every vertex. The array cannot be null and its length must be equal to the value of **vertexCount**. | +| texs | Pointer to the array that holds the texture space coordinate corresponding to each vertex. The array can be null. If the array is not null, its length must be equal to the value of **vertexCount**. | +| colors | Pointer to the array that holds the color corresponding to each vertex. It is used for interpolation in a triangle. The array can be null. If the array is not null, its length must be equal to the value of **vertexCount**. | +| indexCount | Number of indices. The value can be 0 or a value greater than or equal to 3. | +| indices | Pointer to the array that holds the index of each vertex. The array can be null. If the array is not null, its length must be equal to the value of **indexCount**. | +| mode | Blend mode. For details about the available options, see [OH_Drawing_BlendMode](#oh_drawing_blendmode). | ### OH_Drawing_CanvasGetHeight() @@ -8418,9 +8878,9 @@ If **OH_Drawing_Canvas** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is retu **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an [OH_Drawing_Canvas](#oh_drawing_canvas) object.| +| Name | Description | +| ----------------- | ------------------------------------------------------------ | +| OH_Drawing_Canvas | Pointer to an [OH_Drawing_Canvas](#oh_drawing_canvas) object. | **Returns** @@ -8447,10 +8907,10 @@ If either **OH_Drawing_Canvas** or **OH_Drawing_Rect** is NULL, **OH_DRAWING_ERR **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an [OH_Drawing_Canvas](#oh_drawing_canvas) object.| -| OH_Drawing_Rect | Pointer to an [OH_Drawing_Rect](#oh_drawing_rect) object, which is obtained by calling [OH_Drawing_RectCreate](#oh_drawing_rectcreate).| +| Name | Description | +| ----------------- | ------------------------------------------------------------ | +| OH_Drawing_Canvas | Pointer to an [OH_Drawing_Canvas](#oh_drawing_canvas) object. | +| OH_Drawing_Rect | Pointer to an [OH_Drawing_Rect](#oh_drawing_rect) object, which is obtained by calling [OH_Drawing_RectCreate](#oh_drawing_rectcreate). | ### OH_Drawing_CanvasGetSaveCount() @@ -8473,9 +8933,9 @@ If **OH_Drawing_Canvas** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is retu **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object.| +| Name | Description | +| ----------------- | ------------------------------------------- | +| OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object. | **Returns** @@ -8502,10 +8962,10 @@ If either **OH_Drawing_Canvas** or **OH_Drawing_Matrix** is NULL, **OH_DRAWING_E **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an [OH_Drawing_Canvas](#oh_drawing_canvas) object.| -| OH_Drawing_Matrix | Pointer to an [OH_Drawing_Matrix](#oh_drawing_matrix) object, which is obtained by calling [OH_Drawing_MatrixCreate](#oh_drawing_matrixcreate).| +| Name | Description | +| ----------------- | ------------------------------------------------------------ | +| OH_Drawing_Canvas | Pointer to an [OH_Drawing_Canvas](#oh_drawing_canvas) object. | +| OH_Drawing_Matrix | Pointer to an [OH_Drawing_Matrix](#oh_drawing_matrix) object, which is obtained by calling [OH_Drawing_MatrixCreate](#oh_drawing_matrixcreate). | ### OH_Drawing_CanvasGetWidth() @@ -8528,9 +8988,9 @@ If **OH_Drawing_Canvas** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is retu **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an [OH_Drawing_Canvas](#oh_drawing_canvas) object.| +| Name | Description | +| ----------------- | ------------------------------------------------------------ | +| OH_Drawing_Canvas | Pointer to an [OH_Drawing_Canvas](#oh_drawing_canvas) object. | **Returns** @@ -8557,14 +9017,14 @@ If any of **OH_Drawing_Canvas**, **OH_Drawing_Image_Info**, and **dstPixels** is **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an [OH_Drawing_Canvas](#oh_drawing_canvas) object.| -| [OH_Drawing_Image_Info](_o_h___drawing___image___info.md) | Pointer to an [OH_Drawing_Image_Info](_o_h___drawing___image___info.md) object.| -| dstPixels | Pointer to the start address for storing the pixel data.| -| dstRowBytes | Size of pixels per row.| -| srcX | X offset of the pixels on the canvas, in px.| -| srcY | Y offset of the pixels on the canvas, in px.| +| Name | Description | +| --------------------------------------------------------- | ------------------------------------------------------------ | +| OH_Drawing_Canvas | Pointer to an [OH_Drawing_Canvas](#oh_drawing_canvas) object. | +| [OH_Drawing_Image_Info](_o_h___drawing___image___info.md) | Pointer to an [OH_Drawing_Image_Info](_o_h___drawing___image___info.md) object. | +| dstPixels | Pointer to the start address for storing the pixel data. | +| dstRowBytes | Number of bytes in each row of pixels. The value is invalid if it is less than or equal to 0. | +| srcX | X offset of the pixels on the canvas, in px. | +| srcY | Y offset of the pixels on the canvas, in px. | **Returns** @@ -8591,12 +9051,12 @@ If either **OH_Drawing_Canvas** or **OH_Drawing_Bitmap** is NULL, **OH_DRAWING_E **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an [OH_Drawing_Canvas](#oh_drawing_canvas) object.| -| OH_Drawing_Bitmap | Pointer to an [OH_Drawing_Bitmap](#oh_drawing_bitmap) object.| -| srcX | X offset of the pixels on the canvas, in px.| -| srcY | Y offset of the pixels on the canvas, in px.| +| Name | Description | +| ----------------- | ------------------------------------------------------------ | +| OH_Drawing_Canvas | Pointer to an [OH_Drawing_Canvas](#oh_drawing_canvas) object. | +| OH_Drawing_Bitmap | Pointer to an [OH_Drawing_Bitmap](#oh_drawing_bitmap) object. | +| srcX | X offset of the pixels on the canvas, in px. | +| srcY | Y offset of the pixels on the canvas, in px. | **Returns** @@ -8623,9 +9083,9 @@ If **OH_Drawing_Canvas** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is retu **Parameters** -| Name| Description| -| -------- | -------- | -| OH_Drawing_Canvas | Pointer to an [OH_Drawing_Canvas](#oh_drawing_canvas) object.| +| Name | Description | +| ----------------- | ------------------------------------------------------------ | +| OH_Drawing_Canvas | Pointer to an [OH_Drawing_Canvas](#oh_drawing_canvas) object. | ### OH_Drawing_CanvasRestore() @@ -8687,7 +9147,7 @@ void OH_Drawing_CanvasRotate (OH_Drawing_Canvas* , float degrees, float px, floa **Description** -Rotates a canvas by a given angle. A positive value indicates a clockwise rotation, and a negative value indicates a counterclockwise rotation. +Rotates a canvas by a given angle. A positive number indicates a clockwise rotation, and a negative number indicates a counterclockwise rotation. Error codes may be generated in the call. You can view the error code by calling [OH_Drawing_ErrorCodeGet](#oh_drawing_errorcodeget). @@ -8703,8 +9163,8 @@ If **OH_Drawing_Canvas** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is retu | ----------------- | ------------------------------------------- | | OH_Drawing_Canvas | Pointer to an **OH_Drawing_Canvas** object. | | degrees | Angle to rotate. | -| px | X coordinate of the rotation point. | -| py | Y coordinate of the rotation point. | +| px | X coordinate of the rotation center. | +| py | Y coordinate of the rotation center. | ### OH_Drawing_CanvasSave() @@ -8715,7 +9175,7 @@ void OH_Drawing_CanvasSave (OH_Drawing_Canvas* ) **Description** -Saves the current canvas status (canvas matrix) to the top of the stack. +Saves the current canvas status (canvas matrix) to the top of the stack. This function must be used in pair with [OH_Drawing_CanvasRestore](#oh_drawing_canvasrestore). Error codes may be generated in the call. You can view the error code by calling [OH_Drawing_ErrorCodeGet](#oh_drawing_errorcodeget). @@ -9212,7 +9672,7 @@ OH_Drawing_FontCollection* OH_Drawing_CreateSharedFontCollection (void ) **Description** -Creates an [OH_Drawing_FontCollection](#oh_drawing_fontcollection) object that is shareable. +Creates an [OH_Drawing_FontCollection](#oh_drawing_fontcollection) object. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -9250,7 +9710,7 @@ OH_Drawing_TextShadow* OH_Drawing_CreateTextShadow (void ) **Description** -Creates an **OH_Drawing_TextShadow** object. +Creates an **OH_Drawing_TextShadow** object. When [OH_Drawing_TextShadow](#oh_drawing_textshadow) is no longer required, call [OH_Drawing_DestroyTextShadow](#oh_drawing_destroytextshadow) to release the pointer to the object. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -9288,7 +9748,7 @@ OH_Drawing_Typography* OH_Drawing_CreateTypography (OH_Drawing_TypographyCreate* **Description** -Creates an **OH_Drawing_Typography** object. +Creates an **OH_Drawing_Typography** object. When [OH_Drawing_Typography](#oh_drawing_typography) is no longer required, call [OH_Drawing_DestroyTypography](#oh_drawing_destroytypography) to release the pointer to the object. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -9298,7 +9758,7 @@ Creates an **OH_Drawing_Typography** object. | Name | Description | | --------------------------- | ------------------------------------------------------------ | -| OH_Drawing_TypographyCreate | Pointer to an **OH_Drawing_TypographyCreate** object. The pointer is obtained by [OH_Drawing_CreateTypographyHandler](#oh_drawing_createtypographyhandler). | +| OH_Drawing_TypographyCreate | Pointer to an [OH_Drawing_TypographyCreate](#oh_drawing_typographycreate) object. The pointer is obtained by calling [OH_Drawing_CreateTypographyHandler](#oh_drawing_createtypographyhandler). | **Returns** @@ -9313,7 +9773,7 @@ OH_Drawing_TypographyCreate* OH_Drawing_CreateTypographyHandler (OH_Drawing_Typo **Description** -Creates an **OH_Drawing_TypographyCreate** object. +Creates an **OH_Drawing_TypographyCreate** object. When [OH_Drawing_TypographyCreate](#oh_drawing_typographycreate) is no longer required, call [OH_Drawing_DestroyTypographyHandler](#oh_drawing_destroytypographyhandler) to release the pointer to the object. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -9323,8 +9783,8 @@ Creates an **OH_Drawing_TypographyCreate** object. | Name | Description | | -------------------------- | ------------------------------------------------------------ | -| OH_Drawing_TypographyStyle | Pointer to an **OH_Drawing_TypographyStyle** object, which is obtained by calling [OH_Drawing_CreateTypographyStyle](#oh_drawing_createtypographystyle). | -| OH_Drawing_FontCollection | Pointer to an **OH_Drawing_FontCollection** object, which is obtained by calling [OH_Drawing_CreateFontCollection](#oh_drawing_createfontcollection) or [OH_Drawing_CreateSharedFontCollection](#oh_drawing_createsharedfontcollection) (recommended). | +| OH_Drawing_TypographyStyle | Pointer to an [OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) object, which is obtained by calling [OH_Drawing_CreateTypographyStyle](#oh_drawing_createtypographystyle). | +| OH_Drawing_FontCollection | Pointer to an [OH_Drawing_FontCollection](#oh_drawing_fontcollection) object, which is obtained by calling [OH_Drawing_CreateFontCollection](#oh_drawing_createfontcollection) or [OH_Drawing_CreateSharedFontCollection](#oh_drawing_createsharedfontcollection) (recommended). | **Returns** @@ -9339,7 +9799,7 @@ OH_Drawing_TypographyStyle* OH_Drawing_CreateTypographyStyle (void ) **Description** -Creates an **OH_Drawing_TypographyStyle** object. +Creates an **OH_Drawing_TypographyStyle** object. When [OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) is no longer required, call [OH_Drawing_DestroyTypographyStyle](#oh_drawing_destroytypographystyle) to release the pointer to the object. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -9389,7 +9849,7 @@ Destroys an **OH_Drawing_FontDescriptor** object and reclaims the memory occupie | Name | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) | Pointer to an [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) object, which is obtained by calling [OH_Drawing_CreateFontDescriptor](#oh_drawing_createfontdescriptor). | +| [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) | Pointer to a [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) object, which is obtained by calling [OH_Drawing_CreateFontDescriptor](#oh_drawing_createfontdescriptor). | ### OH_Drawing_DestroyFontParser() @@ -9558,7 +10018,7 @@ Destroys an **OH_Drawing_Typography** object and reclaims the memory occupied by | Name | Description | | --------------------- | ------------------------------------------------------------ | -| OH_Drawing_Typography | Pointer to an **OH_Drawing_Typography** object, which is obtained by calling [OH_Drawing_CreateTypography](#oh_drawing_createtypography). | +| OH_Drawing_Typography | Pointer to an [OH_Drawing_Typography](#oh_drawing_typography) object, which is obtained by calling [OH_Drawing_CreateTypography](#oh_drawing_createtypography). | ### OH_Drawing_DestroyTypographyHandler() @@ -9579,7 +10039,7 @@ Destroys an **OH_Drawing_TypographyCreate** object and reclaims the memory occup | Name | Description | | --------------------------- | ------------------------------------------------------------ | -| OH_Drawing_TypographyCreate | Pointer to an **OH_Drawing_TypographyCreate** object. The pointer is obtained by [OH_Drawing_CreateTypographyHandler](#oh_drawing_createtypographyhandler). | +| OH_Drawing_TypographyCreate | Pointer to an [OH_Drawing_TypographyCreate](#oh_drawing_typographycreate) object. The pointer is obtained by calling [OH_Drawing_CreateTypographyHandler](#oh_drawing_createtypographyhandler). | ### OH_Drawing_DestroyTypographyStyle() @@ -9600,7 +10060,7 @@ Destroys an **OH_Drawing_TypographyStyle** object and reclaims the memory occupi | Name | Description | | -------------------------- | ------------------------------------------------------------ | -| OH_Drawing_TypographyStyle | Pointer to an **OH_Drawing_TypographyStyle** object, which is obtained by calling [OH_Drawing_CreateTypographyStyle](#oh_drawing_createtypographystyle). | +| OH_Drawing_TypographyStyle | Pointer to an [OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) object, which is obtained by calling [OH_Drawing_CreateTypographyStyle](#oh_drawing_createtypographystyle). | ### OH_Drawing_DisableFontCollectionFallback() @@ -9611,7 +10071,7 @@ void OH_Drawing_DisableFontCollectionFallback (OH_Drawing_FontCollection* fontCo **Description** -Disables the alternate fonts. +Disables the system fonts. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -9898,7 +10358,7 @@ OH_Drawing_FontMgr* OH_Drawing_FontMgrCreate (void ) **Description** -Creates an **OH_Drawing_FontMgr** object. +Creates an **OH_Drawing_FontMgr** object, which can be used only to manage system fonts. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -10046,7 +10506,7 @@ Obtains the font family name based on an index. **Returns** -Returns the font family name. +Returns the font family name. When the font family name is no longer required, call [OH_Drawing_FontMgrDestroyFamilyName](#oh_drawing_fontmgrdestroyfamilyname) to release the pointer to the object. ### OH_Drawing_FontMgrMatchFamily() @@ -10072,7 +10532,7 @@ Obtains a font style set based on a font family name. **Returns** -Returns the pointer to the [OH_Drawing_FontStyleSet](#oh_drawing_fontstyleset) object obtained. +Returns the pointer to an [OH_Drawing_FontStyleSet](#oh_drawing_fontstyleset) object. When the object is no longer required, call [OH_Drawing_FontMgrDestroyFontStyleSet](#oh_drawing_fontmgrdestroyfontstyleset) to release the pointer to the object. ### OH_Drawing_FontMgrMatchFamilyStyle() @@ -10099,7 +10559,7 @@ Obtains a typeface based on the font style information and font family name. **Returns** -Returns the pointer to the [OH_Drawing_Typeface](#oh_drawing_typeface) object obtained. +Returns the pointer to an [OH_Drawing_Typeface](#oh_drawing_typeface) object. When the object is no longer required, call [OH_Drawing_TypefaceDestroy](#oh_drawing_typefacedestroy) to release the pointer to the object. ### OH_Drawing_FontMgrMatchFamilyStyleCharacter() @@ -10110,7 +10570,7 @@ OH_Drawing_Typeface* OH_Drawing_FontMgrMatchFamilyStyleCharacter (OH_Drawing_Fon **Description** -Obtains a typeface for the specified character. +Obtains a typeface for the specified character. A null pointer is returned only when no typeface corresponding to the input UTF-8 character is found in the **OH_Drawing_FontMgr** object. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -10155,7 +10615,7 @@ Obtains the descriptor of a system font based on the font name. **Returns** -Returns the system font. +Returns the system font description object. When the object is no longer required, call [OH_Drawing_DestroyFontParser](#oh_drawing_destroyfontparser) to release the pointer to the object. ### OH_Drawing_FontParserGetSystemFontList() @@ -10166,7 +10626,7 @@ char** OH_Drawing_FontParserGetSystemFontList (OH_Drawing_FontParser* , size_t* **Description** -Obtains the list of system fonts. This function can be used only on 2-in-1 devices. +Obtains the list of system fonts. This function can be used only on 2-in-1 devices and phones. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -10233,7 +10693,7 @@ If **OH_Drawing_Font** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is return | Name | Description | | --------------- | ------------------------------------------------------------ | | OH_Drawing_Font | Pointer to an **OH_Drawing_Font** object. | -| isLinearText | Whether to enable linear scaling. The value **true** means to enable linear scaling, and **false** means the opposite. | +| isLinearText | Whether to set linear scaling. The value **true** means to set linear scaling, and **false** means the opposite. | ### OH_Drawing_FontSetTextSize() @@ -10256,10 +10716,10 @@ If **OH_Drawing_Font** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is return **Parameters** -| Name | Description | -| --------------- | ----------------------------------------- | -| OH_Drawing_Font | Pointer to an **OH_Drawing_Font** object. | -| textSize | Font size. | +| Name | Description | +| --------------- | ------------------------------------------------------------ | +| OH_Drawing_Font | Pointer to an **OH_Drawing_Font** object. | +| textSize | Text size. The value is a floating point number. If a negative number is passed in, the size is set to 0. If the size is 0, the text drawn will not be displayed. | ### OH_Drawing_FontSetTextSkewX() @@ -10296,7 +10756,7 @@ void OH_Drawing_FontSetTypeface (OH_Drawing_Font* , OH_Drawing_Typeface* ) **Description** -Sets the typeface for a font. +Sets a typeface for a font. Error codes may be generated in the call. You can view the error code by calling [OH_Drawing_ErrorCodeGet](#oh_drawing_errorcodeget). @@ -10664,7 +11124,7 @@ Obtains the system font configuration. **Returns** -Returns the pointer to the system font configuration. +Returns the pointer to the system font configuration. When it is no longer required, call [OH_Drawing_DestroySystemFontConfigInfo](#oh_drawing_destroysystemfontconfiginfo) to release the pointer to the object. ### OH_Drawing_GetTextDirectionFromTextBox() @@ -10685,7 +11145,7 @@ Obtains the text direction of a text box. | Name | Description | | ------------------ | ------------------------------------------------------------ | -| OH_Drawing_TextBox | Pointer to an **OH_Drawing_TextBox** object, which is obtained by calling [OH_Drawing_TypographyGetRectsForRange](#oh_drawing_typographygetrectsforrange) or [OH_Drawing_TypographyGetRectsForPlaceholders](#oh_drawing_typographygetrectsforplaceholders). | +| OH_Drawing_TextBox | Pointer to an [OH_Drawing_TextBox](#oh_drawing_textbox) object, which is obtained by calling [OH_Drawing_TypographyGetRectsForRange](#oh_drawing_typographygetrectsforrange) or [OH_Drawing_TypographyGetRectsForPlaceholders](#oh_drawing_typographygetrectsforplaceholders). | | int | Index of the text box. | **Returns** @@ -10952,7 +11412,7 @@ OH_Drawing_MaskFilter* OH_Drawing_MaskFilterCreateBlur (OH_Drawing_BlurType blur **Description** -Creates an **OH_Drawing_MaskFilter** object with a given blur type. +Creates an **OH_Drawing_MaskFilter** object with a blur type. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -11056,7 +11516,7 @@ Creates an **OH_Drawing_Matrix** with the rotation attribute. The matrix is obta | Name | Description | | ---- | ------------------------------------------------------------ | -| deg | Angle to rotate, in degrees. A positive value indicates a clockwise rotation, and a negative value indicates a counterclockwise rotation. | +| deg | Angle to rotate, in degrees. A positive number indicates a clockwise rotation, and a negative number indicates a counterclockwise rotation. | | x | Coordinate point on the X axis. | | y | Coordinate point on the Y axis. | @@ -11081,12 +11541,12 @@ Creates an **OH_Drawing_Matrix** with the scale attribute. The matrix is obtaine **Parameters** -| Name | Description | -| ---- | ------------------------------- | -| sx | Scale factor on the X axis. | -| sy | Scale factor on the Y axis. | -| px | Coordinate point on the X axis. | -| py | Coordinate point on the Y axis. | +| Name | Description | +| ---- | ------------------------------------------------------------ | +| sx | Scale coefficient along the X axis. If a negative number is passed in, the matrix is mirrored around y = px before being scaled. The value is a floating point number. | +| sy | Scale coefficient along the Y axis. If a negative number is passed in, the matrix is mirrored around x = py before being scaled. The value is a floating point number. | +| px | Coordinate point on the X axis. | +| py | Coordinate point on the Y axis. | **Returns** @@ -11109,10 +11569,10 @@ Creates an **OH_Drawing_Matrix** with the translation attribute. The matrix is o **Parameters** -| Name | Description | -| ---- | ------------------------------------ | -| dx | Distance to translate on the X axis. | -| dy | Distance to translate on the Y axis. | +| Name | Description | +| ---- | ------------------------------------------------------------ | +| dx | Distance to translate on the X axis. A positive number indicates a translation towards the positive direction of the X axis, and a negative number indicates a translation towards the negative direction of the X axis. The value is a floating point number. | +| dy | Distance to translate on the Y axis. A positive number indicates a translation towards the positive direction of the Y axis, and a negative number indicates a translation towards the negative direction of the Y axis. The value is a floating point number. | **Returns** @@ -11284,7 +11744,7 @@ If **OH_Drawing_Matrix** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is retu | Name | Description | | ----------------- | ------------------------------------------------------------ | | OH_Drawing_Matrix | Pointer to an [OH_Drawing_Matrix](#oh_drawing_matrix) object. | -| degree | Angle to rotate, in degrees. A positive value indicates a clockwise rotation, and a negative value indicates a counterclockwise rotation. | +| degree | Angle to rotate, in degrees. A positive number indicates a clockwise rotation, and a negative number indicates a counterclockwise rotation. | | px | X coordinate of the rotation point. | | py | Y coordinate of the rotation point. | @@ -11313,8 +11773,8 @@ If **OH_Drawing_Matrix** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is retu | Name | Description | | ----------------- | ------------------------------------------------------------ | | OH_Drawing_Matrix | Pointer to an [OH_Drawing_Matrix](#oh_drawing_matrix) object. | -| sx | Scale factor on the X axis. | -| sy | Scale factor on the Y axis. | +| sx | Scale factor on the X axis. If a negative number is passed in, the matrix is mirrored around y = px before being scaled. The value is a floating point number. | +| sy | Scale factor on the Y axis. If a negative number is passed in, the matrix is mirrored around x = py before being scaled. The value is a floating point number. | | px | X coordinate of the scale point. | | py | Y coordinate of the scale point. | @@ -11371,7 +11831,7 @@ If **OH_Drawing_Matrix** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is retu | Name | Description | | ----------------- | ------------------------------------------------------------ | | OH_Drawing_Matrix | Pointer to an [OH_Drawing_Matrix](#oh_drawing_matrix) object. | -| degree | Angle to rotate, in degrees. A positive value indicates a clockwise rotation, and a negative value indicates a counterclockwise rotation. | +| degree | Angle to rotate, in degrees. A positive number indicates a clockwise rotation, and a negative number indicates a counterclockwise rotation. | | px | X coordinate of the rotation point. | | py | Y coordinate of the rotation point. | @@ -11400,8 +11860,8 @@ If **OH_Drawing_Matrix** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is retu | Name | Description | | ----------------- | ------------------------------------------------------------ | | OH_Drawing_Matrix | Pointer to an [OH_Drawing_Matrix](#oh_drawing_matrix) object. | -| sx | Scale factor on the X axis. | -| sy | Scale factor on the Y axis. | +| sx | Scale factor on the X axis. If a negative number is passed in, the matrix is mirrored around y = px before being scaled. The value is a floating point number. | +| sy | Scale factor on the Y axis. If a negative number is passed in, the matrix is mirrored around x = py before being scaled. The value is a floating point number. | | px | X coordinate of the scale point. | | py | Y coordinate of the scale point. | @@ -11481,7 +11941,7 @@ If **OH_Drawing_Matrix** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is retu | Name | Description | | ----------------- | ------------------------------------------------------------ | | OH_Drawing_Matrix | Pointer to an [OH_Drawing_Matrix](#oh_drawing_matrix) object. | -| degree | Angle to rotate, in degrees. A positive value indicates a clockwise rotation, and a negative value indicates a counterclockwise rotation. | +| degree | Angle to rotate, in degrees. A positive number indicates a clockwise rotation, and a negative number indicates a counterclockwise rotation. | | px | Coordinate point on the X axis. | | py | Coordinate point on the Y axis. | @@ -11509,8 +11969,8 @@ If **OH_Drawing_Matrix** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is retu | Name | Description | | ----------------- | ------------------------------------------------------------ | | OH_Drawing_Matrix | Pointer to an [OH_Drawing_Matrix](#oh_drawing_matrix) object. | -| sx | Scale factor on the X axis. | -| sy | Scale factor on the Y axis. | +| sx | Scale factor on the X axis. If a negative number is passed in, the matrix is mirrored around y = px before being scaled. The value is a floating point number. | +| sy | Scale factor on the Y axis. If a negative number is passed in, the matrix is mirrored around x = py before being scaled. The value is a floating point number. | | px | Coordinate point on the X axis. | | py | Coordinate point on the Y axis. | @@ -11612,7 +12072,7 @@ If any of **OH_Drawing_Matrix**, **src**, and **dst** is NULL, OH_DRAWING_ERROR_ **Returns** -Returns **true** if the operation is successful; returns **false** if the operation fails; returns **true** and sets the matrix to |0 0 0| |0 0 0| |0 0 1| if the passed-in matrix is empty. +Returns **true** if the operation is successful; returns **false** if the operation fails. In particular, if either the width or the height of the source rectangle is less than or equal to 0, the function returns **false** and sets the matrix to an identity matrix. If either the width or height of the destination rectangle is less than or equal to 0, the function returns **true** and sets the matrix to a matrix with all values 0, except for a perspective scaling coefficient of 1. ### OH_Drawing_MatrixTranslate() @@ -11637,8 +12097,8 @@ If **OH_Drawing_Matrix** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is retu | Name | Description | | ----------------- | ------------------------------------------------------------ | | OH_Drawing_Matrix | Pointer to an [OH_Drawing_Matrix](#oh_drawing_matrix) object. | -| dx | Distance to translate on the X axis. | -| dy | Distance to translate on the Y axis. | +| dx | Distance to translate on the X axis. A positive number indicates a translation towards the positive direction of the X axis, and a negative number indicates a translation towards the negative direction of the X axis. The value is a floating point number. | +| dy | Distance to translate on the Y axis. A positive number indicates a translation towards the positive direction of the Y axis, and a negative number indicates a translation towards the negative direction of the Y axis. The value is a floating point number. | ### OH_Drawing_MemoryStreamCreate() @@ -11903,7 +12363,7 @@ void OH_Drawing_PathAddRect (OH_Drawing_Path* , float left, float top, float rig **Description** -Adds a rectangle contour to a path in the specified direction. +Adds a rectangle to a path in the specified direction. The start point is the upper left corner of the rectangle. Error codes may be generated in the call. You can view the error code by calling [OH_Drawing_ErrorCodeGet](#oh_drawing_errorcodeget). @@ -11965,7 +12425,7 @@ void OH_Drawing_PathAddRoundRect (OH_Drawing_Path* , const OH_Drawing_RoundRect* **Description** -Adds a rounded rectangle to a path in the specified direction. +Adds a rounded rectangle contour to a path in the specified direction. When the path direction is clockwise, the start point is at the intersection of the rounded rectangle's left boundary and its lower left corner. When the path direction is counterclockwise, the start point is at the intersection point between the left boundary and the upper left corner. Error codes may be generated in the call. You can view the error code by calling [OH_Drawing_ErrorCodeGet](#oh_drawing_errorcodeget). @@ -12247,7 +12707,7 @@ If **OH_Drawing_Path** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is return | Name | Description | | --------------- | ------------------------------------------------------------ | | OH_Drawing_Path | Pointer to an [OH_Drawing_Path](#oh_drawing_path) object. | -| forceClosed | Whether the path can be modified or deleted freely after the function is called. The value **true** means that the path can be modified or deleted freely, and **false** means the opposite. | +| forceClosed | Whether the path is measured as a closed path. The value **true** means that the path is considered closed during measurement, and **false** means that the path is measured based on the actual closed status. | **Returns** @@ -12501,8 +12961,8 @@ If **OH_Drawing_Path** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is return | Name | Description | | --------------- | ------------------------------------------------------------ | | OH_Drawing_Path | Pointer to an [OH_Drawing_Path](#oh_drawing_path) object. | -| x | X offset relative to the last point, which is used to specify the X coordinate of the start point. | -| y | Y offset relative to the last point, which is used to specify the Y coordinate of the start point. | +| x | X offset of the target point relative to the last point. A positive number indicates a rightward shift from the last point, and a negative number indicates a leftward shift from the last point. The value is a floating point number. | +| y | Y offset of the target point relative to the last point. A positive number indicates an upward shift from the last point, and a negative number indicates a downward shift from the last point. The value is a floating point number. | ### OH_Drawing_PathRQuadTo() @@ -12542,7 +13002,7 @@ void OH_Drawing_PathSetFillType (OH_Drawing_Path* , OH_Drawing_PathFillType ) **Description** -Sets the fill type for a path. +Sets the fill type of a path. The fill type determines how "inside" of the path is drawn. For example, when the fill type **Winding** is used, "inside" of the path is determined by a non-zero sum of signed edge crossings. When **EvenOdd** is used, "inside" of the path is determined by an odd number of edge crossings. Error codes may be generated in the call. You can view the error code by calling [OH_Drawing_ErrorCodeGet](#oh_drawing_errorcodeget). @@ -12570,7 +13030,7 @@ void OH_Drawing_PathTransform (OH_Drawing_Path* , const OH_Drawing_Matrix* ) **Description** -Transforms the points in a path by a matrix. +Transforms the points in a path by matrix. Error codes may be generated in the call. You can view the error code by calling [OH_Drawing_ErrorCodeGet](#oh_drawing_errorcodeget). @@ -13378,7 +13838,7 @@ If **OH_Drawing_Rect** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is return **Returns** -Returns the height. +Returns the height of the rectangle, in pixels. ### OH_Drawing_RectGetLeft() @@ -13494,7 +13954,7 @@ If **OH_Drawing_Rect** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is return **Returns** -Returns the width. +Returns the weight of the rectangle, in pixels. ### OH_Drawing_RectIntersect() @@ -13776,11 +14236,11 @@ If **OH_Drawing_Rect** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is return **Parameters** -| Name | Description | -| --------------- | ------------------------------------------- | -| OH_Drawing_Rect | Pointer to an **OH_Drawing_Rect** object. | -| xRad | Radius of the rounded corner on the X axis. | -| yRad | Radius of the rounded corner on the Y axis. | +| Name | Description | +| --------------- | ------------------------------------------------------------ | +| OH_Drawing_Rect | Pointer to an **OH_Drawing_Rect** object. | +| xRad | Radius of the rounded corner on the X axis. A negative number is invalid. | +| yRad | Radius of the rounded corner on the Y axis. A negative number is invalid. | **Returns** @@ -13862,7 +14322,7 @@ If **OH_Drawing_RoundRect** is NULL, **OH_DRAWING_ERROR_INVALID_PARAMETER** is r | ----------------------- | ------------------------------------------------------------ | | OH_Drawing_RoundRect | Pointer to an **OH_Drawing_RoundRect** object. | | pos | Position of the rounded corner. For details about the available options, see [OH_Drawing_CornerPos](#oh_drawing_cornerpos). | -| OH_Drawing_Corner_Radii | [OH_Drawing_Corner_Radii](#oh_drawing_corner_radii) struct, including the radii on the X axis and Y axis. | +| OH_Drawing_Corner_Radii | [OH_Drawing_Corner_Radii](#oh_drawing_corner_radii) struct, including the radii on the X axis and Y axis. The value must be greater than or equal to 0. | ### OH_Drawing_SamplingOptionsCreate() @@ -14012,7 +14472,7 @@ void OH_Drawing_SetTextStyleDecoration (OH_Drawing_TextStyle* , int ) **Description** -Sets the decoration for a text style. +Sets the decoration for a text style. Only one decoration can be set. To add multiple decorations, use [OH_Drawing_AddTextStyleDecoration](#oh_drawing_addtextstyledecoration). **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -14155,8 +14615,8 @@ Sets the font families for a text style. | Name | Description | | -------------------- | ------------------------------------------------------------ | | OH_Drawing_TextStyle | Pointer to an **OH_Drawing_TextStyle** object, which is obtained by calling [OH_Drawing_CreateTextStyle](#oh_drawing_createtextstyle). | -| int | Number of font families. | -| char | Pointer to the font families. | +| int | Number of font families. A negative number is not allowed. | +| char* | Pointer to the font families. | ### OH_Drawing_SetTextStyleFontHeight() @@ -14206,7 +14666,7 @@ Sets the font size for a text style. ### OH_Drawing_SetTextStyleFontStyle() ``` -void OH_Drawing_SetTextStyleFontStyle (OH_Drawing_TextStyle* , int ) +void OH_Drawing_SetTextStyleFontStyle (OH_Drawing_TextStyle* , int) ``` **Description** @@ -14250,7 +14710,7 @@ Sets the font style, including the font weight, width, and slant, for a text sty ### OH_Drawing_SetTextStyleFontWeight() ``` -void OH_Drawing_SetTextStyleFontWeight (OH_Drawing_TextStyle* , int ) +void OH_Drawing_SetTextStyleFontWeight (OH_Drawing_TextStyle* , int) ``` **Description** @@ -14409,7 +14869,7 @@ void OH_Drawing_SetTypographyStyleFontStyleStruct (OH_Drawing_TypographyStyle* d **Description** -Sets the font style, including the font weight, width, and slant, for a typography style. +Sets the font style, including the font weight, width, and slant, for the default text style of a typography style. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -14463,7 +14923,7 @@ Sets the text alignment mode. | Name | Description | | -------------------------- | ------------------------------------------------------------ | -| OH_Drawing_TypographyStyle | Pointer to an **OH_Drawing_TypographyStyle** object, which is obtained by calling [OH_Drawing_CreateTypographyStyle](#oh_drawing_createtypographystyle). | +| OH_Drawing_TypographyStyle | Pointer to an [OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) object, which is obtained by calling [OH_Drawing_CreateTypographyStyle](#oh_drawing_createtypographystyle). | | int | Text alignment mode. For details about the available options, see [OH_Drawing_TextAlign](#oh_drawing_textalign). | @@ -14485,7 +14945,7 @@ Sets the text break strategy. | Name | Description | | -------------------------- | ------------------------------------------------------------ | -| OH_Drawing_TypographyStyle | Pointer to an **OH_Drawing_TypographyStyle** object, which is obtained by calling [OH_Drawing_CreateTypographyStyle](#oh_drawing_createtypographystyle). | +| OH_Drawing_TypographyStyle | Pointer to an [OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) object, which is obtained by calling [OH_Drawing_CreateTypographyStyle](#oh_drawing_createtypographystyle). | | int | Text break strategy. For details about the available options, see [OH_Drawing_BreakStrategy](#oh_drawing_breakstrategy). | @@ -14497,7 +14957,7 @@ void OH_Drawing_SetTypographyTextDirection (OH_Drawing_TypographyStyle* , int ) **Description** -Sets the text direction. +Sets the text direction in a typography style. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -14507,7 +14967,7 @@ Sets the text direction. | Name | Description | | -------------------------- | ------------------------------------------------------------ | -| OH_Drawing_TypographyStyle | Pointer to an **OH_Drawing_TypographyStyle** object, which is obtained by calling [OH_Drawing_CreateTypographyStyle](#oh_drawing_createtypographystyle). | +| OH_Drawing_TypographyStyle | Pointer to an [OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) object, which is obtained by calling [OH_Drawing_CreateTypographyStyle](#oh_drawing_createtypographystyle). | | int | Text direction. For details about the available options, see [OH_Drawing_TextDirection](#oh_drawing_textdirection). | @@ -14519,7 +14979,7 @@ void OH_Drawing_SetTypographyTextEllipsis (OH_Drawing_TypographyStyle* style, co **Description** -Sets the text ellipsis content. +Sets the ellipsis text for a typography style. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -14530,18 +14990,18 @@ Sets the text ellipsis content. | Name | Description | | -------------------------- | ------------------------------------------------------------ | | OH_Drawing_TypographyStyle | Pointer to an [OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) object, which is obtained by calling [OH_Drawing_CreateTypographyStyle](#oh_drawing_createtypographystyle). | -| char | Pinter to the ellipsis content. | +| char | Pinter to an ellipsis style. | ### OH_Drawing_SetTypographyTextEllipsisModal() ``` -void OH_Drawing_SetTypographyTextEllipsisModal (OH_Drawing_TypographyStyle* , int ) +void OH_Drawing_SetTypographyTextEllipsisModal (OH_Drawing_TypographyStyle* , int) ``` **Description** -Sets the text ellipsis style. +Sets the text ellipsis style for a typography style. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -14624,12 +15084,12 @@ Sets the font size for text. ### OH_Drawing_SetTypographyTextFontStyle() ``` -void OH_Drawing_SetTypographyTextFontStyle (OH_Drawing_TypographyStyle* , int ) +void OH_Drawing_SetTypographyTextFontStyle (OH_Drawing_TypographyStyle* , int) ``` **Description** -Sets the font style for text. +Sets the default font style for a typography style. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -14646,12 +15106,12 @@ Sets the font style for text. ### OH_Drawing_SetTypographyTextFontWeight() ``` -void OH_Drawing_SetTypographyTextFontWeight (OH_Drawing_TypographyStyle* , int ) +void OH_Drawing_SetTypographyTextFontWeight (OH_Drawing_TypographyStyle* , int) ``` **Description** -Sets the font weight for text. Currently, only the default system font supports font weight adjustment. For other fonts, if the weight is less than semi-bold, there is no variation in stroke thickness. If the weight is greater than or equal to semi-bold, it might result in a fake bold effect. +Sets the default font weight for a typography style. Currently, only the default system font supports font weight adjustment. For other fonts, if the weight is less than semi-bold, there is no variation in stroke thickness. If the weight is greater than or equal to semi-bold, it might result in a fake bold effect. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -14762,7 +15222,7 @@ void OH_Drawing_SetTypographyTextLineStyleFontStyle (OH_Drawing_TypographyStyle* **Description** -Sets the font style for a text line style. +Sets the font style of the strut style in a typography style. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -14779,12 +15239,12 @@ Sets the font style for a text line style. ### OH_Drawing_SetTypographyTextLineStyleFontWeight() ``` -void OH_Drawing_SetTypographyTextLineStyleFontWeight (OH_Drawing_TypographyStyle* , int ) +void OH_Drawing_SetTypographyTextLineStyleFontWeight (OH_Drawing_TypographyStyle* , int) ``` **Description** -Sets the font weight for a text line style. Currently, only the default system font supports font weight adjustment. For other fonts, if the weight is less than semi-bold, there is no variation in stroke thickness. If the weight is greater than or equal to semi-bold, it might result in a fake bold effect. +Sets the text font weight of the strut style in a typography style. Currently, only the default system font supports font weight adjustment. For other fonts, if the weight is less than semi-bold, there is no variation in stroke thickness. If the weight is greater than or equal to semi-bold, it might result in a fake bold effect. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -14806,7 +15266,7 @@ void OH_Drawing_SetTypographyTextLineStyleHalfLeading (OH_Drawing_TypographyStyl **Description** -Sets whether to enable half leading for a text line style. +Sets whether to enable half leading for the strut style in a typography style. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -14850,7 +15310,7 @@ void OH_Drawing_SetTypographyTextLineStyleSpacingScale (OH_Drawing_TypographySty **Description** -Sets the spacing scale factor for a text line style. +Sets the spacing ratio of the text line style. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -14872,7 +15332,7 @@ void OH_Drawing_SetTypographyTextLocale (OH_Drawing_TypographyStyle* style, cons **Description** -Sets the locale for text. +Sets the locale for a typography style. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -14904,7 +15364,7 @@ Sets the maximum number of lines in the text. | Name | Description | | -------------------------- | ------------------------------------------------------------ | -| OH_Drawing_TypographyStyle | Pointer to an **OH_Drawing_TypographyStyle** object, which is obtained by calling [OH_Drawing_CreateTypographyStyle](#oh_drawing_createtypographystyle). | +| OH_Drawing_TypographyStyle | Pointer to an [OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) object, which is obtained by calling [OH_Drawing_CreateTypographyStyle](#oh_drawing_createtypographystyle). | | int | Maximum number of lines. | ### OH_Drawing_SetTypographyTextSplitRatio() @@ -14970,7 +15430,7 @@ Sets whether to enable the text line style. | Name | Description | | -------------------------- | ------------------------------------------------------------ | | OH_Drawing_TypographyStyle | Pointer to an [OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) object, which is obtained by calling [OH_Drawing_CreateTypographyStyle](#oh_drawing_createtypographystyle). | -| bool | Whether to enable the text line style. The value **true** means to enable the text line style, and **false** means the opposite. | +| bool | Whether to enable the line style. The value **true** means to enable the line style, and **false** means the opposite. | ### OH_Drawing_SetTypographyTextWordBreakType() @@ -14991,7 +15451,7 @@ Sets the word break type. | Name | Description | | -------------------------- | ------------------------------------------------------------ | -| OH_Drawing_TypographyStyle | Pointer to an **OH_Drawing_TypographyStyle** object, which is obtained by calling [OH_Drawing_CreateTypographyStyle](#oh_drawing_createtypographystyle). | +| OH_Drawing_TypographyStyle | Pointer to an [OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) object, which is obtained by calling [OH_Drawing_CreateTypographyStyle](#oh_drawing_createtypographystyle). | | int | Word break type. For details about the available options, see [OH_Drawing_WordBreakType](#oh_drawing_wordbreaktype). | @@ -15091,7 +15551,7 @@ If **OH_Drawing_TileMode** is not set to one of the enumerated values, **OH_DRAW | Name | Description | | ------------------- | ------------------------------------------------------------ | | centerPt | Center of the circle. | -| radius | Radius of the circle. | +| radius | Circle radius of the gradient. The value should be a non-negative number. | | colors | Colors to distribute in the radial direction. | | pos | Relative position of each color in the color array. If **pos** is NULL, colors are evenly distributed in the radial direction. | | size | Number of colors and positions (if **pos** is not NULL). | @@ -15561,7 +16021,7 @@ void OH_Drawing_TextStyleClearFontFeature (OH_Drawing_TextStyle* ) **Description** -Clears all the contents in a font feature map container. +Clears all the contents in a font feature map container of a text style. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -15598,12 +16058,12 @@ Clears all shadows in a text shadow container. ### OH_Drawing_TextStyleDestroyFontFamilies() ``` -void OH_Drawing_TextStyleDestroyFontFamilies (char** fontFamilies, size_t num ) +void OH_Drawing_TextStyleDestroyFontFamilies (char** fontFamilies, size_t num) ``` **Description** -Reclaims the memory occupied by the font families. +Reclaims the memory occupied by the font families, where **num** specifies the number of font families. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -15611,10 +16071,10 @@ Reclaims the memory occupied by the font families. **Parameters** -| Name | Description | -| -------- | ------------------------------------ | -| char\*\* | Double pointer to the font families. | -| size_t | Number of font families. | +| Name | Description | +| ------------ | ------------------------------------ | +| fontFamilies | Double pointer to the font families. | +| num | Number of font families. | ### OH_Drawing_TextStyleDestroyFontFeatures() @@ -15647,7 +16107,7 @@ void OH_Drawing_TextStyleGetBackgroundBrush (OH_Drawing_TextStyle* , OH_Drawing_ **Description** -Obtains the background brush of a text style. +Obtains the background brush. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -15669,7 +16129,7 @@ void OH_Drawing_TextStyleGetBackgroundPen (OH_Drawing_TextStyle* , OH_Drawing_Pe **Description** -Obtains the background pen of a text style. +Obtains the background pen. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -15711,7 +16171,7 @@ Returns the text baseline. For details about the available options, see [OH_Draw ### OH_Drawing_TextStyleGetBaselineShift() ``` -double OH_Drawing_TextStyleGetBaselineShift (OH_Drawing_TextStyle* ) +double OH_Drawing_TextStyleGetBaselineShift (OH_Drawing_TextStyle*) ``` **Description** @@ -15802,7 +16262,7 @@ Obtains the font families of a text style. | Name | Description | | -------------------- | ------------------------------------------------------------ | | OH_Drawing_TextStyle | Pointer to an [OH_Drawing_TextStyle](#oh_drawing_textstyle) object, which is obtained by calling [OH_Drawing_CreateTextStyle](#oh_drawing_createtextstyle). | -| size_t | Pointer to the number of font families. | +| num | Pointer to the number of font families. | **Returns** @@ -15817,7 +16277,7 @@ OH_Drawing_FontFeature* OH_Drawing_TextStyleGetFontFeatures (OH_Drawing_TextStyl **Description** -Obtains all the contents in a font feature map container. +Obtains all the contents in a font feature map container of a text style. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -15842,7 +16302,7 @@ size_t OH_Drawing_TextStyleGetFontFeatureSize (OH_Drawing_TextStyle* ) **Description** -Obtains the size of a font feature map container. +Obtains the size of a font feature map container in a text style. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -15892,7 +16352,7 @@ bool OH_Drawing_TextStyleGetFontMetrics (OH_Drawing_Typography* , OH_Drawing_Tex **Description** -Obtains the font metrics of a text style. +Obtains the font metrics. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -15914,7 +16374,7 @@ Returns **true** if the font metrics are obtained; returns **false** otherwise. ### OH_Drawing_TextStyleGetFontSize() ``` -double OH_Drawing_TextStyleGetFontSize (OH_Drawing_TextStyle* ) +double OH_Drawing_TextStyleGetFontSize (OH_Drawing_TextStyle*) ``` **Description** @@ -15989,7 +16449,7 @@ Returns the font style, including the font weight, width, and slant. ### OH_Drawing_TextStyleGetFontWeight() ``` -OH_Drawing_FontWeight OH_Drawing_TextStyleGetFontWeight (OH_Drawing_TextStyle* ) +OH_Drawing_FontWeight OH_Drawing_TextStyleGetFontWeight (OH_Drawing_TextStyle*) ``` **Description** @@ -16058,7 +16518,7 @@ Obtains the foreground pen of a text style. ### OH_Drawing_TextStyleGetHalfLeading() ``` -bool OH_Drawing_TextStyleGetHalfLeading (OH_Drawing_TextStyle* ) +bool OH_Drawing_TextStyleGetHalfLeading (OH_Drawing_TextStyle*) ``` **Description** @@ -16083,7 +16543,7 @@ Returns **true** if half leading is enabled; returns **false** otherwise. ### OH_Drawing_TextStyleGetLetterSpacing() ``` -double OH_Drawing_TextStyleGetLetterSpacing (OH_Drawing_TextStyle* ) +double OH_Drawing_TextStyleGetLetterSpacing (OH_Drawing_TextStyle*) ``` **Description** @@ -16108,7 +16568,7 @@ Returns the letter spacing. ### OH_Drawing_TextStyleGetLocale() ``` -const char* OH_Drawing_TextStyleGetLocale (OH_Drawing_TextStyle* ) +const char* OH_Drawing_TextStyleGetLocale (OH_Drawing_TextStyle*) ``` **Description** @@ -16163,7 +16623,7 @@ OH_Drawing_TextShadow* OH_Drawing_TextStyleGetShadows (OH_Drawing_TextStyle* ) **Description** -Obtains a text shadow container. +Obtains a text shadow container. When [OH_Drawing_TextShadow](#oh_drawing_textshadow) is no longer required, call [OH_Drawing_DestroyTextShadows](#oh_drawing_destroytextshadows) to release the pointer to the object. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -16209,7 +16669,7 @@ Returns the pointer to the [OH_Drawing_TextShadow](#oh_drawing_textshadow) objec ### OH_Drawing_TextStyleGetWordSpacing() ``` -double OH_Drawing_TextStyleGetWordSpacing (OH_Drawing_TextStyle* ) +double OH_Drawing_TextStyleGetWordSpacing (OH_Drawing_TextStyle*) ``` **Description** @@ -16266,7 +16726,7 @@ bool OH_Drawing_TextStyleIsEqual (const OH_Drawing_TextStyle* style, const OH_Dr **Description** -Checks whether two text styles are equal. +Checks whether two text styles are equal. The word width property is not involved in the comparison. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -16300,10 +16760,10 @@ Checks whether the font style properties of two text styles are equal. **Parameters** -| Name | Description | -| ------------- | --------------------------------- | -| style | Pointer to the first text style. | -| comparedStyle | Pointer to the second text style. | +| Name | Description | +| ------------- | ---------------------------------- | +| style | Pointer to the first text style. | +| comparedStyle | Pointer to the first second style. | **Returns** @@ -16361,7 +16821,7 @@ Sets a background rectangle and style ID for a text style. The style ID is valid ### OH_Drawing_TextStyleSetBaselineShift() ``` -void OH_Drawing_TextStyleSetBaselineShift (OH_Drawing_TextStyle* , double lineShift ) +void OH_Drawing_TextStyleSetBaselineShift (OH_Drawing_TextStyle*, double lineShift) ``` **Description** @@ -16551,7 +17011,7 @@ bool OH_Drawing_TypographyDidExceedMaxLines (OH_Drawing_Typography* ) **Description** -Checks whether the maximum number of lines is exceeded. +Checks whether the maximum number of lines of a typography object is exceeded. This function must be called after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called. If the maximum number of lines is not set by calling [OH_Drawing_SetTypographyTextMaxLines](#oh_drawing_settypographytextmaxlines), **false** is returned. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -16576,7 +17036,7 @@ double OH_Drawing_TypographyGetAlphabeticBaseline (OH_Drawing_Typography* ) **Description** -Obtains the alphabetic baseline. +Obtains the alphabetic baseline in a typography object. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -16680,7 +17140,7 @@ double OH_Drawing_TypographyGetHeight (OH_Drawing_Typography* ) **Description** -Obtains the height. +Obtains the overall height of a typography object. This function must be called after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -16705,7 +17165,7 @@ double OH_Drawing_TypographyGetIdeographicBaseline (OH_Drawing_Typography* ) **Description** -Obtains the ideographic baseline. +Obtains the ideographic baseline in a typography object. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -16730,7 +17190,7 @@ float OH_Drawing_TypographyGetIndentsWithIndex (OH_Drawing_Typography* , int ) **Description** -Obtains indents with a given index. +Obtains indents with a given index in a typography object. The line index starts from 0. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -16756,7 +17216,7 @@ size_t OH_Drawing_TypographyGetLineCount (OH_Drawing_Typography* ) **Description** -Obtains the number of lines. +Obtains the number of lines in a typography object. This function must be called after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -16781,7 +17241,7 @@ OH_Drawing_Font_Metrics* OH_Drawing_TypographyGetLineFontMetrics (OH_Drawing_Typ **Description** -Obtains all font metrics from a given line. +Obtains all font metrics from a given line in a typography object. This function must be called after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called. Otherwise, a null pointer is returned. When [OH_Drawing_Font_Metrics](_o_h___drawing___font___metrics.md) is no longer required, call [OH_Drawing_TypographyDestroyLineFontMetrics](#oh_drawing_typographydestroylinefontmetrics) to release the pointer to the object. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -16808,7 +17268,7 @@ double OH_Drawing_TypographyGetLineHeight (OH_Drawing_Typography* , int ) **Description** -Obtains the line height. +Obtains the line height in a typography object. This function must be called after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -16834,7 +17294,7 @@ bool OH_Drawing_TypographyGetLineInfo (OH_Drawing_Typography* , int , bool , boo **Description** -Obtains the metrics of a given line or the metrics of the first character in a given line. +Obtains the metrics of a given line or the metrics of the first character in a given line in a typography object. This function must be called after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -16863,7 +17323,7 @@ OH_Drawing_LineMetrics* OH_Drawing_TypographyGetLineMetrics (OH_Drawing_Typograp **Description** -Obtains the line metrics. +Obtains the line metrics in a typography object. This function must be called after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called. When [OH_Drawing_LineMetrics](_o_h___drawing___line_metrics.md) is no longer required, call [OH_Drawing_DestroyLineMetrics](#oh_drawing_destroylinemetrics) to release the pointer to the object. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -16888,7 +17348,7 @@ bool OH_Drawing_TypographyGetLineMetricsAt (OH_Drawing_Typography* , int , OH_Dr **Description** -Obtains the metrics of a given line. +Obtains the metrics of a given line in a typography object. For details, see [OH_Drawing_LineMetrics](_o_h___drawing___line_metrics.md). This function must be called after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -16915,7 +17375,7 @@ OH_Drawing_Range* OH_Drawing_TypographyGetLineTextRange (OH_Drawing_Typography* **Description** -Obtains the line bounds. +Obtains the line bounds in a typography object. This function must be called after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called. This function can only be used to obtain the bounds of existing lines. That is, the line index must start from 0, and the maximum index is [OH_Drawing_TypographyGetLineCount](#oh_drawing_typographygetlinecount) - 1. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -16942,7 +17402,7 @@ double OH_Drawing_TypographyGetLineWidth (OH_Drawing_Typography* , int ) **Description** -Obtains the line width. +Obtains the line width in a typography object. This function must be called after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -16968,7 +17428,7 @@ double OH_Drawing_TypographyGetLongestLine (OH_Drawing_Typography* ) **Description** -Obtains the width of the longest line. You are advised to round up the return value in actual use. When the text content is empty, the minimum float value, that is, -340282346638528859811704183484516925440.000000, is returned. +Obtains the width of the longest line in a typography object. This function must be called after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called. You are advised to round up the return value. If the text content is empty, **0.0** is returned. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -16993,7 +17453,7 @@ double OH_Drawing_TypographyGetMaxIntrinsicWidth (OH_Drawing_Typography* ) **Description** -Obtains the maximum intrinsic width. +Obtains the maximum intrinsic width in a typography object. This function must be called after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -17018,7 +17478,7 @@ double OH_Drawing_TypographyGetMaxWidth (OH_Drawing_Typography* ) **Description** -Obtains the maximum width. +Obtains the typography width set by the user. This function must be called after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -17032,7 +17492,7 @@ Obtains the maximum width. **Returns** -Returns the maximum width. +Returns the typography width set by the user. ### OH_Drawing_TypographyGetMinIntrinsicWidth() @@ -17043,7 +17503,7 @@ double OH_Drawing_TypographyGetMinIntrinsicWidth (OH_Drawing_Typography* ) **Description** -Obtains the minimum intrinsic width. +Obtains the minimum intrinsic width in a typography object. This function must be called after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -17068,7 +17528,7 @@ OH_Drawing_TextBox* OH_Drawing_TypographyGetRectsForPlaceholders (OH_Drawing_Typ **Description** -Obtains text boxes for placeholders. +Obtains text boxes for placeholders in a typography object. This function must be called after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called. When [OH_Drawing_TextBox](#oh_drawing_textbox) is no longer required, call [OH_Drawing_TypographyDestroyTextBox](#oh_drawing_typographydestroytextbox) to release the pointer to the object. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -17092,7 +17552,7 @@ OH_Drawing_TextBox* OH_Drawing_TypographyGetRectsForRange (OH_Drawing_Typography **Description** -Obtains text boxes in a given range. +Obtains text boxes in a given range of a typography object. This function must be called after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called. When [OH_Drawing_TextBox](#oh_drawing_textbox) is no longer required, call [OH_Drawing_TypographyDestroyTextBox](#oh_drawing_typographydestroytextbox) to release the pointer to the object. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -17146,7 +17606,7 @@ OH_Drawing_TextDirection OH_Drawing_TypographyGetTextDirection (OH_Drawing_Typog **Description** -Obtains the text direction. +Obtains the text direction of a typography style. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -17171,7 +17631,7 @@ char* OH_Drawing_TypographyGetTextEllipsis (OH_Drawing_TypographyStyle* ) **Description** -Obtains the text ellipsis content. +Obtains the text ellipsis content of a typography style. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -17221,7 +17681,7 @@ OH_Drawing_TextStyle* OH_Drawing_TypographyGetTextStyle (OH_Drawing_TypographySt **Description** -Obtains the text style of a typography style. +Obtains the default text style of a typography style. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -17235,7 +17695,7 @@ Obtains the text style of a typography style. **Returns** -Returns the pointer to the [OH_Drawing_TextStyle](#oh_drawing_textstyle) object. +Returns the pointer to an [OH_Drawing_TextStyle](#oh_drawing_textstyle) object. If the object is no longer required, call [OH_Drawing_DestroyTextStyle](#oh_drawing_destroytextstyle) to release the pointer to the object. ### OH_Drawing_TypographyGetUnresolvedGlyphsCount() @@ -17246,7 +17706,7 @@ int32_t OH_Drawing_TypographyGetUnresolvedGlyphsCount (OH_Drawing_Typography* ) **Description** -Obtains the number of unresolved glyphs in a typography object. +Obtains the number of unresolved glyphs in a typography object. This function can be called only after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called and applied. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -17271,7 +17731,7 @@ OH_Drawing_Range* OH_Drawing_TypographyGetWordBoundary (OH_Drawing_Typography* , **Description** -Obtains the word boundary. +Obtains the word boundary in a typography object. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -17305,10 +17765,10 @@ Adds a placeholder. **Parameters** -| Name | Description | -| ------------------------------------------------------------ | ------------------------------------------------------------ | -| OH_Drawing_TypographyCreate | Pointer to an **OH_Drawing_TypographyCreate** object. The pointer is obtained by [OH_Drawing_CreateTypographyHandler](#oh_drawing_createtypographyhandler). | -| [OH_Drawing_PlaceholderSpan](_o_h___drawing___placeholder_span.md) | Pointer to an **OH_Drawing_PlaceholderSpan** object. | +| Name | Description | +| --------------------------- | ------------------------------------------------------------ | +| OH_Drawing_TypographyCreate | Pointer to an [OH_Drawing_TypographyCreate](#oh_drawing_typographycreate) object. The pointer is obtained by calling [OH_Drawing_CreateTypographyHandler](#oh_drawing_createtypographyhandler). | +| OH_Drawing_PlaceholderSpan | Pointer to an [OH_Drawing_PlaceholderSpan](_o_h___drawing___placeholder_span.md) object. | ### OH_Drawing_TypographyHandlerAddSymbol() @@ -17329,8 +17789,8 @@ Adds the symbol to use in the typography creation process. | Name | Description | | --------------------------- | ------------------------------------------------------------ | -| OH_Drawing_TypographyCreate | Pointer to an **OH_Drawing_TypographyCreate** object. The pointer is obtained by [OH_Drawing_CreateTypographyHandler](#oh_drawing_createtypographyhandler). | -| uint32_t | Symbol. For details about the supported symbols, see the value in the JSON file. [https://gitee.com/openharmony/global_system_resources/blob/master/systemres/main/resources/base/element/symbol.json](https://gitee.com/openharmony/global_system_resources/blob/master/systemres/main/resources/base/element/symbol.json) | +| OH_Drawing_TypographyCreate | Pointer to an [OH_Drawing_TypographyCreate](#oh_drawing_typographycreate) object. The pointer is obtained by calling [OH_Drawing_CreateTypographyHandler](#oh_drawing_createtypographyhandler). | +| uint32_t | Symbol. For details about the supported symbols, see the value in the JSON file. For details about the configurable symbols (unicode values in the list view), see [HarmonyOS Symbol](https://developer.huawei.com/consumer/cn/design/harmonyos-symbol/). | ### OH_Drawing_TypographyHandlerAddText() @@ -17351,7 +17811,7 @@ Adds text. | Name | Description | | --------------------------- | ------------------------------------------------------------ | -| OH_Drawing_TypographyCreate | Pointer to an **OH_Drawing_TypographyCreate** object. The pointer is obtained by [OH_Drawing_CreateTypographyHandler](#oh_drawing_createtypographyhandler). | +| OH_Drawing_TypographyCreate | Pointer to an [OH_Drawing_TypographyCreate](#oh_drawing_typographycreate) object. The pointer is obtained by calling [OH_Drawing_CreateTypographyHandler](#oh_drawing_createtypographyhandler). | | char | Pointer to the text content. | @@ -17363,7 +17823,7 @@ void OH_Drawing_TypographyHandlerPopTextStyle (OH_Drawing_TypographyCreate* ) **Description** -Removes the topmost text style in the stack, leaving the remaining styles in effect. +Pops the top text style out of the text style stack. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -17373,7 +17833,7 @@ Removes the topmost text style in the stack, leaving the remaining styles in eff | Name | Description | | --------------------------- | ------------------------------------------------------------ | -| OH_Drawing_TypographyCreate | Pointer to an **OH_Drawing_TypographyCreate** object. The pointer is obtained by [OH_Drawing_CreateTypographyHandler](#oh_drawing_createtypographyhandler). | +| OH_Drawing_TypographyCreate | Pointer to an [OH_Drawing_TypographyCreate](#oh_drawing_typographycreate) object. The pointer is obtained by calling [OH_Drawing_CreateTypographyHandler](#oh_drawing_createtypographyhandler). | ### OH_Drawing_TypographyHandlerPushTextStyle() @@ -17384,7 +17844,7 @@ void OH_Drawing_TypographyHandlerPushTextStyle (OH_Drawing_TypographyCreate* , O **Description** -Pushes the text style. +Pushes a text style into the text style stack. Any text added afterward will use the style currently on top of the stack. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -17394,8 +17854,8 @@ Pushes the text style. | Name | Description | | --------------------------- | ------------------------------------------------------------ | -| OH_Drawing_TypographyCreate | Pointer to an **OH_Drawing_TypographyCreate** object. The pointer is obtained by [OH_Drawing_CreateTypographyHandler](#oh_drawing_createtypographyhandler). | -| OH_Drawing_TextStyle | Pointer to an **OH_Drawing_TextStyle** object, which is obtained by calling [OH_Drawing_CreateTextStyle](#oh_drawing_createtextstyle). | +| OH_Drawing_TypographyCreate | Pointer to an [OH_Drawing_TypographyCreate](#oh_drawing_typographycreate) object. The pointer is obtained by calling [OH_Drawing_CreateTypographyHandler](#oh_drawing_createtypographyhandler). | +| OH_Drawing_TextStyle | Pointer to an [OH_Drawing_TextStyle](#oh_drawing_textstyle) object, which is obtained by calling [OH_Drawing_CreateTextStyle](#oh_drawing_createtextstyle). | ### OH_Drawing_TypographyIsEllipsized() @@ -17406,7 +17866,7 @@ bool OH_Drawing_TypographyIsEllipsized (OH_Drawing_TypographyStyle* style) **Description** -Checks whether the text has an ellipsis. +Checks whether an ellipsis is configured for a typography style. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -17466,7 +17926,7 @@ Lays out the typography. | Name | Description | | --------------------- | ------------------------------------------------------------ | -| OH_Drawing_Typography | Pointer to an **OH_Drawing_Typography** object, which is obtained by calling [OH_Drawing_CreateTypography](#oh_drawing_createtypography). | +| OH_Drawing_Typography | Pointer to an [OH_Drawing_Typography](#oh_drawing_typography) object, which is obtained by calling [OH_Drawing_CreateTypography](#oh_drawing_createtypography). | | double | Maximum text width. | @@ -17499,7 +17959,7 @@ void OH_Drawing_TypographyPaint (OH_Drawing_Typography* , OH_Drawing_Canvas* , d **Description** -Paints text on the canvas. +Draws text from the upper left corner at a specified position. This function must be called after [OH_Drawing_TypographyLayout](#oh_drawing_typographylayout) is called and applied. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -17567,7 +18027,7 @@ bool OH_Drawing_TypographyStyleEquals (OH_Drawing_TypographyStyle* from, OH_Draw **Description** -Checks whether two typography styles are the same. +Checks whether two typography styles are the same. The text height modifier mode [OH_Drawing_TextHeightBehavior](#oh_drawing_textheightbehavior) is not involved in the comparison. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -17618,7 +18078,7 @@ OH_Drawing_FontStyleStruct OH_Drawing_TypographyStyleGetFontStyleStruct (OH_Draw **Description** -Obtains the font style, including the font weight, width, and slant, of a typography style. +Obtains the font style, including the font weight, width, and slant, of the default text style of a typography style. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -17750,7 +18210,7 @@ Obtains the text height modifier pattern. | Name | Description | | -------------------------- | ------------------------------------------------------------ | -| OH_Drawing_TypographyStyle | Pointer to an **OH_Drawing_TypographyStyle** object, which is obtained by calling [OH_Drawing_CreateTypographyStyle](#oh_drawing_createtypographystyle). | +| OH_Drawing_TypographyStyle | Pointer to an [OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) object, which is obtained by calling [OH_Drawing_CreateTypographyStyle](#oh_drawing_createtypographystyle). | **Returns** @@ -17832,7 +18292,7 @@ Reclaims the memory occupied by the font families. ### OH_Drawing_TypographyTextlineStyleGetFontFamilies() ``` -char** OH_Drawing_TypographyTextlineStyleGetFontFamilies (OH_Drawing_TypographyStyle* ) +char** OH_Drawing_TypographyTextlineStyleGetFontFamilies (OH_Drawing_TypographyStyle* , size_t* num) ``` **Description** @@ -17848,6 +18308,7 @@ Obtains the font families of a text line style. | Name | Description | | -------------------------- | ------------------------------------------------------------ | | OH_Drawing_TypographyStyle | Pointer to an [OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) object, which is obtained by calling [OH_Drawing_CreateTypographyStyle](#oh_drawing_createtypographystyle). | +| num | Pointer to the number of font families. | **Returns** @@ -17887,7 +18348,7 @@ OH_Drawing_FontStyle OH_Drawing_TypographyTextlineStyleGetFontStyle (OH_Drawing_ **Description** -Obtains the font style of a text line style. +Obtains the font style of the strut style in a typography style. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -17907,12 +18368,12 @@ Returns the font style. For details about the available options, see [OH_Drawing ### OH_Drawing_TypographyTextlineStyleGetFontWeight() ``` -OH_Drawing_FontWeight OH_Drawing_TypographyTextlineStyleGetFontWeight (OH_Drawing_TypographyStyle* ) +OH_Drawing_FontWeight OH_Drawing_TypographyTextlineStyleGetFontWeight (OH_Drawing_TypographyStyle*) ``` **Description** -Obtains the font weight of a text line style. +Obtains the font weight of the strut style in a typography style. **System capability**: SystemCapability.Graphic.Graphic2D.NativeDrawing @@ -18001,7 +18462,7 @@ Obtains the height scale factor of a text line style. **Returns** -Returns the font height scale factor. +Returns the height scale factor. ### OH_Drawing_TypographyTextlineStyleGetSpacingScale() @@ -18047,7 +18508,7 @@ Sets a text height modifier pattern. | Name | Description | | -------------------------- | ------------------------------------------------------------ | -| OH_Drawing_TypographyStyle | Pointer to an **OH_Drawing_TypographyStyle** object, which is obtained by calling [OH_Drawing_CreateTypographyStyle](#oh_drawing_createtypographystyle). | +| OH_Drawing_TypographyStyle | Pointer to an [OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) object, which is obtained by calling [OH_Drawing_CreateTypographyStyle](#oh_drawing_createtypographystyle). | | heightMode | Text height modifier pattern. For details about the available options, see [OH_Drawing_TextHeightBehavior](#oh_drawing_textheightbehavior). | @@ -18070,6 +18531,6 @@ Updates the font size in a typography object. | Name | Description | | --------------------- | ------------------------------------------------------------ | | OH_Drawing_Typography | Pointer to an [OH_Drawing_Typography](#oh_drawing_typography) object, which is obtained by calling [OH_Drawing_CreateTypography](#oh_drawing_createtypography). | -| from | Original font size. | -| to | New font size. | -| fontSize | Font size. | \ No newline at end of file +| from | Reserved field, which is not used. | +| to | Reserved field, which is not used. | +| fontSize | New font size. | \ No newline at end of file diff --git a/en/application-dev/reference/apis-arkgraphics2d/_native_vsync.md b/en/application-dev/reference/apis-arkgraphics2d/_native_vsync.md index 171565867981f4195ce9ae36afb25dcf3d3a1bdc..6e48f37b05867fbf1a03afd9ad07732533b211c7 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/_native_vsync.md +++ b/en/application-dev/reference/apis-arkgraphics2d/_native_vsync.md @@ -3,7 +3,7 @@ ## Overview -The **NativeVsync** module provides the capabilities of native virtual synchronization (VSync). +The NativeVsync module provides the capabilities for obtaining the system virtual synchronization (VSync) callback, allowing you to synchronize your application's drawing frame rate with the system's frame rate. \@syscap SystemCapability.Graphic.Graphic2D.NativeVsync @@ -228,7 +228,7 @@ Creates an **OH_NativeVSync** instance. A new **OH_NativeVSync** instance is cre | Name| Description| | -------- | -------- | | name | Pointer to the name that associates with the **OH_NativeVSync** instance.| -| length | Length of the name.| +| length | Length of the name (number of characters).| **Returns** @@ -245,6 +245,8 @@ OH_NativeVSync* OH_NativeVSync_Create_ForAssociatedWindow (uint64_t windowID, co Creates an **OH_NativeVSync** instance to bind with a window. A new **OH_NativeVSync** instance is created each time this API is called. +The actual VSync period of the **OH_NativeVSync** instance created by calling this function may be different from the system's VSync period. The system adjusts the actual VSync period based on the window status. + **System capability**: SystemCapability.Graphic.Graphic2D.NativeVsync **Since**: 14 @@ -255,7 +257,7 @@ Creates an **OH_NativeVSync** instance to bind with a window. A new **OH_NativeV | -------- | -------- | | windowID | Window ID, which is the index identifier of the window child process and can be obtained through [OH_NativeWindow_GetSurfaceId](_native_window.md#oh_nativewindow_getsurfaceid).| | name | Pointer to the name that associates with the **OH_NativeVSync** instance.| -| length | Length of the name.| +| length | Length of the name (number of characters).| **Returns** @@ -274,7 +276,7 @@ void OH_NativeVSync_Destroy (OH_NativeVSync * nativeVsync) Destroys an **OH_NativeVSync** instance. -Once the **OH_NativeVSync** pointer is destroyed, it must not be used to prevent dangling pointer problems. Pay special attention to the management of the **OH_NativeVSync** pointer in concurrent multithreaded scenarios. +Once the **OH_NativeVSync** pointer is destroyed, it should not be used, as this can result in dangling pointer problems. Pay special attention to the management of the **OH_NativeVSync** pointer in multithreaded scenarios. \@syscap SystemCapability.Graphic.Graphic2D.NativeVsync diff --git a/en/application-dev/reference/apis-arkgraphics2d/_native_window.md b/en/application-dev/reference/apis-arkgraphics2d/_native_window.md index fc2343454ea14482e1755926b19c6b2dfe5e2c29..f0e67786e0dcee2e78e0be471063a921cf1d56dd 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/_native_window.md +++ b/en/application-dev/reference/apis-arkgraphics2d/_native_window.md @@ -3,7 +3,7 @@ ## Overview -The **NativeWindow** module provides the **NativeWindow** capability for connection to the EGL. +The NativeWindow module provides the image buffer rotation capability, compatible with EGL. As the producer of the image buffer, your application produces the buffer and transfers the buffer through NativeWindow for the consumer to read. **System capability**: SystemCapability.Graphic.Graphic2D.NativeWindow @@ -27,7 +27,7 @@ The **NativeWindow** module provides the **NativeWindow** capability for connect | struct [Region](_region.md) | Describes the rectangle (dirty region) where the content is to be updated in the local **OHNativeWindow**.| | struct [OHHDRMetaData](_o_h_h_d_r_meta_data.md) | Describes the HDR metadata.
**Deprecated**: This struct is deprecated since API version 10. No substitute is provided.| | struct [OHExtDataHandle](_o_h_ext_data_handle.md) | Describes the extended data handle.
**Deprecated**: This struct is deprecated since API version 10. No substitute is provided.| - +| struct [BufferHandle](_buffer_handle.md) | Describes the buffer handle, which is used to transfer and obtain buffer information. The handle contains the file descriptor, size, format, usage, virtual address, shared memory key, physical address, and custom data of the buffer. | ### Types @@ -67,7 +67,7 @@ The **NativeWindow** module provides the **NativeWindow** capability for connect | int32_t [OH_NativeWindow_GetLastFlushedBuffer](#oh_nativewindow_getlastflushedbuffer) ([OHNativeWindow](#ohnativewindow) \*window, [OHNativeWindowBuffer](#ohnativewindowbuffer) \*\*buffer, int \*fenceFd, float matrix[16]) | Obtains the **OHNativeWindowBuffer** that was flushed to the buffer queue last time through an **OHNativeWindow** instance.| | int32_t [OH_NativeWindow_NativeWindowAbortBuffer](#oh_nativewindow_nativewindowabortbuffer) ([OHNativeWindow](#ohnativewindow) \*window, [OHNativeWindowBuffer](#ohnativewindowbuffer) \*buffer) | Returns the **OHNativeWindowBuffer** to the buffer queue through an **OHNativeWindow** instance, without filling in any content. The **OHNativeWindowBuffer** can be used for a new request.| | int32_t [OH_NativeWindow_NativeWindowHandleOpt](#oh_nativewindow_nativewindowhandleopt) ([OHNativeWindow](#ohnativewindow) \*window, int code,...) | Sets or obtains the attributes of an **OHNativeWindow** instance, including the width, height, and content format.| -| BufferHandle \* [OH_NativeWindow_GetBufferHandleFromNative](#oh_nativewindow_getbufferhandlefromnative) ([OHNativeWindowBuffer](#ohnativewindowbuffer) \*buffer) | Obtains the pointer to a **BufferHandle** of an **OHNativeWindowBuffer** instance.| +| [BufferHandle](_buffer_handle.md) \* [OH_NativeWindow_GetBufferHandleFromNative](#oh_nativewindow_getbufferhandlefromnative) ([OHNativeWindowBuffer](#ohnativewindowbuffer) \*buffer) | Obtains the pointer to a **BufferHandle** of an **OHNativeWindowBuffer** instance.
This function is not thread-safe.| | int32_t [OH_NativeWindow_NativeObjectReference](#oh_nativewindow_nativeobjectreference) (void \*obj) | Adds the reference count of a native object.| | int32_t [OH_NativeWindow_NativeObjectUnreference](#oh_nativewindow_nativeobjectunreference) (void \*obj) | Decreases the reference count of a native object and, when the reference count reaches 0, destroys this object.| | int32_t [OH_NativeWindow_GetNativeObjectMagic](#oh_nativewindow_getnativeobjectmagic) (void \*obj) | Obtains the magic ID of a native object.| @@ -268,10 +268,10 @@ Enumerates the operation codes in the **OH_NativeWindow_NativeWindowHandleOpt** | SET_FORMAT | Setting the format for the local window buffer.
Variable argument in the function: [Input] int32_t format.
For details about the available options, see [OH_NativeBuffer_Format](_o_h___native_buffer.md#oh_nativebuffer_format-1).| | GET_USAGE | Obtaining the usage mode of the local window buffer.
Variable argument in the function: [Output] uint64_t \*usage.
For details about the available options, see [OH_NativeBuffer_Usage](_o_h___native_buffer.md#oh_nativebuffer_usage-1).| | SET_USAGE | Setting the usage mode for the local window buffer.
Variable argument in the function: [Input] uint64_t usage.
For details about the available options, see [OH_NativeBuffer_Usage](_o_h___native_buffer.md#oh_nativebuffer_usage-1).| -| SET_STRIDE | Setting the stride for the local window buffer, in bytes.
Variable argument in the function: [Input] int32_t stride.| -| GET_STRIDE | Obtaining the stride of the local window buffer, in bytes.
Variable argument in the function: [Output] int32_t \*stride.| +| SET_STRIDE(deprecated) | Setting the stride for the local window buffer.
Variable argument in the function: [Input] int32_t stride.
**Deprecated**: This API is deprecated since API version 16.| +| GET_STRIDE(deprecated) | Obtaining the stride of the local window buffer.
Variable argument in the function: [Output] int32_t *stride.
**Deprecated**: This API is deprecated since API version 16.
**Substitute**: Use [OH_NativeWindow_GetBufferHandleFromNative](#oh_nativewindow_getbufferhandlefromnative) to obtain a [BufferHandle](_buffer_handle.md) instance, and obtain the stride from this instance.| | SET_SWAP_INTERVAL | Setting the swap interval for the local window buffer.
Variable argument in the function: [Input] int32_t interval.| -| GET_SWAP_INTERVAL | Obtaining the swap interval of the local window buffer.
Variable argument in the function: [Output] int32_t \*interval.| +| GET_SWAP_INTERVAL | Obtaining the swap interval of the local window buffer.
Variable argument in the function: [Output] int32_t *interval.| | SET_TIMEOUT | Setting the timeout duration for requesting the local window buffer, in ms.
Default value: 3000 ms.
Variable argument in the function: [Input] int32_t timeout.| | GET_TIMEOUT | Obtaining the timeout duration for requesting the local window buffer, in ms.
Default value: 3000 ms.
Variable argument in the function: [Output] int32_t \*timeout.| | SET_COLOR_GAMUT | Setting the color gamut for the local window buffer.
Variable argument in the function: [Input] int32_t colorGamut.
For details about the available options, see [OH_NativeBuffer_ColorGamut](_o_h___native_buffer.md#oh_nativebuffer_colorgamut-1).| @@ -389,7 +389,7 @@ This function is not thread-safe. **Returns** -Returns **0** if the operation is successful; returns an error code defined in [OHNativeErrorCode](_o_h___native_buffer.md#ohnativeerrorcode) otherwise. +Returns **0** if the operation is successful; returns an error code defined in [OHNativeErrorCode](_o_h___native_buffer.md#ohnativeerrorcode-1) otherwise. ### OH_NativeWindow_SetMetadataValue() @@ -419,7 +419,7 @@ This function is not thread-safe. **Returns** -Returns **0** if the operation is successful; returns an error code defined in [OHNativeErrorCode](_o_h___native_buffer.md#ohnativeerrorcode) otherwise. +Returns **0** if the operation is successful; returns an error code defined in [OHNativeErrorCode](_o_h___native_buffer.md#ohnativeerrorcode-1) otherwise. ### OH_NativeWindow_GetColorSpace() @@ -446,7 +446,7 @@ This function is not thread-safe. **Returns** -Returns **0** if the operation is successful; returns an error code defined in [OHNativeErrorCode](_o_h___native_buffer.md#ohnativeerrorcode) otherwise. +Returns **0** if the operation is successful; returns an error code defined in [OHNativeErrorCode](_o_h___native_buffer.md#ohnativeerrorcode-1) otherwise. ### OH_NativeWindow_GetMetadataValue() @@ -476,7 +476,7 @@ This function is not thread-safe. **Returns** -Returns **0** if the operation is successful; returns an error code defined in [OHNativeErrorCode](_o_h___native_buffer.md#ohnativeerrorcode) otherwise. +Returns **0** if the operation is successful; returns an error code defined in [OHNativeErrorCode](_o_h___native_buffer.md#ohnativeerrorcode-1) otherwise. ### OH_NativeWindow_WriteToParcel() @@ -781,7 +781,7 @@ This function is not thread-safe. **Returns** -Returns the pointer to the **BufferHandle** instance obtained. +Returns the pointer to the [BufferHandle](_buffer_handle.md) instance obtained. ### OH_NativeWindow_GetLastFlushedBuffer() diff --git a/en/application-dev/reference/apis-arkgraphics2d/_o_h___drawing___bitmap_format.md b/en/application-dev/reference/apis-arkgraphics2d/_o_h___drawing___bitmap_format.md index 171c24037f1252b11fe5bc502d5b253bcef50161..4a5c957db91b5984b9ca5f073ad5a6c7235b7045 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/_o_h___drawing___bitmap_format.md +++ b/en/application-dev/reference/apis-arkgraphics2d/_o_h___drawing___bitmap_format.md @@ -3,7 +3,7 @@ ## Overview -The **OH_Drawing_BitmapFormat** struct describes the pixel format of a bitmap, including the color type and alpha type. +The OH_Drawing_BitmapFormat struct describes the pixel format of a bitmap, including the color type and alpha type. **Since**: 8 diff --git a/en/application-dev/reference/apis-arkgraphics2d/_o_h___drawing___image___info.md b/en/application-dev/reference/apis-arkgraphics2d/_o_h___drawing___image___info.md index 1b71bc061cda9becda556f623ebcc2f83452fc1b..6685978085da8799b346f93ae40807be6627cc1b 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/_o_h___drawing___image___info.md +++ b/en/application-dev/reference/apis-arkgraphics2d/_o_h___drawing___image___info.md @@ -17,8 +17,8 @@ The **OH_Drawing_Image_Info** struct describes the image information. | Name| Description| | -------- | -------- | -| int32_t [width](#width) | Width, in px.| -| int32_t [height](#height) | Height, in px.| +| int32_t [width](#width) | Width, in pixels.| +| int32_t [height](#height) | Height, in pixels.| | [OH_Drawing_ColorFormat](_drawing.md#oh_drawing_colorformat) [colorType](#colortype) | Color format. For details, see [OH_Drawing_ColorFormat](_drawing.md#oh_drawing_colorformat).| | [OH_Drawing_AlphaFormat](_drawing.md#oh_drawing_alphaformat) [alphaType](#alphatype) | Alpha format. For details, see [OH_Drawing_AlphaFormat](_drawing.md#oh_drawing_alphaformat).| diff --git a/en/application-dev/reference/apis-arkgraphics2d/_o_h___drawing___placeholder_span.md b/en/application-dev/reference/apis-arkgraphics2d/_o_h___drawing___placeholder_span.md index 009b24917326082a1e12666d8de2f893ad5f5b9c..97f10debacd74ac568ff19e8a8923c950b8036a9 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/_o_h___drawing___placeholder_span.md +++ b/en/application-dev/reference/apis-arkgraphics2d/_o_h___drawing___placeholder_span.md @@ -3,7 +3,7 @@ ## Overview -The **OH_Drawing_PlaceholderSpan** struct describes the placeholder that acts as a span. +The OH_Drawing_PlaceholderSpan struct describes the placeholder that acts as a span. **Since**: 11 diff --git a/en/application-dev/reference/apis-arkgraphics2d/_o_h___drawing___point2_d.md b/en/application-dev/reference/apis-arkgraphics2d/_o_h___drawing___point2_d.md index 868896f0d4e49f79fa04b2ef759e0d4dce905b9d..c365eda633d6c3281f919335f91900675e416988 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/_o_h___drawing___point2_d.md +++ b/en/application-dev/reference/apis-arkgraphics2d/_o_h___drawing___point2_d.md @@ -3,7 +3,7 @@ ## Overview -The **OH_Drawing_Point2D** struct describes a two-dimensional coordinate point. +The OH_Drawing_Point2D struct describes a two-dimensional coordinate point. **Since**: 12 diff --git a/en/application-dev/reference/apis-arkgraphics2d/_o_h___drawing___point3_d.md b/en/application-dev/reference/apis-arkgraphics2d/_o_h___drawing___point3_d.md index 8259c23be6df50c38fb2467d91aff363e499ac03..84078c824bb97949914de1f59cf6709992f8d799 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/_o_h___drawing___point3_d.md +++ b/en/application-dev/reference/apis-arkgraphics2d/_o_h___drawing___point3_d.md @@ -3,7 +3,7 @@ ## Overview -The **OH_Drawing_Point3D** struct describes a three-dimensional coordinate point. +The OH_Drawing_Point3D struct describes a three-dimensional coordinate point. **Since**: 12 diff --git a/en/application-dev/reference/apis-arkgraphics2d/_o_h___drawing___run_buffer.md b/en/application-dev/reference/apis-arkgraphics2d/_o_h___drawing___run_buffer.md index ecbb73d39d774f34ad962c0b4bf398b7d3b66780..0a660eee441d18b0014dcf01365626d4c31208b8 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/_o_h___drawing___run_buffer.md +++ b/en/application-dev/reference/apis-arkgraphics2d/_o_h___drawing___run_buffer.md @@ -3,7 +3,7 @@ ## Overview -The **OH_Drawing_RunBuffer** struct describes a run, which provides storage for glyphs and positions. +The OH_Drawing_RunBuffer struct describes a run, which provides storage for glyphs and positions. **Since**: 11 diff --git a/en/application-dev/reference/apis-arkgraphics2d/_o_h___drawing___strut_style.md b/en/application-dev/reference/apis-arkgraphics2d/_o_h___drawing___strut_style.md index cafbb445db480b14248b61d4830083b6b84cfe23..76f3fb5c6a28dd215c1cb0c01f0625be402a0889 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/_o_h___drawing___strut_style.md +++ b/en/application-dev/reference/apis-arkgraphics2d/_o_h___drawing___strut_style.md @@ -20,7 +20,7 @@ The OH_Drawing_StrutStyle struct describes a strut style. The strut style determ | [OH_Drawing_FontWeight](_drawing.md#oh_drawing_fontweight) [weight](#weight) | Font weight used for calculating the strut. | | [OH_Drawing_FontStyle](_drawing.md#oh_drawing_fontstyle) [style](#style) | Font style used for calculating the strut. | | double [size](#size) | Size of the ascent plus descent in the logical pixels. | -| double [heightScale](#heightscale) | Line height. | +| double [heightScale](#heightscale) | Scale factor of the line height. | | bool [heightOverride](#heightoverride) | Whether to enable the feature to override the height. The value **true** means to enable the feature, and **false** means the opposite. | | bool [halfLeading](#halfleading) | Whether to enable half leading. The value **true** means to enable half leading, and **false** means the opposite. | | double [leading](#leading) | Custom leading to be applied to the strut. | @@ -92,7 +92,7 @@ double OH_Drawing_StrutStyle::heightScale **Description** -Line height. +Scale factor of the line height. ### leading diff --git a/en/application-dev/reference/apis-arkgraphics2d/_o_h___filter.md b/en/application-dev/reference/apis-arkgraphics2d/_o_h___filter.md index 090be89701a33389d2a95201e7f3ffe140bf329c..1498b71a5de9dfc557256917c89017f0619f992b 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/_o_h___filter.md +++ b/en/application-dev/reference/apis-arkgraphics2d/_o_h___filter.md @@ -3,7 +3,7 @@ ## Overview -The OH_Filter struct describes a filter used to generate a filter pixel map. +The OH_Filter struct describes a filter used to generate a filter PixelMap. **Since**: 12 diff --git a/en/application-dev/reference/apis-arkgraphics2d/_o_h___native_buffer.md b/en/application-dev/reference/apis-arkgraphics2d/_o_h___native_buffer.md index 9339f1e3d9d3f4059956a32d9333d8dd3bcb7f5b..ff420faf48ceca8b41c07b757925e3f93f9d15a0 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/_o_h___native_buffer.md +++ b/en/application-dev/reference/apis-arkgraphics2d/_o_h___native_buffer.md @@ -2,7 +2,7 @@ ## Overview -The **OH_NativeBuffer** module provides the capabilities of **NativeBuffer**. Using the functions provided by this module, you can apply for, use, and release the shared memory, and query its attributes. +The OH_NativeBuffer module provides the capabilities of **NativeBuffer**. Using the functions provided by this module, you can apply for, use, and release the shared memory, and query its properties. **System capability**: SystemCapability.Graphic.Graphic2D.NativeBuffer @@ -16,14 +16,15 @@ The **OH_NativeBuffer** module provides the capabilities of **NativeBuffer**. Us | Name| Description| | -------- | -------- | -| [native_buffer.h](native__buffer_8h.md) | Declares the functions for obtaining and using **NativeBuffer**.| +| [buffer_common.h](buffer__common_8h.md) | Declares the common types used in the NativeBuffer module.
Since API version 12, certain type definitions have been relocated from **native_buffer.h** to this header file for a more cohesive presentation. These types were available prior to API version 12 and can be used seamlessly across all versions.| +| [native_buffer.h](native__buffer_8h.md) | Declares the functions for obtaining and using **NativeBuffer**. | ### Structs | Name| Description| | -------- | -------- | -| struct [OH_NativeBuffer_Config](_o_h___native_buffer___config.md) | Describes the **OH_NativeBuffer** attribute configuration, which is used when you apply for a new **OH_NativeBuffer** instance or query the attributes of an existing instance.| +| struct [OH_NativeBuffer_Config](_o_h___native_buffer___config.md) | Describes the **OH_NativeBuffer** property configuration, which is used when you apply for a new **OH_NativeBuffer** instance or query the properties of an existing instance.| | struct [OH_NativeBuffer_Plane](_o_h___native_buffer___plane.md) | Describes the plane information of an image.| | struct [OH_NativeBuffer_Planes](_o_h___native_buffer___planes.md) | Describes the plane information of images in an **OH_NativeBuffer** instance.| | struct [OH_NativeBuffer_ColorXY](_o_h___native_buffer___color_x_y.md) | Describes the X and Y coordinates of the primary color.| @@ -43,7 +44,7 @@ The **OH_NativeBuffer** module provides the capabilities of **NativeBuffer**. Us | typedef enum [OH_NativeBuffer_TransformType](#oh_nativebuffer_transformtype-1) [OH_NativeBuffer_TransformType](#oh_nativebuffer_transformtype) | Defines an enum for the transform types of an **OH_NativeBuffer** instance.| | typedef enum [OH_NativeBuffer_ColorGamut](#oh_nativebuffer_colorgamut-1) [OH_NativeBuffer_ColorGamut](#oh_nativebuffer_colorgamut) | Defines an enum for the color gamuts of an **OH_NativeBuffer** instance.| | typedef enum [OHNativeErrorCode](_native_window.md#ohnativeerrorcode-1) [OHNativeErrorCode](#ohnativeerrorcode) | Defines an enum for the error codes.| -| typedef struct [OH_NativeBuffer_Config](_o_h___native_buffer___config.md) [OH_NativeBuffer_Config](#oh_nativebuffer_config) | Defines the **OH_NativeBuffer** attribute configuration, which is used when you apply for a new **OH_NativeBuffer** instance or query the attributes of an existing instance.| +| typedef struct [OH_NativeBuffer_Config](_o_h___native_buffer___config.md) [OH_NativeBuffer_Config](#oh_nativebuffer_config) | Defines the **OH_NativeBuffer** property configuration, which is used when you apply for a new **OH_NativeBuffer** instance or query the properties of an existing instance.| | typedef struct [OH_NativeBuffer_Plane](_o_h___native_buffer___plane.md) [OH_NativeBuffer_Plane](#oh_nativebuffer_plane) | Defines a struct for the plane information of an image.| | typedef struct [OH_NativeBuffer_Planes](_o_h___native_buffer___planes.md) [OH_NativeBuffer_Planes](#oh_nativebuffer_planes) | Defines a struct for the plane information of images in an **OH_NativeBuffer** instance.| | typedef enum [OH_NativeBuffer_MetadataType](#oh_nativebuffer_metadatatype) [OH_NativeBuffer_MetadataType](#oh_nativebuffer_metadatatype) | Defines an enum for the **OH_NativeBuffer** image standards.| @@ -59,7 +60,7 @@ The **OH_NativeBuffer** module provides the capabilities of **NativeBuffer**. Us | Name| Description| | -------- | -------- | | [OH_NativeBuffer_Usage](#oh_nativebuffer_usage-1) {
NATIVEBUFFER_USAGE_CPU_READ = (1ULL << 0), NATIVEBUFFER_USAGE_CPU_WRITE = (1ULL << 1), NATIVEBUFFER_USAGE_MEM_DMA = (1ULL << 3), NATIVEBUFFER_USAGE_HW_RENDER = (1ULL << 8),
NATIVEBUFFER_USAGE_HW_TEXTURE = (1ULL << 9), NATIVEBUFFER_USAGE_CPU_READ_OFTEN = (1ULL << 16), NATIVEBUFFER_USAGE_ALIGNMENT_512 = (1ULL << 18)
} | Enumerates the **OH_NativeBuffer** usages.| -| [OH_NativeBuffer_Format](#oh_nativebuffer_format-1) {
NATIVEBUFFER_PIXEL_FMT_CLUT8 = 0, NATIVEBUFFER_PIXEL_FMT_CLUT1, NATIVEBUFFER_PIXEL_FMT_CLUT4, NATIVEBUFFER_PIXEL_FMT_RGB_565 = 3,
NATIVEBUFFER_PIXEL_FMT_RGBA_5658, NATIVEBUFFER_PIXEL_FMT_RGBX_4444, NATIVEBUFFER_PIXEL_FMT_RGBA_4444, NATIVEBUFFER_PIXEL_FMT_RGB_444,
NATIVEBUFFER_PIXEL_FMT_RGBX_5551, NATIVEBUFFER_PIXEL_FMT_RGBA_5551, NATIVEBUFFER_PIXEL_FMT_RGB_555, NATIVEBUFFER_PIXEL_FMT_RGBX_8888,
NATIVEBUFFER_PIXEL_FMT_RGBA_8888, NATIVEBUFFER_PIXEL_FMT_RGB_888, NATIVEBUFFER_PIXEL_FMT_BGR_565, NATIVEBUFFER_PIXEL_FMT_BGRX_4444,
NATIVEBUFFER_PIXEL_FMT_BGRA_4444, NATIVEBUFFER_PIXEL_FMT_BGRX_5551, NATIVEBUFFER_PIXEL_FMT_BGRA_5551, NATIVEBUFFER_PIXEL_FMT_BGRX_8888,
NATIVEBUFFER_PIXEL_FMT_BGRA_8888, NATIVEBUFFER_PIXEL_FMT_YUV_422_I, NATIVEBUFFER_PIXEL_FMT_YCBCR_422_SP, NATIVEBUFFER_PIXEL_FMT_YCRCB_422_SP,
NATIVEBUFFER_PIXEL_FMT_YCBCR_420_SP, NATIVEBUFFER_PIXEL_FMT_YCRCB_420_SP, NATIVEBUFFER_PIXEL_FMT_YCBCR_422_P, NATIVEBUFFER_PIXEL_FMT_YCRCB_422_P,
NATIVEBUFFER_PIXEL_FMT_YCBCR_420_P, NATIVEBUFFER_PIXEL_FMT_YCRCB_420_P, NATIVEBUFFER_PIXEL_FMT_YUYV_422_PKG, NATIVEBUFFER_PIXEL_FMT_UYVY_422_PKG,
NATIVEBUFFER_PIXEL_FMT_YVYU_422_PKG, NATIVEBUFFER_PIXEL_FMT_VYUY_422_PKG, NATIVEBUFFER_PIXEL_FMT_RGBA_1010102, NATIVEBUFFER_PIXEL_FMT_YCBCR_P010,
NATIVEBUFFER_PIXEL_FMT_YCRCB_P010, NATIVEBUFFER_PIXEL_FMT_RAW10, NATIVEBUFFER_PIXEL_FMT_VENDER_MASK = 0X7FFF0000, NATIVEBUFFER_PIXEL_FMT_BUTT = 0X7FFFFFFF
} | Enumerates the **OH_NativeBuffer** formats.| +| [OH_NativeBuffer_Format](#oh_nativebuffer_format-1) {
NATIVEBUFFER_PIXEL_FMT_CLUT8 = 0, NATIVEBUFFER_PIXEL_FMT_CLUT1, NATIVEBUFFER_PIXEL_FMT_CLUT4, NATIVEBUFFER_PIXEL_FMT_RGB_565 = 3,
NATIVEBUFFER_PIXEL_FMT_RGBA_5658, NATIVEBUFFER_PIXEL_FMT_RGBX_4444, NATIVEBUFFER_PIXEL_FMT_RGBA_4444, NATIVEBUFFER_PIXEL_FMT_RGB_444,
NATIVEBUFFER_PIXEL_FMT_RGBX_5551, NATIVEBUFFER_PIXEL_FMT_RGBA_5551, NATIVEBUFFER_PIXEL_FMT_RGB_555, NATIVEBUFFER_PIXEL_FMT_RGBX_8888,
NATIVEBUFFER_PIXEL_FMT_RGBA_8888, NATIVEBUFFER_PIXEL_FMT_RGB_888, NATIVEBUFFER_PIXEL_FMT_BGR_565, NATIVEBUFFER_PIXEL_FMT_BGRX_4444,
NATIVEBUFFER_PIXEL_FMT_BGRA_4444, NATIVEBUFFER_PIXEL_FMT_BGRX_5551, NATIVEBUFFER_PIXEL_FMT_BGRA_5551, NATIVEBUFFER_PIXEL_FMT_BGRX_8888,
NATIVEBUFFER_PIXEL_FMT_BGRA_8888, NATIVEBUFFER_PIXEL_FMT_YUV_422_I, NATIVEBUFFER_PIXEL_FMT_YCBCR_422_SP, NATIVEBUFFER_PIXEL_FMT_YCRCB_422_SP,
NATIVEBUFFER_PIXEL_FMT_YCBCR_420_SP, NATIVEBUFFER_PIXEL_FMT_YCRCB_420_SP, NATIVEBUFFER_PIXEL_FMT_YCBCR_422_P, NATIVEBUFFER_PIXEL_FMT_YCRCB_422_P,
NATIVEBUFFER_PIXEL_FMT_YCBCR_420_P, NATIVEBUFFER_PIXEL_FMT_YCRCB_420_P, NATIVEBUFFER_PIXEL_FMT_YUYV_422_PKG, NATIVEBUFFER_PIXEL_FMT_UYVY_422_PKG,
NATIVEBUFFER_PIXEL_FMT_YVYU_422_PKG, NATIVEBUFFER_PIXEL_FMT_VYUY_422_PKG, NATIVEBUFFER_PIXEL_FMT_RGBA_1010102, NATIVEBUFFER_PIXEL_FMT_YCBCR_P010,
NATIVEBUFFER_PIXEL_FMT_YCRCB_P010, NATIVEBUFFER_PIXEL_FMT_RAW10, NATIVEBUFFER_PIXEL_FMT_BLOB, NATIVEBUFFER_PIXEL_FMT_RGBA16_FLOAT, NATIVEBUFFER_PIXEL_FMT_VENDER_MASK = 0X7FFF0000, NATIVEBUFFER_PIXEL_FMT_BUTT = 0X7FFFFFFF
} | Enumerates the **OH_NativeBuffer** formats.| | [OH_NativeBuffer_ColorSpace](#oh_nativebuffer_colorspace-1) {
OH_COLORSPACE_NONE, OH_COLORSPACE_BT601_EBU_FULL, OH_COLORSPACE_BT601_SMPTE_C_FULL, OH_COLORSPACE_BT709_FULL,
OH_COLORSPACE_BT2020_HLG_FULL, OH_COLORSPACE_BT2020_PQ_FULL, OH_COLORSPACE_BT601_EBU_LIMIT, OH_COLORSPACE_BT601_SMPTE_C_LIMIT,
OH_COLORSPACE_BT709_LIMIT, OH_COLORSPACE_BT2020_HLG_LIMIT, OH_COLORSPACE_BT2020_PQ_LIMIT, OH_COLORSPACE_SRGB_FULL,
OH_COLORSPACE_P3_FULL, OH_COLORSPACE_P3_HLG_FULL, OH_COLORSPACE_P3_PQ_FULL, OH_COLORSPACE_ADOBERGB_FULL,
OH_COLORSPACE_SRGB_LIMIT, OH_COLORSPACE_P3_LIMIT, OH_COLORSPACE_P3_HLG_LIMIT, OH_COLORSPACE_P3_PQ_LIMIT,
OH_COLORSPACE_ADOBERGB_LIMIT, OH_COLORSPACE_LINEAR_SRGB, OH_COLORSPACE_LINEAR_BT709, OH_COLORSPACE_LINEAR_P3,
OH_COLORSPACE_LINEAR_BT2020, OH_COLORSPACE_DISPLAY_SRGB, OH_COLORSPACE_DISPLAY_P3_SRGB, OH_COLORSPACE_DISPLAY_P3_HLG,
OH_COLORSPACE_DISPLAY_P3_PQ, OH_COLORSPACE_DISPLAY_BT2020_SRGB, OH_COLORSPACE_DISPLAY_BT2020_HLG, OH_COLORSPACE_DISPLAY_BT2020_PQ
} | Enumerates the color spaces of an **OH_NativeBuffer** instance.| | [OH_NativeBuffer_TransformType](#oh_nativebuffer_transformtype-1) {
NATIVEBUFFER_ROTATE_NONE = 0, NATIVEBUFFER_ROTATE_90, NATIVEBUFFER_ROTATE_180, NATIVEBUFFER_ROTATE_270,
NATIVEBUFFER_FLIP_H, NATIVEBUFFER_FLIP_V, NATIVEBUFFER_FLIP_H_ROT90, NATIVEBUFFER_FLIP_V_ROT90,
NATIVEBUFFER_FLIP_H_ROT180, NATIVEBUFFER_FLIP_V_ROT180, NATIVEBUFFER_FLIP_H_ROT270, NATIVEBUFFER_FLIP_V_ROT270
} | Enumerates the transform types of an **OH_NativeBuffer** instance.| | [OH_NativeBuffer_ColorGamut](#oh_nativebuffer_colorgamut-1) {
NATIVEBUFFER_COLOR_GAMUT_NATIVE = 0, NATIVEBUFFER_COLOR_GAMUT_STANDARD_BT601 = 1, NATIVEBUFFER_COLOR_GAMUT_STANDARD_BT709 = 2, NATIVEBUFFER_COLOR_GAMUT_DCI_P3 = 3,
NATIVEBUFFER_COLOR_GAMUT_SRGB = 4, NATIVEBUFFER_COLOR_GAMUT_ADOBE_RGB = 5, NATIVEBUFFER_COLOR_GAMUT_DISPLAY_P3 = 6, NATIVEBUFFER_COLOR_GAMUT_BT2020 = 7,
NATIVEBUFFER_COLOR_GAMUT_BT2100_PQ = 8, NATIVEBUFFER_COLOR_GAMUT_BT2100_HLG = 9, NATIVEBUFFER_COLOR_GAMUT_DISPLAY_BT2020 = 10
} | Enumerates the color gamuts of an **OH_NativeBuffer** instance.| @@ -75,9 +76,9 @@ The **OH_NativeBuffer** module provides the capabilities of **NativeBuffer**. Us | [OH_NativeBuffer](#oh_nativebuffer) \* [OH_NativeBuffer_Alloc](#oh_nativebuffer_alloc) (const [OH_NativeBuffer_Config](_o_h___native_buffer___config.md) \*config) | Creates an **OH_NativeBuffer** instance based on an **OH_NativeBuffer_Config** struct. A new **OH_NativeBuffer** instance is created each time this function is called.| | int32_t [OH_NativeBuffer_Reference](#oh_nativebuffer_reference) ([OH_NativeBuffer](#oh_nativebuffer) \*buffer) | Increases the reference count of an **OH_NativeBuffer** instance by 1.| | int32_t [OH_NativeBuffer_Unreference](#oh_nativebuffer_unreference) ([OH_NativeBuffer](#oh_nativebuffer) \*buffer) | Decreases the reference count of an **OH_NativeBuffer** instance by 1 and, when the reference count reaches 0, destroys the instance.| -| void [OH_NativeBuffer_GetConfig](#oh_nativebuffer_getconfig) ([OH_NativeBuffer](#oh_nativebuffer) \*buffer, [OH_NativeBuffer_Config](_o_h___native_buffer___config.md) \*config) | Obtains the attributes of an **OH_NativeBuffer** instance.| -| int32_t [OH_NativeBuffer_Map](#oh_nativebuffer_map) ([OH_NativeBuffer](#oh_nativebuffer) \*buffer, void \*\*virAddr) | Maps the ION memory corresponding to an **OH_NativeBuffer** instance to the process address space.| -| int32_t [OH_NativeBuffer_Unmap](#oh_nativebuffer_unmap) ([OH_NativeBuffer](#oh_nativebuffer) \*buffer) | Unmaps the ION memory corresponding to an **OH_NativeBuffer** instance from the process address space.| +| void [OH_NativeBuffer_GetConfig](#oh_nativebuffer_getconfig) ([OH_NativeBuffer](#oh_nativebuffer) \*buffer, [OH_NativeBuffer_Config](_o_h___native_buffer___config.md) \*config) | Obtains the properties of an **OH_NativeBuffer** instance.| +| int32_t [OH_NativeBuffer_Map](#oh_nativebuffer_map) ([OH_NativeBuffer](#oh_nativebuffer) \*buffer, void \*\*virAddr) | Maps the ION memory allocated to an **OH_NativeBuffer** instance to the process address space.| +| int32_t [OH_NativeBuffer_Unmap](#oh_nativebuffer_unmap) ([OH_NativeBuffer](#oh_nativebuffer) \*buffer) | Unmaps the ION memory allocated to an **OH_NativeBuffer** instance from the process address space.| | uint32_t [OH_NativeBuffer_GetSeqNum](#oh_nativebuffer_getseqnum) ([OH_NativeBuffer](#oh_nativebuffer) \*buffer) | Obtains the sequence number of an **OH_NativeBuffer** instance.| | int32_t [OH_NativeBuffer_SetColorSpace](#oh_nativebuffer_setcolorspace) ([OH_NativeBuffer](#oh_nativebuffer) \*buffer, [OH_NativeBuffer_ColorSpace](#oh_nativebuffer_colorspace) colorSpace) | Sets the color space for an **OH_NativeBuffer** instance.| | int32_t [OH_NativeBuffer_MapPlanes](#oh_nativebuffer_mapplanes) ([OH_NativeBuffer](#oh_nativebuffer) \*buffer, void \*\*virAddr, [OH_NativeBuffer_Planes](_o_h___native_buffer___planes.md) \*outPlanes) | Maps the multi-channel ION memory corresponding to an **OH_NativeBuffer** instance to the process address space.| @@ -156,7 +157,7 @@ typedef struct OH_NativeBuffer_Config OH_NativeBuffer_Config **Description** -Defines the **OH_NativeBuffer** attribute configuration, which is used when you apply for a new **OH_NativeBuffer** instance or query the attributes of an existing instance. +Defines the **OH_NativeBuffer** property configuration, which is used when you apply for a new **OH_NativeBuffer** instance or query the properties of an existing instance. **System capability**: SystemCapability.Graphic.Graphic2D.NativeBuffer @@ -462,6 +463,8 @@ Enumerates the **OH_NativeBuffer** formats. | NATIVEBUFFER_PIXEL_FMT_YCBCR_P01012+ | YCBCR420 semi-planar 10-bit packed.| | NATIVEBUFFER_PIXEL_FMT_YCRCB_P01012+ | YCRCB420 semi-planar 10-bit packed.| | NATIVEBUFFER_PIXEL_FMT_RAW1012+ | Raw 10-bit packed.| +| NATIVEBUFFER_PIXEL_FMT_BLOB15+ | BLOB.| +| NATIVEBUFFER_PIXEL_FMT_RGBA16_FLOAT15+ | RGBA16 float.| | NATIVEBUFFER_PIXEL_FMT_VENDER_MASK12+ | Vendor mask.| | NATIVEBUFFER_PIXEL_FMT_BUTT | Invalid format.| @@ -696,7 +699,7 @@ void OH_NativeBuffer_GetConfig (OH_NativeBuffer *buffer, OH_NativeBuffer_Config* **Description** -Obtains the attributes of an **OH_NativeBuffer** instance. +Obtains the properties of an **OH_NativeBuffer** instance. This function is not thread-safe. @@ -709,7 +712,7 @@ This function is not thread-safe. | Name| Description| | -------- | -------- | | buffer | Pointer to an **OH_NativeBuffer** instance.| -| config | Pointer to an **OH_NativeBuffer_Config** instance, which is used to receive the attributes of **OH_NativeBuffer**.| +| config | Pointer to an **OH_NativeBuffer_Config** instance, which is used to receive the properties of **OH_NativeBuffer**.| ### OH_NativeBuffer_GetMetadataValue() @@ -777,7 +780,7 @@ int32_t OH_NativeBuffer_Map (OH_NativeBuffer *buffer, void **virAddr ) **Description** -Maps the ION memory corresponding to an **OH_NativeBuffer** instance to the process address space. +Maps the ION memory allocated to an **OH_NativeBuffer** instance to the process address space. This function must be used in pair with **OH_NativeBuffer_Unmap**. @@ -923,7 +926,7 @@ int32_t OH_NativeBuffer_Unmap (OH_NativeBuffer *buffer) **Description** -Unmaps the ION memory corresponding to an **OH_NativeBuffer** instance from the process address space. +Unmaps the ION memory allocated to an **OH_NativeBuffer** instance from the process address space. This function is not thread-safe. diff --git a/en/application-dev/reference/apis-arkgraphics2d/_o_h___native_buffer___plane.md b/en/application-dev/reference/apis-arkgraphics2d/_o_h___native_buffer___plane.md index fc55bdd8be6e08479db62bde661db92f79265008..e306ce9f37abbd4428d5700c09a7f5ab99df08cc 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/_o_h___native_buffer___plane.md +++ b/en/application-dev/reference/apis-arkgraphics2d/_o_h___native_buffer___plane.md @@ -33,6 +33,7 @@ The OH_NativeBuffer_Plane struct describes the plane information of an image. uint32_t OH_NativeBuffer_Plane::columnStride ``` **Description** + Distance from the first value in an image column to the first value in the next column, in bytes. @@ -42,6 +43,7 @@ Distance from the first value in an image column to the first value in the next uint64_t OH_NativeBuffer_Plane::offset ``` **Description** + Offset of the image plane, in bytes. @@ -51,4 +53,5 @@ Offset of the image plane, in bytes. uint32_t OH_NativeBuffer_Plane::rowStride ``` **Description** + Distance from the first value in an image row to the first value in the next row, in bytes. diff --git a/en/application-dev/reference/apis-arkgraphics2d/_o_h___native_buffer___smpte2086.md b/en/application-dev/reference/apis-arkgraphics2d/_o_h___native_buffer___smpte2086.md index 3936f585d0438ac4be6ce4dcb7f18687fc7b9b59..87b7cd27b2ffc07a0f8f971a2b5a3192bf704a4d 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/_o_h___native_buffer___smpte2086.md +++ b/en/application-dev/reference/apis-arkgraphics2d/_o_h___native_buffer___smpte2086.md @@ -19,9 +19,9 @@ The OH_NativeBuffer_Smpte2086 struct describes the SMPTE ST 2086 static metadata | Name| Description| | -------- | -------- | -| [OH_NativeBuffer_ColorXY](_o_h___native_buffer___color_x_y.md) [displaPrimaryRed](#displaprimaryred) | Red primary color.| -| [OH_NativeBuffer_ColorXY](_o_h___native_buffer___color_x_y.md) [displaPrimaryGreen](#displaprimarygreen) | Green primary color.| -| [OH_NativeBuffer_ColorXY](_o_h___native_buffer___color_x_y.md) [displaPrimaryBlue](#displaprimaryblue) | Blue primary color.| +| [OH_NativeBuffer_ColorXY](_o_h___native_buffer___color_x_y.md) [displayPrimaryRed](#displayprimaryred) | Red primary color.| +| [OH_NativeBuffer_ColorXY](_o_h___native_buffer___color_x_y.md) [displayPrimaryGreen](#displayprimarygreen) | Green primary color.| +| [OH_NativeBuffer_ColorXY](_o_h___native_buffer___color_x_y.md) [displayPrimaryBlue](#displayprimaryblue) | Blue primary color.| | [OH_NativeBuffer_ColorXY](_o_h___native_buffer___color_x_y.md) [whitePoint](#whitepoint) | White point.| | float [maxLuminance](#maxluminance) | Maximum luminance.| | float [minLuminance](#minluminance) | Minimum luminance.| @@ -30,10 +30,10 @@ The OH_NativeBuffer_Smpte2086 struct describes the SMPTE ST 2086 static metadata ## Member Variable Description -### displaPrimaryBlue +### displayPrimaryBlue ``` -OH_NativeBuffer_ColorXY OH_NativeBuffer_Smpte2086::displaPrimaryBlue +OH_NativeBuffer_ColorXY OH_NativeBuffer_Smpte2086::displayPrimaryBlue ``` **Description** @@ -41,10 +41,10 @@ OH_NativeBuffer_ColorXY OH_NativeBuffer_Smpte2086::displaPrimaryBlue Blue primary color. -### displaPrimaryGreen +### displayPrimaryGreen ``` -OH_NativeBuffer_ColorXY OH_NativeBuffer_Smpte2086::displaPrimaryGreen +OH_NativeBuffer_ColorXY OH_NativeBuffer_Smpte2086::displayPrimaryGreen ``` **Description** @@ -52,10 +52,10 @@ OH_NativeBuffer_ColorXY OH_NativeBuffer_Smpte2086::displaPrimaryGreen Green primary color. -### displaPrimaryRed +### displayPrimaryRed ``` -OH_NativeBuffer_ColorXY OH_NativeBuffer_Smpte2086::displaPrimaryRed +OH_NativeBuffer_ColorXY OH_NativeBuffer_Smpte2086::displayPrimaryRed ``` **Description** diff --git a/en/application-dev/reference/apis-arkgraphics2d/_o_h___native_image.md b/en/application-dev/reference/apis-arkgraphics2d/_o_h___native_image.md index a1985c62d4e0b3e91e38aed2f4f31911bb672d75..f01f657ed4979352dc860d141f5b9a82d39cde49 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/_o_h___native_image.md +++ b/en/application-dev/reference/apis-arkgraphics2d/_o_h___native_image.md @@ -3,7 +3,7 @@ ## Overview -The **OH_NativeImage** module provides the capabilities of **NativeImage**. Functioning as a data consumer, it is used to associate data with the OpenGL texture. It is used in the OpenGL environment. +The OH_NativeImage module provides the capabilities of **NativeImage**. Functioning as a data consumer, it is used to associate data with the OpenGL texture. It is used in the OpenGL environment. Alternatively, you can directly obtain the buffer for custom rendering. **System capability**: SystemCapability.Graphic.Graphic2D.NativeImage @@ -31,11 +31,11 @@ The **OH_NativeImage** module provides the capabilities of **NativeImage**. Func | Name| Description| | -------- | -------- | -| typedef struct [OH_NativeImage](#oh_nativeimage) [OH_NativeImage](#oh_nativeimage) | Provides the declaration of an **OH_NativeImage** struct. | +| typedef struct [OH_NativeImage](#oh_nativeimage-1) [OH_NativeImage](#oh_nativeimage-1) | Provides the declaration of an **OH_NativeImage** struct. | | typedef struct NativeWindow [OHNativeWindow](#ohnativewindow) | Provides the capability of accessing the **NativeWindow**. | | typedef struct NativeWindowBuffer [OHNativeWindowBuffer](#ohnativewindowbuffer) | Provides the declaration of a **NativeWindowBuffer** struct.| | typedef void(\* [OH_OnFrameAvailable](#oh_onframeavailable)) (void \*context) | Defines the callback function triggered when a frame is available. | -| typedef struct [OH_OnFrameAvailableListener](_o_h___on_frame_available_listener.md) [OH_OnFrameAvailableListener](#oh_onframeavailablelistener) | Defines an **OH_NativeImage** listener, which is registered through **OH_NativeImage_SetOnFrameAvailableListener**. The listener triggers a callback when a frame is available. | +| typedef struct [OH_OnFrameAvailableListener](_o_h___on_frame_available_listener.md) [OH_OnFrameAvailableListener](#oh_onframeavailablelistener) | Defines an **OH_NativeImage** listener, which is registered through [OH_NativeImage_SetOnFrameAvailableListener](#oh_nativeimage_setonframeavailablelistener). The listener triggers a callback when a frame is available.| | typedef enum [OHNativeErrorCode](#ohnativeerrorcode) [OHNativeErrorCode](#ohnativeerrorcode) | Defines an enum for the error codes. | ### Enums @@ -48,24 +48,24 @@ The **OH_NativeImage** module provides the capabilities of **NativeImage**. Func | Name| Description| | -------- | -------- | -| [OH_NativeImage](#oh_nativeimage) \* [OH_NativeImage_Create](#oh_nativeimage_create) (uint32_t textureId, uint32_t textureTarget) | Creates an **OH_NativeImage** instance to be associated with the OpenGL ES texture ID and target.
This function must be used in pair with [OH_NativeImage_Destroy](#oh_nativeimage_destroy). Otherwise, memory leak occurs.
This function is not thread-safe.| -| [OHNativeWindow](_native_window.md#ohnativewindow) \* [OH_NativeImage_AcquireNativeWindow](#oh_nativeimage_acquirenativewindow) ([OH_NativeImage](#oh_nativeimage) \*image) | Obtains an **OHNativeWindow** instance associated with an **OH_NativeImage** instance.
This function is not thread-safe.
When **OH_NativeImage** is being destructed, the corresponding **OHNativeWindow** instance is released. If the **OHNativeWindow** pointer is obtained by using this function, set the pointer to null when releasing the **OH_NativeImage** instance, so as to prevent subsequent wild pointers.| -| int32_t [OH_NativeImage_AttachContext](#oh_nativeimage_attachcontext) ([OH_NativeImage](#oh_nativeimage) \*image, uint32_t textureId) | Attaches an **OH_NativeImage** instance to the current OpenGL ES context. The OpenGL ES texture will be bound to an **GL_TEXTURE_EXTERNAL_OES** instance and updated through the **OH_NativeImage** instance.
This function is not thread-safe.| -| int32_t [OH_NativeImage_DetachContext](#oh_nativeimage_detachcontext) ([OH_NativeImage](#oh_nativeimage) \*image) | Detaches an **OH_NativeImage** instance from the current OpenGL ES context.
This function is not thread-safe.| -| int32_t [OH_NativeImage_UpdateSurfaceImage](#oh_nativeimage_updatesurfaceimage) ([OH_NativeImage](#oh_nativeimage) \*image) | Updates the OpenGL ES texture associated with the latest frame through an **OH_NativeImage** instance.
This function must be called in a thread of the OpenGL ES context.
This function must be called after the [OH_OnFrameAvailableListener](_o_h___on_frame_available_listener.md) callback is triggered.
This function is not thread-safe.| -| int64_t [OH_NativeImage_GetTimestamp](#oh_nativeimage_gettimestamp) ([OH_NativeImage](#oh_nativeimage) \*image) | Obtains the timestamp of the texture image that recently called the **OH_NativeImage_UpdateSurfaceImage** function.
This function is not thread-safe.| -| int32_t [OH_NativeImage_GetTransformMatrix](#oh_nativeimage_gettransformmatrix) ([OH_NativeImage](#oh_nativeimage) \*image, float matrix[16]) | Obtains the transformation matrix of the texture image that recently called the **OH_NativeImage_UpdateSurfaceImage** function.| -| int32_t [OH_NativeImage_GetSurfaceId](#oh_nativeimage_getsurfaceid) ([OH_NativeImage](#oh_nativeimage) \*image, uint64_t \*surfaceId) | Obtains the surface ID of an **OH_NativeImage** instance.
This function is not thread-safe.| -| int32_t [OH_NativeImage_SetOnFrameAvailableListener](#oh_nativeimage_setonframeavailablelistener) ([OH_NativeImage](#oh_nativeimage) \*image, [OH_OnFrameAvailableListener](_o_h___on_frame_available_listener.md) listener) | Registers a listener to listen for frame availability events.
Do not call other functions of this module in the callback.
This function is not thread-safe.| -| int32_t [OH_NativeImage_UnsetOnFrameAvailableListener](#oh_nativeimage_unsetonframeavailablelistener) ([OH_NativeImage](#oh_nativeimage) \*image) | Deregisters the listener used to listen for frame availability events.
This function is not thread-safe.| -| void [OH_NativeImage_Destroy](#oh_nativeimage_destroy) ([OH_NativeImage](#oh_nativeimage) \*\*image) | Destroys an **OH_NativeImage** instance created by calling **OH_NativeImage_Create**. After the instance is destroyed,
the pointer to the **OH_NativeImage** instance is assigned **NULL**.
This function is not thread-safe.| -| int32_t [OH_NativeImage_GetTransformMatrixV2](#oh_nativeimage_gettransformmatrixv2) ([OH_NativeImage](#oh_nativeimage) \*image, float matrix[16]) | Obtains, based on the rotation angle set by the producer, the transform matrix of the texture image that recently called the **OH_NativeImage_UpdateSurfaceImage** function.
The matrix is updated only after [OH_NativeImage_UpdateSurfaceImage](#oh_nativeimage_updatesurfaceimage) is called.
This function is not thread-safe.| -| int32_t [OH_NativeImage_GetBufferMatrix](#oh_nativeimage_getbuffermatrix) ([OH_NativeImage](#oh_nativeimage) \*image, float matrix[16]) | Obtains the transformation matrix calculated based on the rotation angle set by the producer and the actual valid content area of the buffer.| -| int32_t [OH_NativeImage_AcquireNativeWindowBuffer](#oh_nativeimage_acquirenativewindowbuffer) ([OH_NativeImage](#oh_nativeimage) \*image, [OHNativeWindowBuffer](_native_window.md#ohnativewindowbuffer) \*\*nativeWindowBuffer, int \*fenceFd) | Obtains an **OHNativeWindowBuffer** instance through an **OH_NativeImage** instance on the consumer side.
This function cannot be used together with [OH_NativeImage_UpdateSurfaceImage](#oh_nativeimage_updatesurfaceimage).
This function creates an **OHNativeWindowBuffer**.
When using the **OHNativeWindowBuffer**, call [OH_NativeWindow_NativeObjectReference](_native_window.md#oh_nativewindow_nativeobjectreference) to increase its reference count by one.
When finishing using the **OHNativeWindowBuffer**, call [OH_NativeWindow_NativeObjectUnreference](_native_window.md#oh_nativewindow_nativeobjectunreference) to decrease the reference count by one.
This function must be used in pair with [OH_NativeImage_ReleaseNativeWindowBuffer](#oh_nativeimage_releasenativewindowbuffer). Otherwise, memory leak occurs.
When **fenceFd** is used up, you must close it.
This function is not thread-safe.| -| int32_t [OH_NativeImage_ReleaseNativeWindowBuffer](#oh_nativeimage_releasenativewindowbuffer) ([OH_NativeImage](#oh_nativeimage) \*image, [OHNativeWindowBuffer](_native_window.md#ohnativewindowbuffer) \*nativeWindowBuffer, int fenceFd) | Releases an **OHNativeWindowBuffer** instance through an **OH_NativeImage** instance.
The system will close **fenFd**. You do not need to close it.
This function is not thread-safe.| -| [OH_NativeImage](#oh_nativeimage) \* [OH_ConsumerSurface_Create](#oh_consumersurface_create) () | Creates an **OH_NativeImage** instance as the consumer of the surface.
This function is used only for memory cycling of the surface consumer. Memory rendering is not proactively performed in the created **OH_NativeImage** instance.
This function cannot be used together with [OH_NativeImage_UpdateSurfaceImage](#oh_nativeimage_updatesurfaceimage).
This function must be used in pair with **OH_NativeImage_AcquireNativeWindowBuffer** and **OH_NativeImage_ReleaseNativeWindowBuffer**.
This function must be used in pair with [OH_NativeImage_Destroy](#oh_nativeimage_destroy). Otherwise, memory leak occurs.
This function is not thread-safe.| -| int32_t [OH_ConsumerSurface_SetDefaultUsage](#oh_consumersurface_setdefaultusage) ([OH_NativeImage](#oh_nativeimage) \*image, uint64_t usage) | Sets the default read/write mode. This function is not thread-safe.| -| int32_t [OH_ConsumerSurface_SetDefaultSize](#oh_consumersurface_setdefaultsize) ([OH_NativeImage](#oh_nativeimage) \*image, int32_t width, int32_t height) | Sets the default size of a geometric shape. This function is not thread-safe.| +| [OH_NativeImage](#oh_nativeimage-1) \* [OH_NativeImage_Create](#oh_nativeimage_create) (uint32_t textureId, uint32_t textureTarget) | Creates an **OH_NativeImage** instance to be associated with the OpenGL ES texture ID and target.
This function must be used in pair with [OH_NativeImage_Destroy](#oh_nativeimage_destroy). Otherwise, memory leak occurs.
This function is not thread-safe.| +| [OHNativeWindow](_native_window.md#ohnativewindow) \* [OH_NativeImage_AcquireNativeWindow](#oh_nativeimage_acquirenativewindow) ([OH_NativeImage](#oh_nativeimage-1) \*image) | Obtains an **OHNativeWindow** instance associated with an **OH_NativeImage** instance.
This function is not thread-safe.
When **OH_NativeImage** is being destructed, the corresponding **OHNativeWindow** instance is released. If the **OHNativeWindow** pointer is obtained by using this function, set the pointer to null when releasing the **OH_NativeImage** instance, so as to prevent subsequent wild pointers.| +| int32_t [OH_NativeImage_AttachContext](#oh_nativeimage_attachcontext) ([OH_NativeImage](#oh_nativeimage-1) \*image, uint32_t textureId) | Attaches an **OH_NativeImage** instance to the current OpenGL ES context. The OpenGL ES texture will be bound to an **GL_TEXTURE_EXTERNAL_OES** instance and updated through the **OH_NativeImage** instance.
This function is not thread-safe.| +| int32_t [OH_NativeImage_DetachContext](#oh_nativeimage_detachcontext) ([OH_NativeImage](#oh_nativeimage-1) \*image) | Detaches an **OH_NativeImage** instance from the current OpenGL ES context.
This function is not thread-safe.| +| int32_t [OH_NativeImage_UpdateSurfaceImage](#oh_nativeimage_updatesurfaceimage) ([OH_NativeImage](#oh_nativeimage-1) \*image) | Updates the OpenGL ES texture associated with the latest frame through an **OH_NativeImage** instance.
This function must be called in a thread of the OpenGL ES context.
This function must be called after the [OH_OnFrameAvailableListener](_o_h___on_frame_available_listener.md) callback is triggered.
This function is not thread-safe.| +| int64_t [OH_NativeImage_GetTimestamp](#oh_nativeimage_gettimestamp) ([OH_NativeImage](#oh_nativeimage-1) \*image) | Obtains the timestamp of the texture image that recently called the **OH_NativeImage_UpdateSurfaceImage** function.
This function is not thread-safe.| +| int32_t [OH_NativeImage_GetTransformMatrix](#oh_nativeimage_gettransformmatrix) ([OH_NativeImage](#oh_nativeimage-1) \*image, float matrix[16]) | Obtains the transformation matrix of the texture image that recently called the **OH_NativeImage_UpdateSurfaceImage** function.| +| int32_t [OH_NativeImage_GetSurfaceId](#oh_nativeimage_getsurfaceid) ([OH_NativeImage](#oh_nativeimage-1) \*image, uint64_t \*surfaceId) | Obtains the surface ID of an **OH_NativeImage** instance.
This function is not thread-safe.| +| int32_t [OH_NativeImage_SetOnFrameAvailableListener](#oh_nativeimage_setonframeavailablelistener) ([OH_NativeImage](#oh_nativeimage-1) \*image, [OH_OnFrameAvailableListener](_o_h___on_frame_available_listener.md) listener) | Registers a listener to listen for frame availability events.
Do not call other functions of this module in the callback.
This function is not thread-safe.| +| int32_t [OH_NativeImage_UnsetOnFrameAvailableListener](#oh_nativeimage_unsetonframeavailablelistener) ([OH_NativeImage](#oh_nativeimage-1) \*image) | Deregisters the listener used to listen for frame availability events.
This function is not thread-safe.| +| void [OH_NativeImage_Destroy](#oh_nativeimage_destroy) ([OH_NativeImage](#oh_nativeimage-1) \*\*image) | Destroys an **OH_NativeImage** instance created by calling **OH_NativeImage_Create**. After the instance is destroyed,
the pointer to the **OH_NativeImage** instance is assigned **NULL**.
This function is not thread-safe.| +| int32_t [OH_NativeImage_GetTransformMatrixV2](#oh_nativeimage_gettransformmatrixv2) ([OH_NativeImage](#oh_nativeimage-1) \*image, float matrix[16]) | Obtains, based on the rotation angle set by the producer, the transform matrix of the texture image that recently called the **OH_NativeImage_UpdateSurfaceImage** function.
The matrix is updated only after [OH_NativeImage_UpdateSurfaceImage](#oh_nativeimage_updatesurfaceimage) is called.
This function is not thread-safe.| +| int32_t [OH_NativeImage_GetBufferMatrix](#oh_nativeimage_getbuffermatrix) ([OH_NativeImage](#oh_nativeimage-1) \*image, float matrix[16]) | Obtains the transformation matrix calculated based on the rotation angle set by the producer and the actual valid content area of the buffer.| +| int32_t [OH_NativeImage_AcquireNativeWindowBuffer](#oh_nativeimage_acquirenativewindowbuffer) ([OH_NativeImage](#oh_nativeimage-1) \*image, [OHNativeWindowBuffer](_native_window.md#ohnativewindowbuffer) \*\*nativeWindowBuffer, int \*fenceFd) | Obtains an **OHNativeWindowBuffer** instance through an **OH_NativeImage** instance on the consumer side.
This function cannot be used together with [OH_NativeImage_UpdateSurfaceImage](#oh_nativeimage_updatesurfaceimage).
This function creates an **OHNativeWindowBuffer**.
When using the **OHNativeWindowBuffer**, call [OH_NativeWindow_NativeObjectReference](_native_window.md#oh_nativewindow_nativeobjectreference) to increase its reference count by one.
When finishing using the **OHNativeWindowBuffer**, call [OH_NativeWindow_NativeObjectUnreference](_native_window.md#oh_nativewindow_nativeobjectunreference) to decrease the reference count by one.
This function must be used in pair with [OH_NativeImage_ReleaseNativeWindowBuffer](#oh_nativeimage_releasenativewindowbuffer). Otherwise, memory leak occurs.
When **fenceFd** is used up, you must close it.
This function is not thread-safe.| +| int32_t [OH_NativeImage_ReleaseNativeWindowBuffer](#oh_nativeimage_releasenativewindowbuffer) ([OH_NativeImage](#oh_nativeimage-1) \*image, [OHNativeWindowBuffer](_native_window.md#ohnativewindowbuffer) \*nativeWindowBuffer, int fenceFd) | Releases an **OHNativeWindowBuffer** instance through an **OH_NativeImage** instance.
The system will close **fenFd**. You do not need to close it.
This function is not thread-safe.| +| [OH_NativeImage](#oh_nativeimage-1) \* [OH_ConsumerSurface_Create](#oh_consumersurface_create) () | Creates an **OH_NativeImage** instance as the consumer of the surface.
This function is used only for memory cycling of the surface consumer. Memory rendering is not proactively performed in the created **OH_NativeImage** instance.
This function cannot be used together with [OH_NativeImage_UpdateSurfaceImage](#oh_nativeimage_updatesurfaceimage).
This function must be used in pair with **OH_NativeImage_AcquireNativeWindowBuffer** and **OH_NativeImage_ReleaseNativeWindowBuffer**.
This function must be used in pair with [OH_NativeImage_Destroy](#oh_nativeimage_destroy). Otherwise, memory leak occurs.
This function is not thread-safe.| +| int32_t [OH_ConsumerSurface_SetDefaultUsage](#oh_consumersurface_setdefaultusage) ([OH_NativeImage](#oh_nativeimage-1) \*image, uint64_t usage) | Sets the default read/write mode. This function is not thread-safe.| +| int32_t [OH_ConsumerSurface_SetDefaultSize](#oh_consumersurface_setdefaultsize) ([OH_NativeImage](#oh_nativeimage-1) \*image, int32_t width, int32_t height) | Sets the default size of a geometric shape. This function is not thread-safe.| ## Type Description @@ -204,7 +204,7 @@ int32_t OH_NativeImage_GetBufferMatrix (OH_NativeImage* image, float matrix[16] Obtains the transformation matrix calculated based on the rotation angle set by the producer and the actual valid content area of the buffer. -This function returns a transformation matrix that is determined by the buffer's rotation angle and actual valid content area during the consumption of the buffer by [OH_NativeImage](#oh_nativeimage), specifically when invoking the function [OH_NativeImage_UpdateSurfaceImage](#oh_nativeimage_updatesurfaceimage) or [OH_NativeImage_AcquireNativeWindowBuffer](#oh_nativeimage_acquirenativewindowbuffer). +This function returns a transformation matrix that is determined by the buffer's rotation angle and actual valid content area during the consumption of the buffer by [OH_NativeImage](#oh_nativeimage-1), specifically when invoking the function [OH_NativeImage_UpdateSurfaceImage](#oh_nativeimage_updatesurfaceimage) or [OH_NativeImage_AcquireNativeWindowBuffer](#oh_nativeimage_acquirenativewindowbuffer). This function is not thread-safe. @@ -216,7 +216,7 @@ This function is not thread-safe. | Name| Description| | -------- | -------- | -| image | Pointer to an [OH_NativeImage](#oh_nativeimage) instance.| +| image | Pointer to an [OH_NativeImage](#oh_nativeimage-1) instance.| | matrix | Buffer used to store the 4 x 4 transformation matrix obtained.| **Returns** diff --git a/en/application-dev/reference/apis-arkgraphics2d/buffer__common_8h.md b/en/application-dev/reference/apis-arkgraphics2d/buffer__common_8h.md new file mode 100644 index 0000000000000000000000000000000000000000..0491ab3c731d3e7e8118e65ac02cc418952ecc82 --- /dev/null +++ b/en/application-dev/reference/apis-arkgraphics2d/buffer__common_8h.md @@ -0,0 +1,51 @@ +# buffer_common.h + + +## Overview + +The **buffer_common.h** file declares the common types used in the NativeBuffer module. + +Certain type definitions have been relocated from **native_buffer.h** to this header file for a more cohesive presentation. These types were available prior to API version 12 and can be used seamlessly across all versions. + +**Library**: libnative_buffer.so + +**System capability**: SystemCapability.Graphic.Graphic2D.NativeBuffer + +**Since**: 12 + +**Related module**: [OH_NativeBuffer](_o_h___native_buffer.md) + + +## Summary + + +### Structs + +| Name| Description| +| -------- | -------- | +| struct [OH_NativeBuffer_ColorXY](_o_h___native_buffer___color_x_y.md) | Describes the X and Y coordinates of the primary color. | +| struct [OH_NativeBuffer_Smpte2086](_o_h___native_buffer___smpte2086.md) | Describes the SMPTE ST 2086 static metadata. | +| struct [OH_NativeBuffer_Cta861](_o_h___native_buffer___cta861.md) | Describes the CTA-861.3 static metadata. | +| struct [OH_NativeBuffer_StaticMetadata](_o_h___native_buffer___static_metadata.md) | Describes the HDR static metadata. | + + +### Types + +| Name| Description| +| -------- | -------- | +| typedef enum [OH_NativeBuffer_ColorSpace](_o_h___native_buffer.md#oh_nativebuffer_colorspace) [OH_NativeBuffer_ColorSpace](_o_h___native_buffer.md#oh_nativebuffer_colorspace) | Defines an enum for the color spaces of an **OH_NativeBuffer** instance. It is relocated from **native_buffer.h** to this header file for a more cohesive presentation. | +| typedef enum [OH_NativeBuffer_MetadataType](_o_h___native_buffer.md#oh_nativebuffer_metadatatype) [OH_NativeBuffer_MetadataType](_o_h___native_buffer.md#oh_nativebuffer_metadatatype) | Defines an enum for the **OH_NativeBuffer** image standards. | +| typedef struct [OH_NativeBuffer_ColorXY](_o_h___native_buffer___color_x_y.md) [OH_NativeBuffer_ColorXY](_o_h___native_buffer.md#oh_nativebuffer_colorxy) | Defines a struct for the X and Y coordinates of the primary color. | +| typedef struct [OH_NativeBuffer_Smpte2086](_o_h___native_buffer___smpte2086.md) [OH_NativeBuffer_Smpte2086](_o_h___native_buffer.md#oh_nativebuffer_smpte2086) | Defines a struct for the SMPTE ST 2086 static metadata. | +| typedef struct [OH_NativeBuffer_Cta861](_o_h___native_buffer___cta861.md) [OH_NativeBuffer_Cta861](_o_h___native_buffer.md#oh_nativebuffer_cta861) | Defines a struct for the CTA-861.3 static metadata. | +| typedef struct [OH_NativeBuffer_StaticMetadata](_o_h___native_buffer___static_metadata.md) [OH_NativeBuffer_StaticMetadata](_o_h___native_buffer.md#oh_nativebuffer_staticmetadata) | Defines a struct for the HDR static metadata. | +| typedef enum [OH_NativeBuffer_MetadataKey](_o_h___native_buffer.md#oh_nativebuffer_metadatakey) [OH_NativeBuffer_MetadataKey](_o_h___native_buffer.md#oh_nativebuffer_metadatakey) | Defines an enum for the keys that specify the HDR metadata of an **OH_NativeBuffer** instance. | + + +### Enums + +| Name| Description| +| -------- | -------- | +| [OH_NativeBuffer_ColorSpace](_o_h___native_buffer.md#oh_nativebuffer_colorspace-1) {
OH_COLORSPACE_NONE, OH_COLORSPACE_BT601_EBU_FULL, OH_COLORSPACE_BT601_SMPTE_C_FULL, OH_COLORSPACE_BT709_FULL,
OH_COLORSPACE_BT2020_HLG_FULL, OH_COLORSPACE_BT2020_PQ_FULL, OH_COLORSPACE_BT601_EBU_LIMIT, OH_COLORSPACE_BT601_SMPTE_C_LIMIT,
OH_COLORSPACE_BT709_LIMIT, OH_COLORSPACE_BT2020_HLG_LIMIT, OH_COLORSPACE_BT2020_PQ_LIMIT, OH_COLORSPACE_SRGB_FULL,
OH_COLORSPACE_P3_FULL, OH_COLORSPACE_P3_HLG_FULL, OH_COLORSPACE_P3_PQ_FULL, OH_COLORSPACE_ADOBERGB_FULL,
OH_COLORSPACE_SRGB_LIMIT, OH_COLORSPACE_P3_LIMIT, OH_COLORSPACE_P3_HLG_LIMIT, OH_COLORSPACE_P3_PQ_LIMIT,
OH_COLORSPACE_ADOBERGB_LIMIT, OH_COLORSPACE_LINEAR_SRGB, OH_COLORSPACE_LINEAR_BT709, OH_COLORSPACE_LINEAR_P3,
OH_COLORSPACE_LINEAR_BT2020, OH_COLORSPACE_DISPLAY_SRGB, OH_COLORSPACE_DISPLAY_P3_SRGB, OH_COLORSPACE_DISPLAY_P3_HLG,
OH_COLORSPACE_DISPLAY_P3_PQ, OH_COLORSPACE_DISPLAY_BT2020_SRGB, OH_COLORSPACE_DISPLAY_BT2020_HLG, OH_COLORSPACE_DISPLAY_BT2020_PQ
} | Enumerates the color spaces of an **OH_NativeBuffer** instance. It is relocated from **native_buffer.h** to this header file for a more cohesive presentation. | +| [OH_NativeBuffer_MetadataType](_o_h___native_buffer.md#oh_nativebuffer_metadatatype-1) { OH_VIDEO_HDR_HLG, OH_VIDEO_HDR_HDR10, OH_VIDEO_HDR_VIVID, OH_VIDEO_NONE = -1 } | Enumerates the **OH_NativeBuffer** image standards. | +| [OH_NativeBuffer_MetadataKey](_o_h___native_buffer.md#oh_nativebuffer_metadatakey-1) { OH_HDR_METADATA_TYPE, OH_HDR_STATIC_METADATA, OH_HDR_DYNAMIC_METADATA } | Enumerates the keys that specify the HDR metadata of an **OH_NativeBuffer** instance. | diff --git a/en/application-dev/reference/apis-arkgraphics2d/buffer__handle_8h.md b/en/application-dev/reference/apis-arkgraphics2d/buffer__handle_8h.md new file mode 100644 index 0000000000000000000000000000000000000000..4dafae15019caeb1cedf803ab61e3bf439f39f5f --- /dev/null +++ b/en/application-dev/reference/apis-arkgraphics2d/buffer__handle_8h.md @@ -0,0 +1,23 @@ +# buffer_handle.h + +## Overview + +The **buffer_handle.h** file declares the BufferHandle struct used by the NativeWindow module. + +**File to include**: <native_window/buffer_handle.h> + +**Library**: libnative_window.so + +**Since**: 8 + +**Related module**: [NativeWindow](_native_window.md) + + +## Summary + + +### Structs + +| Name| Description| +| -------- | -------- | +| struct  [BufferHandle](_buffer_handle.md) | Describes the buffer handle, which is used to transfer and obtain buffer information. The handle contains the file descriptor, size, format, usage, virtual address, shared memory key, physical address, and custom data of the buffer. | diff --git a/en/application-dev/reference/apis-arkgraphics2d/drawing__bitmap_8h.md b/en/application-dev/reference/apis-arkgraphics2d/drawing__bitmap_8h.md index d34a4e701835e915a39d0267f65950f94912fde7..338ee3de572a3ca6e73bef9347e461bca612344f 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/drawing__bitmap_8h.md +++ b/en/application-dev/reference/apis-arkgraphics2d/drawing__bitmap_8h.md @@ -28,7 +28,7 @@ The **drawing_bitmap.h** declares the functions related to the bitmap in the dra | Name| Description| | -------- | -------- | -| typedef struct [OH_Drawing_BitmapFormat](_o_h___drawing___bitmap_format.md) [OH_Drawing_BitmapFormat](_drawing.md#oh_drawing_bitmapformat) | Defines a struct that describes the pixel format of a bitmap, including the color type and alpha type.| +| typedef struct [OH_Drawing_BitmapFormat](_o_h___drawing___bitmap_format.md) [OH_Drawing_BitmapFormat](_drawing.md#oh_drawing_bitmapformat) | Defines a struct for the pixel format of a bitmap, including the color type and alpha type.| ### Functions diff --git a/en/application-dev/reference/apis-arkgraphics2d/drawing__canvas_8h.md b/en/application-dev/reference/apis-arkgraphics2d/drawing__canvas_8h.md index 939c3d3c7feabec21918f844c4e1915de6d962c3..06f3c5f2a2a1154fb8fcf90f0775613eb5d4976c 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/drawing__canvas_8h.md +++ b/en/application-dev/reference/apis-arkgraphics2d/drawing__canvas_8h.md @@ -23,79 +23,86 @@ Canvases that are not set for recording will immediately draw the commands onto ### Types -| Name| Description| +| Name| Description| | -------- | -------- | -| typedef enum [OH_Drawing_SrcRectConstraint](_drawing.md#oh_drawing_srcrectconstraint) [OH_Drawing_SrcRectConstraint](_drawing.md#oh_drawing_srcrectconstraint) | Defines an enum for the constraint types of the source rectangle.| -| typedef enum [OH_Drawing_PointMode](_drawing.md#oh_drawing_pointmode) [OH_Drawing_PointMode](_drawing.md#oh_drawing_pointmode) | Defines an enum for the modes of drawing multiple points. The modes include discrete points, line segments, and open polygons.| -| typedef enum [OH_Drawing_VertexMode](_drawing.md#oh_drawing_vertexmode) [OH_Drawing_VertexMode](_drawing.md#oh_drawing_vertexmode) | Defines an enum for the modes of interpreting the geometry of a given vertex.| -| typedef enum [OH_Drawing_CanvasClipOp](_drawing.md#oh_drawing_canvasclipop) [OH_Drawing_CanvasClipOp](_drawing.md#oh_drawing_canvasclipop) | Defines an enum for the canvas clipping modes.| -| typedef enum [OH_Drawing_CanvasShadowFlags](_drawing.md#oh_drawing_canvasshadowflags) [OH_Drawing_CanvasShadowFlags](_drawing.md#oh_drawing_canvasshadowflags) | Defines an enum for the canvas shadow flags.| +| typedef enum [OH_Drawing_SrcRectConstraint](_drawing.md#oh_drawing_srcrectconstraint) [OH_Drawing_SrcRectConstraint](_drawing.md#oh_drawing_srcrectconstraint) | Defines an enum for the constraint types of the source rectangle.| +| typedef enum [OH_Drawing_PointMode](_drawing.md#oh_drawing_pointmode) [OH_Drawing_PointMode](_drawing.md#oh_drawing_pointmode) | Defines an enum for the modes of drawing multiple points. The modes include discrete points, line segments, and open polygons.| +| typedef enum [OH_Drawing_VertexMode](_drawing.md#oh_drawing_vertexmode) [OH_Drawing_VertexMode](_drawing.md#oh_drawing_vertexmode) | Defines an enum for the modes of interpreting the geometry of a given vertex.| +| typedef enum [OH_Drawing_CanvasClipOp](_drawing.md#oh_drawing_canvasclipop) [OH_Drawing_CanvasClipOp](_drawing.md#oh_drawing_canvasclipop) | Defines an enum for the canvas clipping modes.| +| typedef enum [OH_Drawing_CanvasShadowFlags](_drawing.md#oh_drawing_canvasshadowflags) [OH_Drawing_CanvasShadowFlags](_drawing.md#oh_drawing_canvasshadowflags) | Defines an enum for the canvas shadow flags.| ### Enums -| Name| Description| +| Name| Description| | -------- | -------- | -| [OH_Drawing_SrcRectConstraint](_drawing.md#oh_drawing_srcrectconstraint) { STRICT_SRC_RECT_CONSTRAINT, FAST_SRC_RECT_CONSTRAINT } | Enumerates the constraint types of the source rectangle.| -| [OH_Drawing_PointMode](_drawing.md#oh_drawing_pointmode) { POINT_MODE_POINTS, POINT_MODE_LINES, POINT_MODE_POLYGON } | Enumerates the modes of drawing multiple points. The modes include discrete points, line segments, and open polygons.| -| [OH_Drawing_VertexMode](_drawing.md#oh_drawing_vertexmode) { VERTEX_MODE_TRIANGLES, VERTEX_MODE_TRIANGLESSTRIP, VERTEX_MODE_TRIANGLEFAN } | Enumerates the modes of interpreting the geometry of a given vertex.| -| [OH_Drawing_CanvasClipOp](_drawing.md#oh_drawing_canvasclipop) { DIFFERENCE, INTERSECT } | Enumerates the canvas clipping modes.| -| [OH_Drawing_CanvasShadowFlags](_drawing.md#oh_drawing_canvasshadowflags) { SHADOW_FLAGS_NONE, SHADOW_FLAGS_TRANSPARENT_OCCLUDER, SHADOW_FLAGS_GEOMETRIC_ONLY, SHADOW_FLAGS_ALL } | Enumerates the canvas shadow flags.| +| [OH_Drawing_SrcRectConstraint](_drawing.md#oh_drawing_srcrectconstraint-1) { STRICT_SRC_RECT_CONSTRAINT, FAST_SRC_RECT_CONSTRAINT } | Enumerates the constraint types of the source rectangle.| +| [OH_Drawing_PointMode](_drawing.md#oh_drawing_pointmode-1) { POINT_MODE_POINTS, POINT_MODE_LINES, POINT_MODE_POLYGON } | Enumerates the modes of drawing multiple points. The modes include discrete points, line segments, and open polygons.| +| [OH_Drawing_VertexMode](_drawing.md#oh_drawing_vertexmode-1) { VERTEX_MODE_TRIANGLES, VERTEX_MODE_TRIANGLESSTRIP, VERTEX_MODE_TRIANGLEFAN } | Enumerates the modes of interpreting the geometry of a given vertex.| +| [OH_Drawing_CanvasClipOp](_drawing.md#oh_drawing_canvasclipop-1) { DIFFERENCE, INTERSECT } | Enumerates the canvas clipping modes.| +| [OH_Drawing_CanvasShadowFlags](_drawing.md#oh_drawing_canvasshadowflags-1) { SHADOW_FLAGS_NONE, SHADOW_FLAGS_TRANSPARENT_OCCLUDER, SHADOW_FLAGS_GEOMETRIC_ONLY, SHADOW_FLAGS_ALL } | Enumerates the canvas shadow flags.| ### Functions -| Name| Description| +| Name| Description| | -------- | -------- | +| [OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \* [OH_Drawing_CanvasCreate](_drawing.md#oh_drawing_canvascreate) (void) | Creates an **OH_Drawing_Canvas** object. | +| void [OH_Drawing_CanvasDestroy](_drawing.md#oh_drawing_canvasdestroy) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*) | Destroys an **OH_Drawing_Canvas** object and reclaims the memory occupied by the object. | +| void [OH_Drawing_CanvasBind](_drawing.md#oh_drawing_canvasbind) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, [OH_Drawing_Bitmap](_drawing.md#oh_drawing_bitmap) \*) | Binds a bitmap to a canvas so that the content drawn on the canvas is output to the bitmap. (This process is called CPU rendering.) A canvas bound to a bitmap is a non-recording canvas. | +| void [OH_Drawing_CanvasAttachPen](_drawing.md#oh_drawing_canvasattachpen) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, const [OH_Drawing_Pen](_drawing.md#oh_drawing_pen) \*) | Attaches a pen to a canvas so that the canvas can use the style and color of the pen to outline a shape. If the pen effect changes after this function is called, you must call the function again to use the new effect in the subsequent drawing. | +| void [OH_Drawing_CanvasDetachPen](_drawing.md#oh_drawing_canvasdetachpen) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*) | Detaches the pen from a canvas so that the canvas can no longer use the style and color of the pen to outline a shape. | +| void [OH_Drawing_CanvasAttachBrush](_drawing.md#oh_drawing_canvasattachbrush) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, const [OH_Drawing_Brush](_drawing.md#oh_drawing_brush) \*) | Attaches a brush to a canvas so that the canvas can use the style and color of the brush to fill in a shape. If the brush effect changes after this function is called, you must call the function again to use the new effect in the subsequent drawing. | +| void [OH_Drawing_CanvasDetachBrush](_drawing.md#oh_drawing_canvasdetachbrush) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*) | Detaches the brush from a canvas so that the canvas can no longer use the previously set brush to fill in a shape. | +| void [OH_Drawing_CanvasSave](_drawing.md#oh_drawing_canvassave) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*) | Saves the current canvas status (canvas matrix) to the top of the stack. This function must be used in pair with [OH_Drawing_CanvasRestore](_drawing.md#oh_drawing_canvasrestore). | +| void [OH_Drawing_CanvasSaveLayer](_drawing.md#oh_drawing_canvassavelayer) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, const [OH_Drawing_Rect](_drawing.md#oh_drawing_rect) \*, const [OH_Drawing_Brush](_drawing.md#oh_drawing_brush) \*) | Saves the matrix and cropping region, and allocates a bitmap for subsequent drawing. If you call [OH_Drawing_CanvasRestore](_drawing.md#oh_drawing_canvasrestore), changes made to the matrix and clipping region are discarded, and the bitmap is drawn. | +| void [OH_Drawing_CanvasRestore](_drawing.md#oh_drawing_canvasrestore) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*) | Restores the canvas status (canvas matrix) saved on the top of the stack. | +| uint32_t [OH_Drawing_CanvasGetSaveCount](_drawing.md#oh_drawing_canvasgetsavecount) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*) | Obtains the number of canvas statuses (canvas matrices) saved in the stack. | +| void [OH_Drawing_CanvasRestoreToCount](_drawing.md#oh_drawing_canvasrestoretocount) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, uint32_t saveCount) | Restores to a given number of canvas statuses (canvas matrices). | +| void [OH_Drawing_CanvasDrawLine](_drawing.md#oh_drawing_canvasdrawline) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, float x1, float y1, float x2, float y2) | Draws a line segment. | +| void [OH_Drawing_CanvasDrawPath](_drawing.md#oh_drawing_canvasdrawpath) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, const [OH_Drawing_Path](_drawing.md#oh_drawing_path) \*) | Draws a path. | +| void [OH_Drawing_CanvasDrawPixelMapRect](_drawing.md#oh_drawing_canvasdrawpixelmaprect) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, [OH_Drawing_PixelMap](_drawing.md#oh_drawing_pixelmap) \*, const [OH_Drawing_Rect](_drawing.md#oh_drawing_rect) \*src, const [OH_Drawing_Rect](_drawing.md#oh_drawing_rect) \*dst, const [OH_Drawing_SamplingOptions](_drawing.md#oh_drawing_samplingoptions) \*) | Draws a portion of a pixel map onto a specified area of the canvas. | +| void [OH_Drawing_CanvasDrawBackground](_drawing.md#oh_drawing_canvasdrawbackground) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, const [OH_Drawing_Brush](_drawing.md#oh_drawing_brush) \*) | Draws a background filled with a brush. | +| void [OH_Drawing_CanvasDrawRegion](_drawing.md#oh_drawing_canvasdrawregion) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, const [OH_Drawing_Region](_drawing.md#oh_drawing_region) \*) | Draws a region. | +| [OH_Drawing_ErrorCode](_drawing.md#oh_drawing_errorcode) [OH_Drawing_CanvasDrawPoint](_drawing.md#oh_drawing_canvasdrawpoint) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*canvas, const [OH_Drawing_Point2D](_o_h___drawing___point2_d.md) \*point) | Draws a point. | +| void [OH_Drawing_CanvasDrawPoints](_drawing.md#oh_drawing_canvasdrawpoints) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, [OH_Drawing_PointMode](_drawing.md#oh_drawing_pointmode) mode, uint32_t count, const [OH_Drawing_Point2D](_o_h___drawing___point2_d.md) \*) | Draws multiple points. You can draw a single point, a line segment, or an open polygon. | +| void [OH_Drawing_CanvasDrawBitmap](_drawing.md#oh_drawing_canvasdrawbitmap) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, const [OH_Drawing_Bitmap](_drawing.md#oh_drawing_bitmap) \*, float left, float top) | Draws a bitmap. A bitmap, also referred to as a dot matrix image, a pixel map image, or a grid image, includes single points called pixels (image elements). | +| void [OH_Drawing_CanvasDrawBitmapRect](_drawing.md#oh_drawing_canvasdrawbitmaprect) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, const [OH_Drawing_Bitmap](_drawing.md#oh_drawing_bitmap) \*, const [OH_Drawing_Rect](_drawing.md#oh_drawing_rect) \*src, const [OH_Drawing_Rect](_drawing.md#oh_drawing_rect) \*dst, const [OH_Drawing_SamplingOptions](_drawing.md#oh_drawing_samplingoptions) \*) | Draws a portion of a bitmap onto a specified area of the canvas. | +| void [OH_Drawing_CanvasSetMatrix](_drawing.md#oh_drawing_canvassetmatrix) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, [OH_Drawing_Matrix](_drawing.md#oh_drawing_matrix) \*) | Sets the matrix status for a canvas. | +| void [OH_Drawing_CanvasResetMatrix](_drawing.md#oh_drawing_canvasresetmatrix) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*) | Resets the matrix of a canvas to an identity matrix. | +| void [OH_Drawing_CanvasDrawImageRectWithSrc](_drawing.md#oh_drawing_canvasdrawimagerectwithsrc) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, const [OH_Drawing_Image](_drawing.md#oh_drawing_image) \*, const [OH_Drawing_Rect](_drawing.md#oh_drawing_rect) \*src, const [OH_Drawing_Rect](_drawing.md#oh_drawing_rect) \*dst, const [OH_Drawing_SamplingOptions](_drawing.md#oh_drawing_samplingoptions) \*, [OH_Drawing_SrcRectConstraint](_drawing.md#oh_drawing_srcrectconstraint)) | Draws a portion of an image onto a specified area of the canvas. The area selected by the source rectangle is scaled and translated to the destination rectangle. | +| void [OH_Drawing_CanvasDrawImageRect](_drawing.md#oh_drawing_canvasdrawimagerect) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, [OH_Drawing_Image](_drawing.md#oh_drawing_image) \*, [OH_Drawing_Rect](_drawing.md#oh_drawing_rect) \*dst, [OH_Drawing_SamplingOptions](_drawing.md#oh_drawing_samplingoptions) \*) | Draws an image onto a specified area of the canvas. | +| void [OH_Drawing_CanvasDrawVertices](_drawing.md#oh_drawing_canvasdrawvertices) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, [OH_Drawing_VertexMode](_drawing.md#oh_drawing_vertexmode) vertexMmode, int32_t vertexCount, const [OH_Drawing_Point2D](_o_h___drawing___point2_d.md) \*positions, const [OH_Drawing_Point2D](_o_h___drawing___point2_d.md) \*texs, const uint32_t \*colors, int32_t indexCount, const uint16_t \*indices, [OH_Drawing_BlendMode](_drawing.md#oh_drawing_blendmode) mode) | Draws a triangular grid described by a vertex array. | +| bool [OH_Drawing_CanvasReadPixels](_drawing.md#oh_drawing_canvasreadpixels) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, [OH_Drawing_Image_Info](_o_h___drawing___image___info.md) \*, void \*dstPixels, uint32_t dstRowBytes, int32_t srcX, int32_t srcY) | Copies pixel data from a canvas to a specified address. This function cannot be used for recorded canvases. | +| bool [OH_Drawing_CanvasReadPixelsToBitmap](_drawing.md#oh_drawing_canvasreadpixelstobitmap) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, [OH_Drawing_Bitmap](_drawing.md#oh_drawing_bitmap) \*, int32_t srcX, int32_t srcY) | Copies pixel data from a canvas to an image. This function cannot be used for recorded canvases. | +| [OH_Drawing_ErrorCode](_drawing.md#oh_drawing_errorcode) [OH_Drawing_CanvasIsClipEmpty](_drawing.md#oh_drawing_canvasisclipempty) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*canvas, bool \*isClipEmpty) | Checks whether the region that can be drawn is empty after cropping. | +| [OH_Drawing_ErrorCode](_drawing.md#oh_drawing_errorcode) [OH_Drawing_CanvasGetImageInfo](_drawing.md#oh_drawing_canvasgetimageinfo) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*canvas, [OH_Drawing_Image_Info](_o_h___drawing___image___info.md) \*imageInfo) | Obtains the image information of a canvas. | +| void [OH_Drawing_CanvasDrawRect](_drawing.md#oh_drawing_canvasdrawrect) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, const [OH_Drawing_Rect](_drawing.md#oh_drawing_rect) \*) | Draws a rectangle. | +| void [OH_Drawing_CanvasDrawCircle](_drawing.md#oh_drawing_canvasdrawcircle) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, const [OH_Drawing_Point](_drawing.md#oh_drawing_point) \*, float radius) | Draws a circle. | +| [OH_Drawing_ErrorCode](_drawing.md#oh_drawing_errorcode) [OH_Drawing_CanvasDrawColor](_drawing.md#oh_drawing_canvasdrawcolor) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*canvas, uint32_t color, [OH_Drawing_BlendMode](_drawing.md#oh_drawing_blendmode) blendMode) | Fills the entire canvas with the specified color and blend mode. | +| void [OH_Drawing_CanvasDrawOval](_drawing.md#oh_drawing_canvasdrawoval) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, const [OH_Drawing_Rect](_drawing.md#oh_drawing_rect) \*) | Draws an oval. | +| void [OH_Drawing_CanvasDrawArc](_drawing.md#oh_drawing_canvasdrawarc) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, const [OH_Drawing_Rect](_drawing.md#oh_drawing_rect) \*, float startAngle, float sweepAngle) | Draws an arc. If the absolute value of the sweep angle exceeds 360 degrees, an ellipse is drawn. | +| [OH_Drawing_ErrorCode](_drawing.md#oh_drawing_errorcode) [OH_Drawing_CanvasDrawArcWithCenter](_drawing.md#oh_drawing_canvasdrawarcwithcenter) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*canvas, const [OH_Drawing_Rect](_drawing.md#oh_drawing_rect) \*rect, float startAngle, float sweepAngle, bool useCenter) | Draws an arc. It enables you to define the starting angle, the sweep angle, and whether the arc's endpoints should connect to its center. | +| void [OH_Drawing_CanvasDrawRoundRect](_drawing.md#oh_drawing_canvasdrawroundrect) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, const [OH_Drawing_RoundRect](_drawing.md#oh_drawing_roundrect) \*) | Draws a rounded rectangle. | +| [OH_Drawing_ErrorCode](_drawing.md#oh_drawing_errorcode) [OH_Drawing_CanvasDrawNestedRoundRect](_drawing.md#oh_drawing_canvasdrawnestedroundrect) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*canvas, const [OH_Drawing_RoundRect](_drawing.md#oh_drawing_roundrect) \*outer, const [OH_Drawing_RoundRect](_drawing.md#oh_drawing_roundrect) \*inner) | Draws two nested rounded rectangles. The outer rectangle boundary must contain the inner rectangle boundary. Otherwise, there is no drawing effect. | | [OH_Drawing_ErrorCode](_drawing.md#oh_drawing_errorcode) [OH_Drawing_CanvasDrawSingleCharacter](_drawing.md#oh_drawing_canvasdrawsinglecharacter) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*canvas, const char \*str, const [OH_Drawing_Font](_drawing.md#oh_drawing_font) \*font, float x, float y) | Draws a single character. If the typeface of the current font does not support the character to draw, the system typeface is used to draw the character. | -| [OH_Drawing_ErrorCode](_drawing.md#oh_drawing_errorcode) [OH_Drawing_CanvasClipRegion](_drawing.md#oh_drawing_canvasclipregion) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*canvas, const [OH_Drawing_Region](_drawing.md#oh_drawing_region) \*region, [OH_Drawing_CanvasClipOp](_drawing.md#oh_drawing_canvasclipop) clipOp) | Clips a rectangle.| -| [OH_Drawing_ErrorCode](_drawing.md#oh_drawing_errorcode) [OH_Drawing_CanvasDrawColor](_drawing.md#oh_drawing_canvasdrawcolor) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*canvas, uint32_t color, [OH_Drawing_BlendMode](_drawing.md#oh_drawing_blendmode) blendMode) | Fills the entire canvas with the specified color and blend mode.| -| [OH_Drawing_ErrorCode](_drawing.md#oh_drawing_errorcode) [OH_Drawing_CanvasGetImageInfo](_drawing.md#oh_drawing_canvasgetimageinfo) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*canvas, [OH_Drawing_Image_Info](_o_h___drawing___image___info.md) \*imageInfo) | Obtains the image information of a canvas.| -| [OH_Drawing_ErrorCode](_drawing.md#oh_drawing_errorcode) [OH_Drawing_CanvasIsClipEmpty](_drawing.md#oh_drawing_canvasisclipempty) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*canvas, bool \*isClipEmpty) | Checks whether the region that can be drawn is empty after cropping.| -| [OH_Drawing_ErrorCode](_drawing.md#oh_drawing_errorcode) [OH_Drawing_CanvasDrawPoint](_drawing.md#oh_drawing_canvasdrawpoint) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*canvas, const [OH_Drawing_Point2D](_o_h___drawing___point2_d.md) \*point) | Draws a point.| -| [OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \* [OH_Drawing_CanvasCreate](_drawing.md#oh_drawing_canvascreate) (void) | Creates an **OH_Drawing_Canvas** object.| -| void [OH_Drawing_CanvasDestroy](_drawing.md#oh_drawing_canvasdestroy) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*) | Destroys an **OH_Drawing_Canvas** object and reclaims the memory occupied by the object.| -| void [OH_Drawing_CanvasBind](_drawing.md#oh_drawing_canvasbind) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, [OH_Drawing_Bitmap](_drawing.md#oh_drawing_bitmap) \*) | Binds a bitmap to a canvas so that the content drawn on the canvas is output to the bitmap. (This process is called CPU rendering.) A canvas bound to a bitmap is a non-recording canvas.| -| void [OH_Drawing_CanvasAttachPen](_drawing.md#oh_drawing_canvasattachpen) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, const [OH_Drawing_Pen](_drawing.md#oh_drawing_pen) \*) | Attaches a pen to a canvas so that the canvas can use the style and color of the pen to outline a shape.| -| void [OH_Drawing_CanvasDetachPen](_drawing.md#oh_drawing_canvasdetachpen) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*) | Detaches the pen from a canvas so that the canvas can no longer use the style and color of the pen to outline a shape.| -| void [OH_Drawing_CanvasAttachBrush](_drawing.md#oh_drawing_canvasattachbrush) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, const [OH_Drawing_Brush](_drawing.md#oh_drawing_brush) \*) | Attaches a brush to a canvas so that the canvas can use the style and color of the brush to fill in a shape.| -| void [OH_Drawing_CanvasDetachBrush](_drawing.md#oh_drawing_canvasdetachbrush) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*) | Detaches the brush from a canvas so that the canvas can no longer use the previously set brush to fill in a shape.| -| void [OH_Drawing_CanvasSave](_drawing.md#oh_drawing_canvassave) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*) | Saves the current canvas status (canvas matrix) to the top of the stack.| -| void [OH_Drawing_CanvasSaveLayer](_drawing.md#oh_drawing_canvassavelayer) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, const [OH_Drawing_Rect](_drawing.md#oh_drawing_rect) \*, const [OH_Drawing_Brush](_drawing.md#oh_drawing_brush) \*) | Saves the matrix and cropping region, and allocates a bitmap for subsequent drawing. If you call [OH_Drawing_CanvasRestore](_drawing.md#oh_drawing_canvasrestore), the changes made to the matrix and clipping region are discarded, and the bitmap is drawn.| -| void [OH_Drawing_CanvasRestore](_drawing.md#oh_drawing_canvasrestore) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*) | Restores the canvas status (canvas matrix) saved on the top of the stack.| -| uint32_t [OH_Drawing_CanvasGetSaveCount](_drawing.md#oh_drawing_canvasgetsavecount) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*) | Obtains the number of canvas statuses (canvas matrices) saved in the stack.| -| void [OH_Drawing_CanvasRestoreToCount](_drawing.md#oh_drawing_canvasrestoretocount) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, uint32_t saveCount) | Restores to a given number of canvas statuses (canvas matrices).| -| void [OH_Drawing_CanvasDrawLine](_drawing.md#oh_drawing_canvasdrawline) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, float x1, float y1, float x2, float y2) | Draws a line segment.| -| void [OH_Drawing_CanvasDrawPath](_drawing.md#oh_drawing_canvasdrawpath) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, const [OH_Drawing_Path](_drawing.md#oh_drawing_path) \*) | Draws a path.| -| void [OH_Drawing_CanvasDrawPixelMapRect](_drawing.md#oh_drawing_canvasdrawpixelmaprect) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, [OH_Drawing_PixelMap](_drawing.md#oh_drawing_pixelmap) \*, const [OH_Drawing_Rect](_drawing.md#oh_drawing_rect) \*src, const [OH_Drawing_Rect](_drawing.md#oh_drawing_rect) \*dst, const [OH_Drawing_SamplingOptions](_drawing.md#oh_drawing_samplingoptions) \*) | Draws a portion of a pixel map onto a specified area of the canvas.| -| void [OH_Drawing_CanvasDrawBackground](_drawing.md#oh_drawing_canvasdrawbackground) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, const [OH_Drawing_Brush](_drawing.md#oh_drawing_brush) \*) | Draws a background filled with a brush.| -| void [OH_Drawing_CanvasDrawRegion](_drawing.md#oh_drawing_canvasdrawregion) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, const [OH_Drawing_Region](_drawing.md#oh_drawing_region) \*) | Draws a region.| -| void [OH_Drawing_CanvasDrawPoints](_drawing.md#oh_drawing_canvasdrawpoints) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, [OH_Drawing_PointMode](_drawing.md#oh_drawing_pointmode) mode, uint32_t count, const [OH_Drawing_Point2D](_o_h___drawing___point2_d.md) \*) | Draws multiple points. You can draw a single point, a line segment, or an open polygon.| -| void [OH_Drawing_CanvasDrawBitmap](_drawing.md#oh_drawing_canvasdrawbitmap) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, const [OH_Drawing_Bitmap](_drawing.md#oh_drawing_bitmap) \*, float left, float top) | Draws a bitmap. A bitmap, also referred to as a dot matrix image, a pixel map image, or a grid image, includes single points called pixels (image elements).| -| void [OH_Drawing_CanvasDrawBitmapRect](_drawing.md#oh_drawing_canvasdrawbitmaprect) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, const [OH_Drawing_Bitmap](_drawing.md#oh_drawing_bitmap) \*, const [OH_Drawing_Rect](_drawing.md#oh_drawing_rect) \*src, const [OH_Drawing_Rect](_drawing.md#oh_drawing_rect) \*dst, const [OH_Drawing_SamplingOptions](_drawing.md#oh_drawing_samplingoptions) \*) | Draws a portion of a bitmap onto a specified area of the canvas.| -| void [OH_Drawing_CanvasSetMatrix](_drawing.md#oh_drawing_canvassetmatrix) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, [OH_Drawing_Matrix](_drawing.md#oh_drawing_matrix) \*) | Sets the matrix status for a canvas.| -| void [OH_Drawing_CanvasResetMatrix](_drawing.md#oh_drawing_canvasresetmatrix) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*) | Resets the matrix of a canvas to an identity matrix.| -| void [OH_Drawing_CanvasDrawImageRectWithSrc](_drawing.md#oh_drawing_canvasdrawimagerectwithsrc) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, const [OH_Drawing_Image](_drawing.md#oh_drawing_image) \*, const [OH_Drawing_Rect](_drawing.md#oh_drawing_rect) \*src, const [OH_Drawing_Rect](_drawing.md#oh_drawing_rect) \*dst, const [OH_Drawing_SamplingOptions](_drawing.md#oh_drawing_samplingoptions) \*, [OH_Drawing_SrcRectConstraint](_drawing.md#oh_drawing_srcrectconstraint)) | Draws a portion of an image onto a specified area of the canvas. The area selected by the source rectangle is scaled and translated to the destination rectangle.| -| void [OH_Drawing_CanvasDrawImageRect](_drawing.md#oh_drawing_canvasdrawimagerect) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, [OH_Drawing_Image](_drawing.md#oh_drawing_image) \*, [OH_Drawing_Rect](_drawing.md#oh_drawing_rect) \*dst, [OH_Drawing_SamplingOptions](_drawing.md#oh_drawing_samplingoptions) \*) | Draws an image onto a specified area of the canvas.| -| void [OH_Drawing_CanvasDrawVertices](_drawing.md#oh_drawing_canvasdrawvertices) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, [OH_Drawing_VertexMode](_drawing.md#oh_drawing_vertexmode) vertexMmode, int32_t vertexCount, const [OH_Drawing_Point2D](_o_h___drawing___point2_d.md) \*positions, const [OH_Drawing_Point2D](_o_h___drawing___point2_d.md) \*texs, const uint32_t \*colors, int32_t indexCount, const uint16_t \*indices, [OH_Drawing_BlendMode](_drawing.md#oh_drawing_blendmode) mode) | Draws a triangular grid described by a vertex array.| -| bool [OH_Drawing_CanvasReadPixels](_drawing.md#oh_drawing_canvasreadpixels) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, [OH_Drawing_Image_Info](_o_h___drawing___image___info.md) \*, void \*dstPixels, uint32_t dstRowBytes, int32_t srcX, int32_t srcY) | Copies pixel data from a canvas to a specified address. This function cannot be used for recorded canvases.| -| bool [OH_Drawing_CanvasReadPixelsToBitmap](_drawing.md#oh_drawing_canvasreadpixelstobitmap) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, [OH_Drawing_Bitmap](_drawing.md#oh_drawing_bitmap) \*, int32_t srcX, int32_t srcY) | Copies pixel data from a canvas to an image. This function cannot be used for recorded canvases.| -| void [OH_Drawing_CanvasDrawRect](_drawing.md#oh_drawing_canvasdrawrect) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, const [OH_Drawing_Rect](_drawing.md#oh_drawing_rect) \*) | Draws a rectangle.| -| void [OH_Drawing_CanvasDrawCircle](_drawing.md#oh_drawing_canvasdrawcircle) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, const [OH_Drawing_Point](_drawing.md#oh_drawing_point) \*, float radius) | Draws a circle.| -| void [OH_Drawing_CanvasDrawOval](_drawing.md#oh_drawing_canvasdrawoval) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, const [OH_Drawing_Rect](_drawing.md#oh_drawing_rect) \*) | Draws an oval.| -| void [OH_Drawing_CanvasDrawArc](_drawing.md#oh_drawing_canvasdrawarc) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, const [OH_Drawing_Rect](_drawing.md#oh_drawing_rect) \*, float startAngle, float sweepAngle) | Draws an arc.| -| void [OH_Drawing_CanvasDrawRoundRect](_drawing.md#oh_drawing_canvasdrawroundrect) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, const [OH_Drawing_RoundRect](_drawing.md#oh_drawing_roundrect) \*) | Draws a rounded rectangle.| -| void [OH_Drawing_CanvasDrawTextBlob](_drawing.md#oh_drawing_canvasdrawtextblob) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, const [OH_Drawing_TextBlob](_drawing.md#oh_drawing_textblob) \*, float x, float y) | Draws a TextBlob. If the typeface used to construct **OH_Drawing_TextBlob** does not support a character, that character will not be drawn.| -| void [OH_Drawing_CanvasClipRect](_drawing.md#oh_drawing_canvascliprect) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, const [OH_Drawing_Rect](_drawing.md#oh_drawing_rect) \*, [OH_Drawing_CanvasClipOp](_drawing.md#oh_drawing_canvasclipop) clipOp, bool doAntiAlias) | Clips a rectangle.| -| void [OH_Drawing_CanvasClipRoundRect](_drawing.md#oh_drawing_canvascliproundrect) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, const [OH_Drawing_RoundRect](_drawing.md#oh_drawing_roundrect) \*, [OH_Drawing_CanvasClipOp](_drawing.md#oh_drawing_canvasclipop) clipOp, bool doAntiAlias) | Clips a rounded rectangle.| -| void [OH_Drawing_CanvasClipPath](_drawing.md#oh_drawing_canvasclippath) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, const [OH_Drawing_Path](_drawing.md#oh_drawing_path) \*, [OH_Drawing_CanvasClipOp](_drawing.md#oh_drawing_canvasclipop) clipOp, bool doAntiAlias) | Clips a path.| -| void [OH_Drawing_CanvasRotate](_drawing.md#oh_drawing_canvasrotate) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, float degrees, float px, float py) | Rotates a canvas by a given angle. A positive number indicates a clockwise rotation, and a negative number indicates a counterclockwise rotation.| -| void [OH_Drawing_CanvasTranslate](_drawing.md#oh_drawing_canvastranslate) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, float dx, float dy) | Translates a canvas by a given distance.| -| void [OH_Drawing_CanvasScale](_drawing.md#oh_drawing_canvasscale) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, float sx, float sy) | Scales a canvas.| -| void [OH_Drawing_CanvasSkew](_drawing.md#oh_drawing_canvasskew) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, float sx, float sy) | Skews a canvas. This function premultiplies the current canvas matrix by a skew transformation matrix and applies the resulting matrix to the canvas. The skew transformation matrix is as follows: \|1 sx 0\| \|sy 1 0\| \|0 0 1\| | -| void [OH_Drawing_CanvasClear](_drawing.md#oh_drawing_canvasclear) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, uint32_t color) | Clears a canvas by using a given color.| -| int32_t [OH_Drawing_CanvasGetWidth](_drawing.md#oh_drawing_canvasgetwidth) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*) | Obtains the canvas width.| -| int32_t [OH_Drawing_CanvasGetHeight](_drawing.md#oh_drawing_canvasgetheight) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*) | Obtains the canvas height.| -| void [OH_Drawing_CanvasGetLocalClipBounds](_drawing.md#oh_drawing_canvasgetlocalclipbounds) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, [OH_Drawing_Rect](_drawing.md#oh_drawing_rect) \*) | Obtains the bounds of the cropping region of a canvas. This function cannot be used for recorded canvases.| -| void [OH_Drawing_CanvasGetTotalMatrix](_drawing.md#oh_drawing_canvasgettotalmatrix) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, [OH_Drawing_Matrix](_drawing.md#oh_drawing_matrix) \*) | Obtains the 3x3 matrix of a canvas.| -| void [OH_Drawing_CanvasConcatMatrix](_drawing.md#oh_drawing_canvasconcatmatrix) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, [OH_Drawing_Matrix](_drawing.md#oh_drawing_matrix) \*) | Preconcats the existing matrix with the passed-in matrix. The drawing operation triggered before this function is called is not affected.| -| void [OH_Drawing_CanvasDrawShadow](_drawing.md#oh_drawing_canvasdrawshadow) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, [OH_Drawing_Path](_drawing.md#oh_drawing_path) \*, [OH_Drawing_Point3D](_o_h___drawing___point3_d.md) planeParams, [OH_Drawing_Point3D](_o_h___drawing___point3_d.md) devLightPos, float lightRadius, uint32_t ambientColor, uint32_t spotColor, [OH_Drawing_CanvasShadowFlags](_drawing.md#oh_drawing_canvasshadowflags) flag) | Draws an offset spot shadow and uses a given path to outline the ambient shadow.| -| [OH_Drawing_ErrorCode](_drawing.md#oh_drawing_errorcode) [OH_Drawing_CanvasDrawRecordCmd](_drawing.md#oh_drawing_canvasdrawrecordcmd) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*canvas, [OH_Drawing_RecordCmd](_drawing.md#oh_drawing_recordcmd) \*recordCmd) | Draws an **OH_Drawing_RecordCmd** object.| +| void [OH_Drawing_CanvasDrawTextBlob](_drawing.md#oh_drawing_canvasdrawtextblob) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, const [OH_Drawing_TextBlob](_drawing.md#oh_drawing_textblob) \*, float x, float y) | Draws a TextBlob. If the typeface used to construct **OH_Drawing_TextBlob** does not support a character, that character will not be drawn. | +| enum [OH_Drawing_CanvasShadowFlags](_drawing.md#oh_drawing_canvasshadowflags) { [SHADOW_FLAGS_NONE](_drawing.md), [SHADOW_FLAGS_TRANSPARENT_OCCLUDER](_drawing.md), [SHADOW_FLAGS_GEOMETRIC_ONLY](_drawing.md), [SHADOW_FLAGS_ALL](_drawing.md) } | Enumerates the canvas shadow flags. | +| typedef enum [OH_Drawing_CanvasShadowFlags](_drawing.md#oh_drawing_canvasshadowflags) [OH_Drawing_CanvasShadowFlags](_drawing.md#oh_drawing_canvasshadowflags) | Defines an enum for the canvas shadow flags. | +| void [OH_Drawing_CanvasClipRect](_drawing.md#oh_drawing_canvascliprect) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, const [OH_Drawing_Rect](_drawing.md#oh_drawing_rect) \*, [OH_Drawing_CanvasClipOp](_drawing.md#oh_drawing_canvasclipop) clipOp, bool doAntiAlias) | Clips a rectangle. | +| void [OH_Drawing_CanvasClipRoundRect](_drawing.md#oh_drawing_canvascliproundrect) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, const [OH_Drawing_RoundRect](_drawing.md#oh_drawing_roundrect) \*, [OH_Drawing_CanvasClipOp](_drawing.md#oh_drawing_canvasclipop) clipOp, bool doAntiAlias) | Clips a rounded rectangle. | +| void [OH_Drawing_CanvasClipPath](_drawing.md#oh_drawing_canvasclippath) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, const [OH_Drawing_Path](_drawing.md#oh_drawing_path) \*, [OH_Drawing_CanvasClipOp](_drawing.md#oh_drawing_canvasclipop) clipOp, bool doAntiAlias) | Clips a path. | +| [OH_Drawing_ErrorCode](_drawing.md#oh_drawing_errorcode) [OH_Drawing_CanvasClipRegion](_drawing.md#oh_drawing_canvasclipregion) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*canvas, const [OH_Drawing_Region](_drawing.md#oh_drawing_region) \*region, [OH_Drawing_CanvasClipOp](_drawing.md#oh_drawing_canvasclipop) clipOp) | Clips a rectangle. | +| void [OH_Drawing_CanvasRotate](_drawing.md#oh_drawing_canvasrotate) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, float degrees, float px, float py) | Rotates a canvas by a given angle. A positive number indicates a clockwise rotation, and a negative number indicates a counterclockwise rotation. | +| void [OH_Drawing_CanvasTranslate](_drawing.md#oh_drawing_canvastranslate) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, float dx, float dy) | Translates a canvas by a given distance. | +| void [OH_Drawing_CanvasScale](_drawing.md#oh_drawing_canvasscale) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, float sx, float sy) | Scales a canvas. | +| void [OH_Drawing_CanvasSkew](_drawing.md#oh_drawing_canvasskew) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, float sx, float sy) | Skews a canvas. This function premultiplies the current canvas matrix by a skew transformation matrix and applies the resulting matrix to the canvas. The skew transformation matrix is as follows: \|1 sx 0\| \|sy 1 0\| \|0 0 1\| | +| void [OH_Drawing_CanvasClear](_drawing.md#oh_drawing_canvasclear) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, uint32_t color) | Clears a canvas by using a given color. | +| int32_t [OH_Drawing_CanvasGetWidth](_drawing.md#oh_drawing_canvasgetwidth) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*) | Obtains the canvas width. | +| int32_t [OH_Drawing_CanvasGetHeight](_drawing.md#oh_drawing_canvasgetheight) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*) | Obtains the canvas height. | +| void [OH_Drawing_CanvasGetLocalClipBounds](_drawing.md#oh_drawing_canvasgetlocalclipbounds) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, [OH_Drawing_Rect](_drawing.md#oh_drawing_rect) \*) | Obtains the bounds of the cropping region of a canvas. This function cannot be used for recorded canvases. | +| void [OH_Drawing_CanvasGetTotalMatrix](_drawing.md#oh_drawing_canvasgettotalmatrix) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, [OH_Drawing_Matrix](_drawing.md#oh_drawing_matrix) \*) | Obtains the 3x3 matrix of a canvas. | +| void [OH_Drawing_CanvasConcatMatrix](_drawing.md#oh_drawing_canvasconcatmatrix) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, [OH_Drawing_Matrix](_drawing.md#oh_drawing_matrix) \*) | Preconcats the existing matrix with the passed-in matrix. The drawing operation triggered before this function is called is not affected. | +| void [OH_Drawing_CanvasDrawShadow](_drawing.md#oh_drawing_canvasdrawshadow) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, [OH_Drawing_Path](_drawing.md#oh_drawing_path) \*, [OH_Drawing_Point3D](_o_h___drawing___point3_d.md) planeParams, [OH_Drawing_Point3D](_o_h___drawing___point3_d.md) devLightPos, float lightRadius, uint32_t ambientColor, uint32_t spotColor, [OH_Drawing_CanvasShadowFlags](_drawing.md#oh_drawing_canvasshadowflags) flag) | Draws an offset spot shadow and uses a given path to outline the ambient shadow. | +| [OH_Drawing_ErrorCode](_drawing.md#oh_drawing_errorcode) [OH_Drawing_CanvasDrawRecordCmd](_drawing.md#oh_drawing_canvasdrawrecordcmd) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*canvas, [OH_Drawing_RecordCmd](_drawing.md#oh_drawing_recordcmd) \*recordCmd) | Draws an **OH_Drawing_RecordCmd** object. | +| [OH_Drawing_ErrorCode](_drawing.md#oh_drawing_errorcode) [OH_Drawing_CanvasQuickRejectPath](_drawing.md#oh_drawing_canvasquickrejectpath) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*canvas, const [OH_Drawing_Path](_drawing.md#oh_drawing_path) \*path, bool \*quickReject) | Checks whether the path is not intersecting with the canvas area. The canvas area includes its boundaries. | +| [OH_Drawing_ErrorCode](_drawing.md#oh_drawing_errorcode) [OH_Drawing_CanvasQuickRejectRect](_drawing.md#oh_drawing_canvasquickrejectrect) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*canvas, const [OH_Drawing_Rect](_drawing.md#oh_drawing_rect) \*rect, bool \*quickReject) | Checks whether the rectangle is not intersecting with the canvas area. The canvas area includes its boundaries. | +| [OH_Drawing_ErrorCode](_drawing.md#oh_drawing_errorcode) [OH_Drawing_CanvasDrawPixelMapNine](_drawing.md#oh_drawing_canvasdrawpixelmapnine) ([OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*canvas, [OH_Drawing_PixelMap](_drawing.md#oh_drawing_pixelmap) \*pixelMap, const [OH_Drawing_Rect](_drawing.md#oh_drawing_rect) \*center, const [OH_Drawing_Rect](_drawing.md#oh_drawing_rect) \*dst, [OH_Drawing_FilterMode](_drawing.md#oh_drawing_filtermode) mode) | Splits a PixelMap into nine sections using two horizontal and two vertical lines: four edge sections, four corner sections, and a central section. If the four corner sections are smaller than the target rectangle, they will be drawn in the target rectangle without scaling. Otherwise, they will be scaled to fit the target rectangle. Any remaining space will be filled by stretching or compressing the other five sections to cover the entire target rectangle. | diff --git a/en/application-dev/reference/apis-arkgraphics2d/drawing__error__code_8h.md b/en/application-dev/reference/apis-arkgraphics2d/drawing__error__code_8h.md index c09e94c7d414e0216ef839edd6db4e6a3c45b805..dcb34a3a636a80d357c98a29421d9450cec29437 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/drawing__error__code_8h.md +++ b/en/application-dev/reference/apis-arkgraphics2d/drawing__error__code_8h.md @@ -28,7 +28,7 @@ The **drawing_error_code.h** file declares the functions related to the error co | Name| Description| | -------- | -------- | -| [OH_Drawing_ErrorCode](_drawing.md#oh_drawing_errorcode) { OH_DRAWING_SUCCESS = 0, OH_DRAWING_ERROR_NO_PERMISSION = 201, OH_DRAWING_ERROR_INVALID_PARAMETER = 401, OH_DRAWING_ERROR_PARAMETER_OUT_OF_RANGE = 26200001,OH_DRAWING_ERROR_ALLOCATION_FAILED = 26200002 } | Enumerates the error codes that may be generated by the module.| +| [OH_Drawing_ErrorCode](_drawing.md#oh_drawing_errorcode-1) { OH_DRAWING_SUCCESS = 0, OH_DRAWING_ERROR_NO_PERMISSION = 201, OH_DRAWING_ERROR_INVALID_PARAMETER = 401, OH_DRAWING_ERROR_PARAMETER_OUT_OF_RANGE = 26200001,OH_DRAWING_ERROR_ALLOCATION_FAILED = 26200002 } | Enumerates the error codes that may be generated by the module.| ### Functions @@ -36,3 +36,4 @@ The **drawing_error_code.h** file declares the functions related to the error co | Name| Description| | -------- | -------- | | [OH_Drawing_ErrorCode](_drawing.md#oh_drawing_errorcode) [OH_Drawing_ErrorCodeGet](_drawing.md#oh_drawing_errorcodeget) () | Obtains the latest error code of the module. After the function is successfully executed, the error code returned by this function will not be modified.| +| void [OH_Drawing_ErrorCodeReset](_drawing.md#oh_drawing_errorcodereset) (void) | Resets the error code of this module to **OH_DRAWING_SUCCESS**.
When a function that does not return an error code fails, the error code obtained through [OH_Drawing_ErrorCodeGet](_drawing.md#oh_drawing_errorcodeget) is reset to the corresponding error number. However, it is not reset to **OH_DRAWING_SUCCESS** for a successful operation.
By calling this function, you can manually reset the error code to **OH_DRAWING_SUCCESS**, avoiding interference between different functions and simplifying the debugging process.| diff --git a/en/application-dev/reference/apis-arkgraphics2d/drawing__font__collection_8h.md b/en/application-dev/reference/apis-arkgraphics2d/drawing__font__collection_8h.md index 23df0777beb790f3aa21a7cd93369c40e528c255..42c2597c776ad0a889d77e343c5737aceff7b00b 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/drawing__font__collection_8h.md +++ b/en/application-dev/reference/apis-arkgraphics2d/drawing__font__collection_8h.md @@ -23,7 +23,7 @@ The **drawing_font_collection.h** file declares the functions related to the fon | -------- | -------- | | [OH_Drawing_FontCollection](_drawing.md#oh_drawing_fontcollection) \* [OH_Drawing_CreateFontCollection](_drawing.md#oh_drawing_createfontcollection) (void) | Creates an [OH_Drawing_FontCollection](_drawing.md#oh_drawing_fontcollection) object. The [OH_Drawing_FontCollection](_drawing.md#oh_drawing_fontcollection) object created by this function can be used by only one [OH_Drawing_TypographyCreate](_drawing.md#oh_drawing_typographycreate) object. To share an [OH_Drawing_FontCollection](_drawing.md#oh_drawing_fontcollection) object among multiple [OH_Drawing_TypographyCreate](_drawing.md#oh_drawing_typographycreate) objects, use [OH_Drawing_CreateSharedFontCollection](_drawing.md#oh_drawing_createsharedfontcollection) to create it.| | void [OH_Drawing_DestroyFontCollection](_drawing.md#oh_drawing_destroyfontcollection) ([OH_Drawing_FontCollection](_drawing.md#oh_drawing_fontcollection) \*) | Destroys an **OH_Drawing_FontCollection** object and reclaims the memory occupied by the object.| -| void [OH_Drawing_DisableFontCollectionFallback](_drawing.md#oh_drawing_disablefontcollectionfallback) ([OH_Drawing_FontCollection](_drawing.md#oh_drawing_fontcollection) \*fontCollection) | Disables the alternate fonts.| +| void [OH_Drawing_DisableFontCollectionFallback](_drawing.md#oh_drawing_disablefontcollectionfallback) ([OH_Drawing_FontCollection](_drawing.md#oh_drawing_fontcollection) \*fontCollection) | Disables the system fonts.| | void [OH_Drawing_DisableFontCollectionSystemFont](_drawing.md#oh_drawing_disablefontcollectionsystemfont) ([OH_Drawing_FontCollection](_drawing.md#oh_drawing_fontcollection) \*fontCollection) | Disables the system fonts.| | [OH_Drawing_FontCollection](_drawing.md#oh_drawing_fontcollection) \* [OH_Drawing_CreateSharedFontCollection](_drawing.md#oh_drawing_createsharedfontcollection) (void) | Creates an [OH_Drawing_FontCollection](_drawing.md#oh_drawing_fontcollection) object that is shareable.| | void [OH_Drawing_ClearFontCaches](_drawing.md#oh_drawing_clearfontcaches) ([OH_Drawing_FontCollection](_drawing.md#oh_drawing_fontcollection) \*) | Clears the font cache. (The font cache has a memory limit and a clearing mechanism. It occupies limited memory. You are not advised to clear it unless otherwise required.)| diff --git a/en/application-dev/reference/apis-arkgraphics2d/drawing__font__mgr_8h.md b/en/application-dev/reference/apis-arkgraphics2d/drawing__font__mgr_8h.md index e256c52f1d906aef58f295f0de41de1a5bcd84f7..f3b715c7274759999a25959f7a8fbd46e92ebb2e 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/drawing__font__mgr_8h.md +++ b/en/application-dev/reference/apis-arkgraphics2d/drawing__font__mgr_8h.md @@ -21,7 +21,7 @@ The **drawing_font_mgr.h** file declares the functions related to font managemen | Name| Description| | -------- | -------- | -| [OH_Drawing_FontMgr](_drawing.md#oh_drawing_fontmgr) \* [OH_Drawing_FontMgrCreate](_drawing.md#oh_drawing_fontmgrcreate) (void) | Creates an **OH_Drawing_FontMgr** object.| +| [OH_Drawing_FontMgr](_drawing.md#oh_drawing_fontmgr) \* [OH_Drawing_FontMgrCreate](_drawing.md#oh_drawing_fontmgrcreate) (void) | Creates an **OH_Drawing_FontMgr** object, which can be used only to manage system fonts.| | void [OH_Drawing_FontMgrDestroy](_drawing.md#oh_drawing_fontmgrdestroy) ([OH_Drawing_FontMgr](_drawing.md#oh_drawing_fontmgr) \*) | Destroys an **OH_Drawing_FontMgr** object and reclaims the memory occupied by the object.| | int [OH_Drawing_FontMgrGetFamilyCount](_drawing.md#oh_drawing_fontmgrgetfamilycount) ([OH_Drawing_FontMgr](_drawing.md#oh_drawing_fontmgr) \*) | Obtains the number of font families.| | char \* [OH_Drawing_FontMgrGetFamilyName](_drawing.md#oh_drawing_fontmgrgetfamilyname) ([OH_Drawing_FontMgr](_drawing.md#oh_drawing_fontmgr) \*, int index) | Obtains the font family name based on an index.| @@ -30,7 +30,7 @@ The **drawing_font_mgr.h** file declares the functions related to font managemen | void [OH_Drawing_FontMgrDestroyFontStyleSet](_drawing.md#oh_drawing_fontmgrdestroyfontstyleset) ([OH_Drawing_FontStyleSet](_drawing.md#oh_drawing_fontstyleset) \*) | Reclaims the memory occupied by a font style set.| | [OH_Drawing_FontStyleSet](_drawing.md#oh_drawing_fontstyleset) \* [OH_Drawing_FontMgrMatchFamily](_drawing.md#oh_drawing_fontmgrmatchfamily) ([OH_Drawing_FontMgr](_drawing.md#oh_drawing_fontmgr) \*, const char \*familyName) | Obtains a font style set based on a font family name.| | [OH_Drawing_Typeface](_drawing.md#oh_drawing_typeface) \* [OH_Drawing_FontMgrMatchFamilyStyle](_drawing.md#oh_drawing_fontmgrmatchfamilystyle) ([OH_Drawing_FontMgr](_drawing.md#oh_drawing_fontmgr) \*, const char \*familyName, [OH_Drawing_FontStyleStruct](_o_h___drawing___font_style_struct.md)) | Obtains a typeface based on the font style information and font family name.| -| [OH_Drawing_Typeface](_drawing.md#oh_drawing_typeface) \* [OH_Drawing_FontMgrMatchFamilyStyleCharacter](_drawing.md#oh_drawing_fontmgrmatchfamilystylecharacter) ([OH_Drawing_FontMgr](_drawing.md#oh_drawing_fontmgr) \*, const char \*familyName, [OH_Drawing_FontStyleStruct](_o_h___drawing___font_style_struct.md), const char \*bcp47[], int bcp47Count, int32_t character) | Obtains a typeface for the specified character.| +| [OH_Drawing_Typeface](_drawing.md#oh_drawing_typeface) \* [OH_Drawing_FontMgrMatchFamilyStyleCharacter](_drawing.md#oh_drawing_fontmgrmatchfamilystylecharacter) ([OH_Drawing_FontMgr](_drawing.md#oh_drawing_fontmgr) \*, const char \*familyName, [OH_Drawing_FontStyleStruct](_o_h___drawing___font_style_struct.md), const char \*bcp47[], int bcp47Count, int32_t character) | Obtains a typeface for the specified character. A null pointer is returned only when no typeface corresponding to the input UTF-8 character is found in the **OH_Drawing_FontMgr** object.| | [OH_Drawing_Typeface](_drawing.md#oh_drawing_typeface) \* [OH_Drawing_FontStyleSetCreateTypeface](_drawing.md#oh_drawing_fontstylesetcreatetypeface) ([OH_Drawing_FontStyleSet](_drawing.md#oh_drawing_fontstyleset) \*, int index) | Obtains a typeface for the specified index.| | [OH_Drawing_FontStyleStruct](_o_h___drawing___font_style_struct.md) [OH_Drawing_FontStyleSetGetStyle](_drawing.md#oh_drawing_fontstylesetgetstyle) ([OH_Drawing_FontStyleSet](_drawing.md#oh_drawing_fontstyleset) \*, int32_t index, char \*\*styleName) | Obtains the font style.| | void [OH_Drawing_FontStyleSetFreeStyleName](_drawing.md#oh_drawing_fontstylesetfreestylename) (char \*\*styleName) | Reclaims the memory occupied by a font style.| diff --git a/en/application-dev/reference/apis-arkgraphics2d/drawing__gpu__context_8h.md b/en/application-dev/reference/apis-arkgraphics2d/drawing__gpu__context_8h.md index 04c106323c899facc542c4fd1181a2ac2542c900..c7288185ca103fcbade7cb4122d92407a18423af 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/drawing__gpu__context_8h.md +++ b/en/application-dev/reference/apis-arkgraphics2d/drawing__gpu__context_8h.md @@ -36,4 +36,5 @@ The **drawing_gpu_context.h** file declares the functions related to the GPU con | Name| Description| | -------- | -------- | | [OH_Drawing_GpuContext](_drawing.md#oh_drawing_gpucontext) \* [OH_Drawing_GpuContextCreateFromGL](_drawing.md#oh_drawing_gpucontextcreatefromgl) ([OH_Drawing_GpuContextOptions](_o_h___drawing___gpu_context_options.md)) | Creates an **OH_Drawing_GpuContext** object that uses OpenGL as the backend interface.| +| [OH_Drawing_GpuContext](_drawing.md#oh_drawing_gpucontext) \* [OH_Drawing_GpuContextCreate](_drawing.md#oh_drawing_gpucontextcreate) (void) | Creates an **OH_Drawing_GpuContext** object, for which the backend type depends on the device. | | void [OH_Drawing_GpuContextDestroy](_drawing.md#oh_drawing_gpucontextdestroy) ([OH_Drawing_GpuContext](_drawing.md#oh_drawing_gpucontext) \*) | Destroys an **OH_Drawing_GpuContext** object and reclaims the memory occupied by the object.| diff --git a/en/application-dev/reference/apis-arkgraphics2d/drawing__path_8h.md b/en/application-dev/reference/apis-arkgraphics2d/drawing__path_8h.md index 72433a5a6d081ff6661fd2810f150928a021f781..623cfa0bfb7bac27d0f1b3e8aab0b8909db45d8d 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/drawing__path_8h.md +++ b/en/application-dev/reference/apis-arkgraphics2d/drawing__path_8h.md @@ -42,6 +42,7 @@ The **drawing_path.h** file declares the functions related to the path in the dr | Name| Description| | -------- | -------- | +| [OH_Drawing_ErrorCode](_drawing.md#oh_drawing_errorcode) [OH_Drawing_PathGetSegment](_drawing.md#oh_drawing_pathgetsegment) ([OH_Drawing_Path](_drawing.md#oh_drawing_path) \*path, bool forceClosed, float start, float stop, bool startWithMoveTo, [OH_Drawing_Path](_drawing.md#oh_drawing_path) \*dst, bool \*result) | Extracts a segment of a path and appends it to a destination path. | | [OH_Drawing_Path](_drawing.md#oh_drawing_path) \* [OH_Drawing_PathCreate](_drawing.md#oh_drawing_pathcreate) (void) | Creates an **OH_Drawing_Path** object.| | [OH_Drawing_Path](_drawing.md#oh_drawing_path) \* [OH_Drawing_PathCopy](_drawing.md#oh_drawing_pathcopy) ([OH_Drawing_Path](_drawing.md#oh_drawing_path) \*) | Copies an existing [OH_Drawing_Path](_drawing.md#oh_drawing_path) object to create a new one.| | void [OH_Drawing_PathDestroy](_drawing.md#oh_drawing_pathdestroy) ([OH_Drawing_Path](_drawing.md#oh_drawing_path) \*) | Destroys an **OH_Drawing_Path** object and reclaims the memory occupied by the object.| diff --git a/en/application-dev/reference/apis-arkgraphics2d/drawing__path__effect_8h.md b/en/application-dev/reference/apis-arkgraphics2d/drawing__path__effect_8h.md index f39426b096e3faa073483239ca0171e2e2f39402..9a89ee87d20ce88aa3777bdddae5facd5935573d 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/drawing__path__effect_8h.md +++ b/en/application-dev/reference/apis-arkgraphics2d/drawing__path__effect_8h.md @@ -16,10 +16,27 @@ The **drawing_path_effect.h** file declares the functions related to the path ef ## Summary +### Types + +| Name| Description| +| -------- | -------- | +| typedef enum [OH_Drawing_PathDashStyle](_drawing.md#oh_drawing_pathdashstyle) [OH_Drawing_PathDashStyle](_drawing.md#oh_drawing_pathdashstyle) | Defines an enum for the styles of the dashed path effect. | + + +### Enums + +| Name| Description| +| -------- | -------- | +| [OH_Drawing_PathDashStyle](_drawing.md#oh_drawing_pathdashstyle-1) { DRAWING_PATH_DASH_STYLE_TRANSLATE, DRAWING_PATH_DASH_STYLE_ROTATE, DRAWING_PATH_DASH_STYLE_MORPH } | Enumerates the styles of the dashed path effect. | ### Functions -| Name| Description| +| Name| Description| | -------- | -------- | -| [OH_Drawing_PathEffect](_drawing.md#oh_drawing_patheffect) \* [OH_Drawing_CreateDashPathEffect](_drawing.md#oh_drawing_createdashpatheffect) (float \*intervals, int count, float phase) | Creates an **OH_Drawing_PathEffect** object with a dashed line effect. The dashed line effect is determined by a group of "on" and "off" intervals.| -| void [OH_Drawing_PathEffectDestroy](_drawing.md#oh_drawing_patheffectdestroy) ([OH_Drawing_PathEffect](_drawing.md#oh_drawing_patheffect) \*) | Destroys an **OH_Drawing_PathEffect** object and reclaims the memory occupied by the object.| +| [OH_Drawing_PathEffect](_drawing.md#oh_drawing_patheffect) \* [OH_Drawing_CreateComposePathEffect](_drawing.md#oh_drawing_createcomposepatheffect) ([OH_Drawing_PathEffect](_drawing.md#oh_drawing_patheffect) \*outer, [OH_Drawing_PathEffect](_drawing.md#oh_drawing_patheffect) \*inner) | Creates a path effect by sequentially applying the inner effect and then the outer effect. | +| [OH_Drawing_PathEffect](_drawing.md#oh_drawing_patheffect) \* [OH_Drawing_CreateCornerPathEffect](_drawing.md#oh_drawing_createcornerpatheffect) (float radius) | Creates a path effect that transforms the sharp angle between line segments into a rounded corner with the specified radius. | +| [OH_Drawing_PathEffect](_drawing.md#oh_drawing_patheffect) \* [OH_Drawing_CreateDashPathEffect](_drawing.md#oh_drawing_createdashpatheffect) (float \*intervals, int count, float phase) | Creates a dashed path effect, which is determined by a group of "on" and "off" intervals. | +| [OH_Drawing_PathEffect](_drawing.md#oh_drawing_patheffect) \* [OH_Drawing_CreateDiscretePathEffect](_drawing.md#oh_drawing_creatediscretepatheffect) (float segLength, float deviation) | Creates a path effect that segments the path and scatters the segments in an irregular pattern along the path. | +| [OH_Drawing_PathEffect](_drawing.md#oh_drawing_patheffect) \* [OH_Drawing_CreatePathDashEffect](_drawing.md#oh_drawing_createpathdasheffect) (const [OH_Drawing_Path](_drawing.md#oh_drawing_path) \*path, float advance, float phase, [OH_Drawing_PathDashStyle](_drawing.md#oh_drawing_pathdashstyle) type) | Creates a dashed path effect. | +| [OH_Drawing_PathEffect](_drawing.md#oh_drawing_patheffect) \* [OH_Drawing_CreateSumPathEffect](_drawing.md#oh_drawing_createsumpatheffect) ([OH_Drawing_PathEffect](_drawing.md#oh_drawing_patheffect) \*firstPathEffect, [OH_Drawing_PathEffect](_drawing.md#oh_drawing_patheffect) \*secondPathEffect) | Creates an overlay path effect based on two distinct path effects that take effect separately. | +| void [OH_Drawing_PathEffectDestroy](_drawing.md#oh_drawing_patheffectdestroy) ([OH_Drawing_PathEffect](_drawing.md#oh_drawing_patheffect) \*) | Destroys an **OH_Drawing_PathEffect** object and reclaims the memory occupied by the object. | diff --git a/en/application-dev/reference/apis-arkgraphics2d/drawing__rect_8h.md b/en/application-dev/reference/apis-arkgraphics2d/drawing__rect_8h.md index 2f5d3ef1c58e68f3a7e324911418123c208cbfeb..ab54311998760baeadd8c0fd7c083d63b38641ff 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/drawing__rect_8h.md +++ b/en/application-dev/reference/apis-arkgraphics2d/drawing__rect_8h.md @@ -36,7 +36,7 @@ The **drawing_rect.h** file declares the functions related to the rectangle in t | void [OH_Drawing_RectSetBottom](_drawing.md#oh_drawing_rectsetbottom) ([OH_Drawing_Rect](_drawing.md#oh_drawing_rect) \*rect, float bottom) | Sets the Y coordinate of the lower right corner of a rectangle. | | void [OH_Drawing_RectCopy](_drawing.md#oh_drawing_rectcopy) ([OH_Drawing_Rect](_drawing.md#oh_drawing_rect) \*sRect, [OH_Drawing_Rect](_drawing.md#oh_drawing_rect) \*dRect) | Copies a source rectangle to create a new one. | | void [OH_Drawing_RectDestroy](_drawing.md#oh_drawing_rectdestroy) ([OH_Drawing_Rect](_drawing.md#oh_drawing_rect) \*) | Destroys an **OH_Drawing_Rect** object and reclaims the memory occupied by the object. | -| [OH_Drawing_Array](_drawing.md#oh_drawing_array) \* [OH_Drawing_RectCreateArray](_drawing.md#oh_drawing_rectcreatearray) (size_t size) | Creates a rectangle array object to store multiple rectangle objects. | +| [OH_Drawing_Array](_drawing.md#oh_drawing_array) \* [OH_Drawing_RectCreateArray](_drawing.md#oh_drawing_rectcreatearray) (size_t size) | Creates a rectangle array object to store multiple rectangle objects. When [OH_Drawing_Array](_drawing.md#oh_drawing_array) is no longer required, call [OH_Drawing_RectDestroyArray](_drawing.md#oh_drawing_rectdestroyarray) to release the pointer to the object. | | [OH_Drawing_ErrorCode](_drawing.md#oh_drawing_errorcode) [OH_Drawing_RectGetArraySize](_drawing.md#oh_drawing_rectgetarraysize) ([OH_Drawing_Array](_drawing.md#oh_drawing_array) \*rectArray, size_t \*pSize) | Obtains the size of a rectangle array, which is an [OH_Drawing_Array](_drawing.md#oh_drawing_array) object. | | [OH_Drawing_ErrorCode](_drawing.md#oh_drawing_errorcode) [OH_Drawing_RectGetArrayElement](_drawing.md#oh_drawing_rectgetarrayelement) ([OH_Drawing_Array](_drawing.md#oh_drawing_array) \*rectArray, size_t index, [OH_Drawing_Rect](_drawing.md#oh_drawing_rect) \*\*rect) | Obtains the rectangle with the specified index in a rectangle array. | | [OH_Drawing_ErrorCode](_drawing.md#oh_drawing_errorcode) [OH_Drawing_RectDestroyArray](_drawing.md#oh_drawing_rectdestroyarray) ([OH_Drawing_Array](_drawing.md#oh_drawing_array) \*rectArray) | Destroys an **OH_Drawing_Array** object and reclaims the memory occupied by the object. | diff --git a/en/application-dev/reference/apis-arkgraphics2d/drawing__surface_8h.md b/en/application-dev/reference/apis-arkgraphics2d/drawing__surface_8h.md index a40ac9f2291321b07cbe697339fead01165d33b2..6d2738ddc597a9dcbbe490f1b423d592d3771abb 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/drawing__surface_8h.md +++ b/en/application-dev/reference/apis-arkgraphics2d/drawing__surface_8h.md @@ -16,11 +16,12 @@ The **drawing_surface.h** file declares the functions related to the surface in ## Summary - ### Functions | Name| Description| | -------- | -------- | -| [OH_Drawing_Surface](_drawing.md#oh_drawing_surface) \* [OH_Drawing_SurfaceCreateFromGpuContext](_drawing.md#oh_drawing_surfacecreatefromgpucontext) ([OH_Drawing_GpuContext](_drawing.md#oh_drawing_gpucontext) \*, bool budgeted, [OH_Drawing_Image_Info](_o_h___drawing___image___info.md)) | Creates an **OH_Drawing_Surface** object using the GPU context to manage the content drawn on the canvas.| -| [OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \* [OH_Drawing_SurfaceGetCanvas](_drawing.md#oh_drawing_surfacegetcanvas) ([OH_Drawing_Surface](_drawing.md#oh_drawing_surface) \*) | Obtains a canvas from an **OH_Drawing_Surface** object.| -| void [OH_Drawing_SurfaceDestroy](_drawing.md#oh_drawing_surfacedestroy) ([OH_Drawing_Surface](_drawing.md#oh_drawing_surface) \*) | Destroys an **OH_Drawing_Surface** object and reclaims the memory occupied.| +| [OH_Drawing_Surface](_drawing.md#oh_drawing_surface) \* [OH_Drawing_SurfaceCreateFromGpuContext](_drawing.md#oh_drawing_surfacecreatefromgpucontext) ([OH_Drawing_GpuContext](_drawing.md#oh_drawing_gpucontext) \*, bool budgeted, [OH_Drawing_Image_Info](_o_h___drawing___image___info.md)) | Creates an **OH_Drawing_Surface** object using the GPU context to manage the content drawn on the canvas. | +| [OH_Drawing_Surface](_drawing.md#oh_drawing_surface) \* [OH_Drawing_SurfaceCreateOnScreen](_drawing.md#oh_drawing_surfacecreateonscreen) ([OH_Drawing_GpuContext](_drawing.md#oh_drawing_gpucontext) \*gpuContext, [OH_Drawing_Image_Info](_o_h___drawing___image___info.md) imageInfo, void \*window) | Creates an **OH_Drawing_Surface** object bound to the window using the GPU context to manage the content drawn on the canvas. | +| [OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \* [OH_Drawing_SurfaceGetCanvas](_drawing.md#oh_drawing_surfacegetcanvas) ([OH_Drawing_Surface](_drawing.md#oh_drawing_surface) \*) | Obtains a canvas from an **OH_Drawing_Surface** object. | +| [OH_Drawing_ErrorCode](_drawing.md#oh_drawing_errorcode) [OH_Drawing_SurfaceFlush](_drawing.md#oh_drawing_surfaceflush) ([OH_Drawing_Surface](_drawing.md#oh_drawing_surface) \*surface) | Pushes the drawing content from an **OH_Drawing_Surface** object to the GPU for rendering. | +| void [OH_Drawing_SurfaceDestroy](_drawing.md#oh_drawing_surfacedestroy) ([OH_Drawing_Surface](_drawing.md#oh_drawing_surface) \*) | Destroys an **OH_Drawing_Surface** object and reclaims the memory occupied. | diff --git a/en/application-dev/reference/apis-arkgraphics2d/drawing__text__declaration_8h.md b/en/application-dev/reference/apis-arkgraphics2d/drawing__text__declaration_8h.md index 9eb633128bca5f5449df2cb093deb2c7a30f3a64..111af0c04d3992d8f9d2726f0a12e87b71045ae1 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/drawing__text__declaration_8h.md +++ b/en/application-dev/reference/apis-arkgraphics2d/drawing__text__declaration_8h.md @@ -28,7 +28,7 @@ The **drawing_text_declaration.h** file declares the structs related to text in | typedef struct [OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) [OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) | Defines a struct used to manage text colors and decorations.| | typedef struct [OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) [OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) | Defines a struct used to manage the typography style, such as the text direction.| | typedef struct [OH_Drawing_TypographyCreate](_drawing.md#oh_drawing_typographycreate) [OH_Drawing_TypographyCreate](_drawing.md#oh_drawing_typographycreate) | Defines a struct used to create an [OH_Drawing_Typography](_drawing.md#oh_drawing_typography) object.| -| typedef struct [OH_Drawing_TextBox](_drawing.md#oh_drawing_textbox) [OH_Drawing_TextBox](_drawing.md#oh_drawing_textbox) | Defines a struct used to receive the rectangle size, direction, and quantity of text boxes.| +| typedef struct [OH_Drawing_TextBox](_drawing.md#oh_drawing_textbox) [OH_Drawing_TextBox](_drawing.md#oh_drawing_textbox) | Defines a struct for a text box, which is used to receive the rectangle size, direction, and quantity.| | typedef struct [OH_Drawing_PositionAndAffinity](_drawing.md#oh_drawing_positionandaffinity) [OH_Drawing_PositionAndAffinity](_drawing.md#oh_drawing_positionandaffinity) | Defines a struct used to receive the position and affinity of a glyph.| | typedef struct [OH_Drawing_Range](_drawing.md#oh_drawing_range) [OH_Drawing_Range](_drawing.md#oh_drawing_range) | Defines a struct used to receive the start position and end position of a glyph.| | typedef struct [OH_Drawing_TextShadow](_drawing.md#oh_drawing_textshadow) [OH_Drawing_TextShadow](_drawing.md#oh_drawing_textshadow) | Defines a struct used to manage text shadows.| diff --git a/en/application-dev/reference/apis-arkgraphics2d/drawing__text__font__descriptor_8h.md b/en/application-dev/reference/apis-arkgraphics2d/drawing__text__font__descriptor_8h.md index 317361b04c57094a0214e811c742957e45acce09..d544b4242926b8ff5ff4bce2ff8e433a2fa3cc78 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/drawing__text__font__descriptor_8h.md +++ b/en/application-dev/reference/apis-arkgraphics2d/drawing__text__font__descriptor_8h.md @@ -35,7 +35,7 @@ The **drawing_text_font_descriptor.h** file declares the capabilities of font in | Name| Description| | -------- | -------- | -| [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) \* [OH_Drawing_MatchFontDescriptors](_drawing.md#oh_drawing_matchfontdescriptors) ([OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) \*, size_t \*) | Obtains all system font descriptors that match a font descriptor. In the [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) struct, the **path** field is not used for matching, and other fields are valid only when they are not set to their default values. If all fields in [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) are set to their default values, all system font descriptors are obtained. If no matching is found, NULL is returned. | +| [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) \* [OH_Drawing_MatchFontDescriptors](_drawing.md#oh_drawing_matchfontdescriptors) ([OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) \*, size_t \*) | Obtains all system font descriptors that match a font descriptor. In the [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) struct, the **path** field is not used for matching, and other fields are valid only when they are not set to their default values. If all fields in [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) are set to their default values, all system font descriptors are returned. If no matching is found, NULL is returned. When [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) is no longer required, call [OH_Drawing_DestroyFontDescriptors](_drawing.md#oh_drawing_destroyfontdescriptors) to release the pointer to the object. | | void [OH_Drawing_DestroyFontDescriptors](_drawing.md#oh_drawing_destroyfontdescriptors) ([OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) \*, size_t) | Releases an array of [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) objects. | | [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) \* [OH_Drawing_GetFontDescriptorByFullName](_drawing.md#oh_drawing_getfontdescriptorbyfullname) (const [OH_Drawing_String](_o_h___drawing___string.md) \*, [OH_Drawing_SystemFontType](_drawing.md#oh_drawing_systemfonttype)) | Obtains a font descriptor based on the font name and type. System fonts, style fonts, and user-installed fonts are supported. A font descriptor is a data structure that describes font features. It contains details of the font appearance and properties. | | [OH_Drawing_Array](_drawing.md#oh_drawing_array) \* [OH_Drawing_GetSystemFontFullNamesByType](_drawing.md#oh_drawing_getsystemfontfullnamesbytype) ([OH_Drawing_SystemFontType](_drawing.md#oh_drawing_systemfonttype)) | Obtains an array of font names by font type. | diff --git a/en/application-dev/reference/apis-arkgraphics2d/drawing__text__line_8h.md b/en/application-dev/reference/apis-arkgraphics2d/drawing__text__line_8h.md index 89f36ea5ff1cc46f6f3f96fa0587409718348a36..eca698af324619a8db52d264574bce763a7e91a6 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/drawing__text__line_8h.md +++ b/en/application-dev/reference/apis-arkgraphics2d/drawing__text__line_8h.md @@ -28,7 +28,7 @@ The **drawing_text_line.h** file declares the capabilities for obtaining the cha | Name| Description| | -------- | -------- | -| [OH_Drawing_Array](_drawing.md#oh_drawing_array) \* [OH_Drawing_TypographyGetTextLines](_drawing.md#oh_drawing_typographygettextlines) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*typography) | Obtains the array of text lines in a typography object. This array contains one or more text line objects. | +| [OH_Drawing_Array](_drawing.md#oh_drawing_array) \* [OH_Drawing_TypographyGetTextLines](_drawing.md#oh_drawing_typographygettextlines) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*typography) | Obtains the array of text lines in a typography object. This array contains one or more text line objects. When [OH_Drawing_Array](_drawing.md#oh_drawing_array) is no longer required, call [OH_Drawing_DestroyTextLines](_drawing.md#oh_drawing_destroytextlines) to release the pointer to the object. | | void [OH_Drawing_DestroyTextLines](_drawing.md#oh_drawing_destroytextlines) ([OH_Drawing_Array](_drawing.md#oh_drawing_array) \*lines) | Releases the memory occupied by a text line array. | | void [OH_Drawing_DestroyTextLine](_drawing.md#oh_drawing_destroytextline) (OH_Drawing_TextLine \*line) | Releases the memory occupied by a text line object. This is applicable only to text line objects that have requested memory on their own and not to a particular text line object within a text line array. | | OH_Drawing_TextLine \* [OH_Drawing_GetTextLineByIndex](_drawing.md#oh_drawing_gettextlinebyindex) ([OH_Drawing_Array](_drawing.md#oh_drawing_array) \*lines, size_t index) | Obtains the text line object with the specified index in a text line array. | diff --git a/en/application-dev/reference/apis-arkgraphics2d/drawing__text__run_8h.md b/en/application-dev/reference/apis-arkgraphics2d/drawing__text__run_8h.md index f98a5e3c376cda593fed354c39b5f4bc8af63228..04f7c52d2c92843ef824182d30b8151b6d755878 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/drawing__text__run_8h.md +++ b/en/application-dev/reference/apis-arkgraphics2d/drawing__text__run_8h.md @@ -21,7 +21,7 @@ The **drawing_text_run.h** file declares the capabilities of runs, such as obtai | Name| Description| | -------- | -------- | -| [OH_Drawing_Array](_drawing.md#oh_drawing_array) \* [OH_Drawing_GetRunStringIndices](_drawing.md#oh_drawing_getrunstringindices) (OH_Drawing_Run \*run, int64_t start, int64_t length) | Obtains character indices of glyphs within a specified range of a run, where the indices are offsets relative to the entire paragraph. | +| [OH_Drawing_Array](_drawing.md#oh_drawing_array) \* [OH_Drawing_GetRunStringIndices](_drawing.md#oh_drawing_getrunstringindices) (OH_Drawing_Run \*run, int64_t start, int64_t length) | Obtains an array of character indices of glyphs within a specified range of a run, where the indices are offsets relative to the entire paragraph. | | uint64_t [OH_Drawing_GetRunStringIndicesByIndex](_drawing.md#oh_drawing_getrunstringindicesbyindex) ([OH_Drawing_Array](_drawing.md#oh_drawing_array) \*stringIndices, size_t index) | Obtains character indices of glyphs in a run by index. | | void [OH_Drawing_DestroyRunStringIndices](_drawing.md#oh_drawing_destroyrunstringindices) ([OH_Drawing_Array](_drawing.md#oh_drawing_array) \*stringIndices) | Releases the pointer to a character index array. | | void [OH_Drawing_GetRunStringRange](_drawing.md#oh_drawing_getrunstringrange) (OH_Drawing_Run \*run, uint64_t \*location, uint64_t \*length) | Obtains the range of glyphs generated by a run. | diff --git a/en/application-dev/reference/apis-arkgraphics2d/drawing__text__typography_8h.md b/en/application-dev/reference/apis-arkgraphics2d/drawing__text__typography_8h.md index 352e11beec1e87278f9427de874f2d4808da29db..2f30be01b246101044174972600e930258399b9f 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/drawing__text__typography_8h.md +++ b/en/application-dev/reference/apis-arkgraphics2d/drawing__text__typography_8h.md @@ -40,7 +40,7 @@ The **drawing_text_typography.h** file declares the functions related to typogra | Name| Description| | -------- | -------- | | typedef enum [OH_Drawing_PlaceholderVerticalAlignment](_drawing.md#oh_drawing_placeholderverticalalignment-1) [OH_Drawing_PlaceholderVerticalAlignment](_drawing.md#oh_drawing_placeholderverticalalignment) | Defines an enum for the vertical alignment modes of placeholders. | -| typedef struct [OH_Drawing_PlaceholderSpan](_o_h___drawing___placeholder_span.md) [OH_Drawing_PlaceholderSpan](_drawing.md#oh_drawing_placeholderspan) | Describes the placeholder that acts as a span. | +| typedef struct [OH_Drawing_PlaceholderSpan](_o_h___drawing___placeholder_span.md) [OH_Drawing_PlaceholderSpan](_drawing.md#oh_drawing_placeholderspan) | Defines a struct for the placeholder that acts as a span. | | typedef enum [OH_Drawing_TextDecorationStyle](_drawing.md#oh_drawing_textdecorationstyle-1) [OH_Drawing_TextDecorationStyle](_drawing.md#oh_drawing_textdecorationstyle) | Defines an enum for the text decoration styles. | | typedef enum [OH_Drawing_EllipsisModal](_drawing.md#oh_drawing_ellipsismodal-1) [OH_Drawing_EllipsisModal](_drawing.md#oh_drawing_ellipsismodal) | Defines an enum for the text ellipsis styles. | | typedef enum [OH_Drawing_BreakStrategy](_drawing.md#oh_drawing_breakstrategy-1) [OH_Drawing_BreakStrategy](_drawing.md#oh_drawing_breakstrategy) | Defines an enum for the text break strategies. | @@ -73,7 +73,7 @@ The **drawing_text_typography.h** file declares the functions related to typogra | [OH_Drawing_TextDecorationStyle](_drawing.md#oh_drawing_textdecorationstyle) {
TEXT_DECORATION_STYLE_SOLID, TEXT_DECORATION_STYLE_DOUBLE, TEXT_DECORATION_STYLE_DOTTED, TEXT_DECORATION_STYLE_DASHED,
TEXT_DECORATION_STYLE_WAVY
} | Enumerates the text decoration styles. | | [OH_Drawing_EllipsisModal](_drawing.md#oh_drawing_ellipsismodal) { ELLIPSIS_MODAL_HEAD = 0, ELLIPSIS_MODAL_MIDDLE = 1, ELLIPSIS_MODAL_TAIL = 2 } | Enumerates the text ellipsis styles. | | [OH_Drawing_BreakStrategy](_drawing.md#oh_drawing_breakstrategy) { BREAK_STRATEGY_GREEDY = 0, BREAK_STRATEGY_HIGH_QUALITY = 1, BREAK_STRATEGY_BALANCED = 2 } | Enumerates the text break strategies. | -| [OH_Drawing_WordBreakType](_drawing.md#oh_drawing_wordbreaktype) { WORD_BREAK_TYPE_NORMAL = 0, WORD_BREAK_TYPE_BREAK_ALL = 1, WORD_BREAK_TYPE_BREAK_WORD = 2 } | Enumerates the word break types. | +| [OH_Drawing_WordBreakType](_drawing.md#oh_drawing_wordbreaktype) { WORD_BREAK_TYPE_NORMAL = 0, WORD_BREAK_TYPE_BREAK_ALL = 1, WORD_BREAK_TYPE_BREAK_WORD = 2, WORD_BREAK_TYPE_BREAK_HYPHEN = 3 } | Enumerates the word break types. | | [OH_Drawing_RectHeightStyle](_drawing.md#oh_drawing_rectheightstyle) {
RECT_HEIGHT_STYLE_TIGHT, [RECT_HEIGHT_STYLE_MAX, RECT_HEIGHT_STYLE_INCLUDELINESPACEMIDDLE, RECT_HEIGHT_STYLE_INCLUDELINESPACETOP,
RECT_HEIGHT_STYLE_INCLUDELINESPACEBOTTOM, RECT_HEIGHT_STYLE_STRUCT
} | Enumerates the rectangle height styles. | | [OH_Drawing_RectWidthStyle](_drawing.md#oh_drawing_rectwidthstyle) { RECT_WIDTH_STYLE_TIGHT, RECT_WIDTH_STYLE_MAX } | Enumerates the rectangle width styles. | | [OH_Drawing_FontConfigInfoErrorCode](_drawing.md#oh_drawing_fontconfiginfoerrorcode) {
SUCCESS_FONT_CONFIG_INFO = 0, ERROR_FONT_CONFIG_INFO_UNKNOWN = 1, ERROR_FONT_CONFIG_INFO_PARSE_FILE = 2, ERROR_FONT_CONFIG_INFO_ALLOC_MEMORY = 3,
ERROR_FONT_CONFIG_INFO_COPY_STRING_DATA = 4
} | Enumerates the error codes that may be used during the obtaining of system font configurations. | @@ -86,27 +86,27 @@ The **drawing_text_typography.h** file declares the functions related to typogra | Name| Description| | -------- | -------- | -| [OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \* [OH_Drawing_CreateTypographyStyle](_drawing.md#oh_drawing_createtypographystyle) (void) | Creates an **OH_Drawing_TypographyStyle** object. | +| [OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \* [OH_Drawing_CreateTypographyStyle](_drawing.md#oh_drawing_createtypographystyle) (void) | Creates an **OH_Drawing_TypographyStyle** object. When [OH_Drawing_TypographyStyle](#oh_drawing_typographystyle) is no longer required, call [OH_Drawing_DestroyTypographyStyle](_drawing.md#oh_drawing_destroytypographystyle) to release the pointer to the object. | | void [OH_Drawing_DestroyTypographyStyle](_drawing.md#oh_drawing_destroytypographystyle) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*) | Destroys an **OH_Drawing_TypographyStyle** object and reclaims the memory occupied by the object. | -| void [OH_Drawing_SetTypographyTextDirection](_drawing.md#oh_drawing_settypographytextdirection) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*, int) | Sets the text direction. | +| void [OH_Drawing_SetTypographyTextDirection](_drawing.md#oh_drawing_settypographytextdirection) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*, int) | Sets the text direction in a typography style. | | void [OH_Drawing_SetTypographyTextAlign](_drawing.md#oh_drawing_settypographytextalign) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*, int) | Sets the text alignment mode. | | int [OH_Drawing_TypographyGetEffectiveAlignment](_drawing.md#oh_drawing_typographygeteffectivealignment) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*style) | Obtains the text alignment mode. | | void [OH_Drawing_SetTypographyTextMaxLines](_drawing.md#oh_drawing_settypographytextmaxlines) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*, int) | Sets the maximum number of lines in the text. | | [OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \* [OH_Drawing_CreateTextStyle](_drawing.md#oh_drawing_createtextstyle) (void) | Creates an **OH_Drawing_TextStyle** object. | -| [OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \* [OH_Drawing_TypographyGetTextStyle](_drawing.md#oh_drawing_typographygettextstyle) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*style) | Obtains the text style of a typography style. | +| [OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \* [OH_Drawing_TypographyGetTextStyle](_drawing.md#oh_drawing_typographygettextstyle) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*style) | Obtains the default text style of a typography style. | | void [OH_Drawing_DestroyTextStyle](_drawing.md#oh_drawing_destroytextstyle) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*) | Destroys an **OH_Drawing_TextStyle** object and reclaims the memory occupied by the object. | | void [OH_Drawing_SetTextStyleColor](_drawing.md#oh_drawing_settextstylecolor) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, uint32_t) | Sets the color for a text style. | | void [OH_Drawing_SetTextStyleFontSize](_drawing.md#oh_drawing_settextstylefontsize) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, double) | Sets the font size for a text style. | -| void [OH_Drawing_SetTextStyleFontWeight](_drawing.md#oh_drawing_settextstylefontweight) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, int) | Sets the font weight for a text style. Currently, only the default system font supports font weight adjustment. For other fonts, if the weight is less than semi-bold, there is no variation in stroke thickness. If the weight is greater than or equal to semi-bold, it might result in a fake bold effect. | -| void [OH_Drawing_SetTextStyleBaseLine](_drawing.md#oh_drawing_settextstylebaseline) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, int) | Sets the baseline for a text style. | -| void [OH_Drawing_SetTextStyleDecoration](_drawing.md#oh_drawing_settextstyledecoration) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, int) | Sets the decoration for a text style. | +| void [OH_Drawing_SetTextStyleFontWeight](_drawing.md#oh_drawing_settextstylefontweight) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, int) | Sets the font weight for a text style. Currently, only the default system font supports font weight adjustment. For other fonts, if the weight is less than semi-bold, there is no variation in stroke thickness. If the weight is greater than or equal to semi-bold, it might result in a fake bold effect.| +| void [OH_Drawing_SetTextStyleBaseLine](_drawing.md#oh_drawing_settextstylebaseline) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, int) | Sets the baseline for a text style.| +| void [OH_Drawing_SetTextStyleDecoration](_drawing.md#oh_drawing_settextstyledecoration) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, int) | Sets the decoration for a text style. Only one decoration can be set. To add multiple decorations, use [OH_Drawing_AddTextStyleDecoration](_drawing.md#oh_drawing_addtextstyledecoration).| | void [OH_Drawing_AddTextStyleDecoration](_drawing.md#oh_drawing_addtextstyledecoration) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, int) | Adds the decoration for a text style. Multiple decoration lines can be displayed. | | void [OH_Drawing_RemoveTextStyleDecoration](_drawing.md#oh_drawing_removetextstyledecoration) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, int) | Removes the decoration for a text style. | | void [OH_Drawing_SetTextStyleDecorationColor](_drawing.md#oh_drawing_settextstyledecorationcolor) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, uint32_t) | Sets the decoration color for a text style. | | void [OH_Drawing_SetTextStyleFontHeight](_drawing.md#oh_drawing_settextstylefontheight) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, double) | Sets the line height based on the multiple of the font size. | -| void [OH_Drawing_SetTextStyleFontFamilies](_drawing.md#oh_drawing_settextstylefontfamilies) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, int, const char \*fontFamilies[]) | Sets the font families for a text style. | -| void [OH_Drawing_SetTextStyleFontStyle](_drawing.md#oh_drawing_settextstylefontstyle) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, int) | Sets the font style for a text style. | -| void [OH_Drawing_SetTextStyleLocale](_drawing.md#oh_drawing_settextstylelocale) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, const char \*) | Sets the locale for a text style. | +| void [OH_Drawing_SetTextStyleFontFamilies](_drawing.md#oh_drawing_settextstylefontfamilies) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, int, const char \*fontFamilies[]) | Sets the font families for a text style. | +| void [OH_Drawing_SetTextStyleFontStyle](_drawing.md#oh_drawing_settextstylefontstyle) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, int) | Sets the font style for a text style. | +| void [OH_Drawing_SetTextStyleLocale](_drawing.md#oh_drawing_settextstylelocale) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, const char \*) | Sets the locale for a text style. | | void [OH_Drawing_SetTextStyleForegroundBrush](_drawing.md#oh_drawing_settextstyleforegroundbrush) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, [OH_Drawing_Brush](_drawing.md#oh_drawing_brush) \*) | Sets the foreground brush for a text style. | | void [OH_Drawing_TextStyleGetForegroundBrush](_drawing.md#oh_drawing_textstylegetforegroundbrush) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, [OH_Drawing_Brush](_drawing.md#oh_drawing_brush) \*) | Obtains the foreground brush of a text style. | | void [OH_Drawing_SetTextStyleForegroundPen](_drawing.md#oh_drawing_settextstyleforegroundpen) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, [OH_Drawing_Pen](_drawing.md#oh_drawing_pen) \*) | Sets the foreground pen for a text style. | @@ -115,28 +115,28 @@ The **drawing_text_typography.h** file declares the functions related to typogra | void [OH_Drawing_TextStyleGetBackgroundBrush](_drawing.md#oh_drawing_textstylegetbackgroundbrush) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, [OH_Drawing_Brush](_drawing.md#oh_drawing_brush) \*) | Obtains the background brush of a text style. | | void [OH_Drawing_SetTextStyleBackgroundPen](_drawing.md#oh_drawing_settextstylebackgroundpen) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, [OH_Drawing_Pen](_drawing.md#oh_drawing_pen) \*) | Sets the background pen for a text style. | | void [OH_Drawing_TextStyleGetBackgroundPen](_drawing.md#oh_drawing_textstylegetbackgroundpen) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, [OH_Drawing_Pen](_drawing.md#oh_drawing_pen) \*) | Obtains the background pen of a text style. | -| [OH_Drawing_TypographyCreate](_drawing.md#oh_drawing_typographycreate) \* [OH_Drawing_CreateTypographyHandler](_drawing.md#oh_drawing_createtypographyhandler) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*, [OH_Drawing_FontCollection](_drawing.md#oh_drawing_fontcollection) \*) | Creates a handler to an **OH_Drawing_TypographyCreate** object. | +| [OH_Drawing_TypographyCreate](_drawing.md#oh_drawing_typographycreate) \* [OH_Drawing_CreateTypographyHandler](_drawing.md#oh_drawing_createtypographyhandler) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*, [OH_Drawing_FontCollection](_drawing.md#oh_drawing_fontcollection) \*) | Creates a handler to an **OH_Drawing_TypographyCreate** object. When [OH_Drawing_TypographyCreate](_drawing.md#oh_drawing_typographycreate) is no longer required, call [OH_Drawing_DestroyTypographyHandler](_drawing.md#oh_drawing_destroytypographyhandler) to release the pointer to the object. | | void [OH_Drawing_DestroyTypographyHandler](_drawing.md#oh_drawing_destroytypographyhandler) ([OH_Drawing_TypographyCreate](_drawing.md#oh_drawing_typographycreate) \*) | Reclaims the memory occupied by an **OH_Drawing_TypographyCreate** object. | -| void [OH_Drawing_TypographyHandlerPushTextStyle](_drawing.md#oh_drawing_typographyhandlerpushtextstyle) ([OH_Drawing_TypographyCreate](_drawing.md#oh_drawing_typographycreate) \*, [OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*) | Pushes the text style. | +| void [OH_Drawing_TypographyHandlerPushTextStyle](_drawing.md#oh_drawing_typographyhandlerpushtextstyle) ([OH_Drawing_TypographyCreate](_drawing.md#oh_drawing_typographycreate) \*, [OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*) | Pushes a text style into the text style stack. Any text added afterward will use the style currently on top of the stack. | | void [OH_Drawing_TypographyHandlerAddText](_drawing.md#oh_drawing_typographyhandleraddtext) ([OH_Drawing_TypographyCreate](_drawing.md#oh_drawing_typographycreate) \*, const char \*) | Adds text. | -| void [OH_Drawing_TypographyHandlerPopTextStyle](_drawing.md#oh_drawing_typographyhandlerpoptextstyle) ([OH_Drawing_TypographyCreate](_drawing.md#oh_drawing_typographycreate) \*) | Removes the topmost text style in the stack, leaving the remaining styles in effect. | -| [OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \* [OH_Drawing_CreateTypography](_drawing.md#oh_drawing_createtypography) ([OH_Drawing_TypographyCreate](_drawing.md#oh_drawing_typographycreate) \*) | Creates an **OH_Drawing_Typography** object. | +| void [OH_Drawing_TypographyHandlerPopTextStyle](_drawing.md#oh_drawing_typographyhandlerpoptextstyle) ([OH_Drawing_TypographyCreate](_drawing.md#oh_drawing_typographycreate) \*) | Pops the top text style out of the text style stack. | +| [OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \* [OH_Drawing_CreateTypography](_drawing.md#oh_drawing_createtypography) ([OH_Drawing_TypographyCreate](_drawing.md#oh_drawing_typographycreate) \*) | Creates an **OH_Drawing_Typography** object. When [OH_Drawing_Typography](_drawing.md#oh_drawing_typography) is no longer required, call [OH_Drawing_DestroyTypography](_drawing.md#oh_drawing_destroytypography) to release the pointer to the object. | | void [OH_Drawing_DestroyTypography](_drawing.md#oh_drawing_destroytypography) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*) | Destroys an **OH_Drawing_Typography** object and reclaims the memory occupied by the object. | | void [OH_Drawing_TypographyLayout](_drawing.md#oh_drawing_typographylayout) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*, double) | Lays out the typography. | -| void [OH_Drawing_TypographyPaint](_drawing.md#oh_drawing_typographypaint) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*, [OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, double, double) | Paints text. | +| void [OH_Drawing_TypographyPaint](_drawing.md#oh_drawing_typographypaint) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*, [OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, double, double) | Draws text from the upper left corner at a specified position. This function must be called after [OH_Drawing_TypographyLayout](_drawing.md#oh_drawing_typographylayout) is called and applied. | | void [OH_Drawing_TypographyPaintOnPath](_drawing.md#oh_drawing_typographypaintonpath) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*, [OH_Drawing_Canvas](_drawing.md#oh_drawing_canvas) \*, [OH_Drawing_Path](_drawing.md#oh_drawing_path) \*, double, double) | Draws text along a path. | -| double [OH_Drawing_TypographyGetMaxWidth](_drawing.md#oh_drawing_typographygetmaxwidth) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*) | Obtains the maximum width. | -| double [OH_Drawing_TypographyGetHeight](_drawing.md#oh_drawing_typographygetheight) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*) | Obtains the height. | -| double [OH_Drawing_TypographyGetLongestLine](_drawing.md#oh_drawing_typographygetlongestline) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*) | Obtains the width of the longest line. You are advised to round up the return value in actual use. When the text content is empty, the minimum float value, that is, -340282346638528859811704183484516925440.000000, is returned. | -| double [OH_Drawing_TypographyGetLongestLineWithIndent](_drawing.md#oh_drawing_typographygetlongestlinewithindent) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*) | Obtains the width of the longest line, including its indentation. You are advised to round up the return value in actual use. If the text content is empty, **0.0** is returned. | -| double [OH_Drawing_TypographyGetMinIntrinsicWidth](_drawing.md#oh_drawing_typographygetminintrinsicwidth) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*) | Obtains the minimum intrinsic width. | -| double [OH_Drawing_TypographyGetMaxIntrinsicWidth](_drawing.md#oh_drawing_typographygetmaxintrinsicwidth) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*) | Obtains the maximum intrinsic width. | -| double [OH_Drawing_TypographyGetAlphabeticBaseline](_drawing.md#oh_drawing_typographygetalphabeticbaseline) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*) | Obtains the alphabetic baseline. | -| double [OH_Drawing_TypographyGetIdeographicBaseline](_drawing.md#oh_drawing_typographygetideographicbaseline) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*) | Obtains the ideographic baseline. | +| double [OH_Drawing_TypographyGetMaxWidth](_drawing.md#oh_drawing_typographygetmaxwidth) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*) | Obtains the typography width set by the user. This function must be called after [OH_Drawing_TypographyLayout](_drawing.md#oh_drawing_typographylayout) is called. | +| double [OH_Drawing_TypographyGetHeight](_drawing.md#oh_drawing_typographygetheight) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*) | Obtains the overall height of a typography object. This function must be called after [OH_Drawing_TypographyLayout](_drawing.md#oh_drawing_typographylayout) is called. | +| double [OH_Drawing_TypographyGetLongestLine](_drawing.md#oh_drawing_typographygetlongestline) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*) | Obtains the width of the longest line in a typography object. This function must be called after [OH_Drawing_TypographyLayout](_drawing.md#oh_drawing_typographylayout) is called. You are advised to round up the return value. If the text content is empty, **0.0** is returned. | +| double [OH_Drawing_TypographyGetLongestLineWithIndent](_drawing.md#oh_drawing_typographygetlongestlinewithindent) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*) | Obtains the width of the longest line of a typography object, including its indentation. This function must be called after [OH_Drawing_TypographyLayout](_drawing.md#oh_drawing_typographylayout) is called. You are advised to round up the return value. If the text content is empty, **0.0** is returned. | +| double [OH_Drawing_TypographyGetMinIntrinsicWidth](_drawing.md#oh_drawing_typographygetminintrinsicwidth) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*) | Obtains the minimum intrinsic width in a typography object. This function must be called after [OH_Drawing_TypographyLayout](_drawing.md#oh_drawing_typographylayout) is called. | +| double [OH_Drawing_TypographyGetMaxIntrinsicWidth](_drawing.md#oh_drawing_typographygetmaxintrinsicwidth) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*) | Obtains the maximum intrinsic width in a typography object. This function must be called after [OH_Drawing_TypographyLayout](_drawing.md#oh_drawing_typographylayout) is called. | +| double [OH_Drawing_TypographyGetAlphabeticBaseline](_drawing.md#oh_drawing_typographygetalphabeticbaseline) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*) | Obtains the alphabetic baseline in a typography object. | +| double [OH_Drawing_TypographyGetIdeographicBaseline](_drawing.md#oh_drawing_typographygetideographicbaseline) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*) | Obtains the ideographic baseline in a typography object. | | void [OH_Drawing_TypographyHandlerAddPlaceholder](_drawing.md#oh_drawing_typographyhandleraddplaceholder) ([OH_Drawing_TypographyCreate](_drawing.md#oh_drawing_typographycreate) \*, [OH_Drawing_PlaceholderSpan](_o_h___drawing___placeholder_span.md) \*) | Adds a placeholder. | -| bool [OH_Drawing_TypographyDidExceedMaxLines](_drawing.md#oh_drawing_typographydidexceedmaxlines) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*) | Checks whether the maximum number of lines is exceeded. | -| [OH_Drawing_TextBox](_drawing.md#oh_drawing_textbox) \* [OH_Drawing_TypographyGetRectsForRange](_drawing.md#oh_drawing_typographygetrectsforrange) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*, size_t, size_t, [OH_Drawing_RectHeightStyle](_drawing.md#oh_drawing_rectheightstyle), [OH_Drawing_RectWidthStyle](_drawing.md#oh_drawing_rectwidthstyle)) | Obtains text boxes in a given range. | -| [OH_Drawing_TextBox](_drawing.md#oh_drawing_textbox) \* [OH_Drawing_TypographyGetRectsForPlaceholders](_drawing.md#oh_drawing_typographygetrectsforplaceholders) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*) | Obtains text boxes for placeholders. | +| bool [OH_Drawing_TypographyDidExceedMaxLines](_drawing.md#oh_drawing_typographydidexceedmaxlines) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*) | Checks whether the maximum number of lines of a typography object is exceeded. This function must be called after [OH_Drawing_TypographyLayout](_drawing.md#oh_drawing_typographylayout) is called. If the maximum number of lines is not set by calling [OH_Drawing_SetTypographyTextMaxLines](_drawing.md#oh_drawing_settypographytextmaxlines), **false** is returned. | +| [OH_Drawing_TextBox](_drawing.md#oh_drawing_textbox) \* [OH_Drawing_TypographyGetRectsForRange](_drawing.md#oh_drawing_typographygetrectsforrange) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*, size_t, size_t, [OH_Drawing_RectHeightStyle](_drawing.md#oh_drawing_rectheightstyle), [OH_Drawing_RectWidthStyle](_drawing.md#oh_drawing_rectwidthstyle)) | Obtains text boxes in a given range of a typography object. This function must be called after [OH_Drawing_TypographyLayout](_drawing.md#oh_drawing_typographylayout) is called. When [OH_Drawing_TextBox](_drawing.md#oh_drawing_textbox) is no longer required, call [OH_Drawing_TypographyDestroyTextBox](_drawing.md#oh_drawing_typographydestroytextbox) to release the pointer to the object. | +| [OH_Drawing_TextBox](_drawing.md#oh_drawing_textbox) \* [OH_Drawing_TypographyGetRectsForPlaceholders](_drawing.md#oh_drawing_typographygetrectsforplaceholders) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*) | Obtains text boxes for placeholders in a typography object. This function must be called after [OH_Drawing_TypographyLayout](_drawing.md#oh_drawing_typographylayout) is called. When [OH_Drawing_TextBox](_drawing.md#oh_drawing_textbox) is no longer required, call [OH_Drawing_TypographyDestroyTextBox](_drawing.md#oh_drawing_typographydestroytextbox) to release the pointer to the object. | | float [OH_Drawing_GetLeftFromTextBox](_drawing.md#oh_drawing_getleftfromtextbox) ([OH_Drawing_TextBox](_drawing.md#oh_drawing_textbox) \*, int) | Obtains the left position of a text box. | | float [OH_Drawing_GetRightFromTextBox](_drawing.md#oh_drawing_getrightfromtextbox) ([OH_Drawing_TextBox](_drawing.md#oh_drawing_textbox) \*, int) | Obtains the right position of a text box. | | float [OH_Drawing_GetTopFromTextBox](_drawing.md#oh_drawing_gettopfromtextbox) ([OH_Drawing_TextBox](_drawing.md#oh_drawing_textbox) \*, int) | Obtains the top position of a text box. | @@ -147,10 +147,10 @@ The **drawing_text_typography.h** file declares the functions related to typogra | [OH_Drawing_PositionAndAffinity](_drawing.md#oh_drawing_positionandaffinity) \* [OH_Drawing_TypographyGetGlyphPositionAtCoordinateWithCluster](_drawing.md#oh_drawing_typographygetglyphpositionatcoordinatewithcluster) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*, double, double) | Obtains the position and affinity of the glyph cluster to which the glyph at the given coordinates belongs. The glyph cluster is a container that holds one or more glyphs. | | size_t [OH_Drawing_GetPositionFromPositionAndAffinity](_drawing.md#oh_drawing_getpositionfrompositionandaffinity) ([OH_Drawing_PositionAndAffinity](_drawing.md#oh_drawing_positionandaffinity) \*) | Obtains the position attribute of an **OH_Drawing_PositionAndAffinity** object. | | int [OH_Drawing_GetAffinityFromPositionAndAffinity](_drawing.md#oh_drawing_getaffinityfrompositionandaffinity) ([OH_Drawing_PositionAndAffinity](_drawing.md#oh_drawing_positionandaffinity) \*) | Obtains the affinity attribute of an **OH_Drawing_PositionAndAffinity** object. The affinity determines whether the font is close to the front text or rear text. | -| [OH_Drawing_Range](_drawing.md#oh_drawing_range) \* [OH_Drawing_TypographyGetWordBoundary](_drawing.md#oh_drawing_typographygetwordboundary) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*, size_t) | Obtains the word boundary. | +| [OH_Drawing_Range](_drawing.md#oh_drawing_range) \* [OH_Drawing_TypographyGetWordBoundary](_drawing.md#oh_drawing_typographygetwordboundary) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*, size_t) | Obtains the word boundary in a typography object. | | size_t [OH_Drawing_GetStartFromRange](_drawing.md#oh_drawing_getstartfromrange) ([OH_Drawing_Range](_drawing.md#oh_drawing_range) \*) | Obtains the start position of an **OH_Drawing_Range** object. | | size_t [OH_Drawing_GetEndFromRange](_drawing.md#oh_drawing_getendfromrange) ([OH_Drawing_Range](_drawing.md#oh_drawing_range) \*) | Obtains the end position of an **OH_Drawing_Range** object. | -| size_t [OH_Drawing_TypographyGetLineCount](_drawing.md#oh_drawing_typographygetlinecount) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*) | Obtains the number of lines. | +| size_t [OH_Drawing_TypographyGetLineCount](_drawing.md#oh_drawing_typographygetlinecount) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*) | Obtains the number of lines in a typography object. This function must be called after [OH_Drawing_TypographyLayout](_drawing.md#oh_drawing_typographylayout) is called. | | void [OH_Drawing_SetTextStyleDecorationStyle](_drawing.md#oh_drawing_settextstyledecorationstyle) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, int) | Sets the decoration style for a text style. | | void [OH_Drawing_SetTextStyleDecorationThicknessScale](_drawing.md#oh_drawing_settextstyledecorationthicknessscale) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, double) | Sets the thickness scale factor for the decoration style of a text style. | | void [OH_Drawing_SetTextStyleLetterSpacing](_drawing.md#oh_drawing_settextstyleletterspacing) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, double) | Sets the letter spacing for a text style. | @@ -160,93 +160,93 @@ The **drawing_text_typography.h** file declares the functions related to typogra | void [OH_Drawing_SetTextStyleEllipsisModal](_drawing.md#oh_drawing_settextstyleellipsismodal) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, int) | Sets the ellipsis style for a text style. | | void [OH_Drawing_SetTypographyTextBreakStrategy](_drawing.md#oh_drawing_settypographytextbreakstrategy) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*, int) | Sets the text break strategy. | | void [OH_Drawing_SetTypographyTextWordBreakType](_drawing.md#oh_drawing_settypographytextwordbreaktype) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*, int) | Sets the word break type. | -| void [OH_Drawing_SetTypographyTextEllipsisModal](_drawing.md#oh_drawing_settypographytextellipsismodal) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*, int) | Sets the text ellipsis style. | +| void [OH_Drawing_SetTypographyTextEllipsisModal](_drawing.md#oh_drawing_settypographytextellipsismodal) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*, int) | Sets the text ellipsis style for a typography style. | | void [OH_Drawing_SetTypographyTextEllipsis](_drawing.md#oh_drawing_settypographytextellipsis) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*style, const char \*ellipsis) | Sets the text ellipsis content. | -| double [OH_Drawing_TypographyGetLineHeight](_drawing.md#oh_drawing_typographygetlineheight) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*, int) | Obtains the line height. | -| double [OH_Drawing_TypographyGetLineWidth](_drawing.md#oh_drawing_typographygetlinewidth) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*, int) | Obtains the line width. | +| double [OH_Drawing_TypographyGetLineHeight](_drawing.md#oh_drawing_typographygetlineheight) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*, int) | Obtains the line height in a typography object. This function must be called after [OH_Drawing_TypographyLayout](_drawing.md#oh_drawing_typographylayout) is called. | +| double [OH_Drawing_TypographyGetLineWidth](_drawing.md#oh_drawing_typographygetlinewidth) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*, int) | Obtains the line width in a typography object. This function must be called after [OH_Drawing_TypographyLayout](_drawing.md#oh_drawing_typographylayout) is called. | | void [OH_Drawing_SetTypographyTextSplitRatio](_drawing.md#oh_drawing_settypographytextsplitratio) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*style, float textSplitRatio) | Sets the text split ratio. | | bool [OH_Drawing_TypographyIsLineUnlimited](_drawing.md#oh_drawing_typographyislineunlimited) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*style) | Checks whether the maximum number of lines is limited. | -| bool [OH_Drawing_TypographyIsEllipsized](_drawing.md#oh_drawing_typographyisellipsized) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*style) | Checks whether the text has an ellipsis. | -| void [OH_Drawing_SetTypographyTextLocale](_drawing.md#oh_drawing_settypographytextlocale) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*style, const char \*locale) | Sets the locale for a typography style. | +| bool [OH_Drawing_TypographyIsEllipsized](_drawing.md#oh_drawing_typographyisellipsized) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*style) | Checks whether an ellipsis is configured for a typography style. | +| void [OH_Drawing_SetTypographyTextLocale](_drawing.md#oh_drawing_settypographytextlocale) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*style, const char \*locale) | Sets the locale for a typography style.| | bool [OH_Drawing_TextStyleGetFontMetrics](_drawing.md#oh_drawing_textstylegetfontmetrics) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*, [OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, [OH_Drawing_Font_Metrics](_o_h___drawing___font___metrics.md) \*) | Obtains the font metrics of a text style. | | void [OH_Drawing_SetTypographyTextStyle](_drawing.md#oh_drawing_settypographytextstyle) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*, [OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*) | Sets a text style. | | [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) \* [OH_Drawing_CreateFontDescriptor](_drawing.md#oh_drawing_createfontdescriptor) (void) | Creates an **OH_Drawing_FontDescriptor** object to describe the detailed information about a system font. | | void [OH_Drawing_DestroyFontDescriptor](_drawing.md#oh_drawing_destroyfontdescriptor) ([OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) \*) | Destroys an **OH_Drawing_FontDescriptor** object and reclaims the memory occupied by the object. | | [OH_Drawing_FontParser](_drawing.md#oh_drawing_fontparser) \* [OH_Drawing_CreateFontParser](_drawing.md#oh_drawing_createfontparser) (void) | Creates an **OH_Drawing_FontParser** object to parse a system font. | | void [OH_Drawing_DestroyFontParser](_drawing.md#oh_drawing_destroyfontparser) ([OH_Drawing_FontParser](_drawing.md#oh_drawing_fontparser) \*) | Destroys an **OH_Drawing_FontParser** object and reclaims the memory occupied by the object. | -| char \*\* [OH_Drawing_FontParserGetSystemFontList](_drawing.md#oh_drawing_fontparsergetsystemfontlist) ([OH_Drawing_FontParser](_drawing.md#oh_drawing_fontparser) \*, size_t \*) | Obtains the list of system fonts. This function can be used only on 2-in-1 devices. | +| char \*\* [OH_Drawing_FontParserGetSystemFontList](_drawing.md#oh_drawing_fontparsergetsystemfontlist) ([OH_Drawing_FontParser](_drawing.md#oh_drawing_fontparser) \*, size_t \*) | Obtains the list of system fonts. This function can be used only on 2-in-1 devices and phones. | | void [OH_Drawing_DestroySystemFontList](_drawing.md#oh_drawing_destroysystemfontlist) (char \*\*, size_t) | Reclaims the memory occupied by the system font list. | | [OH_Drawing_FontDescriptor](_o_h___drawing___font_descriptor.md) \* [OH_Drawing_FontParserGetFontByName](_drawing.md#oh_drawing_fontparsergetfontbyname) ([OH_Drawing_FontParser](_drawing.md#oh_drawing_fontparser) \*, const char \*) | Obtains the descriptor of a system font based on the font name. | -| [OH_Drawing_LineMetrics](_o_h___drawing___line_metrics.md) \* [OH_Drawing_TypographyGetLineMetrics](_drawing.md#oh_drawing_typographygetlinemetrics) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*) | Obtains the line metrics. | +| [OH_Drawing_LineMetrics](_o_h___drawing___line_metrics.md) \* [OH_Drawing_TypographyGetLineMetrics](_drawing.md#oh_drawing_typographygetlinemetrics) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*) | Obtains the line metrics in a typography object. This function must be called after [OH_Drawing_TypographyLayout](_drawing.md#oh_drawing_typographylayout) is called. When [OH_Drawing_LineMetrics](_o_h___drawing___line_metrics.md) is no longer required, call [OH_Drawing_DestroyLineMetrics](_drawing.md#oh_drawing_destroylinemetrics) to release the pointer to the object. | | size_t [OH_Drawing_LineMetricsGetSize](_drawing.md#oh_drawing_linemetricsgetsize) ([OH_Drawing_LineMetrics](_o_h___drawing___line_metrics.md) \*) | Obtains the number of lines. | | void [OH_Drawing_DestroyLineMetrics](_drawing.md#oh_drawing_destroylinemetrics) ([OH_Drawing_LineMetrics](_o_h___drawing___line_metrics.md) \*) | Destroys an **OH_Drawing_LineMetrics** object and reclaims the memory occupied by the object. | -| bool [OH_Drawing_TypographyGetLineMetricsAt](_drawing.md#oh_drawing_typographygetlinemetricsat) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*, int, [OH_Drawing_LineMetrics](_o_h___drawing___line_metrics.md) \*) | Obtains the metrics of a given line. | -| bool [OH_Drawing_TypographyGetLineInfo](_drawing.md#oh_drawing_typographygetlineinfo) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*, int, bool, bool, [OH_Drawing_LineMetrics](_o_h___drawing___line_metrics.md) \*) | Obtains the metrics of a given line or the metrics of the first character in a given line. | -| void [OH_Drawing_SetTypographyTextFontWeight](_drawing.md#oh_drawing_settypographytextfontweight) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*, int) | Sets the font weight for text. Currently, only the default system font supports font weight adjustment. For other fonts, if the weight is less than semi-bold, there is no variation in stroke thickness. If the weight is greater than or equal to semi-bold, it might result in a fake bold effect. | -| void [OH_Drawing_SetTypographyTextFontStyle](_drawing.md#oh_drawing_settypographytextfontstyle) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*, int) | Sets the font style for text. | +| bool [OH_Drawing_TypographyGetLineMetricsAt](_drawing.md#oh_drawing_typographygetlinemetricsat) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*, int, [OH_Drawing_LineMetrics](_o_h___drawing___line_metrics.md) \*) | Obtains the metrics of a given line in a typography object. For details, see [OH_Drawing_LineMetrics](_o_h___drawing___line_metrics.md). This function must be called after [OH_Drawing_TypographyLayout](_drawing.md#oh_drawing_typographylayout) is called. | +| bool [OH_Drawing_TypographyGetLineInfo](_drawing.md#oh_drawing_typographygetlineinfo) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*, int, bool, bool, [OH_Drawing_LineMetrics](_o_h___drawing___line_metrics.md) \*) | Obtains the metrics of a given line or the metrics of the first character in a given line in a typography object. This function must be called after [OH_Drawing_TypographyLayout](_drawing.md#oh_drawing_typographylayout) is called. | +| void [OH_Drawing_SetTypographyTextFontWeight](_drawing.md#oh_drawing_settypographytextfontweight) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*, int) | Sets the default font weight for a typography style. Currently, only the default system font supports font weight adjustment. For other fonts, if the weight is less than semi-bold, there is no variation in stroke thickness. If the weight is greater than or equal to semi-bold, it might result in a fake bold effect.| +| void [OH_Drawing_SetTypographyTextFontStyle](_drawing.md#oh_drawing_settypographytextfontstyle) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*, int) | Sets the default font style for a typography style. | | void [OH_Drawing_SetTypographyTextFontFamily](_drawing.md#oh_drawing_settypographytextfontfamily) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*, const char \*) | Sets the font family name for text. | | void [OH_Drawing_SetTypographyTextFontSize](_drawing.md#oh_drawing_settypographytextfontsize) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*, double) | Sets the font size for text. | | void [OH_Drawing_SetTypographyTextFontHeight](_drawing.md#oh_drawing_settypographytextfontheight) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*, double) | Sets the font height for text. | | void [OH_Drawing_SetTypographyTextHalfLeading](_drawing.md#oh_drawing_settypographytexthalfleading) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*, bool) | Sets whether to enable half leading for text. | | void [OH_Drawing_SetTypographyTextUseLineStyle](_drawing.md#oh_drawing_settypographytextuselinestyle) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*, bool) | Sets whether to enable the text line style. | -| void [OH_Drawing_SetTypographyTextLineStyleFontWeight](_drawing.md#oh_drawing_settypographytextlinestylefontweight) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*, int) | Sets the font weight for a text line style. Currently, only the default system font supports font weight adjustment. For other fonts, if the weight is less than semi-bold, there is no variation in stroke thickness. If the weight is greater than or equal to semi-bold, it might result in a fake bold effect. | -| void [OH_Drawing_SetTypographyTextLineStyleFontStyle](_drawing.md#oh_drawing_settypographytextlinestylefontstyle) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*, int) | Sets the font style for a text line style. | +| void [OH_Drawing_SetTypographyTextLineStyleFontWeight](_drawing.md#oh_drawing_settypographytextlinestylefontweight) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*, int) | Sets the text font weight of the strut style in a typography style. Currently, only the default system font supports font weight adjustment. For other fonts, if the weight is less than semi-bold, there is no variation in stroke thickness. If the weight is greater than or equal to semi-bold, it might result in a fake bold effect.| +| void [OH_Drawing_SetTypographyTextLineStyleFontStyle](_drawing.md#oh_drawing_settypographytextlinestylefontstyle) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*, int) | Sets the font style of the strut style in a typography style.| | void [OH_Drawing_SetTypographyTextLineStyleFontFamilies](_drawing.md#oh_drawing_settypographytextlinestylefontfamilies) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*, int, const char \*fontFamilies[]) | Sets the font families for a text line style. | | void [OH_Drawing_SetTypographyTextLineStyleFontSize](_drawing.md#oh_drawing_settypographytextlinestylefontsize) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*, double) | Sets the font size for a text line style. | | void [OH_Drawing_SetTypographyTextLineStyleFontHeight](_drawing.md#oh_drawing_settypographytextlinestylefontheight) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*, double) | Sets the font height for a text line style. | -| void [OH_Drawing_SetTypographyTextLineStyleHalfLeading](_drawing.md#oh_drawing_settypographytextlinestylehalfleading) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*, bool) | Sets whether to enable half leading for a text line style. | +| void [OH_Drawing_SetTypographyTextLineStyleHalfLeading](_drawing.md#oh_drawing_settypographytextlinestylehalfleading) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*, bool) | Sets whether to enable half leading for the strut style in a typography style.| | void [OH_Drawing_SetTypographyTextLineStyleSpacingScale](_drawing.md#oh_drawing_settypographytextlinestylespacingscale) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*, double) | Sets the spacing scale factor for a text line style. | | void [OH_Drawing_SetTypographyTextLineStyleOnly](_drawing.md#oh_drawing_settypographytextlinestyleonly) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*, bool) | Sets whether to enable the text line style only. | -| [OH_Drawing_TextShadow](_drawing.md#oh_drawing_textshadow) \* [OH_Drawing_CreateTextShadow](_drawing.md#oh_drawing_createtextshadow) (void) | Creates a pointer to an **OH_Drawing_TextShadow** object. | +| [OH_Drawing_TextShadow](_drawing.md#oh_drawing_textshadow) \* [OH_Drawing_CreateTextShadow](_drawing.md#oh_drawing_createtextshadow) (void) | Creates a pointer to an **OH_Drawing_TextShadow** object. When [OH_Drawing_TextShadow](_drawing.md#oh_drawing_textshadow) is no longer required, call [OH_Drawing_DestroyTextShadow](_drawing.md#oh_drawing_destroytextshadow) to release the pointer to the object. | | void [OH_Drawing_DestroyTextShadow](_drawing.md#oh_drawing_destroytextshadow) ([OH_Drawing_TextShadow](_drawing.md#oh_drawing_textshadow) \*) | Destroys an **OH_Drawing_TextShadow** object and reclaims the memory occupied by the object. | -| [OH_Drawing_TextShadow](_drawing.md#oh_drawing_textshadow) \* [OH_Drawing_TextStyleGetShadows](_drawing.md#oh_drawing_textstylegetshadows) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*) | Obtains a text shadow container. | +| [OH_Drawing_TextShadow](_drawing.md#oh_drawing_textshadow) \* [OH_Drawing_TextStyleGetShadows](_drawing.md#oh_drawing_textstylegetshadows) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*) | Obtains a text shadow container. When [OH_Drawing_TextShadow](_drawing.md#oh_drawing_textshadow) is no longer required, call [OH_Drawing_DestroyTextShadows](_drawing.md#oh_drawing_destroytextshadows) to release the pointer to the object. | | int [OH_Drawing_TextStyleGetShadowCount](_drawing.md#oh_drawing_textstylegetshadowcount) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*) | Obtains the size of a text shadow container. | | void [OH_Drawing_TextStyleAddShadow](_drawing.md#oh_drawing_textstyleaddshadow) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, const [OH_Drawing_TextShadow](_drawing.md#oh_drawing_textshadow) \*) | Adds a shadow to a text shadow container. | | void [OH_Drawing_TextStyleClearShadows](_drawing.md#oh_drawing_textstyleclearshadows) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*) | Clears all shadows in a text shadow container. | | [OH_Drawing_TextShadow](_drawing.md#oh_drawing_textshadow) \* [OH_Drawing_TextStyleGetShadowWithIndex](_drawing.md#oh_drawing_textstylegetshadowwithindex) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, int) | Obtains a shadow with a given index in a text shadow container. | | void [OH_Drawing_TypographySetIndents](_drawing.md#oh_drawing_typographysetindents) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*, int, const float indents[]) | Sets indents for typography. If this function is not called, texts will have no indentation applied. | -| float [OH_Drawing_TypographyGetIndentsWithIndex](_drawing.md#oh_drawing_typographygetindentswithindex) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*, int) | Obtains indents with a given index. | -| [OH_Drawing_Range](_drawing.md#oh_drawing_range) \* [OH_Drawing_TypographyGetLineTextRange](_drawing.md#oh_drawing_typographygetlinetextrange) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*, int, bool) | Obtains the line bounds. | +| float [OH_Drawing_TypographyGetIndentsWithIndex](_drawing.md#oh_drawing_typographygetindentswithindex) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*, int) | Obtains indents with a given index in a typography object. The line index starts from 0. | +| [OH_Drawing_Range](_drawing.md#oh_drawing_range) \* [OH_Drawing_TypographyGetLineTextRange](_drawing.md#oh_drawing_typographygetlinetextrange) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*, int, bool) | Obtains the line bounds in a typography object. This function must be called after [OH_Drawing_TypographyLayout](_drawing.md#oh_drawing_typographylayout) is called. This function can only be used to obtain the bounds of existing lines. That is, the line index must start from 0, and the maximum index is [OH_Drawing_TypographyGetLineCount](_drawing.md#oh_drawing_typographygetlinecount) - 1. | | void [OH_Drawing_DestroyTextShadows](_drawing.md#oh_drawing_destroytextshadows) ([OH_Drawing_TextShadow](_drawing.md#oh_drawing_textshadow) \*) | Reclaims the memory occupied by the vector consisting of the **OH_Drawing_TextShadow** objects. | | [OH_Drawing_FontConfigInfo](_o_h___drawing___font_config_info.md) \* [OH_Drawing_GetSystemFontConfigInfo](_drawing.md#oh_drawing_getsystemfontconfiginfo) ([OH_Drawing_FontConfigInfoErrorCode](_drawing.md#oh_drawing_fontconfiginfoerrorcode) \*) | Obtains the system font configuration. | | void [OH_Drawing_DestroySystemFontConfigInfo](_drawing.md#oh_drawing_destroysystemfontconfiginfo) ([OH_Drawing_FontConfigInfo](_o_h___drawing___font_config_info.md) \*) | Reclaims the memory occupied by the system font configuration. | | void [OH_Drawing_SetTextStyleFontStyleStruct](_drawing.md#oh_drawing_settextstylefontstylestruct) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*drawingTextStyle, [OH_Drawing_FontStyleStruct](_o_h___drawing___font_style_struct.md) fontStyle) | Sets the font style, including the font weight, width, and slant, for a text style. | -| [OH_Drawing_FontStyleStruct](_o_h___drawing___font_style_struct.md OH_Drawing_TextStyleGetFontStyleStruct](_drawing.md#oh_drawing_textstylegetfontstylestruct) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*drawingTextStyle) | Obtains the font style, including the font weight, width, and slant, of a text style. | -| void [OH_Drawing_SetTypographyStyleFontStyleStruct](_drawing.md#oh_drawing_settypographystylefontstylestruct) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*drawingStyle, [OH_Drawing_FontStyleStruct](_o_h___drawing___font_style_struct.md) fontStyle) | Sets the font style, including the font weight, width, and slant, for a typography style. | -| [OH_Drawing_FontStyleStruct](_o_h___drawing___font_style_struct.md) [OH_Drawing_TypographyStyleGetFontStyleStruct](_drawing.md#oh_drawing_typographystylegetfontstylestruct) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*drawingStyle) | Obtains the font style, including the font weight, width, and slant, of a typography style. | +| [OH_Drawing_FontStyleStruct](_o_h___drawing___font_style_struct.md) [OH_Drawing_TextStyleGetFontStyleStruct](_drawing.md#oh_drawing_textstylegetfontstylestruct) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*drawingTextStyle) | Obtains the font style, including the font weight, width, and slant, of a text style. | +| void [OH_Drawing_SetTypographyStyleFontStyleStruct](_drawing.md#oh_drawing_settypographystylefontstylestruct) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*drawingStyle, [OH_Drawing_FontStyleStruct](_o_h___drawing___font_style_struct.md) fontStyle) | Sets the font style, including the font weight, width, and slant, for the default text style in a typography style.| +| [OH_Drawing_FontStyleStruct](_o_h___drawing___font_style_struct.md) [OH_Drawing_TypographyStyleGetFontStyleStruct](_drawing.md#oh_drawing_typographystylegetfontstylestruct) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*drawingStyle) | Obtains the font style, including the font weight, width, and slant, of the default text style in a typography style. | | void [OH_Drawing_TextStyleSetBackgroundRect](_drawing.md#oh_drawing_textstylesetbackgroundrect) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, const [OH_Drawing_RectStyle_Info](_o_h___drawing___rect_style___info.md) \*, int styleId) | Sets a background rectangle and style ID for a text style. The style ID is valid only when the background box is a rounded rectangle. | | void [OH_Drawing_TypographyHandlerAddSymbol](_drawing.md#oh_drawing_typographyhandleraddsymbol) ([OH_Drawing_TypographyCreate](_drawing.md#oh_drawing_typographycreate) \*, uint32_t symbol) | Adds the symbol to use in the typography creation process. | -| void [OH_Drawing_TextStyleAddFontFeature](_drawing.md#oh_drawing_textstyleaddfontfeature) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, const char \*tag, int value) | Adds a font feature for a text style. | +| void [OH_Drawing_TextStyleAddFontFeature](_drawing.md#oh_drawing_textstyleaddfontfeature) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, const char \*tag, int value) | Adds a font feature for a text style.| | void [OH_Drawing_TextStyleAddFontVariation](_drawing.md#oh_drawing_textstyleaddfontvariation) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, const char \*, const float) | Adds a font variation. This function takes effect only when the corresponding font file (.ttf file) supports variable adjustment. Otherwise, calling this function does not take effect. | -| [OH_Drawing_FontFeature](_o_h___drawing___font_feature.md) \* [OH_Drawing_TextStyleGetFontFeatures](_drawing.md#oh_drawing_textstylegetfontfeatures) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*) | Obtains all the contents in a font feature map container. | +| [OH_Drawing_FontFeature](_o_h___drawing___font_feature.md) \* [OH_Drawing_TextStyleGetFontFeatures](_drawing.md#oh_drawing_textstylegetfontfeatures) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*) | Obtains all the contents in a font feature map container of a text style.| | void [OH_Drawing_TextStyleDestroyFontFeatures](_drawing.md#oh_drawing_textstyledestroyfontfeatures) ([OH_Drawing_FontFeature](_o_h___drawing___font_feature.md) \*, size_t fontFeatureSize) | Reclaims the memory occupied by the struct array that holds all the font features. | -| size_t [OH_Drawing_TextStyleGetFontFeatureSize](_drawing.md#oh_drawing_textstylegetfontfeaturesize) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*) | Obtains the size of a font feature map container. | -| void [OH_Drawing_TextStyleClearFontFeature](_drawing.md#oh_drawing_textstyleclearfontfeature) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*) | Clears all the contents in a font feature map container. | -| double [OH_Drawing_TextStyleGetBaselineShift](_drawing.md#oh_drawing_textstylegetbaselineshift) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*) | Obtains the baseline drift of a text style. | -| void [OH_Drawing_TextStyleSetBaselineShift](_drawing.md#oh_drawing_textstylesetbaselineshift) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, double lineShift) | Sets a baseline drift for a text style. | +| size_t [OH_Drawing_TextStyleGetFontFeatureSize](_drawing.md#oh_drawing_textstylegetfontfeaturesize) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*) | Obtains the size of a font feature map container in a text style.| +| void [OH_Drawing_TextStyleClearFontFeature](_drawing.md#oh_drawing_textstyleclearfontfeature) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*) | Clears all the contents in a font feature map container of a text style.| +| double [OH_Drawing_TextStyleGetBaselineShift](_drawing.md#oh_drawing_textstylegetbaselineshift) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*) | Obtains the baseline drift of a text style.| +| void [OH_Drawing_TextStyleSetBaselineShift](_drawing.md#oh_drawing_textstylesetbaselineshift) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, double lineShift) | Sets a baseline drift for a text style.| | void [OH_Drawing_TypographyTextSetHeightBehavior](_drawing.md#oh_drawing_typographytextsetheightbehavior) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*, [OH_Drawing_TextHeightBehavior](_drawing.md#oh_drawing_textheightbehavior) heightMode) | Sets a text height modifier pattern. | | [OH_Drawing_TextHeightBehavior](_drawing.md#oh_drawing_textheightbehavior) [OH_Drawing_TypographyTextGetHeightBehavior](_drawing.md#oh_drawing_typographytextgetheightbehavior) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*) | Obtains the text height modifier pattern. | -| [OH_Drawing_Font_Metrics](_o_h___drawing___font___metrics.md) \* [OH_Drawing_TypographyGetLineFontMetrics](_drawing.md#oh_drawing_typographygetlinefontmetrics) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*, size_t lineNumber, size_t \*fontMetricsSize) | Obtains all font metrics from a given line. | +| [OH_Drawing_Font_Metrics](_o_h___drawing___font___metrics.md) \* [OH_Drawing_TypographyGetLineFontMetrics](_drawing.md#oh_drawing_typographygetlinefontmetrics) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*, size_t lineNumber, size_t \*fontMetricsSize) | Obtains all font metrics from a given line in a typography object. This function must be called after [OH_Drawing_TypographyLayout](_drawing.md#oh_drawing_typographylayout) is called. Otherwise, a null pointer is returned. When [OH_Drawing_Font_Metrics](_o_h___drawing___font___metrics.md) is no longer required, call [OH_Drawing_TypographyDestroyLineFontMetrics](_drawing.md#oh_drawing_typographydestroylinefontmetrics) to release the pointer to the object.| | void [OH_Drawing_TypographyDestroyLineFontMetrics](_drawing.md#oh_drawing_typographydestroylinefontmetrics) ([OH_Drawing_Font_Metrics](_o_h___drawing___font___metrics.md) \*) | Reclaims the memory occupied by the struct array that holds all the font metrics of a given line. | -| bool [OH_Drawing_TextStyleIsEqual](_drawing.md#oh_drawing_textstyleisequal) (const [OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*style, const [OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*comparedStyle) | Checks whether two text styles are equal. | +| bool [OH_Drawing_TextStyleIsEqual](_drawing.md#oh_drawing_textstyleisequal) (const [OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*style, const [OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*comparedStyle) | Checks whether two text styles are equal. The word width property is not involved in the comparison. | | bool [OH_Drawing_TextStyleIsEqualByFont](_drawing.md#oh_drawing_textstyleisequalbyfont) (const [OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*style, const [OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*comparedStyle) | Checks whether the font style properties of two text styles are equal. | | bool [OH_Drawing_TextStyleIsAttributeMatched](_drawing.md#oh_drawing_textstyleisattributematched) (const [OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*style, const [OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*comparedStyle, [OH_Drawing_TextStyleType](_drawing.md#oh_drawing_textstyletype) textStyleType) | Checks whether two text styles have the same text style type. | | void [OH_Drawing_TextStyleSetPlaceholder](_drawing.md#oh_drawing_textstylesetplaceholder) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*style) | Sets a placeholder for a text style. | | bool [OH_Drawing_TextStyleIsPlaceholder](_drawing.md#oh_drawing_textstyleisplaceholder) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*style) | Checks whether a placeholder is set for a text style. | | [OH_Drawing_TextAlign](_drawing.md#oh_drawing_textalign) [OH_Drawing_TypographyStyleGetEffectiveAlignment](_drawing.md#oh_drawing_typographystylegeteffectivealignment) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*style) | Obtains the text alignment mode. | -| bool [OH_Drawing_TypographyStyleIsHintEnabled](_drawing.md#oh_drawing_typographystyleishintenabled) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*style) | Checks whether font hinting is enabled. Font hinting is used to improve the readability and appearance of small-sized text when rendering it. | +| bool [OH_Drawing_TypographyStyleIsHintEnabled](_drawing.md#oh_drawing_typographystyleishintenabled) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*style) | Checks whether font hinting is enabled for a typography style. Font hinting is used to improve the readability and appearance of small-sized text when rendering it. | | void [OH_Drawing_SetTypographyStyleTextStrutStyle](_drawing.md#oh_drawing_settypographystyletextstrutstyle) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*, [OH_Drawing_StrutStyle](_o_h___drawing___strut_style.md) \*) | Sets the strut style for a typography style. | | [OH_Drawing_StrutStyle](_o_h___drawing___strut_style.md) \* [OH_Drawing_TypographyStyleGetStrutStyle](_drawing.md#oh_drawing_typographystylegetstrutstyle) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*) | Obtains the strut style of a typography style. | | void [OH_Drawing_TypographyStyleDestroyStrutStyle](_drawing.md#oh_drawing_typographystyledestroystrutstyle) ([OH_Drawing_StrutStyle](_o_h___drawing___strut_style.md) \*) | Reclaims the memory occupied by a strut style. | | bool [OH_Drawing_TypographyStyleStrutStyleEquals](_drawing.md#oh_drawing_typographystylestrutstyleequals) ([OH_Drawing_StrutStyle](_o_h___drawing___strut_style.md) \*from, [OH_Drawing_StrutStyle](_o_h___drawing___strut_style.md) \*to) | Checks whether two strut styles are equal. | | void [OH_Drawing_TypographyStyleSetHintsEnabled](_drawing.md#oh_drawing_typographystylesethintsenabled) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*style, bool hintsEnabled) | Sets whether to enable font hinting for a typography style. Font hinting is used to improve the readability and appearance of small-sized text when rendering it. | | void [OH_Drawing_TypographyMarkDirty](_drawing.md#oh_drawing_typographymarkdirty) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*) | Marks a typography object as dirty data. This function is used to initialize the typography state. | -| int32_t [OH_Drawing_TypographyGetUnresolvedGlyphsCount](_drawing.md#oh_drawing_typographygetunresolvedglyphscount) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*) | Obtains the number of unresolved glyphs in a typography object. | +| int32_t [OH_Drawing_TypographyGetUnresolvedGlyphsCount](_drawing.md#oh_drawing_typographygetunresolvedglyphscount) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*) | Obtains the number of unresolved glyphs in a typography object. This function can be called only after [OH_Drawing_TypographyLayout](_drawing.md#oh_drawing_typographylayout) is called and applied. | | void [OH_Drawing_TypographyUpdateFontSize](_drawing.md#oh_drawing_typographyupdatefontsize) ([OH_Drawing_Typography](_drawing.md#oh_drawing_typography) \*, size_t from, size_t to, float fontSize) | Updates the font size in a typography object. | | bool [OH_Drawing_TypographyTextGetLineStyle](_drawing.md#oh_drawing_typographytextgetlinestyle) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*) | Checks whether the text line style is enabled for a typography style. | -| [OH_Drawing_FontWeight](_drawing.md#oh_drawing_fontweight) [OH_Drawing_TypographyTextlineStyleGetFontWeight](_drawing.md#oh_drawing_typographytextlinestylegetfontweight) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*) | Obtains the font weight of a text line style. | -| [OH_Drawing_FontStyle](_drawing.md#oh_drawing_fontstyle) [OH_Drawing_TypographyTextlineStyleGetFontStyle](_drawing.md#oh_drawing_typographytextlinestylegetfontstyle) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*) | Obtains the font style of a text line style. | -| char \*\* [OH_Drawing_TypographyTextlineStyleGetFontFamilies](_drawing.md#oh_drawing_typographytextlinestylegetfontfamilies) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*) | Obtains the font families of a text line style. | +| [OH_Drawing_FontWeight](_drawing.md#oh_drawing_fontweight) [OH_Drawing_TypographyTextlineStyleGetFontWeight](_drawing.md#oh_drawing_typographytextlinestylegetfontweight) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*) | Obtains the font weight of the strut style in a typography style. | +| [OH_Drawing_FontStyle](_drawing.md#oh_drawing_fontstyle) [OH_Drawing_TypographyTextlineStyleGetFontStyle](_drawing.md#oh_drawing_typographytextlinestylegetfontstyle) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*) | Obtains the font style of the strut style in the typography style. | +| char \*\* [OH_Drawing_TypographyTextlineStyleGetFontFamilies](_drawing.md#oh_drawing_typographytextlinestylegetfontfamilies) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*, size_t \*num) | Obtains the font families of a text line style. | | void [OH_Drawing_TypographyTextlineStyleDestroyFontFamilies](_drawing.md#oh_drawing_typographytextlinestyledestroyfontfamilies) (char \*\*fontFamilies, size_t fontFamiliesNum) | Reclaims the memory occupied by the font families. | | double [OH_Drawing_TypographyTextlineStyleGetFontSize](_drawing.md#oh_drawing_typographytextlinestylegetfontsize) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*) | Obtains the font size of a text line style. | | double [OH_Drawing_TypographyTextlineStyleGetHeightScale](_drawing.md#oh_drawing_typographytextlinestylegetheightscale) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*) | Obtains the height scale factor of a text line style. | @@ -255,24 +255,24 @@ The **drawing_text_typography.h** file declares the functions related to typogra | double [OH_Drawing_TypographyTextlineStyleGetSpacingScale](_drawing.md#oh_drawing_typographytextlinestylegetspacingscale) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*) | Obtains the spacing factor scale of a text line style. | | bool [OH_Drawing_TypographyTextlineGetStyleOnly](_drawing.md#oh_drawing_typographytextlinegetstyleonly) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*) | Checks whether only the text line style is enabled for a typography style. | | [OH_Drawing_TextAlign](_drawing.md#oh_drawing_textalign) [OH_Drawing_TypographyGetTextAlign](_drawing.md#oh_drawing_typographygettextalign) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*) | Obtains the text alignment mode. | -| [OH_Drawing_TextDirection](_drawing.md#oh_drawing_textdirection) [OH_Drawing_TypographyGetTextDirection](_drawing.md#oh_drawing_typographygettextdirection) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*) | Obtains the text direction. | +| [OH_Drawing_TextDirection](_drawing.md#oh_drawing_textdirection) [OH_Drawing_TypographyGetTextDirection](_drawing.md#oh_drawing_typographygettextdirection) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*) | Obtains the text direction of a typography style. | | size_t [OH_Drawing_TypographyGetTextMaxLines](_drawing.md#oh_drawing_typographygettextmaxlines) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*) | Obtains the maximum number of lines. | -| char \* [OH_Drawing_TypographyGetTextEllipsis](_drawing.md#oh_drawing_typographygettextellipsis) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*) | Obtains the text ellipsis content. | +| char \* [OH_Drawing_TypographyGetTextEllipsis](_drawing.md#oh_drawing_typographygettextellipsis) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*) | Obtains the text ellipsis content of a typography style.| | void [OH_Drawing_TypographyDestroyEllipsis](_drawing.md#oh_drawing_typographydestroyellipsis) (char \*ellipsis) | Reclaims the memory occupied by the text ellipsis names. | -| bool [OH_Drawing_TypographyStyleEquals](_drawing.md#oh_drawing_typographystyleequals) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*from, [OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*to) | Checks whether two typography styles are the same. | +| bool [OH_Drawing_TypographyStyleEquals](_drawing.md#oh_drawing_typographystyleequals) ([OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*from, [OH_Drawing_TypographyStyle](_drawing.md#oh_drawing_typographystyle) \*to) | Checks whether two typography styles are the same. The text height modifier mode [OH_Drawing_TextHeightBehavior](_drawing.md#oh_drawing_textheightbehavior) is not involved in the comparison. | | uint32_t [OH_Drawing_TextStyleGetColor](_drawing.md#oh_drawing_textstylegetcolor) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*) | Obtains the color of a text style. | | [OH_Drawing_TextDecorationStyle](_drawing.md#oh_drawing_textdecorationstyle) [OH_Drawing_TextStyleGetDecorationStyle](_drawing.md#oh_drawing_textstylegetdecorationstyle) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*) | Obtains the decoration style of a text style. | -| [OH_Drawing_FontWeight](_drawing.md#oh_drawing_fontweight) [OH_Drawing_TextStyleGetFontWeight](_drawing.md#oh_drawing_textstylegetfontweight) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*) | Obtains the font weight of a text style. | -| [OH_Drawing_FontStyle](_drawing.md#oh_drawing_fontstyle) [OH_Drawing_TextStyleGetFontStyle](_drawing.md#oh_drawing_textstylegetfontstyle) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*) | Obtains the font style of a text style. | -| [OH_Drawing_TextBaseline](_drawing.md#oh_drawing_textbaseline) [OH_Drawing_TextStyleGetBaseline](_drawing.md#oh_drawing_textstylegetbaseline) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*) | Obtains the baseline of a text style. | +| [OH_Drawing_FontWeight](_drawing.md#oh_drawing_fontweight) [OH_Drawing_TextStyleGetFontWeight](_drawing.md#oh_drawing_textstylegetfontweight) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*) | Obtains the font weight of a text style.| +| [OH_Drawing_FontStyle](_drawing.md#oh_drawing_fontstyle) [OH_Drawing_TextStyleGetFontStyle](_drawing.md#oh_drawing_textstylegetfontstyle) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*) | Obtains the font style of a text style.| +| [OH_Drawing_TextBaseline](_drawing.md#oh_drawing_textbaseline) [OH_Drawing_TextStyleGetBaseline](_drawing.md#oh_drawing_textstylegetbaseline) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*) | Obtains the baseline of a text style.| | char \*\* [OH_Drawing_TextStyleGetFontFamilies](_drawing.md#oh_drawing_textstylegetfontfamilies) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*, size_t \*num) | Obtains the font families of a text style. | -| void [OH_Drawing_TextStyleDestroyFontFamilies](_drawing.md#oh_drawing_textstyledestroyfontfamilies) (char \*\*fontFamilies, size_t num) | Reclaims the memory occupied by the font families. | -| double [OH_Drawing_TextStyleGetFontSize](_drawing.md#oh_drawing_textstylegetfontsize) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*) | Obtains the font size of a text style. | -| double [OH_Drawing_TextStyleGetLetterSpacing](_drawing.md#oh_drawing_textstylegetletterspacing) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*) | Obtains the letter spacing of a text style. | -| double [OH_Drawing_TextStyleGetWordSpacing](_drawing.md#oh_drawing_textstylegetwordspacing) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*) | Obtains the word spacing of a text style. | -| double [OH_Drawing_TextStyleGetFontHeight](_drawing.md#oh_drawing_textstylegetfontheight) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*) | Obtains the font height of a text style. | +| void [OH_Drawing_TextStyleDestroyFontFamilies](_drawing.md#oh_drawing_textstyledestroyfontfamilies) (char \*\*fontFamilies, size_t num) | Reclaims the memory occupied by the font families, where **num** specifies the number of font families.| +| double [OH_Drawing_TextStyleGetFontSize](_drawing.md#oh_drawing_textstylegetfontsize) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*) | Obtains the font size of a text style.| +| double [OH_Drawing_TextStyleGetLetterSpacing](_drawing.md#oh_drawing_textstylegetletterspacing) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*) | Obtains the letter spacing of a text style.| +| double [OH_Drawing_TextStyleGetWordSpacing](_drawing.md#oh_drawing_textstylegetwordspacing) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*) | Obtains the word spacing of a text style.| +| double [OH_Drawing_TextStyleGetFontHeight](_drawing.md#oh_drawing_textstylegetfontheight) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*) | Obtains the font height of a text style.| | bool [OH_Drawing_TextStyleGetHalfLeading](_drawing.md#oh_drawing_textstylegethalfleading) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*) | Checks whether half leading is enabled for a text style. | -| const char \* [OH_Drawing_TextStyleGetLocale](_drawing.md#oh_drawing_textstylegetlocale) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*) | Obtains the locale of a text style. | +| const char \* [OH_Drawing_TextStyleGetLocale](_drawing.md#oh_drawing_textstylegetlocale) ([OH_Drawing_TextStyle](_drawing.md#oh_drawing_textstyle) \*) | Obtains the locale of a text style.| | void [OH_Drawing_TypographyDestroyTextBox](_drawing.md#oh_drawing_typographydestroytextbox) ([OH_Drawing_TextBox](_drawing.md#oh_drawing_textbox) \*) | Releases the memory occupied by a text box. | | void [OH_Drawing_SetTextShadow](_drawing.md#oh_drawing_settextshadow) ([OH_Drawing_TextShadow](_drawing.md#oh_drawing_textshadow) \*shadow, uint32_t color, [OH_Drawing_Point](_drawing.md#oh_drawing_point) \*offset, double blurRadius) | Sets a text shadow. | | [OH_Drawing_TextTab](_drawing.md#oh_drawing_texttab) \* [OH_Drawing_CreateTextTab](_drawing.md#oh_drawing_createtexttab) ([OH_Drawing_TextAlign](_drawing.md#oh_drawing_textalign) alignment, float location) | Creates a text tab object. | diff --git a/en/application-dev/reference/apis-arkgraphics2d/drawing__types_8h.md b/en/application-dev/reference/apis-arkgraphics2d/drawing__types_8h.md index 55b23fe5942c24f3bdf902d70cf6e45949f88152..6f56526cd6c9bc0fb642bedd1a14550dfa288e52 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/drawing__types_8h.md +++ b/en/application-dev/reference/apis-arkgraphics2d/drawing__types_8h.md @@ -53,7 +53,7 @@ The **drawing_types.h** file declares the data types of the canvas, brush, pen, | typedef struct [OH_Drawing_ShaderEffect](_drawing.md#oh_drawing_shadereffect) [OH_Drawing_ShaderEffect](_drawing.md#oh_drawing_shadereffect) | Defines a struct for a shader effect, which is used to describe the source color of the drawn content.| | typedef struct [OH_Drawing_ShadowLayer](_drawing.md#oh_drawing_shadowlayer) [OH_Drawing_ShadowLayer](_drawing.md#oh_drawing_shadowlayer) | Defines a struct for a shadow, which is used to describe the shadow layer of the drawn content.| | typedef struct [OH_Drawing_Filter](_drawing.md#oh_drawing_filter) [OH_Drawing_Filter](_drawing.md#oh_drawing_filter) | Defines a struct for a filter, which consists of a color filter, mask filter, and image filter.| -| typedef struct [OH_Drawing_MaskFilter](_drawing.md#oh_drawing_maskfilter) [OH_Drawing_MaskFilter](_drawing.md#oh_drawing_maskfilter) | Defines a struct for a mask filter, which is used to convert a mask into a new one.| +| typedef struct [OH_Drawing_MaskFilter](_drawing.md#oh_drawing_maskfilter) [OH_Drawing_MaskFilter](_drawing.md#oh_drawing_maskfilter) | Defines a struct for a mask filter.| | typedef struct [OH_Drawing_ColorFilter](_drawing.md#oh_drawing_colorfilter) [OH_Drawing_ColorFilter](_drawing.md#oh_drawing_colorfilter) | Defines a struct for a color filter, which is used to convert a color into a new one.| | typedef struct [OH_Drawing_ImageFilter](_drawing.md#oh_drawing_imagefilter) [OH_Drawing_ImageFilter](_drawing.md#oh_drawing_imagefilter) | Defines a struct for an image filter, which is used to operate all color bits that make up image pixels.| | typedef struct [OH_Drawing_Font](_drawing.md#oh_drawing_font) [OH_Drawing_Font](_drawing.md#oh_drawing_font) | Defines a struct for a font.| @@ -68,7 +68,7 @@ The **drawing_types.h** file declares the data types of the canvas, brush, pen, | typedef struct [OH_Drawing_Surface](_drawing.md#oh_drawing_surface) [OH_Drawing_Surface](_drawing.md#oh_drawing_surface) | Defines a struct for a surface, which is used to manage the content drawn on the canvas.| | typedef enum [OH_Drawing_ColorFormat](_drawing.md#oh_drawing_colorformat) [OH_Drawing_ColorFormat](_drawing.md#oh_drawing_colorformat) | Defines an enum for storage formats of bitmap pixels.| | typedef enum [OH_Drawing_AlphaFormat](_drawing.md#oh_drawing_alphaformat) [OH_Drawing_AlphaFormat](_drawing.md#oh_drawing_alphaformat) | Defines an enum for alpha formats of bitmap pixels.| -| typedef enum [OH_Drawing_BlendMode](_drawing.md#oh_drawing_blendmode) [OH_Drawing_BlendMode](_drawing.md#oh_drawing_blendmode) | Defines an enum for blend modes. In blend mode, each operation generates a new color for the two colors (source color and target color). These operations are the same on the four channels (red, green, blue, and alpha). The operations for the alpha channel are used as examples.| +| typedef enum [OH_Drawing_BlendMode](_drawing.md#oh_drawing_blendmode) [OH_Drawing_BlendMode](_drawing.md#oh_drawing_blendmode) | Defines an enum for blend modes. In blend mode, each operation generates a new color for the two colors (source color and target color). These operations are the same for the red, green, and blue color channels (the alpha channel follows a different rule).| | typedef struct [OH_Drawing_Image_Info](_o_h___drawing___image___info.md) [OH_Drawing_Image_Info](_drawing.md#oh_drawing_image_info) | Defines a struct that describes the image information.| | typedef struct [OH_Drawing_RectStyle_Info](_o_h___drawing___rect_style___info.md) [OH_Drawing_RectStyle_Info](_drawing.md#oh_drawing_rectstyle_info) | Defines a struct for the style of a rectangle.| | typedef enum [OH_Drawing_TextEncoding](_drawing.md#oh_drawing_textencoding) [OH_Drawing_TextEncoding](_drawing.md#oh_drawing_textencoding) | Defines an enum for text encoding types.| @@ -83,5 +83,5 @@ The **drawing_types.h** file declares the data types of the canvas, brush, pen, | -------- | -------- | | [OH_Drawing_ColorFormat](_drawing.md#oh_drawing_colorformat) {
COLOR_FORMAT_UNKNOWN, COLOR_FORMAT_ALPHA_8, COLOR_FORMAT_RGB_565, COLOR_FORMAT_ARGB_4444,
COLOR_FORMAT_RGBA_8888, COLOR_FORMAT_BGRA_8888
} | Enumerates the storage formats of bitmap pixels.| | [OH_Drawing_AlphaFormat](_drawing.md#oh_drawing_alphaformat) { ALPHA_FORMAT_UNKNOWN, ALPHA_FORMAT_OPAQUE, ALPHA_FORMAT_PREMUL, ALPHA_FORMAT_UNPREMUL } | Enumerates the alpha formats of bitmap pixels.| -| [OH_Drawing_BlendMode](_drawing.md#oh_drawing_blendmode) {
BLEND_MODE_CLEAR, BLEND_MODE_SRC, BLEND_MODE_DST, BLEND_MODE_SRC_OVER,
BLEND_MODE_DST_OVER, BLEND_MODE_SRC_IN, BLEND_MODE_DST_IN, BLEND_MODE_SRC_OUT,
BLEND_MODE_DST_OUT, BLEND_MODE_SRC_ATOP, BLEND_MODE_DST_ATOP, BLEND_MODE_XOR,
BLEND_MODE_PLUS, BLEND_MODE_MODULATE, BLEND_MODE_SCREEN, BLEND_MODE_OVERLAY,
BLEND_MODE_DARKEN, BLEND_MODE_LIGHTEN, BLEND_MODE_COLOR_DODGE, BLEND_MODE_COLOR_BURN,
BLEND_MODE_HARD_LIGHT, BLEND_MODE_SOFT_LIGHT, BLEND_MODE_DIFFERENCE, BLEND_MODE_EXCLUSION,
BLEND_MODE_MULTIPLY, BLEND_MODE_HUE, BLEND_MODE_SATURATION, BLEND_MODE_COLOR,
BLEND_MODE_LUMINOSITY
} | Enumerates the blend modes. In blend mode, each operation generates a new color for the two colors (source color and target color). These operations are the same on the four channels (red, green, blue, and alpha). The operations for the alpha channel are used as examples.| +| [OH_Drawing_BlendMode](_drawing.md#oh_drawing_blendmode) {
BLEND_MODE_CLEAR, BLEND_MODE_SRC, BLEND_MODE_DST, BLEND_MODE_SRC_OVER,
BLEND_MODE_DST_OVER, BLEND_MODE_SRC_IN, BLEND_MODE_DST_IN, BLEND_MODE_SRC_OUT,
BLEND_MODE_DST_OUT, BLEND_MODE_SRC_ATOP, BLEND_MODE_DST_ATOP, BLEND_MODE_XOR,
BLEND_MODE_PLUS, BLEND_MODE_MODULATE, BLEND_MODE_SCREEN, BLEND_MODE_OVERLAY,
BLEND_MODE_DARKEN, BLEND_MODE_LIGHTEN, BLEND_MODE_COLOR_DODGE, BLEND_MODE_COLOR_BURN,
BLEND_MODE_HARD_LIGHT, BLEND_MODE_SOFT_LIGHT, BLEND_MODE_DIFFERENCE, BLEND_MODE_EXCLUSION,
BLEND_MODE_MULTIPLY, BLEND_MODE_HUE, BLEND_MODE_SATURATION, BLEND_MODE_COLOR,
BLEND_MODE_LUMINOSITY
} | Enumerates the blend modes. In blend mode, each operation generates a new color for the two colors (source color and target color). These operations are the same for the red, green, and blue color channels (the alpha channel follows a different rule).| | [OH_Drawing_TextEncoding](_drawing.md#oh_drawing_textencoding) { TEXT_ENCODING_UTF8, TEXT_ENCODING_UTF16, TEXT_ENCODING_UTF32, TEXT_ENCODING_GLYPH_ID } | Enumerates the text encoding types.| diff --git a/en/application-dev/reference/apis-arkgraphics2d/effect__filter_8h.md b/en/application-dev/reference/apis-arkgraphics2d/effect__filter_8h.md index 620c3c682710561fc6e47175d1397b41e24d98d0..1ddccbf9085d7a1ea4a77ad1b23c8bddc593563a 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/effect__filter_8h.md +++ b/en/application-dev/reference/apis-arkgraphics2d/effect__filter_8h.md @@ -23,12 +23,12 @@ The **effect_filter.h** file declares the APIs of an image effect filter. | Name| Description| | -------- | -------- | -| [EffectErrorCode](effect_kit.md#effecterrorcode) [OH_Filter_CreateEffect](effect_kit.md#oh_filter_createeffect) (OH_PixelmapNative \*pixelmap, [OH_Filter](_o_h___filter.md) \*\*filter) | Creates an **OH_Filter** object.| -| [EffectErrorCode](effect_kit.md#effecterrorcode) [OH_Filter_Release](effect_kit.md#oh_filter_release) ([OH_Filter](_o_h___filter.md) \*filter) | Releases an **OH_Filter** object.| -| [EffectErrorCode](effect_kit.md#effecterrorcode) [OH_Filter_Blur](effect_kit.md#oh_filter_blur) ([OH_Filter](_o_h___filter.md) \*filter, float radius) | Creates the frosted glass effect and adds it to a filter.| -| [EffectErrorCode](effect_kit.md#effecterrorcode) [OH_Filter_BlurWithTileMode](effect_kit.md#oh_filter_blurwithtilemode) ([OH_Filter](_o_h___filter.md) \*filter, float radius, [EffectTileMode](effect_kit.md#effecttilemode) tileMode) | Creates the frosted glass effect and adds it to a filter.| -| [EffectErrorCode](effect_kit.md#effecterrorcode) [OH_Filter_Brighten](effect_kit.md#oh_filter_brighten) ([OH_Filter](_o_h___filter.md) \*filter, float brightness) | Creates the brightening effect and adds it to a filter.| -| [EffectErrorCode](effect_kit.md#effecterrorcode) [OH_Filter_GrayScale](effect_kit.md#oh_filter_grayscale) ([OH_Filter](_o_h___filter.md) \*filter) | Creates the grayscale effect and adds it to a filter.| -| [EffectErrorCode](effect_kit.md#effecterrorcode) [OH_Filter_Invert](effect_kit.md#oh_filter_invert) ([OH_Filter](_o_h___filter.md) \*filter) | Creates the inverted color effect and adds it to a filter.| -| [EffectErrorCode](effect_kit.md#effecterrorcode) [OH_Filter_SetColorMatrix](effect_kit.md#oh_filter_setcolormatrix) ([OH_Filter](_o_h___filter.md) \*filter, [OH_Filter_ColorMatrix](_o_h___filter___color_matrix.md) \*matrix) | Creates a custom effect through a matrix and adds it to a filter.| -| [EffectErrorCode](effect_kit.md#effecterrorcode) [OH_Filter_GetEffectPixelMap](effect_kit.md#oh_filter_geteffectpixelmap) ([OH_Filter](_o_h___filter.md) \*filter, OH_PixelmapNative \*\*pixelmap) | Obtains the pixel map used to create a filter.| +| [EffectErrorCode](effect_kit.md#effecterrorcode) [OH_Filter_CreateEffect](effect_kit.md#oh_filter_createeffect) ([OH_PixelmapNative](effect_kit.md#oh_pixelmapnative) \*pixelmap, [OH_Filter](effect_kit.md#oh_filter) \*\*filter) | Creates an **OH_Filter** object.| +| [EffectErrorCode](effect_kit.md#effecterrorcode) [OH_Filter_Release](effect_kit.md#oh_filter_release) ([OH_Filter](effect_kit.md#oh_filter) \*filter) | Releases an **OH_Filter** object.| +| [EffectErrorCode](effect_kit.md#effecterrorcode) [OH_Filter_Blur](effect_kit.md#oh_filter_blur) ([OH_Filter](effect_kit.md#oh_filter) \*filter, float radius) | Creates the frosted glass effect and adds it to a filter.| +| [EffectErrorCode](effect_kit.md#effecterrorcode) [OH_Filter_BlurWithTileMode](effect_kit.md#oh_filter_blurwithtilemode) ([OH_Filter](effect_kit.md#oh_filter) \*filter, float radius, [EffectTileMode](effect_kit.md#effecttilemode) tileMode) | Creates the frosted glass effect and adds it to a filter.| +| [EffectErrorCode](effect_kit.md#effecterrorcode) [OH_Filter_Brighten](effect_kit.md#oh_filter_brighten) ([OH_Filter](effect_kit.md#oh_filter) \*filter, float brightness) | Creates the brightening effect and adds it to a filter.| +| [EffectErrorCode](effect_kit.md#effecterrorcode) [OH_Filter_GrayScale](effect_kit.md#oh_filter_grayscale) ([OH_Filter](effect_kit.md#oh_filter) \*filter) | Creates the grayscale effect and adds it to a filter.| +| [EffectErrorCode](effect_kit.md#effecterrorcode) [OH_Filter_Invert](effect_kit.md#oh_filter_invert) ([OH_Filter](effect_kit.md#oh_filter) \*filter) | Creates the inverted color effect and adds it to a filter.| +| [EffectErrorCode](effect_kit.md#effecterrorcode) [OH_Filter_SetColorMatrix](effect_kit.md#oh_filter_setcolormatrix) ([OH_Filter](effect_kit.md#oh_filter) \*filter, [OH_Filter_ColorMatrix](_o_h___filter___color_matrix.md) \*matrix) | Creates a custom effect through a matrix and adds it to a filter.| +| [EffectErrorCode](effect_kit.md#effecterrorcode) [OH_Filter_GetEffectPixelMap](effect_kit.md#oh_filter_geteffectpixelmap) ([OH_Filter](effect_kit.md#oh_filter) \*filter, [OH_PixelmapNative](effect_kit.md#oh_pixelmapnative) \*\*pixelmap) | Obtains the pixel map used to create a filter.| diff --git a/en/application-dev/reference/apis-arkgraphics2d/effect__types_8h.md b/en/application-dev/reference/apis-arkgraphics2d/effect__types_8h.md index 09407f143364250f6b296f26a8f65c004220d5f2..daeedc00b5663cb541387a9fd5b4266149b27435 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/effect__types_8h.md +++ b/en/application-dev/reference/apis-arkgraphics2d/effect__types_8h.md @@ -23,16 +23,15 @@ The **effect_types.h** file declares the data types of the image effect filter. | Name| Description| | -------- | -------- | -| struct [OH_Filter](_o_h___filter.md) | Describes a filter used to generate a filter pixel map.| -| struct [OH_Filter_ColorMatrix](_o_h___filter___color_matrix.md) | Describes a matrix used to create an effect filter.| +| struct  [OH_Filter_ColorMatrix](_o_h___filter___color_matrix.md) | Describes a matrix used to create an effect filter.| ### Types | Name| Description| | -------- | -------- | -| typedef struct [OH_Filter](_o_h___filter.md) [pixelMap](effect_kit.md#pixelmap) | Defines a struct for a filter used to generate a filter pixel map.| -| typedef enum [EffectErrorCode](effect_kit.md#effecterrorcode) [EffectErrorCode](effect_kit.md#effecterrorcode) | Defines an enum for the status codes that may be used by the effect filter.| +| typedef struct [OH_Filter](effect_kit.md#oh_filter) [OH_Filter](effect_kit.md#oh_filter) | Defines a struct for a filter used to generate a filter PixelMap.| +| typedef struct [OH_PixelmapNative](effect_kit.md#oh_pixelmapnative) [OH_PixelmapNative](effect_kit.md#oh_pixelmapnative) | Defines a struct for the PixelMap.| ### Enums diff --git a/en/application-dev/reference/apis-arkgraphics2d/effect_kit.md b/en/application-dev/reference/apis-arkgraphics2d/effect_kit.md index 8ba304b01bc8e6b8c9d19267f02e37e441ae897e..2bc47849ce6a637141697690366fba882fb6219c 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/effect_kit.md +++ b/en/application-dev/reference/apis-arkgraphics2d/effect_kit.md @@ -5,6 +5,8 @@ The EffectKit module provides the basic image processing capabilities, including brightness adjustment, blurring, and grayscale adjustment. +**System capability**: SystemCapability.Multimedia.Image.Core + **Since**: 12 @@ -23,7 +25,6 @@ The EffectKit module provides the basic image processing capabilities, including | Name| Description| | -------- | -------- | -| struct [OH_Filter](_o_h___filter.md) | Describes a filter used to generate a filter pixel map.| | struct [OH_Filter_ColorMatrix](_o_h___filter___color_matrix.md) | Describes a matrix used to create an effect filter.| @@ -31,8 +32,8 @@ The EffectKit module provides the basic image processing capabilities, including | Name| Description| | -------- | -------- | -| typedef struct [OH_Filter](_o_h___filter.md) [pixelMap](#pixelmap) | Defines a struct for a filter used to generate a filter pixel map.| -| typedef enum [EffectErrorCode](#effecterrorcode) [EffectErrorCode](#effecterrorcode) | Defines an enum for the status codes that may be used by the effect filter.| +| typedef struct [OH_Filter](#oh_filter) [OH_Filter](#oh_filter) | Defines a struct for a filter used to generate a filter PixelMap.| +| typedef struct [OH_PixelmapNative](#oh_pixelmapnative) [OH_PixelmapNative](#oh_pixelmapnative) | Defines a struct for a PixelMap.| ### Enums @@ -42,48 +43,49 @@ The EffectKit module provides the basic image processing capabilities, including | [EffectErrorCode](#effecterrorcode) { EFFECT_SUCCESS = 0, EFFECT_BAD_PARAMETER = 401, EFFECT_UNSUPPORTED_OPERATION = 7600201, EFFECT_UNKNOWN_ERROR = 7600901 } | Enumerates the status codes that may be used by the effect filter.| | [EffectTileMode](#effecttilemode) { CLAMP = 0, REPEAT, MIRROR, DECAL } | Enumerates the tile modes of the shader effect.| + ### Functions | Name| Description| | -------- | -------- | -| [EffectErrorCode](#effecterrorcode) [OH_Filter_CreateEffect](#oh_filter_createeffect) (OH_PixelmapNative \*pixelmap, [OH_Filter](_o_h___filter.md) \*\*filter) | Creates an **OH_Filter** object.| -| [EffectErrorCode](#effecterrorcode) [OH_Filter_Release](#oh_filter_release) ([OH_Filter](_o_h___filter.md) \*filter) | Releases an **OH_Filter** object.| -| [EffectErrorCode](#effecterrorcode) [OH_Filter_Blur](#oh_filter_blur) ([OH_Filter](_o_h___filter.md) \*filter, float radius) | Creates the frosted glass effect and adds it to a filter.| -| [EffectErrorCode](#effecterrorcode) [OH_Filter_BlurWithTileMode](#oh_filter_blurwithtilemode) ([OH_Filter](_o_h___filter.md) \*filter, float radius, [EffectTileMode](#effecttilemode) tileMode) | Creates the frosted glass effect and adds it to a filter.| -| [EffectErrorCode](#effecterrorcode) [OH_Filter_Brighten](#oh_filter_brighten) ([OH_Filter](_o_h___filter.md) \*filter, float brightness) | Creates the brightening effect and adds it to a filter.| -| [EffectErrorCode](#effecterrorcode) [OH_Filter_GrayScale](#oh_filter_grayscale) ([OH_Filter](_o_h___filter.md) \*filter) | Creates the grayscale effect and adds it to a filter.| -| [EffectErrorCode](#effecterrorcode) [OH_Filter_Invert](#oh_filter_invert) ([OH_Filter](_o_h___filter.md) \*filter) | Creates the inverted color effect and adds it to a filter.| -| [EffectErrorCode](#effecterrorcode) [OH_Filter_SetColorMatrix](#oh_filter_setcolormatrix) ([OH_Filter](_o_h___filter.md) \*filter, [OH_Filter_ColorMatrix](_o_h___filter___color_matrix.md) \*matrix) | Creates a custom effect through a matrix and adds it to a filter.| -| [EffectErrorCode](#effecterrorcode) [OH_Filter_GetEffectPixelMap](#oh_filter_geteffectpixelmap) ([OH_Filter](_o_h___filter.md) \*filter, OH_PixelmapNative \*\*pixelmap) | Obtains the pixel map used to create a filter.| +| [EffectErrorCode](#effecterrorcode) [OH_Filter_CreateEffect](#oh_filter_createeffect) ([OH_PixelmapNative](#oh_pixelmapnative) \*pixelmap, [OH_Filter](#oh_filter) \*\*filter) | Creates an **OH_Filter** object.| +| [EffectErrorCode](#effecterrorcode) [OH_Filter_Release](#oh_filter_release) ([OH_Filter](#oh_filter) \*filter) | Releases an **OH_Filter** object.| +| [EffectErrorCode](#effecterrorcode) [OH_Filter_Blur](#oh_filter_blur) ([OH_Filter](#oh_filter) \*filter, float radius) | Creates the frosted glass effect and adds it to a filter.| +| [EffectErrorCode](#effecterrorcode) [OH_Filter_BlurWithTileMode](#oh_filter_blurwithtilemode) ([OH_Filter](#oh_filter) \*filter, float radius, [EffectTileMode](#effecttilemode) tileMode) | Creates the frosted glass effect and adds it to a filter.| +| [EffectErrorCode](#effecterrorcode) [OH_Filter_Brighten](#oh_filter_brighten) ([OH_Filter](#oh_filter) \*filter, float brightness) | Creates the brightening effect and adds it to a filter.| +| [EffectErrorCode](#effecterrorcode) [OH_Filter_GrayScale](#oh_filter_grayscale) ([OH_Filter](#oh_filter) \*filter) | Creates the grayscale effect and adds it to a filter.| +| [EffectErrorCode](#effecterrorcode) [OH_Filter_Invert](#oh_filter_invert) ([OH_Filter](#oh_filter) \*filter) | Creates the inverted color effect and adds it to a filter.| +| [EffectErrorCode](#effecterrorcode) [OH_Filter_SetColorMatrix](#oh_filter_setcolormatrix) ([OH_Filter](#oh_filter) \*filter, [OH_Filter_ColorMatrix](_o_h___filter___color_matrix.md) \*matrix) | Creates a custom effect through a matrix and adds it to a filter.| +| [EffectErrorCode](#effecterrorcode) [OH_Filter_GetEffectPixelMap](#oh_filter_geteffectpixelmap) ([OH_Filter](#oh_filter) \*filter, [OH_PixelmapNative](#oh_pixelmapnative) \*\*pixelmap) | Obtains the PixelMap used to create a filter.| ## Type Description -### EffectErrorCode +### OH_Filter ``` -typedef enum EffectErrorCode EffectErrorCode +typedef struct OH_Filter OH_Filter ``` **Description** -Defines an enum for the status codes that may be used by the effect filter. +Defines a struct for a filter used to generate a filter PixelMap. **Since**: 12 -### pixelMap +### OH_PixelmapNative ``` -typedef struct OH_Filter pixelMap +typedef struct OH_PixelmapNative OH_PixelmapNative ``` **Description** -Defines a struct for a filter used to generate a filter pixel map. + -**Since**: 12 +**Since**: 12 ## Enum Description @@ -179,6 +181,11 @@ Creates the frosted glass effect and adds it to a filter. Returns a status code defined in [EffectErrorCode](#effecterrorcode). +If the operation is successful, **EFFECT_SUCCESS** is returned. + +If a parameter is invalid, **EFFECT_BAD_PARAMETER** is returned. + + ### OH_Filter_Brighten() ``` @@ -219,7 +226,7 @@ Creates an **OH_Filter** object. | Name| Description| | -------- | -------- | -| pixelmap | Pointer to the pixel map.| +| pixelmap | Pointer to the PixelMap.| | filter | Double pointer to the filter created.| **Returns** @@ -235,7 +242,7 @@ EffectErrorCode OH_Filter_GetEffectPixelMap (OH_Filter* filter, OH_PixelmapNativ **Description** -Obtains the pixel map used to create a filter. +Obtains the PixelMap used to create a filter. **Since**: 12 @@ -244,7 +251,7 @@ Obtains the pixel map used to create a filter. | Name| Description| | -------- | -------- | | filter | Pointer to the filter.| -| pixelmap | Double pointer to the pixel map obtained.| +| pixelmap | Double pointer to the PixelMap obtained.| **Returns** diff --git a/en/application-dev/reference/apis-arkgraphics2d/figures/image_Lattice.png b/en/application-dev/reference/apis-arkgraphics2d/figures/image_Lattice.png new file mode 100644 index 0000000000000000000000000000000000000000..372e5f10bca04fc891795b0e0e3f072412cbb1bd Binary files /dev/null and b/en/application-dev/reference/apis-arkgraphics2d/figures/image_Lattice.png differ diff --git a/en/application-dev/reference/apis-arkgraphics2d/figures/image_Nine.png b/en/application-dev/reference/apis-arkgraphics2d/figures/image_Nine.png new file mode 100644 index 0000000000000000000000000000000000000000..68b61da52208a50244989a1dec3255de279e4af1 Binary files /dev/null and b/en/application-dev/reference/apis-arkgraphics2d/figures/image_Nine.png differ diff --git a/en/application-dev/reference/apis-arkgraphics2d/js-apis-effectKit.md b/en/application-dev/reference/apis-arkgraphics2d/js-apis-effectKit.md index 77099171e14d4772012680d72c6483d2bd9e3e13..2555484f226cedc389089b45589797d9a26924fb 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/js-apis-effectKit.md +++ b/en/application-dev/reference/apis-arkgraphics2d/js-apis-effectKit.md @@ -1,6 +1,6 @@ # @ohos.effectKit (Image Effects) -The **EffectKit** module provides basic image processing capabilities, including brightness adjustment, blurring, grayscale adjustment, and color picker. +The EffectKit module provides basic image processing capabilities, including brightness adjustment, blurring, grayscale adjustment, and color picker. This module provides the following classes: @@ -482,7 +482,7 @@ Obtains a given number of colors with the top proportions in the image. This API | Type | Description | | :--------------------------------------- | :---------------------------------------------- | -| Array<[Color](#color) \| null> | Array of colors, sorted by proportion.
- If the number of colors obtained is less than the value of **colorCount**, the array size is the actual number obtained.
- If the color fails to be obtained, an empty array is returned.
- If the value of **colorCount** is less than 1, **[null]** is returned.
- If the value of **colorCount** is greater than 10, an array holding the first 10 colors with the top proportions is returned.| +| Array<[Color](#color) \| null> | Array of colors, sorted by proportion.
- If the number of colors obtained is less than the value of **colorCount**, the array size is the actual number obtained.
- If the colors fail to be obtained or the number of colors obtained is less than 1, **[null]** is returned.
- If the value of **colorCount** is greater than 10, an array holding the first 10 colors with the top proportions is returned.| **Example** diff --git a/en/application-dev/reference/apis-arkgraphics2d/js-apis-graphics-drawing.md b/en/application-dev/reference/apis-arkgraphics2d/js-apis-graphics-drawing.md index 5b0940a9f469b210fd5978740d6bb5747589a876..e4573dfe81589d39226d6c3e7143aa78f62f9435 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/js-apis-graphics-drawing.md +++ b/en/application-dev/reference/apis-arkgraphics2d/js-apis-graphics-drawing.md @@ -18,15 +18,20 @@ import { drawing } from '@kit.ArkGraphics2D'; ## BlendMode -Enumerates the blend modes. In blend mode, each operation generates a new color from two colors (source color and target color). These operations are the same on the four channels (red, green, blue, and alpha). The operations for the alpha channel are used as examples. +Enumerates the blend modes. In blend mode, each operation generates a new color from two colors (source color and destination color). These operations are the same for the red, green, and blue color channels (the alpha channel follows a different rule). For simplicity, the following description uses the alpha channel as an example rather than naming each channel individually. For brevity, the following abbreviations are used: -**s**: source. **d**: destination. **sa**: source alpha. **da**: destination alpha. +- **s**: source. +- **d**: destination. +- **sa**: source alpha. +- **da**: destination alpha. The following abbreviations are used in the calculation result: -**r**: The calculation methods of the four channels are the same. **ra**: Only the alpha channel is manipulated. **rc**: The other three color channels are manipulated. +- **r**: used when the calculation method is the same for the four channels (alpha, red, green, and blue channels). +- **ra**: used when only the alpha channel is manipulated. +- **rc**: used when the other three color channels are manipulated. The table below shows the effect of each blend mode, where the yellow rectangle is the source and the blue circle is the destination. @@ -34,35 +39,35 @@ The table below shows the effect of each blend mode, where the yellow rectangle | Name | Value | Description | Diagram | | ----------- | ---- | ------------------------------------------------------------ | -------- | -| CLEAR | 0 | Clear mode. r = 0. | ![CLEAR](./figures/image_BlendMode_Clear.png) | -| SRC | 1 | r = s (The four channels of **result** are equal to the four channels of **source**, that is, the result is equal to the source.)| ![SRC](./figures/image_BlendMode_Src.png) | -| DST | 2 | r = d (The four channels of **result** are equal to the four channels of **destination**, that is, the result is equal to the destination.)| ![DST](./figures/image_BlendMode_Dst.png) | -| SRC_OVER | 3 | r = s + (1 - sa) * d | ![SRC_OVER](./figures/image_BlendMode_SrcOver.png) | -| DST_OVER | 4 | r = d + (1 - da) * s | ![DST_OVER](./figures/image_BlendMode_DstOver.png) | -| SRC_IN | 5 | r = s * da | ![SRC_IN](./figures/image_BlendMode_SrcIn.png) | -| DST_IN | 6 | r = d * sa | ![DST_IN](./figures/image_BlendMode_DstIn.png) | -| SRC_OUT | 7 | r = s * (1 - da) | ![SRC_OUT](./figures/image_BlendMode_SrcOut.png) | -| DST_OUT | 8 | r = d * (1 - sa) | ![DST_OUT](./figures/image_BlendMode_DstOut.png) | -| SRC_ATOP | 9 | r = s * da + d * (1 - sa) | ![SRC_ATOP](./figures/image_BlendMode_SrcATop.png) | -| DST_ATOP | 10 | r = d * sa + s * (1 - da) | ![DST_ATOP](./figures/image_BlendMode_DstATop.png) | -| XOR | 11 | r = s * (1 - da) + d * (1 - sa) | ![XOR](./figures/image_BlendMode_Xor.png) | -| PLUS | 12 | r = min(s + d, 1) | ![PLUS](./figures/image_BlendMode_Plus.png) | -| MODULATE | 13 | r = s * d | ![MODULATE](./figures/image_BlendMode_Modulate.png) | -| SCREEN | 14 | Screen mode. r = s + d - s * d | ![SCREEN](./figures/image_BlendMode_Screen.png) | -| OVERLAY | 15 | Overlay mode. | ![OVERLAY](./figures/image_BlendMode_Overlay.png) | -| DARKEN | 16 | Darken mode. rc = s + d - max(s * da, d * sa), ra = s + (1 - sa) * d | ![DARKEN](./figures/image_BlendMode_Darken.png) | -| LIGHTEN | 17 | Lighten mode. rc = rc = s + d - min(s * da, d * sa), ra = s + (1 - sa) * d | ![LIGHTEN](./figures/image_BlendMode_Lighten.png) | -| COLOR_DODGE | 18 | Color dodge mode. | ![COLOR_DODGE](./figures/image_BlendMode_ColorDodge.png) | -| COLOR_BURN | 19 | Color burn mode. | ![COLOR_BURN](./figures/image_BlendMode_ColorBurn.png) | -| HARD_LIGHT | 20 | Hard light mode. | ![HARD_LIGHT](./figures/image_BlendMode_HardLight.png) | -| SOFT_LIGHT | 21 | Soft light mode. | ![SOFT_LIGHT](./figures/image_BlendMode_SoftLight.png) | -| DIFFERENCE | 22 | Difference mode. rc = s + d - 2 * (min(s * da, d * sa)), ra = s + (1 - sa) * d | ![DIFFERENCE](./figures/image_BlendMode_Difference.png) | -| EXCLUSION | 23 | Exclusion mode. rc = s + d - two(s * d), ra = s + (1 - sa) * d | ![EXCLUSION](./figures/image_BlendMode_Exclusion.png) | -| MULTIPLY | 24 | Multiply mode. r = s * (1 - da) + d * (1 - sa) + s * d | ![MULTIPLY](./figures/image_BlendMode_Multiply.png) | -| HUE | 25 | Hue mode. | ![HUE](./figures/image_BlendMode_Hue.png) | -| SATURATION | 26 | Saturation mode. | ![SATURATION](./figures/image_BlendMode_Saturation.png) | -| COLOR | 27 | Color mode. | ![COLOR](./figures/image_BlendMode_Color.png) | -| LUMINOSITY | 28 | Luminosity mode. | ![LUMINOSITY](./figures/image_BlendMode_Luminosity.png) | +| CLEAR | 0 | r = 0, sets the the destination pixels to fully transparent. | ![CLEAR](./figures/image_BlendMode_Clear.png) | +| SRC | 1 | r = s (all channels of the result equal those of the source), replaces the destination pixels with the source pixels.| ![SRC](./figures/image_BlendMode_Src.png) | +| DST | 2 | r = d (all channels of the result equal those of the destination), keeps the destination pixels unchanged.| ![DST](./figures/image_BlendMode_Dst.png) | +| SRC_OVER | 3 | r = s + (1 - sa) * d, draws the source pixels over the destination pixels, considering the source's transparency.| ![SRC_OVER](./figures/image_BlendMode_SrcOver.png) | +| DST_OVER | 4 | r = d + (1 - da) * s, draws the destination pixels over the source pixels, considering the destination's transparency.| ![DST_OVER](./figures/image_BlendMode_DstOver.png) | +| SRC_IN | 5 | r = s * da, retains only the intersection of the source pixels with the opaque parts of the destination.| ![SRC_IN](./figures/image_BlendMode_SrcIn.png) | +| DST_IN | 6 | r = d * sa, retains only the intersection of the destination pixels with the opaque parts of the source.| ![DST_IN](./figures/image_BlendMode_DstIn.png) | +| SRC_OUT | 7 | r = s * (1 - da), retains the parts of the source pixels that do not overlap with the destination.| ![SRC_OUT](./figures/image_BlendMode_SrcOut.png) | +| DST_OUT | 8 | r = d * (1 - sa), retains the parts of the destination pixels that do not overlap with the source.| ![DST_OUT](./figures/image_BlendMode_DstOut.png) | +| SRC_ATOP | 9 | r = s * da + d * (1 - sa), covers the destination pixels with the source pixels, showing the source only in the opaque parts of the destination.| ![SRC_ATOP](./figures/image_BlendMode_SrcATop.png) | +| DST_ATOP | 10 | r = d * sa + s * (1 - da), covers the source pixels with the destination pixels, showing the destination only in the opaque parts of the source.| ![DST_ATOP](./figures/image_BlendMode_DstATop.png) | +| XOR | 11 | r = s * (1 - da) + d * (1 - sa), shows only the non-overlapping parts of the source and destination pixels.| ![XOR](./figures/image_BlendMode_Xor.png) | +| PLUS | 12 | r = min(s + d, 1), adds the color values of the source and destination pixels. | ![PLUS](./figures/image_BlendMode_Plus.png) | +| MODULATE | 13 | r = s * d, multiplies the color values of the source and destination pixels. | ![MODULATE](./figures/image_BlendMode_Modulate.png) | +| SCREEN | 14 | r = s + d - s * d, inverts the color values of the source and destination pixels, multiplies them, and then inverts the result, typically producing a brighter outcome.| ![SCREEN](./figures/image_BlendMode_Screen.png) | +| OVERLAY | 15 | Selectively applies **MULTIPLY** or **SCREEN** based on the brightness of the destination pixels, enhancing contrast.| ![OVERLAY](./figures/image_BlendMode_Overlay.png) | +| DARKEN | 16 | rc = s + d - max(s * da, d * sa), ra = s + (1 - sa) * d, takes the darker color values between the source and destination pixels.| ![DARKEN](./figures/image_BlendMode_Darken.png) | +| LIGHTEN | 17 | rc = s + d - min(s * da, d * sa), ra = s + (1 - sa) * d, takes the lighter color values between the source and destination pixels.| ![LIGHTEN](./figures/image_BlendMode_Lighten.png) | +| COLOR_DODGE | 18 | Brightens the destination pixels by reducing contrast to reflect the source pixels. | ![COLOR_DODGE](./figures/image_BlendMode_ColorDodge.png) | +| COLOR_BURN | 19 | Darkens the destination pixels by increasing contrast to reflect the source pixels. | ![COLOR_BURN](./figures/image_BlendMode_ColorBurn.png) | +| HARD_LIGHT | 20 | Selectively applies **MULTIPLY** or **SCREEN** based on the brightness of the source pixels. | ![HARD_LIGHT](./figures/image_BlendMode_HardLight.png) | +| SOFT_LIGHT | 21 | Softly brightens or darkens the destination pixels based on the brightness of the source pixels. | ![SOFT_LIGHT](./figures/image_BlendMode_SoftLight.png) | +| DIFFERENCE | 22 | rc = s + d - 2 * (min(s * da, d * sa)), ra = s + (1 - sa) * d, calculates the difference between the color values of the source and destination pixels.| ![DIFFERENCE](./figures/image_BlendMode_Difference.png) | +| EXCLUSION | 23 | rc = s + d - two(s * d), ra = s + (1 - sa) * d, similar to **DIFFERENCE** but with lower contrast.| ![EXCLUSION](./figures/image_BlendMode_Exclusion.png) | +| MULTIPLY | 24 | r = s * (1 - da) + d * (1 - sa) + s * d, multiplies the color values of the source and destination pixels, typically resulting in a darker outcome.| ![MULTIPLY](./figures/image_BlendMode_Multiply.png) | +| HUE | 25 | Uses the hue of the source pixels and the saturation and brightness of the destination pixels. | ![HUE](./figures/image_BlendMode_Hue.png) | +| SATURATION | 26 | Uses the saturation of the source pixels and the hue and brightness of the destination pixels. | ![SATURATION](./figures/image_BlendMode_Saturation.png) | +| COLOR | 27 | Uses the hue and saturation of the source pixels and the brightness of the destination pixels. | ![COLOR](./figures/image_BlendMode_Color.png) | +| LUMINOSITY | 28 | Uses the brightness of the source pixels and the hue and saturation of the destination pixels. | ![LUMINOSITY](./figures/image_BlendMode_Luminosity.png) | ## PathMeasureMatrixFlags12+ @@ -114,7 +119,7 @@ Enumerates the operation modes available for a path. | XOR | 3 | XOR operation.| | REVERSE_DIFFERENCE | 4 | Reverse difference operation.| -## PathIteratorVerb16+ +## PathIteratorVerb18+ Enumerates the types of path operations contained in the iterator. @@ -130,11 +135,11 @@ Enumerates the types of path operations contained in the iterator. | CLOSE | 5 | Closes a path.| | DONE | CLOSE + 1 | The path setting is complete.| -## PathIterator16+ +## PathIterator18+ Implements a path operation iterator. -### constructor16+ +### constructor18+ constructor(path: Path) @@ -156,7 +161,7 @@ let path: drawing.Path = new drawing.Path(); let iter: drawing.PathIterator = new drawing.PathIterator(path); ``` -### next16+ +### next18+ next(points: Array, offset?: number): PathIteratorVerb @@ -175,7 +180,7 @@ Retrieves the next operation in this path and moves the iterator to that operati | Type | Description | | --------------------- | -------------- | -| [PathIteratorVerb](#pathiteratorverb16) | Path operation type contained in the iterator.| +| [PathIteratorVerb](#pathiteratorverb18) | Path operation type contained in the iterator.| **Error codes** @@ -205,7 +210,7 @@ for (let j = 0; j < pointCount[verb] + offset; j++) { console.info(outputMessage); ``` -### peek16+ +### peek18+ peek(): PathIteratorVerb @@ -217,7 +222,7 @@ Retrieves the next operation in this path, without moving the iterator. | Type | Description | | --------------------- | -------------- | -| [PathIteratorVerb](#pathiteratorverb16) | Path operation type contained in the iterator.| +| [PathIteratorVerb](#pathiteratorverb18) | Path operation type contained in the iterator.| **Example** @@ -228,7 +233,7 @@ let iter: drawing.PathIterator = new drawing.PathIterator(path); let res = iter.peek(); ``` -### hasNext16+ +### hasNext18+ hasNext(): boolean @@ -375,8 +380,8 @@ Draws an arc to this path. This is done by using angle arc mode. In this mode, a | y1 | number | Yes | Y coordinate of the upper left corner of the rectangle. The value is a floating point number.| | x2 | number | Yes | X coordinate of the lower right corner of the rectangle. The value is a floating point number.| | y2 | number | Yes | Y coordinate of the lower right corner of the rectangle. The value is a floating point number.| -| startDeg | number | Yes | Start angle, in degrees. The value is a floating point number.| -| sweepDeg | number | Yes | Sweep degree. The value is a floating point number.| +| startDeg | number | Yes | Start angle. The start direction (0°) of the angle is the positive direction of the X axis.| +| sweepDeg | number | Yes | Angle to sweep, in degrees. A positive number indicates a clockwise sweep, and a negative value indicates a counterclockwise swipe. The actual swipe degree is the modulo operation result of the input parameter by 360.| **Error codes** @@ -497,7 +502,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ import { drawing } from '@kit.ArkGraphics2D'; let path = new drawing.Path(); path.moveTo(10,10); -path.cubicTo(10, 10, 10, 10, 15, 15); +path.cubicTo(100, 100, 80, 150, 300, 150); ``` ### rMoveTo12+ @@ -935,7 +940,7 @@ Checks whether a coordinate point is included in this path. For details, see [Pa | Type | Description | | ------- | -------------- | -| boolean | Result indicating whether the coordinate point is included in the path. The value **true** means that the coordinate point is included in the path, and **false** means the opposite.| +| boolean | Check result. The value **true** means that the coordinate point is included in the path, and **false** means the opposite.| **Error codes** @@ -1225,7 +1230,7 @@ Obtains the coordinates and tangent at a distance from the start point of this p | Type | Description | | --------------------- | -------------- | -| boolean |Result indicating whether the coordinates and tangent of the point are obtained. The value **true** means that they are obtained, and **false** means the opposite. The values of **position** and **tangent** are not changed.| +| boolean |Check result. The value **true** means that they are obtained, and **false** means the opposite. The values of **position** and **tangent** are not changed.| **Error codes** @@ -1253,6 +1258,50 @@ if (path.getPositionAndTangent(false, 0.1, position, tangent)) { } ``` +### getSegment18+ + +getSegment(forceClosed: boolean, start: number, stop: number, startWithMoveTo: boolean, dst: Path): boolean + +Extracts a segment of this path and appends it to a destination path. + +**System capability**: SystemCapability.Graphics.Drawing + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------- | ---- | ------------------------------- | +| forceClosed | boolean | Yes | Whether the path is measured as a closed path. The value **true** means that the path is considered closed during measurement, and **false** means that the path is measured based on the actual closed status. | +| start | number | Yes | Distance from the start point of the path to the start point of the segment. If it is less than 0, it defaults to 0. If it is greater than or equal to **stop**, the extraction fails. The value is a floating point number. | +| stop | number | Yes | Distance from the start point of the path to the end point of the segment. If it is less than or equal to **start**, the extraction fails. If it is greater than the path length, it defaults to the path length. The value is a floating point number. | +| startWithMoveTo | boolean | Yes | Whether to execute [moveTo](#moveto) in the destination path to move to its start point. The value **true** means to move to the start point, and **false** means the opposite. | +| dst | number | [Path](#path) | Destination path. If the extraction succeeds, the segment is appended to the path. If the extraction fails, nothing changes. | + +**Return value** + +| Type | Description | +| --------------------- | -------------- | +| boolean |Extraction result. The value **true** means that the extraction is successful, and **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types. | + +**Example** + +```ts +import { drawing } from '@kit.ArkGraphics2D'; +let path: drawing.Path = new drawing.Path(); +path.moveTo(0, 0); +path.lineTo(0, 700); +path.lineTo(700, 0); +let dstPath: drawing.Path = new drawing.Path(); +console.info("getSegment-----result: "+ path.getSegment(true, 10.0, 20.0, true, dstPath)); +``` + ### isClosed12+ isClosed(): boolean @@ -1265,7 +1314,7 @@ Checks whether a path is closed. | Type | Description | | --------------------- | -------------- | -| boolean | Result indicating whether the path is closed. The value **true** means that the path is closed, and **false** means the opposite.| +| boolean | Check result. The value **true** means that the path is closed, and **false** means the opposite.| **Example** @@ -1302,7 +1351,7 @@ Obtains a transformation matrix at a distance from the start point of this path. | Type | Description | | --------------------- | -------------- | -| boolean | Result indicating whether a transformation matrix is obtained. The value **true** means that a transformation matrix is obtained, and **false** means the opposite.| +| boolean | Check result. The value **true** means that a transformation matrix is obtained, and **false** means the opposite.| **Error codes** @@ -1343,7 +1392,7 @@ Parses the path represented by an SVG string. | Type | Description | | --------------------- | -------------- | -| boolean | Result indicating whether the SVG string is parsed. The value **true** means that the parsing is successful, and **false** means the opposite.| +| boolean | Check result. The value **true** means that the parsing is successful, and **false** means the opposite.| **Error codes** @@ -1366,7 +1415,7 @@ if(path.buildFromSvgString(svgStr)) { } ``` -### getPathIterator16+ +### getPathIterator18+ getPathIterator(): PathIterator @@ -1378,7 +1427,7 @@ Obtains the operation iterator of this path. | Type | Description | | --------------------- | -------------- | -| [PathIterator](#pathiterator16) | **Iterator** object of the path.| +| [PathIterator](#pathiterator18) | **Iterator** object of the path.| **Example** @@ -1408,7 +1457,7 @@ A constructor used to create a **Canvas** object. | Name | Type | Mandatory| Description | | -------- | -------------------------------------------- | ---- | -------------- | -| pixelmap | [image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | Yes | Pixel map used to create the object.| +| pixelmap | [image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | Yes | PixelMap used to create the object.| **Error codes** @@ -1650,7 +1699,7 @@ Draws a spot shadow and uses a given path to outline the ambient shadow. | Name | Type | Mandatory | Description | | ------------ | ---------------------------------------- | ---- | ---------- | | path | [Path](#path) | Yes | **Path** object, which is used to outline the shadow.| -| planeParams | [common2D.Point3d](js-apis-graphics-common2D.md#point3d12) | Yes | 3D vector, which is used to calculate the offset in the Z axis.| +| planeParams | [common2D.Point3d](js-apis-graphics-common2D.md#point3d12) | Yes | 3D vector, which is used to determine the z-axis offset of an occluder relative to the canvas, based on its x and y coordinates.| | devLightPos | [common2D.Point3d](js-apis-graphics-common2D.md#point3d12) | Yes | Position of the light relative to the canvas.| | lightRadius | number | Yes | Radius of the light. The value is a floating point number. | | ambientColor | [common2D.Color](js-apis-graphics-common2D.md#color) | Yes | Color of the ambient shadow.| @@ -1695,9 +1744,9 @@ class DrawingRenderNode extends RenderNode { } ``` -### drawShadow16+ +### drawShadow18+ -drawShadow(path: Path, planeParams: common2D.Point3d, devLightPos: common2D.Point3d, lightRadius: number, ambientColor: number, spotColor: number, flag: ShadowFlag) : void +drawShadow(path: Path, planeParams: common2D.Point3d, devLightPos: common2D.Point3d, lightRadius: number, ambientColor: common2D.Color | number, spotColor: common2D.Color | number, flag: ShadowFlag) : void Draws a spot shadow and uses a given path to outline the ambient shadow. @@ -1711,8 +1760,8 @@ Draws a spot shadow and uses a given path to outline the ambient shadow. | planeParams | [common2D.Point3d](js-apis-graphics-common2D.md#point3d12) | Yes | 3D vector, which is used to calculate the offset in the Z axis.| | devLightPos | [common2D.Point3d](js-apis-graphics-common2D.md#point3d12) | Yes | Position of the light relative to the canvas.| | lightRadius | number | Yes | Radius of the light. The value is a floating point number. | -| ambientColor |number | Yes | Ambient shadow color, represented by a 32-bit unsigned integer in hexadecimal ARGB format.| -| spotColor |number | Yes | Spot shadow color, represented by a 32-bit unsigned integer in hexadecimal ARGB format.| +| ambientColor |[common2D.Color](js-apis-graphics-common2D.md#color) \| number | Yes | Ambient shadow color, represented by a 32-bit unsigned integer in hexadecimal ARGB format.| +| spotColor |[common2D.Color](js-apis-graphics-common2D.md#color) \| number | Yes | Spot shadow color, represented by a 32-bit unsigned integer in hexadecimal ARGB format.| | flag | [ShadowFlag](#shadowflag12) | Yes | Shadow flag. | **Error codes** @@ -1860,7 +1909,7 @@ Draws an image. The coordinates of the upper left corner of the image are (left, | Name | Type | Mandatory| Description | | -------- | -------------------------------------------- | ---- | ------------------------------- | -| pixelmap | [image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | Yes | Pixel map of the image. | +| pixelmap | [image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | Yes | PixelMap. | | left | number | Yes | X coordinate of the upper left corner of the image. The value is a floating point number.| | top | number | Yes | Y coordinate of the upper left corner of the image. The value is a floating point number.| | samplingOptions12+ | [SamplingOptions](#samplingoptions12) | No | Sampling options. By default, the **SamplingOptions** object created using the no-argument constructor is used.| @@ -1904,7 +1953,7 @@ Draws an image onto a specified area of the canvas. | Name | Type | Mandatory| Description | | -------- | -------------------------------------------- | ---- | ------------------------------- | -| pixelmap | [image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | Yes | Pixel map of the image. | +| pixelmap | [image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | Yes | PixelMap. | | dstRect | [common2D.Rect](js-apis-graphics-common2D.md#rect) | Yes | **Rectangle** object, which specifies the area of the canvas onto which the image will be drawn.| | samplingOptions | [SamplingOptions](#samplingoptions12) | No | Sampling options. By default, the **SamplingOptions** object created using the no-argument constructor is used.| @@ -1947,7 +1996,7 @@ Draws a portion of an image onto a specified area of the canvas. | Name | Type | Mandatory| Description | | -------- | -------------------------------------------- | ---- | ------------------------------- | -| pixelmap | [image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | Yes | Pixel map of the image. | +| pixelmap | [image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | Yes | PixelMap. | | srcRect | [common2D.Rect](js-apis-graphics-common2D.md#rect) | Yes | **Rectangle** object, which specifies the portion of the image to draw.| | dstRect | [common2D.Rect](js-apis-graphics-common2D.md#rect) | Yes | **Rectangle** object, which specifies the area of the canvas onto which the image will be drawn.| | samplingOptions | [SamplingOptions](#samplingoptions12) | No | Sampling options. By default, the **SamplingOptions** object created using the no-argument constructor is used.| @@ -2062,7 +2111,7 @@ class DrawingRenderNode extends RenderNode { } ``` -### drawColor16+ +### drawColor18+ drawColor(color: number, blendMode?: BlendMode): void @@ -2102,7 +2151,7 @@ class DrawingRenderNode extends RenderNode { drawPixelMapMesh(pixelmap: image.PixelMap, meshWidth: number, meshHeight: number, vertices: Array\, vertOffset: number, colors: Array\, colorOffset: number): void -Draws a pixel map based on a mesh, where mesh vertices are evenly distributed across the pixel map. +Draws a PixelMap based on a mesh, where mesh vertices are evenly distributed across the PixelMap. **System capability**: SystemCapability.Graphics.Drawing @@ -2110,7 +2159,7 @@ Draws a pixel map based on a mesh, where mesh vertices are evenly distributed ac | Name | Type | Mandatory| Description | | ----------- | ------------- | ---- | ------------------------------- | -| pixelmap | [image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | Yes | Pixel map to draw.| +| pixelmap | [image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | Yes | PixelMap to draw.| | meshWidth | number | Yes | Number of columns in the mesh. The value is an integer greater than 0.| | meshHeight | number | Yes | Number of rows in the mesh. The value is an integer greater than 0.| | vertices | Array\ | Yes | Array of vertices, which specify the position to draw. The value is a floating-point array and the size must be ((meshWidth+1) * (meshHeight+1) + vertOffset) * 2.| @@ -2184,9 +2233,9 @@ class DrawingRenderNode extends RenderNode { } ``` -### clear16+ +### clear18+ -clear(color: number): void +clear(color: common2D.Color | number): void Clears the canvas with a given color. @@ -2196,7 +2245,7 @@ Clears the canvas with a given color. | Name | Type | Mandatory| Description | | --------- | ---------------------------------------------------- | ---- | -------------------------------- | -| color | number| Yes | Color in hexadecimal ARGB format. | +| color | [common2D.Color](js-apis-graphics-common2D.md#color) \| number| Yes | Color, represented by a 32-bit unsigned integer in hexadecimal ARGB format. | **Error codes** @@ -2322,7 +2371,7 @@ class DrawingRenderNode extends RenderNode { drawArc(arc: common2D.Rect, startAngle: number, sweepAngle: number): void -Draws an arc on the canvas, with the start angle and sweep angle specified. +Draws an arc on the canvas, with the start angle and sweep angle specified. If the absolute value of the sweep angle exceeds 360 degrees, an ellipse is drawn. **System capability**: SystemCapability.Graphics.Drawing @@ -2332,7 +2381,7 @@ Draws an arc on the canvas, with the start angle and sweep angle specified. | ------ | -------------------------------------------------- | ---- | -------------- | | arc | [common2D.Rect](js-apis-graphics-common2D.md#rect) | Yes | Rectangular boundary that encapsulates the oval including the arc.| | startAngle | number | Yes | Start angle, in degrees. The value is a floating point number. When the degree is 0, the start point is located at the right end of the oval. A positive number indicates that the start point is placed clockwise, and a negative number indicates that the start point is placed counterclockwise.| -| sweepAngle | number | Yes | Angle to sweep, in degrees. The value is a floating point number. A positive number indicates a clockwise sweep, and a negative value indicates a counterclockwise swipe.| +| sweepAngle | number | Yes | Angle to sweep, in degrees. The value is a floating point number. A positive number indicates a clockwise sweep, and a negative value indicates a counterclockwise swipe. The valid range is from -360 degrees to 360 degrees. If the absolute value of the sweep angle exceeds 360 degrees, an ellipse is drawn.| **Error codes** @@ -2652,6 +2701,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts import { RenderNode } from '@kit.ArkUI'; +import { drawing } from '@kit.ArkGraphics2D'; class DrawingRenderNode extends RenderNode { draw(context : DrawContext) { const canvas = context.canvas; @@ -2837,16 +2887,12 @@ import { common2D, drawing } from '@kit.ArkGraphics2D'; class DrawingRenderNode extends RenderNode { draw(context : DrawContext) { const canvas = context.canvas; - const pen = new drawing.Pen(); - pen.setStrokeWidth(5); - pen.setColor({alpha: 255, red: 255, green: 0, blue: 0}); let path = new drawing.Path(); path.moveTo(10, 10); - path.cubicTo(10, 10, 10, 10, 15, 15); + path.cubicTo(100, 100, 80, 150, 300, 150); path.close(); - canvas.attachPen(pen); - canvas.clipPath(path, drawing.ClipOp.DIFFERENCE, true); - canvas.detachPen(); + canvas.clipPath(path, drawing.ClipOp.INTERSECT, true); + canvas.clear({alpha: 255, red: 255, green: 0, blue: 0}); } } ``` @@ -2883,12 +2929,8 @@ import { common2D, drawing } from '@kit.ArkGraphics2D'; class DrawingRenderNode extends RenderNode { draw(context : DrawContext) { const canvas = context.canvas; - const pen = new drawing.Pen(); - pen.setStrokeWidth(5); - pen.setColor({alpha: 255, red: 255, green: 0, blue: 0}); - canvas.attachPen(pen); canvas.clipRect({left : 10, right : 500, top : 300, bottom : 900}, drawing.ClipOp.DIFFERENCE, true); - canvas.detachPen(); + canvas.clear({alpha: 255, red: 255, green: 0, blue: 0}); } } ``` @@ -2897,7 +2939,7 @@ class DrawingRenderNode extends RenderNode { save(): number -Saves the current canvas status (canvas matrix) to the top of the stack. +Saves the current canvas status (canvas matrix) to the top of the stack. This API must be used in pair with [restore](#restore12). **System capability**: SystemCapability.Graphics.Drawing @@ -2926,7 +2968,7 @@ class DrawingRenderNode extends RenderNode { saveLayer(rect?: common2D.Rect | null, brush?: Brush | null): number -Saves the matrix and cropping region of the canvas, and allocates a bitmap for subsequent drawing. If you call [restore](#restore12), the changes made to the matrix and clipping region are discarded, and the bitmap is drawn. +Saves the matrix and cropping region of the canvas, and allocates a PixelMap for subsequent drawing. If you call [restore](#restore12), changes made to the matrix and clipping region are discarded, and the PixelMap is drawn. **System capability**: SystemCapability.Graphics.Drawing @@ -3037,8 +3079,8 @@ Skews the canvas in both the horizontal and vertical directions. | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ----------------- | -| sx | number | Yes | Amount of tilt on the X axis. The value is a floating point number. | -| sy | number | Yes | Amount of tilt on the Y axis. The value is a floating point number. | +| sx | number | Yes | Amount of tilt on the X axis. The value is a floating point number. A positive number tilts the drawing rightwards along the positive direction of the Y axis, and a negative number tilts the drawing leftwards along the positive direction of the Y axis. | +| sy | number | Yes | Amount of tilt on the Y axis. The value is a floating point number. A positive number tilts the drawing downwards along the positive direction of the X axis, and a negative number tilts the drawing upwards along the positive direction of the X axis. | **Error codes** @@ -3293,6 +3335,7 @@ class DrawingRenderNode extends RenderNode { let matrix = new drawing.Matrix(); matrix.setMatrix([5, 0, 0, 0, 1, 2, 0, 0, 1]); canvas.concatMatrix(matrix); + canvas.drawRect({left: 10, right: 200, top: 100, bottom: 500}); } } ``` @@ -3330,6 +3373,7 @@ class DrawingRenderNode extends RenderNode { let matrix = new drawing.Matrix() matrix.setMatrix([5, 0, 0, 0, 1, 1, 0, 0, 1]); canvas.setMatrix(matrix); + canvas.drawRect({left: 10, right: 200, top: 100, bottom: 500}); } } ``` @@ -3346,7 +3390,7 @@ Checks whether the region that can be drawn is empty after clipping. | Type | Description | | --------------------- | -------------- | -| boolean | Chek result. The value **true** means that the region is empty, and **false** means the opposite.| +| boolean | Check result. The value **true** means that the region is empty, and **false** means the opposite.| **Example** @@ -3392,13 +3436,15 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts import { RenderNode } from '@kit.ArkUI'; -import { drawing } from '@kit.ArkGraphics2D'; +import { common2D, drawing } from '@kit.ArkGraphics2D'; class DrawingRenderNode extends RenderNode { draw(context : DrawContext) { const canvas = context.canvas; let region : drawing.Region = new drawing.Region(); region.setRect(0, 0, 500, 500); canvas.clipRegion(region); + let color: common2D.Color = {alpha: 255, red: 255, green: 0, blue: 0}; + canvas.clear(color); } } ``` @@ -3438,6 +3484,8 @@ class DrawingRenderNode extends RenderNode { let rect: common2D.Rect = { left: 10, top: 100, right: 200, bottom: 300 }; let roundRect = new drawing.RoundRect(rect, 10, 10); canvas.clipRoundRect(roundRect); + let color: common2D.Color = {alpha: 255, red: 255, green: 0, blue: 0}; + canvas.clear(color); } } ``` @@ -3464,6 +3512,249 @@ class DrawingRenderNode extends RenderNode { } ``` +### quickRejectPath18+ + +quickRejectPath(path: Path): boolean + +Checks whether the path is not intersecting with the canvas area. The canvas area includes its boundaries. + +**System capability**: SystemCapability.Graphics.Drawing + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------- | ---- | ------------------ | +| path | [Path](#path) | Yes | Path object.| + +**Return value** + +| Type | Description | +| --------------------- | -------------- | +| boolean | Check result. The value **true** means that the path is not intersecting with the canvas area, and **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types. | + +**Example** + +```ts +import { RenderNode } from '@kit.ArkUI'; +import { drawing } from '@kit.ArkGraphics2D'; + +class DrawingRenderNode extends RenderNode { + draw(context : DrawContext) { + const canvas = context.canvas; + let path = new drawing.Path(); + path.moveTo(10, 10); + path.cubicTo(10, 10, 10, 10, 15, 15); + path.close(); + if (canvas.quickRejectPath(path)) { + console.info("canvas and path do not intersect."); + } else { + console.info("canvas and path intersect."); + } + } +} +``` + +### quickRejectRect18+ + +quickRejectRect(rect: common2D.Rect): boolean + +Checks whether the rectangle is not intersecting with the canvas area. The canvas area includes its boundaries. + +**System capability**: SystemCapability.Graphics.Drawing + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------------------------------------------- | ---- | -------------- | +| rect | [common2D.Rect](js-apis-graphics-common2D.md#rect) | Yes | Rectangle.| + +**Return value** + +| Type | Description | +| --------------------- | -------------- | +| boolean | Check result. The value **true** means that the rectangle is not intersecting with the canvas area, and **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types. | + +**Example** + +```ts +import { RenderNode } from '@kit.ArkUI'; +import { common2D, drawing } from '@kit.ArkGraphics2D'; + +class DrawingRenderNode extends RenderNode { + draw(context : DrawContext) { + const canvas = context.canvas; + let rect: common2D.Rect = { left : 10, top : 20, right : 50, bottom : 30 }; + if (canvas.quickRejectRect(rect)) { + console.info("canvas and rect do not intersect."); + } else { + console.info("canvas and rect intersect."); + } + } +} +``` + +### drawArcWithCenter18+ + +drawArcWithCenter(arc: common2D.Rect, startAngle: number, sweepAngle: number, useCenter: boolean): void + +Draws an arc on the canvas. It enables you to define the starting angle, sweep angle, and whether the arc's endpoints should connect to its center. + +**System capability**: SystemCapability.Graphics.Drawing + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------------------------------------------- | ---- | -------------- | +| arc | [common2D.Rect](js-apis-graphics-common2D.md#rect) | Yes | Rectangular boundary that encapsulates the oval including the arc.| +| startAngle | number | Yes | Start angle, in degrees. The value is a floating point number. When the degree is 0, the start point is located at the right end of the oval. A positive number indicates that the start point is placed clockwise, and a negative number indicates that the start point is placed counterclockwise.| +| sweepAngle | number | Yes | Angle to sweep, in degrees. The value is a floating point number. A positive number indicates a clockwise sweep, and a negative value indicates a counterclockwise swipe. The swipe angle can exceed 360 degrees, and a complete ellipse is drawn.| +| useCenter | boolean | Yes | Whether the start point and end point of the arc are connected to its center. The value **true** means that they are connected to the center; the value **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types. | + +**Example** + +```ts +import { RenderNode } from '@kit.ArkUI'; +import { common2D, drawing } from '@kit.ArkGraphics2D'; + +class DrawingRenderNode extends RenderNode { + draw(context : DrawContext) { + const canvas = context.canvas; + const pen = new drawing.Pen(); + pen.setStrokeWidth(5); + const color : common2D.Color = { alpha: 255, red: 255, green: 0, blue: 0 }; + pen.setColor(color); + canvas.attachPen(pen); + const rect: common2D.Rect = { left: 100, top: 50, right: 400, bottom: 200 }; + canvas.drawArcWithCenter(rect, 90, 180, false); + canvas.detachPen(); + } +} +``` + +### drawImageNine18+ + +drawImageNine(pixelmap: image.PixelMap, center: common2D.Rect, dstRect: common2D.Rect, filterMode: FilterMode): void + +Splits an image into nine sections using two horizontal and two vertical lines: four edge sections, four corner sections, and a central section. + +If the four corner sections are smaller than the target rectangle, they will be drawn in the target rectangle without scaling. Otherwise, they will be scaled to fit the target rectangle. Any remaining space will be filled by stretching or compressing the other five sections to cover the entire target rectangle. + +**System capability**: SystemCapability.Graphics.Drawing + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------- | +| pixelmap | [image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | Yes | PixelMap to split.| +| center | [common2D.Rect](js-apis-graphics-common2D.md#rect) | Yes | Central rectangle that divides the image into nine sections by extending its four edges.| +| dstRect | [common2D.Rect](js-apis-graphics-common2D.md#rect) | Yes | Target rectangle drawn on the canvas.| +| filterMode | [FilterMode](#filtermode12) | Yes | Filter mode.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types;3.Parameter verification failed. | + +**Example** + +```ts +import { RenderNode } from '@kit.ArkUI'; +import { common2D, drawing } from '@kit.ArkGraphics2D'; +import { image } from '@kit.ImageKit'; + +class DrawingRenderNode extends RenderNode { + draw(context : DrawContext) { + const canvas = context.canvas; + let pixelMap: image.PixelMap = globalThis.getInstance().getPixelMap("test_2.jpg"); + canvas.drawImage(pixelMap, 0, 0); // Original image + let center: common2D.Rect = { left: 20, top: 10, right: 50, bottom: 40 }; + let dst: common2D.Rect = { left: 70, top: 0, right: 100, bottom: 30 }; + let dst1: common2D.Rect = { left: 110, top: 0, right: 200, bottom: 90 }; + canvas.drawImageNine(pixelMap, center, dst, drawing.FilterMode.FILTER_MODE_NEAREST); // Example 1 + canvas.drawImageNine(pixelMap, center, dst1, drawing.FilterMode.FILTER_MODE_NEAREST); // Example 2 + } +} +``` +![image_Nine.png](figures/image_Nine.png) + +### drawImageLattice18+ + +drawImageLattice(pixelmap: image.PixelMap, lattice: Lattice, dstRect: common2D.Rect, filterMode: FilterMode): void + +Splits an image into multiple sections based on the lattice object's configuration and draws each section into the specified target rectangle on the canvas. + +The intersections of even-numbered rows and columns (starting from 0) are fixed points. If the fixed lattice area fits within the target rectangle, it will be drawn without scaling. Otherwise, it will be scaled proportionally to fit the target rectangle. Any remaining space will be filled by stretching or compressing the remaining sections to cover the entire target rectangle. + +**System capability**: SystemCapability.Graphics.Drawing + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------- | +| pixelmap | [image.PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | Yes | PixelMap to split.| +| lattice | [Lattice](#lattice12) | Yes | Lattice object.| +| dstRect | [common2D.Rect](js-apis-graphics-common2D.md#rect) | Yes | Target rectangle.| +| filterMode | [FilterMode](#filtermode12) | Yes | Filter mode.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types;3.Parameter verification failed. | + +**Example** + +```ts +import { RenderNode } from '@kit.ArkUI'; +import { common2D, drawing } from '@kit.ArkGraphics2D'; +import { image } from '@kit.ImageKit'; + +class DrawingRenderNode extends RenderNode { + draw(context : DrawContext) { + const canvas = context.canvas; + let pixelMap: image.PixelMap = globalThis.getInstance().getPixelMap("test_3.jpg"); + canvas.drawImage(pixelMap, 0, 0); // Original image + let xDivs: Array = [28, 36, 44, 52]; + let yDivs: Array = [28, 36, 44, 52]; + let lattice = drawing.Lattice.createImageLattice(xDivs, yDivs, 4, 4); + let dst: common2D.Rect = { left: 100, top: 0, right: 164, bottom: 64 }; + let dst1: common2D.Rect = { left: 200, top: 0, right: 360, bottom: 160 }; + canvas.drawImageLattice(pixelMap, lattice, dst, drawing.FilterMode.FILTER_MODE_NEAREST); // Example 1 + canvas.drawImageLattice(pixelMap, lattice, dst1, drawing.FilterMode.FILTER_MODE_NEAREST); // Example 2 + } +} +``` +![image_Lattice.png](figures/image_Lattice.png) + ## ImageFilter12+ Implements an image filter. @@ -3620,6 +3911,7 @@ Enumerates the fill types of a path. | INVERSE_EVEN_ODD | 3 | Same as **EVEN_ODD**, but draws outside of the path, rather than inside.| > **NOTE** +> > ![WINDING&EVEN_ODD](./figures/image_PathFillType_Winding_Even_Odd.png) > As shown in the above figure, the path is a circle, the arrow indicates the path direction, **p** is any point "inside" the path, the blue line is the ray emitted from **p**, and the black arrow indicates the fill result using blue under the corresponding fill type. Under the **WINDING** fill rule, the number of intersection points of the ray and path is 2 (not 0), and therefore **p** is colored. Under the **EVEN_ODD** filling rule, the number of intersection points of the ray and path is 2 (an even number), and therefore **p** is not colored. @@ -3949,7 +4241,7 @@ class TextRenderNode extends RenderNode { } ``` -### makeFromRawFile16+ +### makeFromRawFile18+ static makeFromRawFile(rawfile: Resource): Typeface @@ -4689,7 +4981,7 @@ Checks whether baselines are requested to be snapped to pixels when the current | Type | Description | | ------ | ---------------- | -| boolean | Result indicating whether the baselines are requested to be snapped to pixels when the current canvas matrix is axis aligned. The value **true** means that the baselines are requested to be snapped to pixels, and **false** means the opposite.| +| boolean | Check result. The value **true** means that the baselines are requested to be snapped to pixels, and **false** means the opposite.| **Example** @@ -4747,7 +5039,7 @@ Checks whether bitmaps are used in this font. | Type | Description | | ------ | ---------------- | -| boolean | Result indicating whether the bitmaps are used in the font. The value **true** means that the bitmaps are used, and **false** means the opposite.| +| boolean | Check result. The value **true** means that the bitmaps are used, and **false** means the opposite.| **Example** @@ -4805,7 +5097,7 @@ Checks whether auto hinting is forcibly used. | Type | Description | | ------ | ---------------- | -| boolean | Result indicating whether auto hinting is forcibly used. The value **true** means that auto hinting is forcibly used, and **false** means the opposite.| +| boolean | Check result. The value **true** means that auto hinting is forcibly used, and **false** means the opposite.| **Example** @@ -4900,7 +5192,7 @@ let glyphs : number[] = font.textToGlyphs(text); console.info("drawing text toglyphs OnTestFunction num = " + glyphs.length ); ``` -### getBounds16+ +### getBounds18+ getBounds(glyphs: Array\): Array\ @@ -4933,36 +5225,17 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts import { common2D, drawing } from '@kit.ArkGraphics2D'; -@Entry -@Component -struct Index { - @State message: string = 'Hello World'; - - build() { - Row() { - Column() { - Text(this.message) - .fontSize(50) - .fontWeight(FontWeight.Bold) - .onClick(() => { - let font: drawing.Font = new drawing.Font(); - let text: string = 'hello world'; - let glyphs: number[] = font.textToGlyphs(text); - let fontBounds: Array = font.getBounds(glyphs); - for (let index = 0; index < fontBounds.length; index++) { - console.info("get fontWidths[", index, "] left:", fontBounds[index].left, " top:", fontBounds[index].top, - " right:", fontBounds[index].right, " bottom:", fontBounds[index].bottom); - } - }) - } - .width('100%') - } - .height('100%') - } +let font: drawing.Font = new drawing.Font(); +let text: string = 'hello world'; +let glyphs: number[] = font.textToGlyphs(text); +let fontBounds: Array = font.getBounds(glyphs); +for (let index = 0; index < fontBounds.length; index++) { + console.info("get fontWidths[", index, "] left:", fontBounds[index].left, " top:", fontBounds[index].top, + " right:", fontBounds[index].right, " bottom:", fontBounds[index].bottom); } ``` -### getTextPath16+ +### getTextPath18+ getTextPath(text: string, byteLength: number, x: number, y: number): Path; @@ -5013,7 +5286,7 @@ class DrawingRenderNode extends RenderNode { } ``` -### createPathForGlyph16+ +### createPathForGlyph18+ createPathForGlyph(index: number): Path @@ -5062,7 +5335,7 @@ class DrawingRenderNode extends RenderNode { } ``` -### setThemeFontFollowed16+ +### setThemeFontFollowed15+ setThemeFontFollowed(followed: boolean): void @@ -5094,7 +5367,7 @@ font.setThemeFontFollowed(true); console.info("font is theme font followed: " + font.isThemeFontFollowed()); ``` -### isThemeFontFollowed()16+ +### isThemeFontFollowed()15+ isThemeFontFollowed(): boolean @@ -5198,9 +5471,9 @@ const color : common2D.Color = { alpha: 255, red: 255, green: 0, blue: 0 }; let colorFilter = drawing.ColorFilter.createBlendModeColorFilter(color, drawing.BlendMode.SRC); ``` -### createBlendModeColorFilter16+ +### createBlendModeColorFilter18+ -static createBlendModeColorFilter(color: number, mode: BlendMode) : ColorFilter +static createBlendModeColorFilter(color: common2D.Color | number, mode: BlendMode) : ColorFilter Creates a **ColorFilter** object with a given color and blend mode. @@ -5210,14 +5483,14 @@ Creates a **ColorFilter** object with a given color and blend mode. | Name| Type | Mandatory| Description | | ------ | ---------------------------------------------------- | ---- | ---------------- | -| color | number | Yes | Color in hexadecimal ARGB format.| +| color | [common2D.Color](js-apis-graphics-common2D.md#color) \| number | Yes | Color, represented by a 32-bit unsigned integer in hexadecimal ARGB format.| | mode | [BlendMode](#blendmode) | Yes | Blend mode.| **Return value** | Type | Description | | --------------------------- | ------------------ | -| [ColorFilter](#colorfilter) | Color filter created.| +| [ColorFilter](#colorfilter) | **ColorFilter** object created.| **Error codes** @@ -5319,7 +5592,7 @@ let colorFilter = drawing.ColorFilter.createSRGBGammaToLinear(); createLumaColorFilter() : ColorFilter -Creates a **ColorFilter** object that multiplies the luma into the alpha channel. +Creates a **ColorFilter** object that multiplies the luma into the alpha channel and sets the RGB channels to zero. **System capability**: SystemCapability.Graphics.Drawing @@ -5354,7 +5627,7 @@ Creates a color filter object with a 4*5 color matrix. | Type | Description | | --------------------------- | ------------------ | -| [ColorFilter](#colorfilter) | Color filter created.| +| [ColorFilter](#colorfilter) | **ColorFilter** object created.| **Error codes** @@ -5528,7 +5801,7 @@ class DrawingRenderNode extends RenderNode { ``` ![Lattice.png](figures/Lattice.png) -### createImageLattice16+ +### createImageLattice18+ static createImageLattice(xDivs: Array\, yDivs: Array\, fXCount: number, fYCount: number, fBounds?: common2D.Rect | null, fRectTypes?: Array\ | null, fColors?: Array\ | null): Lattice @@ -5635,7 +5908,7 @@ class DrawingRenderNode extends RenderNode { } ``` -## PathDashStyle16+ +## PathDashStyle18+ Enumerates the styles of the dashed path effect. @@ -5694,7 +5967,7 @@ class DrawingRenderNode extends RenderNode { } ``` -### createPathDashEffect16+ +### createPathDashEffect18+ static createPathDashEffect(path: Path, advance: number, phase: number, style: PathDashStyle): PathEffect @@ -5709,7 +5982,7 @@ Creates a dashed path effect based on the shape described by a path. | path | [Path](#path) | Yes| Path that defines the shape to be used for filling each dash in the pattern.| | advance | number | Yes| Distance between two consecutive dashes. The value is a floating point number greater than 0. Otherwise, an error code is thrown.| | phase | number | Yes| Starting offset of the dash pattern. The value is a floating point number. The actual offset used is the absolute value of this value modulo the value of **advance**.| -| style | [PathDashStyle](#pathdashstyle16) | Yes| Style of the dashed path effect.| +| style | [PathDashStyle](#pathdashstyle18) | Yes| Style of the dashed path effect.| **Return value** @@ -5762,9 +6035,9 @@ class DrawingRenderNode extends RenderNode { } ``` -### createSumPathEffect16+ +### createSumPathEffect18+ -static createSumPathEffect(pathEffectOne: PathEffect, pathEffectTwo: PathEffect): PathEffect +static createSumPathEffect(firstPathEffect: PathEffect, secondPathEffect: PathEffect): PathEffect Creates an overlay path effect based on two distinct path effects. Different from **createComposePathEffect**, this API applies each effect separately and then displays them as a simple overlay. @@ -5774,8 +6047,8 @@ Creates an overlay path effect based on two distinct path effects. Different fro | Name | Type | Mandatory | Description | | ---------- | ------------- | ------- | -------------------------------------------------- | -| pathEffectOne | [PathEffect](#patheffect12) | Yes| First path effect.| -| pathEffectTwo | [PathEffect](#patheffect12) | Yes| Second path effect.| +| firstPathEffect | [PathEffect](#patheffect12) | Yes| First path effect.| +| secondPathEffect | [PathEffect](#patheffect12) | Yes| Second path effect.| **Return value** @@ -5848,7 +6121,7 @@ class DrawingRenderNode extends RenderNode { } ``` -### createDiscretePathEffect16+ +### createDiscretePathEffect18+ static createDiscretePathEffect(segLength: number, dev: number, seedAssist?: number): PathEffect @@ -5891,7 +6164,7 @@ class DrawingRenderNode extends RenderNode { } ``` -### createComposePathEffect16+ +### createComposePathEffect18+ static createComposePathEffect(outer: PathEffect, inner: PathEffect): PathEffect @@ -5984,9 +6257,9 @@ class DrawingRenderNode extends RenderNode { } ``` -### create16+ +### create18+ -static create(blurRadius: number, x: number, y: number, color: number): ShadowLayer +static create(blurRadius: number, x: number, y: number, color: common2D.Color | number): ShadowLayer Creates a **ShadowLayer** object. @@ -5999,7 +6272,7 @@ Creates a **ShadowLayer** object. | blurRadius | number | Yes | Radius of the shadow layer. The value must be a floating point number greater than 0. | | x | number | Yes | Offset on the X axis. The value is a floating point number. | | y | number | Yes | Offset on the Y axis. The value is a floating point number. | -| color | number | Yes | Color in hexadecimal ARGB format.| +| color | [common2D.Color](js-apis-graphics-common2D.md#color) \| number | Yes | Color, represented by a 32-bit unsigned integer in hexadecimal ARGB format. | **Return value** @@ -6257,7 +6530,7 @@ const pen = new drawing.Pen(); pen.setColor(255, 255, 0, 0); ``` -### setColor16+ +### setColor18+ setColor(color: number) : void @@ -6312,7 +6585,7 @@ pen.setColor(color); let colorGet = pen.getColor(); ``` -### getHexColor16+ +### getHexColor18+ getHexColor(): number @@ -6433,7 +6706,7 @@ Checks whether anti-aliasing is enabled for this pen. | Type | Description | | ------- | ------------------------- | -| boolean | Result indicating whether anti-aliasing is enabled. The value **true** means that anti-aliasing is enabled, and **false** means the opposite.| +| boolean | Check result. The value **true** means that anti-aliasing is enabled, and **false** means the opposite.| **Example** @@ -6905,7 +7178,7 @@ Obtains the source path outline drawn using this pen and represents it using a d | Type | Description | | --------------------- | -------------- | -| boolean | Result indicating whether the source path outline is obtained. The value **true** means that the source path outline is obtained, and **false** means the opposite.| +| boolean | Check result. The value **true** means that the source path outline is obtained, and **false** means the opposite.| **Error codes** @@ -7061,7 +7334,7 @@ const brush = new drawing.Brush(); brush.setColor(255, 255, 0, 0); ``` -### setColor16+ +### setColor18+ setColor(color: number) : void @@ -7116,7 +7389,7 @@ brush.setColor(color); let colorGet = brush.getColor(); ``` -### getHexColor16+ +### getHexColor18+ getHexColor(): number @@ -7184,7 +7457,7 @@ Checks whether anti-aliasing is enabled for this brush. | Type | Description | | ------- | ------------------------- | -| boolean | Result indicating whether anti-aliasing is enabled. The value **true** means that anti-aliasing is enabled, and **false** means the opposite.| +| boolean | Check result. The value **true** means that anti-aliasing is enabled, and **false** means the opposite.| **Example** @@ -7785,7 +8058,7 @@ Inverts this matrix and returns the result. | Type | Description | | --------------------------- | -------------------- | -| Boolean | Result indicating whether the matrix is revertible. The value **true** means that the matrix is revertible and the **matrix** object is filled with the inverted matrix, and **false** means that the matrix is not revertible and the **matrix** object is filled with the current matrix (not changed).| +| Boolean | Check result. The value **true** means that the matrix is revertible and the **matrix** object is filled with the inverted matrix, and **false** means that the matrix is not revertible and the **matrix** object is filled with the current matrix (not changed).| **Error codes** @@ -7823,7 +8096,7 @@ Checks whether this matrix is an identity matrix. | Type | Description | | --------------------------- | -------------------- | -| Boolean | Result indicating whether the matrix is an identity matrix. The value **true** means that the matrix is an identity matrix, and **false** means the opposite.| +| Boolean | Check result. The value **true** means that the matrix is an identity matrix, and **false** means the opposite.| **Example** @@ -8062,7 +8335,7 @@ console.info("matrix"+matrix.getAll().toString()); preTranslate(dx: number, dy: number): void -Premultiplies a matrix by a matrix that is derived from an identity matrix after it has been translated by a given distance (dx, dy). +Premultiplies this matrix by a matrix that is derived from an identity matrix after it has been translated by a given distance (dx, dy). **System capability**: SystemCapability.Graphics.Drawing @@ -8195,7 +8468,7 @@ Sets the destination rectangle to the bounding rectangle of the shape obtained a | Type | Description | | --------------------- | -------------- | -| boolean | Result indicating whether the shape, transformed from the source rectangle via a matrix transformation, retains a rectangular form. The value **true** means that the shape retains a rectangular form, and **false** means the opposite.| +| boolean | Check result. The value **true** means that the shape retains a rectangular form, and **false** means the opposite.| **Error codes** @@ -8237,7 +8510,7 @@ Sets this matrix to a transformation matrix that maps a source rectangle to a de | Type | Description | | --------------------- | -------------- | -| boolean | Result indicating whether the matrix can represent the mapping between rectangles. The value **true** means that the matrix can represent the mapping, and **false** means the opposite. In particular, if either the width or the height of the source rectangle is less than or equal to 0, the API returns **false** and sets the matrix to an identity matrix. If either the width or height of the destination rectangle is less than or equal to 0, the API returns **true** and sets the matrix to a matrix with all values 0, except for a perspective scaling coefficient of 1.| +| boolean | Check result. The value **true** means that the matrix can represent the mapping, and **false** means the opposite. In particular, if either the width or the height of the source rectangle is less than or equal to 0, the API returns **false** and sets the matrix to an identity matrix. If either the width or height of the destination rectangle is less than or equal to 0, the API returns **true** and sets the matrix to a matrix with all values 0, except for a perspective scaling coefficient of 1.| **Error codes** @@ -8264,7 +8537,7 @@ if (matrix.setRectToRect(src, dst, scaleToFit)) { setPolyToPoly(src: Array\, dst: Array\, count: number): boolean -Sets this matrix to a transformation matrix that maps the source point array to the destination point array. +Sets this matrix to a transformation matrix that maps the source point array to the destination point array. Both the number of source points and that of destination points must be in the range [0, 4]. **System capability**: SystemCapability.Graphics.Drawing @@ -8280,7 +8553,7 @@ Sets this matrix to a transformation matrix that maps the source point array to | Type | Description | | --------------------- | -------------- | -| boolean | Result indicating whether the setting is successful. The value **true** means that the setting is successful, and **false** means the opposite.| +| boolean | Check result. The value **true** means that the setting is successful, and **false** means the opposite.| **Error codes** @@ -8351,8 +8624,8 @@ Sets the radii of the specified rounded corner in this rounded rectangle. | Name | Type | Mandatory| Description | | -------- | -------------------------------------------- | ---- | ------------------------------- | | pos | [CornerPos](#cornerpos12) | Yes | Position of the rounded corner. | -| x | number | Yes | Radius of the rounded corner on the X axis. The value is a floating point number.| -| y | number | Yes | Radius of the rounded corner on the Y axis. The value is a floating point number.| +| x | number | Yes | Radius of the rounded corner on the X axis. The value is a floating point number. A negative number is invalid.| +| y | number | Yes | Radius of the rounded corner on the Y axis. The value is a floating point number. A negative number is invalid.| **Error codes** @@ -8462,7 +8735,7 @@ Checks whether a point is contained in this region. | Type | Description | | ------- | -------------- | -| boolean | Result indicating whether the point is contained in the region. The value **true** means that the point is contained, and **false** means the opposite.| +| boolean | Check result. The value **true** means that the point is contained, and **false** means the opposite.| **Error codes** @@ -8476,6 +8749,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts import { RenderNode } from '@kit.ArkUI'; +import { drawing } from '@kit.ArkGraphics2D'; class DrawingRenderNode extends RenderNode { draw(context : DrawContext) { const canvas = context.canvas; @@ -8513,7 +8787,7 @@ Checks whether another region is contained in this region. | Type | Description | | ------- | -------------- | -| boolean | Result indicating whether the other region is contained in the current region. The value **true** means that the other region is contained, and **false** means the opposite.| +| boolean | Check result. The value **true** means that the other region is contained, and **false** means the opposite.| **Error codes** @@ -8527,6 +8801,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts import { RenderNode } from '@kit.ArkUI'; +import { drawing } from '@kit.ArkGraphics2D'; class DrawingRenderNode extends RenderNode { draw(context : DrawContext) { const canvas = context.canvas; @@ -8567,7 +8842,7 @@ Performs an operation on this region and another region, and stores the resultin | Type | Description | | ------- | -------------- | -| boolean | Result indicating whether the resulting region is stored in the current **Region** object. The value **true** means that the resulting region is stored in the current **Region** object, and **false** means the opposite.| +| boolean | Check result. The value **true** means that the resulting region is stored in the current **Region** object, and **false** means the opposite.| **Error codes** @@ -8581,6 +8856,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts import { RenderNode } from '@kit.ArkUI'; +import { drawing } from '@kit.ArkGraphics2D'; class DrawingRenderNode extends RenderNode { draw(context : DrawContext) { const canvas = context.canvas; @@ -8636,6 +8912,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts import { RenderNode } from '@kit.ArkUI'; +import { drawing } from '@kit.ArkGraphics2D'; class DrawingRenderNode extends RenderNode { draw(context : DrawContext) { const canvas = context.canvas; @@ -8687,6 +8964,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts import { RenderNode } from '@kit.ArkUI'; +import { drawing } from '@kit.ArkGraphics2D'; class DrawingRenderNode extends RenderNode { draw(context : DrawContext) { const canvas = context.canvas; @@ -8742,6 +9020,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ ```ts import { RenderNode } from '@kit.ArkUI'; +import { drawing } from '@kit.ArkGraphics2D'; class DrawingRenderNode extends RenderNode { draw(context : DrawContext) { const canvas = context.canvas; @@ -8857,7 +9136,7 @@ import { common2D,drawing } from '@kit.ArkGraphics2D'; let startPt: common2D.Point = { x: 100, y: 100 }; let endPt: common2D.Point = { x: 300, y: 300 }; -let shaderEffect =drawing.ShaderEffect.createLinearGradient(startPt, endPt, [0xFF00FF00, 0xFFFF0000], drawing.TileMode.REPEAT); +let shaderEffect = drawing.ShaderEffect.createLinearGradient(startPt, endPt, [0xFF00FF00, 0xFFFF0000], drawing.TileMode.REPEAT); ``` ### createRadialGradient12+ @@ -9005,11 +9284,11 @@ let endPt: common2D.Point = {x: 200, y: 200}; let shaderEffect = drawing.ShaderEffect.createConicalGradient(startPt, 100, endPt, 50, [0xFF00FF00, 0xFFFF0000], drawing.TileMode.REPEAT); ``` -## Tool16+ +## Tool15+ A utility class that provides only static methods to convert data structs defined in other modules and [common2D](js-apis-graphics-common2D.md). -### makeColorFromResourceColor16+ +### makeColorFromResourceColor15+ static makeColorFromResourceColor(resourceColor: ResourceColor): common2D.Color diff --git a/en/application-dev/reference/apis-arkgraphics2d/js-apis-graphics-text.md b/en/application-dev/reference/apis-arkgraphics2d/js-apis-graphics-text.md index 53d29be923a0d2d95d92aa9cec985ea50af7b0d1..a8eaa49ce7fe165b8fe95af419ac9628749337df 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/js-apis-graphics-text.md +++ b/en/application-dev/reference/apis-arkgraphics2d/js-apis-graphics-text.md @@ -8,7 +8,7 @@ This module provides the following classes: - [FontCollection](#fontcollection): font manager, which controls various fonts. - [ParagraphStyle](#paragraphstyle): paragraph style, which controls the display style of a paragraph. - [Paragraph](#paragraph): paragraph, which is constructed by calling [build()](#build) in the **ParagraphBuilder** class. -- [LineTypeset](#linetypeset16): line typesetter, which is constructed by calling [buildLineTypeset()](#buildlinetypeset16) in the **ParagraphBuilder** class. +- [LineTypeset](#linetypeset18): line typesetter, which is constructed by calling [buildLineTypeset()](#buildlinetypeset18) in the **ParagraphBuilder** class. - [ParagraphBuilder](#paragraphbuilder): paragraph builder, which controls the generation of different paragraph objects. - [TextLine](#textline): carrier of the paragraph text in lines. It is obtained by calling [getTextLines()](#gettextlines) in the **Paragraph** class. - [Run](#run): rendering unit used for text typesetting. It is obtained by calling [getGlyphRuns()](#getglyphruns) in the **TextLine** class. @@ -23,7 +23,7 @@ This module provides the following classes: import { text } from '@kit.ArkGraphics2D'; ``` -## text.matchFontDescriptors16+ +## text.matchFontDescriptors18+ matchFontDescriptors(desc: FontDescriptor): Promise<Array<FontDescriptor>> @@ -262,11 +262,12 @@ Enumerates the word break types. **System capability**: SystemCapability.Graphics.Drawing -| Name | Value | Description | -| ----------- | ---- | -------------------------------------------------------------------------------------------------------------------- | -| NORMAL | 0 | Default mode. Word breaks are allowed between words as appropriate to the relevant language writing systems. | -| BREAK_ALL | 1 | Word breaks are allowed between any characters for non-CJK text. (CJK means Chinese, Japanese, and Korean.) This value is suitable for Asian text that contains some non-Asian text. For example, it can be used to break consecutive English characters.| -| BREAK_WORD | 2 | Works in the same way as **BREAK_ALL**, except that it does not break unbreakable words. | +| Name | Value | Description | +|-----------------------------| ---- | -------------------------------------------------------------------------------------------------------------------- | +| NORMAL | 0 | Default mode. Word breaks are allowed between words as appropriate to the relevant language writing systems. | +| BREAK_ALL | 1 | Word breaks are allowed between any characters for non-CJK text. (CJK means Chinese, Japanese, and Korean.) This value is suitable for Asian text that contains some non-Asian text. For example, it can be used to break consecutive English characters.| +| BREAK_WORD | 2 | Works in the same way as **BREAK_ALL**, except that it does not break unbreakable words. | +| BREAK_HYPHEN18+ | 3 | Uses a hyphen (-) to break a word at the end of each line. If adding a hyphen is not possible, it will behave the same as **BREAK_WORD**. | ## Decoration @@ -367,7 +368,7 @@ Enumerates the text height modifier patterns. | ALL | 0x0 | Enables ascent for the first and last rows of a paragraph. | | DISABLE_FIRST_ASCENT | 0x1 | Disables ascent for the first row of a paragraph. | | DISABLE_LAST_ASCENT | 0x2 | Disables ascent for the last row of a paragraph. | -| DISABLE_ALL | 0x3 | Disables ascent for the first and last rows of a paragraph. | +| DISABLE_ALL | 0x1 \| 0x2 | Disables ascent for the first and last rows of a paragraph. | ## TextBaseline @@ -504,7 +505,7 @@ Describes the font descriptor information. | fullName | string | No| Yes| Font name. Any value is acceptable. The default value is an empty string.| | fontFamily | string | No| Yes| Family name of the font. Any value is acceptable. The default value is an empty string.| | fontSubfamily | string | No| Yes| Subfamily name of the font. Any value is acceptable. The default value is an empty string.| -| weight | [FontWeight](#fontweight) | No| Yes| Font weight. The default value is the value of **FontWeight.W100**, that is, **0**. In [matchFontDescriptors](#textmatchfontdescriptors16), omitting this parameter is equivalent to setting it to its default value.| +| weight | [FontWeight](#fontweight) | No| Yes| Font weight. The default value is the value of **FontWeight.W100**, that is, **0**. In [matchFontDescriptors](#textmatchfontdescriptors18), omitting this parameter is equivalent to setting it to its default value.| | width | number | No| Yes| Font width. The value is an integer ranging from 1 to 9. The default value is **0**.| | italic | number | No| Yes| Whether the font is italic. The value **0** means that the font is not italic, and **1** means the opposite. The default value is **0**.| | monoSpace | boolean | No| Yes| Whether the font is monospaced. The value **true** means that the font is monospaced, and **false** means the opposite. The default value is **false**.| @@ -602,7 +603,7 @@ struct RenderTest { } ``` -### loadFont16+ +### loadFont18+ loadFont(name: string, path: string | Resource): Promise\ @@ -702,7 +703,7 @@ Describes a paragraph style. | breakStrategy | [BreakStrategy](#breakstrategy) | Yes | Yes | Text break strategy. The default value is **GREEDY**. | | strutStyle | [StrutStyle](#strutstyle) | Yes | Yes | Strut style. The default value is the initial **StrutStyle** object. | | textHeightBehavior | [TextHeightBehavior](#textheightbehavior) | Yes | Yes | Text height modifier pattern. The default value is **ALL**. | -| tab16+ | [TextTab](#texttab16) | Yes | Yes | Alignment mode and position of the text after the tab character in a paragraph. By default, the tab character is replaced with a space. This parameter does not take effect when it is configured together with the text alignment mode (specified by **align**) or ellipsis content (specified by **ellipsis** in [TextStyle](#textstyle)).| +| tab18+ | [TextTab](#texttab18) | Yes | Yes | Alignment mode and position of the text after the tab character in a paragraph. By default, the tab character is replaced with a space. This parameter does not take effect when it is configured together with the text alignment mode (specified by **align**) or ellipsis content (specified by **ellipsis** in [TextStyle](#textstyle)).| ## PlaceholderAlignment @@ -779,7 +780,7 @@ Performs typography and calculates the positions of all glyphs. paragraph.layoutSync(100); ``` -### layout16+ +### layout18+ layout(width: number): Promise\ @@ -1388,13 +1389,13 @@ Obtains the line measurement information of a line. let lineMetrics = paragraph.getLineMetrics(0); ``` -## LineTypeset16+ +## LineTypeset18+ Implements a carrier that stores the text content and style. It can be used to compute typography details for individual lines of text. -Before calling any of the following APIs, you must use [buildLineTypeset()](#buildlinetypeset16) in the [ParagraphBuilder](#paragraphbuilder) class to create a **LineTypeset** object. +Before calling any of the following APIs, you must use [buildLineTypeset()](#buildlinetypeset18) in the [ParagraphBuilder](#paragraphbuilder) class to create a **LineTypeset** object. -### getLineBreak16+ +### getLineBreak18+ getLineBreak(startIndex: number, width: number): number @@ -1431,7 +1432,7 @@ let width = 100.0; let count = lineTypeset.getLineBreak(startIndex, width); ``` -### createLine16+ +### createLine18+ createLine(startIndex: number, count: number): TextLine @@ -1444,7 +1445,7 @@ Generates a text line object based on the specified layout range. | Name| Type | Mandatory| Description | | ----- | ------ | ---- | -------------- | | startIndex | number | Yes| Start position for layout calculation. The value is an integer in the range [0, total number of text characters).| -| count | number | Yes | Number of characters from the specified start position. The value is an integer in the range [0, total number of text characters). The sum of **startIndex** and **count** cannot be greater than the total number of text characters. When **count** is **0**, the specified range is [startIndex, end of the text]. You can use [getLineBreak](#getlinebreak16) to obtain the number of characters that can fit in the layout.| +| count | number | Yes | Number of characters from the specified start position. The value is an integer in the range [0, total number of text characters). The sum of **startIndex** and **count** cannot be greater than the total number of text characters. When **count** is **0**, the specified range is [startIndex, end of the text]. You can use [getLineBreak](#getlinebreak18) to obtain the number of characters that can fit in the layout.| **Return value** @@ -1860,7 +1861,7 @@ struct Index { } ``` -### buildLineTypeset16+ +### buildLineTypeset18+ buildLineTypeset(): LineTypeset @@ -1872,7 +1873,7 @@ Builds a line typesetter. | Type | Description | | ------------------------ | ------------------------------ | -| [LineTypeset](#linetypeset16) | **LineTypeset** object.| +| [LineTypeset](#linetypeset18) | **LineTypeset** object.| **Example** @@ -1915,7 +1916,7 @@ Inserts a symbol into the paragraph being built. | Name | Type | Mandatory| Description | | -------- | ------- | ---- | ----------------------------------------------------------- | -| symbolId | number | Yes | Symbol code to insert. The value is a hexadecimal number in the range 0xF0000-0xF0C97. For details about the configurable symbol codes and symbol names, see the **value** and **name** fields in the [JSON file](https://gitee.com/openharmony/global_system_resources/blob/master/systemres/main/resources/base/element/symbol.json).| +| symbolId | number | Yes | Symbol code to insert. The value is a hexadecimal number in the range 0xF0000-0xF0C97. For details about the configurable symbol codes (unicode values in the list view), see [HarmonyOS Symbol](https://developer.huawei.com/consumer/cn/design/harmonyos-symbol/).| **Example** @@ -1951,7 +1952,7 @@ struct Index { } ``` -## TypographicBounds16+ +## TypographicBounds18+ Describes the typographic boundary of a text line. The typographic boundary is related to the font and font size used for typography, but not the characters within the text. For example, for the string " a b " (which has a space before "a" and a space after "b"), the typographic boundary encompasses the spaces at the beginning and end. For the strings "j" and "E", the typographic boundaries are the same, indicating that they are irrelevant to specific characters. @@ -1978,7 +1979,7 @@ Describes the typographic boundary of a text line. The typographic boundary is r > >![image_TypographicBounds_Character.png](figures/image_TypographicBounds_Character.png) -## CaretOffsetsCallback16+ +## CaretOffsetsCallback18+ type CaretOffsetsCallback = (offset: number, index: number, leadingEdge: boolean) => boolean @@ -2003,7 +2004,7 @@ Defines the callback used to receive the offset and index of each character in a Implements a carrier that describes the basic text line structure of a paragraph. -Before calling any of the following APIs, you must use [getTextLines ()](#gettextlines) of the [Paragraph](#paragraph) class or [createLine()](#createline16) of the [LineTypeset](#linetypeset16) class to create a **TextLine** object. +Before calling any of the following APIs, you must use [getTextLines()](#gettextlines) of the [Paragraph](#paragraph) class or [createLine()](#createline18) of the [LineTypeset](#linetypeset18) class to create a **TextLine** object. ### getGlyphCount getGlyphCount(): number @@ -2045,7 +2046,7 @@ struct Index { getTextRange(): Range -Obtains the range of the text in this text line in the entire paragraph. The [TextLine](#textline) object created by calling [creatLine](#createline16) of the [LineTypeset](#linetypeset16) class is a temporary object and is automatically destroyed when [creatLine](#createline16) is called next time. Therefore, the index range returned by [getTextRange] through this object is relative to a temporary [Paragraph](#paragraph) object. +Obtains the range of the text in this text line in the entire paragraph. The [TextLine](#textline) object created by calling [creatLine](#createline18) of the [LineTypeset](#linetypeset18) class is a temporary object and is automatically destroyed when [creatLine](#createline18) is called next time. Therefore, the index range returned by [getTextRange] through this object is relative to a temporary [Paragraph](#paragraph) object. **System capability**: SystemCapability.Graphics.Drawing @@ -2165,7 +2166,7 @@ struct Index { } ``` -### createTruncatedLine16+ +### createTruncatedLine18+ createTruncatedLine(width: number, ellipsisMode: EllipsisMode, ellipsis: string): TextLine @@ -2228,7 +2229,7 @@ struct Index { } ``` -### getTypographicBounds16+ +### getTypographicBounds18+ getTypographicBounds(): TypographicBounds @@ -2250,7 +2251,7 @@ Obtains the typographic boundary of this text line. The typographic boundary is | Type| Description | | -| - | -| [TypographicBounds](#typographicbounds16) | Typographic boundary of the text line.| +| [TypographicBounds](#typographicbounds18) | Typographic boundary of the text line.| **Example** @@ -2276,7 +2277,7 @@ struct Index { } ``` -### getImageBounds16+ +### getImageBounds18+ getImageBounds(): common2D.Rect @@ -2325,7 +2326,7 @@ struct Index { } ``` -### getTrailingSpaceWidth16+ +### getTrailingSpaceWidth18+ getTrailingSpaceWidth(): number @@ -2363,7 +2364,7 @@ struct Index { } ``` -### getStringIndexForPosition16+ +### getStringIndexForPosition18+ getStringIndexForPosition(point: common2D.Point): number @@ -2416,7 +2417,7 @@ struct Index { } ``` -### getOffsetForStringIndex16+ +### getOffsetForStringIndex18+ getOffsetForStringIndex(index: number): number @@ -2468,7 +2469,7 @@ struct Index { } ``` -### enumerateCaretOffsets16+ +### enumerateCaretOffsets18+ enumerateCaretOffsets(callback: CaretOffsetsCallback): void @@ -2480,7 +2481,7 @@ Enumerates the offset and index of each character in a text line. | Name| Type| Mandatory| Description| | -| - | - | - | -| callback | [CaretOffsetsCallback](#caretoffsetscallback16) | Yes| Custom function, which is used to receive the offset and index of each character in a text line object as its parameters.| +| callback | [CaretOffsetsCallback](#caretoffsetscallback18) | Yes| Custom function, which is used to receive the offset and index of each character in a text line object as its parameters.| **Error codes** @@ -2518,7 +2519,7 @@ struct Index { } ``` -### getAlignmentOffset16+ +### getAlignmentOffset18+ getAlignmentOffset(alignmentFactor: number, alignmentWidth: number): number @@ -2651,7 +2652,7 @@ struct Index { } ``` -### getGlyphs16+ +### getGlyphs18+ getGlyphs(range: Range): Array\ @@ -2685,7 +2686,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ import { text } from "@kit.ArkGraphics2D" function textFunc() { - let glyphs = runs[0].getGlyphs (); // Obtain the index of all glyphs of the run. + let glyphs = runs[0].getGlyphs(); // Obtain the index of all glyphs of the run. let glyphsRange = runs[0].getGlyphs ({start:1, end:2}); // Obtain the indices of glyphs in the range starting from position 1, with a length of 2. glyphsRange = runs[0].getGlyphs({start:-1, end:2}); // -1 is an invalid value, and undefined is returned. glyphsRange = runs[0].getGlyphs({start:0, end:-10}); // -10 is an invalid value, and undefined is returned. @@ -2727,7 +2728,7 @@ Obtains the position of each glyph relative to the respective line in this run. import { text } from "@kit.ArkGraphics2D"; function textFunc() { - let positions = runs[0].getPositions (); // Obtain the positions of all glyphs in the run. + let positions = runs[0].getPositions(); // Obtain the positions of all glyphs in the run. } @Entry @@ -2743,7 +2744,7 @@ struct Index { } } ``` -### getPositions16+ +### getPositions18+ getPositions(range: Range): Array @@ -2898,29 +2899,33 @@ import { text } from "@kit.ArkGraphics2D" import { common2D } from "@kit.ArkGraphics2D" import { image } from '@kit.ImageKit'; -function textFunc() { - const color: ArrayBuffer = new ArrayBuffer(160000); - let opts: image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 200, width: 200 } } - let pixelMap: image.PixelMap = image.createPixelMapSync(color, opts); - let canvas = new drawing.Canvas(pixelMap); +function textFunc(pixelmap: PixelMap) { + let canvas = new drawing.Canvas(pixelmap); runs[0].paint(canvas, 0, 0); } @Entry @Component struct Index { + @State pixelmap?: PixelMap = undefined; fun: Function = textFunc; build() { Column() { + Image(this.pixelmap).width(200).height(200); Button().onClick(() => { - this.fun(); + if (this.pixelmap == undefined) { + const color: ArrayBuffer = new ArrayBuffer(160000); + let opts: image.InitializationOptions = { editable: true, pixelFormat: 3, size: { height: 200, width: 200 } } + this.pixelmap = image.createPixelMapSync(color, opts); + } + this.fun(this.pixelmap); }) } } } ``` -### getStringRange16+ +### getStringRange18+ getStringRange(): Range @@ -2960,7 +2965,7 @@ struct Index { } ``` -### getStringIndices16+ +### getStringIndices18+ getStringIndices(range?: Range): Array\ @@ -2994,7 +2999,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ import { text } from "@kit.ArkGraphics2D"; function textFunc() { - let indices = runs[0].getStringIndices (); // Obtain the indices of all characters in the run. + let indices = runs[0].getStringIndices(); // Obtain the indices of all characters in the run. let indicesRange = runs[0].getStringIndices({start:1, end:2}); // Obtain the indices of characters in the range starting from position 1, with a length of 2. indicesRange = runs[0].getStringIndices({start:-1, end:2}); // -1 is an invalid value, and undefined is returned. indicesRange = runs[0].getStringIndices({start:0, end:-10}); // -10 is an invalid value, and undefined is returned. @@ -3016,7 +3021,7 @@ struct Index { } ``` -### getImageBounds16+ +### getImageBounds18+ getImageBounds(): common2D.Rect @@ -3063,7 +3068,7 @@ struct Index { } ``` -### getTypographicBounds16+ +### getTypographicBounds18+ getTypographicBounds(): TypographicBounds @@ -3085,7 +3090,7 @@ Obtain a typographic boundary of this run. The typographic boundary is related t | Type | Description | | ---------------------- | -------------- | -| [TypographicBounds](#typographicbounds16) | Typographic boundary of the run.| +| [TypographicBounds](#typographicbounds18) | Typographic boundary of the run.| **Example** @@ -3110,7 +3115,7 @@ struct Index { } ``` -## TextTab16+ +## TextTab18+ Implements a paragraph-style text tab, which stores the alignment mode and position. @@ -3147,4 +3152,4 @@ Enumerates the font types, which can be combined through bitwise OR operations. | GENERIC | 1 << 1 | System font type.| | STYLISH | 1 << 2 | Style font type. The style font type is designed for 2-in-1 devices.| | INSTALLED | 1 << 3 | Font type that has been installed.| -| CUSTOMIZED16+ | 1 << 4 | Custom font type.| +| CUSTOMIZED18+ | 1 << 4 | Custom font type.| diff --git a/en/application-dev/reference/apis-arkgraphics2d/js-apis-uiEffect-sys.md b/en/application-dev/reference/apis-arkgraphics2d/js-apis-uiEffect-sys.md index b5ff5c61f7d0761f32b0b6bda691121b1e51fe93..ae51922cc84340fc526db881282aad2a568ed1d0 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/js-apis-uiEffect-sys.md +++ b/en/application-dev/reference/apis-arkgraphics2d/js-apis-uiEffect-sys.md @@ -99,6 +99,14 @@ Applies the ripple effect onto the component. | ----------------- | --------------------------------- | | [Filter](#filter) | **Filter** instance with the ripple effect.| +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 202 | Permission verification failed. A non-system application calls a system API. | + **Example** ```ts @@ -127,6 +135,14 @@ Applies fly-in and fly-out animations onto the component. | ----------------- | --------------------------------- | | [Filter](#filter) | **Filter** instance with the fly-in and fly-out animations.| +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 202 | Permission verification failed. A non-system application calls a system API. | + **Example** ```ts diff --git a/en/application-dev/reference/apis-arkgraphics2d/native__buffer_8h.md b/en/application-dev/reference/apis-arkgraphics2d/native__buffer_8h.md index 6ace9f0af340b98758650a745718b9b740957811..02be42673a63ac38938aee58fd017a2d91aa7d61 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/native__buffer_8h.md +++ b/en/application-dev/reference/apis-arkgraphics2d/native__buffer_8h.md @@ -20,67 +20,53 @@ The **native_buffer.h** file declares the functions for obtaining and using **Na ### Structs -| Name| Description| +| Name| Description| | -------- | -------- | -| struct [OH_NativeBuffer_Config](_o_h___native_buffer___config.md) | Describes the **OH_NativeBuffer** attribute configuration, which is used when you apply for a new **OH_NativeBuffer** instance or query the attributes of an existing instance.| -| struct [OH_NativeBuffer_Plane](_o_h___native_buffer___plane.md) | Describes the plane information of an image.| -| struct [OH_NativeBuffer_Planes](_o_h___native_buffer___planes.md) | Describes the plane information of images in an **OH_NativeBuffer** instance.| -| struct [OH_NativeBuffer_ColorXY](_o_h___native_buffer___color_x_y.md) | Describes the X and Y coordinates of the primary color.| -| struct [OH_NativeBuffer_Smpte2086](_o_h___native_buffer___smpte2086.md) | Describes the SMPTE ST 2086 static metadata.| -| struct [OH_NativeBuffer_Cta861](_o_h___native_buffer___cta861.md) | Describes the CTA-861.3 static metadata.| -| struct [OH_NativeBuffer_StaticMetadata](_o_h___native_buffer___static_metadata.md) | Describes the HDR static metadata.| +| struct [OH_NativeBuffer_Config](_o_h___native_buffer___config.md) | Describes the **OH_NativeBuffer** property configuration, which is used when you apply for a new **OH_NativeBuffer** instance or query the properties of an existing instance. | +| struct [OH_NativeBuffer_Plane](_o_h___native_buffer___plane.md) | Describes the plane information of an image. | +| struct [OH_NativeBuffer_Planes](_o_h___native_buffer___planes.md) | Describes the plane information of images in an **OH_NativeBuffer** instance. | ### Types -| Name| Description| +| Name| Description| | -------- | -------- | -| typedef struct [OH_NativeBuffer](_o_h___native_buffer.md#oh_nativebuffer) [OH_NativeBuffer](_o_h___native_buffer.md#oh_nativebuffer) | Provides the declaration of an **OH_NativeBuffer** struct.| -| typedef enum [OH_NativeBuffer_Usage](_o_h___native_buffer.md#oh_nativebuffer_usage-1) [OH_NativeBuffer_Usage](_o_h___native_buffer.md#oh_nativebuffer_usage) | Defines an enum for the **OH_NativeBuffer** usages.| -| typedef enum [OH_NativeBuffer_Format](_o_h___native_buffer.md#oh_nativebuffer_format-1) [OH_NativeBuffer_Format](_o_h___native_buffer.md#oh_nativebuffer_format) | Defines an enum for the **OH_NativeBuffer** formats.| -| typedef enum [OH_NativeBuffer_ColorSpace](_o_h___native_buffer.md#oh_nativebuffer_colorspace-1) [OH_NativeBuffer_ColorSpace](_o_h___native_buffer.md#oh_nativebuffer_colorspace) | Defines an enum for the color spaces of an **OH_NativeBuffer** instance.| -| typedef enum [OH_NativeBuffer_TransformType](_o_h___native_buffer.md#oh_nativebuffer_transformtype-1) [OH_NativeBuffer_TransformType](_o_h___native_buffer.md#oh_nativebuffer_transformtype) | Defines an enum for the transform types of an **OH_NativeBuffer** instance.| -| typedef enum [OH_NativeBuffer_ColorGamut](_o_h___native_buffer.md#oh_nativebuffer_colorgamut-1) [OH_NativeBuffer_ColorGamut](_o_h___native_buffer.md#oh_nativebuffer_colorgamut) | Defines an enum for the color gamuts of an **OH_NativeBuffer** instance.| -| typedef enum [OHNativeErrorCode](_native_window.md#ohnativeerrorcode-1) [OHNativeErrorCode](_o_h___native_buffer.md#ohnativeerrorcode) | Defines an enum for the error codes.| -| typedef struct [OH_NativeBuffer_Config](_o_h___native_buffer___config.md) [OH_NativeBuffer_Config](_o_h___native_buffer.md#oh_nativebuffer_config) | Describes the **OH_NativeBuffer** attribute configuration, which is used when you apply for a new **OH_NativeBuffer** instance or query the attributes of an existing instance.| -| typedef struct [OH_NativeBuffer_Plane](_o_h___native_buffer___plane.md) [OH_NativeBuffer_Plane](_o_h___native_buffer.md#oh_nativebuffer_plane) | Defines a struct for the plane information of an image.| -| typedef struct [OH_NativeBuffer_Planes](_o_h___native_buffer___planes.md) [OH_NativeBuffer_Planes](_o_h___native_buffer.md#oh_nativebuffer_planes) | Defines a struct for the plane information of images in an **OH_NativeBuffer** instance.| -| typedef enum [OH_NativeBuffer_MetadataType](_o_h___native_buffer.md#oh_nativebuffer_metadatatype-1) [OH_NativeBuffer_MetadataType](_o_h___native_buffer.md#oh_nativebuffer_metadatatype) | Defines an enum for the **OH_NativeBuffer** image standards.| -| typedef struct [OH_NativeBuffer_ColorXY](_o_h___native_buffer___color_x_y.md) [OH_NativeBuffer_ColorXY](_o_h___native_buffer.md#oh_nativebuffer_colorxy) | Defines a struct for the X and Y coordinates of the primary color.| -| typedef struct [OH_NativeBuffer_Smpte2086](_o_h___native_buffer___smpte2086.md) [OH_NativeBuffer_Smpte2086](_o_h___native_buffer.md#oh_nativebuffer_smpte2086) | Defines a struct for the SMPTE ST 2086 static metadata.| -| typedef struct [OH_NativeBuffer_Cta861](_o_h___native_buffer___cta861.md) [OH_NativeBuffer_Cta861](_o_h___native_buffer.md#oh_nativebuffer_cta861) | Defines a struct for the CTA-861.3 static metadata.| -| typedef struct [OH_NativeBuffer_StaticMetadata](_o_h___native_buffer___static_metadata.md) [OH_NativeBuffer_StaticMetadata](_o_h___native_buffer.md#oh_nativebuffer_staticmetadata) | Defines a struct for the HDR static metadata.| -| typedef enum [OH_NativeBuffer_MetadataKey](_o_h___native_buffer.md#oh_nativebuffer_metadatakey-1) [OH_NativeBuffer_MetadataKey](_o_h___native_buffer.md#oh_nativebuffer_metadatakey) | Defines an enum for the keys that specify the HDR metadata of an **OH_NativeBuffer** instance.| +| typedef struct [OH_NativeBuffer](_o_h___native_buffer.md#oh_nativebuffer) [OH_NativeBuffer](_o_h___native_buffer.md#oh_nativebuffer) | Provides the declaration of an **OH_NativeBuffer** struct. | +| typedef enum [OH_NativeBuffer_Usage](_o_h___native_buffer.md#oh_nativebuffer_usage) [OH_NativeBuffer_Usage](_o_h___native_buffer.md#oh_nativebuffer_usage) | Defines an enum for the **OH_NativeBuffer** usages. | +| typedef enum [OH_NativeBuffer_Format](_o_h___native_buffer.md#oh_nativebuffer_format) [OH_NativeBuffer_Format](_o_h___native_buffer.md#oh_nativebuffer_format) | Defines an enum for the **OH_NativeBuffer** formats. | +| typedef enum [OH_NativeBuffer_TransformType](_o_h___native_buffer.md#oh_nativebuffer_transformtype) [OH_NativeBuffer_TransformType](_o_h___native_buffer.md#oh_nativebuffer_transformtype) | Defines an enum for the transform types of an **OH_NativeBuffer** instance. | +| typedef enum [OH_NativeBuffer_ColorGamut](_o_h___native_buffer.md#oh_nativebuffer_colorgamut) [OH_NativeBuffer_ColorGamut](_o_h___native_buffer.md#oh_nativebuffer_colorgamut) | Defines an enum for the color gamuts of an **OH_NativeBuffer** instance. | +| typedef enum [OHNativeErrorCode](_o_h___native_buffer.md#ohnativeerrorcode) [OHNativeErrorCode](_o_h___native_buffer.md#ohnativeerrorcode) | Defines an enum for the error codes. | +| typedef struct [OH_NativeBuffer_Config](_o_h___native_buffer___config.md) [OH_NativeBuffer_Config](_o_h___native_buffer.md#oh_nativebuffer_config) | Defines the **OH_NativeBuffer** property configuration, which is used when you apply for a new **OH_NativeBuffer** instance or query the properties of an existing instance. | +| typedef struct [OH_NativeBuffer_Plane](_o_h___native_buffer___plane.md) [OH_NativeBuffer_Plane](_o_h___native_buffer.md#oh_nativebuffer_plane) | Defines a struct for the plane information of an image. | +| typedef struct [OH_NativeBuffer_Planes](_o_h___native_buffer___planes.md) [OH_NativeBuffer_Planes](_o_h___native_buffer.md#oh_nativebuffer_planes) | Defines a struct for the plane information of images in an **OH_NativeBuffer** instance. | ### Enums -| Name| Description| +| Name| Description| | -------- | -------- | -| [OH_NativeBuffer_Usage](_o_h___native_buffer.md#oh_nativebuffer_usage-1) {
NATIVEBUFFER_USAGE_CPU_READ = (1ULL << 0), NATIVEBUFFER_USAGE_CPU_WRITE = (1ULL << 1), NATIVEBUFFER_USAGE_MEM_DMA = (1ULL << 3), NATIVEBUFFER_USAGE_HW_RENDER = (1ULL << 8),
NATIVEBUFFER_USAGE_HW_TEXTURE = (1ULL << 9), NATIVEBUFFER_USAGE_CPU_READ_OFTEN = (1ULL << 16), NATIVEBUFFER_USAGE_ALIGNMENT_512 = (1ULL << 18)
} | Enumerates the **OH_NativeBuffer** usages.| -| [OH_NativeBuffer_Format](_o_h___native_buffer.md#oh_nativebuffer_format-1) {
NATIVEBUFFER_PIXEL_FMT_CLUT8 = 0, NATIVEBUFFER_PIXEL_FMT_CLUT1, NATIVEBUFFER_PIXEL_FMT_CLUT4, NATIVEBUFFER_PIXEL_FMT_RGB_565 = 3,
NATIVEBUFFER_PIXEL_FMT_RGBA_5658, NATIVEBUFFER_PIXEL_FMT_RGBX_4444, NATIVEBUFFER_PIXEL_FMT_RGBA_4444, NATIVEBUFFER_PIXEL_FMT_RGB_444,
NATIVEBUFFER_PIXEL_FMT_RGBX_5551, NATIVEBUFFER_PIXEL_FMT_RGBA_5551, NATIVEBUFFER_PIXEL_FMT_RGB_555, NATIVEBUFFER_PIXEL_FMT_RGBX_8888,
NATIVEBUFFER_PIXEL_FMT_RGBA_8888, NATIVEBUFFER_PIXEL_FMT_RGB_888, NATIVEBUFFER_PIXEL_FMT_BGR_565, NATIVEBUFFER_PIXEL_FMT_BGRX_4444,
NATIVEBUFFER_PIXEL_FMT_BGRA_4444, NATIVEBUFFER_PIXEL_FMT_BGRX_5551, NATIVEBUFFER_PIXEL_FMT_BGRA_5551, NATIVEBUFFER_PIXEL_FMT_BGRX_8888,
NATIVEBUFFER_PIXEL_FMT_BGRA_8888, NATIVEBUFFER_PIXEL_FMT_YUV_422_I, NATIVEBUFFER_PIXEL_FMT_YCBCR_422_SP, NATIVEBUFFER_PIXEL_FMT_YCRCB_422_SP,
NATIVEBUFFER_PIXEL_FMT_YCBCR_420_SP, NATIVEBUFFER_PIXEL_FMT_YCRCB_420_SP, NATIVEBUFFER_PIXEL_FMT_YCBCR_422_P, NATIVEBUFFER_PIXEL_FMT_YCRCB_422_P,
NATIVEBUFFER_PIXEL_FMT_YCBCR_420_P, NATIVEBUFFER_PIXEL_FMT_YCRCB_420_P, NATIVEBUFFER_PIXEL_FMT_YUYV_422_PKG, NATIVEBUFFER_PIXEL_FMT_UYVY_422_PKG,
NATIVEBUFFER_PIXEL_FMT_YVYU_422_PKG, NATIVEBUFFER_PIXEL_FMT_VYUY_422_PKG, NATIVEBUFFER_PIXEL_FMT_RGBA_1010102, NATIVEBUFFER_PIXEL_FMT_YCBCR_P010,
NATIVEBUFFER_PIXEL_FMT_YCRCB_P010, NATIVEBUFFER_PIXEL_FMT_RAW10, NATIVEBUFFER_PIXEL_FMT_VENDER_MASK = 0X7FFF0000, NATIVEBUFFER_PIXEL_FMT_BUTT = 0X7FFFFFFF
} | Enumerates the **OH_NativeBuffer** formats.| -| [OH_NativeBuffer_ColorSpace](_o_h___native_buffer.md#oh_nativebuffer_colorspace-1) {
OH_COLORSPACE_NONE, OH_COLORSPACE_BT601_EBU_FULL, OH_COLORSPACE_BT601_SMPTE_C_FULL, OH_COLORSPACE_BT709_FULL,
OH_COLORSPACE_BT2020_HLG_FULL, OH_COLORSPACE_BT2020_PQ_FULL, OH_COLORSPACE_BT601_EBU_LIMIT, OH_COLORSPACE_BT601_SMPTE_C_LIMIT,
OH_COLORSPACE_BT709_LIMIT, OH_COLORSPACE_BT2020_HLG_LIMIT, OH_COLORSPACE_BT2020_PQ_LIMIT, OH_COLORSPACE_SRGB_FULL,
OH_COLORSPACE_P3_FULL, OH_COLORSPACE_P3_HLG_FULL, OH_COLORSPACE_P3_PQ_FULL, OH_COLORSPACE_ADOBERGB_FULL,
OH_COLORSPACE_SRGB_LIMIT, OH_COLORSPACE_P3_LIMIT, OH_COLORSPACE_P3_HLG_LIMIT, OH_COLORSPACE_P3_PQ_LIMIT,
OH_COLORSPACE_ADOBERGB_LIMIT, OH_COLORSPACE_LINEAR_SRGB, OH_COLORSPACE_LINEAR_BT709, OH_COLORSPACE_LINEAR_P3,
OH_COLORSPACE_LINEAR_BT2020, OH_COLORSPACE_DISPLAY_SRGB, OH_COLORSPACE_DISPLAY_P3_SRGB, OH_COLORSPACE_DISPLAY_P3_HLG,
OH_COLORSPACE_DISPLAY_P3_PQ, OH_COLORSPACE_DISPLAY_BT2020_SRGB, OH_COLORSPACE_DISPLAY_BT2020_HLG, OH_COLORSPACE_DISPLAY_BT2020_PQ
} | Enumerates the color spaces of an **OH_NativeBuffer** instance.| -| [OH_NativeBuffer_TransformType](_o_h___native_buffer.md#oh_nativebuffer_transformtype-1) {
NATIVEBUFFER_ROTATE_NONE = 0, NATIVEBUFFER_ROTATE_90, NATIVEBUFFER_ROTATE_180, NATIVEBUFFER_ROTATE_270,
NATIVEBUFFER_FLIP_H, NATIVEBUFFER_FLIP_V, NATIVEBUFFER_FLIP_H_ROT90, NATIVEBUFFER_FLIP_V_ROT90,
NATIVEBUFFER_FLIP_H_ROT180, NATIVEBUFFER_FLIP_V_ROT180, NATIVEBUFFER_FLIP_H_ROT270, NATIVEBUFFER_FLIP_V_ROT270
} | Enumerates the transform types of an **OH_NativeBuffer** instance.| -| [OH_NativeBuffer_ColorGamut](_o_h___native_buffer.md#oh_nativebuffer_colorgamut-1) {
NATIVEBUFFER_COLOR_GAMUT_NATIVE = 0, NATIVEBUFFER_COLOR_GAMUT_STANDARD_BT601 = 1, NATIVEBUFFER_COLOR_GAMUT_STANDARD_BT709 = 2, NATIVEBUFFER_COLOR_GAMUT_DCI_P3 = 3,
NATIVEBUFFER_COLOR_GAMUT_SRGB = 4, NATIVEBUFFER_COLOR_GAMUT_ADOBE_RGB = 5, NATIVEBUFFER_COLOR_GAMUT_DISPLAY_P3 = 6, NATIVEBUFFER_COLOR_GAMUT_BT2020 = 7,
NATIVEBUFFER_COLOR_GAMUT_BT2100_PQ = 8, NATIVEBUFFER_COLOR_GAMUT_BT2100_HLG = 9, NATIVEBUFFER_COLOR_GAMUT_DISPLAY_BT2020 = 10
} | Enumerates the color gamuts of an **OH_NativeBuffer** instance.| -| [OHNativeErrorCode](_o_h___native_buffer.md#ohnativeerrorcode-1) {
NATIVE_ERROR_OK = 0, NATIVE_ERROR_MEM_OPERATION_ERROR = 30001000, NATIVE_ERROR_INVALID_ARGUMENTS = 40001000, NATIVE_ERROR_NO_PERMISSION = 40301000, NATIVE_ERROR_NO_BUFFER = 40601000,
NATIVE_ERROR_NO_CONSUMER = 41202000, NATIVE_ERROR_NOT_INIT = 41203000, NATIVE_ERROR_CONSUMER_CONNECTED = 41206000, NATIVE_ERROR_BUFFER_STATE_INVALID = 41207000,
NATIVE_ERROR_BUFFER_IN_CACHE = 41208000, NATIVE_ERROR_BUFFER_QUEUE_FULL = 41209000, NATIVE_ERROR_BUFFER_NOT_IN_CACHE = 41210000, NATIVE_ERROR_CONSUMER_DISCONNECTED = 41211000,NATIVE_ERROR_CONSUMER_NO_LISTENER_REGISTERED = 41212000,NATIVE_ERROR_UNSUPPORTED = 50102000,
NATIVE_ERROR_UNKNOWN = 50002000, NATIVE_ERROR_HDI_ERROR = 50007000,NATIVE_ERROR_BINDER_ERROR = 50401000,NATIVE_ERROR_EGL_STATE_UNKNOWN = 60001000, NATIVE_ERROR_EGL_API_FAILED = 60002000
} | Enumerates the error codes.| -| [OH_NativeBuffer_MetadataType](_o_h___native_buffer.md#oh_nativebuffer_metadatatype-1) { OH_VIDEO_HDR_HLG, OH_VIDEO_HDR_HDR10, OH_VIDEO_HDR_VIVID,OH_VIDEO_NONE = -1 } | Enumerates the **OH_NativeBuffer** image standards.| -| [OH_NativeBuffer_MetadataKey](_o_h___native_buffer.md#oh_nativebuffer_metadatakey-1) { OH_HDR_METADATA_TYPE, OH_HDR_STATIC_METADATA, OH_HDR_DYNAMIC_METADATA } | Enumerates the keys that specify the HDR metadata of an **OH_NativeBuffer** instance.| +| [OH_NativeBuffer_Usage](_o_h___native_buffer.md#oh_nativebuffer_usage-1) {
NATIVEBUFFER_USAGE_CPU_READ = (1ULL << 0), NATIVEBUFFER_USAGE_CPU_WRITE = (1ULL << 1), NATIVEBUFFER_USAGE_MEM_DMA = (1ULL << 3), NATIVEBUFFER_USAGE_HW_RENDER = (1ULL << 8),
NATIVEBUFFER_USAGE_HW_TEXTURE = (1ULL << 9), NATIVEBUFFER_USAGE_CPU_READ_OFTEN = (1ULL << 16), NATIVEBUFFER_USAGE_ALIGNMENT_512 = (1ULL << 18)
} | Enumerates the **OH_NativeBuffer** usages. | +| [OH_NativeBuffer_Format](_o_h___native_buffer.md#oh_nativebuffer_format-1) {
NATIVEBUFFER_PIXEL_FMT_CLUT8 = 0, NATIVEBUFFER_PIXEL_FMT_CLUT1, NATIVEBUFFER_PIXEL_FMT_CLUT4, NATIVEBUFFER_PIXEL_FMT_RGB_565 = 3,
NATIVEBUFFER_PIXEL_FMT_RGBA_5658, NATIVEBUFFER_PIXEL_FMT_RGBX_4444, NATIVEBUFFER_PIXEL_FMT_RGBA_4444, NATIVEBUFFER_PIXEL_FMT_RGB_444,
NATIVEBUFFER_PIXEL_FMT_RGBX_5551, NATIVEBUFFER_PIXEL_FMT_RGBA_5551, NATIVEBUFFER_PIXEL_FMT_RGB_555, NATIVEBUFFER_PIXEL_FMT_RGBX_8888,
NATIVEBUFFER_PIXEL_FMT_RGBA_8888, NATIVEBUFFER_PIXEL_FMT_RGB_888, NATIVEBUFFER_PIXEL_FMT_BGR_565, NATIVEBUFFER_PIXEL_FMT_BGRX_4444,
NATIVEBUFFER_PIXEL_FMT_BGRA_4444, NATIVEBUFFER_PIXEL_FMT_BGRX_5551, NATIVEBUFFER_PIXEL_FMT_BGRA_5551, NATIVEBUFFER_PIXEL_FMT_BGRX_8888,
NATIVEBUFFER_PIXEL_FMT_BGRA_8888, NATIVEBUFFER_PIXEL_FMT_YUV_422_I, NATIVEBUFFER_PIXEL_FMT_YCBCR_422_SP, NATIVEBUFFER_PIXEL_FMT_YCRCB_422_SP,
NATIVEBUFFER_PIXEL_FMT_YCBCR_420_SP, NATIVEBUFFER_PIXEL_FMT_YCRCB_420_SP, NATIVEBUFFER_PIXEL_FMT_YCBCR_422_P, NATIVEBUFFER_PIXEL_FMT_YCRCB_422_P,
NATIVEBUFFER_PIXEL_FMT_YCBCR_420_P, NATIVEBUFFER_PIXEL_FMT_YCRCB_420_P, NATIVEBUFFER_PIXEL_FMT_YUYV_422_PKG, [NATIVEBUFFER_PIXEL_FMT_UYVY_422_PKG,
NATIVEBUFFER_PIXEL_FMT_YVYU_422_PKG, NATIVEBUFFER_PIXEL_FMT_VYUY_422_PKG, NATIVEBUFFER_PIXEL_FMT_RGBA_1010102, NATIVEBUFFER_PIXEL_FMT_YCBCR_P010,
NATIVEBUFFER_PIXEL_FMT_YCRCB_P010, NATIVEBUFFER_PIXEL_FMT_RAW10, NATIVEBUFFER_PIXEL_FMT_BLOB, NATIVEBUFFER_PIXEL_FMT_RGBA16_FLOAT,
NATIVEBUFFER_PIXEL_FMT_VENDER_MASK = 0X7FFF0000, NATIVEBUFFER_PIXEL_FMT_BUTT = 0X7FFFFFFF
} | Enumerates the **OH_NativeBuffer** formats. | +| [OH_NativeBuffer_TransformType](_o_h___native_buffer.md#oh_nativebuffer_transformtype-1) {
NATIVEBUFFER_ROTATE_NONE = 0, NATIVEBUFFER_ROTATE_90, NATIVEBUFFER_ROTATE_180, NATIVEBUFFER_ROTATE_270,
NATIVEBUFFER_FLIP_H, NATIVEBUFFER_FLIP_V, NATIVEBUFFER_FLIP_H_ROT90, NATIVEBUFFER_FLIP_V_ROT90,
NATIVEBUFFER_FLIP_H_ROT180, NATIVEBUFFER_FLIP_V_ROT180, NATIVEBUFFER_FLIP_H_ROT270, NATIVEBUFFER_FLIP_V_ROT270
} | Enumerates the transform types of an **OH_NativeBuffer** instance. | +| [OH_NativeBuffer_ColorGamut](_o_h___native_buffer.md#oh_nativebuffer_colorgamut-1) {
NATIVEBUFFER_COLOR_GAMUT_NATIVE = 0, NATIVEBUFFER_COLOR_GAMUT_STANDARD_BT601 = 1, NATIVEBUFFER_COLOR_GAMUT_STANDARD_BT709 = 2, NATIVEBUFFER_COLOR_GAMUT_DCI_P3 = 3,
NATIVEBUFFER_COLOR_GAMUT_SRGB = 4, NATIVEBUFFER_COLOR_GAMUT_ADOBE_RGB = 5, NATIVEBUFFER_COLOR_GAMUT_DISPLAY_P3 = 6, NATIVEBUFFER_COLOR_GAMUT_BT2020 = 7,
NATIVEBUFFER_COLOR_GAMUT_BT2100_PQ = 8, NATIVEBUFFER_COLOR_GAMUT_BT2100_HLG = 9, NATIVEBUFFER_COLOR_GAMUT_DISPLAY_BT2020 = 10
} | Enumerates the color gamuts of an **OH_NativeBuffer** instance. | +| [OHNativeErrorCode](_o_h___native_buffer.md#ohnativeerrorcode-1) {
NATIVE_ERROR_OK = 0, NATIVE_ERROR_MEM_OPERATION_ERROR = 30001000, NATIVE_ERROR_INVALID_ARGUMENTS = 40001000, [NATIVE_ERROR_NO_PERMISSION = 40301000,
NATIVE_ERROR_NO_BUFFER = 40601000, NATIVE_ERROR_NO_CONSUMER = 41202000, NATIVE_ERROR_NOT_INIT = 41203000, NATIVE_ERROR_CONSUMER_CONNECTED = 41206000,
NATIVE_ERROR_BUFFER_STATE_INVALID = 41207000, NATIVE_ERROR_BUFFER_IN_CACHE = 41208000, NATIVE_ERROR_BUFFER_QUEUE_FULL = 41209000, NATIVE_ERROR_BUFFER_NOT_IN_CACHE = 41210000,
NATIVE_ERROR_CONSUMER_DISCONNECTED = 41211000, NATIVE_ERROR_CONSUMER_NO_LISTENER_REGISTERED = 41212000, NATIVE_ERROR_UNSUPPORTED = 50102000, NATIVE_ERROR_UNKNOWN = 50002000,
NATIVE_ERROR_HDI_ERROR = 50007000, NATIVE_ERROR_BINDER_ERROR = 50401000, NATIVE_ERROR_EGL_STATE_UNKNOWN = 60001000, [NATIVE_ERROR_EGL_API_FAILED = 60002000
} | Enumerates the error codes. | ### Functions -| Name| Description| +| Name| Description| | -------- | -------- | -| [OH_NativeBuffer](_o_h___native_buffer.md#oh_nativebuffer) \* [OH_NativeBuffer_Alloc](_o_h___native_buffer.md#oh_nativebuffer_alloc) (const [OH_NativeBuffer_Config](_o_h___native_buffer___config.md) \*config) | Creates an **OH_NativeBuffer** instance based on an **OH_NativeBuffer_Config** struct. A new **OH_NativeBuffer** instance is created each time this function is called.| -| int32_t [OH_NativeBuffer_Reference](_o_h___native_buffer.md#oh_nativebuffer_reference) ([OH_NativeBuffer](_o_h___native_buffer.md#oh_nativebuffer) \*buffer) | Increases the reference count of an **OH_NativeBuffer** instance by 1.| -| int32_t [OH_NativeBuffer_Unreference](_o_h___native_buffer.md#oh_nativebuffer_unreference) ([OH_NativeBuffer](_o_h___native_buffer.md#oh_nativebuffer) \*buffer) | Decreases the reference count of an **OH_NativeBuffer** instance by 1 and, when the reference count reaches 0, destroys the instance.| -| void [OH_NativeBuffer_GetConfig](_o_h___native_buffer.md#oh_nativebuffer_getconfig) ([OH_NativeBuffer](_o_h___native_buffer.md#oh_nativebuffer) \*buffer, [OH_NativeBuffer_Config](_o_h___native_buffer___config.md) \*config) | Obtains the properties of an **OH_NativeBuffer** instance.| -| int32_t [OH_NativeBuffer_Map](_o_h___native_buffer.md#oh_nativebuffer_map) ([OH_NativeBuffer](_o_h___native_buffer.md#oh_nativebuffer) \*buffer, void \*\*virAddr) | Maps the ION memory allocated to an **OH_NativeBuffer** instance to the process address space.| -| int32_t [OH_NativeBuffer_Unmap](_o_h___native_buffer.md#oh_nativebuffer_unmap) ([OH_NativeBuffer](_o_h___native_buffer.md#oh_nativebuffer) \*buffer) | Unmaps the ION memory allocated to an **OH_NativeBuffer** instance from the process address space.| -| uint32_t [OH_NativeBuffer_GetSeqNum](_o_h___native_buffer.md#oh_nativebuffer_getseqnum) ([OH_NativeBuffer](_o_h___native_buffer.md#oh_nativebuffer) \*buffer) | Obtains the sequence number of an **OH_NativeBuffer** instance.| -| int32_t [OH_NativeBuffer_SetColorSpace](_o_h___native_buffer.md#oh_nativebuffer_setcolorspace) ([OH_NativeBuffer](_o_h___native_buffer.md#oh_nativebuffer) \*buffer, [OH_NativeBuffer_ColorSpace](_o_h___native_buffer.md#oh_nativebuffer_colorspace) colorSpace) | Sets the color space for an **OH_NativeBuffer** instance.| -| int32_t [OH_NativeBuffer_MapPlanes](_o_h___native_buffer.md#oh_nativebuffer_mapplanes) ([OH_NativeBuffer](_o_h___native_buffer.md#oh_nativebuffer) \*buffer, void \*\*virAddr, [OH_NativeBuffer_Planes](_o_h___native_buffer___planes.md) \*outPlanes) | Maps the multi-channel ION memory corresponding to an **OH_NativeBuffer** instance to the process address space.| -| int32_t [OH_NativeBuffer_FromNativeWindowBuffer](_o_h___native_buffer.md#oh_nativebuffer_fromnativewindowbuffer) ([OHNativeWindowBuffer](_native_window.md#ohnativewindowbuffer) \*nativeWindowBuffer, [OH_NativeBuffer](_o_h___native_buffer.md#oh_nativebuffer) \*\*buffer) | Converts an **OHNativeWindowBuffer** instance to an **OH_NativeBuffer** instance.| -| int32_t [OH_NativeBuffer_GetColorSpace](_o_h___native_buffer.md#oh_nativebuffer_getcolorspace) ([OH_NativeBuffer](_o_h___native_buffer.md#oh_nativebuffer) \*buffer, [OH_NativeBuffer_ColorSpace](_o_h___native_buffer.md#oh_nativebuffer_colorspace) \*colorSpace) | Obtains the color space of an **OH_NativeBuffer** instance.| -| int32_t [OH_NativeBuffer_SetMetadataValue](_o_h___native_buffer.md#oh_nativebuffer_setmetadatavalue) ([OH_NativeBuffer](_o_h___native_buffer.md#oh_nativebuffer) \*buffer, [OH_NativeBuffer_MetadataKey](_o_h___native_buffer.md#oh_nativebuffer_metadatakey) metadataKey, int32_t size, uint8_t \*metaData) | Sets a metadata value for an **OH_NativeBuffer** instance.| -| int32_t [OH_NativeBuffer_GetMetadataValue](_o_h___native_buffer.md#oh_nativebuffer_getmetadatavalue) ([OH_NativeBuffer](_o_h___native_buffer.md#oh_nativebuffer) \*buffer, [OH_NativeBuffer_MetadataKey](_o_h___native_buffer.md#oh_nativebuffer_metadatakey) metadataKey, int32_t \*size, uint8_t \*\*metaData) | Obtains the metadata value of an **OH_NativeBuffer** instance.| +| [OH_NativeBuffer](_o_h___native_buffer.md#oh_nativebuffer) \* [OH_NativeBuffer_Alloc](_o_h___native_buffer.md#oh_nativebuffer_alloc) (const [OH_NativeBuffer_Config](_o_h___native_buffer___config.md) \*config) | Creates an **OH_NativeBuffer** instance based on an **OH_NativeBuffer_Config** struct. A new **OH_NativeBuffer** instance is created each time this function is called.
This function must be used in pair with [OH_NativeBuffer_Unreference](_o_h___native_buffer.md#oh_nativebuffer_unreference). Otherwise, memory leak occurs.
This function is not thread-safe.| +| int32_t [OH_NativeBuffer_Reference](_o_h___native_buffer.md#oh_nativebuffer_reference) ([OH_NativeBuffer](_o_h___native_buffer.md#oh_nativebuffer) \*buffer) | Increases the reference count of an **OH_NativeBuffer** instance by 1.
This function must be used in pair with [OH_NativeBuffer_Unreference](_o_h___native_buffer.md#oh_nativebuffer_unreference). Otherwise, memory leak occurs.
This function is not thread-safe.| +| int32_t [OH_NativeBuffer_Unreference](_o_h___native_buffer.md#oh_nativebuffer_unreference) ([OH_NativeBuffer](_o_h___native_buffer.md#oh_nativebuffer) \*buffer) | Decreases the reference count of an **OH_NativeBuffer** instance by 1 and, when the reference count reaches 0, destroys the instance.
This function is not thread-safe.| +| void [OH_NativeBuffer_GetConfig](_o_h___native_buffer.md#oh_nativebuffer_getconfig) ([OH_NativeBuffer](_o_h___native_buffer.md#oh_nativebuffer) \*buffer, [OH_NativeBuffer_Config](_o_h___native_buffer___config.md) \*config) | Obtains the properties of an **OH_NativeBuffer** instance.
This function is not thread-safe.| +| int32_t [OH_NativeBuffer_Map](_o_h___native_buffer.md#oh_nativebuffer_map) ([OH_NativeBuffer](_o_h___native_buffer.md#oh_nativebuffer) \*buffer, void \*\*virAddr) | Maps the ION memory allocated to an **OH_NativeBuffer** instance to the process address space.
This function must be used in pair with [OH_NativeBuffer_Unmap](_o_h___native_buffer.md#oh_nativebuffer_unmap).
This function is not thread-safe.| +| int32_t [OH_NativeBuffer_Unmap](_o_h___native_buffer.md#oh_nativebuffer_unmap) ([OH_NativeBuffer](_o_h___native_buffer.md#oh_nativebuffer) \*buffer) | Unmaps the ION memory allocated to an **OH_NativeBuffer** instance from the process address space.
This function is not thread-safe.| +| uint32_t [OH_NativeBuffer_GetSeqNum](_o_h___native_buffer.md#oh_nativebuffer_getseqnum) ([OH_NativeBuffer](_o_h___native_buffer.md#oh_nativebuffer) \*buffer) | Obtains the sequence number of an **OH_NativeBuffer** instance.
This function is not thread-safe.| +| int32_t [OH_NativeBuffer_SetColorSpace](_o_h___native_buffer.md#oh_nativebuffer_setcolorspace) ([OH_NativeBuffer](_o_h___native_buffer.md#oh_nativebuffer) \*buffer, [OH_NativeBuffer_ColorSpace](_o_h___native_buffer.md#oh_nativebuffer_colorspace) colorSpace) | Sets the color space for an **OH_NativeBuffer** instance.
This function is not thread-safe.| +| int32_t [OH_NativeBuffer_MapPlanes](_o_h___native_buffer.md#oh_nativebuffer_mapplanes) ([OH_NativeBuffer](_o_h___native_buffer.md#oh_nativebuffer) \*buffer, void \*\*virAddr, [OH_NativeBuffer_Planes](_o_h___native_buffer___planes.md) \*outPlanes) | Maps the multi-channel ION memory corresponding to an **OH_NativeBuffer** instance to the process address space.
This function is not thread-safe.| +| int32_t [OH_NativeBuffer_FromNativeWindowBuffer](_o_h___native_buffer.md#oh_nativebuffer_fromnativewindowbuffer) (OHNativeWindowBuffer \*nativeWindowBuffer, [OH_NativeBuffer](_o_h___native_buffer.md#oh_nativebuffer) \*\*buffer) | Converts an **OHNativeWindowBuffer** instance to an **OH_NativeBuffer** instance.
This function is not thread-safe.| +| int32_t [OH_NativeBuffer_GetColorSpace](_o_h___native_buffer.md#oh_nativebuffer_getcolorspace) ([OH_NativeBuffer](_o_h___native_buffer.md#oh_nativebuffer) \*buffer, [OH_NativeBuffer_ColorSpace](_o_h___native_buffer.md#oh_nativebuffer_colorspace) \*colorSpace) | Obtains the color space of an **OH_NativeBuffer** instance.
This function is not thread-safe.| +| int32_t [OH_NativeBuffer_SetMetadataValue](_o_h___native_buffer.md#oh_nativebuffer_setmetadatavalue) ([OH_NativeBuffer](_o_h___native_buffer.md#oh_nativebuffer) \*buffer, [OH_NativeBuffer_MetadataKey](_o_h___native_buffer.md#oh_nativebuffer_metadatakey) metadataKey, int32_t size, uint8_t \*metaData) | Sets a metadata value for an **OH_NativeBuffer** instance.
This function is not thread-safe.| +| int32_t [OH_NativeBuffer_GetMetadataValue](_o_h___native_buffer.md#oh_nativebuffer_getmetadatavalue) ([OH_NativeBuffer](_o_h___native_buffer.md#oh_nativebuffer) \*buffer, [OH_NativeBuffer_MetadataKey](_o_h___native_buffer.md#oh_nativebuffer_metadatakey) metadataKey, int32_t \*size, uint8_t \*\*metaData) | Obtains the metadata value of an **OH_NativeBuffer** instance.
This function is not thread-safe.| diff --git a/en/application-dev/reference/apis-arkgraphics2d/native__vsync_8h.md b/en/application-dev/reference/apis-arkgraphics2d/native__vsync_8h.md index 01969e6e9c33e3780422eba7952e330f55f9bccb..91358ee5ad17dbb9811c466423fff9ef07648827 100644 --- a/en/application-dev/reference/apis-arkgraphics2d/native__vsync_8h.md +++ b/en/application-dev/reference/apis-arkgraphics2d/native__vsync_8h.md @@ -5,13 +5,9 @@ The **native_vsync.h** file declares the functions for obtaining and using native virtual synchronization (VSync). -**Since** +**Since**: 9 -9 - -**Related Modules** - -[NativeVsync](_native_vsync.md) +**Related module**: [NativeVsync](_native_vsync.md) ## Summary diff --git a/en/application-dev/reference/apis-arkts/Readme-EN.md b/en/application-dev/reference/apis-arkts/Readme-EN.md index c71d474759a36c4f00833abff3d9ff5318a431c4..6d36b6124954ba93c428d07ef79a4613bd3d64d3 100644 --- a/en/application-dev/reference/apis-arkts/Readme-EN.md +++ b/en/application-dev/reference/apis-arkts/Readme-EN.md @@ -1,6 +1,6 @@ # ArkTS -- ArkTS APIs +- ArkTS APIs - [@arkts.collections (ArkTS Collections)](js-apis-arkts-collections.md) - [@arkts.lang (ArkTS Base Capability)](js-apis-arkts-lang.md) - [@arkts.math.Decimal (High-Precision Math Library Decimal)](js-apis-arkts-decimal.md) @@ -28,8 +28,13 @@ - [@ohos.util.TreeMap (Nonlinear Container TreeMap)](js-apis-treemap.md) - [@ohos.util.TreeSet (Nonlinear Container TreeSet)](js-apis-treeset.md) - [@ohos.worker (Starting the Worker)](js-apis-worker.md) + + - [@ohos.worker (Starting the Worker) (System API)](js-apis-worker-sys.md) + - [@ohos.xml (XML Parsing and Generation)](js-apis-xml.md) - - APIs No Longer Maintained + - APIs No Longer Maintained - [@ohos.util.Vector (Linear Container Vector)](js-apis-vector.md) -- Error Codes +- Error Codes - [Common Library Error Codes](errorcode-utils.md) + - [TypeScript Compiler Error Codes](errorcode-tsc.md) + - [Compilation Toolchain Error Codes](errorcode-ets-loader.md) diff --git a/en/application-dev/reference/apis-arkts/errorcode-ets-loader.md b/en/application-dev/reference/apis-arkts/errorcode-ets-loader.md new file mode 100644 index 0000000000000000000000000000000000000000..bb9862b8c619ec8151a78606de53c9ec6d40bdad --- /dev/null +++ b/en/application-dev/reference/apis-arkts/errorcode-ets-loader.md @@ -0,0 +1,173 @@ +# Compilation Toolchain Error Codes + +> **NOTE** +> +> This topic describes only module-specific error codes. For details about universal error codes, see [Universal Error Codes](../errorcode-universal.md). + +## 10311001 Failed to Import ArkTS Files + +**Error Message** + +Importing ArkTS files in JS and TS files is forbidden. + +**Description** + +It is forbidden to import ArkTS files to JS or TS files. + +**Possible Causes** + +ArkTS files have been imported in JS and TS files. + +**Solution** + +Remove the import statements for ArkTS files from JS and TS files. + +## 10311002 Failed to Parse OhmUrl + +**Error Message** + +Failed to resolve OhmUrl. Failed to get a resolved OhmUrl for `${filePath}` imported by `${importerFile}`. + +**Description** + +Failed to resolve OhmUrl. Failed to obtain the parsed OhmUrl for ${filePath} imported by ${importerFile}. + +**Possible Causes** + +The ${pkgName} module to which ${filePath} belongs is configured incorrectly. + +**Solution** + +1. Make sure the ${pkgName} module is correctly configured in the ${filePath} file. +2. Make sure the file name is correct, including its case sensitivity. + +## 10311003 Failed to Obtain the Kit Configuration File + +**Error Message** + +Kit `${moduleRequest}` has no corresponding config file in ArkTS SDK. + +**Description** + +The ${moduleRequest} kit does not have the corresponding configuration file in the ArkTS SDK. + +**Possible Causes** + +1. The APIs of the kit are inconsistent with those in the SDK. +2. The APIs of the kit are modified locally. + +**Solution** + +1. Make sure the kit API you are importing is consistent with the SDK version you are using, and the kit APIs are not modified locally. +2. For details about the kit APIs, see [API Reference Document Description](../development-intro.md). + +## 10311005 Incorrect Kit Identifier + +**Error Message** + +Identifier `${this.importName}` comes from `${this.symbol.source}` which can not be imported in .ts file. + +**Description** + +The identifier ${this.importName} comes from ${this.symbol.source}. This identifier cannot be imported to a .ts file. + +**Possible Causes** + +An ArkTS file of the kit is imported to the TS file. + +**Solution** + +Remove the import statement or change the file name extension to .ets. + +## 10311006 Failed to Export Imported Names from the Kit + +**Error Message** + +`${importName}` is not exported from Kit `${KitInfo.getCurrentKitName()}`. + +**Description** + +Kit ${importName} is not exported from ${KitInfo.getCurrentKitName()}. + +**Possible Causes** + +1. The APIs of the kit are inconsistent with those in the SDK. +2. The APIs of the kit are modified locally. + +**Solution** + +1. Make sure the kit API you are importing is consistent with the SDK version you are using, and the kit APIs are not modified locally. +2. For details about the kit APIs, see [API Reference Document Description](../development-intro.md). + +## 10311007 Failed to Import or Export Kit Namespaces + +**Error Message** + +Namespace import or export of Kit is not supported currently. + +**Description** + +Currently, the namespace of a kit cannot be imported or exported. + +**Possible Causes** + +The file uses the namespace of the kit for import or export. + +**Solution** + +Replace the namespace import or export of the kit with a named import or export. Example: `import * as ArkTS from "@kit.ArkUI";` -> `import { AlertDialog } from "@kit.ArkUI";`; + +## 10311008 Kit Empty Import Error + +**Error Message** + +Can not use empty import(side-effect import) statement with Kit `${(kitNode.moduleSpecifier as ts.StringLiteral).text.replace(/'|"/g, '')}`. + +**Description** + +Empty import (side-effect import) statements cannot be used in Kit `${(kitNode.moduleSpecifier as ts.StringLiteral).text.replace(/'|"/g, '')}`. + +**Possible Causes** + +The empty import (side-effect import) statement of the kit is used in the file. + +**Solution** + +Specify the symbol to be imported. Example: `import "@kit.ArkUI";` -> `import { lang } from "@kit.ArkUI";` + +## 10311009 es2abc Execution Error + +**Error Message** + +Failed to execute es2abc. + +**Description** + +es2abc fails to be executed. + +**Possible Causes** + +An error occurred during the execution of es2abc. + +**Solution** + +Refer to the error codes of es2abc for troubleshooting. + +## 10311010 Lazy Import Re-export Error + +**Error Message** + +`${elementText}` of lazy-import is re-export. + +**Description** + +The lazy import of ${elementText} is re-exported. + +**Possible Causes** + +The lazy-imported ${elementText} lazy-imported is exported again. + +**Solution** + +1. Make sure lazily loaded named bindings are not re-exported. +2. Check whether **autoLazyImport** is enabled. diff --git a/en/application-dev/reference/apis-arkts/errorcode-tsc.md b/en/application-dev/reference/apis-arkts/errorcode-tsc.md new file mode 100644 index 0000000000000000000000000000000000000000..1c4abab27c12c51824716c19fdc569ba3b559773 --- /dev/null +++ b/en/application-dev/reference/apis-arkts/errorcode-tsc.md @@ -0,0 +1,96 @@ +# TypeScript Compiler Error Codes + +Error codes of Typescript Compiler (TSC) start with '105' and serve as error indicators during the TSC compilation process. These error codes and their corresponding descriptions are shown in the editor, console, or log files. + +## 10505001 TSC Native Errors + +TSC native errors, ending with '001', represent existing native error rules checked by TSC. Common causes of TSC native errors during compilation include: missing keywords or symbols, type mismatches in assignments, and undefined types or variables. These issues typically arise from not adhering to [language specifications](https://developer.huawei.com/consumer/en/doc/harmonyos-guides-V5/introduction-to-arkts-V5) when writing code. Developers can adjust the code based on the error descriptions. + +### Missing Keywords Or Symbols + +**Error Example Scenario** + +```typescript +declare type AAA = 'BBB; +``` + +**Error Message** + +Unterminated string literal. + +**Description** + +The string literal is not correctly terminated at the expected position. + +**Possible Causes** + +The closing quote is missing. + +**Solution** + +Based on the error description, add the missing quotes to the code block. The updated code is as follows: + +```typescript +declare type AAA = 'BBB'; +``` + +### Multiple Default Exports + +**Error Example Scenario** + +```typescript +export default A; +export default B; +``` + +**Error Message** + +A module cannot have multiple default exports. + +**Description** + +A module cannot have multiple default exports. + +**Possible Causes** + +Multiple default exports are defined in the module. + +**Solution** + +Based on the error description, delete unnecessary default exports. The updated code is as follows: + +```typescript +export default A; +``` + +### Type Mismatch in Assignments + +**Error Example Scenario** + +```typescript +let a: number = 1; +let b: string = '2'; +a = b; +``` + +**Error Message** + +Type 'string' is not assignable to type 'number'. + +**Description** + +Type 'string' cannot be assigned to type 'number'. + +**Possible Causes** + +Assigning a value of one type to a variable of a different type results in a type mismatch error. + +**Solution** + +Based on the error description, ensure type consistency by making appropriate type assignment changes. The updated code is as follows: + +```typescript +let a: number = 1; +let b: number = 2; +a = b; +``` diff --git a/en/application-dev/reference/apis-arkts/errorcode-utils.md b/en/application-dev/reference/apis-arkts/errorcode-utils.md index 532c2e752b961bff52fe2dbc8521f7d2c0bb93c5..7be28c5d9ba5a09e1627aeb17c4b5aa25f5a549b 100644 --- a/en/application-dev/reference/apis-arkts/errorcode-utils.md +++ b/en/application-dev/reference/apis-arkts/errorcode-utils.md @@ -740,7 +740,7 @@ A task within the waiting list of the asynchronous queue is discarded. **Possible Causes** -When the number of tasks executed by calling [asyncRunner.execute](../apis-arkts/js-apis-taskpool.md#execute16) exceeds the capacity of the waiting list, the earliest task in the list is discarded. +When the number of tasks executed by calling [asyncRunner.execute](../apis-arkts/js-apis-taskpool.md#execute18) exceeds the capacity of the waiting list, the earliest task in the list is discarded. **Solution** @@ -791,17 +791,17 @@ The task cannot be executed by two APIs. **Description** -Asynchronous queue tasks can be executed only by [asyncRunner.execute](../apis-arkts/js-apis-taskpool.md#execute16), whereas non-asynchronous tasks cannot be executed by [asyncRunner.execute](../apis-arkts/js-apis-taskpool.md#execute16). +Asynchronous queue tasks can be executed only by [asyncRunner.execute](../apis-arkts/js-apis-taskpool.md#execute18), whereas non-asynchronous tasks cannot be executed by [asyncRunner.execute](../apis-arkts/js-apis-taskpool.md#execute18). **Possible Causes** -1. [sequenceRunner.execute](../apis-arkts/js-apis-taskpool.md#execute11), [executeDelayed](../apis-arkts/js-apis-taskpool.md#taskpoolexecutedelayed11), [addTask](../apis-arkts/js-apis-taskpool.md#addtask10-1), [taskpool.execute](../apis-arkts/js-apis-taskpool.md#taskpoolexecute-1), [asyncRunner.execute](../apis-arkts/js-apis-taskpool.md#execute16), [executePeriodically](../apis-arkts/js-apis-taskpool.md#taskpoolexecuteperiodically12), or [addDependency](js-apis-taskpool.md#adddependency11) is called to execute an asynchronous queue task. -2. [execute](../apis-arkts/js-apis-taskpool.md#execute16) of the asynchronous queue is called again to execute a task that has been executed. +1. [sequenceRunner.execute](../apis-arkts/js-apis-taskpool.md#execute11), [executeDelayed](../apis-arkts/js-apis-taskpool.md#taskpoolexecutedelayed11), [addTask](../apis-arkts/js-apis-taskpool.md#addtask10-1), [taskpool.execute](../apis-arkts/js-apis-taskpool.md#taskpoolexecute-1), [asyncRunner.execute](../apis-arkts/js-apis-taskpool.md#execute18), [executePeriodically](../apis-arkts/js-apis-taskpool.md#taskpoolexecuteperiodically12), or [addDependency](js-apis-taskpool.md#adddependency11) is called to execute an asynchronous queue task. +2. [execute](../apis-arkts/js-apis-taskpool.md#execute18) of the asynchronous queue is called again to execute a task that has been executed. **Solution** 1. When calling these APIs, ensure that the asynchronous queue task will not be executed. If you are not sure, capture exceptions. -2. When calling [execute](../apis-arkts/js-apis-taskpool.md#execute16) of the asynchronous queue, ensure that the task has not been executed. If you are not sure, capture exceptions. +2. When calling [execute](../apis-arkts/js-apis-taskpool.md#execute18) of the asynchronous queue, ensure that the task has not been executed. If you are not sure, capture exceptions. ## 10200060 Precision Limit Is Exceeded diff --git a/en/application-dev/reference/apis-arkts/js-apis-arkts-collections.md b/en/application-dev/reference/apis-arkts/js-apis-arkts-collections.md index 78b0d9ebcb889348d0c66aefb4eb8ea9dc55f886..a39bd284cbae3a1e19597680be67e1b5ce468433 100644 --- a/en/application-dev/reference/apis-arkts/js-apis-arkts-collections.md +++ b/en/application-dev/reference/apis-arkts/js-apis-arkts-collections.md @@ -11,6 +11,8 @@ Currently, the following ArkTS containers are provided: [Array](#collectionsarra > **NOTE** > > The initial APIs of this module are supported since API version 12. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> This module can be imported only to ArkTS files (with the file name extension .ets). ## Modules to Import @@ -157,6 +159,76 @@ let concatArray : collections.ConcatArray = new collections.Array18+
+type ArrayFromMapFn = (value: FromElementType, index: number) => ToElementType + +Defines the ArkTS Array reduction function, which is used by the **from** API of the Array class. + +**System capability**: SystemCapability.Utils.Lang + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | --------------------------- | +| value | FromElementType | Yes| Element that is being processed.| +| index | number | Yes| Index of the element in the ArkTS array.| + +**Return value** + +| Type | Description | +| ------ | --------------------------- | +| ToElementType | Result of the reduction function, which is used as a new element in the array.| + +## ArrayPredicateFn18+ +type ArrayPredicateFn = (value: ElementType, index: number, array: ArrayType) => boolean + +Defines the ArkTS Array reduction function, which is used by the **some** and **every** APIs of the Array class to determine whether array elements meet certain test conditions. + +**System capability**: SystemCapability.Utils.Lang + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | --------------------------- | +| value | ElementType | Yes| Element that is being processed.| +| index | number | Yes| Index of the element in the ArkTS array.| +| array | ArrayType | Yes| ArkTS array that is being traversed.| + +**Return value** + +| Type | Description | +| ------ | --------------------------- | +| boolean | Result of the reduction function, indicating whether the current element meets the test condition. The value **true** means that the current element or a previous element meets the condition, and **false** means that no element meets the condition.| + +## ArrayReduceCallback18+ +type ArrayReduceCallback = + (previousValue: AccType, currentValue: ElementType, currentIndex: number, array: ArrayType) => AccType + +Defines the ArkTS Array reduction function, which is used by the **reduceRight** API of the Array class. + +**System capability**: SystemCapability.Utils.Lang + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | --------------------------- | +| previousValue | AccType | Yes| Accumulated value of the current traversal.| +| currentValue | ElementType | Yes| Element that is being traversed in the ArkTS array.| +| currentIndex | number | Yes| Index of the element in the ArkTS array.| +| array | ArrayType | Yes| ArkTS array that is being traversed.| + +**Return value** + +| Type | Description | +| ------ | --------------------------- | +| AccType | Result of the reduction function, which is used as the **previousValue** parameter in the next call of **ArrayReduceCallback**.| + ## collections.Array A linear data structure that is implemented on arrays and can be passed between ArkTS concurrent instances. @@ -333,19 +405,435 @@ For details about the error codes, see [Utils Error Codes](errorcode-utils.md). | -------- | -------------------------------- | | 10200011 | The from method cannot be bound. | -**Example** +**Example** + +```ts +// Positive example: +let array: Array = ['str1', 'str2', 'str3']; // Native Array, where T is the sendable data type. +let sendableArray = collections.Array.from(array); // Returns Sendable Array. +``` + + +```ts +// Negative example: +let array: Array> = [['str1', 'str2', 'str3'], ['str4', 'str5', 'str6'], ['str7', 'str8', 'str9']]; // Native Array, where T is a non-sendable data type. +let sendableArray = collections.Array.from>(array); // Prints the following exception information: Parameter error.Only accept sendable value +``` + +### from12+ + +static from\(iterable: Iterable\): Array\ + +Creates an ArkTS array from an iterable object. + +**Atomic service API**: This API can be used in atomic services since API version 12. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------- | ---- | ------------------------------- | +| iterable | Iterable\ | Yes | Array-like object.| + +**Return value** + +| Type | Description | +| --------- | ----------------------- | +| Array\ | Newly created ArkTS array.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------- | +| 401 | Parameter error: Possible causes: 1. Mandatory parameters are left unspecified;2. Incorrect parameter types; 3. Parameter verification failed. | +| 10200011 | The from method cannot be bound. | + +**Example** + +```ts +// Positive example: +const mapper = new Map([ + ['1', 'a'], + ['2', 'b'], +]); +let newArray: collections.Array = collections.Array.from(mapper.values()); +console.info(newArray.toString()); +// Expected output: a,b +``` + +### from18+ + +static from\(arrayLike: ArrayLike\ | Iterable\, mapFn: ArrayFromMapFn\): Array\ + +Creates an ArkTS array from an array-like object, and uses a custom function to process each array element. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------- | ---- | ------------------------------- | +| arrayLike | ArrayLike\ \| Iterable\ | Yes | Array-like object.| +| mapFn | ArrayFromMapFn\ | Yes | Functions used to process the array elements.| + +**Return value** + +| Type | Description | +| --------- | ----------------------- | +| Array\ | Newly created ArkTS array.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------- | +| 401 | Parameter error: Possible causes: 1. Mandatory parameters are left unspecified;2. Incorrect parameter types; 3. Parameter verification failed. | +| 10200011 | The from method cannot be bound. | + +**Example** + +```ts +let array : Array = [1, 2, 3]; // Native Array, where T is of the Sendable type. +let newarray = collections.Array.from(array, (value, index) => value + index); // Return a new Array. +console.info(newarray.toString()); +// Expected output: 1, 3, 5 +``` + +### from18+ + +static from\(arrayLike: ArrayLike\ | Iterable\, mapFn: ArrayFromMapFn\): Array\ + +Creates an ArkTS array from an array-like object, and uses a custom function to process each array element. The type of the elements in the array-like object can be different from that of the array elements. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------- | ---- | ------------------------------- | +| arrayLike | ArrayLike\ \| Iterable\ | Yes | Array-like object.| +| mapFn | ArrayFromMapFn\ | Yes | Functions used to process the array elements.| + +**Return value** + +| Type | Description | +| --------- | ----------------------- | +| Array\ | Newly created ArkTS array.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------- | +| 401 | Parameter error: Possible causes: 1. Mandatory parameters are left unspecified;2. Incorrect parameter types; 3. Parameter verification failed. | +| 10200011 | The from method cannot be bound. | + +**Example** + +```ts +let array : Array = [1, 2, 3]; // Native Array +let newarray = collections.Array.from(array, (value, index) => value + "." + index); // Return a new Array. +console.info(newarray.toString()); +// Expected output: 1.0, 2.1, 3.2 +``` + +### isArray18+ + +static isArray\(value: Object | undefined | null): boolean + +Check whether the input parameter is an ArkTS array. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------- | ---- | ------------------------------- | +| value | Object \| undefined \| null | Yes | Value to check.| + +**Return value** + +| Type | Description | +| --------- | ----------------------- | +| boolean | Check result. The value **true** means that the input parameter is an ArkTS array, and **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message | +| -------- | -------------------------------- | +| 401 | Parameter error: Possible causes: 1. Mandatory parameters are left unspecified;2. Incorrect parameter types; 3. Parameter verification failed. | + +**Example** + +```ts +let arr: collections.Array = new collections.Array('a', 'b', 'c', 'd') +let result: boolean = collections.Array.isArray(arr); +console.info(result + ''); +// Expected output: true +``` + +### of18+ + +static of\(...items: T\[]): Array\ + +Creates an ArkTS array with a variable number of parameters. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------- | ---- | ------------------------------- | +| items | T[] | No | Array of elements used to create the array. The number of elements can be zero, one, or more.| + +**Return value** + +| Type | Description | +| --------- | ----------------------- | +| Array\ | Newly created ArkTS array.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message | +| -------- | -------------------------------- | +| 401 | Parameter error: Possible causes: 1. Mandatory parameters are left unspecified;2. Incorrect parameter types; 3. Parameter verification failed. | + +**Example** + +```ts +let arr: collections.Array = collections.Array.of('a', 'b', 'c', 'd') +console.info(arr.toString()); +// Expected output: a, b, c, d +``` + +### copyWithin18+ +copyWithin(target: number, start: number, end?: number): Array\ + +Copies elements within a given range from this ArkTS array to another position in sequence. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------------------------------------------------------ | +| target | number | Yes| Index to copy the elements to.| +| start | number | Yes| Start index of the range. If a negative number is passed in, it refers to the index of **start + array.length**.| +| end | number | No| End index of the range. If a negative number is passed in, it refers to the index of **end + array.length**. The default value is the length of the ArkTS array.| + +**Return value** + +| Type | Description | +| ------------ | --------- | +| Array\ | ArkTS array after being modified.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md). + +| ID| Error Message | +| -------- | ------------------------------------------------ | +| 401 | Parameter error: Possible causes: 1. Mandatory parameters are left unspecified;2. Incorrect parameter types; 3. Parameter verification failed. | +| 10200011 | The copyWithin method cannot be bound. | +| 10200201 | Concurrent modification exception. | + +**Example** + +```ts +let array: collections.Array = collections.Array.from([1, 2, 3, 4, 5, 6, 7, 8]); +let copied: collections.Array = array.copyWithin(3, 1, 3); +console.info(copied.toString()); +// Expected output: 1, 2, 3, 2, 3, 6, 7, 8 +``` + +### lastIndexOf18+ + +lastIndexOf(searchElement: T, fromIndex?: number): number + +Obtains the index of the last occurrence of the specified value in in this ArkTS array. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------------- | ------ | --- | --------------------------------------------------------------------------------- | +| searchElement | T | Yes | Value to search for. | +| fromIndex | number | No | Index from which the search starts. The default value is **0**. If the index is greater than or equal to the length of the ArkTS array, **-1** is returned. If a negative number is passed in, it refers to the index of **fromIndex + array.length**.| + +**Return value** + +| Type | Description | +| ------ | ----------------------- | +| number | Index of the last occurrence of the value. If the value is not found, **-1** is returned.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md). + +| ID | Error Message | +| -------- | --------------------------------------- | +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | +| 10200001 | The value of fromIndex or toIndex is out of range. | +| 10200011 | The lastIndexOf method cannot be bound. | +| 10200201 | Concurrent modification exception. | + +**Example** + +```ts +let array: collections.Array = collections.Array.from([3, 5, 9]); +console.info(array.lastIndexOf(3) + ''); +// Expected output: 0 +console.info(array.lastIndexOf(7) + ''); +// Expected output: -1 +console.info(array.lastIndexOf(9, 2) + ''); +// Expected output: 2 +console.info(array.lastIndexOf(9, -2) + ''); +// Expected output: -1 +``` + +### some18+ +some(predicate: ArrayPredicateFn\>): boolean + +Checks whether this ArkTS array contains an element that meets certain conditions. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ---------------------------------------------------- | +| predicate | ArrayPredicateFn\ | Yes| Assertion function used for the test.| + +**Return value** + +| Type | Description | +| ------------ | --------- | +| boolean | Check result. The value **true** means that an element meeting the given condition exists, and **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md). + +| ID| Error Message | +| -------- | ---------------------------------- | +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | +| 10200011 | The some method cannot be bound. | +| 10200201 | Concurrent modification exception. | + +**Example** + +```ts +let newArray: collections.Array = collections.Array.from([-10, 20, -30, 40, -50]); +console.info(newArray.some((element: number) => element < 0) + ''); +// Expected output: true +``` + +### reduceRight18+ + +reduceRight(callbackFn: ArrayReduceCallback\>): T + +Goes through each element in this ArkTS array from right to left, uses a callback function to combine them into a single value, and returns that final value. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------- | -------------------------------------------------------------------------------- | --- | ------------------------------------------ | +| callbackFn | ArrayReduceCallback\> | Yes | Function that takes four arguments. It performs an operation on each element and passes the result as an accumulated value to the next element.| + +**Return value** + +| Type | Description | +| --- | ------------- | +| T | Final result obtained from the last call of the callback function.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md). + +| ID | Error Message | +| -------- | --------------------------------------- | +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | +| 10200011 | The reduceRight method cannot be bound. | +| 10200201 | Concurrent modification error. | + +**Example** + +```ts +let array = new collections.Array(1, 2, 3, 4, 5); +let reducedValue = array.reduceRight((accumulator, value) => accumulator + value); // Accumulated result of all elements. +console.info(reducedValue + ''); +// Expected output: 15 +``` + +### reduceRight18+ + +reduceRight\(callbackFn: ArrayReduceCallback\>, initialValue: U): U + +This API is similar to the previous API, but it takes an initial value as the second parameter to initialize the accumulator before the array traversal starts from right to left. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------------ | -------------------------------------------------------------------------------------------- | --- | ------------------------------------------ | +| callbackFn | ArrayReduceCallback\> | Yes | Function that takes four arguments. It performs an operation on each element and passes the result as an accumulated value to the next element.| +| initialValue | U | Yes | Initial value of the accumulator. | + +**Return value** + +| Type | Description | +| --- | ------------- | +| U | Final result obtained from the last call of the callback function.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md). + +| ID | Error Message | +| -------- | --------------------------------------- | +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | +| 10200011 | The reduceRight method cannot be bound. | +| 10200201 | Concurrent modification error. | -```ts -// Positive example: -let array: Array = ['str1', 'str2', 'str3']; // Native Array, where T is the sendable data type. -let sendableArray = collections.Array.from(array); // Returns Sendable Array. -``` +**Example** - ```ts -// Negative example: -let array: Array> = [['str1', 'str2', 'str3'], ['str4', 'str5', 'str6'], ['str7', 'str8', 'str9']]; // Native Array, where T is a non-sendable data type. -let sendableArray = collections.Array.from>(array); // Prints the following exception information: Parameter error.Only accept sendable value +// An accumulator with the initial value 0 is used. The accumulator is used to calculate the sum of all elements in the array and return the sum. +let array = new collections.Array(1, 2, 3, 4, 5); +let reducedValue = array.reduceRight((accumulator: number, value: number) => accumulator + value, 0); // Accumulated result of all elements. The initial value is 0. +console.info(reducedValue + ''); +// Expected output: 15 ``` ### pop @@ -488,6 +976,40 @@ let array = new collections.Array(1, 2, 3); let firstElement = array.shift(); // 1 is returned. The array changes to [2, 3]. ``` +### reverse18+ + +reverse(): Array\ + +Reverses elements in this ArkTS array and returns a reference to the same array. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Return value** + +| Type | Description | +| ----- | ------------------ | +| Array | Reversed ArkTS array.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](errorcode-utils.md). + +| ID | Error Message | +| -------- | ----------------------------------- | +| 10200011 | The reverse method cannot be bound. | +| 10200201 | Concurrent modification exception. | + +**Example** + +```ts +let array = new collections.Array(1, 2, 3, 4, 5); +let reversed = array.reverse(); +console.info(array.toString()); +// Expected output: 5, 4, 3, 2, 1 +``` + ### unshift unshift(...items: T[]): number @@ -526,6 +1048,40 @@ let array = new collections.Array(1, 2, 3); let newLength = array.unshift(0); // 4 is returned. The array changes to [0, 1, 2, 3]. ``` +### toString18+ + +toString(): string + +Converts an ArkTS array into a string. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Return value** + +| Type | Description | +| ---------- | ------------- | +| string | A string that contains all elements of the array.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](errorcode-utils.md). + +| ID | Error Message | +| -------- | ------------------------------------ | +| 10200011 | The toString method cannot be bound. | +| 10200201 | Concurrent modification error. | + +**Example** + +```ts +let array = new collections.Array(1, 2, 3, 4, 5); +let stringArray = array.toString(); +console.info(stringArray); +// Expected output: 1,2,3,4,5 +``` + ### slice slice(start?: number, end?: number): Array\ @@ -732,7 +1288,7 @@ Returns a new array containing all elements that pass a test provided by a callb | Name | Type | Mandatory| Description | | --------- | ------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| predicate | (value: T, index: number, array: Array\) => boolean | Yes | Function that takes three arguments. It is used to filter elements.| +| predicate | (value: T, index: number, array: Array\) => boolean | Yes | Function that takes three arguments. It is used to filter elements. The value **true** means that the current element passes the test and should be retained in the new array. The value **false** means that the current element fails the test and should be excluded from the new array.| **Return value** @@ -990,7 +1546,7 @@ Returns the value of the first element that passes a test provided by a callback | Name | Type | Mandatory| Description | | --------- | ---------------------------------------------------- | ---- | ------------------------------------------------------ | -| predicate | (value: T, index: number, obj: Array\) => boolean | Yes | Function that takes three arguments. It is used to filter elements.| +| predicate | (value: T, index: number, obj: Array\) => boolean | Yes | Function that takes three arguments. It is used to filter elements. The value **true** means that the current element meets the conditions, the traversal stops, and that element is returned. The value **false** means that the current element does not meet the condition, and the traversal continues until the element that meets the condition is found or the entire array is traversed.| **Return value** @@ -1035,7 +1591,7 @@ Checks whether this ArkTS array contains an element and returns a Boolean value. | Type | Description | | ------- | --------------------------------------------------- | -| boolean | **true**: The element exists.
**false**: The element does not exist.| +| boolean | Check result. The value **true** means that the element exists, and **false** means the opposite.| **Error codes** @@ -1067,7 +1623,7 @@ Returns the index of the first element that passes a test provided by a callback | Name | Type | Mandatory| Description | | --------- | ---------------------------------------------------- | ---- | ------------------------------------------------------ | -| predicate | (value: T, index: number, obj: Array\) => boolean | Yes | Function that takes three arguments. It is used to filter elements.| +| predicate | (value: T, index: number, obj: Array\) => boolean | Yes | Function that takes three arguments. It is used to filter elements. The value **true** means that the current element meets the conditions, the traversal stops, and the index of that element is returned. The value **false** means that the current element does not meet the condition, and the traversal continues until the element that meets the condition is found or the entire array is traversed.| **Return value** @@ -1272,7 +1828,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ---------------------------------- | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2.Incorrect parameter types. | +| 401 | Parameter error. Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types. | | 10200011 | The splice method cannot be bound. | | 10200201 | Concurrent modification error. | @@ -1283,6 +1839,80 @@ let array = new collections.Array(1, 2, 3, 4, 5); let removeArray = array.splice(2); // The array is changed to [1, 2], and [3, 4, 5] is returned. ``` +### every18+ + +every(predicate: ArrayPredicateFn\>): boolean + +Checks whether all elements in this ArkTS array meet a given condition. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ----------------------------------------------------- | +| predicate | ArrayPredicateFn\> | Yes| Assertion function used for the test.| + +**Return value** + +| Type | Description | +| ------------ | --------- | +| boolean | Check result. The value **true** means that all elements meet the given condition, and **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md). + +| ID| Error Message | +| -------- | ------------------------------------------------- | +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | +| 10200011 | The every method cannot be bound. | +| 10200201 | Concurrent modification exception. | + +**Example** + +```ts +let newArray: collections.Array = collections.Array.from([-10, 20, -30, 40, -50]); +console.info(newArray.every((element: number) => element > 0) + ''); +// Expected output: false +``` + +### toLocaleString18+ + +toLocaleString(): string + +Generates a string that matches the cultural conversions of the current system locale. Each element converts itself to a string via its **toLocaleString** API, and these strings are then joined together in sequence with commas (,). + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Return value** + +| Type | Description | +| ---------- | ------------- | +| string | A string that contains all elements of the array.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](errorcode-utils.md). + +| ID | Error Message | +| -------- | ------------------------------------------ | +| 10200011 | The toLocaleString method cannot be bound. | +| 10200201 | Concurrent modification error. | + +**Example** + +```ts +// The system where the application is running is set to the French locale. +let array = new collections.Array(1000, 'Test', 53621); +let stringArray = array.toLocaleString(); +console.info(stringArray); +// Expected output: 1,000,Test,53,621 +``` + ### splice splice(start: number, deleteCount: number, ...items: T[]): Array\ @@ -1313,7 +1943,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ---------------------------------- | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2.Incorrect parameter types. | +| 401 | Parameter error. Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types. | | 10200011 | The splice method cannot be bound. | | 10200201 | Concurrent modification error. | @@ -1665,7 +2295,7 @@ Deletes a specified key from this ArkTS map. | Type | Description | | ------- | ------------------------------------------------------------ | -| boolean | **true**: The key exists and has been deleted.
**false**: The key does not exist.| +| boolean | Operation result. The value **true** means that the key exists and has been deleted, and **false** means the opposite.| **Error codes** @@ -1803,7 +2433,7 @@ Checks whether a key exists in this ArkTS map. | Type | Description | | ------- | --------------------------------------------- | -| boolean | **true**: The key exists.
**false**: The key does not exist.| +| boolean | Check result. The value **true** means that the key exists, and **false** means the opposite.| **Error codes** @@ -2150,7 +2780,7 @@ Deletes an element from this ArkTS set. | Type | Description | | ------- | --------------------------------- | -| boolean | **true**: The key is deleted.
**false**: The key fails to be deleted.| +| boolean | Operation result. The value **true** means that the key is deleted, and **false** means the opposite.| **Error codes** @@ -2236,7 +2866,7 @@ Checks whether a value exists in this ArkTS set. | Type | Description | | ------- | --------------------------------------------- | -| boolean | **true**: The value exists.
**false**: The value does not exist.| +| boolean | Check result. The value **true** means that the value exists, and **false** means the opposite.| **Error codes** @@ -2462,7 +3092,7 @@ Describes the assertion function of the ArkTS typed array. | Type | Description | | ------ | --------------------------- | -| boolean | **true**: The value meets the condition.
**false**: The value does not meet the condition.| +| boolean | Operation result. The value **true** means that the value meets the condition, and **false** means the opposite.| ## TypedArrayForEachCallback type TypedArrayForEachCallback\ = (value: ElementType, index: number, array: ArrayType) => void @@ -2830,6 +3460,113 @@ let array: collections.Uint32Array = collections.Uint32Array.from( // Uint32Array [1, 3, 5] ``` +### of18+ + +static of(...items: number[]): TypedArray + +Creates an ArkTS typed array with a variable number of parameters. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------- | ---- | ------------------------------- | +| items | number[] | No | Array of elements used to create the array. The number of elements can be zero, one, or more.| + +**Return value** + +| Type | Description | +| --------- | ----------------------- | +| TypedArray | New ArkTS typed array.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message | +| -------- | -------------------------------- | +| 401 | Parameter error: Possible causes: 1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | + +**Example** + +```ts +let arr: collections.Uint32Array = collections.Uint32Array.of(1, 2, 3, 4) +console.info(arr.toString()); +// Expected output: 1,2,3,4 +``` + +### toString18+ + +toString(): string + +Converts an ArkTS typed array into a string. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Return value** + +| Type | Description | +| ---------- | ------------- | +| string | A string that contains all elements of the array.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](errorcode-utils.md). + +| ID | Error Message | +| -------- | ------------------------------------ | +| 10200011 | The toString method cannot be bound. | +| 10200201 | Concurrent modification error. | + +**Example** + +```ts +let array = new collections.Uint32Array([1, 2, 3, 4, 5]); +let stringArray = array.toString(); +console.info(stringArray); +// Expected output: 1,2,3,4,5 +``` + +### toLocaleString18+ + +toLocaleString(): string + +Generates a string of digits that matches the cultural conventions of the current system locale. Each element converts its digits to a string via its **toLocaleString** API, and these strings are then joined together in sequence with commas (,). + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Return value** + +| Type | Description | +| ---------- | ------------- | +| string | A string that contains all elements of the array.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](errorcode-utils.md). + +| ID | Error Message | +| -------- | ------------------------------------------ | +| 10200011 | The toLocaleString method cannot be bound. | +| 10200201 | Concurrent modification error. | + +**Example** + +```ts +// The system where the application is running is set to the French locale. +let array = new collections.Uint32Array([1000, 2000, 3000]); +let stringArray = array.toLocaleString(); +console.info(stringArray); +// Expected output: 1,000,2,000,3,000 +``` + ### copyWithin copyWithin(target: number, start: number, end?: number): TypedArray @@ -2889,7 +3626,7 @@ Checks whether any element in this ArkTS typed array meets a given condition. | Type | Description | | ------------ | --------- | -| boolean | **true**: An element meeting the given condition exists.
**false**: An element meeting the given condition does not exist.| +| boolean | Check result. The value **true** means that an element meeting the given condition exists, and **false** means the opposite.| **Error codes** @@ -2930,7 +3667,7 @@ Checks whether all elements in this ArkTS typed array meet a given condition. | Type | Description | | ------------ | --------- | -| boolean | **true**: All elements meet the given condition.
**false**: Not all elements meet the given condition.| +| boolean | Check result. The value **true** means that all elements meet the given condition, and **false** means the opposite.| **Error codes** @@ -3181,6 +3918,53 @@ array.indexOf(9, 2); // 2 array.indexOf(9, -2); // 2 ``` +### lastIndexOf18+ + +lastIndexOf(searchElement: number, fromIndex?: number): number + +Obtains the index of the last occurrence of the specified value in in this ArkTS typed array. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------------- | ------ | --- | --------------------------------------------------------------------------------- | +| searchElement | number | Yes | Value to search for. | +| fromIndex | number | No | Index from which the search starts. The default value is **0**. If the index is greater than or equal to the length of the ArkTS typed array, **-1** is returned. If a negative number is passed in, the search starts from the end of the ArkTS typed array.| + +**Return value** + +| Type | Description | +| ------ | ----------------------- | +| number | Index of the last occurrence of the value. If the value is not found, **-1** is returned.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md). + +| ID | Error Message | +| -------- | --------------------------------------- | +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | +| 10200001 | The value of fromIndex or toIndex is out of range. | +| 10200011 | The lastIndexOf method cannot be bound. | + +**Example** + +```ts +let array: collections.Uint32Array = collections.Uint32Array.from([3, 5, 9]); +console.info(array.lastIndexOf(3) + ''); +// Expected output: 0 +console.info(array.lastIndexOf(7) + ''); +// Expected output: -1 +console.info(array.lastIndexOf(9, 2) + ''); +// Expected output: 2 +console.info(array.lastIndexOf(9, -2) + ''); +// Expected output: -1 +``` + ### join join(separator?: string): string @@ -3292,6 +4076,46 @@ let reducedValue: number = array.reduce((accumulator: number, value: number) => // reducedValue == 15 ``` +### reduceRight18+ + +reduceRight(callbackFn: TypedArrayReduceCallback\): number + +Reversely traverses this ArkTS typed array, applies a reduce function on each element in the array, and returns the final reduction result. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** +| Name | Type | Mandatory| Description | +| ---------- | ---------------------- | ---- | ------------------------------------------------------------ | +| callbackFn | [TypedArrayReduceCallback](#typedarrayreducecallback)\ | Yes| Reduce function.| + +**Return value** + +| Type | Description | +| ------ | ----------- | +| number | Final result obtained from the last call of the reduce function.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md). + +| ID | Error Message | +| -------- | --------------------------------------- | +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | +| 10200011 | The reduceRight method cannot be bound. | +| 10200201 | Concurrent modification exception. | + +**Example** + +```ts +let array: collections.Uint32Array = collections.Uint32Array.from([1, 2, 3, 4, 5]); +let reducedValue: number = array.reduceRight((accumulator: number, value: number) => accumulator + value); +console.info(reducedValue + ''); +// Expected output: 15 +``` + ### reduce reduce(callbackFn: TypedArrayReduceCallback\, initialValue: number): number @@ -3331,6 +4155,47 @@ let reducedValue: number = array.reduce((accumulator: number, value: number) => // reducedValue == 16 ``` +### reduceRight18+ + +reduceRight\(callbackFn: TypedArrayReduceCallback\, initialValue: U): U + +Reversely traverses this ArkTS typed array, applies a reduce function for each element in the array, receives an initial value as the parameter called by the reduce function for the first time, and returns the final reduction result. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | --------------------------------------------------- | +| callbackFn | [TypedArrayReduceCallback](#typedarrayreducecallback)\ | Yes | Reduce function.| +| initialValue | U | Yes | Initial value.| + +**Return value** + +| Type | Description | +| ------ | ----------- | +| U | Final result obtained from the last call of the reduce function.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md). + +| ID | Error Message | +| -------- | --------------------------------------- | +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. | +| 10200011 | The reduceRight method cannot be bound. | +| 10200201 | Concurrent modification exception. | + +**Example** + +```ts +let array: collections.Uint32Array = collections.Uint32Array.from([1, 2, 3, 4, 5]); +let reducedValue: number = array.reduceRight((accumulator: number, value: number) => accumulator + value, 1); +console.info(reducedValue + ''); +// Expected output: 16 +``` + ### reduce reduce\(callbackFn: TypedArrayReduceCallback\, initialValue: U): U @@ -3608,7 +4473,7 @@ Checks whether elements are contained in this ArkTS typed array. | Type | Description | | ------- | ---------------------------------------------------------- | -| boolean | **true**: The element exists.
**false**: The element does not exist.| +| boolean | Check result. The value **true** means that the element exists, and **false** means the opposite.| **Error codes** @@ -3868,7 +4733,7 @@ Adds an element at the end of this bit vector. | Type | Description | | ------- | --------------------------------- | -| boolean | **true**: The element is added.
**false**: The element fails to add.| +| boolean | Operation result. The value **true** means that the element is added, and **false** means the opposite.| **Error codes** @@ -3876,7 +4741,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2.Incorrect parameter types. | +| 401 | Parameter error. Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types. | | 10200011 | The push method cannot be bound. | | 10200201 | Concurrent modification error. | @@ -3926,7 +4791,7 @@ bitVector.push(0); bitVector.push(1); bitVector.push(0); // bitVector: [0, 1, 0, 1, 0] let res = bitVector.pop(); // bitVector: [0, 1, 0, 1] -console.info("bitVector pop:", res) // 0 +console.info("bitVector pop:", res); // 0 ``` ### has @@ -3951,7 +4816,7 @@ Checks whether a bit value is included in a given range of this bit vector. | Type | Description | | ------- | -------------------------------------- | -| boolean | **true**: The bit value exists.
**false**: The bit value does not exist.| +| boolean | Check result. The value **true** means that the bit value exists, and **false** means the opposite.| **Error codes** @@ -3959,7 +4824,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2.Incorrect parameter types. | +| 401 | Parameter error. Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types. | | 10200001 | The value of fromIndex or toIndex is out of range. | | 10200011 | The has method cannot be bound. | | 10200201 | Concurrent modification error. | @@ -3974,7 +4839,7 @@ bitVector.push(0); bitVector.push(1); bitVector.push(0); // bitVector: [0, 1, 0, 1, 0] let res0: boolean = bitVector.has(0, 1, 4); -console.info("bitVector has 0:", res0) // true +console.info("bitVector has 0:", res0); // true ``` ### setBitsByRange @@ -4001,7 +4866,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2.Incorrect parameter types. | +| 401 | Parameter error. Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types. | | 10200001 | The value of fromIndex or toIndex is out of range. | | 10200011 | The setBitsByRange method cannot be bound. | | 10200201 | Concurrent modification error. | @@ -4040,7 +4905,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2.Incorrect parameter types. | +| 401 | Parameter error. Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types. | | 10200011 | The setAllBits method cannot be bound. | | 10200201 | Concurrent modification error. | @@ -4085,7 +4950,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2.Incorrect parameter types. | +| 401 | Parameter error. Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types. | | 10200001 | The value of fromIndex or toIndex is out of range. | | 10200011 | The getBitsByRange method cannot be bound. | | 10200201 | Concurrent modification error. | @@ -4100,7 +4965,7 @@ bitVector.push(0); bitVector.push(1); bitVector.push(0); // bitVector: [0, 1, 0, 1, 0] let bitVector2 = bitVector.getBitsByRange(1, 3); // bitVector2: [1, 0] -console.info("bitVector2 length:", bitVector2.length) // 2 +console.info("bitVector2 length:", bitVector2.length); // 2 ``` ### resize @@ -4129,7 +4994,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2.Incorrect parameter types. | +| 401 | Parameter error. Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types. | | 10200011 | The resize method cannot be bound. | | 10200201 | Concurrent modification error. | @@ -4143,9 +5008,9 @@ bitVector.push(0); bitVector.push(1); bitVector.push(0); // bitVector: [0, 1, 0, 1, 0] bitVector.resize(10); // bitVector: [0, 1, 0, 1, 0, 0, 0, 0, 0, 0] -console.info("bitVector get bit vector's length:", bitVector.length) // 10 +console.info("bitVector get bit vector's length:", bitVector.length); // 10 bitVector.resize(3); // bitVector: [0, 1, 0] -console.info("bitVector get bit vector's length:", bitVector.length) // 3 +console.info("bitVector get bit vector's length:", bitVector.length); // 3 ``` ### getBitCountByRange @@ -4178,7 +5043,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2.Incorrect parameter types. | +| 401 | Parameter error. Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types. | | 10200001 | The value of fromIndex or toIndex is out of range. | | 10200011 | The getBitCountByRange method cannot be bound. | | 10200201 | Concurrent modification error. | @@ -4193,7 +5058,7 @@ bitVector.push(0); bitVector.push(1); bitVector.push(0); // bitVector: [0, 1, 0, 1, 0] let res: number = bitVector.getBitCountByRange(1, 1, 4); -console.info("bitVector getBitCountByRange:", res) // 2 +console.info("bitVector getBitCountByRange:", res); // 2 ``` ### getIndexOf @@ -4226,7 +5091,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2.Incorrect parameter types. | +| 401 | Parameter error. Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types. | | 10200001 | The value of fromIndex or toIndex is out of range. | | 10200011 | The getIndexOf method cannot be bound. | | 10200201 | Concurrent modification error. | @@ -4241,7 +5106,7 @@ bitVector.push(0); bitVector.push(1); bitVector.push(0); // bitVector: [0, 1, 0, 1, 0] let res: number = bitVector.getIndexOf(0, 1, 4); -console.info("bitVector getIndexOf:", res) // 2 +console.info("bitVector getIndexOf:", res); // 2 ``` ### getLastIndexOf @@ -4274,7 +5139,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2.Incorrect parameter types. | +| 401 | Parameter error. Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types. | | 10200001 | The value of fromIndex or toIndex is out of range. | | 10200011 | The getLastIndexOf method cannot be bound. | | 10200201 | Concurrent modification error. | @@ -4289,7 +5154,7 @@ bitVector.push(0); bitVector.push(1); bitVector.push(0); // bitVector: [0, 1, 0, 1, 0] let res: number = bitVector.getLastIndexOf(0, 1, 4); -console.info("bitVector getLastIndexOf:", res) // 2 +console.info("bitVector getLastIndexOf:", res); // 2 ``` ### flipBitByIndex @@ -4314,7 +5179,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2.Incorrect parameter types. | +| 401 | Parameter error. Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types. | | 10200001 | The value of index is out of range. | | 10200011 | The flipBitByIndex method cannot be bound. | | 10200201 | Concurrent modification error. | @@ -4354,7 +5219,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Mandatory parameters are left unspecified;
2.Incorrect parameter types. | +| 401 | Parameter error. Possible causes:1.Mandatory parameters are left unspecified;2.Incorrect parameter types. | | 10200001 | The value of fromIndex or toIndex is out of range. | | 10200011 | The flipBitsByRange method cannot be bound. | | 10200201 | Concurrent modification error. | diff --git a/en/application-dev/reference/apis-arkts/js-apis-arkts-decimal.md b/en/application-dev/reference/apis-arkts/js-apis-arkts-decimal.md index def57fd3991cd2b7a73a693e0d0b5e705f3fe3cd..4f7ab587836c0ebdcd3acdc6fe8b6ba6fd4f0cda 100644 --- a/en/application-dev/reference/apis-arkts/js-apis-arkts-decimal.md +++ b/en/application-dev/reference/apis-arkts/js-apis-arkts-decimal.md @@ -5,7 +5,8 @@ The Decimal module provides a high-precision math library that offers the capabi > **NOTE** > > The initial APIs of this module are supported since API version 12. Newly added APIs will be marked with a superscript to indicate their earliest API version. - +> +> This module can be imported only to ArkTS files (with the file name extension .ets). ## Modules to Import @@ -90,7 +91,7 @@ Describes the configuration of a **Decimal** object. You can call [Decimal.set]( | toExpPos | number | No | No | Positive exponent value at and above which [toString](#tostring) returns exponential notation. The value range is [0, 9e15], and the default value is **21**.| | minE | number | No | No | Minimum negative exponents. A decimal with an exponent less than this minimum value underflows towards zero. The value range is [-9e15, 0], and the default value is **-9e15**.| | maxE | number | No | No | Maximum positive exponent. A decimal with an exponent greater than this maximum value overflows to infinity. The value range is [0, 9e15], and the default value is **9e15**.| -| crypto | boolean | No | No | Whether to use a pseudorandom number for encryption. The default value is **false**. The capability is not supported yet, and error code 10200061 is reported if it is used. | +| crypto | boolean | No | No | Whether to use a pseudorandom number for encryption. The value **true** means to use a pseudorandom number for encryption, and **false** means the opposite. The default value is **false**. The capability is not supported yet, and error code 10200061 is reported if it is used. | | modulo | [Modulo](#modulo) | No | No | Rounding mode used in the modulo operation. The value is an integer ranging from 0 to 9, and the default value is **1**. | | defaults | boolean | No | No | Whether the default value is used if no value is passed in for a property. The value **true** means that the default value is used, and **false** means the opposite. The default value is **true**.| @@ -151,7 +152,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -164,7 +165,7 @@ console.info("test Decimal constructor:" + data.toString()); // 'test Decimal co abs(): Decimal -Returns a new **Decimal** object representing the absolute value of this decimal. +Returns a **Decimal** object representing the absolute value of this decimal. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -187,7 +188,7 @@ console.info("test Decimal abs:" + data.toString()); // 'test Decimal abs:0.5' floor(): Decimal -Returns a new **Decimal** object representing the nearest integer to which this decimal is rounded down. +Returns a **Decimal** object representing the nearest integer to which this decimal is rounded down. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -210,7 +211,7 @@ console.info("test Decimal floor:" + data.toString()); // 'test Decimal floor:1' ceil(): Decimal -Returns a new **Decimal** object representing the nearest integer to which this decimal is rounded up. +Returns a **Decimal** object representing the nearest integer to which this decimal is rounded up. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -233,7 +234,7 @@ console.info("test Decimal ceil:" + data.toString()); // 'test Decimal ceil:2' trunc(): Decimal -Returns a new **Decimal** object representing the integer part truncated from this decimal. +Returns a **Decimal** object representing the integer part truncated from this decimal. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -256,7 +257,7 @@ console.info("test Decimal trunc:" + data.toString()); // 'test Decimal trunc:2' clamp(min: Value, max: Value): Decimal -Returns a new **Decimal** object representing the value clamped to the inclusive range of **min** and **max**. +Returns a **Decimal** object representing the value clamped to the inclusive range of **min** and **max**. If the actual value exceeds the maximum limit, **max** is returned; if it falls below the minimum limit, **min** is returned; otherwise, the actual value is returned. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -281,7 +282,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | | 10200001 | The value of 'min' is out of range. | **Example** @@ -295,9 +296,9 @@ console.info("test Decimal clamp:" + data.toString()); // 'test Decimal clamp:10 ### add -add(n: Value): Decimal; +add(n: Value): Decimal -Returns a new **Decimal** object representing the sum of adding the specified number *n* to this decimal. +Returns a **Decimal** object representing the sum of adding the specified number *n* to this decimal. You can use [DecimalConfig.precision](#decimalconfig) to specify the precision and use [DecimalConfig.rounding](#decimalconfig) to specify the rounding mode. @@ -323,7 +324,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -336,7 +337,7 @@ console.info("test Decimal add:" + data.toString()); // 'test Decimal add:1' sub(n: Value): Decimal -Returns a new **Decimal** object representing the difference of subtracting the specified number *n* from this decimal. +Returns a **Decimal** object representing the difference of subtracting the specified number *n* from this decimal. You can use [DecimalConfig.precision](#decimalconfig) to specify the precision and use [DecimalConfig.rounding](#decimalconfig) to specify the rounding mode. @@ -362,7 +363,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -375,7 +376,7 @@ console.info("test Decimal sub:" + data.toString()); // 'test Decimal sub:0.5' mul(n: Value): Decimal -Returns a new **Decimal** object representing the product of multiplying this decimal by the specified number *n*. +Returns a **Decimal** object representing the product of multiplying this decimal by the specified number *n*. You can use [DecimalConfig.precision](#decimalconfig) to specify the precision and use [DecimalConfig.rounding](#decimalconfig) to specify the rounding mode. @@ -401,7 +402,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -414,7 +415,7 @@ console.info("test Decimal mul:" + data.toString()); // 'test Decimal mul:0.5' div(n: Value): Decimal -Returns a new **Decimal** object representing the quotient of dividing this decimal by the specified number *n*. +Returns a **Decimal** object representing the quotient of dividing this decimal by the specified number *n*. You can use [DecimalConfig.precision](#decimalconfig) to specify the precision and use [DecimalConfig.rounding](#decimalconfig) to specify the rounding mode. @@ -440,7 +441,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -453,7 +454,7 @@ console.info("test Decimal div:" + data.toString()); // 'test Decimal div:2' mod(n: Value): Decimal -Returns a new **Decimal** object representing the remainder of dividing this decimal by the specified number *n*. +Returns a **Decimal** object representing the remainder of dividing this decimal by the specified number *n*. You can use [DecimalConfig.precision](#decimalconfig) to specify the precision and use [DecimalConfig.rounding](#decimalconfig) to specify the rounding mode. @@ -479,7 +480,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -492,7 +493,7 @@ console.info("test Decimal mod:" + data.toString()); // 'test Decimal mod:0' sqrt(): Decimal -Returns a new **Decimal** object representing the square root of this decimal. +Returns a **Decimal** object representing the square root of this decimal. You can use [DecimalConfig.precision](#decimalconfig) to specify the precision and use [DecimalConfig.rounding](#decimalconfig) to specify the rounding mode. @@ -517,7 +518,7 @@ console.info("test Decimal sqrt:" + data.toString()); // 'test Decimal sqrt:1.73 cbrt(): Decimal -Returns a new **Decimal** object representing the cube root of this decimal. +Returns a **Decimal** object representing the cube root of this decimal. You can use [DecimalConfig.precision](#decimalconfig) to specify the precision and use [DecimalConfig.rounding](#decimalconfig) to specify the rounding mode. @@ -542,7 +543,7 @@ console.info("test Decimal cbrt:" + data.toString()); // 'test Decimal cbrt:1.44 pow(n: Value): Decimal -Returns a new **Decimal** object representing the value resulting from raising this decimal to the power of the specified number *n*. +Returns a **Decimal** object representing the value resulting from raising this decimal to the power of the specified number *n*. You can use [DecimalConfig.precision](#decimalconfig) to specify the precision and use [DecimalConfig.rounding](#decimalconfig) to specify the rounding mode. @@ -568,7 +569,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | | 10200060 | Precision limit exceeded. | **Example** @@ -582,7 +583,7 @@ console.info("test Decimal pow:" + data.toString()); // 'test Decimal pow:0.1111 exp(): Decimal -Returns a new **Decimal** object representing the value resulting from raising e to the power of this decimal. +Returns a **Decimal** object representing the value resulting from raising e to the power of this decimal. You can use [DecimalConfig.precision](#decimalconfig) to specify the precision and use [DecimalConfig.rounding](#decimalconfig) to specify the rounding mode. @@ -615,7 +616,7 @@ console.info("test Decimal exp:" + data.toString()); // 'test Decimal exp:7.3890 log(n: Value): Decimal -Returns a new **Decimal** object representing the logarithm of this decimal to the specified base *n*. +Returns a **Decimal** object representing the logarithm of this decimal to the specified base *n*. You can use [DecimalConfig.precision](#decimalconfig) to specify the precision and use [DecimalConfig.rounding](#decimalconfig) to specify the rounding mode. @@ -641,7 +642,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | | 10200060 | Precision limit exceeded. | **Example** @@ -655,7 +656,7 @@ console.info("test Decimal log:" + data.toString()); // 'test Decimal log:0.125' ln(): Decimal -Returns a new **Decimal** object representing the natural logarithm of this decimal. +Returns a **Decimal** object representing the natural logarithm of this decimal. You can use [DecimalConfig.precision](#decimalconfig) to specify the precision and use [DecimalConfig.rounding](#decimalconfig) to specify the rounding mode. @@ -688,7 +689,7 @@ console.info("test Decimal ln:" + data.toString()); // 'test Decimal ln:69.28456 cos(): Decimal -Returns a new **Decimal** object representing the cosine of this decimal. +Returns a **Decimal** object representing the cosine of this decimal. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -711,7 +712,7 @@ console.info("test Decimal cos:" + data.toString()); // 'test Decimal cos:0.9689 sin(): Decimal -Returns a new **Decimal** object representing the sine of this decimal. +Returns a **Decimal** object representing the sine of this decimal. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -734,7 +735,7 @@ console.info("test Decimal sin:" + data.toString()); // 'test Decimal sin:0.6816 tan(): Decimal -Returns a new **Decimal** object representing the tangent of this decimal. +Returns a **Decimal** object representing the tangent of this decimal. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -757,7 +758,7 @@ console.info("test Decimal tan:" + data.toString()); // 'test Decimal tan:0.9315 cosh(): Decimal -Returns a new **Decimal** object representing the hyperbolic cosine of this decimal. +Returns a **Decimal** object representing the hyperbolic cosine of this decimal. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -780,7 +781,7 @@ console.info("test Decimal cosh:" + data.toString()); // 'test Decimal cosh:1.12 sinh(): Decimal -Returns a new **Decimal** object representing the hyperbolic sine of this decimal. +Returns a **Decimal** object representing the hyperbolic sine of this decimal. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -803,7 +804,7 @@ console.info("test Decimal sinh:" + data.toString()); // 'test Decimal sinh:0.52 tanh(): Decimal -Returns a new **Decimal** object representing the hyperbolic tangent of this decimal. +Returns a **Decimal** object representing the hyperbolic tangent of this decimal. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -826,7 +827,7 @@ console.info("test Decimal tanh:" + data.toString()); // 'test Decimal tanh:0.46 acos(): Decimal -Returns a new **Decimal** object representing the arc cosine of this decimal. +Returns a **Decimal** object representing the arc cosine of this decimal. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -857,7 +858,7 @@ console.info("test Decimal acos:" + data.toString()); // 'test Decimal acos:1.04 asin(): Decimal -Returns a new **Decimal** object representing the arc sine of this decimal. +Returns a **Decimal** object representing the arc sine of this decimal. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -888,7 +889,7 @@ console.info("test Decimal asin:" + data.toString()); // 'test Decimal asin:0.84 atan(): Decimal -Returns a new **Decimal** object representing the arc tangent of this decimal. +Returns a **Decimal** object representing the arc tangent of this decimal. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -919,7 +920,7 @@ console.info("test Decimal atan:" + data.toString()); // 'test Decimal atan:0.64 acosh(): Decimal -Returns a new **Decimal** object representing the inverse hyperbolic cosine of this decimal. +Returns a **Decimal** object representing the inverse hyperbolic cosine of this decimal. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -950,7 +951,7 @@ console.info("test Decimal acosh:" + data.toString()); // 'test Decimal acosh:4. asinh(): Decimal -Returns a new **Decimal** object representing the inverse hyperbolic sine of this decimal. +Returns a **Decimal** object representing the inverse hyperbolic sine of this decimal. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -981,7 +982,7 @@ console.info("test Decimal asinh:" + data.toString()); // 'test Decimal asinh:4. atanh(): Decimal -Returns a new **Decimal** object representing the inverse hyperbolic tangent of this decimal. +Returns a **Decimal** object representing the inverse hyperbolic tangent of this decimal. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -1036,7 +1037,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -1070,7 +1071,7 @@ Checks whether this decimal is equal to the specified number *n*. | Type | Description | | ------- | ------------------------------------------------ | -| boolean | **true**: They are equal.
**false**: They are not equal.| +| boolean | Check result. The value **true** means that they are equal, and **false** means the opposite.| **Error codes** @@ -1078,7 +1079,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -1108,7 +1109,7 @@ Checks whether this decimal is greater than the specified number *n*. | Type | Description | | ------- | ---------------------------------------------- | -| boolean | **true**: The decimal is greater than *n*.
**false**: The decimal is not greater than *n*.| +| boolean | Check result. The value **true** means that the decimal is greater than *n*, and **false** means the opposite.| **Error codes** @@ -1116,7 +1117,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -1146,7 +1147,7 @@ Checks whether this decimal is greater than or equal to the specified number *n* | Type | Description | | ------- | -------------------------------------------------- | -| boolean | **true**: The decimal is greater than or equal to *n*.
**false**: The decimal is not greater than or equal to *n*.| +| boolean | Check result. The value **true** means that the decimal is greater than or equal to *n*, and **false** means the opposite.| **Error codes** @@ -1154,7 +1155,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -1184,7 +1185,7 @@ Checks whether this decimal is less than the specified number *n*. | Type | Description | | ------- | ---------------------------------------------- | -| boolean | **true**: The decimal is less than *n*.
**false**: The decimal is not less than *n*.| +| boolean | Check result. The value **true** means that the decimal is less than *n*, and **false** means the opposite.| **Error codes** @@ -1192,7 +1193,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -1222,7 +1223,7 @@ Checks whether this decimal is less than or equal to the specified number *n*. | Type | Description | | ------- | -------------------------------------------------- | -| boolean | **true**: The decimal is less than or equal to *n*.
**false**: The decimal is not less than or equal to *n*.| +| boolean | Check result. The value **true** means that the decimal is less than or equal to *n*, and **false** means the opposite.| **Error codes** @@ -1230,7 +1231,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -1254,7 +1255,7 @@ Checks whether this decimal is finite. | Type | Description | | ------- | -------------------------------------------- | -| boolean | **true**: The decimal is finite.
**false**: The decimal is not finite.| +| boolean | Check result. The value **true** means that the decimal is finite, and **false** means the opposite.| **Example** @@ -1278,7 +1279,7 @@ Checks whether this decimal is an integer. | Type | Description | | ------- | ------------------------------------------ | -| boolean | **true**: The decimal is an integer.
**false**: The decimal is not an integer.| +| boolean | Check result. The value **true** means that the decimal is an integer, and **false** means the opposite.| **Example** @@ -1302,7 +1303,7 @@ Checks whether this decimal is NaN. | Type | Description | | ------- | ----------------------------------------- | -| boolean | **true**: The decimal is NaN.
**false**: The decimal is not NaN.| +| boolean | Check result. The value **true** means that the decimal is NaN, **false** means the opposite.| **Example** @@ -1316,7 +1317,7 @@ console.info("test Decimal isNaN:" + data1); // 'test Decimal isNaN:true' isNegative(): boolean -Checks whether this decimal is negative. +Checks whether this decimal is negative (including a distinction between positive and negative zero). **Atomic service API**: This API can be used in atomic services since API version 12. @@ -1326,7 +1327,7 @@ Checks whether this decimal is negative. | Type | Description | | ------- | ------------------------------------------ | -| boolean | **true**: The decimal is negative.
**false**: The decimal is not negative.| +| boolean | Check result. The value **true** means that the decimal is negative, and **false** means the opposite.| **Example** @@ -1336,7 +1337,7 @@ let data1: boolean = data.isNegative(); console.info("test Decimal isNegative:" + data1); // 'test Decimal isNegative:true' let data2: Decimal = new Decimal(-0); -let data3: boolean = data.isNegative(); +let data3: boolean = data2.isNegative(); console.info("test Decimal isNegative:" + data3); // 'test Decimal isNegative:true' ``` @@ -1344,7 +1345,7 @@ console.info("test Decimal isNegative:" + data3); // 'test Decimal isNegative:tr isPositive(): boolean -Checks whether this decimal is positive. +Checks whether this decimal is positive (including a distinction between positive and negative zero). **Atomic service API**: This API can be used in atomic services since API version 12. @@ -1354,7 +1355,7 @@ Checks whether this decimal is positive. | Type | Description | | ------- | ------------------------------------------ | -| boolean | **true**: The decimal is positive.
**false**: The decimal is not positive.| +| boolean | Check result. The value **true** means that the decimal is positive, and **false** means the opposite.| **Example** @@ -1364,7 +1365,7 @@ let data1: boolean = data.isPositive(); console.info("test Decimal isPositive:" + data1); // 'test Decimal isPositive:true' let data2: Decimal = new Decimal(0); -let data3: boolean = data.isPositive(); +let data3: boolean = data2.isPositive(); console.info("test Decimal isPositive:" + data3); // 'test Decimal isPositive:true' ``` @@ -1382,7 +1383,7 @@ Returns whether this decimal is zero or minus zero. | Type | Description | | ------- | --------------------------------------------- | -| boolean | **true**: The decimal is zero or minus zero.
**false**: The decimal is not zero.| +| boolean | Check result. The value **true** means that the decimal is zero or minus zero, and **false** means the opposite.| **Example** @@ -1396,7 +1397,7 @@ console.info("test Decimal isZero:" + data1.toString()); // 'test Decimal isZero dividedToIntegerBy(n: Value): Decimal -Returns a new **Decimal** object representing the integer part of this decimal divided by the specified number *n*. +Returns a **Decimal** object representing the integer part of this decimal divided by the specified number *n*. You can use [DecimalConfig.precision](#decimalconfig) to specify the precision and use [DecimalConfig.rounding](#decimalconfig) to specify the rounding mode. @@ -1422,7 +1423,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -1437,7 +1438,7 @@ console.info("test Decimal dividedToIntegerBy:" + data2.toString()); // 'test De negate(): Decimal -Returns a new **Decimal** object representing the result of multiplying this decimal by negative one. +Returns a **Decimal** object representing the result of multiplying this decimal by negative one. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -2146,7 +2147,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -2644,7 +2645,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -2681,7 +2682,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -2718,7 +2719,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -2755,7 +2756,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -2768,7 +2769,7 @@ console.info("test Decimal trunc:" + data.toString()); // 'test Decimal trunc:2' static clamp(n: Value, min: Value, max: Value): Decimal -Returns a **Decimal** object representing the value clamped to the inclusive range of **min** and **max** of the specified number *n*. +Returns a **Decimal** object representing the value clamped to the inclusive range of **min** and **max** of the specified number *n*. If the actual value exceeds the maximum limit, **max** is returned; if it falls below the minimum limit, **min** is returned; otherwise, the actual value is returned. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -2794,7 +2795,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | | 10200001 | The value of 'min' is out of range. | **Example** @@ -2835,7 +2836,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -2874,7 +2875,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -2914,7 +2915,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -2954,7 +2955,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -2994,7 +2995,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -3035,7 +3036,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -3074,7 +3075,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -3113,7 +3114,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -3151,7 +3152,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | | 10200060 | Precision limit exceeded. | **Example** @@ -3191,7 +3192,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | | 10200060 | Precision limit exceeded. | **Example** @@ -3232,7 +3233,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | | 10200060 | Precision limit exceeded. | **Example** @@ -3272,7 +3273,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | | 10200060 | Precision limit exceeded. | **Example** @@ -3312,7 +3313,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | | 10200060 | Precision limit exceeded. | **Example** @@ -3352,7 +3353,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | | 10200060 | Precision limit exceeded. | **Example** @@ -3392,7 +3393,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -3431,7 +3432,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -3470,7 +3471,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -3509,7 +3510,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -3548,7 +3549,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -3587,7 +3588,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -3626,7 +3627,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | | 10200060 | Precision limit exceeded. | **Example** @@ -3666,7 +3667,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | | 10200060 | Precision limit exceeded. | **Example** @@ -3706,7 +3707,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | | 10200060 | Precision limit exceeded. | **Example** @@ -3746,7 +3747,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | | 10200060 | Precision limit exceeded. | **Example** @@ -3786,7 +3787,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | | 10200060 | Precision limit exceeded. | **Example** @@ -3826,7 +3827,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | | 10200060 | Precision limit exceeded. | **Example** @@ -3867,7 +3868,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | | 10200060 | Precision limit exceeded. | **Example** @@ -3907,7 +3908,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -3944,7 +3945,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -3981,7 +3982,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -4048,7 +4049,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | | 10200061 | Crypto unavailable. | **Example** @@ -4085,7 +4086,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -4122,7 +4123,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | **Example** @@ -4154,7 +4155,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 401 | Parameter error. Possible causes:
1. Incorrect parameter types;
2. Parameter verification failed. | +| 401 | Parameter error. Possible causes:1. Incorrect parameter types;2. Parameter verification failed. | | 10200001 | The value of 'DecimalConfig.properties' is out of range. | | 10200061 | Crypto unavailable. | diff --git a/en/application-dev/reference/apis-arkts/js-apis-arkts-lang.md b/en/application-dev/reference/apis-arkts/js-apis-arkts-lang.md index 40d6aac017e5391d869ed40e0b9bd63e4df72cea..585496efbe5dde8afdac6237f7b1c0964d86db64 100644 --- a/en/application-dev/reference/apis-arkts/js-apis-arkts-lang.md +++ b/en/application-dev/reference/apis-arkts/js-apis-arkts-lang.md @@ -5,6 +5,8 @@ The module provides the basic type definition of ArkTS. Currently, the **ISendab > **NOTE** > > The initial APIs of this module are supported since API version 12. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> This module can be imported only to ArkTS files (with the file name extension .ets). ## Modules to Import diff --git a/en/application-dev/reference/apis-arkts/js-apis-arkts-utils.md b/en/application-dev/reference/apis-arkts/js-apis-arkts-utils.md index 60aa2b355320ab18815279a53b49b39a65a2b232..5fc225bf3d80391f76d2210492f6cc1a7733f281 100644 --- a/en/application-dev/reference/apis-arkts/js-apis-arkts-utils.md +++ b/en/application-dev/reference/apis-arkts/js-apis-arkts-utils.md @@ -5,6 +5,8 @@ The Utils module provides a variety of ArkTS utility functions. > **NOTE** > > The initial APIs of this module are supported since API version 12. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> This module can be imported only to ArkTS files (with the file name extension .ets). ## Modules to Import @@ -32,7 +34,7 @@ A supplementary type alias that represents the callback in all the overloads of ### AsyncLock -A class that implements an asynchronous lock and allows asynchronous operations to be performed under a lock. +A class that implements an asynchronous lock and allows asynchronous operations to be performed under a lock. This class is decorated by [@Sendable](../../arkts-utils/arkts-sendable.md). #### Attributes @@ -163,10 +165,11 @@ Queries information about an asynchronous lock. **Error codes** -For details about the error codes, see [Utils Error Codes](errorcode-utils.md). +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md). | ID| Error Message | | -------- | ------------- | +| 401 | The input parameters are invalid. | | 10200030 | The lock does not exist. | **Example** @@ -231,10 +234,11 @@ Performs an operation exclusively under a lock. This API acquires the lock, exec **Error codes** -For details about the error codes, see [Utils Error Codes](errorcode-utils.md). +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md). | ID| Error Message | | -------- | ------------- | +| 401 | The input parameters are invalid. | | 10200030 | The lock does not exist. | **Example** @@ -271,10 +275,11 @@ Performs an operation under a lock. This API acquires the lock, executes the cal **Error codes** -For details about the error codes, see [Utils Error Codes](errorcode-utils.md). +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md). | ID| Error Message | | -------- | ------------- | +| 401 | The input parameters are invalid. | | 10200030 | The lock does not exist. | **Example** @@ -312,10 +317,11 @@ Performs an operation under a lock. This API acquires the lock, executes the cal **Error codes** -For details about the error codes, see [Utils Error Codes](errorcode-utils.md). +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Utils Error Codes](errorcode-utils.md). | ID| Error Message | | -------- | ----------------- | +| 401 | The input parameters are invalid. | | 10200030 | The lock does not exist. | | 10200031 | Timeout exceeded. | @@ -353,27 +359,27 @@ Enumerates the modes of an asynchronous lock. let lock = new ArkTSUtils.locks.AsyncLock(); // shared0 can acquire the lock and start execution. lock.lockAsync(async () => { - console.log('shared0'); + console.info('shared0'); await new Promise((resolve) => setTimeout(resolve, 1000)); }, ArkTSUtils.locks.AsyncLockMode.SHARED); // shared1 can acquire the lock and start execution without waiting for shared0. lock.lockAsync(async () => { - console.log('shared1'); + console.info('shared1'); await new Promise((resolve) => setTimeout(resolve, 1000)); }, ArkTSUtils.locks.AsyncLockMode.SHARED); // exclusive0 can acquire the lock and start execution after shared0 and shared1 are executed. lock.lockAsync(async () => { - console.log('exclusive0'); + console.info('exclusive0'); await new Promise((resolve) => setTimeout(resolve, 1000)); }, ArkTSUtils.locks.AsyncLockMode.EXCLUSIVE); // shared2 can acquire the lock and start execution after exclusive0 is executed. lock.lockAsync(async () => { - console.log('shared2'); + console.info('shared2'); await new Promise((resolve) => setTimeout(resolve, 1000)); }, ArkTSUtils.locks.AsyncLockMode.SHARED); // shared3 can acquire the lock and start execution after exclusive0 is executed, but not after shared2 is executed. lock.lockAsync(async () => { - console.log('shared3'); + console.info('shared3'); await new Promise((resolve) => setTimeout(resolve, 1000)); }, ArkTSUtils.locks.AsyncLockMode.SHARED); ``` @@ -418,7 +424,7 @@ options.signal = s; | Name | Type | Readable| Writable| Description | | ----------- | ------------------------------------- | ---- | ---- | ------------------------------------------------------------------------------------------------------------------------- | | isAvailable | boolean | Yes | Yes | Whether the lock is available. If the value is **true**, a lock is granted only when it is not held. If the value is **false**, a lock is granted once it is released. The default value is **false**.| -| signal | [AbortSignal\](#abortsignal)\|null | Yes | Yes | Signal used to abort an asynchronous operation. If **signal.aborted** is **true**, the lock request is discarded. If **signal.aborted** is **null**, the request is queued normally. The default value is **null**. | +| signal | [AbortSignal\](#abortsignal)\|null | Yes | Yes | Signal used to abort an asynchronous operation. If **signal.aborted** is **true**, the lock request is discarded. If **signal.aborted** is **false**, the request keeps waiting. If **signal.aborted** is **null**, the request is queued normally. The default value is **null**. | | timeout | number | Yes | Yes | Timeout interval of the lock request, in milliseconds. If the value is greater than zero and a lock is not acquired before time, [lockAsync](#lockasync) returns a rejected Promise. The default value is **0**. | ### AsyncLockState @@ -464,9 +470,176 @@ A class that implements a signal used to abort an asynchronous operation. An ins | Name | Type | Readable| Writable| Description | | ------- | ------- | ---- | ---- | ---------------------------------------------------------------- | -| aborted | boolean | Yes | Yes | Whether to abort the operation. The value **true** means to abort the operation, and **false** means the opposite. | +| aborted | boolean | Yes | Yes | Whether to abort the asynchronous operation. The value **true** means to abort the asynchronous operation, and **false** means the opposite. | | reason | \ | Yes | Yes | Reason for abort. This value will be used in the rejected Promise returned by [lockAsync](#lockasync).| +### ConditionVariable18+ + +A class that implements asynchronous waiting, enabling asynchronous wait and notify operations. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +#### constructor18+ + +constructor() + +Default constructor used to create an object for asynchronous wait and notify operations. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Example** + +```ts +let conditionVariable = new ArkTSUtils.locks.ConditionVariable(); +``` + +#### request18+ + +static request(name: string): ConditionVariable + +Looks up or creates (if not found) an object for asynchronous wait and notify operations based on the specified name. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type | Mandatory| Description | +| ---- | ------ | ---- | -------------------------------- | +| name | string | Yes | Name used to identify the object for asynchronous wait and notify operations.| + +**Return value** + +| Type | Description | +| ----------------------- | -------------------------------- | +| [ConditionVariable](#conditionvariable18) | Object for asynchronous wait and notify operations.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message | +| -------- | ----------------- | +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | + +**Example** + +```ts +let conditionVariable = ArkTSUtils.locks.ConditionVariable.request("conditionName"); +``` + +#### wait18+ + +wait(): Promise\ + +Asynchronously waits until notified. This API uses a promise to return the result. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Return value** + +| Type | Description | +| ----------- | --------------------------- | +| Promise\ | Promise that returns no value.| + +**Example** + +```ts +let conditionVariable = ArkTSUtils.locks.AsyncLock.ConditionVariable(); +conditionVariable.wait().then(() => { + console.info(`Thread being awakened, then continue...`); // Output logs upon awakening. +}); +``` + +#### waitFor18+ + +waitFor(timeout : number) : Promise\ + +Asynchronously waits for a specified duration or until notified. This API uses a promise to return the result. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type | Mandatory| Description | +| -------- | -------- | ---- | ---------- | +| timeout | number | Yes | Duration to wait, in ms. The value is a positive integer.| + +**Return value** + +| Type | Description | +| ----------- | --------------------------- | +| Promise\ | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message | +| -------- | ----------------- | +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types. | + +**Example** + +```ts +let conditionVariable = ArkTSUtils.locks.AsyncLock.ConditionVariable(); +conditionVariable.waitFor(3000).then(() => { + console.info(`Thread being awakened, then continue...`); // Output logs upon awakening. +}); +``` + +#### notifyAll18+ + +notifyAll() : void + +Notifies all waiting threads. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Example** + +```ts +let conditionVariable = ArkTSUtils.locks.AsyncLock.ConditionVariable(); +conditionVariable.waitFor(3000).then(() => { + console.info(`Thread being awakened, then continue...`); // Output logs upon awakening. +}); +conditionVariable.notifyAll(); +``` + +#### notifyOne18+ + +notifyOne() : void + +Notifies the first waiting thread. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Example** + +```ts +let conditionVariable = ArkTSUtils.locks.AsyncLock.ConditionVariable(); +conditionVariable.waitFor(3000).then(() => { + console.info(`Thread a being awakened, then continue...`); // Output logs upon awakening. +}); +conditionVariable.waitFor().then(() => { + console.info(`Thread twob being awakened, then continue...`); // Output logs upon awakening. +}); +conditionVariable.notifyOne(); +``` + ## ArkTSUtils.ASON A utility class used to parse JSON strings into [sendable data](../../arkts-utils/arkts-sendable.md#sendable-data-types). ASON allows you to parse JSON strings and generate data that can be passed across concurrency domains. It also supports conversion from sendable data into JSON strings. @@ -642,13 +815,13 @@ console.info(str); // Expected output: '[1,2,3]' ``` -### stringify16+ +### stringify18+ stringify(value: Object | null | undefined): string Converts ArkTS object data into a JSON string, with additional support for Map and Set types. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.Utils.Lang @@ -752,3 +925,579 @@ if (ArkTSUtils.isSendable(sendableFunc)) { } // Expected output: 'SendableFunc is Sendable' ``` + +## SendableLruCache18+ + +Provides APIs to discard the least recently used data to make rooms for new elements when the cache is full. This class uses the Least Recently Used (LRU) algorithm, which believes that the recently used data may be accessed again in the near future and the least accessed data is the least valuable data and should be removed from the cache. **SendableLruCache** supports the Sendable feature, allowing it to store Sendable objects, which can be accessed safely across threads. + +### Attributes + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +| Name | Type | Readable| Writable| Description | +| ------ | ------ | ---- | ---- | ---------------------- | +| length | number | Yes | No | Total number of values in this cache.| + +**Example** + +```ts +let pro = new ArkTSUtils.SendableLruCache(); +pro.put(2, 10); +pro.put(1, 8); +let result = pro.length; +console.info('result = ' + result); +// Expected output: result = 2 +``` + +### constructor18+ + +constructor(capacity?: number) + +A constructor used to create a **SendableLruCache** instance. The default capacity of the cache is 64. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ---------------------------- | +| capacity | number | No | Capacity of the cache to create. The default value is **64**, and the maximum value is **2147483647**.| + +**Example** + +```ts +let pro = new ArkTSUtils.SendableLruCache(); +``` + +### updateCapacity18+ + +updateCapacity(newCapacity: number): void + +Changes the cache capacity. If the total number of values in the cache is greater than the specified capacity, the least used key-value pairs are deleted. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ---------------------------- | +| newCapacity | number | Yes | New capacity of the cache. The maximum value is 2147483647. If the value is less than or equal to 0, an exception is thrown.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID | Error Message | +| -------- | ------------------------------------------| +| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified;2.Incorrect parameter types. | + +**Example** + +```ts +let pro = new ArkTSUtils.SendableLruCache(); +pro.updateCapacity(100); +``` + +### toString18+ + +toString(): string + +Obtains the string representation of this cache. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Return value** + +| Type | Description | +| ------ | -------------------------- | +| string | String representation of the cache, in the format of SendableLruCache[ maxSize = (maxSize), hits = (hitCount), misses = (missCount), hitRate = (hitRate) ], where **(maxSize)** indicates the maximum size of the cache, **(hitCount)** indicates the number of matched queries, **(missCount)** indicates the number of times that the number of mismatched queries, and **(hitRate)** indicates the matching rate.| + +**Example** + +```ts +let pro = new ArkTSUtils.SendableLruCache(); +pro.put(2, 10); +pro.get(2); +pro.get(3); +console.info(pro.toString()); +// Expected output: SendableLruCache[ maxSize = 64, hits = 1, misses = 1, hitRate = 50% ] +// maxSize: maximum size of the cache. hits: number of matched queries. misses: number of mismatched queries. hitRate: matching rate. +``` + +### getCapacity18+ + +getCapacity(): number + +Obtains the capacity of this cache. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Return value** + +| Type | Description | +| ------ | ---------------------- | +| number | Capacity of the cache.| + +**Example** + +```ts +let pro = new ArkTSUtils.SendableLruCache(); +let result = pro.getCapacity(); +console.info('result = ' + result); +// Expected output: result = 64 +``` + +### clear18+ + +clear(): void + +Clears all key-value pairs from this cache. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Example** + +```ts +let pro = new ArkTSUtils.SendableLruCache(); +pro.put(2, 10); +let result = pro.length; +pro.clear(); +let res = pro.length; +console.info('result = ' + result); +console.info('res = ' + res); +// Expected output: result = 1 +// Expected output: res = 0 +``` + +### getCreateCount18+ + +getCreateCount(): number + +Obtains the number of times that the **createDefault** API is called to create objects. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Return value** + +| Type | Description | +| ------ | -------------------| +| number | Number of times that the **createDefault** API is called.| + +**Example** + +```ts +@Sendable +class ChildLRUCache extends ArkTSUtils.SendableLruCache { + constructor() { + super(); + } + createDefault(key: number): number { + return key; + } +} + +let lru = new ChildLRUCache(); +lru.put(2, 10); +lru.get(3); +lru.get(5); +let res = lru.getCreateCount(); +console.info('res = ' + res); +// Expected output: res = 2 +// When the get operation is performed, if the key does not exist, call the createDefault API to check whether the return value is undefined. +// If the return value is not undefined, add the key and return value to the cache as a new entry and increase the creation count by one. +``` + +### getMissCount18+ + +getMissCount(): number + +Obtains the number of times that the queried values are mismatched. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Return value** + +| Type | Description | +| ------ | ------------------------ | +| number | Number of times that the queried values are mismatched.| + +**Example** + +```ts +let pro = new ArkTSUtils.SendableLruCache(); +pro.put(2, 10); +pro.get(2); +let result = pro.getMissCount(); +console.info('result = ' + result); +// Expected output: result = 0 +``` + +### getRemoveCount18+ + +getRemoveCount(): number + +Obtains the number of times that key-value pairs in the cache are recycled. When the size of the cache exceeds the capacity limit, the least used key-value pairs will be recycled. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Return value** + +| Type | Description | +| ------ | -------------------------- | +| number | Number of times that key-value pairs in the cache are recycled.| + +**Example** + +```ts +let pro = new ArkTSUtils.SendableLruCache(); +pro.put(2, 10); +pro.updateCapacity(2); +pro.put(50, 22); +let result = pro.getRemoveCount(); +console.info('result = ' + result); +// Expected output: result = 0 +``` + +### getMatchCount18+ + +getMatchCount(): number + +Obtains the number of times that the queried values are matched. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Return value** + +| Type | Description | +| ------ | -------------------------- | +| number | Number of times that the queried values are matched.| + +**Example** + +```ts +let pro = new ArkTSUtils.SendableLruCache(); +pro.put(2, 10); +pro.get(2); +let result = pro.getMatchCount(); +console.info('result = ' + result); +// Expected output: result = 1 +``` + +### getPutCount18+ + +getPutCount(): number + +Obtains the number of additions to this cache. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Return value** + +| Type | Description | +| ------ | ---------------------------- | +| number | Number of additions to the cache.| + +**Example** + +```ts +let pro = new ArkTSUtils.SendableLruCache(); +pro.put(2, 10); +let result = pro.getPutCount(); +console.info('result = ' + result); +// Expected output: result = 1 +``` + +### isEmpty18+ + +isEmpty(): boolean + +Checks whether this cache is empty. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Return value** + +| Type | Description | +| ------- | ---------------------------------------- | +| boolean | Check result. The value **true** means that the cache is empty and does not contain any key-value pairs, and **false** means the opposite.| + +**Example** + +```ts +let pro = new ArkTSUtils.SendableLruCache(); +pro.put(2, 10); +let result = pro.isEmpty(); +console.info('result = ' + result); +// Expected output: result = false +``` + +### get18+ + +get(key: K): V | undefined + +Obtains the value of a key. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ------------ | +| key | K | Yes | Key based on which the value is queried.| + +**Return value** + +| Type | Description | +| ------------------------ | ------------------------------------------------------------ | +| V \| undefined | If the specified key exists in the cache, the return value is the value associated with that key. If not, the **createDefault** API is called. If **createDefault** returns undefined, the return value is undefined; otherwise, the return value is whatever **createDefault** comes up with.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| -------- | -------- | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | + +**Example** + +```ts +let pro = new ArkTSUtils.SendableLruCache(); +pro.put(2, 10); +let result = pro.get(2); +console.info('result = ' + result); +// Expected output: result = 10 +``` + +### put18+ + +put(key: K,value: V): V + +Adds a key-value pair to this cache and returns the value associated with the key. If the total number of values in the cache is greater than the specified capacity, the deletion operation is performed. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | -------------------------- | +| key | K | Yes | Key of the key-value pair to add. | +| value | V | Yes | Value of the key-value pair to add.| + +**Return value** + +| Type| Description | +| ---- | ------------------------------------------------------------ | +| V | Value of the key-value pair added. If the key or value is empty, error code 401 is thrown.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| -------- | -------- | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | + +**Example** + +```ts +let pro = new ArkTSUtils.SendableLruCache(); +let result = pro.put(2, 10); +console.info('result = ' + result); +// Expected output: result = 10 +``` + +### values18+ + +values(): V[] + +Obtains all values in this cache, listed from the most to the least recently accessed, where the most recently accessed indicates the key-value pair with the latest operation. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Return value** + +| Type | Description | +| --------- | ------------------------------------------------------------ | +| V [] | All values in the cache, listed from the most to the least recently accessed.| + +**Example** + +```ts +let pro = new ArkTSUtils.SendableLruCache(); +pro.put(2, 10); +pro.put(2, "anhu"); +pro.put("afaf", "grfb"); +let result = pro.values(); +console.info('result = ' + result); +// Expected output: result = anhu,grfb +``` + +### keys18+ + +keys(): K[] + +Obtains all keys in this cache, listed from the most to the least recently accessed. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Return value** + +| Type | Description | +| --------- | ------------------------------------------------------------ | +| K [] | All keys in the cache, listed from the most to the least recently accessed.| + +**Example** + +```ts +let pro = new ArkTSUtils.SendableLruCache(); +pro.put(2, 10); +pro.put(3, 1); +let result = pro.keys(); +console.info('result = ' + result); +// Expected output: result = 2,3 +``` + +### remove18+ + +remove(key: K): V | undefined + +Removes a key and its associated value from this cache and returns the value associated with the key. If the key does not exist, undefined is returned. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | -------------- | +| key | K | Yes | Key to remove.| + +**Return value** + +| Type | Description | +| ------------------------ | ------------------------------------------------------------ | +| V \| undefined | Returns an **Optional** object containing the removed key-value pair if the key exists in the cache; returns undefined if the key does not exist; throws an error if **null** is passed in for **key**.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| -------- | -------- | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | + +**Example** + +```ts +let pro = new ArkTSUtils.SendableLruCache(); +pro.put(2, 10); +let result = pro.remove(20); +console.info('result = ' + result); +// Expected output: result = undefined +``` + +### contains18+ + +contains(key: K): boolean + +Checks whether the cache contains the specified key. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------- | +| key | K | Yes | Key to check.| + +**Return value** + +| Type | Description | +| ------- | ------------------------------------------ | +| boolean | Check result. The value **true** means that the cache contains the specified key, and **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| -------- | -------- | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | + +**Example** + +```ts +let pro = new ArkTSUtils.SendableLruCache(); +pro.put(2, 10); +let result = pro.contains(2); +console.info('result = ' + result); +// Expected output: result = true +``` + +### entries18+ + +entries(): IterableIterator<[K,V]> + +Obtains a new iterator object that contains all key-value pairs in this object. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Return value** + +| Type | Description | +| ----------- | -------------------- | +| IterableIterator<[K, V]> | Iterable array.| + +**Example** + +```ts +let pro = new ArkTSUtils.SendableLruCache(); +pro.put(2, 10); +pro.put(3, 15); +let pair:Iterable = pro.entries(); +let arrayValue = Array.from(pair); +for (let value of arrayValue) { + console.info(value[0]+ ', '+ value[1]); + // Expected output: + // 2, 10 + // 3, 15 +} +``` diff --git a/en/application-dev/reference/apis-arkts/js-apis-buffer.md b/en/application-dev/reference/apis-arkts/js-apis-buffer.md index 305e7bb8fce8f89886cb285dd4547fc2f29467a5..c1dfbfcc7b7808aae62ec848e9a0caee3475aba0 100644 --- a/en/application-dev/reference/apis-arkts/js-apis-buffer.md +++ b/en/application-dev/reference/apis-arkts/js-apis-buffer.md @@ -289,7 +289,7 @@ console.info(buf.toString('hex')); ## buffer.from -from(array: number[]): Buffer; +from(array: number[]): Buffer Creates a **Buffer** instance with the specified array. @@ -2285,7 +2285,7 @@ Converts the data at the specified position in this **Buffer** instance into a s | Type| Description| | -------- | -------- | -| string | String obtained. When the value of **start** is greater than or equal to **Buffer.length** or **start** is greater than **end**, an empty string is returned.| +| string | String. When the value of **start** is greater than or equal to **Buffer.length** or **start** is greater than **end**, an empty string is returned.| **Error codes** @@ -2362,7 +2362,7 @@ Writes a string of the specified length to this **Buffer** instance at the speci | -------- | -------- | -------- | -------- | | str | string | Yes| String to write.| | offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.| -| length | number | No| Maximum number of bytes to write. The default value is the length of the **Buffer** instance minus the offset.| +| length | number | No| Maximum number of bytes to write. The default value is **Buffer.length** minus **offset**.| | encoding | string | No| Encoding format of the string. The default value is **'utf8'**.| diff --git a/en/application-dev/reference/apis-arkts/js-apis-convertxml.md b/en/application-dev/reference/apis-arkts/js-apis-convertxml.md index 0bfe4f252e37b2da890a61faaf130c57721c8580..74029075ab605ae8c07b1b4fadbe3259e19b5627 100644 --- a/en/application-dev/reference/apis-arkts/js-apis-convertxml.md +++ b/en/application-dev/reference/apis-arkts/js-apis-convertxml.md @@ -199,14 +199,14 @@ Options for conversion. | Name | Type| Mandatory| Description | | ----------------- | -------- | ---- | ----------------------------------------------------------- | -| trim | boolean | Yes | Whether to trim the whitespace characters before and after the text. | -| ignoreDeclaration | boolean | No | Whether to ignore the XML declaration. The default value is **false**. | -| ignoreInstruction | boolean | No | Whether to ignore the XML processing instruction. The default value is **false**. | -| ignoreAttributes | boolean | No | Whether to ignore the element's attribute information. The default value is **false**. | -| ignoreComment | boolean | No | Whether to ignore element comments. The default value is **false**. | -| ignoreCDATA | boolean | No | Whether to ignore the element's CDATA information. The default value is **false**. | -| ignoreDoctype | boolean | No | Whether to ignore the element's Doctype information. The default value is **false**. | -| ignoreText | boolean | No | Whether to ignore the element's text information. The default value is **false**. | +| trim | boolean | Yes | Whether to trim the whitespace characters before and after the text. The value **true** means to trim the whitespace characters before and after the text, and **false** means to keep them. | +| ignoreDeclaration | boolean | No | Whether to ignore the XML declaration. The value **true** means to ignore the XML declaration, and **false** means the opposite. The default value is **false**. | +| ignoreInstruction | boolean | No | Whether to ignore the XML processing instruction. The value **true** means to ignore the XML processing instruction, and **false** means the opposite. The default value is **false**. | +| ignoreAttributes | boolean | No | Whether to ignore the element's attribute information. The value **true** means to ignore the element's attribute information, and **false** means the opposite. The default value is **false**. | +| ignoreComment | boolean | No | Whether to ignore element comments. The value **true** means to ignore element comments, and **false** means the opposite. The default value is **false**. | +| ignoreCDATA | boolean | No | Whether to ignore the element's CDATA information. The value **true** means to ignore the element's CDATA information, and **false** means the opposite. The default value is **false**. | +| ignoreDoctype | boolean | No | Whether to ignore the element's Doctype information. The value **true** means to ignore the element's Doctype information, and **false** means the opposite. The default value is **false**. | +| ignoreText | boolean | No | Whether to ignore the element's text information. The value **true** means to ignore the element's text information, and **false** means the opposite. The default value is **false**. | | declarationKey | string | Yes | Name of the attribute key for **declaration** in the output object.| | instructionKey | string | Yes | Name of the attribute key for **instruction** in the output object.| | attributesKey | string | Yes | Name of the attribute key for **attributes** in the output object. | diff --git a/en/application-dev/reference/apis-arkts/js-apis-json.md b/en/application-dev/reference/apis-arkts/js-apis-json.md index e8e1b1547ee0d59b3871ca22f2cc890712697091..8ef57abb6d0113702f0b1aec57583bffa8d38c50 100644 --- a/en/application-dev/reference/apis-arkts/js-apis-json.md +++ b/en/application-dev/reference/apis-arkts/js-apis-json.md @@ -314,7 +314,7 @@ Checks whether an ArkTS object contains a key. This API can be used for related | Type| Description| | -------- | -------- | -| boolean | **true**: The ArkTS object contains the key.
**false**: The ArkTS object does not contain the key.| +| boolean | Check result. The value **true** means that the ArkTS object contains the key, and **false** means the opposite.| **Error codes** diff --git a/en/application-dev/reference/apis-arkts/js-apis-process.md b/en/application-dev/reference/apis-arkts/js-apis-process.md index 640a6f5c1e969ac213991fe249c0a751ea879d3e..078e069eeaaa7143295bf4632f2bcb1bdc05a940 100644 --- a/en/application-dev/reference/apis-arkts/js-apis-process.md +++ b/en/application-dev/reference/apis-arkts/js-apis-process.md @@ -20,9 +20,9 @@ import { process } from '@kit.ArkTS'; **Atomic service API**: This API can be used in atomic services since API version 11. -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable| Writable| Description | | ---------------- | ------ | ---- | ---- | ---------------- | -| uid | number | Yes | No | User identifier (UID) of the process. | +| uid | number | Yes | No | User identifier (UID) of the process.| | pid | number | Yes | No | Process ID (PID) of the process. | | tid8+ | number | Yes | No | Thread ID (TID) of the thread. | @@ -39,9 +39,9 @@ Describes the event to store. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | --------------- | -| evt | Object | Yes | Event.| +| evt | Object | Yes| Event.| ## process.isIsolatedProcess8+ @@ -57,7 +57,7 @@ Checks whether this process is isolated. | Type | Description | | ------- | ------------------------------------------------------- | -| boolean | **true**: The process is isolated.
**false**: The process is not isolated. | +| boolean | Check result. The value **true** means that the process is isolated, and **false** means the opposite.| **Example** @@ -80,7 +80,7 @@ Checks whether this process is running in a 64-bit environment. | Type | Description | | ------- | ----------------------------------------------------------- | -| boolean | **true**: The process is running in a 64-bit environment.
**false**: The process is not running in a 64-bit environment. | +| boolean | Check result. The value **true** means that the process is running in a 64-bit environment, and **false** means the opposite.| **Example** @@ -101,9 +101,9 @@ Obtains the duration, in milliseconds, from the time the system starts to the ti **Return value** -| Type | Description | -| ------ | ------------------------------ | -| number | Duration obtained, in millisecond. | +| Type | Description | +| ------ | -------------------------------- | +| number | Duration obtained, in milliseconds.| **Example** @@ -123,14 +123,14 @@ Obtains the CPU time (in milliseconds) from the time the process starts to the c **Return value** -| Type | Description | -| ------ | ----------------------------- | -| number | CPU time obtained, in millisecond. | +| Type | Description | +| ------ | ------------------------------- | +| number | CPU time obtained, in milliseconds.| **Example** ```js -let result = process.getPastCpuTime() ; +let result = process.getPastCpuTime(); ``` @@ -165,7 +165,7 @@ Obtains the running time of this process. | Type | Description | | ------ | ---------------------- | -| number | Running time of the process, in seconds. | +| number | Running time of the process, in seconds.| **Example** @@ -188,22 +188,22 @@ Sends a signal to the specified process to terminate it. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------ | -| signal | number | Yes | Signal to send. | +| signal | number | Yes | Signal to send.| | pid | number | Yes | PID of the process, to which the signal will be sent. | **Return value** | Type | Description | | ------- | ------------------------------------------------------------ | -| boolean | **true**: The signal is sent successfully.
**false**: The signal fails to be sent. | +| boolean | Signal sending result. The value **true** means that the signal is sent successfully, and **false** means the opposite.| **Example** ```js -let pres = process.pid -let result = process.kill(28, pres) +let pres = process.pid; +let result = process.kill(28, pres); ``` @@ -223,9 +223,9 @@ Exercise caution when using this API. After this API is called, the application **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------- | -| code | number | Yes | Exit code of the process. | +| code | number | Yes | Exit code of the process.| **Example** @@ -248,20 +248,20 @@ Obtains the UID of a user from the user database of the system based on the spec **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------- | -| v | string | Yes | User name. | +| v | string | Yes | User name.| **Return value** | Type | Description | | ------ | ------------- | -| number | UID of the user. | +| number | UID of the user.| **Example** ```js -let pres = process.getUidForName("tool") +let pres = process.getUidForName("tool"); ``` @@ -279,15 +279,15 @@ Obtains the thread priority based on the specified TID. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | --------------- | -| v | number | Yes | TID. | +| v | number | Yes | TID.| **Return value** | Type | Description | | ------ | ------------------------------------------------ | -| number | Priority of the thread. The priority depends on the operating system. | +| number | Priority of the thread. The priority depends on the operating system.| **Example** @@ -311,15 +311,15 @@ Checks whether a UID belongs to this application. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | --------------- | -| v | number | Yes | UID. | +| v | number | Yes | UID.| **Return value** | Type | Description | | ------- | ------------------------------------------------------------ | -| boolean | **true**: The UID belongs to the application.
**false**: The UID does not belong to the application. | +| boolean | Check result. The value **true** means that the UID belongs to the application, and **false** means the opposite.| **Example** @@ -342,21 +342,21 @@ Obtains the system configuration. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------- | -| name | number | Yes | System configuration parameter name. | +| name | number | Yes | System configuration parameter name.| **Return value** | Type | Description | | ------ | ------------------ | -| number | System configuration obtained. | +| number | System configuration obtained.| **Example** ```js -let _SC_ARG_MAX = 0 -let pres = process.getSystemConfig(_SC_ARG_MAX) +let _SC_ARG_MAX = 0; +let pres = process.getSystemConfig(_SC_ARG_MAX); ``` @@ -374,20 +374,20 @@ Obtains the value of an environment variable. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------ | -| name | string | Yes | Environment variable name. | +| name | string | Yes | Environment variable name.| **Return value** | Type | Description | | ------ | --------------------------- | -| string | Value of the environment variable. | +| string | Value of the environment variable.| **Example** ```js -let pres = process.getEnvironmentVar("PATH") +let pres = process.getEnvironmentVar("PATH"); ``` @@ -409,21 +409,21 @@ Checks whether a UID belongs to this application. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | --------------- | -| v | number | Yes | UID, which can be obtained by running **process.uid**. | +| v | number | Yes | UID. which can be obtained by running **process.uid**.| **Return value** | Type | Description | | ------- | ------------------------------------------------------------ | -| boolean | **true**: The UID belongs to the application.
**false**: The UID does not belong to the application. | +| boolean | Check result. The value **true** means that the UID belongs to the application, and **false** means the opposite.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message| | -------- | -------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | @@ -450,9 +450,9 @@ Obtains the UID of a user from the user database of the system based on the spec **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------- | -| v | string | Yes | User name. | +| v | string | Yes | User name.| **Return value** @@ -464,7 +464,7 @@ Obtains the UID of a user from the user database of the system based on the spec For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message| | -------- | -------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | @@ -488,21 +488,21 @@ Obtains the thread priority based on the specified TID. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | --------------- | -| v | number | Yes | TID. | +| v | number | Yes | TID.| **Return value** | Type | Description | | ------ | ------------------------------------------------ | -| number | Priority of the thread. The priority depends on the operating system. | +| number | Priority of the thread. The priority depends on the operating system.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message| | -------- | -------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | @@ -527,21 +527,21 @@ Obtains the system configuration. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------- | -| name | number | Yes | System configuration parameter name. | +| name | number | Yes | System configuration parameter name.| **Return value** | Type | Description | | ------ | ------------------ | -| number | System configuration obtained. If the system configuration does not exist, **-1** is returned. | +| number | System configuration obtained. If the system configuration does not exist, **-1** is returned.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message| | -------- | -------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | @@ -570,21 +570,21 @@ Obtains the value of an environment variable. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------ | -| name | string | Yes | Environment variable name. | +| name | string | Yes | Environment variable name.| **Return value** | Type | Description | | ------ | ------------------------ | -| string | Value of the environment variable. | +| string | Value of the environment variable.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message| | -------- | -------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | @@ -610,15 +610,15 @@ Exercise caution when using this API. After this API is called, the application **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------- | -| code | number | Yes | Exit code of the process. | +| code | number | Yes | Exit code of the process.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message| | -------- | -------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | @@ -642,22 +642,22 @@ Sends a signal to the specified process to terminate it. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------ | -| signal | number | Yes | Signal to send. | +| signal | number | Yes | Signal to send.| | pid | number | Yes | PID of the process, to which the signal will be sent. | **Return value** | Type | Description | | ------- | ------------------------------------------------------------ | -| boolean | **true**: The signal is sent successfully.
**false**: The signal fails to be sent. | +| boolean | Signal sending result. The value **true** means that the signal is sent successfully, and **false** means the opposite.| **Error codes** For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). -| ID | Error Message | +| ID| Error Message| | -------- | -------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | diff --git a/en/application-dev/reference/apis-arkts/js-apis-stream.md b/en/application-dev/reference/apis-arkts/js-apis-stream.md index 92e7ad5b82fd2e95578f6e6332ed05578a80fe45..d2804bdad14c61c876b90ba5a5540adb08fbe26a 100644 --- a/en/application-dev/reference/apis-arkts/js-apis-stream.md +++ b/en/application-dev/reference/apis-arkts/js-apis-stream.md @@ -27,10 +27,10 @@ Stream to which data can be written. A writable stream allows data to be written | Name | Type | Read-Only| Optional | Description | | ------- | -------- | ------ | ------ | ----------- | | writableObjectMode | boolean | Yes | No| Whether the writable stream works in object mode. The value **true** means that the stream is configured in object mode, and **false** means the opposite. Currently, only raw data (string and Uint8Array) is supported, and the return value is **false**.| -| writableHighWatermark | number | Yes| No | Maximum amount of data that can be stored in the buffer. The default value is 16 x 1024, in bytes.| +| writableHighWatermark | number | Yes| No | High watermark for the data volume in the buffer. This value is not customizable currently. When you call [write()](#write), if the data volume in the buffer reaches this watermark, [write()](#write) will return **false**. The default value is 16 x 1024, in bytes.| | writable | boolean | Yes| No | Whether the writable stream is currently writable. The value **true** means that the stream is currently writable, and **false** means that the stream does not accept write operations.| -| writableLength | number | Yes| No | Number of bytes to be written in the buffer of the readable stream.| -| writableCorked | number | Yes | No| Number of times the **uncork()** API needs to be called in order to fully uncork the writable stream.| +| writableLength | number | Yes| No | Number of bytes to be written in the buffer of the writable stream.| +| writableCorked | number | Yes | No| Count of cork states of the writable stream. If the value is greater than 0, the writable stream buffers all writes. If the value is **0**, buffering stops. You can call [cork()](#cork) to increment the count by one, call [uncork()](#uncork) to decrement the count by one, and call [end()](#end) to clear the count.| | writableEnded | boolean | Yes | No| Whether [end()](#end) has been called for the writable stream. This property does not specify whether the data has been flushed. The value **true** means that [end()](#end) has been called, and **false** means the opposite.| | writableFinished | boolean | Yes | No| Whether data in the writable stream has been flushed. The value **true** means that data in the stream has been flushed, and **false** means the opposite.| @@ -72,7 +72,7 @@ Writes data to the buffer of the stream. This API uses an asynchronous callback | Type | Description | | ------ | ---------------------- | -| boolean | Whether there is space in the buffer of the writable stream. The value **true** means that there is still space in the buffer, and **false** means that the buffer is full.| +| boolean | Whether there is space in the buffer of the writable stream. The value **true** means that there is still space in the buffer. The value **false** means that the buffer is full, and you are not advised to continue writing data.| **Error codes** @@ -109,6 +109,8 @@ end(chunk?: string | Uint8Array, encoding?: string, callback?: Function): Writab Ends the writing process in a writable stream. This API uses an asynchronous callback to return the result. +If the value of **writableCorked** is greater than 0, the value is set to **0** and the remaining data in the buffer is output. + If the **chunk** parameter is passed, it is treated as the final data chunk and written using either the **write** or **doWrite** API, based on the current execution context. If **doWrite** is used for writing, the validity check of the **encoding** parameter depends on **doWrite**. @@ -221,6 +223,8 @@ cork(): boolean Forces all written data to be buffered in memory. This API is called to optimize the performance of continuous write operations. +After this API is called, the value of **writableCorked** is incremented by one. It is recommended that this API be used in pair with [uncork()](#uncork). + **Atomic service API**: This API can be used in atomic services since API version 12. **System capability**: SystemCapability.Utils.Lang @@ -255,6 +259,8 @@ uncork(): boolean Flushes all data buffered, and writes the data to the target. +After this API is called, the value of **writableCorked** is decremented by one. If the value reaches **0**, the stream is no longer in the cork state. Otherwise, the stream is still in the cork state. It is recommended that this API be used in pair with [cork()](#cork). + **Atomic service API**: This API can be used in atomic services since API version 12. **System capability**: SystemCapability.Utils.Lang @@ -1168,11 +1174,11 @@ The **Duplex** class inherits from [Readable](#readable) and supports all the AP | Name | Type | Read-Only| Optional | Description | | ------- | -------- | ------ | ------ | ----------- | | writableObjectMode | boolean | Yes | No| Whether the writable side of the duplex stream works in object mode. The value **true** means that the writable side of the stream is configured in object mode, and **false** means the opposite. Currently, only raw data (string and Uint8Array) is supported, and the return value is **false**.| -| writableHighWatermark | number | Yes| No | Maximum amount of data that can be stored in the buffer in the writable side of the duplex stream. The default value is 16 x 1024, in bytes.| +| writableHighWatermark | number | Yes| No | High watermark for the data volume in the buffer of the duplex stream in write mode. This value is not customizable currently. When you call [write()](#write-1), if the data volume in the buffer reaches this watermark, [write()](#write-1) will return **false**. The default value is 16 x 1024, in bytes.| | writable | boolean | Yes| No | Whether the duplex stream is currently writable. The value **true** means that the stream is currently writable, and **false** means that the stream does not accept write operations.| | writableLength | number | Yes| No | Number of bytes to be written in the buffer of the duplex stream.| -| writableCorked | number | Yes | No| Number of times the **uncork()** API needs to be called in order to fully uncork the duplex stream.| -| writableEnded | boolean | Yes | No| Whether [end()](#end) has been called for the duplex stream. This property does not specify whether the data has been flushed. The value **true** means that [end()](#end) has been called, and **false** means the opposite.| +| writableCorked | number | Yes | No| Count of cork states of the duplex stream. If the value is greater than 0, the duplex stream buffers all writes. If the value is **0**, buffering stops. You can call [cork()](#cork-1) to increment the count by one, call [uncork()](#uncork-1) to decrement the count by one, and call [end()](#end-1) to clear the count.| +| writableEnded | boolean | Yes | No| Whether [end()](#end-1) has been called for the duplex stream. This property does not specify whether the data has been flushed. The value **true** means that [end()](#end-1) has been called, and **false** means the opposite.| | writableFinished | boolean | Yes | No| Whether data in the duplex stream has been flushed. The value **true** means that data in the stream has been flushed, and **false** means the opposite.| ### constructor @@ -1213,7 +1219,7 @@ Writes data to the buffer of the stream. This API uses an asynchronous callback | Type | Description | | ------ | ---------------------- | -| boolean | Whether there is space in the buffer of the writable stream. The value **true** means that there is still space in the buffer, and **false** means that the buffer is full.| +| boolean | Whether there is space in the buffer of the writable stream. The value **true** means that there is still space in the buffer. The value **false** means that the buffer is full, and you are not advised to continue writing data.| **Error codes** @@ -1254,9 +1260,11 @@ end(chunk?: string | Uint8Array, encoding?: string, callback?: Function): Writab Ends the writing process in a duplex stream. This API uses an asynchronous callback to return the result. +If the value of **writableCorked** is greater than 0, the value is set to **0** and the remaining data in the buffer is output. + If the **chunk** parameter is passed, it is treated as the final data chunk and written using either the **write** or **doWrite** API, based on the current execution context. -If **doWrite** is used for writing, the validity check of the **encoding** parameter depends on **doWrite**. +If **doWrite** is used for writing, the validity check of the **encoding** parameter depends on **doWrite**. If **end** is used alone (without **write**) and the **chunk** parameter is passed, the data is written through **doWrite**. @@ -1367,6 +1375,8 @@ cork(): boolean Forces all written data to be buffered in memory. This API is called to optimize the performance of continuous write operations. +After this API is called, the value of **writableCorked** is incremented by one. It is recommended that this API be used in pair with [uncork()](#uncork-1). + **Atomic service API**: This API can be used in atomic services since API version 12. **System capability**: SystemCapability.Utils.Lang @@ -1391,6 +1401,8 @@ uncork(): boolean Flushes all data buffered, and writes the data to the target. +After this API is called, the value of **writableCorked** is decremented by one. If the value reaches **0**, the stream is no longer in the cork state. Otherwise, the stream is still in the cork state. It is recommended that this API be used in pair with [cork()](#cork-1). + **Atomic service API**: This API can be used in atomic services since API version 12. **System capability**: SystemCapability.Utils.Lang diff --git a/en/application-dev/reference/apis-arkts/js-apis-taskpool.md b/en/application-dev/reference/apis-arkts/js-apis-taskpool.md index 21efec76a1f690649dfdea5933e52d4f83f30bdf..ff7de9cf545ced357dc9bcdaa1a2dbc14b6953b5 100644 --- a/en/application-dev/reference/apis-arkts/js-apis-taskpool.md +++ b/en/application-dev/reference/apis-arkts/js-apis-taskpool.md @@ -13,7 +13,7 @@ For details about the precautions for using **TaskPool**, see [Precautions for T The following concepts are used in this topic: - Task group task: task in a [TaskGroup](#taskgroup10). - Serial queue task: task in a [SequenceRunner](#sequencerunner-11). -- Asynchronous queue task: task in an [AsyncRunner](#asyncrunner16). +- Asynchronous queue task: task in an [AsyncRunner](#asyncrunner18). - Periodic task: task executed by calling [executePeriodically](#taskpoolexecuteperiodically12). > **NOTE** @@ -725,7 +725,7 @@ function concurrentFunc() { concurrentFunc(); ``` -## taskpool.cancel16+ +## taskpool.cancel18+ cancel(taskId: number): void @@ -733,7 +733,7 @@ Cancels a task in the task pool by task ID. If the task is in the internal queue **System capability**: SystemCapability.Utils.Lang -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **Parameters** @@ -857,7 +857,7 @@ Checks whether a function is a concurrent function. | Type | Description | | ------- | ------------------------------------ | -| boolean | **true**: The function is a concurrent function, that is, a function decorated with [@Concurrent](../../arkts-utils/taskpool-introduction.md#concurrent-decorator).
**false**: The function is not a concurrent function.| +| boolean | Check result. The value **true** means that the function is a concurrent function, that is, a function decorated with [@Concurrent](../../arkts-utils/taskpool-introduction.md#concurrent-decorator); **false** means the opposite.| **Error codes** @@ -952,7 +952,7 @@ for (let i: number = 0; i < taskArray.length; i+=4) { // 4: Four tasks are execu Implements a task. Before calling any APIs in **Task**, you must use [constructor](#constructor) to create a **Task** instance. A task can be executed for multiple times, placed in a task group, serial queue, or asynchronous queue for execution, or added with dependencies for execution. -### Attributes +### Properties **System capability**: SystemCapability.Utils.Lang @@ -961,10 +961,10 @@ Implements a task. Before calling any APIs in **Task**, you must use [constructo | function | Function | Yes | Yes | Function to be passed in during task creation. For details about the supported return value types of the function, see [Sequenceable Data Types](#sequenceable-data-types).
**Atomic service API**: This API can be used in atomic services since API version 11.| | arguments | Object[] | Yes | Yes | Arguments of the function. For details about the supported parameter types, see [Sequenceable Data Types](#sequenceable-data-types).
**Atomic service API**: This API can be used in atomic services since API version 11.| | name11+ | string | Yes | No | Name of the task specified when the task is created.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| taskId16+ | number | Yes | No | Task ID.
**Atomic service API**: This API can be used in atomic services since API version 16.| -| totalDuration11+ | number | Yes | No | Total execution time of the task.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| ioDuration11+ | number | Yes | No | Asynchronous I/O time of the task.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| cpuDuration11+ | number | Yes | No | CPU time of the task.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| taskId18+ | number | Yes | No | Task ID.
**Atomic service API**: This API can be used in atomic services since API version 18.| +| totalDuration11+ | number | Yes | No | Total execution time of the task. in ms.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| ioDuration11+ | number | Yes | No | Asynchronous I/O time of the task. in ms.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| cpuDuration11+ | number | Yes | No | CPU time of the task. in ms.
**Atomic service API**: This API can be used in atomic services since API version 11.| ### constructor @@ -1266,7 +1266,7 @@ export class DeriveClass extends BaseClass { ```ts // index.ets -// The host thread (UI main thread) calls the methods of BaseClass and DeriveClass in the task pool thread and accesses their attributes. +// The host thread (UI main thread) calls the methods of BaseClass and DeriveClass in the task pool thread and accesses their properties. import { taskpool } from '@kit.ArkTS' import { BusinessError } from '@kit.BasicServicesKit' import { BaseClass, DeriveClass } from './sendable' @@ -1793,7 +1793,7 @@ Checks whether the task is complete. | Type | Description | | ------- | ------------------------------------ | -| boolean | **true**: The task is complete.
**false**: The task is not complete.| +| boolean | Check result. The value **true** means that the task is complete, and **false** means the opposite.| **Example** @@ -1846,6 +1846,7 @@ Describes a callback function with an error message. **System capability**: SystemCapability.Utils.Lang **Atomic service API**: This API can be used in atomic services since API version 12. + **Parameters** | Name| Type | Mandatory| Description | @@ -1976,7 +1977,7 @@ let name: string = task.name; ## TaskGroup10+ -Implements a task group, in which tasks are associated with each other and all tasks are executed at a time. If all the tasks are executed normally, an array of task results is returned asynchronously, and the sequence of elements in the array is the same as the sequence of tasks added by calling [addTask](#addtask10-1). If any task fails, the corresponding exception is thrown. A task group can be executed for multiple times, but no task can be added after the task group is executed. Before calling any APIs in **TaskGroup**, you must use [constructor](#constructor10) to create a **TaskGroup** instance. +Implements a task group, in which tasks are associated with each other and all tasks are executed at a time. If all the tasks are executed normally, an array of task results is returned asynchronously, and the sequence of elements in the array is the same as the sequence of tasks added by calling [addTask](#addtask10-1). If any task fails, the corresponding exception is thrown. If multiple tasks in the task group fail, the exception of the first failed task is thrown. A task group can be executed for multiple times, but no task can be added after the task group is executed. Before calling any APIs in **TaskGroup**, you must use [constructor](#constructor10) to create a **TaskGroup** instance. ### constructor10+ @@ -2106,7 +2107,7 @@ let task: taskpool.Task = new taskpool.Task(printArgs, 200); // 200: test number taskGroup.addTask(task); ``` -### Attributes +### Properties **System capability**: SystemCapability.Utils.Lang @@ -2265,11 +2266,11 @@ async function seqRunner() } ``` -## AsyncRunner16+ +## AsyncRunner18+ -Implements an asynchronous queue, for which you can specify the task execution concurrency and queuing policy. Before calling any APIs in **AsyncRunner**, you must use [constructor](#constructor16) to create an **AsyncRunner** instance. +Implements an asynchronous queue, for which you can specify the task execution concurrency and queuing policy. Before calling any APIs in **AsyncRunner**, you must use [constructor](#constructor18) to create an **AsyncRunner** instance. -### constructor16+ +### constructor18+ constructor(runningCapacity: number, waitingCapacity?: number) @@ -2277,7 +2278,7 @@ A constructor used to create an **AsyncRunner** instance. It constructs a non-gl **System capability**: SystemCapability.Utils.Lang -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **Parameters** @@ -2300,7 +2301,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ let runner: taskpool.AsyncRunner = new taskpool.AsyncRunner(5); ``` -### constructor16+ +### constructor18+ constructor(name: string, runningCapacity: number, waitingCapacity?: number) @@ -2313,14 +2314,14 @@ A constructor used to create an **AsyncRunner** instance. It constructs a global **System capability**: SystemCapability.Utils.Lang -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **Parameters** | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ---------------------------------------------------------- | | name | string | Yes | Name of an asynchronous queue.| -| runningCapacity | number | Yes | Maximum number of tasks that can run concurrently. The value must be a positive integer. If a negative value is passed, an error is reported. If a non-integer is passed, the value is rounded down.| +| runningCapacity | number | Yes | Maximum number of tasks that can run concurrently. The value must be a positive integer. If a negative number is passed, an error is reported. If a non-integer is passed, the value is rounded down.| | waitingCapacity | number | No | Maximum number of tasks that can be queued. The value must be greater than or equal to 0. If a negative number is passed, an error is reported. If a non-integer is passed, the value is rounded down. The default value is 0, indicating that there is no limit to the number of tasks that can wait. If a value greater than 0 is passed, tasks will be discarded from the front of the queue once the queue size exceeds this limit, implementing a discard policy.| **Error codes** @@ -2337,7 +2338,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ let runner:taskpool.AsyncRunner = new taskpool.AsyncRunner("runner1", 5, 5); ``` -### execute16+ +### execute18+ execute(task: Task, priority?: Priority): Promise\ @@ -2355,7 +2356,7 @@ Adds a task to the asynchronous queue for execution. Before using this API, you **System capability**: SystemCapability.Utils.Lang -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **Parameters** @@ -2439,7 +2440,7 @@ Describes the internal information about a task. **System capability**: SystemCapability.Utils.Lang -### Attributes +### Properties **System capability**: SystemCapability.Utils.Lang @@ -2456,7 +2457,7 @@ Describes the internal information about a worker thread. **System capability**: SystemCapability.Utils.Lang -### Attributes +### Properties **System capability**: SystemCapability.Utils.Lang @@ -2474,7 +2475,7 @@ Describes the internal information about a task pool. **System capability**: SystemCapability.Utils.Lang -### Attributes +### Properties **System capability**: SystemCapability.Utils.Lang diff --git a/en/application-dev/reference/apis-arkts/js-apis-uri.md b/en/application-dev/reference/apis-arkts/js-apis-uri.md index 262badd9aa2a999272d161f2a06323db5ba75ffa..2e30661d0d548860cd94d25d8b1d37a63bbc9b63 100644 --- a/en/application-dev/reference/apis-arkts/js-apis-uri.md +++ b/en/application-dev/reference/apis-arkts/js-apis-uri.md @@ -267,8 +267,9 @@ Normalizes the path of this URI. > If the URI is opaque or its path is already in normalized, the URI is directly returned. Otherwise, a new URI is created. The new URI is similar to the current URI. The only difference relies on its path, which is determined by normalizing the path of the current URI according to the following guidelines: > > - All . (dot) segments are removed. +> > - For any .. (double-dot) segment that is immediately preceded by a segment that is not .., both segments are removed. This process is iterated until no further removals can be made. -> +> > If normalization results in a path starting with a .. (double-dot) segment, it indicates that there were insufficient preceding non-.. segments for removal. As a result, the path will start with a .. segment. @@ -608,7 +609,7 @@ Obtains the value of the Boolean type of a query parameter in this URI. | Name | Type | Mandatory| Description | | ------------ | ------- | ---- | ------------------------------------- | | key | string | Yes | Name of the query parameter. | -| defaultValue | boolean | Yes | Default value.| +| defaultValue | boolean | Yes | Default value returned when the query parameter does not contain the specified key.| **Return value** @@ -635,6 +636,8 @@ const uriInstance2 = new uri.URI("https://www.test.com/search?active=aa&active=f console.info(`${uriInstance2.getBooleanQueryValue("active", false)}`); // true const uriInstance3 = new uri.URI("https://www.test.com/search?active=0"); console.info(`${uriInstance3.getBooleanQueryValue("active", true)}`); // false +const uriInstance4 = new uri.URI("https://www.test.com/search"); +console.info(`${uriInstance4.getBooleanQueryValue("active", true)}`); // true ``` ### clearQuery12+ diff --git a/en/application-dev/reference/apis-arkts/js-apis-url.md b/en/application-dev/reference/apis-arkts/js-apis-url.md index 8066c78bbb5cfb2033420f88950f5fd7c4fb1cba..996b87f7b925d9d38a7bf44fa492476e87a5fb4e 100644 --- a/en/application-dev/reference/apis-arkts/js-apis-url.md +++ b/en/application-dev/reference/apis-arkts/js-apis-url.md @@ -1,6 +1,6 @@ # @ohos.url (URL String Parsing) -The **url** module provides APIs for parsing URL strings and constructing [URL](#url) instances to process URL strings. +The url module provides APIs for parsing URL strings and constructing [URL](#url) instances to process URL strings. > **NOTE** > @@ -29,7 +29,7 @@ A constructor used to create a **URLParams** instance. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| init | string[][] \| Record<string, string> \| string \| URLParams | No| Input parameter objects, which include the following:
- **string[][]**: two-dimensional string array
- **Record<string, string>**: list of objects
- **string**: string
- **URLParams**: object
The default value is **null**.| +| init | string[][] \| Record<string, string> \| string \| URLParams | No| Input parameter objects, which include the following:
- **string[][]**: two-dimensional string array.
- **Record<string, string>**: list of objects.
- **string**: string.
- **URLParams**: object.
The default value is **null**.| **Error codes** @@ -539,7 +539,7 @@ Creates a URL. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | url | string | Yes| A string representing an absolute or a relative URL.
In the case of a relative URL, you must specify **base** to parse the final URL.
In the case of an absolute URL, the passed **base** will be ignored.| -| base | string \| URL | No| Either a string or an object. The default value is **undefined**.
- **string**: string
- **URL**: a URL object
- This parameter is used when **url** is a relative URL.| +| base | string \| URL | No| Either a string or an object. The default value is **undefined**.
- **string**: string.
- **URL**: URL object.
- This parameter is used when **url** is a relative URL.| **Example** @@ -583,7 +583,7 @@ Parses a URL. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | url | string | Yes| A string representing an absolute or a relative URL.
In the case of a relative URL, you must specify **base** to parse the final URL.
In the case of an absolute URL, the passed **base** will be ignored.| -| base | string \| URL | No| Either a string or an object. The default value is **undefined**.
- **string**: string
- **URL**: a URL object
- This parameter is used when **url** is a relative URL.| +| base | string \| URL | No| Either a string or an object. The default value is **undefined**.
- **string**: string.
- **URL**: URL object.
- This parameter is used when **url** is a relative URL.| > **NOTE** > @@ -605,7 +605,7 @@ let mm = 'https://username:password@host:8080/test/test1/test3'; let urlObject = url.URL.parseURL(mm); let result = urlObject.toString(); // Output 'https://username:password@host:8080/test/test1/test3' // If url is a relative path, the path in the base parameter is test/test1, and the path of the parsed URL is /test/path2/path3. -let url1 = url.URL.parseURL('path2/path3', 'https://www.huawei.com/test/test1'); // Output 'https://www.huawei.com/test/path2/path3' +let url1 = url.URL.parseURL('path2/path3', 'https://www.example.com/test/test1'); // Output 'https://www.example.com/test/path2/path3' // If url is a root directory, the path in the base parameter is /test/test1/test3, and the path of the parsed URL is /path1/path2. let url2 = url.URL.parseURL('/path1/path2', urlObject); // Output 'https://username:password@host:8080/path1/path2' url.URL.parseURL('/path/path1', "https://www.exampleUrl/fr-FR/toot"); // Output 'https://www.exampleUrl/path/path1' @@ -682,7 +682,7 @@ A constructor used to create a **URLSearchParams** instance. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| init | string[][] \| Record<string, string> \| string \| URLSearchParams | No| Input parameter objects, which include the following:
- **string[][]**: two-dimensional string array
- **Record<string, string>**: list of objects
- **string**: string
- **URLSearchParams**: object
The default value is **null**.| +| init | string[][] \| Record<string, string> \| string \| URLSearchParams | No| Input parameter objects, which include the following:
- **string[][]**: two-dimensional string array.
- **Record<string, string>**: list of objects.
- **string**: string.
- **URLSearchParams**: object.
The default value is **null**.| **Example** @@ -906,7 +906,7 @@ Checks whether a key has a value. | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the value exists; returns **false** otherwise.| +| boolean | Check result. The value **true** means that the key has a value, and **false** means the opposite.| **Example** diff --git a/en/application-dev/reference/apis-arkts/js-apis-util.md b/en/application-dev/reference/apis-arkts/js-apis-util.md index 725845a7e0492663e18d0fbff91a3d5edbb25484..24cd45900d0d7890fe580188d010c66e1c483eae 100644 --- a/en/application-dev/reference/apis-arkts/js-apis-util.md +++ b/en/application-dev/reference/apis-arkts/js-apis-util.md @@ -286,7 +286,7 @@ Uses a secure random number generator to generate a random universally unique id | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| entropyCache | boolean | No| Whether a cached UUID can be used. The default value is **true**.| +| entropyCache | boolean | No| Whether to use a cached UUID. The value **true** means to use a cached UUID, and **false** means the opposite. The default value is **true**.| **Return value** @@ -324,7 +324,7 @@ Uses a secure random number generator to generate a random UUID of the Uint8Arra | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| entropyCache | boolean | No| Whether a cached UUID can be used. The default value is **true**.| +| entropyCache | boolean | No| Whether to use a cached UUID. The value **true** means to use a cached UUID, and **false** means the opposite. The default value is **true**.| **Return value** @@ -535,8 +535,8 @@ Describes decoding-related options, which include **fatal** and **ignoreBOM**. | Name | Type| Mandatory| Description | | --------- | -------- | ---- | ------------------ | -| fatal | boolean | No | Whether to display fatal errors. The default value is **false**.| -| ignoreBOM | boolean | No | Whether to ignore the BOM. The default value is **false**. | +| fatal | boolean | No | Whether to display fatal errors. The value **true** means to display fatal errors, and **false** means the opposite. The default value is **false**.| +| ignoreBOM | boolean | No | Whether to ignore the BOM. The value **true** means to ignore the BOM, and **false** means the opposite. The default value is **false**. | ## DecodeToStringOptions12+ @@ -582,7 +582,7 @@ Inserts a function before a method of a class object. The inserted function is e | -------- | ------- | ---- | -------------------------------------| | targetClass | Object | Yes | Target class object. | | methodName | string | Yes | Name of the method. Read-only methods are not supported. | -| isStatic | boolean | Yes | Whether the method is a static method. The value **true** indicates a static method, and **false** indicates an instance method. | +| isStatic | boolean | Yes | Whether the method is a static method. The value **true** means a static method, and **false** means an instance method. | | before | Function | Yes | Function to insert. If the function carries parameters, then the first parameter is the **this** object, which is the target class object (specified by **targetClass**) if **isStatic** is **true** or the instance object of the method if **isStatic** is **false**; other parameters are the parameters carried in the original method. If the function does not carry any parameter, no processing is performed.| **Error codes** @@ -674,7 +674,7 @@ Inserts a function after a method of a class object. The final return value is t | -------- | ------- | ---- | -------------------------------------| | targetClass | Object | Yes | Target class object. | | methodName | string | Yes | Name of the method. Read-only methods are not supported. | -| isStatic | boolean | Yes | Whether the method is a static method. The value **true** indicates a static method, and **false** indicates an instance method. | +| isStatic | boolean | Yes | Whether the method is a static method. The value **true** means a static method, and **false** means an instance method. | | after | Function | Yes | Function to insert. If the function carries parameters, then the first parameter is the **this** object, which is the target class object (specified by **targetClass**) if **isStatic** is **true** or the instance object of the method if **isStatic** is **false**; the second parameter is the return value of the original method (**undefined** if the original method does not have a return value); other parameters are the parameters carried by the original method. If the function does not carry any parameter, no processing is performed. | **Error codes** @@ -757,7 +757,7 @@ Replaces a method of a class object with another function. After the replacement | -------- | ------- | ---- | -------------------------------------| | targetClass | Object | Yes | Target class object. | | methodName | string | Yes | Name of the method. Read-only methods are not supported. | -| isStatic | boolean | Yes | Whether the method is a static method. The value **true** indicates a static method, and **false** indicates an instance method. | +| isStatic | boolean | Yes | Whether the method is a static method. The value **true** means a static method, and **false** means an instance method. | | instead | Function | Yes | Function to be used replacement. If the function carries parameters, then the first parameter is the **this** object, which is the target class object (specified by **targetClass**) if **isStatic** is **true** or the instance object of the method if **isStatic** is **false**; other parameters are the parameters carried in the original method. If the function does not carry any parameter, no processing is performed. | **Error codes** @@ -818,7 +818,7 @@ Provides APIs to decode byte arrays into strings. It supports multiple formats, | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | | encoding | string | Yes| No| Encoding format.
The following formats are supported: utf-8, ibm866, iso-8859-2, iso-8859-3, iso-8859-4, iso-8859-5, iso-8859-6, iso-8859-7, iso-8859-8, iso-8859-8-i, iso-8859-10, iso-8859-13, iso-8859-14, iso-8859-15, koi8-r, koi8-u, macintosh, windows-874, windows-1250, windows-1251, windows-1252, windows-1253, windows-1254, windows-1255, windows-1256, windows-1257, windows-1258, x-mac-cyrillic, gbk, gb18030, big5, euc-jp, iso-2022-jp, shift_jis, euc-kr, utf-16be, utf-16le, UTF-8, GBK, GB2312, gb2312, GB18030 and iso-8859-1.| -| fatal | boolean | Yes| No| Whether to display fatal errors.| +| fatal | boolean | Yes| No| Whether to display fatal errors. The value **true** means to display fatal errors, and **false** means the opposite.| | ignoreBOM | boolean | Yes| No| Whether to ignore the byte order marker (BOM). The default value is **false**, which indicates that the result contains the BOM.| ### constructor9+ @@ -1007,8 +1007,8 @@ A constructor used to create a **TextDecoder** object. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| fatal | boolean | No| Whether to display fatal errors. The default value is **false**.| -| ignoreBOM | boolean | No| Whether to ignore the BOM. The default value is **false**.| +| fatal | boolean | No| Whether to display fatal errors. The value **true** means to display fatal errors, and **false** means the opposite. The default value is **false**.| +| ignoreBOM | boolean | No| Whether to ignore the BOM. The value **true** means to ignore the BOM, and **false** means the opposite. The default value is **false**.| **Example** @@ -1185,7 +1185,7 @@ Encodes the input content into a Uint8Array object. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------ | -| input | string | No | String to encode. The default value is an empty string.| +| input | string | No | String to encode. The default value is an empty string. If the input parameter is an empty string, the return value is undefined.| **Return value** @@ -1250,6 +1250,10 @@ let uint8 = new Uint8Array(buffer); let result = textEncoder.encodeIntoUint8Array('abcd', uint8); console.info("uint8 = " + uint8); // Output: uint8 = 97,98,99,100 +console.info("result.read = " + result.read); +// Output: result.read = 4 +console.info("result.written = " + result.written); +// Output: result.written = 4 ``` ### encodeInto(deprecated) @@ -2721,7 +2725,7 @@ console.info("result = " + result); intersect(range: ScopeHelper): ScopeHelper -Obtains the intersection of this **Scope** and the given **Scope**. +Obtains the intersection of this **Scope** and the given **Scope**. If the intersection is empty, an exception is thrown. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -3442,7 +3446,7 @@ Encodes the input content into a Uint8Array object. This API uses a promise to r | Name| Type | Mandatory| Description | | ------ | ---------- | ---- | ----------------------- | | src | Uint8Array | Yes | Uint8Array object to encode.| -| options12+ | [Type](#type10) | No| Encoding format.
The following values are available:
- **util.Type.BASIC**: Base64 encoding.
- **util.Type.BASIC_URL_SAFE**: Base64URL encoding.| +| options12+ | [Type](#type10) | No| Encoding format.
The following values are available:
- **util.Type.BASIC** (default): Base64 encoding.
- **util.Type.BASIC_URL_SAFE**: Base64URL encoding.| **Return value** diff --git a/en/application-dev/reference/apis-arkts/js-apis-vector.md b/en/application-dev/reference/apis-arkts/js-apis-vector.md index 82241930d037b90a64618d96014cf566142d0a1c..e831a1d65b2d9661d7fb24d049b865f7363cb233 100644 --- a/en/application-dev/reference/apis-arkts/js-apis-vector.md +++ b/en/application-dev/reference/apis-arkts/js-apis-vector.md @@ -838,7 +838,7 @@ Replaces an element at the specified position in this container with a given ele [Symbol.iterator]\(): IterableIterator<T> -Obtains an iterator. Each item of the iterator is a JavaScript object. +Obtains an iterator, each item of which is a JavaScript object. **System capability**: SystemCapability.Utils.Lang diff --git a/en/application-dev/reference/apis-arkts/js-apis-worker-sys.md b/en/application-dev/reference/apis-arkts/js-apis-worker-sys.md index af1d4632bf5c2fd09fd9ea8601af3738c0b3214d..66bc16ee8289ea7d6be585e0d819be4179fd18db 100644 --- a/en/application-dev/reference/apis-arkts/js-apis-worker-sys.md +++ b/en/application-dev/reference/apis-arkts/js-apis-worker-sys.md @@ -69,8 +69,8 @@ import { worker } from '@kit.ArkTS'; // Scenario 1: URL of the Worker thread file: "entry/src/main/ets/workers/worker.ets" const workerStageModel01 = new worker.RestrictedWorker('entry/ets/workers/worker.ets', {name:"first worker in Stage model"}); -// Scenario 2: URL of the Worker thread file: "phone/src/main/ets/ThreadFile/workers/worker.ets" -const workerStageModel02 = new worker.RestrictedWorker('phone/ets/ThreadFile/workers/worker.ets'); +// Scenario 2: URL of the Worker thread file: "testworkers/src/main/ets/ThreadFile/workers/worker.ets" +const workerStageModel02 = new worker.RestrictedWorker('testworkers/ets/ThreadFile/workers/worker.ets'); ``` ```ts diff --git a/en/application-dev/reference/apis-arkts/js-apis-worker.md b/en/application-dev/reference/apis-arkts/js-apis-worker.md index 81bce87a35b2750430ea90d57c7cb68e3d8f5303..fc4bce00bccf129812d224d0879dedee29748208 100644 --- a/en/application-dev/reference/apis-arkts/js-apis-worker.md +++ b/en/application-dev/reference/apis-arkts/js-apis-worker.md @@ -40,16 +40,16 @@ Provides options that can be set for the Worker instance to create. | type | 'classic' \| 'module' | Yes | Yes| Mode in which the Worker instance executes the script. The **module** type is not supported yet. The default value is **classic**.
**Atomic service API**: This API can be used in atomic services since API version 11.| | name | string | Yes | Yes| Name of the Worker thread. The default value is **undefined**.
**Atomic service API**: This API can be used in atomic services since API version 11.| | shared | boolean | Yes | Yes| Whether sharing of the Worker instance is enabled. Currently, sharing is not supported.
**Atomic service API**: This API can be used in atomic services since API version 12.| -| priority16+ | [ThreadWorkerPriority](#threadworkerpriority16) | Yes | Yes| Priority of the Worker thread.
**Atomic service API**: This API can be used in atomic services since API version 16.| +| priority18+ | [ThreadWorkerPriority](#threadworkerpriority18) | Yes | Yes| Priority of the Worker thread.
**Atomic service API**: This API can be used in atomic services since API version 18.| -## ThreadWorkerPriority16+ +## ThreadWorkerPriority18+ Enumerates the priorities available for Worker threads. For details about the mappings between priorities and QoS levels, see [QoS Level](../../napi/qos-guidelines.md#qos-level). **System capability**: SystemCapability.Utils.Lang -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. | Name| Value| Description| | -------- | -------- | -------- | @@ -102,8 +102,8 @@ import { worker } from '@kit.ArkTS'; // Scenario 1: URL of the Worker thread file: "entry/src/main/ets/workers/worker.ets" const workerStageModel01 = new worker.ThreadWorker('entry/ets/workers/worker.ets', {name:"first worker in Stage model"}); -// Scenario 2: URL of the Worker thread file: "phone/src/main/ets/ThreadFile/workers/worker.ets" -const workerStageModel02 = new worker.ThreadWorker('phone/ets/ThreadFile/workers/worker.ets'); +// Scenario 2: URL of the Worker thread file: "testworkers/src/main/ets/ThreadFile/workers/worker.ets" +const workerStageModel02 = new worker.ThreadWorker('testworkers/ets/ThreadFile/workers/worker.ets'); ``` @@ -192,7 +192,7 @@ struct Index { console.log("main thread terminate"); } - workerInstance.onerror = (err: ErrorEvent) => { + workerInstance.onAllErrors = (err: ErrorEvent) => { console.log("main error message " + err.message); } }) @@ -449,6 +449,7 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ **Example** ```ts +//Index.ets const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ets"); class TestObj { private message : string = "this is a message from TestObj" @@ -465,6 +466,31 @@ workerInstance.registerGlobalCallObject("myObj", registerObj); workerInstance.postMessage("start worker") ``` +```ts +// worker.ets +import { worker, MessageEvents } from '@kit.ArkTS'; + +const workerPort = worker.workerPort; +workerPort.onmessage = (e: MessageEvents): void => { + try { + // The method to call does not carry an input parameter. + let res : string = workerPort.callGlobalCallObjectMethod("myObj", "getMessage", 0) as string; + console.info("worker:", res) // worker: this is a message from TestObj + } catch (error) { + // Exception handling. + console.error("worker: error code is " + error.code + " error message is " + error.message); + } + try { + // The method to call carries input parameters. + let res : string = workerPort.callGlobalCallObjectMethod("myObj", "getMessageWithInput", 0, "hello there!") as string; + console.info("worker:", res) //worker: this is a message from TestObj with input: hello there! + } catch (error) { + // Exception handling. + console.error("worker: error code is " + error.code + " error message is " + error.message); + } +} +``` + ### unregisterGlobalCallObject11+ unregisterGlobalCallObject(instanceName?: string): void @@ -605,6 +631,39 @@ workerInstance.onerror = (err: ErrorEvent) => { } ``` +### onAllErrors18+ + +onAllErrors?: ErrorCallback + +Called when an exception occurs within the lifecycle of the Worker thread. The event handler is executed in the host thread. + +[onerror](#onerror9) can capture only exceptions generated by synchronous methods within the [onmessage](#onmessage9) callback. It cannot capture exceptions from multithreaded callbacks or modularization-related exceptions. Once an exception is captured, the Worker thread will proceed to the destruction process and cannot be used. + +**onAllErrors** can capture global exceptions generated during the **onmessage** callback, timer callback, and file execution of the Worker thread. After an exception is captured by **onAllErrors**, the Worker thread remains alive and can continue to be used. You are advised to use **onAllErrors** instead of **onerror**. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Error codes** + +For details about the error codes, see [Utils Error Codes](errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | The Worker instance is not running. | +| 10200005 | The called API is not supported in the worker thread. | + +**Example** + +```ts +import { worker, ErrorEvent } from '@kit.ArkTS'; + +const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ets"); +workerInstance.onAllErrors = (err: ErrorEvent) => { + console.log("onAllErrors" + err.message); +} +``` ### onmessage9+ @@ -765,7 +824,7 @@ Dispatches the event defined for the Worker thread. | Type | Description | | ------- | ------------------------------- | -| boolean | Returns **true** if the event is dispatched; returns **false** otherwise.| +| boolean | Dispatch result. The value **true** means a successful dispatch, and **false** means the opposite.| **Error codes** @@ -955,7 +1014,7 @@ Dispatches the event defined for the Worker thread. | Type | Description | | ------- | ------------------------------- | -| boolean | Returns **true** if the event is dispatched successfully; returns **false** otherwise.| +| boolean | Dispatch result. The value **true** means a successful dispatch, and **false** means the opposite.| **Error codes** @@ -1265,6 +1324,24 @@ For details about the error codes, see [Universal Error Codes](../errorcode-univ | 10200021 | The global call exceeds the timeout. | **Example** +```ts +//Index.ets +const workerInstance = new worker.ThreadWorker("entry/ets/workers/worker.ets"); +class TestObj { + private message : string = "this is a message from TestObj" + public getMessage() : string { + return this.message; + } + public getMessageWithInput(str : string) : string { + return this.message + " with input: " + str; + } +} +let registerObj = new TestObj(); +// Register registerObj with the ThreadWorker instance. +workerInstance.registerGlobalCallObject("myObj", registerObj); +workerInstance.postMessage("start worker") +``` + ```ts // worker.ets import { worker, MessageEvents } from '@kit.ArkTS'; @@ -1525,6 +1602,22 @@ Defines the message type. | 'message' | The message type is message, fixed at **'message'**.| | 'messageerror' | The message type is messageerror, fixed at **'messageerror'**.| +## ErrorCallback18+ + +type ErrorCallback = (err: ErrorEvent) => void + +Defines an error callback. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------- | ---- | ------------------------------------------------------------ | +| err | ErrorEvent | Yes | Error event class, which provides detailed information about the exception occurred during Worker execution.| + ## Worker(deprecated) Before using the following APIs, you must create a Worker instance. The **Worker** class inherits from [EventTarget](#eventtargetdeprecated). @@ -1564,8 +1657,8 @@ import { worker } from '@kit.ArkTS'; // Scenario 1: URL of the Worker thread file: "entry/src/main/ets/workers/worker.ets" const workerStageModel01 = new worker.ThreadWorker('entry/ets/workers/worker.ets', {name:"first worker in Stage model"}); -// Scenario 2: URL of the Worker thread file: "phone/src/main/ets/ThreadFile/workers/worker.ets" -const workerStageModel02 = new worker.ThreadWorker('phone/ets/ThreadFile/workers/worker.ets'); +// Scenario 2: URL of the Worker thread file: "testworkers/src/main/ets/ThreadFile/workers/worker.ets" +const workerStageModel02 = new worker.ThreadWorker('testworkers/ets/ThreadFile/workers/worker.ets'); ``` ### postMessage(deprecated) @@ -1849,9 +1942,13 @@ Adds an event listener for the Worker thread. This API provides the same functio **Example** ```ts -const workerInstance = new worker.Worker("workers/worker.ets"); -workerInstance.addEventListener("alert", ()=>{ - console.log("alert listener callback"); +// worker.ets +import { DedicatedWorkerGlobalScope, ErrorEvent, MessageEvents, worker } from '@kit.ArkTS'; + +const workerPort: DedicatedWorkerGlobalScope = worker.parentPort; + +workerPort.addEventListener("alert", () => { + console.info("alert listener callback"); }) ``` @@ -1877,11 +1974,16 @@ Removes an event listener for the Worker thread. This API provides the same func **Example** ```ts -const workerInstance = new worker.Worker("workers/worker.ets"); -workerInstance.addEventListener("alert", ()=>{ - console.log("alert listener callback"); +// worker.ets +import { DedicatedWorkerGlobalScope, ErrorEvent, MessageEvents, worker } from '@kit.ArkTS'; + +const workerPort: DedicatedWorkerGlobalScope = worker.parentPort; + +workerPort.addEventListener("alert", () => { + console.info("alert listener callback"); }) -workerInstance.removeEventListener("alert"); + +workerPort.removeEventListener('alert'); ``` @@ -1906,57 +2008,51 @@ Dispatches the event defined for the Worker thread. | Type | Description | | ------- | ------------------------------- | -| boolean | Returns **true** if the event is dispatched successfully; returns **false** otherwise.| +| boolean | Dispatch result. The value **true** means a successful dispatch, and **false** means the opposite.| **Example** ```ts -const workerInstance = new worker.Worker("workers/worker.ets"); +// worker.ets +import { DedicatedWorkerGlobalScope, ErrorEvent, MessageEvents, worker } from '@kit.ArkTS'; -workerInstance.dispatchEvent({type:"eventType", timeStamp:0}); // timeStamp is not supported yet. +const workerPort: DedicatedWorkerGlobalScope = worker.parentPort; + +workerPort.addEventListener("alert_add", ()=>{ + console.info("alert listener callback"); +}) + +workerPort.dispatchEvent({type: 'alert_add', timeStamp: 0}); // timeStamp is not supported yet. ``` -The **dispatchEvent** API can be used together with the **on**, **once**, and **addEventListener** APIs. The sample code is as follows: +The **dispatchEvent** API can be used together with the **addEventListener** API. The sample code is as follows: ```ts -const workerInstance = new worker.Worker("workers/worker.ets"); +// Main thread +import { worker } from '@kit.ArkTS'; -// Usage 1: -workerInstance.on("alert_on", ()=>{ - console.log("alert listener callback"); -}) -workerInstance.once("alert_once", ()=>{ - console.log("alert listener callback"); -}) -workerInstance.addEventListener("alert_add", ()=>{ - console.log("alert listener callback"); -}) +const workerInstance = new worker.Worker("workers/worker.ets"); +workerInstance.postMessage("hello world"); +workerInstance.onmessage = (): void => { + console.info("receive data from worker.ets"); +} +``` -// The event listener created by once is removed after being executed once. -workerInstance.dispatchEvent({type:"alert_once", timeStamp:0}); // timeStamp is not supported yet. -// The event listener created by on will not be proactively deleted. -workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); -workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); -// The event listener created by addEventListener will not be proactively deleted. -workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); -workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); +```ts +// worker.ets +import { DedicatedWorkerGlobalScope, ErrorEvent, MessageEvents, worker } from '@kit.ArkTS'; -// Usage 2: -// The event type can be customized, and the special types "message", "messageerror", and "error" exist. -// When type = "message", the event handler defined by onmessage will also be executed. -// When type = "messageerror", the event handler defined by onmessageerror will also be executed. -// When type = "error", the event handler defined by onerror will also be executed. -// removeEventListener or off can be used to remove an event listener that is created by addEventListener, on, or once. +const workerPort: DedicatedWorkerGlobalScope = worker.parentPort; -workerInstance.addEventListener("message", ()=>{ - console.log("message listener callback"); +workerPort.addEventListener("alert", ()=>{ + console.info("alert listener callback"); }) -workerInstance.onmessage = function() { - console.log("onmessage : message listener callback"); + +workerPort.onmessage = (event: MessageEvents) => { + workerPort.dispatchEvent({type:"alert", timeStamp:0}); // timeStamp is not supported yet. } -// When dispatchEvent is called to distribute the "message" event, the callback passed in addEventListener and onmessage will be invoked. -workerInstance.dispatchEvent({type:"message", timeStamp:0}); ``` + ### removeAllListener(deprecated) removeAllListener(): void @@ -1971,11 +2067,16 @@ Removes all event listeners for the Worker thread. **Example** ```ts -const workerInstance = new worker.Worker("workers/worker.ets"); -workerInstance.addEventListener("alert", ()=>{ - console.log("alert listener callback"); +// worker.ets +import { DedicatedWorkerGlobalScope, ErrorEvent, MessageEvents, worker } from '@kit.ArkTS'; + +const workerPort: DedicatedWorkerGlobalScope = worker.parentPort; + +workerPort.addEventListener("alert_add", ()=>{ + console.info("alert listener callback"); }) -workerInstance.removeAllListener(); + +workerPort.removeAllListener(); ``` @@ -2328,7 +2429,7 @@ parentPort.onerror = (err: ErrorEvent) => { ### Sequenceable Data Types -The following object types are supported: basic types except Symbol, Date, String, RegExp, Array, Map, Set, Object (simple objects only, for example, objects created using **{}** or **new Object**), ArrayBuffer, and typedArray. (Note that only attributes can be transferred for common objects. Prototypes and methods cannot be transferred.) +The following object types are supported: basic types except Symbol, Date, String, RegExp, Array, Map, Set, Object (simple objects only, for example, objects created using **{}** or **new Object**), ArrayBuffer, and TypedArray. (Note that only attributes can be transferred for common objects. Prototypes and methods cannot be transferred.) Exception: When an object created through a custom class is passed, no serialization error occurs. However, the attributes (such as Function) of the custom class cannot be passed through serialization. > **NOTE**
@@ -2450,7 +2551,7 @@ Add the following configuration to the module-level **entry/build-profile.json5* } ``` ### Stage Model -> The following uses API version 12 as an example. +> The following uses API version 18 as an example. ```ts // Index.ets import { worker, MessageEvents, ErrorEvent } from '@kit.ArkTS'; @@ -2484,7 +2585,7 @@ struct Index { console.log("main thread terminate"); } - workerInstance.onerror = (err: ErrorEvent) => { + workerInstance.onAllErrors = (err: ErrorEvent) => { console.log("main error message " + err.message); } }) diff --git a/en/application-dev/reference/apis-arkts/js-apis-xml.md b/en/application-dev/reference/apis-arkts/js-apis-xml.md index 18f8381d0656d708a95b19e130570116c8b450e0..8058251bf10b7983ea8d0021b1063817d24e0d8e 100644 --- a/en/application-dev/reference/apis-arkts/js-apis-xml.md +++ b/en/application-dev/reference/apis-arkts/js-apis-xml.md @@ -1,6 +1,6 @@ # @ohos.xml (XML Parsing and Generation) -The **XML** module provides a series of APIs for converting XML text into JavaScript objects and generating and parsing XML files. +The XML module provides a series of APIs for converting XML text into JavaScript objects and generating and parsing XML files. > **NOTE** > @@ -598,8 +598,8 @@ Defines the XML parsing options. | Name | Type | Mandatory| Description | | ------------------------------ | ------------------------------------------------------------ | ---- | --------------------------------------- | -| supportDoctype | boolean | No | Whether to ignore the document type. The default value is **false**, indicating that the document type is not parsed.| -| ignoreNameSpace | boolean | No | Whether to ignore the namespace. The default value is **false**, indicating that the namespace is not ignored.| +| supportDoctype | boolean | No | Whether to parse the document type. The value **true** means to parse the document type, and **false** means the opposite. The default value is **false**.| +| ignoreNameSpace | boolean | No | Whether to ignore the namespace. If the namespace is ignored, it will not be parsed. The value **true** means to ignore the namespace, and **false** means the opposite. The default value is **false**.| | tagValueCallbackFunction | (name: string, value: string) => boolean | No | Start tag, tag value, and end tag of parsing. The default value is **undefined**, indicating no parsing.| | attributeValueCallbackFunction | (name: string, value: string) => boolean | No | Parsing attribute and attribute value. The default value is **undefined**, indicating no parsing.| | tokenValueCallbackFunction | (eventType: [EventType](#eventtype), value: [ParseInfo](#parseinfo)) => boolean | No | Parsing element's [EventType](#eventtype) and [ParseInfo](#parseinfo). The default value is **undefined**, indicating no parsing.| @@ -613,7 +613,7 @@ Provides APIs to manage the parsed XML information. getColumnNumber(): number -Obtains the column line number, starting from 1. +Obtains the current column number, starting from 1. **Atomic service API**: This API can be used in atomic services since API version 11. diff --git a/en/application-dev/reference/apis-arkui/Readme-EN.md b/en/application-dev/reference/apis-arkui/Readme-EN.md index 59209c2a4b92176722d0e05607c9947709059c07..20930adbb3865e9f10793d9c2d72001a38fbbfcb 100644 --- a/en/application-dev/reference/apis-arkui/Readme-EN.md +++ b/en/application-dev/reference/apis-arkui/Readme-EN.md @@ -85,7 +85,7 @@ - [Component Area Change Event](arkui-ts/ts-universal-component-area-change-event.md) - [Component Size Change Event](arkui-ts/ts-universal-component-size-change-event.md) - [Visible Area Change Event](arkui-ts/ts-universal-component-visible-area-change-event.md) - - [Custom Keyboard Shortcuts](arkui-ts/ts-universal-events-keyboardshortcut.md) + - [Component Keyboard Shortcut Event](arkui-ts/ts-universal-events-keyboardshortcut.md) - [Custom Event Dispatch](arkui-ts/ts-universal-attributes-on-child-touch-test.md) - [Custom Event Interception](arkui-ts/ts-universal-attributes-on-touch-intercept.md) - [Focus Axis Event](arkui-ts/ts-universal-events-focus_axis.md) @@ -104,7 +104,7 @@ - [Overlay](arkui-ts/ts-universal-attributes-overlay.md) - [Z-order Control](arkui-ts/ts-universal-attributes-z-order.md) - [Transformation](arkui-ts/ts-universal-attributes-transformation.md) - - [Image Effects](arkui-ts/ts-universal-attributes-image-effect.md) + - [Image Effect](arkui-ts/ts-universal-attributes-image-effect.md) - [Shape Clipping](arkui-ts/ts-universal-attributes-sharp-clipping.md) - [Gradient Color](arkui-ts/ts-universal-attributes-gradient-color.md) - [Popup Control](arkui-ts/ts-universal-attributes-popup.md) @@ -116,7 +116,7 @@ - [Polymorphic Style](arkui-ts/ts-universal-attributes-polymorphic-style.md) - [restoreId](arkui-ts/ts-universal-attributes-restoreId.md) - [Foreground Color](arkui-ts/ts-universal-attributes-foreground-color.md) - - Foreground Effect](arkui-ts/ts-universal-attributes-foreground-effect.md) + - [Foreground Effect](arkui-ts/ts-universal-attributes-foreground-effect.md) - [Foreground Blur](arkui-ts/ts-universal-attributes-foreground-blur-style.md) - [Motion Blur](arkui-ts/ts-universal-attributes-motionBlur.md) - [Click Effect](arkui-ts/ts-universal-attributes-click-effect.md) @@ -145,7 +145,7 @@ - [Special Effect Drawing Combination](arkui-ts/ts-universal-attributes-use-effect.md) - [Point Light Style (System API)](arkui-ts/ts-universal-attributes-point-light-style-sys.md) - - [Image Effects (System API)](arkui-ts/ts-universal-attributes-image-effect-sys.md) + - [Image Effect (System API)](arkui-ts/ts-universal-attributes-image-effect-sys.md) - Gesture Handling - [Gesture Binding Methods](arkui-ts/ts-gesture-settings.md) diff --git a/en/application-dev/reference/apis-arkui/_ark_u_i___native_dialog_a_p_i__1.md b/en/application-dev/reference/apis-arkui/_ark_u_i___native_dialog_a_p_i__1.md index e30886616d57b105448062b705c2d6c7564fc257..9608cd1d00a0f3e32be02a28552953cd818a6d18 100644 --- a/en/application-dev/reference/apis-arkui/_ark_u_i___native_dialog_a_p_i__1.md +++ b/en/application-dev/reference/apis-arkui/_ark_u_i___native_dialog_a_p_i__1.md @@ -34,6 +34,7 @@ Provides the custom dialog box APIs for the native side. | int32_t(\* [registerOnWillDismiss](#registeronwilldismiss) )([ArkUI_NativeDialogHandle](_ark_u_i___native_module.md#arkui_nativedialoghandle) handle, [ArkUI_OnWillDismissEvent](_ark_u_i___native_module.md#arkui_onwilldismissevent) eventHandler) | Registers a callback for a custom dialog box so that the user can decide whether to close the dialog box after they touch the Back button or press the Esc key. | | int32_t(\* [show](#show) )([ArkUI_NativeDialogHandle](_ark_u_i___native_module.md#arkui_nativedialoghandle) handle, bool showInSubWindow) | Shows a custom dialog box. | | int32_t(\* [close](#close) )([ArkUI_NativeDialogHandle](_ark_u_i___native_module.md#arkui_nativedialoghandle) handle) | Closes a custom dialog box. If the dialog box has been closed, this API does not take effect. | +| int32_t(\* [registerOnWillDismissWithUserData](#registeronwilldismisswithuserdata) )([ArkUI_NativeDialogHandle](_ark_u_i___native_module.md#arkui_nativedialoghandle) handle, void \*userData, void(\*callback)([ArkUI_DialogDismissEvent](_ark_u_i___native_module.md#arkui_dialogdismissevent) \*event)) | Registers a callback for the dismissal event of a custom dialog box. | ## Member Variable Description @@ -56,7 +57,7 @@ Closes a custom dialog box. If the dialog box has been closed, this API does not **Returns** -Returns **0** if the operation is successful; returns **401** if a parameter error occurs. +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md#arkui_errorcode) if the operation is successful. Returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md#arkui_errorcode) if a parameter error occurs. ### create @@ -115,7 +116,7 @@ This method must be called before the **show** method. **Returns** -Returns **0** if the operation is successful; returns **401** if a parameter error occurs. +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md#arkui_errorcode) if the operation is successful. Returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md#arkui_errorcode) if a parameter error occurs. ### enableCustomStyle @@ -140,7 +141,7 @@ This method must be called before the **show** method. **Returns** -Returns **0** if the operation is successful; returns **401** if a parameter error occurs. +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md#arkui_errorcode) if the operation is successful. Returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md#arkui_errorcode) if a parameter error occurs. ### registerOnWillDismiss @@ -165,7 +166,29 @@ This method must be called before the **show** method. **Returns** -Returns **0** if the operation is successful; returns **401** if a parameter error occurs. +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md#arkui_errorcode) if the operation is successful. Returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md#arkui_errorcode) if a parameter error occurs. + + +### registerOnWillDismissWithUserData + +``` +int32_t(* ArkUI_NativeDialogAPI_1::registerOnWillDismissWithUserData) (ArkUI_NativeDialogHandle handle, void *userData, void(*callback)(ArkUI_DialogDismissEvent *event)) +``` +**Description** + +Registers a callback for the dismissal event of a custom dialog box. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| handle | Pointer to the custom dialog box controller. | +| userData | Pointer to user data. | +| callback | Callback for the dismissal event of the custom dialog box. | + +**Returns** + +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md#arkui_errorcode) if the operation is successful. Returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md#arkui_errorcode) if a parameter error occurs. ### removeContent @@ -189,7 +212,7 @@ This method must be called before the **show** method. **Returns** -Returns **0** if the operation is successful; returns **401** if a parameter error occurs. +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md#arkui_errorcode) if the operation is successful. Returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md#arkui_errorcode) if a parameter error occurs. ### resetContentAlignment @@ -213,7 +236,7 @@ This method must be called before the **show** method. **Returns** -Returns **0** if the operation is successful; returns **401** if a parameter error occurs. +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md#arkui_errorcode) if the operation is successful. Returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md#arkui_errorcode) if a parameter error occurs. ### setAutoCancel @@ -238,7 +261,7 @@ This method must be called before the **show** method. **Returns** -Returns **0** if the operation is successful; returns **401** if a parameter error occurs. +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md#arkui_errorcode) if the operation is successful. Returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md#arkui_errorcode) if a parameter error occurs. ### setBackgroundColor @@ -263,7 +286,7 @@ This method must be called before the **show** method. **Returns** -Returns **0** if the operation is successful; returns **401** if a parameter error occurs. +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md#arkui_errorcode) if the operation is successful. Returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md#arkui_errorcode) if a parameter error occurs. ### setContent @@ -288,7 +311,7 @@ This method must be called before the **show** method. **Returns** -Returns **0** if the operation is successful; returns **401** if a parameter error occurs. +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md#arkui_errorcode) if the operation is successful. Returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md#arkui_errorcode) if a parameter error occurs. ### setContentAlignment @@ -315,7 +338,7 @@ This method must be called before the **show** method. **Returns** -Returns **0** if the operation is successful; returns **401** if a parameter error occurs. +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md#arkui_errorcode) if the operation is successful. Returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md#arkui_errorcode) if a parameter error occurs. ### setCornerRadius @@ -343,7 +366,7 @@ This method must be called before the **show** method. **Returns** -Returns **0** if the operation is successful; returns **401** if a parameter error occurs. +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md#arkui_errorcode) if the operation is successful. Returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md#arkui_errorcode) if a parameter error occurs. ### setGridColumnCount @@ -368,7 +391,7 @@ This method must be called before the **show** method. **Returns** -Returns **0** if the operation is successful; returns **401** if a parameter error occurs. +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md#arkui_errorcode) if the operation is successful. Returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md#arkui_errorcode) if a parameter error occurs. ### setMask @@ -394,7 +417,7 @@ This method must be called before the **show** method. **Returns** -Returns **0** if the operation is successful; returns **401** if a parameter error occurs. +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md#arkui_errorcode) if the operation is successful. Returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md#arkui_errorcode) if a parameter error occurs. ### setModalMode @@ -419,7 +442,7 @@ This method must be called before the **show** method. **Returns** -Returns **0** if the operation is successful; returns **401** if a parameter error occurs. +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md#arkui_errorcode) if the operation is successful. Returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md#arkui_errorcode) if a parameter error occurs. ### show @@ -440,5 +463,4 @@ Shows a custom dialog box. **Returns** -Returns **0** if the operation is successful; returns **401** if a parameter error occurs. - \ No newline at end of file +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md#arkui_errorcode) if the operation is successful. Returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md#arkui_errorcode) if a parameter error occurs. diff --git a/en/application-dev/reference/apis-arkui/_ark_u_i___native_dialog_a_p_i__2.md b/en/application-dev/reference/apis-arkui/_ark_u_i___native_dialog_a_p_i__2.md new file mode 100644 index 0000000000000000000000000000000000000000..f9b3545715398d05e7bc543e4253d32c3546abae --- /dev/null +++ b/en/application-dev/reference/apis-arkui/_ark_u_i___native_dialog_a_p_i__2.md @@ -0,0 +1,118 @@ +# ArkUI_NativeDialogAPI_2 + + +## Overview + +Provides the custom dialog box APIs (version 2) for the native side. + +**Since**: 15 + +**Related module**: [ArkUI_NativeModule](_ark_u_i___native_module.md) + + +## Summary + + +### Member Variables + +| Name| Description| +| -------- | -------- | +| [ArkUI_NativeDialogAPI_1](_ark_u_i___native_dialog_a_p_i__1.md#ArkUI_NativeDialogAPI_1) nativeDialogAPI1 | A set of the custom dialog box APIs on the native side. | +| int32_t(\* [setKeyboardAvoidDistance](#setkeyboardavoiddistance) )([ArkUI_NativeDialogHandle](_ark_u_i___native_module.md#arkui_nativedialoghandle) handle, float distance, [ArkUI_LengthMetricUnit](_ark_u_i___native_module.md#arkui_lengthmetricunit) unit) | Sets the minimum distance between the dialog box and the keyboard after keyboard avoidance is applied. | +| int32_t(\* [setLevelMode](#setlevelmode) )([ArkUI_NativeDialogHandle](_ark_u_i___native_module.md#arkui_nativedialoghandle) handle, [ArkUI_LevelMode](_ark_u_i___native_module.md#arkui_levelmode) levelMode) | Sets the display level of the dialog box. | +| int32_t(\* [setLevelUniqueId](#setleveluniqueid) )([ArkUI_NativeDialogHandle](_ark_u_i___native_module.md#arkui_nativedialoghandle) handle, int32_t uniqueId) | Sets the ID of the node under the dialog box's display level. | +| int32_t(\* [setImmersiveMode](#setimmersivemode) )([ArkUI_NativeDialogHandle](_ark_u_i___native_module.md#arkui_nativedialoghandle) handle, [ArkUI_ImmersiveMode](_ark_u_i___native_module.md#arkui_immersivemode) immersiveMode) | Sets the display area of the embedded dialog box overlay. | + + + +## Member Variable Description + + +### setKeyboardAvoidDistance + +``` +int32_t(* ArkUI_NativeDialogAPI_2::setKeyboardAvoidDistance) (ArkUI_NativeDialogHandle handle, float distance, ArkUI_LengthMetricUnit unit) +``` +**Description** + +Sets the minimum distance between the dialog box and the keyboard after keyboard avoidance is applied. The default value is **16vp**, and the default unit is vp. This API takes effect only when **keyboardAvoidMode** is set to **DEFAULT**. + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| handle | Pointer to the custom dialog box controller. | +| distance | Distance value between the dialog box and the keyboard.| +| ArkUI_LengthMetricUnit | Unit of the distance. | + +**Returns** + +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. + +### setLevelMode + +``` +int32_t(* ArkUI_NativeDialogAPI_2::setLevelMode) (ArkUI_NativeDialogHandle handle, ArkUI_LevelMode levelMode) +``` +**Description** + +Sets the display level of the dialog box. This API must be called before **show**. + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| handle | Pointer to the custom dialog box controller. | +| levelMode | Display level mode, specified by an enumeration value of type **ArkUI_LevelMode**.| + +**Returns** + +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. + +### setLevelUniqueId + +``` +int32_t(* ArkUI_NativeDialogAPI_2::setLevelUniqueId) (ArkUI_NativeDialogHandle handle, int32_t uniqueId) +``` +**Description** + +Sets the ID of the node under the dialog box's display level. This API must be called before **setLevelMode**. + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| handle | Pointer to the custom dialog box controller. | +| uniqueId | ID of the node under the dialog box's display level. The dialog box will be displayed on the same page as this node.| + +**Returns** + +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. + +### setImmersiveMode + +``` +int32_t(* ArkUI_NativeDialogAPI_2::setImmersiveMode) (ArkUI_NativeDialogHandle handle, ArkUI_ImmersiveMode immersiveMode) +``` +**Description** + +Sets the display area of the embedded dialog box overlay. This API must be called before **show**. + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| handle | Pointer to the custom dialog box controller. | +| immersiveMode | Display area, specified by an enumeration value of type **ArkUI_ImmersiveMode**.| + +**Returns** + +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. diff --git a/en/application-dev/reference/apis-arkui/_ark_u_i___native_gesture_a_p_i__2.md b/en/application-dev/reference/apis-arkui/_ark_u_i___native_gesture_a_p_i__2.md new file mode 100644 index 0000000000000000000000000000000000000000..8dcdee2ccabb6a9ba65c98766ad4c90c95c6de4b --- /dev/null +++ b/en/application-dev/reference/apis-arkui/_ark_u_i___native_gesture_a_p_i__2.md @@ -0,0 +1,59 @@ +# ArkUI_NativeGestureAPI_2 + + +## Overview + +Defines the gesture APIs. + +**Since**: 18 + +**Related module**: [ArkUI_NativeModule](_ark_u_i___native_module.md) + + +## Summary + + +### Member Variables + +| Name| Description| +| -------- | -------- | +| [ArkUI_NativeGestureAPI_1](_ark_u_i___native_gesture_a_p_i__1.md)* [gestureApi1](#gestureapi1); | Pointer to the [ArkUI_NativeGestureAPI_1](_ark_u_i___native_gesture_a_p_i__1.md) struct.| +| int32_t(\* [setGestureInterrupterToNode](#setgestureinterruptertonode) )([ArkUI_NodeHandle](_ark_u_i___native_module.md#arkui_nodehandle) node, void* userData, [ArkUI_GestureInterruptResult](_ark_u_i___native_module.md#arkui_gestureinterruptresult)(\*interrupter)(ArkUI_GestureInterruptInfo \*info)) | Sets the callback for gesture interruption events.| + + +## Member Variable Description + + +### setGestureInterrupterToNode + +``` +int32_t(* ArkUI_NativeGestureAPI_1::setGestureInterrupterToNode) (ArkUI_NodeHandle node, void* userData, ArkUI_GestureInterruptResult(*interrupter)(ArkUI_GestureInterruptInfo *info)) +``` +**Description** + +Sets the callback for gesture interruption events. + +**Since**: 18 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| node | Node for which you want to set a gesture interruption callback.| +| userData | Custom data.| +| interrupter | Gesture interruption callback to set.
If **GESTURE_INTERRUPT_RESULT_CONTINUE** is returned, the gesture recognition process continues.
If **GESTURE_INTERRUPT_RESULT_REJECT** is returned, the gesture recognition process is paused.| + +**Returns** + +Returns **0** if the operation is successful. Returns **401** if a parameter error occurs. + +### gestureApi1 + +``` +ArkUI_NativeGestureAPI_1* gestureApi1 +``` +**Description** + +Pointer to the [ArkUI_NativeGestureAPI_1](_ark_u_i___native_gesture_a_p_i__1.md) struct. + +**Since**: 18 diff --git a/en/application-dev/reference/apis-arkui/_ark_u_i___native_module.md b/en/application-dev/reference/apis-arkui/_ark_u_i___native_module.md index 9d19ccb1bb0e48b55dab2c894bb88c6b535ef422..1f74cfbe22b87cd13a8d8754242ee94eb388f212 100644 --- a/en/application-dev/reference/apis-arkui/_ark_u_i___native_module.md +++ b/en/application-dev/reference/apis-arkui/_ark_u_i___native_module.md @@ -21,7 +21,7 @@ Provides UI capabilities of ArkUI on the native side, such as UI component creat ### Files -| Name| Description| +| Name| Description| | -------- | -------- | | [drag_and_drop.h](drag__and__drop_8h.md) | Declares the APIs of **NativeDrag**. | | [drawable_descriptor.h](drawable__descriptor_8h.md) | Declares the APIs of **NativeDrawableDescriptor**. | @@ -39,714 +39,799 @@ Provides UI capabilities of ArkUI on the native side, such as UI component creat ### Structs -| Name| Description| +| Name| Description| | -------- | -------- | -| struct [ArkUI_ExpectedFrameRateRange](_ark_u_i___expected_frame_rate_range.md) | Defines a struct for the expected frame rate range of the animation. | -| struct [ArkUI_AnimateCompleteCallback](_ark_u_i___animate_complete_callback.md) | Defines a struct for the callback type for when the animation playback is complete. | -| struct [ArkUI_NativeAnimateAPI_1](_ark_u_i___native_animate_a_p_i__1.md) | Defines a struct for the animation APIs of ArkUI on the native side. | -| struct [ArkUI_NativeDialogAPI_1](_ark_u_i___native_dialog_a_p_i__1.md) | Defines a struct for the custom dialog box APIs on the native side. | -| struct [ArkUI_NativeGestureAPI_1](_ark_u_i___native_gesture_a_p_i__1.md) | Defines a struct for the gesture APIs. | -| struct [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) | Defines the general input parameter structure of the **setAttribute** function. | -| struct [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) | Defines a struct for the parameter type of the component callback event. | -| struct [ArkUI_StringAsyncEvent](_ark_u_i___string_async_event.md) | Defines the string type parameter used by the component callback event. | -| struct [ArkUI_NativeNodeAPI_1](_ark_u_i___native_node_a_p_i__1.md) | Defines a struct for node APIs of ArkUI on the native side. | -| struct [ArkUI_ContextCallback](_ark_u_i___context_callback.md) | Defines event callback. | -| union [ArkUI_NumberValue](union_ark_u_i___number_value.md) | Provides the number types of ArkUI in the native code. | -| struct [ARKUI_TextPickerRangeContent](_a_r_k_u_i___text_picker_range_content.md) | Defines the input structure of the single-column text picker with image resources. | -| struct [ARKUI_TextPickerCascadeRangeContent](_a_r_k_u_i___text_picker_cascade_range_content.md) | Defines the input structure of the interconnected multi-column text picker. | -| struct [ArkUI_ColorStop](_ark_u_i___color_stop.md) | Defines a gradient color stop. | -| struct [ArkUI_Rect](_ark_u_i___rect.md) | Defines a mask area. | -| struct [ArkUI_IntSize](_ark_u_i___int_size.md) | Describes the width and height of a component. | -| struct [ArkUI_IntOffset](_ark_u_i___int_offset.md) | Describes the position of a component. | -| struct [ArkUI_Margin](_ark_u_i___margin.md) | Describes the margins of a component. | -| struct [ArkUI_TranslationOptions](_ark_u_i___translation_options.md) | Defines the translation options for component transition. | -| struct [ArkUI_ScaleOptions](_ark_u_i___scale_options.md) | Defines the scaling options for component transition. | -| struct [ArkUI_RotationOptions](_ark_u_i___rotation_options.md) | Defines the rotation options for component transition. | +| struct [ArkUI_ExpectedFrameRateRange](_ark_u_i___expected_frame_rate_range.md) | Defines a struct for the expected frame rate range of the animation. | +| struct [ArkUI_AnimateCompleteCallback](_ark_u_i___animate_complete_callback.md) | Defines a struct for the callback type for when the animation playback is complete. | +| struct [ArkUI_NativeAnimateAPI_1](_ark_u_i___native_animate_a_p_i__1.md) | Defines a struct for the animation APIs of ArkUI on the native side. | +| struct [ArkUI_NativeDialogAPI_1](_ark_u_i___native_dialog_a_p_i__1.md) | Defines a struct for the custom dialog box APIs on the native side. | +| struct [ArkUI_NativeGestureAPI_1](_ark_u_i___native_gesture_a_p_i__1.md) | Defines a struct for the gesture APIs. | +| struct [ArkUI_NativeGestureAPI_2](_ark_u_i___native_gesture_a_p_i__2.md) | Defines a new struct for the gesture APIs.| +| struct [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) | Defines the general input parameter structure of the **setAttribute** function. | +| struct [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) | Defines a struct for the parameter type of the component callback event. | +| struct [ArkUI_StringAsyncEvent](_ark_u_i___string_async_event.md) | Defines the string type parameter used by the component callback event. | +| struct [ArkUI_NativeNodeAPI_1](_ark_u_i___native_node_a_p_i__1.md) | Defines a struct for node APIs of ArkUI on the native side. | +| struct [ArkUI_ContextCallback](_ark_u_i___context_callback.md) | Defines event callback. | +| union [ArkUI_NumberValue](union_ark_u_i___number_value.md) | Provides the number types of ArkUI in the native code. | +| struct [ARKUI_TextPickerRangeContent](_a_r_k_u_i___text_picker_range_content.md) | Defines the input structure of the single-column text picker with image resources. | +| struct [ARKUI_TextPickerCascadeRangeContent](_a_r_k_u_i___text_picker_cascade_range_content.md) | Defines the input structure of the interconnected multi-column text picker. | +| struct [ArkUI_ColorStop](_ark_u_i___color_stop.md) | Defines a gradient color stop. | +| struct [ArkUI_Rect](_ark_u_i___rect.md) | Defines a mask area. | +| struct [ArkUI_IntSize](_ark_u_i___int_size.md) | Describes the width and height of a component. | +| struct [ArkUI_IntOffset](_ark_u_i___int_offset.md) | Describes the position of a component. | +| struct [ArkUI_Margin](_ark_u_i___margin.md) | Describes the margins of a component. | +| struct [ArkUI_TranslationOptions](_ark_u_i___translation_options.md) | Defines the translation options for component transition. | +| struct [ArkUI_ScaleOptions](_ark_u_i___scale_options.md) | Defines the scaling options for component transition. | +| struct [ArkUI_RotationOptions](_ark_u_i___rotation_options.md) | Defines the rotation options for component transition. | ### Macros -| Name| Description| +| Name| Description| | -------- | -------- | -| [OH_ArkUI_GetModuleInterface](#oh_arkui_getmoduleinterface)(nativeAPIVariantKind, structType, structPtr) | Obtains the macro function corresponding to a struct pointer based on the struct type. | -| **MAX_NODE_SCOPE_NUM** | 1000 | -| **MAX_COMPONENT_EVENT_ARG_NUM** | 12 | +| [OH_ArkUI_GetModuleInterface](#oh_arkui_getmoduleinterface)(nativeAPIVariantKind, structType, structPtr) | Obtains the macro function corresponding to a struct pointer based on the struct type. | +| **MAX_NODE_SCOPE_NUM** | 1000 | +| **MAX_COMPONENT_EVENT_ARG_NUM** | 12 | +| **UDMF_KEY_BUFFER_LEN** | 512 | ### Types -| Name| Description| +| Name| Description| | -------- | -------- | -| typedef struct [ArkUI_NodeEvent](#arkui_nodeevent-12) [ArkUI_NodeEvent](#arkui_nodeevent-12) | Defines a struct for a component event. | -| typedef struct [ArkUI_Context](#arkui_context) [ArkUI_Context](#arkui_context) | Defines a struct for a UI context object. | -| typedef struct [ArkUI_Context](#arkui_context) \* [ArkUI_ContextHandle](#arkui_contexthandle-12) | Defines a struct for the handle to the ArkUI native UI context. | -| typedef struct [ArkUI_DragEvent](#arkui_dragevent) [ArkUI_DragEvent](#arkui_dragevent) | Defines a struct for a drag event. | -| typedef struct [ArkUI_DragPreviewOption](#arkui_dragpreviewoption) [ArkUI_DragPreviewOption](#arkui_dragpreviewoption) | Defines a struct for custom drag preview options. | -| typedef struct [ArkUI_DragAction](#arkui_dragaction) [ArkUI_DragAction](#arkui_dragaction) | Defines a struct for a drag action. | -| typedef struct [ArkUI_DragAndDropInfo](#arkui_draganddropinfo) [ArkUI_DragAndDropInfo](#arkui_draganddropinfo) | Defines a struct for drag and drop information returned through a drag status listener. | -| typedef struct [OH_UdmfData](#oh_udmfdata) [OH_UdmfData](#oh_udmfdata) | Defines a struct for UDMF unified data. | -| typedef struct [OH_PixelmapNative](#oh_pixelmapnative) [OH_PixelmapNative](#oh_pixelmapnative) | Defines the **Pixelmap** struct, which is used to perform operations related to a pixel map. | -| typedef struct [ArkUI_DrawableDescriptor](#arkui_drawabledescriptor) [ArkUI_DrawableDescriptor](#arkui_drawabledescriptor) | Defines a struct for the **DrawableDescriptor** object. | -| typedef struct [OH_PixelmapNative](#oh_pixelmapnative) \* [OH_PixelmapNativeHandle](#oh_pixelmapnativehandle) | Defines a struct for the pointer to an **OH_PixelmapNative** object. | -| typedef struct [ArkUI_AnimateOption](#arkui_animateoption) [ArkUI_AnimateOption](#arkui_animateoption) | Defines a struct for the animation configuration. | -| typedef struct ArkUI_Curve \* [ArkUI_CurveHandle](#arkui_curvehandle) | Defines a struct for the pointer to an interpolation curve. | -| typedef struct [ArkUI_KeyframeAnimateOption](#arkui_keyframeanimateoption) [ArkUI_KeyframeAnimateOption](#arkui_keyframeanimateoption) | Defines a struct for the keyframe animation parameter object. | -| typedef struct [ArkUI_AnimatorOption](#arkui_animatoroption) [ArkUI_AnimatorOption](#arkui_animatoroption) | Defines the animator parameter object. | -| typedef struct ArkUI_Animator \* [ArkUI_AnimatorHandle](#arkui_animatorhandle) | Defines a struct for the pointer to an animator object. | -| typedef struct [ArkUI_TransitionEffect](#arkui_transitioneffect) [ArkUI_TransitionEffect](#arkui_transitioneffect) | Defines a struct for the transition effect. | -| typedef bool(\* [ArkUI_OnWillDismissEvent](#arkui_onwilldismissevent)) (int32_t reason) | Defines a pointer to the callback invoked when the dialog box is closed. | -| typedef struct [ArkUI_DialogDismissEvent](#arkui_dialogdismissevent) [ArkUI_DialogDismissEvent](#arkui_dialogdismissevent) | Defines a struct for a dialog box dismiss event. | -| typedef uint32_t [ArkUI_GestureEventActionTypeMask](#arkui_gestureeventactiontypemask) | Defines a set of gesture event types. | -| typedef uint32_t [ArkUI_GestureDirectionMask](#arkui_gesturedirectionmask) | Defines a set of gesture directions. | -| typedef ArkUI_GestureRecognizer \* [ArkUI_GestureRecognizerHandle](#arkui_gesturerecognizerhandle) | Defines the gesture recognizer handle. | -| typedef [ArkUI_GestureRecognizerHandle](#arkui_gesturerecognizerhandle) \* [ArkUI_GestureRecognizerHandleArray](#arkui_gesturerecognizerhandlearray) | Defines the gesture recognizer handle array. | -| typedef struct [ArkUI_GestureEventTargetInfo](#arkui_gestureeventtargetinfo) [ArkUI_GestureEventTargetInfo](#arkui_gestureeventtargetinfo) | Defines a struct for a **GestureEventTargetInfo** object that provides information about a gesture event target. | -| typedef struct [ArkUI_ParallelInnerGestureEvent](#arkui_parallelinnergestureevent) [ArkUI_ParallelInnerGestureEvent](#arkui_parallelinnergestureevent) | Defines a parallel internal gesture event. | -| typedef void(\* [ArkUI_GestureRecognizerDestructNotifyCallback](#arkui_gesturerecognizerdestructnotifycallback)) (ArkUI_GestureRecognizer \*recognizer, void \*userData) | Defines a callback function for notifying gesture recognizer destruction. | -| typedef struct [ArkUI_NodeEvent](#arkui_nodeevent-12) [ArkUI_NodeEvent](#arkui_nodeevent-12) | Defines the common structure of a component event. | -| typedef struct [ArkUI_NodeCustomEvent](#arkui_nodecustomevent) [ArkUI_NodeCustomEvent](#arkui_nodecustomevent) | Defines the common structure of a custom component event. | -| typedef struct ArkUI_NodeAdapter \* [ArkUI_NodeAdapterHandle](#arkui_nodeadapterhandle) | Defines the component adapter, which is used for lazy loading of elements of scrollable components. | -| typedef struct [ArkUI_NodeAdapterEvent](#arkui_nodeadapterevent) [ArkUI_NodeAdapterEvent](#arkui_nodeadapterevent) | Defines the component adapter event. | -| typedef struct [ArkUI_NodeContentEvent](#arkui_nodecontentevent) [ArkUI_NodeContentEvent](#arkui_nodecontentevent) | Defines the common structure type of a NodeContent event. | -| typedef void(\* [ArkUI_NodeContentCallback](#arkui_nodecontentcallback)) ([ArkUI_NodeContentEvent](#arkui_nodecontentevent) \*event) | Defines the callback for the NodeContent event. | -| typedef struct [ArkUI_LayoutConstraint](#arkui_layoutconstraint) [ArkUI_LayoutConstraint](#arkui_layoutconstraint) | Defines the size constraints of a component during component layout. | -| typedef struct [ArkUI_DrawContext](#arkui_drawcontext) [ArkUI_DrawContext](#arkui_drawcontext) | Defines the component drawing context. | -| typedef struct ArkUI_Node \* [ArkUI_NodeHandle](#arkui_nodehandle) | Defines the pointer to the ArkUI native component object. | -| typedef struct ArkUI_NativeDialog \* [ArkUI_NativeDialogHandle](#arkui_nativedialoghandle) | Defines the handle to the custom dialog box controller of ArkUI on the native side. | -| typedef struct [ArkUI_WaterFlowSectionOption](#arkui_waterflowsectionoption) [ArkUI_WaterFlowSectionOption](#arkui_waterflowsectionoption) | Defines the water flow section configuration. | -| typedef struct [ArkUI_ListItemSwipeActionItem](#arkui_listitemswipeactionitem) [ArkUI_ListItemSwipeActionItem](#arkui_listitemswipeactionitem) | Defines the item configuration for **ListItemSwipeActionOption**. | -| typedef struct [ArkUI_ListItemSwipeActionOption](#arkui_listitemswipeactionoption) [ArkUI_ListItemSwipeActionOption](#arkui_listitemswipeactionoption) | Defines the configuration for **ListItemSwipeActionOption**. | -| typedef struct [ArkUI_Context](#arkui_context) \* [ArkUI_ContextHandle](#arkui_contexthandle-12) | Defines the handle to the ArkUI native UI context. | -| typedef struct ArkUI_NodeContent \* [ArkUI_NodeContentHandle](#arkui_nodecontenthandle) | Defines the handle to the ArkUI NodeContent instance on the native side. | -| typedef struct [ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) [ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) | Defines the alignment rule in the relative container. | -| typedef struct [ArkUI_GuidelineOption](#arkui_guidelineoption) [ArkUI_GuidelineOption](#arkui_guidelineoption) | Defines the ID, direction, and position of a guideline. | -| typedef struct [ArkUI_BarrierOption](#arkui_barrieroption) [ArkUI_BarrierOption](#arkui_barrieroption) | Defines the ID, direction, and referenced component of a barrier. | -| typedef struct [ArkUI_ImageAnimatorFrameInfo](#arkui_imageanimatorframeinfo) [ArkUI_ImageAnimatorFrameInfo](#arkui_imageanimatorframeinfo) | Defines the image frame information. | -| typedef struct [ArkUI_ListChildrenMainSize](#arkui_listchildrenmainsize) [ArkUI_ListChildrenMainSize](#arkui_listchildrenmainsize) | Defines the **ChildrenMainSize** information of the **List** component. | -| typedef struct [ArkUI_AccessibilityState](#arkui_accessibilitystate) [ArkUI_AccessibilityState](#arkui_accessibilitystate) | Defines a struct for the component accessibility state. | -| typedef struct [ArkUI_AccessibilityValue](#arkui_accessibilityvalue) [ArkUI_AccessibilityValue](#arkui_accessibilityvalue) | Defines a struct for the component accessibility value. | -| typedef struct [ArkUI_SystemFontStyleEvent](#arkui_systemfontstyleevent) [ArkUI_SystemFontStyleEvent](#arkui_systemfontstyleevent) | Defines a struct for the system font style event. | -| typedef struct [ArkUI_CustomSpanMeasureInfo](#arkui_customspanmeasureinfo) [ArkUI_CustomSpanMeasureInfo](#arkui_customspanmeasureinfo) | Defines a struct for the measurement information of a custom span. | -| typedef struct [ArkUI_CustomSpanMetrics](#arkui_customspanmetrics) [ArkUI_CustomSpanMetrics](#arkui_customspanmetrics) | Defines a struct for the measurement metrics of a custom span. | -| typedef struct [ArkUI_CustomSpanDrawInfo](#arkui_customspandrawinfo) [ArkUI_CustomSpanDrawInfo](#arkui_customspandrawinfo) | Defines a struct for the drawing information of a custom span. | -| typedef struct [ArkUI_SwiperIndicator](#arkui_swiperindicator) [ArkUI_SwiperIndicator](#arkui_swiperindicator) | Defines the navigation point indicator style of the **Swiper** component. | -| typedef struct [ArkUI_StyledString_Descriptor](#arkui_styledstring_descriptor) [ArkUI_StyledString_Descriptor](#arkui_styledstring_descriptor) | Defines a struct for the styled string descriptor object supported by the text component. | -| typedef struct [ArkUI_StyledString](#arkui_styledstring) [ArkUI_StyledString](#arkui_styledstring) | Defines a struct for the styled string object supported by the text component. | +| typedef struct [ArkUI_NodeEvent](#arkui_nodeevent-12) [ArkUI_NodeEvent](#arkui_nodeevent-12) | Defines a struct for a component event. | +| typedef struct [ArkUI_Context](#arkui_context) [ArkUI_Context](#arkui_context) | Defines a struct for a UI context object. | +| typedef struct [ArkUI_Context](#arkui_context) \* [ArkUI_ContextHandle](#arkui_contexthandle-12) | Defines a struct for the handle to the ArkUI native UI context. | +| typedef struct [ArkUI_DragEvent](#arkui_dragevent) [ArkUI_DragEvent](#arkui_dragevent) | Defines a struct for a drag event. | +| typedef struct [ArkUI_DragPreviewOption](#arkui_dragpreviewoption) [ArkUI_DragPreviewOption](#arkui_dragpreviewoption) | Defines a struct for custom drag preview options. | +| typedef struct [ArkUI_DragAction](#arkui_dragaction) [ArkUI_DragAction](#arkui_dragaction) | Defines a struct for a drag action. | +| typedef struct [ArkUI_DragAndDropInfo](#arkui_draganddropinfo) [ArkUI_DragAndDropInfo](#arkui_draganddropinfo) | Defines a struct for drag and drop information returned through a drag status listener. | +| typedef struct [OH_UdmfData](#oh_udmfdata) [OH_UdmfData](#oh_udmfdata) | Defines a struct for UDMF unified data. | +| typedef struct [OH_PixelmapNative](#oh_pixelmapnative) [OH_PixelmapNative](#oh_pixelmapnative) | Defines the **Pixelmap** struct, which is used to perform operations related to a pixel map. | +| typedef struct [ArkUI_DrawableDescriptor](#arkui_drawabledescriptor) [ArkUI_DrawableDescriptor](#arkui_drawabledescriptor) | Defines a struct for the **DrawableDescriptor** object. | +| typedef struct [OH_PixelmapNative](#oh_pixelmapnative) \* [OH_PixelmapNativeHandle](#oh_pixelmapnativehandle) | Defines a struct for the pointer to an **OH_PixelmapNative** object. | +| typedef struct [ArkUI_AnimateOption](#arkui_animateoption) [ArkUI_AnimateOption](#arkui_animateoption) | Defines a struct for the animation configuration. | +| typedef struct ArkUI_Curve \* [ArkUI_CurveHandle](#arkui_curvehandle) | Defines a struct for the pointer to an interpolation curve. | +| typedef struct [ArkUI_KeyframeAnimateOption](#arkui_keyframeanimateoption) [ArkUI_KeyframeAnimateOption](#arkui_keyframeanimateoption) | Defines a struct for the keyframe animation parameter object. | +| typedef struct [ArkUI_AnimatorOption](#arkui_animatoroption) [ArkUI_AnimatorOption](#arkui_animatoroption) | Defines the animator parameter object. | +| typedef struct ArkUI_Animator \* [ArkUI_AnimatorHandle](#arkui_animatorhandle) | Defines a struct for the pointer to an animator object. | +| typedef struct [ArkUI_TransitionEffect](#arkui_transitioneffect) [ArkUI_TransitionEffect](#arkui_transitioneffect) | Defines a struct for the transition effect. | +| typedef bool(\* [ArkUI_OnWillDismissEvent](#arkui_onwilldismissevent)) (int32_t reason) | Defines a pointer to the callback invoked when the dialog box is closed. | +| typedef struct [ArkUI_DialogDismissEvent](#arkui_dialogdismissevent) [ArkUI_DialogDismissEvent](#arkui_dialogdismissevent) | Defines a struct for a dialog box dismiss event. | +| typedef struct [ArkUI_CustomDialogOptions ](#arkui_customdialogoptions) [ArkUI_CustomDialogOptions ](#arkui_customdialogoptions) | Defines a struct for custom dialog box options. | +| typedef uint32_t [ArkUI_GestureEventActionTypeMask](#arkui_gestureeventactiontypemask) | Defines a set of gesture event types. | +| typedef uint32_t [ArkUI_GestureDirectionMask](#arkui_gesturedirectionmask) | Defines a set of gesture directions. | +| typedef ArkUI_GestureRecognizer \* [ArkUI_GestureRecognizerHandle](#arkui_gesturerecognizerhandle) | Defines the gesture recognizer handle. | +| typedef [ArkUI_GestureRecognizerHandle](#arkui_gesturerecognizerhandle) \* [ArkUI_GestureRecognizerHandleArray](#arkui_gesturerecognizerhandlearray) | Defines the gesture recognizer handle array. | +| typedef ArkUI_TouchRecognizer \* [ArkUI_TouchRecognizerHandle](#arkui_touchrecognizerhandle) | Defines a gesture recognizer handle. | +| typedef [ArkUI_TouchRecognizerHandle](#arkui_touchrecognizerhandle) \* [ArkUI_TouchRecognizerHandleArray](#arkui_touchrecognizerhandlearray) | Defines an array of gesture recognizer handles. | +| typedef struct [ArkUI_GestureEventTargetInfo](#arkui_gestureeventtargetinfo) [ArkUI_GestureEventTargetInfo](#arkui_gestureeventtargetinfo) | Defines a struct for a **GestureEventTargetInfo** object that provides information about a gesture event target. | +| typedef struct [ArkUI_ParallelInnerGestureEvent](#arkui_parallelinnergestureevent) [ArkUI_ParallelInnerGestureEvent](#arkui_parallelinnergestureevent) | Defines a parallel internal gesture event. | +| typedef void(\* [ArkUI_GestureRecognizerDestructNotifyCallback](#arkui_gesturerecognizerdestructnotifycallback)) (ArkUI_GestureRecognizer \*recognizer, void \*userData) | Defines a callback function for notifying gesture recognizer destruction. | +| typedef struct [ArkUI_NodeEvent](#arkui_nodeevent-12) [ArkUI_NodeEvent](#arkui_nodeevent-12) | Defines the common structure of a component event. | +| typedef struct [ArkUI_NodeCustomEvent](#arkui_nodecustomevent) [ArkUI_NodeCustomEvent](#arkui_nodecustomevent) | Defines the common structure of a custom component event. | +| typedef struct ArkUI_NodeAdapter \* [ArkUI_NodeAdapterHandle](#arkui_nodeadapterhandle) | Defines the component adapter, which is used for lazy loading of elements of scrollable components. | +| typedef struct [ArkUI_NodeAdapterEvent](#arkui_nodeadapterevent) [ArkUI_NodeAdapterEvent](#arkui_nodeadapterevent) | Defines the component adapter event. | +| typedef struct [ArkUI_NodeContentEvent](#arkui_nodecontentevent) [ArkUI_NodeContentEvent](#arkui_nodecontentevent) | Defines the common structure type of a NodeContent event. | +| typedef void(\* [ArkUI_NodeContentCallback](#arkui_nodecontentcallback)) ([ArkUI_NodeContentEvent](#arkui_nodecontentevent) \*event) | Defines the callback for the NodeContent event. | +| typedef struct [ArkUI_LayoutConstraint](#arkui_layoutconstraint) [ArkUI_LayoutConstraint](#arkui_layoutconstraint) | Defines the size constraints of a component during component layout. | +| typedef struct [ArkUI_DrawContext](#arkui_drawcontext) [ArkUI_DrawContext](#arkui_drawcontext) | Defines the component drawing context. | +| typedef struct ArkUI_Node \* [ArkUI_NodeHandle](#arkui_nodehandle) | Defines the pointer to the ArkUI native component object. | +| typedef struct ArkUI_NativeDialog \* [ArkUI_NativeDialogHandle](#arkui_nativedialoghandle) | Defines the handle to the custom dialog box controller of ArkUI on the native side. | +| typedef struct [ArkUI_WaterFlowSectionOption](#arkui_waterflowsectionoption) [ArkUI_WaterFlowSectionOption](#arkui_waterflowsectionoption) | Defines the water flow section configuration. | +| typedef struct [ArkUI_ListItemSwipeActionItem](#arkui_listitemswipeactionitem) [ArkUI_ListItemSwipeActionItem](#arkui_listitemswipeactionitem) | Defines the item configuration for **ListItemSwipeActionOption**. | +| typedef struct [ArkUI_ListItemSwipeActionOption](#arkui_listitemswipeactionoption) [ArkUI_ListItemSwipeActionOption](#arkui_listitemswipeactionoption) | Defines the configuration for **ListItemSwipeActionOption**. | +| typedef struct [ArkUI_Context](#arkui_context) \* [ArkUI_ContextHandle](#arkui_contexthandle-12) | Defines the handle to the ArkUI native UI context. | +| typedef struct ArkUI_NodeContent \* [ArkUI_NodeContentHandle](#arkui_nodecontenthandle) | Defines the handle to the ArkUI NodeContent instance on the native side. | +| typedef struct [ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) [ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) | Defines the alignment rule in the relative container. | +| typedef struct [ArkUI_GuidelineOption](#arkui_guidelineoption) [ArkUI_GuidelineOption](#arkui_guidelineoption) | Defines the ID, direction, and position of a guideline. | +| typedef struct [ArkUI_BarrierOption](#arkui_barrieroption) [ArkUI_BarrierOption](#arkui_barrieroption) | Defines the ID, direction, and referenced component of a barrier. | +| typedef struct [ArkUI_ImageAnimatorFrameInfo](#arkui_imageanimatorframeinfo) [ArkUI_ImageAnimatorFrameInfo](#arkui_imageanimatorframeinfo) | Defines the image frame information. | +| typedef struct [ArkUI_ListChildrenMainSize](#arkui_listchildrenmainsize) [ArkUI_ListChildrenMainSize](#arkui_listchildrenmainsize) | Defines the **ChildrenMainSize** information of the **List** component. | +| typedef struct [ArkUI_AccessibilityState](#arkui_accessibilitystate) [ArkUI_AccessibilityState](#arkui_accessibilitystate) | Defines a struct for the component accessibility state. | +| typedef struct [ArkUI_AccessibilityValue](#arkui_accessibilityvalue) [ArkUI_AccessibilityValue](#arkui_accessibilityvalue) | Defines a struct for the component accessibility value. | +| typedef struct [ArkUI_SystemFontStyleEvent](#arkui_systemfontstyleevent) [ArkUI_SystemFontStyleEvent](#arkui_systemfontstyleevent) | Defines a struct for the system font style event. | +| typedef struct [ArkUI_CustomSpanMeasureInfo](#arkui_customspanmeasureinfo) [ArkUI_CustomSpanMeasureInfo](#arkui_customspanmeasureinfo) | Defines a struct for the measurement information of a custom span. | +| typedef struct [ArkUI_CustomSpanMetrics](#arkui_customspanmetrics) [ArkUI_CustomSpanMetrics](#arkui_customspanmetrics) | Defines a struct for the measurement metrics of a custom span. | +| typedef struct [ArkUI_CustomSpanDrawInfo](#arkui_customspandrawinfo) [ArkUI_CustomSpanDrawInfo](#arkui_customspandrawinfo) | Defines a struct for the drawing information of a custom span. | +| typedef struct [ArkUI_SwiperIndicator](#arkui_swiperindicator) [ArkUI_SwiperIndicator](#arkui_swiperindicator) | Defines the navigation indicator style of the **Swiper** component. | +| typedef struct [ArkUI_StyledString_Descriptor](#arkui_styledstring_descriptor) [ArkUI_StyledString_Descriptor](#arkui_styledstring_descriptor) | Defines a struct for the styled string descriptor object supported by the text component. | +| typedef struct [ArkUI_StyledString](#arkui_styledstring) [ArkUI_StyledString](#arkui_styledstring) | Defines a struct for the styled string object supported by the text component. | +| typedef struct [OH_UdmfGetDataParams](#oh_udmfgetdataparams) [OH_UdmfGetDataParams](#oh_udmfgetdataparams) | Defines a struct for parameters used for obtaining data from UDMF. | +| typedef struct [ArkUI_ProgressLinearStyleOption](#arkui_progresslinearstyleoption) [ArkUI_ProgressLinearStyleOption](#arkui_progresslinearstyleoption) | Defines the style object for a linear progress indicator.| +| typedef struct [ArkUI_VisibleAreaEventOptions](#arkui_visibleareaeventoptions) [ArkUI_VisibleAreaEventOptions](#arkui_visibleareaeventoptions) | Defines a struct for visible area change event parameters. | ### Enums -| Name| Description| +| Name| Description| | -------- | -------- | -| [ArkUI_DragResult](#arkui_dragresult) { ARKUI_DRAG_RESULT_SUCCESSFUL, ARKUI_DRAG_RESULT_FAILED, ARKUI_DRAG_RESULT_CANCELED } | Defines an enum for drag results, which are set by the data receiver and transferred by the system to the drag source so that the drag source is aware of the data processing result of the receiver. | -| [ArkUI_DropProposal](#arkui_dropproposal) { ARKUI_DROP_PROPOSAL_COPY, ARKUI_DROP_PROPOSAL_MOVE } | Defines an enum for data processing modes used when data is dropped, which affects the display of the badge. | -| [ArkUI_PreDragStatus](#arkui_predragstatus) {
ARKUI_PRE_DRAG_STATUS_UNKNOWN = -1, ARKUI_PRE_DRAG_STATUS_ACTION_DETECTING, ARKUI_PRE_DRAG_STATUS_READY_TO_TRIGGER_DRAG, ARKUI_PRE_DRAG_STATUS_PREVIEW_LIFT_STARTED,
ARKUI_PRE_DRAG_STATUS_PREVIEW_LIFT_FINISHED, ARKUI_PRE_DRAG_STATUS_PREVIEW_LANDING_STARTED, ARKUI_PRE_DRAG_STATUS_PREVIEW_LANDING_FINISHED, ARKUI_PRE_DRAG_STATUS_CANCELED_BEFORE_DRAG
} | Defines an enum for interaction states prior to a drop and drop operation. | -| [ArkUI_DragPreviewScaleMode](#arkui_dragpreviewscalemode) { ARKUI_DRAG_PREVIEW_SCALE_AUTO, ARKUI_DRAG_PREVIEW_SCALE_DISABLED } | Defines an enum for drag preview scale modes. | -| [ArkUI_DragStatus](#arkui_dragstatus) { ArkUI_DRAG_STATUS_UNKNOWN, ArkUI_DRAG_STATUS_STARTED, ArkUI_DRAG_STATUS_ENDED } | Enumerates dragging states. | -| [ArkUI_DismissReason](#arkui_dismissreason) { DIALOG_DISMISS_BACK_PRESS = 0, DIALOG_DISMISS_TOUCH_OUTSIDE, DIALOG_DISMISS_CLOSE_BUTTON, DIALOG_DISMISS_SLIDE_DOWN } | Enumerates the actions for triggering closure of the dialog box. | -| [ArkUI_GestureEventActionType](#arkui_gestureeventactiontype) { GESTURE_EVENT_ACTION_ACCEPT = 0x01, GESTURE_EVENT_ACTION_UPDATE = 0x02, GESTURE_EVENT_ACTION_END = 0x04, GESTURE_EVENT_ACTION_CANCEL = 0x08 } | Enumerates gesture event types. | -| [ArkUI_GesturePriority](#arkui_gesturepriority) { NORMAL = 0, PRIORITY = 1, PARALLEL = 2 } | Enumerates gesture event modes. | -| [ArkUI_GroupGestureMode](#arkui_groupgesturemode) { SEQUENTIAL_GROUP = 0, PARALLEL_GROUP = 1, EXCLUSIVE_GROUP = 2 } | Enumerates gesture group modes. | -| [ArkUI_GestureDirection](#arkui_gesturedirection) {
GESTURE_DIRECTION_ALL = 0b1111, GESTURE_DIRECTION_HORIZONTAL = 0b0011, GESTURE_DIRECTION_VERTICAL = 0b1100, GESTURE_DIRECTION_LEFT = 0b0001,
GESTURE_DIRECTION_RIGHT = 0b0010, GESTURE_DIRECTION_UP = 0b0100, GESTURE_DIRECTION_DOWN = 0b1000, GESTURE_DIRECTION_NONE = 0
} | Enumerates gesture directions. | -| [ArkUI_GestureMask](#arkui_gesturemask) { NORMAL_GESTURE_MASK = 0, IGNORE_INTERNAL_GESTURE_MASK } | Enumerates gesture masking modes. | -| [ArkUI_GestureRecognizerType](#arkui_gesturerecognizertype) {
TAP_GESTURE = 0, LONG_PRESS_GESTURE, PAN_GESTURE, PINCH_GESTURE,
ROTATION_GESTURE, SWIPE_GESTURE, GROUP_GESTURE
} | Enumerates gesture recognizer types. | -| [ArkUI_GestureInterruptResult](#arkui_gestureinterruptresult) { GESTURE_INTERRUPT_RESULT_CONTINUE = 0, GESTURE_INTERRUPT_RESULT_REJECT } | Enumerates gesture interruption results. | -| [ArkUI_GestureRecognizerState](#arkui_gesturerecognizerstate) {
ARKUI_GESTURE_RECOGNIZER_STATE_REDAY = 0, ARKUI_GESTURE_RECOGNIZER_STATE_DETECTING = 1, ARKUI_GESTURE_RECOGNIZER_STATE_PENDING = 2, ARKUI_GESTURE_RECOGNIZER_STATE_BLOCKED = 3,
ARKUI_GESTURE_RECOGNIZER_STATE_SUCCESSFUL = 4, ARKUI_GESTURE_RECOGNIZER_STATE_FAILED = 5
} | Enumerates the gesture recognizer states. | -| [ArkUI_NativeAPIVariantKind](#arkui_nativeapivariantkind) { ARKUI_NATIVE_NODE, ARKUI_NATIVE_DIALOG, ARKUI_NATIVE_GESTURE, ARKUI_NATIVE_ANIMATE } | Defines the native API types. | +| [ArkUI_DragResult](#arkui_dragresult) { ARKUI_DRAG_RESULT_SUCCESSFUL = 0, ARKUI_DRAG_RESULT_FAILED, ARKUI_DRAG_RESULT_CANCELED } | Defines an enum for drag results, which are set by the data receiver and transferred by the system to the drag source so that the drag source is aware of the data processing result of the receiver. | +| [ArkUI_DropOperation](#arkui_dropoperation) { ARKUI_DROP_OPERATION_COPY = 0, ARKUI_DROP_OPERATION_MOVE } | Defines an enum for data processing modes used when data is dropped, which affects the display of the badge. | +| [ArkUI_PreDragStatus](#arkui_predragstatus) {
ARKUI_PRE_DRAG_STATUS_UNKNOWN = -1, ARKUI_PRE_DRAG_STATUS_ACTION_DETECTING, ARKUI_PRE_DRAG_STATUS_READY_TO_TRIGGER_DRAG, ARKUI_PRE_DRAG_STATUS_PREVIEW_LIFT_STARTED,
ARKUI_PRE_DRAG_STATUS_PREVIEW_LIFT_FINISHED, ARKUI_PRE_DRAG_STATUS_PREVIEW_LANDING_STARTED, ARKUI_PRE_DRAG_STATUS_PREVIEW_LANDING_FINISHED, ARKUI_PRE_DRAG_STATUS_CANCELED_BEFORE_DRAG
} | Defines an enum for interaction states prior to a drop and drop operation. | +| [ArkUI_DragPreviewScaleMode](#arkui_dragpreviewscalemode) { ARKUI_DRAG_PREVIEW_SCALE_AUTO = 0, ARKUI_DRAG_PREVIEW_SCALE_DISABLED } | Defines an enum for drag preview scale modes. | +| [ArkUI_DragStatus](#arkui_dragstatus) { ARKUI_DRAG_STATUS_UNKNOWN = -1, ARKUI_DRAG_STATUS_STARTED, ARKUI_DRAG_STATUS_ENDED } | Enumerates dragging states. | +| [ArkUI_DismissReason](#arkui_dismissreason) { DIALOG_DISMISS_BACK_PRESS = 0, DIALOG_DISMISS_TOUCH_OUTSIDE, DIALOG_DISMISS_CLOSE_BUTTON, DIALOG_DISMISS_SLIDE_DOWN } | Enumerates the actions for triggering closure of the dialog box. | +| [ArkUI_LevelMode](#arkui_levelmode) { ARKUI_LEVEL_MODE_OVERLAY = 0, ARKUI_LEVEL_MODE_EMBEDDED } | Enumerates the display levels of the dialog box. | +| [ArkUI_ImmersiveMode](#arkui_immersivemode) { ARKUI_IMMERSIVE_MODE_DEFAULT = 0, ARKUI_IMMERSIVE_MODE_EXTEND } | Enumerates the display areas of the embedded dialog box overlay. | +| [ArkUI_GestureEventActionType](#arkui_gestureeventactiontype) { GESTURE_EVENT_ACTION_ACCEPT = 0x01, GESTURE_EVENT_ACTION_UPDATE = 0x02, GESTURE_EVENT_ACTION_END = 0x04, GESTURE_EVENT_ACTION_CANCEL = 0x08 } | Enumerates gesture event types. | +| [ArkUI_GesturePriority](#arkui_gesturepriority) { NORMAL = 0, PRIORITY = 1, PARALLEL = 2 } | Enumerates gesture event modes. | +| [ArkUI_GroupGestureMode](#arkui_groupgesturemode) { SEQUENTIAL_GROUP = 0, PARALLEL_GROUP = 1, EXCLUSIVE_GROUP = 2 } | Enumerates gesture group modes. | +| [ArkUI_GestureDirection](#arkui_gesturedirection) {
GESTURE_DIRECTION_ALL = 0b1111, GESTURE_DIRECTION_HORIZONTAL = 0b0011, GESTURE_DIRECTION_VERTICAL = 0b1100, GESTURE_DIRECTION_LEFT = 0b0001,
GESTURE_DIRECTION_RIGHT = 0b0010, GESTURE_DIRECTION_UP = 0b0100, GESTURE_DIRECTION_DOWN = 0b1000, GESTURE_DIRECTION_NONE = 0
} | Enumerates gesture directions. | +| [ArkUI_GestureMask](#arkui_gesturemask) { NORMAL_GESTURE_MASK = 0, IGNORE_INTERNAL_GESTURE_MASK } | Enumerates gesture masking modes. | +| [ArkUI_GestureRecognizerType](#arkui_gesturerecognizertype) {
TAP_GESTURE = 0, LONG_PRESS_GESTURE, PAN_GESTURE, PINCH_GESTURE,
ROTATION_GESTURE, SWIPE_GESTURE, GROUP_GESTURE
} | Enumerates gesture recognizer types. | +| [ArkUI_GestureInterruptResult](#arkui_gestureinterruptresult) { GESTURE_INTERRUPT_RESULT_CONTINUE = 0, GESTURE_INTERRUPT_RESULT_REJECT } | Enumerates gesture interruption results. | +| [ArkUI_GestureRecognizerState](#arkui_gesturerecognizerstate) {
ARKUI_GESTURE_RECOGNIZER_STATE_REDAY = 0, ARKUI_GESTURE_RECOGNIZER_STATE_DETECTING = 1, ARKUI_GESTURE_RECOGNIZER_STATE_PENDING = 2, ARKUI_GESTURE_RECOGNIZER_STATE_BLOCKED = 3,
ARKUI_GESTURE_RECOGNIZER_STATE_SUCCESSFUL = 4, ARKUI_GESTURE_RECOGNIZER_STATE_FAILED = 5
} | Enumerates the gesture recognizer states. | +| [ArkUI_NativeAPIVariantKind](#arkui_nativeapivariantkind) { ARKUI_NATIVE_NODE, ARKUI_NATIVE_DIALOG, ARKUI_NATIVE_GESTURE, ARKUI_NATIVE_ANIMATE } | Defines the native API types. | | [ArkUI_KeyCode](#arkui_keycode) {
ARKUI_KEYCODE_UNKNOWN = -1, ARKUI_KEYCODE_FN = 0, ARKUI_KEYCODE_VOLUME_UP = 16, ARKUI_KEYCODE_VOLUME_DOWN = 17,
ARKUI_KEYCODE_POWER = 18, ARKUI_KEYCODE_CAMERA = 19, ARKUI_KEYCODE_VOLUME_MUTE = 22, ARKUI_KEYCODE_MUTE = 23,
ARKUI_KEYCODE_BRIGHTNESS_UP = 40, ARKUI_KEYCODE_BRIGHTNESS_DOWN = 41, ARKUI_KEYCODE_0 = 2000, ARKUI_KEYCODE_1 = 2001,
ARKUI_KEYCODE_2 = 2002, ARKUI_KEYCODE_3 = 2003, ARKUI_KEYCODE_4 = 2004, ARKUI_KEYCODE_5 = 2005,
ARKUI_KEYCODE_6 = 2006, ARKUI_KEYCODE_7 = 2007, ARKUI_KEYCODE_8 = 2008, ARKUI_KEYCODE_9 = 2009,
ARKUI_KEYCODE_STAR = 2010, ARKUI_KEYCODE_POUND = 2011, ARKUI_KEYCODE_DPAD_UP = 2012, ARKUI_KEYCODE_DPAD_DOWN = 2013,
ARKUI_KEYCODE_DPAD_LEFT = 2014, ARKUI_KEYCODE_DPAD_RIGHT = 2015, ARKUI_KEYCODE_DPAD_CENTER = 2016, ARKUI_KEYCODE_A = 2017,
ARKUI_KEYCODE_B = 2018, ARKUI_KEYCODE_C = 2019, ARKUI_KEYCODE_D = 2020, ARKUI_KEYCODE_E = 2021,
ARKUI_KEYCODE_F = 2022, ARKUI_KEYCODE_G = 2023, ARKUI_KEYCODE_H = 2024, ARKUI_KEYCODE_I = 2025,
ARKUI_KEYCODE_J = 2026, ARKUI_KEYCODE_K = 2027, ARKUI_KEYCODE_L = 2028, ARKUI_KEYCODE_M = 2029,
ARKUI_KEYCODE_N = 2030, ARKUI_KEYCODE_O = 2031, ARKUI_KEYCODE_P = 2032, ARKUI_KEYCODE_Q = 2033,
ARKUI_KEYCODE_R = 2034, ARKUI_KEYCODE_S = 2035, ARKUI_KEYCODE_T = 2036, ARKUI_KEYCODE_U = 2037,
ARKUI_KEYCODE_V = 2038, ARKUI_KEYCODE_W = 2039, ARKUI_KEYCODE_X = 2040, ARKUI_KEYCODE_Y = 2041,
ARKUI_KEYCODE_Z = 2042, ARKUI_KEYCODE_COMMA = 2043, ARKUI_KEYCODE_PERIOD = 2044, ARKUI_KEYCODE_ALT_LEFT = 2045,
ARKUI_KEYCODE_ALT_RIGHT = 2046, ARKUI_KEYCODE_SHIFT_LEFT = 2047, ARKUI_KEYCODE_SHIFT_RIGHT = 2048, ARKUI_KEYCODE_TAB = 2049,
ARKUI_KEYCODE_SPACE = 2050, ARKUI_KEYCODE_SYM = 2051, ARKUI_KEYCODE_EXPLORER = 2052, ARKUI_KEYCODE_ENVELOPE = 2053,
ARKUI_KEYCODE_ENTER = 2054, ARKUI_KEYCODE_DEL = 2055, ARKUI_KEYCODE_GRAVE = 2056, ARKUI_KEYCODE_MINUS = 2057,
ARKUI_KEYCODE_EQUALS = 2058, ARKUI_KEYCODE_LEFT_BRACKET = 2059, ARKUI_KEYCODE_RIGHT_BRACKET = 2060, ARKUI_KEYCODE_BACKSLASH = 2061,
ARKUI_KEYCODE_SEMICOLON = 2062, ARKUI_KEYCODE_APOSTROPHE = 2063, ARKUI_KEYCODE_SLASH = 2064, ARKUI_KEYCODE_AT = 2065,
ARKUI_KEYCODE_PLUS = 2066, ARKUI_KEYCODE_MENU = 2067, ARKUI_KEYCODE_PAGE_UP = 2068, ARKUI_KEYCODE_PAGE_DOWN = 2069,
ARKUI_KEYCODE_ESCAPE = 2070, ARKUI_KEYCODE_FORWARD_DEL = 2071, ARKUI_KEYCODE_CTRL_LEFT = 2072, ARKUI_KEYCODE_CTRL_RIGHT = 2073,
ARKUI_KEYCODE_CAPS_LOCK = 2074, ARKUI_KEYCODE_SCROLL_LOCK = 2075, ARKUI_KEYCODE_META_LEFT = 2076, ARKUI_KEYCODE_META_RIGHT = 2077,
ARKUI_KEYCODE_FUNCTION = 2078, ARKUI_KEYCODE_SYSRQ = 2079, ARKUI_KEYCODE_BREAK = 2080, ARKUI_KEYCODE_MOVE_HOME = 2081,
ARKUI_KEYCODE_MOVE_END = 2082, ARKUI_KEYCODE_INSERT = 2083, ARKUI_KEYCODE_FORWARD = 2084, ARKUI_KEYCODE_MEDIA_PLAY = 2085,
ARKUI_KEYCODE_MEDIA_PAUSE = 2086, ARKUI_KEYCODE_MEDIA_CLOSE = 2087, ARKUI_KEYCODE_MEDIA_EJECT = 2088, ARKUI_KEYCODE_MEDIA_RECORD = 2089,
ARKUI_KEYCODE_F1 = 2090, ARKUI_KEYCODE_F2 = 2091, ARKUI_KEYCODE_F3 = 2092, ARKUI_KEYCODE_F4 = 2093,
ARKUI_KEYCODE_F5 = 2094, ARKUI_KEYCODE_F6 = 2095, ARKUI_KEYCODE_F7 = 2096, ARKUI_KEYCODE_F8 = 2097,
ARKUI_KEYCODE_F9 = 2098, ARKUI_KEYCODE_F10 = 2099, ARKUI_KEYCODE_F11 = 2100, ARKUI_KEYCODE_F12 = 2101,
ARKUI_KEYCODE_NUM_LOCK = 2102, ARKUI_KEYCODE_NUMPAD_0 = 2103, ARKUI_KEYCODE_NUMPAD_1 = 2104, ARKUI_KEYCODE_NUMPAD_2 = 2105,
ARKUI_KEYCODE_NUMPAD_3 = 2106, ARKUI_KEYCODE_NUMPAD_4 = 2107, ARKUI_KEYCODE_NUMPAD_5 = 2108, ARKUI_KEYCODE_NUMPAD_6 = 2109,
ARKUI_KEYCODE_NUMPAD_7 = 2110, ARKUI_KEYCODE_NUMPAD_8 = 2111, ARKUI_KEYCODE_NUMPAD_9 = 2112, ARKUI_KEYCODE_NUMPAD_DIVIDE = 2113,
ARKUI_KEYCODE_NUMPAD_MULTIPLY = 2114, ARKUI_KEYCODE_NUMPAD_SUBTRACT = 2115, ARKUI_KEYCODE_NUMPAD_ADD = 2116, ARKUI_KEYCODE_NUMPAD_DOT = 2117,
ARKUI_KEYCODE_NUMPAD_COMMA = 2118, ARKUI_KEYCODE_NUMPAD_ENTER = 2119, ARKUI_KEYCODE_NUMPAD_EQUALS = 2120, ARKUI_KEYCODE_NUMPAD_LEFT_PAREN = 2121,
ARKUI_KEYCODE_NUMPAD_RIGHT_PAREN = 2122
} | Enumerates the key codes for key events. | | [ArkUI_KeyEventType](#arkui_keyeventtype) {
ARKUI_KEY_EVENT_UNKNOWN = -1, ARKUI_KEY_EVENT_DOWN = 0, ARKUI_KEY_EVENT_UP = 1, ARKUI_KEY_EVENT_LONG_PRESS = 2,
ARKUI_KEY_EVENT_CLICK = 3
} | Enumerates the types of key events. | | [ArkUI_KeySourceType](#arkui_keysourcetype) { ARKUI_KEY_SOURCE_UNKNOWN = 0, ARKUI_KEY_SOURCE_TYPE_MOUSE = 1, ARKUI_KEY_SOURCE_TYPE_KEYBOARD = 4, ARKUI_KEY_SOURCE_TYPE_JOYSTICK = 5 } | Enumerates the types of input devices that trigger key events. | | [ArkUI_KeyIntension](#arkui_keyintension) {
ARKUI_KEY_INTENSION_UNKNOWN = -1, ARKUI_KEY_INTENSION_UP = 1, ARKUI_KEY_INTENSION_DOWN = 2, ARKUI_KEY_INTENSION_LEFT = 3,
ARKUI_KEY_INTENSION_RIGHT = 4, ARKUI_KEY_INTENSION_SELECT = 5, ARKUI_KEY_INTENSION_ESCAPE = 6, ARKUI_KEY_INTENSION_BACK = 7,
ARKUI_KEY_INTENSION_FORWARD = 8, ARKUI_KEY_INTENSION_MENU = 9, ARKUI_KEY_INTENSION_HOME = 10, ARKUI_KEY_INTENSION_PAGE_UP = 11,
ARKUI_KEY_INTENSION_PAGE_DOWN = 12, ARKUI_KEY_INTENSION_ZOOM_OUT = 13, ARKUI_KEY_INTENSION_ZOOM_IN = 14, ARKUI_KEY_INTENTION_MEDIA_PLAY_PAUSE = 100,
ARKUI_KEY_INTENTION_MEDIA_FAST_FORWARD = 101, ARKUI_KEY_INTENTION_MEDIA_FAST_PLAYBACK = 103, ARKUI_KEY_INTENTION_MEDIA_NEXT = 104, ARKUI_KEY_INTENTION_MEDIA_PREVIOUS = 105,
ARKUI_KEY_INTENTION_MEDIA_MUTE = 106, ARKUI_KEY_INTENTION_VOLUME_UP = 107, ARKUI_KEY_INTENTION_VOLUME_DOWN = 108, ARKUI_KEY_INTENTION_CALL = 200,
ARKUI_KEY_INTENTION_CAMERA = 300
} | Enumerates the intentions corresponding to key events. | | [ArkUI_NodeType](#arkui_nodetype) {
ARKUI_NODE_CUSTOM = 0, ARKUI_NODE_TEXT = 1, ARKUI_NODE_SPAN = 2, ARKUI_NODE_IMAGE_SPAN = 3,
ARKUI_NODE_IMAGE = 4, ARKUI_NODE_TOGGLE = 5, ARKUI_NODE_LOADING_PROGRESS = 6, ARKUI_NODE_TEXT_INPUT = 7,
ARKUI_NODE_TEXT_AREA = 8, ARKUI_NODE_BUTTON = 9, ARKUI_NODE_PROGRESS = 10, ARKUI_NODE_CHECKBOX = 11,
ARKUI_NODE_XCOMPONENT = 12, ARKUI_NODE_DATE_PICKER = 13, ARKUI_NODE_TIME_PICKER = 14, ARKUI_NODE_TEXT_PICKER = 15,
ARKUI_NODE_CALENDAR_PICKER = 16, ARKUI_NODE_SLIDER = 17, ARKUI_NODE_RADIO = 18, ARKUI_NODE_IMAGE_ANIMATOR = 19,
ARKUI_NODE_XCOMPONENT_TEXTURE = 20,
ARKUI_NODE_CHECKBOX_GROUP = 21,
ARKUI_NODE_STACK = MAX_NODE_SCOPE_NUM, ARKUI_NODE_SWIPER, ARKUI_NODE_SCROLL,
ARKUI_NODE_LIST, ARKUI_NODE_LIST_ITEM, ARKUI_NODE_LIST_ITEM_GROUP, ARKUI_NODE_COLUMN,
ARKUI_NODE_ROW, ARKUI_NODE_FLEX, ARKUI_NODE_REFRESH, ARKUI_NODE_WATER_FLOW,
ARKUI_NODE_FLOW_ITEM, ARKUI_NODE_RELATIVE_CONTAINER, ARKUI_NODE_GRID, ARKUI_NODE_GRID_ITEM,
ARKUI_NODE_CUSTOM_SPAN
} | Enumerates ArkUI component types that can be created on the native side. | -| [ArkUI_NodeAttributeType](#arkui_nodeattributetype) {
NODE_WIDTH = 0, NODE_HEIGHT, NODE_BACKGROUND_COLOR, NODE_BACKGROUND_IMAGE,
NODE_PADDING, NODE_ID, NODE_ENABLED, NODE_MARGIN,
NODE_TRANSLATE, NODE_SCALE, NODE_ROTATE, NODE_BRIGHTNESS,
NODE_SATURATION, NODE_BLUR, NODE_LINEAR_GRADIENT, NODE_ALIGNMENT,
NODE_OPACITY, NODE_BORDER_WIDTH, NODE_BORDER_RADIUS, NODE_BORDER_COLOR,
NODE_BORDER_STYLE, NODE_Z_INDEX, NODE_VISIBILITY, NODE_CLIP,
NODE_CLIP_SHAPE, NODE_TRANSFORM, NODE_HIT_TEST_BEHAVIOR, NODE_POSITION,
NODE_SHADOW, NODE_CUSTOM_SHADOW, NODE_BACKGROUND_IMAGE_SIZE, NODE_BACKGROUND_IMAGE_SIZE_WITH_STYLE,
NODE_BACKGROUND_BLUR_STYLE, NODE_TRANSFORM_CENTER, NODE_OPACITY_TRANSITION, NODE_ROTATE_TRANSITION,
NODE_SCALE_TRANSITION, NODE_TRANSLATE_TRANSITION, NODE_MOVE_TRANSITION, NODE_FOCUSABLE,
NODE_DEFAULT_FOCUS, NODE_RESPONSE_REGION, NODE_OVERLAY, NODE_SWEEP_GRADIENT,
NODE_RADIAL_GRADIENT, NODE_MASK, NODE_BLEND_MODE, NODE_DIRECTION,
NODE_CONSTRAINT_SIZE, NODE_GRAY_SCALE, NODE_INVERT, NODE_SEPIA,
NODE_CONTRAST, NODE_FOREGROUND_COLOR, NODE_OFFSET, NODE_MARK_ANCHOR,
NODE_BACKGROUND_IMAGE_POSITION, NODE_ALIGN_RULES, NODE_ALIGN_SELF, NODE_FLEX_GROW,
NODE_FLEX_SHRINK, NODE_FLEX_BASIS, NODE_ACCESSIBILITY_GROUP, NODE_ACCESSIBILITY_TEXT,
NODE_ACCESSIBILITY_MODE, NODE_ACCESSIBILITY_DESCRIPTION, NODE_FOCUS_STATUS, NODE_ASPECT_RATIO,
NODE_LAYOUT_WEIGHT, NODE_DISPLAY_PRIORITY, NODE_OUTLINE_WIDTH, NODE_WIDTH_PERCENT,
NODE_HEIGHT_PERCENT, NODE_PADDING_PERCENT, NODE_MARGIN_PERCENT, NODE_GEOMETRY_TRANSITION,
NODE_RELATIVE_LAYOUT_CHAIN_MODE, NODE_RENDER_FIT, NODE_OUTLINE_COLOR, NODE_SIZE,
NODE_RENDER_GROUP, NODE_COLOR_BLEND, NODE_FOREGROUND_BLUR_STYLE, NODE_LAYOUT_RECT,
NODE_FOCUS_ON_TOUCH, NODE_BORDER_WIDTH_PERCENT, NODE_BORDER_RADIUS_PERCENT, NODE_ACCESSIBILITY_ID = 87,
NODE_ACCESSIBILITY_ACTIONS = 88, NODE_ACCESSIBILITY_ROLE = 89, NODE_ACCESSIBILITY_STATE = 90, NODE_ACCESSIBILITY_VALUE = 91,
NODE_EXPAND_SAFE_AREA = 92, NODE_VISIBLE_AREA_CHANGE_RATIO = 93, NODE_TRANSITION = 94, NODE_UNIQUE_ID = 95, NODE_FOCUS_BOX = 96,
NODE_CLICK_DISTANCE = 97, NODE_TAB_STOP = 98, NODE_TEXT_CONTENT = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_TEXT, NODE_FONT_COLOR,
NODE_FONT_SIZE, NODE_FONT_STYLE, NODE_FONT_WEIGHT, NODE_TEXT_LINE_HEIGHT,
NODE_TEXT_DECORATION, NODE_TEXT_CASE, NODE_TEXT_LETTER_SPACING, NODE_TEXT_MAX_LINES,
NODE_TEXT_ALIGN, NODE_TEXT_OVERFLOW, NODE_FONT_FAMILY, NODE_TEXT_COPY_OPTION,
NODE_TEXT_BASELINE_OFFSET, NODE_TEXT_TEXT_SHADOW, NODE_TEXT_MIN_FONT_SIZE, NODE_TEXT_MAX_FONT_SIZE,
NODE_TEXT_FONT, NODE_TEXT_HEIGHT_ADAPTIVE_POLICY, NODE_TEXT_INDENT, NODE_TEXT_WORD_BREAK,
NODE_TEXT_ELLIPSIS_MODE, NODE_TEXT_LINE_SPACING, NODE_FONT_FEATURE, NODE_TEXT_ENABLE_DATA_DETECTOR,
NODE_TEXT_ENABLE_DATA_DETECTOR_CONFIG, NODE_TEXT_SELECTED_BACKGROUND_COLOR, NODE_TEXT_CONTENT_WITH_STYLED_STRING, NODE_TEXT_HALF_LEADING = 1029,NODE_IMMUTABLE_FONT_WEIGHT = 1030,
NODE_SPAN_CONTENT = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_SPAN, NODE_SPAN_TEXT_BACKGROUND_STYLE, NODE_SPAN_BASELINE_OFFSET, NODE_IMAGE_SPAN_SRC = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_IMAGE_SPAN,
NODE_IMAGE_SPAN_VERTICAL_ALIGNMENT, NODE_IMAGE_SPAN_ALT, NODE_IMAGE_SPAN_BASELINE_OFFSET = 3003, NODE_IMAGE_SRC = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_IMAGE,
NODE_IMAGE_OBJECT_FIT, NODE_IMAGE_INTERPOLATION, NODE_IMAGE_OBJECT_REPEAT, NODE_IMAGE_COLOR_FILTER,
NODE_IMAGE_AUTO_RESIZE, NODE_IMAGE_ALT, NODE_IMAGE_DRAGGABLE, NODE_IMAGE_RENDER_MODE,
NODE_IMAGE_FIT_ORIGINAL_SIZE, NODE_IMAGE_FILL_COLOR, NODE_IMAGE_RESIZABLE, NODE_TOGGLE_SELECTED_COLOR = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_TOGGLE,
NODE_TOGGLE_SWITCH_POINT_COLOR, NODE_TOGGLE_VALUE, NODE_TOGGLE_UNSELECTED_COLOR, NODE_LOADING_PROGRESS_COLOR = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_LOADING_PROGRESS,
NODE_LOADING_PROGRESS_ENABLE_LOADING, NODE_TEXT_INPUT_PLACEHOLDER = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_TEXT_INPUT, NODE_TEXT_INPUT_TEXT, NODE_TEXT_INPUT_CARET_COLOR,
NODE_TEXT_INPUT_CARET_STYLE, NODE_TEXT_INPUT_SHOW_UNDERLINE, NODE_TEXT_INPUT_MAX_LENGTH, NODE_TEXT_INPUT_ENTER_KEY_TYP NODE_TEXT_INPUT_SHOW_UNDERLINE, NODE_TEXT_INPUT_MAX_LENGTH, NODE_TEXT_INPUT_ENTER_KEY_TYPE,
NODE_TEXT_INPUT_PLACEHOLDER_COLOR, NODE_TEXT_INPUT_PLACEHOLDER_FONT, NODE_TEXT_INPUT_ENABLE_KEYBOARD_ON_FOCUS, NODE_TEXT_INPUT_TYPE,
NODE_TEXT_INPUT_SELECTED_BACKGROUND_COLOR, NODE_TEXT_INPUT_SHOW_PASSWORD_ICON, NODE_TEXT_INPUT_EDITING, NODE_TEXT_INPUT_CANCEL_BUTTON,
NODE_TEXT_INPUT_TEXT_SELECTION, NODE_TEXT_INPUT_UNDERLINE_COLOR, NODE_TEXT_INPUT_ENABLE_AUTO_FILL, NODE_TEXT_INPUT_CONTENT_TYPE,
NODE_TEXT_INPUT_PASSWORD_RULES, NODE_TEXT_INPUT_SELECT_ALL, NODE_TEXT_INPUT_INPUT_FILTER, NODE_TEXT_INPUT_STYLE,
NODE_TEXT_INPUT_CARET_OFFSET, NODE_TEXT_INPUT_CONTENT_RECT, NODE_TEXT_INPUT_CONTENT_LINE_COUNT, NODE_TEXT_INPUT_SELECTION_MENU_HIDDEN,
NODE_TEXT_INPUT_BLUR_ON_SUBMIT, NODE_TEXT_INPUT_CUSTOM_KEYBOARD, NODE_TEXT_INPUT_WORD_BREAK, NODE_TEXT_INPUT_NUMBER_OF_LINES,
NODE_TEXT_INPUT_SHOW_KEYBOARD_ON_FOCUS, NODE_TEXT_INPUT_LETTER_SPACING = 7032, NODE_TEXT_INPUT_ENABLE_PREVIEW_TEXT = 7033, NODE_TEXT_AREA_PLACEHOLDER = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_TEXT_AREA, NODE_TEXT_AREA_TEXT, NODE_TEXT_AREA_MAX_LENGTH,
NODE_TEXT_AREA_PLACEHOLDER_COLOR, NODE_TEXT_AREA_PLACEHOLDER_FONT, NODE_TEXT_AREA_CARET_COLOR, NODE_TEXT_AREA_EDITING,
NODE_TEXT_AREA_TYPE, NODE_TEXT_AREA_SHOW_COUNTER, NODE_TEXT_AREA_SELECTION_MENU_HIDDEN, NODE_TEXT_AREA_BLUR_ON_SUBMIT,
NODE_TEXT_AREA_INPUT_FILTER, NODE_TEXT_AREA_SELECTED_BACKGROUND_COLOR, NODE_TEXT_AREA_ENTER_KEY_TYPE, NODE_TEXT_AREA_ENABLE_KEYBOARD_ON_FOCUS,
NODE_TEXT_AREA_CARET_OFFSET, NODE_TEXT_AREA_CONTENT_RECT, NODE_TEXT_AREA_CONTENT_LINE_COUNT, NODE_TEXT_AREA_TEXT_SELECTION,
NODE_TEXT_AREA_ENABLE_AUTO_FILL, NODE_TEXT_AREA_CONTENT_TYPE, NODE_TEXT_AREA_NUMBER_OF_LINES, NODE_TEXT_AREA_SHOW_KEYBOARD_ON_FOCUS, NODE_TEXT_AREA_LETTER_SPACING = 8023, NODE_TEXT_AREA_ENABLE_PREVIEW_TEXT = 8024,
NODE_BUTTON_LABEL = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_BUTTON, NODE_BUTTON_TYPE, NODE_BUTTON_MIN_FONT_SCALE, NODE_BUTTON_MAX_FONT_SCALE, NODE_PROGRESS_VALUE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_PROGRESS, NODE_PROGRESS_TOTAL,
NODE_PROGRESS_COLOR, NODE_PROGRESS_TYPE, NODE_CHECKBOX_SELECT = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_CHECKBOX, NODE_CHECKBOX_SELECT_COLOR,
NODE_CHECKBOX_UNSELECT_COLOR, NODE_CHECKBOX_MARK, NODE_CHECKBOX_SHAPE, NODE_XCOMPONENT_ID = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_XCOMPONENT,
NODE_XCOMPONENT_TYPE, NODE_XCOMPONENT_SURFACE_SIZE, NODE_DATE_PICKER_LUNAR = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_DATE_PICKER, NODE_DATE_PICKER_START,
NODE_DATE_PICKER_END, NODE_DATE_PICKER_SELECTED, NODE_DATE_PICKER_DISAPPEAR_TEXT_STYLE, NODE_DATE_PICKER_TEXT_STYLE,
NODE_DATE_PICKER_SELECTED_TEXT_STYLE, NODE_DATE_PICKER_MODE,NODE_DATE_PICKER_ENABLE_HAPTIC_FEEDBACK = 13008,NODE_TIME_PICKER_SELECTED = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_TIME_PICKER, NODE_TIME_PICKER_USE_MILITARY_TIME, NODE_TIME_PICKER_DISAPPEAR_TEXT_STYLE,
NODE_TIME_PICKER_TEXT_STYLE, NODE_TIME_PICKER_SELECTED_TEXT_STYLE, NODE_TIME_PICKER_START, NODE_TIME_PICKER_END, NODE_TIME_PICKER_ENABLE_CASCADE = 14007, NODE_TEXT_PICKER_OPTION_RANGE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_TEXT_PICKER, NODE_TEXT_PICKER_OPTION_SELECTED,
NODE_TEXT_PICKER_OPTION_VALUE, NODE_TEXT_PICKER_DISAPPEAR_TEXT_STYLE, NODE_TEXT_PICKER_TEXT_STYLE, NODE_TEXT_PICKER_SELECTED_TEXT_STYLE,
NODE_TEXT_PICKER_SELECTED_INDEX, NODE_TEXT_PICKER_CAN_LOOP, NODE_TEXT_PICKER_DEFAULT_PICKER_ITEM_HEIGHT,NODE_TEXT_PICKER_ENABLE_HAPTIC_FEEDBACK = 15010, NODE_CALENDAR_PICKER_HINT_RADIUS = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_CALENDAR_PICKER,
NODE_CALENDAR_PICKER_SELECTED_DATE, NODE_CALENDAR_PICKER_EDGE_ALIGNMENT, NODE_CALENDAR_PICKER_TEXT_STYLE, NODE_CALENDAR_PICKER_START = 16004, NODE_CALENDAR_PICKER_END = 16005, NODE_SLIDER_BLOCK_COLOR = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_SLIDER,
NODE_SLIDER_TRACK_COLOR, NODE_SLIDER_SELECTED_COLOR, NODE_SLIDER_SHOW_STEPS, NODE_SLIDER_BLOCK_STYLE,
NODE_SLIDER_VALUE, NODE_SLIDER_MIN_VALUE, NODE_SLIDER_MAX_VALUE, NODE_SLIDER_STEP,
NODE_SLIDER_DIRECTION, NODE_SLIDER_REVERSE, NODE_SLIDER_STYLE, NODE_SLIDER_TRACK_THICKNESS,
NODE_RADIO_CHECKED = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_RADIO, NODE_RADIO_STYLE, NODE_RADIO_VALUE, NODE_RADIO_GROUP,
NODE_CHECKBOX_GROUP_NAME = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_CHECKBOX_GROUP, NODE_CHECKBOX_GROUP_SELECT_ALL, NODE_CHECKBOX_GROUP_SELECTED_COLOR, NODE_CHECKBOX_GROUP_UNSELECTED_COLOR, NODE_CHECKBOX_GROUP_MARK, NODE_CHECKBOX_GROUP_SHAPE,
NODE_STACK_ALIGN_CONTENT = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_STACK, NODE_SCROLL_BAR_DISPLAY_MODE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_SCROLL, NODE_SCROLL_BAR_WIDTH, NODE_SCROLL_BAR_COLOR,
NODE_SCROLL_SCROLL_DIRECTION, NODE_SCROLL_EDGE_EFFECT, NODE_SCROLL_ENABLE_SCROLL_INTERACTION, NODE_SCROLL_FRICTION,
NODE_SCROLL_SNAP, NODE_SCROLL_NESTED_SCROLL, NODE_SCROLL_OFFSET, NODE_SCROLL_EDGE,
NODE_SCROLL_ENABLE_PAGING, NODE_SCROLL_PAGE, NODE_SCROLL_BY, NODE_SCROLL_FLING,
NODE_SCROLL_FADING_EDGE, NODE_SCROLL_SIZE, NODE_LIST_DIRECTION = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_LIST, NODE_LIST_STICKY,
NODE_LIST_SPACE, NODE_LIST_NODE_ADAPTER, NODE_LIST_CACHED_COUNT, NODE_LIST_SCROLL_TO_INDEX,
NODE_LIST_ALIGN_LIST_ITEM, NODE_LIST_CHILDREN_MAIN_SIZE = 1003007, NODE_LIST_INITIAL_INDEX = 1003008, NODE_LIST_DIVIDER = 1003009,
NODE_SWIPER_LOOP = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_SWIPER, NODE_SWIPER_AUTO_PLAY, NODE_SWIPER_SHOW_INDICATOR, NODE_SWIPER_INTERVAL,
NODE_SWIPER_VERTICAL, NODE_SWIPER_DURATION, NODE_SWIPER_CURVE, NODE_SWIPER_ITEM_SPACE,
NODE_SWIPER_INDEX, NODE_SWIPER_DISPLAY_COUNT, NODE_SWIPER_DISABLE_SWIPE, NODE_SWIPER_SHOW_DISPLAY_ARROW,
NODE_SWIPER_EDGE_EFFECT_MODE, NODE_SWIPER_NODE_ADAPTER, NODE_SWIPER_CACHED_COUNT, NODE_SWIPER_PREV_MARGIN,
NODE_SWIPER_NEXT_MARGIN, NODE_SWIPER_INDICATOR, NODE_SWIPER_NESTED_SCROLL, NODE_SWIPER_SWIPE_TO_INDEX,
NODE_SWIPER_INDICATOR_INTERACTIVE, NODE_SWIPER_PAGE_FLIP_MODE, NODE_LIST_ITEM_SWIPE_ACTION = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_LIST_ITEM, NODE_LIST_ITEM_GROUP_SET_HEADER = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_LIST_ITEM_GROUP,
NODE_LIST_ITEM_GROUP_SET_FOOTER, NODE_LIST_ITEM_GROUP_SET_DIVIDER, NODE_LIST_ITEM_GROUP_CHILDREN_MAIN_SIZE = 1005003, NODE_COLUMN_ALIGN_ITEMS = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_COLUMN,
NODE_COLUMN_JUSTIFY_CONTENT, NODE_ROW_ALIGN_ITEMS = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_ROW, NODE_ROW_JUSTIFY_CONTENT, NODE_FLEX_OPTION = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_FLEX,
NODE_REFRESH_REFRESHING = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_REFRESH, NODE_REFRESH_CONTENT, NODE_REFRESH_PULL_DOWN_RATIO = 1009002, NODE_REFRESH_OFFSET = 1009003,
NODE_REFRESH_PULL_TO_REFRESH = 1009004, NODE_WATER_FLOW_LAYOUT_DIRECTION = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_WATER_FLOW, NODE_WATER_FLOW_COLUMN_TEMPLATE, NODE_WATER_FLOW_ROW_TEMPLATE,
NODE_WATER_FLOW_COLUMN_GAP, NODE_WATER_FLOW_ROW_GAP, NODE_WATER_FLOW_SECTION_OPTION, NODE_WATER_FLOW_NODE_ADAPTER,
NODE_WATER_FLOW_CACHED_COUNT, NODE_WATER_FLOW_FOOTER, NODE_WATER_FLOW_SCROLL_TO_INDEX, NODE_WATER_FLOW_ITEM_CONSTRAINT_SIZE,
NODE_RELATIVE_CONTAINER_GUIDE_LINE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_RELATIVE_CONTAINER, NODE_RELATIVE_CONTAINER_BARRIER, NODE_GRID_COLUMN_TEMPLATE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_GRID, NODE_GRID_ROW_TEMPLATE,
NODE_GRID_COLUMN_GAP, NODE_GRID_ROW_GAP, NODE_GRID_NODE_ADAPTER, NODE_GRID_CACHED_COUNT, NODE_TEXT_PICKER_COLUMN_WIDTHS = 15009,
NODE_IMAGE_ANIMATOR_IMAGES = ARKUI_NODE_IMAGE_ANIMATOR \* MAX_NODE_SCOPE_NUM, NODE_IMAGE_ANIMATOR_STATE, NODE_IMAGE_ANIMATOR_DURATION, NODE_IMAGE_ANIMATOR_REVERSE,
NODE_IMAGE_ANIMATOR_FIXED_SIZE, NODE_IMAGE_ANIMATOR_FILL_MODE, NODE_IMAGE_ANIMATOR_ITERATION
} | Defines the ArkUI style attributes that can be set on the native side. | -| [ArkUI_NodeEventType](#arkui_nodeeventtype) {
NODE_TOUCH_EVENT = 0, NODE_EVENT_ON_APPEAR, NODE_EVENT_ON_DISAPPEAR, NODE_EVENT_ON_AREA_CHANGE,
NODE_ON_FOCUS, NODE_ON_BLUR, NODE_ON_CLICK, NODE_ON_TOUCH_INTERCEPT,
NODE_EVENT_ON_VISIBLE_AREA_CHANGE, NODE_ON_HOVER, NODE_ON_MOUSE, NODE_EVENT_ON_ATTACH,
NODE_EVENT_ON_DETACH, NODE_ON_ACCESSIBILITY_ACTIONS = 13, NODE_ON_PRE_DRAG = 14, NODE_ON_DRAG_START = 15,
NODE_ON_DRAG_ENTER = 16, NODE_ON_DRAG_MOVE = 17, NODE_ON_DRAG_LEAVE = 18, NODE_ON_DROP = 19,
NODE_ON_DRAG_END = 20, NODE_ON_KEY_EVENT = 21, NODE_ON_KEY_PRE_IME = 22, NODE_TEXT_ON_DETECT_RESULT_UPDATE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_TEXT,
NODE_IMAGE_ON_COMPLETE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_IMAGE, NODE_IMAGE_ON_ERROR, NODE_IMAGE_ON_SVG_PLAY_FINISH, NODE_IMAGE_ON_DOWNLOAD_PROGRESS,
NODE_TOGGLE_ON_CHANGE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_TOGGLE, NODE_TEXT_INPUT_ON_CHANGE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_TEXT_INPUT, NODE_TEXT_INPUT_ON_SUBMIT, NODE_TEXT_INPUT_ON_CUT,
NODE_TEXT_INPUT_ON_PASTE, NODE_TEXT_INPUT_ON_TEXT_SELECTION_CHANGE, NODE_TEXT_INPUT_ON_EDIT_CHANGE, NODE_TEXT_INPUT_ON_INPUT_FILTER_ERROR,
NODE_TEXT_INPUT_ON_CONTENT_SCROLL, NODE_TEXT_INPUT_ON_CONTENT_SIZE_CHANGE, NODE_TEXT_INPUT_ON_WILL_INSERT = 7009, NODE_TEXT_INPUT_ON_DID_INSERT = 7010,
NODE_TEXT_INPUT_ON_WILL_DELETE = 7011, NODE_TEXT_INPUT_ON_DID_DELETE = 7012, NODE_TEXT_INPUT_ON_CHANGE_WITH_PREVIEW_TEXT = 7013, NODE_TEXT_AREA_ON_CHANGE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_TEXT_AREA, NODE_TEXT_AREA_ON_PASTE,
NODE_TEXT_AREA_ON_TEXT_SELECTION_CHANGE, NODE_TEXT_AREA_ON_EDIT_CHANGE, NODE_TEXT_AREA_ON_SUBMIT, NODE_TEXT_AREA_ON_INPUT_FILTER_ERROR,
NODE_TEXT_AREA_ON_CONTENT_SCROLL, NODE_TEXT_AREA_ON_CONTENT_SIZE_CHANGE, NODE_TEXT_AREA_ON_WILL_INSERT = 8008, NODE_TEXT_AREA_ON_DID_INSERT = 8009,
NODE_TEXT_AREA_ON_WILL_DELETE = 8010, NODE_TEXT_AREA_ON_DID_DELETE = 8011, NODE_TEXT_AREA_ON_CHANGE_WITH_PREVIEW_TEXT = 8012, NODE_CHECKBOX_EVENT_ON_CHANGE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_CHECKBOX, NODE_DATE_PICKER_EVENT_ON_DATE_CHANGE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_DATE_PICKER,
NODE_TIME_PICKER_EVENT_ON_CHANGE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_TIME_PICKER, NODE_TEXT_PICKER_EVENT_ON_CHANGE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_TEXT_PICKER, NODE_CALENDAR_PICKER_EVENT_ON_CHANGE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_CALENDAR_PICKER, NODE_SLIDER_EVENT_ON_CHANGE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_SLIDER,
NODE_RADIO_EVENT_ON_CHANGE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_RADIO, NODE_IMAGE_ANIMATOR_EVENT_ON_START = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_IMAGE_ANIMATOR, NODE_IMAGE_ANIMATOR_EVENT_ON_PAUSE, NODE_IMAGE_ANIMATOR_EVENT_ON_REPEAT,
NODE_IMAGE_ANIMATOR_EVENT_ON_CANCEL, NODE_IMAGE_ANIMATOR_EVENT_ON_FINISH,
NODE_CHECKBOX_GROUP_EVENT_ON_CHANGE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_CHECKBOX_GROUP,
NODE_SWIPER_EVENT_ON_CHANGE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_SWIPER, NODE_SWIPER_EVENT_ON_ANIMATION_START,
NODE_SWIPER_EVENT_ON_ANIMATION_END, NODE_SWIPER_EVENT_ON_GESTURE_SWIPE, NODE_SWIPER_EVENT_ON_CONTENT_DID_SCROLL, NODE_SWIPER_EVENT_ON_SELECTED = 1001005, NODE_SCROLL_EVENT_ON_SCROLL = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_SCROLL,
NODE_SCROLL_EVENT_ON_SCROLL_FRAME_BEGIN, NODE_SCROLL_EVENT_ON_WILL_SCROLL, NODE_SCROLL_EVENT_ON_DID_SCROLL, NODE_SCROLL_EVENT_ON_SCROLL_START,
NODE_SCROLL_EVENT_ON_SCROLL_STOP, NODE_SCROLL_EVENT_ON_SCROLL_EDGE, NODE_SCROLL_EVENT_ON_REACH_START, NODE_SCROLL_EVENT_ON_REACH_END,
NODE_LIST_ON_SCROLL_INDEX = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_LIST, NODE_LIST_ON_WILL_SCROLL, NODE_LIST_ON_DID_SCROLL, NODE_REFRESH_STATE_CHANGE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_REFRESH,
NODE_REFRESH_ON_REFRESH, NODE_REFRESH_ON_OFFSET_CHANGE, NODE_ON_WILL_SCROLL = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_WATER_FLOW, NODE_WATER_FLOW_ON_DID_SCROLL,
NODE_WATER_FLOW_ON_SCROLL_INDEX
} | Enumerates the event types supported by the NativeNode component. | -| [ArkUI_NodeDirtyFlag](#arkui_nodedirtyflag) { NODE_NEED_MEASURE = 1, NODE_NEED_LAYOUT, NODE_NEED_RENDER } | Enumerates the dirty area flags passed in the **::markDirty** API. | -| [ArkUI_NodeCustomEventType](#arkui_nodecustomeventtype) {
ARKUI_NODE_CUSTOM_EVENT_ON_MEASURE = 1 << 0, ARKUI_NODE_CUSTOM_EVENT_ON_LAYOUT = 1 << 1, ARKUI_NODE_CUSTOM_EVENT_ON_DRAW = 1 << 2, ARKUI_NODE_CUSTOM_EVENT_ON_FOREGROUND_DRAW = 1 << 3,
ARKUI_NODE_CUSTOM_EVENT_ON_OVERLAY_DRAW = 1 << 4
} | Enumerates the custom component event types. | -| [ArkUI_NodeAdapterEventType](#arkui_nodeadaptereventtype) {
NODE_ADAPTER_EVENT_WILL_ATTACH_TO_NODE = 1, NODE_ADAPTER_EVENT_WILL_DETACH_FROM_NODE = 2, NODE_ADAPTER_EVENT_ON_GET_NODE_ID = 3, NODE_ADAPTER_EVENT_ON_ADD_NODE_TO_ADAPTER = 4,
NODE_ADAPTER_EVENT_ON_REMOVE_NODE_FROM_ADAPTER = 5
} | Enumerates node adapter events. | -| [ArkUI_NodeContentEventType](#arkui_nodecontenteventtype) { NODE_CONTENT_EVENT_ON_ATTACH_TO_WINDOW = 0, NODE_CONTENT_EVENT_ON_DETACH_FROM_WINDOW = 1 } | Defines the NodeContent event type. | -| [ArkUI_Alignment](#arkui_alignment) {
ARKUI_ALIGNMENT_TOP_START = 0, ARKUI_ALIGNMENT_TOP, ARKUI_ALIGNMENT_TOP_END, ARKUI_ALIGNMENT_START,
ARKUI_ALIGNMENT_CENTER, ARKUI_ALIGNMENT_END, ARKUI_ALIGNMENT_BOTTOM_START, ARKUI_ALIGNMENT_BOTTOM,
ARKUI_ALIGNMENT_BOTTOM_END
} | Enumerates the alignment modes. | -| [ArkUI_ImageRepeat](#arkui_imagerepeat) { ARKUI_IMAGE_REPEAT_NONE = 0, ARKUI_IMAGE_REPEAT_X, ARKUI_IMAGE_REPEAT_Y, ARKUI_IMAGE_REPEAT_XY } | Enumerates the image repeat patterns. | -| [ArkUI_FontStyle](#arkui_fontstyle) { ARKUI_FONT_STYLE_NORMAL = 0, ARKUI_FONT_STYLE_ITALIC } | Enumerates the font styles. | -| [ArkUI_FontWeight](#arkui_fontweight) {
ARKUI_FONT_WEIGHT_W100 = 0, ARKUI_FONT_WEIGHT_W200, ARKUI_FONT_WEIGHT_W300, ARKUI_FONT_WEIGHT_W400,
ARKUI_FONT_WEIGHT_W500, ARKUI_FONT_WEIGHT_W600, ARKUI_FONT_WEIGHT_W700, ARKUI_FONT_WEIGHT_W800,
ARKUI_FONT_WEIGHT_W900, ARKUI_FONT_WEIGHT_BOLD, ARKUI_FONT_WEIGHT_NORMAL, ARKUI_FONT_WEIGHT_BOLDER,
ARKUI_FONT_WEIGHT_LIGHTER, ARKUI_FONT_WEIGHT_MEDIUM, ARKUI_FONT_WEIGHT_REGULAR
} | Enumerates the font weights. | -| [ArkUI_TextAlignment](#arkui_textalignment) { ARKUI_TEXT_ALIGNMENT_START = 0, ARKUI_TEXT_ALIGNMENT_CENTER, ARKUI_TEXT_ALIGNMENT_END, ARKUI_TEXT_ALIGNMENT_JUSTIFY } | Enumerates the text alignment mode. | -| [ArkUI_EnterKeyType](#arkui_enterkeytype) {
ARKUI_ENTER_KEY_TYPE_GO = 2, ARKUI_ENTER_KEY_TYPE_SEARCH = 3, ARKUI_ENTER_KEY_TYPE_SEND, ARKUI_ENTER_KEY_TYPE_NEXT,
ARKUI_ENTER_KEY_TYPE_DONE, ARKUI_ENTER_KEY_TYPE_PREVIOUS, ARKUI_ENTER_KEY_TYPE_NEW_LINE
} | Enumerates the types of the Enter key for a single-line text box. | -| [ArkUI_TextInputType](#arkui_textinputtype) {
ARKUI_TEXTINPUT_TYPE_NORMAL = 0, ARKUI_TEXTINPUT_TYPE_NUMBER = 2, ARKUI_TEXTINPUT_TYPE_PHONE_NUMBER = 3, ARKUI_TEXTINPUT_TYPE_EMAIL = 5,
ARKUI_TEXTINPUT_TYPE_PASSWORD = 7, ARKUI_TEXTINPUT_TYPE_NUMBER_PASSWORD = 8, ARKUI_TEXTINPUT_TYPE_SCREEN_LOCK_PASSWORD = 9, ARKUI_TEXTINPUT_TYPE_USER_NAME = 10,
ARKUI_TEXTINPUT_TYPE_NEW_PASSWORD = 11, ARKUI_TEXTINPUT_TYPE_NUMBER_DECIMAL = 12
} | Enumerates the text input types. | -| [ArkUI_TextAreaType](#arkui_textareatype) { ARKUI_TEXTAREA_TYPE_NORMAL = 0, ARKUI_TEXTAREA_TYPE_NUMBER = 2, ARKUI_TEXTAREA_TYPE_PHONE_NUMBER = 3, ARKUI_TEXTAREA_TYPE_EMAIL = 5 } | Enumerates the text box types. | -| [ArkUI_CancelButtonStyle](#arkui_cancelbuttonstyle) { ARKUI_CANCELBUTTON_STYLE_CONSTANT = 0, ARKUI_CANCELBUTTON_STYLE_INVISIBLE, ARKUI_CANCELBUTTON_STYLE_INPUT } | Enumerates the styles of the Cancel button. | -| [ArkUI_XComponentType](#arkui_xcomponenttype) { ARKUI_XCOMPONENT_TYPE_SURFACE = 0, ARKUI_XCOMPONENT_TYPE_TEXTURE = 2 } |Enumerates the types of the XComponent type. | -| [ArkUI_ProgressType](#arkui_progresstype) {
ARKUI_PROGRESS_TYPE_LINEAR = 0, ARKUI_PROGRESS_TYPE_RING, ARKUI_PROGRESS_TYPE_ECLIPSE, ARKUI_PROGRESS_TYPE_SCALE_RING,
ARKUI_PROGRESS_TYPE_CAPSULE
} | Enumerates the styles of the progress indicator. | -| [ArkUI_TextDecorationType](#arkui_textdecorationtype) { ARKUI_TEXT_DECORATION_TYPE_NONE = 0, ARKUI_TEXT_DECORATION_TYPE_UNDERLINE, ARKUI_TEXT_DECORATION_TYPE_OVERLINE, ARKUI_TEXT_DECORATION_TYPE_LINE_THROUGH } | Enumerates the text decoration types. | -| [ArkUI_TextDecorationStyle](#arkui_textdecorationstyle) {
ARKUI_TEXT_DECORATION_STYLE_SOLID = 0, ARKUI_TEXT_DECORATION_STYLE_DOUBLE, ARKUI_TEXT_DECORATION_STYLE_DOTTED, ARKUI_TEXT_DECORATION_STYLE_DASHED,
ARKUI_TEXT_DECORATION_STYLE_WAVY
} | Enumerates the text decoration styles. | -| [ArkUI_TextCase](#arkui_textcase) { ARKUI_TEXT_CASE_NORMAL = 0, ARKUI_TEXT_CASE_LOWER, ARKUI_TEXT_CASE_UPPER } | Enumerates the text cases. | -| [ArkUI_CopyOptions](#arkui_copyoptions) { ARKUI_COPY_OPTIONS_NONE = 0, ARKUI_COPY_OPTIONS_IN_APP, ARKUI_COPY_OPTIONS_LOCAL_DEVICE, ARKUI_COPY_OPTIONS_CROSS_DEVICE } | Enumerates the text copy and paste modes. | -| [ArkUI_ShadowType](#arkui_shadowtype) { ARKUI_SHADOW_TYPE_COLOR = 0, ARKUI_SHADOW_TYPE_BLUR } | Enumerates the shadow types. | -| [ArkUI_TextPickerRangeType](#arkui_textpickerrangetype) { ARKUI_TEXTPICKER_RANGETYPE_SINGLE = 0, ARKUI_TEXTPICKER_RANGETYPE_MULTI, ARKUI_TEXTPICKER_RANGETYPE_RANGE_CONTENT, ARKUI_TEXTPICKER_RANGETYPE_CASCADE_RANGE_CONTENT } | Enumerates the types of the text picker. | -| [ArkUI_AccessibilityCheckedState](#arkui_accessibilitycheckedstate) { ARKUI_ACCESSIBILITY_UNCHECKED = 0, ARKUI_ACCESSIBILITY_CHECKED } | Enumerates the accessibility check box states. | -| [ArkUI_AccessibilityActionType](#arkui_accessibilityactiontype) {
ARKUI_ACCESSIBILITY_ACTION_CLICK = 1 << 0, ARKUI_ACCESSIBILITY_ACTION_LONG_CLICK = 1 << 1, ARKUI_ACCESSIBILITY_ACTION_CUT = 1 << 2, ARKUI_ACCESSIBILITY_ACTION_COPY = 1 << 3,
ARKUI_ACCESSIBILITY_ACTION_PASTE = 1 << 4
} | Defines an enum for the accessibility action types. | -| [ArkUI_EdgeEffect](#arkui_edgeeffect) { ARKUI_EDGE_EFFECT_SPRING = 0, ARKUI_EDGE_EFFECT_FADE, ARKUI_EDGE_EFFECT_NONE } | Enumerates the effects used at the edges of the component when the boundary of the scrollable content is reached. | +| [ArkUI_NodeAttributeType](#arkui_nodeattributetype) {
NODE_WIDTH = 0, NODE_HEIGHT, NODE_BACKGROUND_COLOR, NODE_BACKGROUND_IMAGE,
NODE_PADDING, NODE_ID, NODE_ENABLED, NODE_MARGIN,
NODE_TRANSLATE, NODE_SCALE, NODE_ROTATE, NODE_BRIGHTNESS,
NODE_SATURATION, NODE_BLUR, NODE_LINEAR_GRADIENT, NODE_ALIGNMENT,
NODE_OPACITY, NODE_BORDER_WIDTH, NODE_BORDER_RADIUS, NODE_BORDER_COLOR,
NODE_BORDER_STYLE, NODE_Z_INDEX, NODE_VISIBILITY, NODE_CLIP,
NODE_CLIP_SHAPE, NODE_TRANSFORM, NODE_HIT_TEST_BEHAVIOR, NODE_POSITION,
NODE_SHADOW, NODE_CUSTOM_SHADOW, NODE_BACKGROUND_IMAGE_SIZE, NODE_BACKGROUND_IMAGE_SIZE_WITH_STYLE,
NODE_BACKGROUND_BLUR_STYLE, NODE_TRANSFORM_CENTER, NODE_OPACITY_TRANSITION, NODE_ROTATE_TRANSITION,
NODE_SCALE_TRANSITION, NODE_TRANSLATE_TRANSITION, NODE_MOVE_TRANSITION, NODE_FOCUSABLE,
NODE_DEFAULT_FOCUS, NODE_RESPONSE_REGION, NODE_OVERLAY, NODE_SWEEP_GRADIENT,
NODE_RADIAL_GRADIENT, NODE_MASK, NODE_BLEND_MODE, NODE_DIRECTION,
NODE_CONSTRAINT_SIZE, NODE_GRAY_SCALE, NODE_INVERT, NODE_SEPIA,
NODE_CONTRAST, NODE_FOREGROUND_COLOR, NODE_OFFSET, NODE_MARK_ANCHOR,
NODE_BACKGROUND_IMAGE_POSITION, NODE_ALIGN_RULES, NODE_ALIGN_SELF, NODE_FLEX_GROW,
NODE_FLEX_SHRINK, NODE_FLEX_BASIS, NODE_ACCESSIBILITY_GROUP, NODE_ACCESSIBILITY_TEXT,
NODE_ACCESSIBILITY_MODE, NODE_ACCESSIBILITY_DESCRIPTION, NODE_FOCUS_STATUS, NODE_ASPECT_RATIO,
NODE_LAYOUT_WEIGHT, NODE_DISPLAY_PRIORITY, NODE_OUTLINE_WIDTH, NODE_WIDTH_PERCENT,
NODE_HEIGHT_PERCENT, NODE_PADDING_PERCENT, NODE_MARGIN_PERCENT, NODE_GEOMETRY_TRANSITION,
NODE_RELATIVE_LAYOUT_CHAIN_MODE, NODE_RENDER_FIT, NODE_OUTLINE_COLOR, NODE_SIZE,
NODE_RENDER_GROUP, NODE_COLOR_BLEND, NODE_FOREGROUND_BLUR_STYLE, NODE_LAYOUT_RECT,
NODE_FOCUS_ON_TOUCH, NODE_BORDER_WIDTH_PERCENT, NODE_BORDER_RADIUS_PERCENT, NODE_ACCESSIBILITY_ID = 87,
NODE_ACCESSIBILITY_ACTIONS = 88, NODE_ACCESSIBILITY_ROLE = 89, NODE_ACCESSIBILITY_STATE = 90, NODE_ACCESSIBILITY_VALUE = 91,
NODE_EXPAND_SAFE_AREA = 92, NODE_VISIBLE_AREA_CHANGE_RATIO = 93, NODE_TRANSITION = 94, NODE_UNIQUE_ID = 95, NODE_FOCUS_BOX = 96,
NODE_CLICK_DISTANCE = 97, NODE_TAB_STOP = 98, NODE_BACKGROUND_IMAGE_RESIZABLE_WITH_SLICE = 100, NODE_NEXT_FOCUS = 101, NODE_VISIBLE_AREA_APPROXIMATE_CHANGE_RATIO = 102, NODE_TEXT_CONTENT = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_TEXT, NODE_FONT_COLOR,
NODE_FONT_SIZE, NODE_FONT_STYLE, NODE_FONT_WEIGHT, NODE_TEXT_LINE_HEIGHT,
NODE_TEXT_DECORATION, NODE_TEXT_CASE, NODE_TEXT_LETTER_SPACING, NODE_TEXT_MAX_LINES,
NODE_TEXT_ALIGN, NODE_TEXT_OVERFLOW, NODE_FONT_FAMILY, NODE_TEXT_COPY_OPTION,
NODE_TEXT_BASELINE_OFFSET, NODE_TEXT_TEXT_SHADOW, NODE_TEXT_MIN_FONT_SIZE, NODE_TEXT_MAX_FONT_SIZE,
NODE_TEXT_FONT, NODE_TEXT_HEIGHT_ADAPTIVE_POLICY, NODE_TEXT_INDENT, NODE_TEXT_WORD_BREAK,
NODE_TEXT_ELLIPSIS_MODE, NODE_TEXT_LINE_SPACING, NODE_FONT_FEATURE, NODE_TEXT_ENABLE_DATA_DETECTOR,
NODE_TEXT_ENABLE_DATA_DETECTOR_CONFIG, NODE_TEXT_SELECTED_BACKGROUND_COLOR, NODE_TEXT_CONTENT_WITH_STYLED_STRING, NODE_TEXT_HALF_LEADING = 1029,NODE_IMMUTABLE_FONT_WEIGHT = 1030,
NODE_SPAN_CONTENT = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_SPAN, NODE_SPAN_TEXT_BACKGROUND_STYLE, NODE_SPAN_BASELINE_OFFSET, NODE_IMAGE_SPAN_SRC = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_IMAGE_SPAN,
NODE_IMAGE_SPAN_VERTICAL_ALIGNMENT, NODE_IMAGE_SPAN_ALT, NODE_IMAGE_SPAN_BASELINE_OFFSET = 3003, NODE_IMAGE_SRC = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_IMAGE,
NODE_IMAGE_OBJECT_FIT, NODE_IMAGE_INTERPOLATION, NODE_IMAGE_OBJECT_REPEAT, NODE_IMAGE_COLOR_FILTER,
NODE_IMAGE_AUTO_RESIZE, NODE_IMAGE_ALT, NODE_IMAGE_DRAGGABLE, NODE_IMAGE_RENDER_MODE,
NODE_IMAGE_FIT_ORIGINAL_SIZE, NODE_IMAGE_FILL_COLOR, NODE_IMAGE_RESIZABLE, NODE_TOGGLE_SELECTED_COLOR = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_TOGGLE,
NODE_TOGGLE_SWITCH_POINT_COLOR, NODE_TOGGLE_VALUE, NODE_TOGGLE_UNSELECTED_COLOR, NODE_LOADING_PROGRESS_COLOR = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_LOADING_PROGRESS,
NODE_LOADING_PROGRESS_ENABLE_LOADING, NODE_TEXT_INPUT_PLACEHOLDER = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_TEXT_INPUT, NODE_TEXT_INPUT_TEXT, NODE_TEXT_INPUT_CARET_COLOR,
NODE_TEXT_INPUT_CARET_STYLE, NODE_TEXT_INPUT_SHOW_UNDERLINE, NODE_TEXT_INPUT_MAX_LENGTH, NODE_TEXT_INPUT_ENTER_KEY_TYPE,
NODE_TEXT_INPUT_PLACEHOLDER_COLOR, NODE_TEXT_INPUT_PLACEHOLDER_FONT, NODE_TEXT_INPUT_ENABLE_KEYBOARD_ON_FOCUS, NODE_TEXT_INPUT_TYPE,
NODE_TEXT_INPUT_SELECTED_BACKGROUND_COLOR, NODE_TEXT_INPUT_SHOW_PASSWORD_ICON, NODE_TEXT_INPUT_EDITING, NODE_TEXT_INPUT_CANCEL_BUTTON,
NODE_TEXT_INPUT_TEXT_SELECTION, NODE_TEXT_INPUT_UNDERLINE_COLOR, NODE_TEXT_INPUT_ENABLE_AUTO_FILL, NODE_TEXT_INPUT_CONTENT_TYPE,
NODE_TEXT_INPUT_PASSWORD_RULES, NODE_TEXT_INPUT_SELECT_ALL, NODE_TEXT_INPUT_INPUT_FILTER, NODE_TEXT_INPUT_STYLE,
NODE_TEXT_INPUT_CARET_OFFSET, NODE_TEXT_INPUT_CONTENT_RECT, NODE_TEXT_INPUT_CONTENT_LINE_COUNT, NODE_TEXT_INPUT_SELECTION_MENU_HIDDEN,
NODE_TEXT_INPUT_BLUR_ON_SUBMIT, NODE_TEXT_INPUT_CUSTOM_KEYBOARD, NODE_TEXT_INPUT_WORD_BREAK, NODE_TEXT_INPUT_NUMBER_OF_LINES,
NODE_TEXT_INPUT_SHOW_KEYBOARD_ON_FOCUS, NODE_TEXT_INPUT_LETTER_SPACING = 7032, NODE_TEXT_INPUT_ENABLE_PREVIEW_TEXT = 7033, NODE_TEXT_INPUT_KEYBOARD_APPEARANCE = 7035, NODE_TEXT_AREA_PLACEHOLDER = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_TEXT_AREA, NODE_TEXT_AREA_TEXT, NODE_TEXT_AREA_MAX_LENGTH,
NODE_TEXT_AREA_PLACEHOLDER_COLOR, NODE_TEXT_AREA_PLACEHOLDER_FONT, NODE_TEXT_AREA_CARET_COLOR, NODE_TEXT_AREA_EDITING,
NODE_TEXT_AREA_TYPE, NODE_TEXT_AREA_SHOW_COUNTER, NODE_TEXT_AREA_SELECTION_MENU_HIDDEN, NODE_TEXT_AREA_BLUR_ON_SUBMIT,
NODE_TEXT_AREA_INPUT_FILTER, NODE_TEXT_AREA_SELECTED_BACKGROUND_COLOR, NODE_TEXT_AREA_ENTER_KEY_TYPE, NODE_TEXT_AREA_ENABLE_KEYBOARD_ON_FOCUS,
NODE_TEXT_AREA_CARET_OFFSET, NODE_TEXT_AREA_CONTENT_RECT, NODE_TEXT_AREA_CONTENT_LINE_COUNT, NODE_TEXT_AREA_TEXT_SELECTION,
NODE_TEXT_AREA_ENABLE_AUTO_FILL, NODE_TEXT_AREA_CONTENT_TYPE, NODE_TEXT_AREA_NUMBER_OF_LINES, NODE_TEXT_AREA_SHOW_KEYBOARD_ON_FOCUS, NODE_TEXT_AREA_LETTER_SPACING = 8023, NODE_TEXT_AREA_ENABLE_PREVIEW_TEXT = 8024, NODE_TEXT_AREA_KEYBOARD_APPEARANCE = 8026,
NODE_BUTTON_LABEL = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_BUTTON, NODE_BUTTON_TYPE, NODE_BUTTON_MIN_FONT_SCALE, NODE_BUTTON_MAX_FONT_SCALE, NODE_PROGRESS_VALUE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_PROGRESS, NODE_PROGRESS_TOTAL,
NODE_PROGRESS_COLOR, NODE_PROGRESS_TYPE, NODE_PROGRESS_LINEAR_STYLE, NODE_CHECKBOX_SELECT = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_CHECKBOX, NODE_CHECKBOX_SELECT_COLOR,
NODE_CHECKBOX_UNSELECT_COLOR, NODE_CHECKBOX_MARK, NODE_CHECKBOX_SHAPE, NODE_XCOMPONENT_ID = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_XCOMPONENT,
NODE_XCOMPONENT_TYPE, NODE_XCOMPONENT_SURFACE_SIZE, NODE_XCOMPONENT_SURFACE_RECT, NODE_XCOMPONENT_ENABLE_ANALYZER, NODE_DATE_PICKER_LUNAR = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_DATE_PICKER, NODE_DATE_PICKER_START,
NODE_DATE_PICKER_END, NODE_DATE_PICKER_SELECTED, NODE_DATE_PICKER_DISAPPEAR_TEXT_STYLE, NODE_DATE_PICKER_TEXT_STYLE,
NODE_DATE_PICKER_SELECTED_TEXT_STYLE, NODE_DATE_PICKER_MODE,NODE_DATE_PICKER_ENABLE_HAPTIC_FEEDBACK = 13008,NODE_TIME_PICKER_SELECTED = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_TIME_PICKER, NODE_TIME_PICKER_USE_MILITARY_TIME, NODE_TIME_PICKER_DISAPPEAR_TEXT_STYLE,
NODE_TIME_PICKER_TEXT_STYLE, NODE_TIME_PICKER_SELECTED_TEXT_STYLE, NODE_TIME_PICKER_START, NODE_TIME_PICKER_END, NODE_TIME_PICKER_ENABLE_CASCADE = 14007, NODE_TEXT_PICKER_OPTION_RANGE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_TEXT_PICKER, NODE_TEXT_PICKER_OPTION_SELECTED,
NODE_TEXT_PICKER_OPTION_VALUE, NODE_TEXT_PICKER_DISAPPEAR_TEXT_STYLE, NODE_TEXT_PICKER_TEXT_STYLE, NODE_TEXT_PICKER_SELECTED_TEXT_STYLE,
NODE_TEXT_PICKER_SELECTED_INDEX, NODE_TEXT_PICKER_CAN_LOOP, NODE_TEXT_PICKER_DEFAULT_PICKER_ITEM_HEIGHT,NODE_TEXT_PICKER_ENABLE_HAPTIC_FEEDBACK = 15010, NODE_CALENDAR_PICKER_HINT_RADIUS = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_CALENDAR_PICKER,
NODE_CALENDAR_PICKER_SELECTED_DATE, NODE_CALENDAR_PICKER_EDGE_ALIGNMENT, NODE_CALENDAR_PICKER_TEXT_STYLE, NODE_CALENDAR_PICKER_START = 16004, NODE_CALENDAR_PICKER_END = 16005,
NODE_CALENDAR_PICKER_DISABLED_DATE_RANGE = 16006, NODE_CALENDAR_PICKER_MARK_TODAY = 16007,
NODE_SLIDER_BLOCK_COLOR = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_SLIDER,
NODE_SLIDER_TRACK_COLOR, NODE_SLIDER_SELECTED_COLOR, NODE_SLIDER_SHOW_STEPS, NODE_SLIDER_BLOCK_STYLE,
NODE_SLIDER_VALUE, NODE_SLIDER_MIN_VALUE, NODE_SLIDER_MAX_VALUE, NODE_SLIDER_STEP,
NODE_SLIDER_DIRECTION, NODE_SLIDER_REVERSE, NODE_SLIDER_STYLE, NODE_SLIDER_TRACK_THICKNESS,NODE_SLIDER_ENABLE_HAPTIC_FEEDBACK = 17013,
NODE_RADIO_CHECKED = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_RADIO, NODE_RADIO_STYLE, NODE_RADIO_VALUE, NODE_RADIO_GROUP,
NODE_CHECKBOX_GROUP_NAME = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_CHECKBOX_GROUP, NODE_CHECKBOX_GROUP_SELECT_ALL, NODE_CHECKBOX_GROUP_SELECTED_COLOR, NODE_CHECKBOX_GROUP_UNSELECTED_COLOR, NODE_CHECKBOX_GROUP_MARK, NODE_CHECKBOX_GROUP_SHAPE,
NODE_STACK_ALIGN_CONTENT = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_STACK, NODE_SCROLL_BAR_DISPLAY_MODE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_SCROLL, NODE_SCROLL_BAR_WIDTH, NODE_SCROLL_BAR_COLOR,
NODE_SCROLL_SCROLL_DIRECTION, NODE_SCROLL_EDGE_EFFECT, NODE_SCROLL_ENABLE_SCROLL_INTERACTION, NODE_SCROLL_FRICTION,
NODE_SCROLL_SNAP, NODE_SCROLL_NESTED_SCROLL, NODE_SCROLL_OFFSET, NODE_SCROLL_EDGE,
NODE_SCROLL_ENABLE_PAGING, NODE_SCROLL_PAGE, NODE_SCROLL_BY, NODE_SCROLL_FLING,
NODE_SCROLL_FADING_EDGE, NODE_SCROLL_SIZE, NODE_SCROLL_CONTENT_END_OFFSET, NODE_SCROLL_CONTENT_START_OFFSET, NODE_LIST_DIRECTION = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_LIST, NODE_LIST_STICKY,
NODE_LIST_SPACE, NODE_LIST_NODE_ADAPTER, NODE_LIST_CACHED_COUNT, NODE_LIST_SCROLL_TO_INDEX,
NODE_LIST_ALIGN_LIST_ITEM, NODE_LIST_CHILDREN_MAIN_SIZE = 1003007, NODE_LIST_INITIAL_INDEX = 1003008, NODE_LIST_DIVIDER = 1003009, NODE_LIST_SCROLL_TO_INDEX_IN_GROUP = 1003010, NODE_LIST_LANES = 1003011, NODE_LIST_SCROLL_SNAP_ALIGN = 1003012, NODE_LIST_MAINTAIN_VISIBLE_CONTENT_POSITION = 1003013, NODE_LIST_STACK_FROM_END = 1003014,
NODE_SWIPER_LOOP = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_SWIPER, NODE_SWIPER_AUTO_PLAY, NODE_SWIPER_SHOW_INDICATOR, NODE_SWIPER_INTERVAL,
NODE_SWIPER_VERTICAL, NODE_SWIPER_DURATION, NODE_SWIPER_CURVE, NODE_SWIPER_ITEM_SPACE,
NODE_SWIPER_INDEX, NODE_SWIPER_DISPLAY_COUNT, NODE_SWIPER_DISABLE_SWIPE, NODE_SWIPER_SHOW_DISPLAY_ARROW,
NODE_SWIPER_EDGE_EFFECT_MODE, NODE_SWIPER_NODE_ADAPTER, NODE_SWIPER_CACHED_COUNT, NODE_SWIPER_PREV_MARGIN,
NODE_SWIPER_NEXT_MARGIN, NODE_SWIPER_INDICATOR, NODE_SWIPER_NESTED_SCROLL, NODE_SWIPER_SWIPE_TO_INDEX,
NODE_SWIPER_INDICATOR_INTERACTIVE, NODE_SWIPER_PAGE_FLIP_MODE, NODE_SWIPER_AUTO_FILL, NODE_LIST_ITEM_SWIPE_ACTION = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_LIST_ITEM, NODE_LIST_ITEM_GROUP_SET_HEADER = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_LIST_ITEM_GROUP,
NODE_LIST_ITEM_GROUP_SET_FOOTER, NODE_LIST_ITEM_GROUP_SET_DIVIDER, NODE_LIST_ITEM_GROUP_CHILDREN_MAIN_SIZE = 1005003, NODE_LIST_ITEM_GROUP_NODE_ADAPTER = 1005004, NODE_COLUMN_ALIGN_ITEMS = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_COLUMN,
NODE_COLUMN_JUSTIFY_CONTENT, NODE_ROW_ALIGN_ITEMS = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_ROW, NODE_ROW_JUSTIFY_CONTENT, NODE_FLEX_OPTION = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_FLEX,
NODE_REFRESH_REFRESHING = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_REFRESH, NODE_REFRESH_CONTENT, NODE_REFRESH_PULL_DOWN_RATIO = 1009002, NODE_REFRESH_OFFSET = 1009003,
NODE_REFRESH_PULL_TO_REFRESH = 1009004, NODE_WATER_FLOW_LAYOUT_DIRECTION = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_WATER_FLOW, NODE_WATER_FLOW_COLUMN_TEMPLATE, NODE_WATER_FLOW_ROW_TEMPLATE,
NODE_WATER_FLOW_COLUMN_GAP, NODE_WATER_FLOW_ROW_GAP, NODE_WATER_FLOW_SECTION_OPTION, NODE_WATER_FLOW_NODE_ADAPTER,
NODE_WATER_FLOW_CACHED_COUNT, NODE_WATER_FLOW_FOOTER, NODE_WATER_FLOW_SCROLL_TO_INDEX, NODE_WATER_FLOW_ITEM_CONSTRAINT_SIZE,
NODE_RELATIVE_CONTAINER_GUIDE_LINE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_RELATIVE_CONTAINER, NODE_RELATIVE_CONTAINER_BARRIER, NODE_GRID_COLUMN_TEMPLATE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_GRID, NODE_GRID_ROW_TEMPLATE,
NODE_GRID_COLUMN_GAP, NODE_GRID_ROW_GAP, NODE_GRID_NODE_ADAPTER, NODE_GRID_CACHED_COUNT, NODE_TEXT_PICKER_COLUMN_WIDTHS = 15009,
NODE_IMAGE_ANIMATOR_IMAGES = ARKUI_NODE_IMAGE_ANIMATOR \* MAX_NODE_SCOPE_NUM, NODE_IMAGE_ANIMATOR_STATE, NODE_IMAGE_ANIMATOR_DURATION, NODE_IMAGE_ANIMATOR_REVERSE,
NODE_IMAGE_ANIMATOR_FIXED_SIZE, NODE_IMAGE_ANIMATOR_FILL_MODE, NODE_IMAGE_ANIMATOR_ITERATION
} | Defines the ArkUI style attributes that can be set on the native side. | +| [ArkUI_NodeEventType](#arkui_nodeeventtype) {
NODE_TOUCH_EVENT = 0, NODE_EVENT_ON_APPEAR, NODE_EVENT_ON_DISAPPEAR, NODE_EVENT_ON_AREA_CHANGE,
NODE_ON_FOCUS, NODE_ON_BLUR, NODE_ON_CLICK, NODE_ON_TOUCH_INTERCEPT,
NODE_EVENT_ON_VISIBLE_AREA_CHANGE, NODE_ON_HOVER, NODE_ON_MOUSE, NODE_EVENT_ON_ATTACH,
NODE_EVENT_ON_DETACH, NODE_ON_ACCESSIBILITY_ACTIONS = 13, NODE_ON_PRE_DRAG = 14, NODE_ON_DRAG_START = 15,
NODE_ON_DRAG_ENTER = 16, NODE_ON_DRAG_MOVE = 17, NODE_ON_DRAG_LEAVE = 18, NODE_ON_DROP = 19,
NODE_ON_DRAG_END = 20, NODE_ON_KEY_EVENT = 21, NODE_ON_KEY_PRE_IME = 22, NODE_DISPATCH_KEY_EVENT = 24, NODE_ON_AXIS = 25, NODE_ON_CLICK_EVENT = 26, NODE_ON_HOVER_EVENT = 27, NODE_VISIBLE_AREA_APPROXIMATE_CHANGE_EVENT = 28, NODE_TEXT_ON_DETECT_RESULT_UPDATE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_TEXT,
NODE_IMAGE_ON_COMPLETE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_IMAGE, NODE_IMAGE_ON_ERROR, NODE_IMAGE_ON_SVG_PLAY_FINISH, NODE_IMAGE_ON_DOWNLOAD_PROGRESS,
NODE_TOGGLE_ON_CHANGE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_TOGGLE, NODE_TEXT_INPUT_ON_CHANGE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_TEXT_INPUT, NODE_TEXT_INPUT_ON_SUBMIT, NODE_TEXT_INPUT_ON_CUT,
NODE_TEXT_INPUT_ON_PASTE, NODE_TEXT_INPUT_ON_TEXT_SELECTION_CHANGE, NODE_TEXT_INPUT_ON_EDIT_CHANGE, NODE_TEXT_INPUT_ON_INPUT_FILTER_ERROR,
NODE_TEXT_INPUT_ON_CONTENT_SCROLL, NODE_TEXT_INPUT_ON_CONTENT_SIZE_CHANGE, NODE_TEXT_INPUT_ON_WILL_INSERT = 7009, NODE_TEXT_INPUT_ON_DID_INSERT = 7010,
NODE_TEXT_INPUT_ON_WILL_DELETE = 7011, NODE_TEXT_INPUT_ON_DID_DELETE = 7012, NODE_TEXT_INPUT_ON_CHANGE_WITH_PREVIEW_TEXT = 7013, NODE_TEXT_AREA_ON_CHANGE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_TEXT_AREA, NODE_TEXT_AREA_ON_PASTE,
NODE_TEXT_AREA_ON_TEXT_SELECTION_CHANGE, NODE_TEXT_AREA_ON_EDIT_CHANGE, NODE_TEXT_AREA_ON_SUBMIT, NODE_TEXT_AREA_ON_INPUT_FILTER_ERROR,
NODE_TEXT_AREA_ON_CONTENT_SCROLL, NODE_TEXT_AREA_ON_CONTENT_SIZE_CHANGE, NODE_TEXT_AREA_ON_WILL_INSERT = 8008, NODE_TEXT_AREA_ON_DID_INSERT = 8009,
NODE_TEXT_AREA_ON_WILL_DELETE = 8010, NODE_TEXT_AREA_ON_DID_DELETE = 8011, NODE_TEXT_AREA_ON_CHANGE_WITH_PREVIEW_TEXT = 8012, NODE_CHECKBOX_EVENT_ON_CHANGE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_CHECKBOX, NODE_DATE_PICKER_EVENT_ON_DATE_CHANGE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_DATE_PICKER,
NODE_TIME_PICKER_EVENT_ON_CHANGE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_TIME_PICKER, NODE_TEXT_PICKER_EVENT_ON_CHANGE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_TEXT_PICKER, NODE_CALENDAR_PICKER_EVENT_ON_CHANGE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_CALENDAR_PICKER, NODE_SLIDER_EVENT_ON_CHANGE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_SLIDER,
NODE_RADIO_EVENT_ON_CHANGE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_RADIO, NODE_IMAGE_ANIMATOR_EVENT_ON_START = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_IMAGE_ANIMATOR, NODE_IMAGE_ANIMATOR_EVENT_ON_PAUSE, NODE_IMAGE_ANIMATOR_EVENT_ON_REPEAT,
NODE_IMAGE_ANIMATOR_EVENT_ON_CANCEL, NODE_IMAGE_ANIMATOR_EVENT_ON_FINISH,
NODE_CHECKBOX_GROUP_EVENT_ON_CHANGE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_CHECKBOX_GROUP,
NODE_SWIPER_EVENT_ON_CHANGE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_SWIPER, NODE_SWIPER_EVENT_ON_ANIMATION_START,
NODE_SWIPER_EVENT_ON_ANIMATION_END, NODE_SWIPER_EVENT_ON_GESTURE_SWIPE, NODE_SWIPER_EVENT_ON_CONTENT_DID_SCROLL, NODE_SWIPER_EVENT_ON_SELECTED = 1001005, NODE_SWIPER_EVENT_ON_UNSELECTED = 1001006, NODE_SWIPER_EVENT_ON_CONTENT_WILL_SCROLL = 1001007, NODE_SCROLL_EVENT_ON_SCROLL = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_SCROLL,
NODE_SCROLL_EVENT_ON_SCROLL_FRAME_BEGIN, NODE_SCROLL_EVENT_ON_WILL_SCROLL, NODE_SCROLL_EVENT_ON_DID_SCROLL, NODE_SCROLL_EVENT_ON_SCROLL_START,
NODE_SCROLL_EVENT_ON_SCROLL_STOP, NODE_SCROLL_EVENT_ON_SCROLL_EDGE, NODE_SCROLL_EVENT_ON_REACH_START, NODE_SCROLL_EVENT_ON_REACH_END,
NODE_LIST_ON_SCROLL_INDEX = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_LIST, NODE_LIST_ON_WILL_SCROLL, NODE_LIST_ON_DID_SCROLL, NODE_LIST_ON_SCROLL_VISIBLE_CONTENT_CHANGE, NODE_REFRESH_STATE_CHANGE = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_REFRESH,
NODE_REFRESH_ON_REFRESH, NODE_REFRESH_ON_OFFSET_CHANGE, NODE_ON_WILL_SCROLL = MAX_NODE_SCOPE_NUM \* ARKUI_NODE_WATER_FLOW, NODE_WATER_FLOW_ON_DID_SCROLL,
NODE_WATER_FLOW_ON_SCROLL_INDEX
} | Enumerates the event types supported by the NativeNode component. | +| [ArkUI_NodeDirtyFlag](#arkui_nodedirtyflag) { NODE_NEED_MEASURE = 1, NODE_NEED_LAYOUT, NODE_NEED_RENDER } | Enumerates the dirty area flags passed in the **::markDirty** API. | +| [ArkUI_NodeCustomEventType](#arkui_nodecustomeventtype) {
ARKUI_NODE_CUSTOM_EVENT_ON_MEASURE = 1 << 0, ARKUI_NODE_CUSTOM_EVENT_ON_LAYOUT = 1 << 1, ARKUI_NODE_CUSTOM_EVENT_ON_DRAW = 1 << 2, ARKUI_NODE_CUSTOM_EVENT_ON_FOREGROUND_DRAW = 1 << 3,
ARKUI_NODE_CUSTOM_EVENT_ON_OVERLAY_DRAW = 1 << 4
} | Enumerates the custom component event types. | +| [ArkUI_NodeAdapterEventType](#arkui_nodeadaptereventtype) {
NODE_ADAPTER_EVENT_WILL_ATTACH_TO_NODE = 1, NODE_ADAPTER_EVENT_WILL_DETACH_FROM_NODE = 2, NODE_ADAPTER_EVENT_ON_GET_NODE_ID = 3, NODE_ADAPTER_EVENT_ON_ADD_NODE_TO_ADAPTER = 4,
NODE_ADAPTER_EVENT_ON_REMOVE_NODE_FROM_ADAPTER = 5
} | Enumerates node adapter events. | +| [ArkUI_NodeContentEventType](#arkui_nodecontenteventtype) { NODE_CONTENT_EVENT_ON_ATTACH_TO_WINDOW = 0, NODE_CONTENT_EVENT_ON_DETACH_FROM_WINDOW = 1 } | Defines the NodeContent event type. | +| [ArkUI_Alignment](#arkui_alignment) {
ARKUI_ALIGNMENT_TOP_START = 0, ARKUI_ALIGNMENT_TOP, ARKUI_ALIGNMENT_TOP_END, ARKUI_ALIGNMENT_START,
ARKUI_ALIGNMENT_CENTER, ARKUI_ALIGNMENT_END, ARKUI_ALIGNMENT_BOTTOM_START, ARKUI_ALIGNMENT_BOTTOM,
ARKUI_ALIGNMENT_BOTTOM_END
} | Enumerates the alignment modes. | +| [ArkUI_ImageRepeat](#arkui_imagerepeat) { ARKUI_IMAGE_REPEAT_NONE = 0, ARKUI_IMAGE_REPEAT_X, ARKUI_IMAGE_REPEAT_Y, ARKUI_IMAGE_REPEAT_XY } | Enumerates the image repeat patterns. | +| [ArkUI_FontStyle](#arkui_fontstyle) { ARKUI_FONT_STYLE_NORMAL = 0, ARKUI_FONT_STYLE_ITALIC } | Enumerates the font styles. | +| [ArkUI_FontWeight](#arkui_fontweight) {
ARKUI_FONT_WEIGHT_W100 = 0, ARKUI_FONT_WEIGHT_W200, ARKUI_FONT_WEIGHT_W300, ARKUI_FONT_WEIGHT_W400,
ARKUI_FONT_WEIGHT_W500, ARKUI_FONT_WEIGHT_W600, ARKUI_FONT_WEIGHT_W700, ARKUI_FONT_WEIGHT_W800,
ARKUI_FONT_WEIGHT_W900, ARKUI_FONT_WEIGHT_BOLD, ARKUI_FONT_WEIGHT_NORMAL, ARKUI_FONT_WEIGHT_BOLDER,
ARKUI_FONT_WEIGHT_LIGHTER, ARKUI_FONT_WEIGHT_MEDIUM, ARKUI_FONT_WEIGHT_REGULAR
} | Enumerates the font weights. | +| [ArkUI_TextAlignment](#arkui_textalignment) { ARKUI_TEXT_ALIGNMENT_START = 0, ARKUI_TEXT_ALIGNMENT_CENTER, ARKUI_TEXT_ALIGNMENT_END, ARKUI_TEXT_ALIGNMENT_JUSTIFY } | Enumerates the text alignment mode. | +| [ArkUI_EnterKeyType](#arkui_enterkeytype) {
ARKUI_ENTER_KEY_TYPE_GO = 2, ARKUI_ENTER_KEY_TYPE_SEARCH = 3, ARKUI_ENTER_KEY_TYPE_SEND, ARKUI_ENTER_KEY_TYPE_NEXT,
ARKUI_ENTER_KEY_TYPE_DONE, ARKUI_ENTER_KEY_TYPE_PREVIOUS, ARKUI_ENTER_KEY_TYPE_NEW_LINE
} | Enumerates the types of the Enter key for a single-line text box. | +| [ArkUI_TextInputType](#arkui_textinputtype) {
ARKUI_TEXTINPUT_TYPE_NORMAL = 0, ARKUI_TEXTINPUT_TYPE_NUMBER = 2, ARKUI_TEXTINPUT_TYPE_PHONE_NUMBER = 3, ARKUI_TEXTINPUT_TYPE_EMAIL = 5,
ARKUI_TEXTINPUT_TYPE_PASSWORD = 7, ARKUI_TEXTINPUT_TYPE_NUMBER_PASSWORD = 8, ARKUI_TEXTINPUT_TYPE_SCREEN_LOCK_PASSWORD = 9, ARKUI_TEXTINPUT_TYPE_USER_NAME = 10,
ARKUI_TEXTINPUT_TYPE_NEW_PASSWORD = 11, ARKUI_TEXTINPUT_TYPE_NUMBER_DECIMAL = 12
} | Enumerates the text input types. | +| [ArkUI_TextAreaType](#arkui_textareatype) { ARKUI_TEXTAREA_TYPE_NORMAL = 0, ARKUI_TEXTAREA_TYPE_NUMBER = 2, ARKUI_TEXTAREA_TYPE_PHONE_NUMBER = 3, ARKUI_TEXTAREA_TYPE_EMAIL = 5 } | Enumerates the text box types. | +| [ArkUI_CancelButtonStyle](#arkui_cancelbuttonstyle) { ARKUI_CANCELBUTTON_STYLE_CONSTANT = 0, ARKUI_CANCELBUTTON_STYLE_INVISIBLE, ARKUI_CANCELBUTTON_STYLE_INPUT } | Enumerates the styles of the Cancel button. | +| [ArkUI_XComponentType](#arkui_xcomponenttype) { ARKUI_XCOMPONENT_TYPE_SURFACE = 0, ARKUI_XCOMPONENT_TYPE_TEXTURE = 2 } | Defines the enumerated values of the XComponent type. | +| [ArkUI_ProgressType](#arkui_progresstype) {
ARKUI_PROGRESS_TYPE_LINEAR = 0, ARKUI_PROGRESS_TYPE_RING, ARKUI_PROGRESS_TYPE_ECLIPSE, ARKUI_PROGRESS_TYPE_SCALE_RING,
ARKUI_PROGRESS_TYPE_CAPSULE
} | Enumerates the styles of the progress indicator. | +| [ArkUI_TextDecorationType](#arkui_textdecorationtype) { ARKUI_TEXT_DECORATION_TYPE_NONE = 0, ARKUI_TEXT_DECORATION_TYPE_UNDERLINE, ARKUI_TEXT_DECORATION_TYPE_OVERLINE, ARKUI_TEXT_DECORATION_TYPE_LINE_THROUGH } | Enumerates the text decoration types. | +| [ArkUI_TextDecorationStyle](#arkui_textdecorationstyle) {
ARKUI_TEXT_DECORATION_STYLE_SOLID = 0, ARKUI_TEXT_DECORATION_STYLE_DOUBLE, ARKUI_TEXT_DECORATION_STYLE_DOTTED, ARKUI_TEXT_DECORATION_STYLE_DASHED,
ARKUI_TEXT_DECORATION_STYLE_WAVY
} | Enumerates the text decoration styles. | +| [ArkUI_TextCase](#arkui_textcase) { ARKUI_TEXT_CASE_NORMAL = 0, ARKUI_TEXT_CASE_LOWER, ARKUI_TEXT_CASE_UPPER } | Defines the enumerated values of text case. | +| [ArkUI_CopyOptions](#arkui_copyoptions) { ARKUI_COPY_OPTIONS_NONE = 0, ARKUI_COPY_OPTIONS_IN_APP, ARKUI_COPY_OPTIONS_LOCAL_DEVICE, ARKUI_COPY_OPTIONS_CROSS_DEVICE } | Enumerates the text copy and paste modes. | +| [ArkUI_ShadowType](#arkui_shadowtype) { ARKUI_SHADOW_TYPE_COLOR = 0, ARKUI_SHADOW_TYPE_BLUR } | Defines the enumerated values of the shadow type. | +| [ArkUI_TextPickerRangeType](#arkui_textpickerrangetype) { ARKUI_TEXTPICKER_RANGETYPE_SINGLE = 0, ARKUI_TEXTPICKER_RANGETYPE_MULTI, ARKUI_TEXTPICKER_RANGETYPE_RANGE_CONTENT, ARKUI_TEXTPICKER_RANGETYPE_CASCADE_RANGE_CONTENT } | Enumerates the types of the text picker. | +| [ArkUI_AccessibilityCheckedState](#arkui_accessibilitycheckedstate) { ARKUI_ACCESSIBILITY_UNCHECKED = 0, ARKUI_ACCESSIBILITY_CHECKED } | Enumerates the accessibility check box states. | +| [ArkUI_AccessibilityActionType](#arkui_accessibilityactiontype) {
ARKUI_ACCESSIBILITY_ACTION_CLICK = 1 << 0, ARKUI_ACCESSIBILITY_ACTION_LONG_CLICK = 1 << 1, ARKUI_ACCESSIBILITY_ACTION_CUT = 1 << 2, ARKUI_ACCESSIBILITY_ACTION_COPY = 1 << 3,
ARKUI_ACCESSIBILITY_ACTION_PASTE = 1 << 4
} | Defines an enum for the accessibility action types. | +| [ArkUI_EdgeEffect](#arkui_edgeeffect) { ARKUI_EDGE_EFFECT_SPRING = 0, ARKUI_EDGE_EFFECT_FADE, ARKUI_EDGE_EFFECT_NONE } | Enumerates the effects used at the edges of the component when the boundary of the scrollable content is reached. | | [ArkUI_EffectEdge](#arkui_effectedge) { ARKUI_EFFECT_EDGE_START = 1, ARKUI_EFFECT_EDGE_END = 2 } | Enumerates the edges for which the effect takes effect when the boundary of the scrollable content is reached. | -| [ArkUI_ScrollDirection](#arkui_scrolldirection) { ARKUI_SCROLL_DIRECTION_VERTICAL = 0, ARKUI_SCROLL_DIRECTION_HORIZONTAL, ARKUI_SCROLL_DIRECTION_NONE = 3 } | Enumerates the scroll directions of scrollable components. | -| [ArkUI_ScrollSnapAlign](#arkui_scrollsnapalign) { ARKUI_SCROLL_SNAP_ALIGN_NONE = 0, ARKUI_SCROLL_SNAP_ALIGN_START, ARKUI_SCROLL_SNAP_ALIGN_CENTER, ARKUI_SCROLL_SNAP_ALIGN_END } | Enumerates the alignment modes of list items when scrolling ends. | -| [ArkUI_ScrollBarDisplayMode](#arkui_scrollbardisplaymode) { ARKUI_SCROLL_BAR_DISPLAY_MODE_OFF = 0, ARKUI_SCROLL_BAR_DISPLAY_MODE_AUTO, ARKUI_SCROLL_BAR_DISPLAY_MODE_ON } | Enumerates the scrollbar display modes. | -| [ArkUI_Axis](#arkui_axis) { ARKUI_AXIS_VERTICAL = 0, ARKUI_AXIS_HORIZONTAL } | Enumerates the scroll directions. | -| [ArkUI_StickyStyle](#arkui_stickystyle) { ARKUI_STICKY_STYLE_NONE = 0, ARKUI_STICKY_STYLE_HEADER = 1, ARKUI_STICKY_STYLE_FOOTER = 2, ARKUI_STICKY_STYLE_BOTH = 3 } | Enumerates the modes for pinning the header to the top or the footer to the bottom. | -| [ArkUI_BorderStyle](#arkui_borderstyle) { ARKUI_BORDER_STYLE_SOLID = 0, ARKUI_BORDER_STYLE_DASHED, ARKUI_BORDER_STYLE_DOTTED } | Enumerates the border styles. | -| [ArkUI_HitTestMode](#arkui_hittestmode) { ARKUI_HIT_TEST_MODE_DEFAULT = 0, ARKUI_HIT_TEST_MODE_BLOCK, ARKUI_HIT_TEST_MODE_TRANSPARENT, ARKUI_HIT_TEST_MODE_NONE } | Enumerates the hit test modes. | -| [ArkUI_ShadowStyle](#arkui_shadowstyle) {
ARKUI_SHADOW_STYLE_OUTER_DEFAULT_XS = 0, ARKUI_SHADOW_STYLE_OUTER_DEFAULT_SM, ARKUI_SHADOW_STYLE_OUTER_DEFAULT_MD, ARKUI_SHADOW_STYLE_OUTER_DEFAULT_LG,
ARKUI_SHADOW_STYLE_OUTER_FLOATING_SM, ARKUI_SHADOW_STYLE_OUTER_FLOATING_MD
} | Enumerated value of the shadow effect. | -| [ArkUI_AnimationCurve](#arkui_animationcurve) {
ARKUI_CURVE_LINEAR = 0, ARKUI_CURVE_EASE, ARKUI_CURVE_EASE_IN, ARKUI_CURVE_EASE_OUT,
ARKUI_CURVE_EASE_IN_OUT, ARKUI_CURVE_FAST_OUT_SLOW_IN, ARKUI_CURVE_LINEAR_OUT_SLOW_IN, ARKUI_CURVE_FAST_OUT_LINEAR_IN,
ARKUI_CURVE_EXTREME_DECELERATION, ARKUI_CURVE_SHARP, ARKUI_CURVE_RHYTHM, ARKUI_CURVE_SMOOTH,
ARKUI_CURVE_FRICTION
} | Enumerates the animation curves. | -| [ArkUI_SwiperArrow](#arkui_swiperarrow) { ARKUI_SWIPER_ARROW_HIDE = 0, ARKUI_SWIPER_ARROW_SHOW, ARKUI_SWIPER_ARROW_SHOW_ON_HOVER } | Enumerates arrow styles of the navigation point indicator. | -| [ArkUI_SwiperNestedScrollMode](#arkui_swipernestedscrollmode) { ARKUI_SWIPER_NESTED_SRCOLL_SELF_ONLY = 0, ARKUI_SWIPER_NESTED_SRCOLL_SELF_FIRST } | Enumerates the nested scrolling mode of the **Swiper** component and its parent container. | -| [ArkUI_PageFlipMode](#arkui_pageflipmode) { ARKUI_PAGE_FLIP_MODE_CONTINUOUS = 0, ARKUI_PAGE_FLIP_MODE_SINGLE } | Enumerates the page flipping modes using the mouse wheel for the **Swiper** component. | +| [ArkUI_ScrollDirection](#arkui_scrolldirection) { ARKUI_SCROLL_DIRECTION_VERTICAL = 0, ARKUI_SCROLL_DIRECTION_HORIZONTAL, ARKUI_SCROLL_DIRECTION_NONE = 3 } | Enumerates the scroll directions of scrollable components. | +| [ArkUI_ScrollSnapAlign](#arkui_scrollsnapalign) { ARKUI_SCROLL_SNAP_ALIGN_NONE = 0, ARKUI_SCROLL_SNAP_ALIGN_START, ARKUI_SCROLL_SNAP_ALIGN_CENTER, ARKUI_SCROLL_SNAP_ALIGN_END } | Enumerates the alignment modes of list items when scrolling ends. | +| [ArkUI_ScrollBarDisplayMode](#arkui_scrollbardisplaymode) { ARKUI_SCROLL_BAR_DISPLAY_MODE_OFF = 0, ARKUI_SCROLL_BAR_DISPLAY_MODE_AUTO, ARKUI_SCROLL_BAR_DISPLAY_MODE_ON } | Enumerates the scrollbar display modes. | +| [ArkUI_Axis](#arkui_axis) { ARKUI_AXIS_VERTICAL = 0, ARKUI_AXIS_HORIZONTAL } | Enumerates the scroll directions. | +| [ArkUI_StickyStyle](#arkui_stickystyle) { ARKUI_STICKY_STYLE_NONE = 0, ARKUI_STICKY_STYLE_HEADER = 1, ARKUI_STICKY_STYLE_FOOTER = 2, ARKUI_STICKY_STYLE_BOTH = 3 } | Enumerates the modes for pinning the header to the top or the footer to the bottom. | +| [ArkUI_BorderStyle](#arkui_borderstyle) { ARKUI_BORDER_STYLE_SOLID = 0, ARKUI_BORDER_STYLE_DASHED, ARKUI_BORDER_STYLE_DOTTED } | Enumerates the border styles. | +| [ArkUI_HitTestMode](#arkui_hittestmode) { ARKUI_HIT_TEST_MODE_DEFAULT = 0, ARKUI_HIT_TEST_MODE_BLOCK, ARKUI_HIT_TEST_MODE_TRANSPARENT, ARKUI_HIT_TEST_MODE_NONE } | Enumerates the hit test modes. | +| [ArkUI_ShadowStyle](#arkui_shadowstyle) {
ARKUI_SHADOW_STYLE_OUTER_DEFAULT_XS = 0, ARKUI_SHADOW_STYLE_OUTER_DEFAULT_SM, ARKUI_SHADOW_STYLE_OUTER_DEFAULT_MD, ARKUI_SHADOW_STYLE_OUTER_DEFAULT_LG,
ARKUI_SHADOW_STYLE_OUTER_FLOATING_SM, ARKUI_SHADOW_STYLE_OUTER_FLOATING_MD
} | Enumerated value of the shadow effect. | +| [ArkUI_AnimationCurve](#arkui_animationcurve) {
ARKUI_CURVE_LINEAR = 0, ARKUI_CURVE_EASE, ARKUI_CURVE_EASE_IN, ARKUI_CURVE_EASE_OUT,
ARKUI_CURVE_EASE_IN_OUT, ARKUI_CURVE_FAST_OUT_SLOW_IN, ARKUI_CURVE_LINEAR_OUT_SLOW_IN, ARKUI_CURVE_FAST_OUT_LINEAR_IN,
ARKUI_CURVE_EXTREME_DECELERATION, ARKUI_CURVE_SHARP, ARKUI_CURVE_RHYTHM, ARKUI_CURVE_SMOOTH,
ARKUI_CURVE_FRICTION
} | Enumerates the animation curves. | +| [ArkUI_SwiperArrow](#arkui_swiperarrow) { ARKUI_SWIPER_ARROW_HIDE = 0, ARKUI_SWIPER_ARROW_SHOW, ARKUI_SWIPER_ARROW_SHOW_ON_HOVER } | Enumerates arrow styles of the navigation indicator. | +| [ArkUI_SwiperNestedScrollMode](#arkui_swipernestedscrollmode) { ARKUI_SWIPER_NESTED_SRCOLL_SELF_ONLY = 0, ARKUI_SWIPER_NESTED_SRCOLL_SELF_FIRST } | Enumerates the nested scrolling mode of the **Swiper** component and its parent container. | +| [ArkUI_PageFlipMode](#arkui_pageflipmode) { ARKUI_PAGE_FLIP_MODE_CONTINUOUS = 0, ARKUI_PAGE_FLIP_MODE_SINGLE } | Enumerates the page flipping modes using the mouse wheel for the Swiper component. | | [ArkUI_SwiperAnimationMode](#arkui_swiperanimationmode) { ARKUI_SWIPER_NO_ANIMATION = 0, ARKUI_SWIPER_DEFAULT_ANIMATION, ARKUI_SWIPER_FAST_ANIMATION } | Enumerates the animation modes for the **Swiper** component when jumping to the page with the specified index. | -| [ArkUI_AccessibilityMode](#arkui_accessibilitymode) { ARKUI_ACCESSIBILITY_MODE_AUTO = 0, ARKUI_ACCESSIBILITY_MODE_ENABLED, ARKUI_ACCESSIBILITY_MODE_DISABLED, ARKUI_ACCESSIBILITY_MODE_DISABLED_FOR_DESCENDANTS } | Enumerates the accessibility modes. | -| [ArkUI_TextCopyOptions](#arkui_textcopyoptions) { ARKUI_TEXT_COPY_OPTIONS_NONE = 0, ARKUI_TEXT_COPY_OPTIONS_IN_APP, ARKUI_TEXT_COPY_OPTIONS_LOCAL_DEVICE, ARKUI_TEXT_COPY_OPTIONS_CROSS_DEVICE } | Enumerates copy options, which define whether copy and paste is allowed for text content. | -| [ArkUI_TextHeightAdaptivePolicy](#arkui_textheightadaptivepolicy) { ARKUI_TEXT_HEIGHT_ADAPTIVE_POLICY_MAX_LINES_FIRST = 0, ARKUI_TEXT_HEIGHT_ADAPTIVE_POLICY_MIN_FONT_SIZE_FIRST, ARKUI_TEXT_HEIGHT_ADAPTIVE_POLICY_LAYOUT_CONSTRAINT_FIRST } | Defines how the adaptive height is determined for the text. | -| [ArkUI_ScrollNestedMode](#arkui_scrollnestedmode) { ARKUI_SCROLL_NESTED_MODE_SELF_ONLY = 0, ARKUI_SCROLL_NESTED_MODE_SELF_FIRST, ARKUI_SCROLL_NESTED_MODE_PARENT_FIRST, ARKUI_SCROLL_NESTED_MODE_PARALLEL } | Enumerates the nested scrolling modes. | -| [ArkUI_ScrollEdge](#arkui_scrolledge) { ARKUI_SCROLL_EDGE_TOP = 0, ARKUI_SCROLL_EDGE_BOTTOM, ARKUI_SCROLL_EDGE_START, ARKUI_SCROLL_EDGE_END } | Defines the edge to which the component scrolls. | -| [ArkUI_ScrollAlignment](#arkui_scrollalignment) { ARKUI_SCROLL_ALIGNMENT_START = 0, ARKUI_SCROLL_ALIGNMENT_CENTER, ARKUI_SCROLL_ALIGNMENT_END, ARKUI_SCROLL_ALIGNMENT_AUTO } | Defines how the list item to scroll to is aligned with the container. | -| [ArkUI_ScrollState](#arkui_scrollstate) { ARKUI_SCROLL_STATE_IDLE = 0, ARKUI_SCROLL_STATE_SCROLL, ARKUI_SCROLL_STATE_FLING } | Enumerates the scrolling states. | -| [ArkUI_SliderBlockStyle](#arkui_sliderblockstyle) { ARKUI_SLIDER_BLOCK_STYLE_DEFAULT = 0, ARKUI_SLIDER_BLOCK_STYLE_IMAGE, ARKUI_SLIDER_BLOCK_STYLE_SHAPE } | Enumerates the styles of the slider in the block direction. | -| [ArkUI_SliderDirection](#arkui_sliderdirection) { ARKUI_SLIDER_DIRECTION_VERTICAL = 0, ARKUI_SLIDER_DIRECTION_HORIZONTAL } | Enumerates the scroll directions of the slider. | -| [ArkUI_SliderStyle](#arkui_sliderstyle) { ARKUI_SLIDER_STYLE_OUT_SET = 0, ARKUI_SLIDER_STYLE_IN_SET, ARKUI_SLIDER_STYLE_NONE } | Enumerates the slider styles. | -| [ArkUI_CheckboxShape](#arkui_checkboxshape) { ArkUI_CHECKBOX_SHAPE_CIRCLE = 0, ArkUI_CHECKBOX_SHAPE_ROUNDED_SQUARE } | Enumerates the shapes of the check box. | -| [ArkUI_AnimationPlayMode](#arkui_animationplaymode) { ARKUI_ANIMATION_PLAY_MODE_NORMAL = 0, ARKUI_ANIMATION_PLAY_MODE_REVERSE, ARKUI_ANIMATION_PLAY_MODE_ALTERNATE, ARKUI_ANIMATION_PLAY_MODE_ALTERNATE_REVERSE } | Enumerates the animation playback modes. | -| [ArkUI_ImageSize](#arkui_imagesize) { ARKUI_IMAGE_SIZE_AUTO = 0, ARKUI_IMAGE_SIZE_COVER, ARKUI_IMAGE_SIZE_CONTAIN } | Defines the image size. | -| [ArkUI_AdaptiveColor](#arkui_adaptivecolor) { ARKUI_ADAPTIVE_COLOR_DEFAULT = 0, ARKUI_ADAPTIVE_COLOR_AVERAGE } | Enumerates the adaptive color modes. | -| [ArkUI_ColorMode](#arkui_colormode) { ARKUI_COLOR_MODE_SYSTEM = 0, ARKUI_COLOR_MODE_LIGHT, ARKUI_COLOR_MODE_DARK } | Enumerates the color modes. | -| [ArkUI_SystemColorMode](#arkui_systemcolormode) { ARKUI_SYSTEM_COLOR_MODE_LIGHT = 0, ARKUI_SYSTEM_COLOR_MODE_DARK } | Enumerates the system color modes. | -| [ArkUI_BlurStyle](#arkui_blurstyle) {
ARKUI_BLUR_STYLE_THIN = 0, ARKUI_BLUR_STYLE_REGULAR, ARKUI_BLUR_STYLE_THICK, ARKUI_BLUR_STYLE_BACKGROUND_THIN,
ARKUI_BLUR_STYLE_BACKGROUND_REGULAR, ARKUI_BLUR_STYLE_BACKGROUND_THICK, ARKUI_BLUR_STYLE_BACKGROUND_ULTRA_THICK, ARKUI_BLUR_STYLE_NONE,
ARKUI_BLUR_STYLE_COMPONENT_ULTRA_THIN, ARKUI_BLUR_STYLE_COMPONENT_THIN, ARKUI_BLUR_STYLE_COMPONENT_REGULAR, ARKUI_BLUR_STYLE_COMPONENT_THICK,
ARKUI_BLUR_STYLE_COMPONENT_ULTRA_THICK
} | Enumerates the blur styles. | -| [ArkUI_VerticalAlignment](#arkui_verticalalignment) { ARKUI_VERTICAL_ALIGNMENT_TOP = 0, ARKUI_VERTICAL_ALIGNMENT_CENTER, ARKUI_VERTICAL_ALIGNMENT_BOTTOM } | Enumerates the vertical alignment modes. | -| [ArkUI_HorizontalAlignment](#arkui_horizontalalignment) { ARKUI_HORIZONTAL_ALIGNMENT_START = 0, ARKUI_HORIZONTAL_ALIGNMENT_CENTER, ARKUI_HORIZONTAL_ALIGNMENT_END } | Enumerates the alignment mode in the horizontal direction. | -| [ArkUI_TextOverflow](#arkui_textoverflow) { ARKUI_TEXT_OVERFLOW_NONE = 0, ARKUI_TEXT_OVERFLOW_CLIP, ARKUI_TEXT_OVERFLOW_ELLIPSIS, ARKUI_TEXT_OVERFLOW_MARQUEE } | Enumerates the display modes when the text is too long. | -| [ArkUI_ImageSpanAlignment](#arkui_imagespanalignment) { ARKUI_IMAGE_SPAN_ALIGNMENT_BASELINE = 0, ARKUI_IMAGE_SPAN_ALIGNMENT_BOTTOM, ARKUI_IMAGE_SPAN_ALIGNMENT_CENTER, ARKUI_IMAGE_SPAN_ALIGNMENT_TOP } | Enumerates the alignment mode of the image with the text. | -| [ArkUI_ObjectFit](#arkui_objectfit) {
ARKUI_OBJECT_FIT_CONTAIN = 0, ARKUI_OBJECT_FIT_COVER, ARKUI_OBJECT_FIT_AUTO, ARKUI_OBJECT_FIT_FILL,
ARKUI_OBJECT_FIT_SCALE_DOWN, ARKUI_OBJECT_FIT_NONE, ARKUI_OBJECT_FIT_NONE_AND_ALIGN_TOP_START, ARKUI_OBJECT_FIT_NONE_AND_ALIGN_TOP,
ARKUI_OBJECT_FIT_NONE_AND_ALIGN_TOP_END, ARKUI_OBJECT_FIT_NONE_AND_ALIGN_START, ARKUI_OBJECT_FIT_NONE_AND_ALIGN_CENTER, ARKUI_OBJECT_FIT_NONE_AND_ALIGN_END,
ARKUI_OBJECT_FIT_NONE_AND_ALIGN_BOTTOM_START, ARKUI_OBJECT_FIT_NONE_AND_ALIGN_BOTTOM, ARKUI_OBJECT_FIT_NONE_AND_ALIGN_BOTTOM_END
} | Enumerates the image filling effects. | -| [ArkUI_ImageInterpolation](#arkui_imageinterpolation) { ARKUI_IMAGE_INTERPOLATION_NONE = 0, ARKUI_IMAGE_INTERPOLATION_LOW, ARKUI_IMAGE_INTERPOLATION_MEDIUM, ARKUI_IMAGE_INTERPOLATION_HIGH } | Enumerates the image interpolation effects. | -| [ArkUI_BlendMode](#arkui_blendmode) {
ARKUI_BLEND_MODE_NONE = 0, ARKUI_BLEND_MODE_CLEAR, ARKUI_BLEND_MODE_SRC, ARKUI_BLEND_MODE_DST,
ARKUI_BLEND_MODE_SRC_OVER, ARKUI_BLEND_MODE_DST_OVER, ARKUI_BLEND_MODE_SRC_IN, ARKUI_BLEND_MODE_DST_IN,
ARKUI_BLEND_MODE_SRC_OUT, ARKUI_BLEND_MODE_DST_OUT, ARKUI_BLEND_MODE_SRC_ATOP, ARKUI_BLEND_MODE_DST_ATOP,
ARKUI_BLEND_MODE_XOR, ARKUI_BLEND_MODE_PLUS, ARKUI_BLEND_MODE_MODULATE, ARKUI_BLEND_MODE_SCREEN,
ARKUI_BLEND_MODE_OVERLAY, ARKUI_BLEND_MODE_DARKEN, ARKUI_BLEND_MODE_LIGHTEN, ARKUI_BLEND_MODE_COLOR_DODGE,
ARKUI_BLEND_MODE_COLOR_BURN, ARKUI_BLEND_MODE_HARD_LIGHT, ARKUI_BLEND_MODE_SOFT_LIGHT, ARKUI_BLEND_MODE_DIFFERENCE,
ARKUI_BLEND_MODE_EXCLUSION, ARKUI_BLEND_MODE_MULTIPLY, ARKUI_BLEND_MODE_HUE, ARKUI_BLEND_MODE_SATURATION,
ARKUI_BLEND_MODE_COLOR, ARKUI_BLEND_MODE_LUMINOSITY
} | Enumerates the blend modes. | -| [ArkUI_Direction](#arkui_direction) { ARKUI_DIRECTION_LTR = 0, ARKUI_DIRECTION_RTL, ARKUI_DIRECTION_AUTO = 3 } | Enumerates the modes in which components are laid out along the main axis of the container. | -| [ArkUI_ItemAlignment](#arkui_itemalignment) {
ARKUI_ITEM_ALIGNMENT_AUTO = 0, ARKUI_ITEM_ALIGNMENT_START, ARKUI_ITEM_ALIGNMENT_CENTER, ARKUI_ITEM_ALIGNMENT_END,
ARKUI_ITEM_ALIGNMENT_STRETCH, ARKUI_ITEM_ALIGNMENT_BASELINE
} | Enumerates the modes in which components are laid out along the cross axis of the container. | -| [ArkUI_ColorStrategy](#arkui_colorstrategy) { ARKUI_COLOR_STRATEGY_INVERT = 0, ARKUI_COLOR_STRATEGY_AVERAGE, ARKUI_COLOR_STRATEGY_PRIMARY } | Enumerates the foreground colors. | -| [ArkUI_FlexAlignment](#arkui_flexalignment) {
ARKUI_FLEX_ALIGNMENT_START = 1, ARKUI_FLEX_ALIGNMENT_CENTER = 2, ARKUI_FLEX_ALIGNMENT_END = 3, ARKUI_FLEX_ALIGNMENT_SPACE_BETWEEN = 6,
ARKUI_FLEX_ALIGNMENT_SPACE_AROUND = 7, ARKUI_FLEX_ALIGNMENT_SPACE_EVENLY = 8
} | Enumerates the vertical alignment modes. | -| [ArkUI_FlexDirection](#arkui_flexdirection) { ARKUI_FLEX_DIRECTION_ROW = 0, ARKUI_FLEX_DIRECTION_COLUMN, ARKUI_FLEX_DIRECTION_ROW_REVERSE, ARKUI_FLEX_DIRECTION_COLUMN_REVERSE } | Enumerates the directions of the main axis in the flex container. | -| [ArkUI_FlexWrap](#arkui_flexwrap) { ARKUI_FLEX_WRAP_NO_WRAP = 0, ARKUI_FLEX_WRAP_WRAP, ARKUI_FLEX_WRAP_WRAP_REVERSE } | Defines whether the flex container has a single line or multiple lines. | -| [ArkUI_Visibility](#arkui_visibility) { ARKUI_VISIBILITY_VISIBLE = 0, ARKUI_VISIBILITY_HIDDEN, ARKUI_VISIBILITY_NONE } | Enumerates the visibility values. | -| [ArkUI_CalendarAlignment](#arkui_calendaralignment) { ARKUI_CALENDAR_ALIGNMENT_START = 0, ARKUI_CALENDAR_ALIGNMENT_CENTER, ARKUI_CALENDAR_ALIGNMENT_END } | Enumerates the alignment modes between the calendar picker and the entry component. | -| [ArkUI_MaskType](#arkui_masktype) {
ARKUI_MASK_TYPE_RECTANGLE = 0, ARKUI_MASK_TYPE_CIRCLE, ARKUI_MASK_TYPE_ELLIPSE, ARKUI_MASK_TYPE_PATH,
ARKUI_MASK_TYPE_PROGRESS
} | Enumerates the mask types. | -| [ArkUI_ClipType](#arkui_cliptype) { ARKUI_CLIP_TYPE_RECTANGLE = 0, ARKUI_CLIP_TYPE_CIRCLE, ARKUI_CLIP_TYPE_ELLIPSE, ARKUI_CLIP_TYPE_PATH } | Enumerates the clipping region types. | -| [ArkUI_ShapeType](#arkui_shapetype) { ARKUI_SHAPE_TYPE_RECTANGLE = 0, ARKUI_SHAPE_TYPE_CIRCLE, ARKUI_SHAPE_TYPE_ELLIPSE, ARKUI_SHAPE_TYPE_PATH } | Enumerates custom shape types. | -| [ArkUI_LinearGradientDirection](#arkui_lineargradientdirection) {
ARKUI_LINEAR_GRADIENT_DIRECTION_LEFT = 0, ARKUI_LINEAR_GRADIENT_DIRECTION_TOP, ARKUI_LINEAR_GRADIENT_DIRECTION_RIGHT, ARKUI_LINEAR_GRADIENT_DIRECTION_BOTTOM,
ARKUI_LINEAR_GRADIENT_DIRECTION_LEFT_TOP, ARKUI_LINEAR_GRADIENT_DIRECTION_LEFT_BOTTOM, ARKUI_LINEAR_GRADIENT_DIRECTION_RIGHT_TOP, ARKUI_LINEAR_GRADIENT_DIRECTION_RIGHT_BOTTOM,
ARKUI_LINEAR_GRADIENT_DIRECTION_NONE, ARKUI_LINEAR_GRADIENT_DIRECTION_CUSTOM
} | Enumerates the gradient directions. | -| [ArkUI_WordBreak](#arkui_wordbreak) { ARKUI_WORD_BREAK_NORMAL = 0, ARKUI_WORD_BREAK_BREAK_ALL, ARKUI_WORD_BREAK_BREAK_WORD } | Enumerates the word break rules. | -| [ArkUI_EllipsisMode](#arkui_ellipsismode) { ARKUI_ELLIPSIS_MODE_START = 0, ARKUI_ELLIPSIS_MODE_CENTER, ARKUI_ELLIPSIS_MODE_END } | Enumerates the ellipsis positions. | -| [ArkUI_ImageRenderMode](#arkui_imagerendermode) { ARKUI_IMAGE_RENDER_MODE_ORIGINAL = 0, ARKUI_IMAGE_RENDER_MODE_TEMPLATE } | Enumerates the image rendering modes. | -| [ArkUI_TransitionEdge](#arkui_transitionedge) { ARKUI_TRANSITION_EDGE_TOP = 0, ARKUI_TRANSITION_EDGE_BOTTOM, ARKUI_TRANSITION_EDGE_START, ARKUI_TRANSITION_EDGE_END } | Enumerates the slide-in and slide-out positions of the component from the screen edge during transition. | -| [ArkUI_FinishCallbackType](#arkui_finishcallbacktype) { ARKUI_FINISH_CALLBACK_REMOVED = 0, ARKUI_FINISH_CALLBACK_LOGICALLY } | Enumerates the animation **onFinish** callback types. | -| [ArkUI_ListItemAlignment](#arkui_listitemalignment) { ARKUI_LIST_ITEM_ALIGNMENT_START = 0, ARKUI_LIST_ITEM_ALIGNMENT_CENTER, ARKUI_LIST_ITEM_ALIGNMENT_END } | Enumerates the alignment modes of items along the cross axis. | -| [ArkUI_BlendApplyType](#arkui_blendapplytype) { BLEND_APPLY_TYPE_FAST = 0, BLEND_APPLY_TYPE_OFFSCREEN } | Defines how the specified blend mode is applied. | -| [ArkUI_LengthMetricUnit](#arkui_lengthmetricunit) { ARKUI_LENGTH_METRIC_UNIT_DEFAULT = -1, ARKUI_LENGTH_METRIC_UNIT_PX = 0, ARKUI_LENGTH_METRIC_UNIT_VP, ARKUI_LENGTH_METRIC_UNIT_FP } | Enumerates the component units. | -| [ArkUI_TextInputContentType](#arkui_textinputcontenttype) {
ARKUI_TEXTINPUT_CONTENT_TYPE_USER_NAME = 0, ARKUI_TEXTINPUT_CONTENT_TYPE_PASSWORD, ARKUI_TEXTINPUT_CONTENT_TYPE_NEW_PASSWORD, ARKUI_TEXTINPUT_CONTENT_TYPE_FULL_STREET_ADDRESS,
ARKUI_TEXTINPUT_CONTENT_TYPE_HOUSE_NUMBER, ARKUI_TEXTINPUT_CONTENT_TYPE_DISTRICT_ADDRESS, ARKUI_TEXTINPUT_CONTENT_TYPE_CITY_ADDRESS, ARKUI_TEXTINPUT_CONTENT_TYPE_PROVINCE_ADDRESS,
ARKUI_TEXTINPUT_CONTENT_TYPE_COUNTRY_ADDRESS, ARKUI_TEXTINPUT_CONTENT_TYPE_PERSON_FULL_NAME, ARKUI_TEXTINPUT_CONTENT_TYPE_PERSON_LAST_NAME, ARKUI_TEXTINPUT_CONTENT_TYPE_PERSON_FIRST_NAME,
ARKUI_TEXTINPUT_CONTENT_TYPE_PHONE_NUMBER, ARKUI_TEXTINPUT_CONTENT_TYPE_PHONE_COUNTRY_CODE, ARKUI_TEXTINPUT_CONTENT_TYPE_FULL_PHONE_NUMBER, ARKUI_TEXTINPUT_CONTENT_EMAIL_ADDRESS,
ARKUI_TEXTINPUT_CONTENT_TYPE_BANK_CARD_NUMBER, ARKUI_TEXTINPUT_CONTENT_TYPE_ID_CARD_NUMBER, ARKUI_TEXTINPUT_CONTENT_TYPE_NICKNAME, ARKUI_TEXTINPUT_CONTENT_TYPE_DETAIL_INFO_WITHOUT_STREET,
ARKUI_TEXTINPUT_CONTENT_TYPE_FORMAT_ADDRESS
} | Enumerates the autofill types. | -| [ArkUI_BarrierDirection](#arkui_barrierdirection) { ARKUI_BARRIER_DIRECTION_START = 0, ARKUI_BARRIER_DIRECTION_END, ARKUI_BARRIER_DIRECTION_TOP, ARKUI_BARRIER_DIRECTION_BOTTOM } | Enumerates the barrier directions. | -| [ArkUI_RelativeLayoutChainStyle](#arkui_relativelayoutchainstyle) { ARKUI_RELATIVE_LAYOUT_CHAIN_STYLE_SPREAD = 0, ARKUI_RELATIVE_LAYOUT_CHAIN_STYLE_SPREAD_INSIDE, ARKUI_RELATIVE_LAYOUT_CHAIN_STYLE_PACKED } | Enumerates the chain styles. | -| [ArkUI_TextInputStyle](#arkui_textinputstyle) { ARKUI_TEXTINPUT_STYLE_DEFAULT = 0, ARKUI_TEXTINPUT_STYLE_INLINE } | Enumerates the text input styles. | -| [ArkUI_TextDataDetectorType](#arkui_textdatadetectortype) { ARKUI_TEXT_DATA_DETECTOR_TYPE_PHONE_NUMBER = 0, ARKUI_TEXT_DATA_DETECTOR_TYPE_URL, ARKUI_TEXT_DATA_DETECTOR_TYPE_EMAIL, ARKUI_TEXT_DATA_DETECTOR_TYPE_ADDRESS } | Enumerates the entity types of text recognition. | -| [ArkUI_ButtonType](#arkui_buttontype) { ARKUI_BUTTON_TYPE_NORMAL = 0, ARKUI_BUTTON_TYPE_CAPSULE, ARKUI_BUTTON_TYPE_CIRCLE } | Enumerates the button types. | -| [ArkUI_RenderFit](#arkui_renderfit) {
ARKUI_RENDER_FIT_CENTER = 0, ARKUI_RENDER_FIT_TOP, ARKUI_RENDER_FIT_BOTTOM, ARKUI_RENDER_FIT_LEFT,
ARKUI_RENDER_FIT_RIGHT, ARKUI_RENDER_FIT_TOP_LEFT, ARKUI_RENDER_FIT_TOP_RIGHT, ARKUI_RENDER_FIT_BOTTOM_LEFT,
ARKUI_RENDER_FIT_BOTTOM_RIGHT, ARKUI_RENDER_FIT_RESIZE_FILL, ARKUI_RENDER_FIT_RESIZE_CONTAIN, ARKUI_RENDER_FIT_RESIZE_CONTAIN_TOP_LEFT,
ARKUI_RENDER_FIT_RESIZE_CONTAIN_BOTTOM_RIGHT, ARKUI_RENDER_FIT_RESIZE_COVER, ARKUI_RENDER_FIT_RESIZE_COVER_TOP_LEFT, ARKUI_RENDER_FIT_RESIZE_COVER_BOTTOM_RIGHT
} | | +| [ArkUI_AccessibilityMode](#arkui_accessibilitymode) { ARKUI_ACCESSIBILITY_MODE_AUTO = 0, ARKUI_ACCESSIBILITY_MODE_ENABLED, ARKUI_ACCESSIBILITY_MODE_DISABLED, ARKUI_ACCESSIBILITY_MODE_DISABLED_FOR_DESCENDANTS } | Enumerates the accessibility modes. | +| [ArkUI_TextCopyOptions](#arkui_textcopyoptions) { ARKUI_TEXT_COPY_OPTIONS_NONE = 0, ARKUI_TEXT_COPY_OPTIONS_IN_APP, ARKUI_TEXT_COPY_OPTIONS_LOCAL_DEVICE, ARKUI_TEXT_COPY_OPTIONS_CROSS_DEVICE } | Enumerates copy options, which define whether copy and paste is allowed for text content. | +| [ArkUI_TextHeightAdaptivePolicy](#arkui_textheightadaptivepolicy) { ARKUI_TEXT_HEIGHT_ADAPTIVE_POLICY_MAX_LINES_FIRST = 0, ARKUI_TEXT_HEIGHT_ADAPTIVE_POLICY_MIN_FONT_SIZE_FIRST, ARKUI_TEXT_HEIGHT_ADAPTIVE_POLICY_LAYOUT_CONSTRAINT_FIRST } | Defines how the adaptive height is determined for the text. | +| [ArkUI_ScrollNestedMode](#arkui_scrollnestedmode) { ARKUI_SCROLL_NESTED_MODE_SELF_ONLY = 0, ARKUI_SCROLL_NESTED_MODE_SELF_FIRST, ARKUI_SCROLL_NESTED_MODE_PARENT_FIRST, ARKUI_SCROLL_NESTED_MODE_PARALLEL } | Enumerates nested scrolling options. | +| [ArkUI_ScrollEdge](#arkui_scrolledge) { ARKUI_SCROLL_EDGE_TOP = 0, ARKUI_SCROLL_EDGE_BOTTOM, ARKUI_SCROLL_EDGE_START, ARKUI_SCROLL_EDGE_END } | Defines the edge to which the component scrolls. | +| [ArkUI_ScrollAlignment](#arkui_scrollalignment) { ARKUI_SCROLL_ALIGNMENT_START = 0, ARKUI_SCROLL_ALIGNMENT_CENTER, ARKUI_SCROLL_ALIGNMENT_END, ARKUI_SCROLL_ALIGNMENT_AUTO } | Defines how the list item to scroll to is aligned with the container. | +| [ArkUI_ScrollState](#arkui_scrollstate) { ARKUI_SCROLL_STATE_IDLE = 0, ARKUI_SCROLL_STATE_SCROLL, ARKUI_SCROLL_STATE_FLING } | Enumerates the scrolling states. | +| [ArkUI_SliderBlockStyle](#arkui_sliderblockstyle) { ARKUI_SLIDER_BLOCK_STYLE_DEFAULT = 0, ARKUI_SLIDER_BLOCK_STYLE_IMAGE, ARKUI_SLIDER_BLOCK_STYLE_SHAPE } | Enumerates the styles of the slider in the block direction. | +| [ArkUI_SliderDirection](#arkui_sliderdirection) { ARKUI_SLIDER_DIRECTION_VERTICAL = 0, ARKUI_SLIDER_DIRECTION_HORIZONTAL } | Enumerates the scroll directions of the slider. | +| [ArkUI_SliderStyle](#arkui_sliderstyle) { ARKUI_SLIDER_STYLE_OUT_SET = 0, ARKUI_SLIDER_STYLE_IN_SET, ARKUI_SLIDER_STYLE_NONE } | Enumerates the slider styles. | +| [ArkUI_CheckboxShape](#arkui_checkboxshape) { ArkUI_CHECKBOX_SHAPE_CIRCLE = 0, ArkUI_CHECKBOX_SHAPE_ROUNDED_SQUARE } | Enumerates the shapes of the check box. | +| [ArkUI_AnimationPlayMode](#arkui_animationplaymode) { ARKUI_ANIMATION_PLAY_MODE_NORMAL = 0, ARKUI_ANIMATION_PLAY_MODE_REVERSE, ARKUI_ANIMATION_PLAY_MODE_ALTERNATE, ARKUI_ANIMATION_PLAY_MODE_ALTERNATE_REVERSE } | Enumerates the animation playback modes. | +| [ArkUI_ImageSize](#arkui_imagesize) { ARKUI_IMAGE_SIZE_AUTO = 0, ARKUI_IMAGE_SIZE_COVER, ARKUI_IMAGE_SIZE_CONTAIN } | Defines the image size. | +| [ArkUI_AdaptiveColor](#arkui_adaptivecolor) { ARKUI_ADAPTIVE_COLOR_DEFAULT = 0, ARKUI_ADAPTIVE_COLOR_AVERAGE } | Enumerates the adaptive color modes. | +| [ArkUI_ColorMode](#arkui_colormode) { ARKUI_COLOR_MODE_SYSTEM = 0, ARKUI_COLOR_MODE_LIGHT, ARKUI_COLOR_MODE_DARK } | Enumerates the color modes. | +| [ArkUI_SystemColorMode](#arkui_systemcolormode) { ARKUI_SYSTEM_COLOR_MODE_LIGHT = 0, ARKUI_SYSTEM_COLOR_MODE_DARK } | Enumerates the system color modes. | +| [ArkUI_BlurStyle](#arkui_blurstyle) {
ARKUI_BLUR_STYLE_THIN = 0, ARKUI_BLUR_STYLE_REGULAR, ARKUI_BLUR_STYLE_THICK, ARKUI_BLUR_STYLE_BACKGROUND_THIN,
ARKUI_BLUR_STYLE_BACKGROUND_REGULAR, ARKUI_BLUR_STYLE_BACKGROUND_THICK, ARKUI_BLUR_STYLE_BACKGROUND_ULTRA_THICK, ARKUI_BLUR_STYLE_NONE,
ARKUI_BLUR_STYLE_COMPONENT_ULTRA_THIN, ARKUI_BLUR_STYLE_COMPONENT_THIN, ARKUI_BLUR_STYLE_COMPONENT_REGULAR, ARKUI_BLUR_STYLE_COMPONENT_THICK,
ARKUI_BLUR_STYLE_COMPONENT_ULTRA_THICK
} | Enumerates the blur styles. | +| [ArkUI_VerticalAlignment](#arkui_verticalalignment) { ARKUI_VERTICAL_ALIGNMENT_TOP = 0, ARKUI_VERTICAL_ALIGNMENT_CENTER, ARKUI_VERTICAL_ALIGNMENT_BOTTOM } | Enumerates the vertical alignment modes. | +| [ArkUI_HorizontalAlignment](#arkui_horizontalalignment) { ARKUI_HORIZONTAL_ALIGNMENT_START = 0, ARKUI_HORIZONTAL_ALIGNMENT_CENTER, ARKUI_HORIZONTAL_ALIGNMENT_END } | Enumerates the alignment mode in the horizontal direction. | +| [ArkUI_TextOverflow](#arkui_textoverflow) { ARKUI_TEXT_OVERFLOW_NONE = 0, ARKUI_TEXT_OVERFLOW_CLIP, ARKUI_TEXT_OVERFLOW_ELLIPSIS, ARKUI_TEXT_OVERFLOW_MARQUEE } | Enumerates the display modes when the text is too long. | +| [ArkUI_ImageSpanAlignment](#arkui_imagespanalignment) { ARKUI_IMAGE_SPAN_ALIGNMENT_BASELINE = 0, ARKUI_IMAGE_SPAN_ALIGNMENT_BOTTOM, ARKUI_IMAGE_SPAN_ALIGNMENT_CENTER, ARKUI_IMAGE_SPAN_ALIGNMENT_TOP } | Enumerates the alignment mode of the image with the text. | +| [ArkUI_ObjectFit](#arkui_objectfit) {
ARKUI_OBJECT_FIT_CONTAIN = 0, ARKUI_OBJECT_FIT_COVER, ARKUI_OBJECT_FIT_AUTO, ARKUI_OBJECT_FIT_FILL,
ARKUI_OBJECT_FIT_SCALE_DOWN, ARKUI_OBJECT_FIT_NONE, ARKUI_OBJECT_FIT_NONE_AND_ALIGN_TOP_START, ARKUI_OBJECT_FIT_NONE_AND_ALIGN_TOP,
ARKUI_OBJECT_FIT_NONE_AND_ALIGN_TOP_END, ARKUI_OBJECT_FIT_NONE_AND_ALIGN_START, ARKUI_OBJECT_FIT_NONE_AND_ALIGN_CENTER, ARKUI_OBJECT_FIT_NONE_AND_ALIGN_END,
ARKUI_OBJECT_FIT_NONE_AND_ALIGN_BOTTOM_START, ARKUI_OBJECT_FIT_NONE_AND_ALIGN_BOTTOM, ARKUI_OBJECT_FIT_NONE_AND_ALIGN_BOTTOM_END
} | Enumerates the image filling effects. ImageSpanAlignment | +| [ArkUI_ImageInterpolation](#arkui_imageinterpolation) { ARKUI_IMAGE_INTERPOLATION_NONE = 0, ARKUI_IMAGE_INTERPOLATION_LOW, ARKUI_IMAGE_INTERPOLATION_MEDIUM, ARKUI_IMAGE_INTERPOLATION_HIGH } | Enumerates the image interpolation effects. | +| [ArkUI_BlendMode](#arkui_blendmode) {
ARKUI_BLEND_MODE_NONE = 0, ARKUI_BLEND_MODE_CLEAR, ARKUI_BLEND_MODE_SRC, ARKUI_BLEND_MODE_DST,
ARKUI_BLEND_MODE_SRC_OVER, ARKUI_BLEND_MODE_DST_OVER, ARKUI_BLEND_MODE_SRC_IN, ARKUI_BLEND_MODE_DST_IN,
ARKUI_BLEND_MODE_SRC_OUT, ARKUI_BLEND_MODE_DST_OUT, ARKUI_BLEND_MODE_SRC_ATOP, ARKUI_BLEND_MODE_DST_ATOP,
ARKUI_BLEND_MODE_XOR, ARKUI_BLEND_MODE_PLUS, ARKUI_BLEND_MODE_MODULATE, ARKUI_BLEND_MODE_SCREEN,
ARKUI_BLEND_MODE_OVERLAY, ARKUI_BLEND_MODE_DARKEN, ARKUI_BLEND_MODE_LIGHTEN, ARKUI_BLEND_MODE_COLOR_DODGE,
ARKUI_BLEND_MODE_COLOR_BURN, ARKUI_BLEND_MODE_HARD_LIGHT, ARKUI_BLEND_MODE_SOFT_LIGHT, ARKUI_BLEND_MODE_DIFFERENCE,
ARKUI_BLEND_MODE_EXCLUSION, ARKUI_BLEND_MODE_MULTIPLY, ARKUI_BLEND_MODE_HUE, ARKUI_BLEND_MODE_SATURATION,
ARKUI_BLEND_MODE_COLOR, ARKUI_BLEND_MODE_LUMINOSITY
} | Enumerates the blend modes. | +| [ArkUI_Direction](#arkui_direction) { ARKUI_DIRECTION_LTR = 0, ARKUI_DIRECTION_RTL, ARKUI_DIRECTION_AUTO = 3 } | Enumerates the modes in which components are laid out along the main axis of the container. | +| [ArkUI_ItemAlignment](#arkui_itemalignment) {
ARKUI_ITEM_ALIGNMENT_AUTO = 0, ARKUI_ITEM_ALIGNMENT_START, ARKUI_ITEM_ALIGNMENT_CENTER, ARKUI_ITEM_ALIGNMENT_END,
ARKUI_ITEM_ALIGNMENT_STRETCH, ARKUI_ITEM_ALIGNMENT_BASELINE
} | Enumerates the modes in which components are laid out along the cross axis of the container. | +| [ArkUI_ColorStrategy](#arkui_colorstrategy) { ARKUI_COLOR_STRATEGY_INVERT = 0, ARKUI_COLOR_STRATEGY_AVERAGE, ARKUI_COLOR_STRATEGY_PRIMARY } | Enumerates the foreground colors. | +| [ArkUI_FlexAlignment](#arkui_flexalignment) {
ARKUI_FLEX_ALIGNMENT_START = 1, ARKUI_FLEX_ALIGNMENT_CENTER = 2, ARKUI_FLEX_ALIGNMENT_END = 3, ARKUI_FLEX_ALIGNMENT_SPACE_BETWEEN = 6,
ARKUI_FLEX_ALIGNMENT_SPACE_AROUND = 7, ARKUI_FLEX_ALIGNMENT_SPACE_EVENLY = 8
} | Enumerates the vertical alignment modes. | +| [ArkUI_FlexDirection](#arkui_flexdirection) { ARKUI_FLEX_DIRECTION_ROW = 0, ARKUI_FLEX_DIRECTION_COLUMN, ARKUI_FLEX_DIRECTION_ROW_REVERSE, ARKUI_FLEX_DIRECTION_COLUMN_REVERSE } | Enumerates the directions of the main axis in the flex container. | +| [ArkUI_FlexWrap](#arkui_flexwrap) { ARKUI_FLEX_WRAP_NO_WRAP = 0, ARKUI_FLEX_WRAP_WRAP, ARKUI_FLEX_WRAP_WRAP_REVERSE } | Defines whether the flex container has a single line or multiple lines. | +| [ArkUI_Visibility](#arkui_visibility) { ARKUI_VISIBILITY_VISIBLE = 0, ARKUI_VISIBILITY_HIDDEN, ARKUI_VISIBILITY_NONE } | Enumerates the visibility values. | +| [ArkUI_CalendarAlignment](#arkui_calendaralignment) { ARKUI_CALENDAR_ALIGNMENT_START = 0, ARKUI_CALENDAR_ALIGNMENT_CENTER, ARKUI_CALENDAR_ALIGNMENT_END } | Enumerates the alignment modes between the calendar picker and the entry component. | +| [ArkUI_MaskType](#arkui_masktype) {
ARKUI_MASK_TYPE_RECTANGLE = 0, ARKUI_MASK_TYPE_CIRCLE, ARKUI_MASK_TYPE_ELLIPSE, ARKUI_MASK_TYPE_PATH,
ARKUI_MASK_TYPE_PROGRESS
} | Enumerates the mask types. | +| [ArkUI_ClipType](#arkui_cliptype) { ARKUI_CLIP_TYPE_RECTANGLE = 0, ARKUI_CLIP_TYPE_CIRCLE, ARKUI_CLIP_TYPE_ELLIPSE, ARKUI_CLIP_TYPE_PATH } | Enumerates the clipping region types. | +| [ArkUI_ShapeType](#arkui_shapetype) { ARKUI_SHAPE_TYPE_RECTANGLE = 0, ARKUI_SHAPE_TYPE_CIRCLE, ARKUI_SHAPE_TYPE_ELLIPSE, ARKUI_SHAPE_TYPE_PATH } | Enumerates custom shape types. | +| [ArkUI_LinearGradientDirection](#arkui_lineargradientdirection) {
ARKUI_LINEAR_GRADIENT_DIRECTION_LEFT = 0, ARKUI_LINEAR_GRADIENT_DIRECTION_TOP, ARKUI_LINEAR_GRADIENT_DIRECTION_RIGHT, ARKUI_LINEAR_GRADIENT_DIRECTION_BOTTOM,
ARKUI_LINEAR_GRADIENT_DIRECTION_LEFT_TOP, ARKUI_LINEAR_GRADIENT_DIRECTION_LEFT_BOTTOM, ARKUI_LINEAR_GRADIENT_DIRECTION_RIGHT_TOP, ARKUI_LINEAR_GRADIENT_DIRECTION_RIGHT_BOTTOM,
ARKUI_LINEAR_GRADIENT_DIRECTION_NONE, ARKUI_LINEAR_GRADIENT_DIRECTION_CUSTOM
} | Enumerates the gradient directions. | +| [ArkUI_WordBreak](#arkui_wordbreak) { ARKUI_WORD_BREAK_NORMAL = 0, ARKUI_WORD_BREAK_BREAK_ALL, ARKUI_WORD_BREAK_BREAK_WORD, ARKUI_WORD_BREAK_HYPHENATION } | Enumerates the word break rules. | +| [ArkUI_EllipsisMode](#arkui_ellipsismode) { ARKUI_ELLIPSIS_MODE_START = 0, ARKUI_ELLIPSIS_MODE_CENTER, ARKUI_ELLIPSIS_MODE_END } | Enumerates the ellipsis positions. | +| [ArkUI_ImageRenderMode](#arkui_imagerendermode) { ARKUI_IMAGE_RENDER_MODE_ORIGINAL = 0, ARKUI_IMAGE_RENDER_MODE_TEMPLATE } | Enumerates the image rendering modes. | +| [ArkUI_TransitionEdge](#arkui_transitionedge) { ARKUI_TRANSITION_EDGE_TOP = 0, ARKUI_TRANSITION_EDGE_BOTTOM, ARKUI_TRANSITION_EDGE_START, ARKUI_TRANSITION_EDGE_END } | Enumerates the slide-in and slide-out positions of the component from the screen edge during transition. | +| [ArkUI_FinishCallbackType](#arkui_finishcallbacktype) { ARKUI_FINISH_CALLBACK_REMOVED = 0, ARKUI_FINISH_CALLBACK_LOGICALLY } | Enumerates the animation **onFinish** callback types. | +| [ArkUI_ListItemAlignment](#arkui_listitemalignment) { ARKUI_LIST_ITEM_ALIGNMENT_START = 0, ARKUI_LIST_ITEM_ALIGNMENT_CENTER, ARKUI_LIST_ITEM_ALIGNMENT_END } | Enumerates the alignment modes of items along the cross axis. | +| [ArkUI_BlendApplyType](#arkui_blendapplytype) { BLEND_APPLY_TYPE_FAST = 0, BLEND_APPLY_TYPE_OFFSCREEN } | Defines how the specified blend mode is applied. | +| [ArkUI_LengthMetricUnit](#arkui_lengthmetricunit) { ARKUI_LENGTH_METRIC_UNIT_DEFAULT = -1, ARKUI_LENGTH_METRIC_UNIT_PX = 0, ARKUI_LENGTH_METRIC_UNIT_VP, ARKUI_LENGTH_METRIC_UNIT_FP } | Enumerates the component units. | +| [ArkUI_TextInputContentType](#arkui_textinputcontenttype) {
ARKUI_TEXTINPUT_CONTENT_TYPE_USER_NAME = 0, ARKUI_TEXTINPUT_CONTENT_TYPE_PASSWORD, ARKUI_TEXTINPUT_CONTENT_TYPE_NEW_PASSWORD, ARKUI_TEXTINPUT_CONTENT_TYPE_FULL_STREET_ADDRESS,
ARKUI_TEXTINPUT_CONTENT_TYPE_HOUSE_NUMBER, ARKUI_TEXTINPUT_CONTENT_TYPE_DISTRICT_ADDRESS, ARKUI_TEXTINPUT_CONTENT_TYPE_CITY_ADDRESS, ARKUI_TEXTINPUT_CONTENT_TYPE_PROVINCE_ADDRESS,
ARKUI_TEXTINPUT_CONTENT_TYPE_COUNTRY_ADDRESS, ARKUI_TEXTINPUT_CONTENT_TYPE_PERSON_FULL_NAME, ARKUI_TEXTINPUT_CONTENT_TYPE_PERSON_LAST_NAME, ARKUI_TEXTINPUT_CONTENT_TYPE_PERSON_FIRST_NAME,
ARKUI_TEXTINPUT_CONTENT_TYPE_PHONE_NUMBER, ARKUI_TEXTINPUT_CONTENT_TYPE_PHONE_COUNTRY_CODE, ARKUI_TEXTINPUT_CONTENT_TYPE_FULL_PHONE_NUMBER, ARKUI_TEXTINPUT_CONTENT_EMAIL_ADDRESS,
ARKUI_TEXTINPUT_CONTENT_TYPE_BANK_CARD_NUMBER, ARKUI_TEXTINPUT_CONTENT_TYPE_ID_CARD_NUMBER, ARKUI_TEXTINPUT_CONTENT_TYPE_NICKNAME, ARKUI_TEXTINPUT_CONTENT_TYPE_DETAIL_INFO_WITHOUT_STREET,
ARKUI_TEXTINPUT_CONTENT_TYPE_FORMAT_ADDRESS,
ARKUI_TEXTINPUT_CONTENT_TYPE_PASSPORT_NUMBER,
ARKUI_TEXTINPUT_CONTENT_TYPE_VALIDITY,
ARKUI_TEXTINPUT_CONTENT_TYPE_ISSUE_AT,
ARKUI_TEXTINPUT_CONTENT_TYPE_ORGANIZATION,
ARKUI_TEXTINPUT_CONTENT_TYPE_TAX_ID,
ARKUI_TEXTINPUT_CONTENT_TYPE_ADDRESS_CITY_AND_STATE,
ARKUI_TEXTINPUT_CONTENT_TYPE_FLIGHT_NUMBER,
ARKUI_TEXTINPUT_CONTENT_TYPE_LICENSE_NUMBER,
ARKUI_TEXTINPUT_CONTENT_TYPE_LICENSE_FILE_NUMBER,
ARKUI_TEXTINPUT_CONTENT_TYPE_LICENSE_PLATE,
ARKUI_TEXTINPUT_CONTENT_TYPE_ENGINE_NUMBER,
ARKUI_TEXTINPUT_CONTENT_TYPE_LICENSE_CHASSIS_NUMBER,
} | Enumerates the autofill types. | +| [ArkUI_BarrierDirection](#arkui_barrierdirection) { ARKUI_BARRIER_DIRECTION_START = 0, ARKUI_BARRIER_DIRECTION_END, ARKUI_BARRIER_DIRECTION_TOP, ARKUI_BARRIER_DIRECTION_BOTTOM } | Enumerates the barrier directions. | +| [ArkUI_RelativeLayoutChainStyle](#arkui_relativelayoutchainstyle) { ARKUI_RELATIVE_LAYOUT_CHAIN_STYLE_SPREAD = 0, ARKUI_RELATIVE_LAYOUT_CHAIN_STYLE_SPREAD_INSIDE, ARKUI_RELATIVE_LAYOUT_CHAIN_STYLE_PACKED } | Enumerates the chain styles. | +| [ArkUI_TextInputStyle](#arkui_textinputstyle) { ARKUI_TEXTINPUT_STYLE_DEFAULT = 0, ARKUI_TEXTINPUT_STYLE_INLINE } | Enumerates the text input styles. | +| [ArkUI_TextDataDetectorType](#arkui_textdatadetectortype) { ARKUI_TEXT_DATA_DETECTOR_TYPE_PHONE_NUMBER = 0, ARKUI_TEXT_DATA_DETECTOR_TYPE_URL, ARKUI_TEXT_DATA_DETECTOR_TYPE_EMAIL, ARKUI_TEXT_DATA_DETECTOR_TYPE_ADDRESS } | Enumerates the entity types of text recognition. | +| [ArkUI_ButtonType](#arkui_buttontype) { ARKUI_BUTTON_TYPE_NORMAL = 0, ARKUI_BUTTON_TYPE_CAPSULE, ARKUI_BUTTON_TYPE_CIRCLE } | Enumerates the button types. | +| [ArkUI_RenderFit](#arkui_renderfit) {
ARKUI_RENDER_FIT_CENTER = 0, ARKUI_RENDER_FIT_TOP, ARKUI_RENDER_FIT_BOTTOM, ARKUI_RENDER_FIT_LEFT,
ARKUI_RENDER_FIT_RIGHT, ARKUI_RENDER_FIT_TOP_LEFT, ARKUI_RENDER_FIT_TOP_RIGHT, ARKUI_RENDER_FIT_BOTTOM_LEFT,
ARKUI_RENDER_FIT_BOTTOM_RIGHT, ARKUI_RENDER_FIT_RESIZE_FILL, ARKUI_RENDER_FIT_RESIZE_CONTAIN, ARKUI_RENDER_FIT_RESIZE_CONTAIN_TOP_LEFT,
ARKUI_RENDER_FIT_RESIZE_CONTAIN_BOTTOM_RIGHT, ARKUI_RENDER_FIT_RESIZE_COVER, ARKUI_RENDER_FIT_RESIZE_COVER_TOP_LEFT, ARKUI_RENDER_FIT_RESIZE_COVER_BOTTOM_RIGHT
} | | | [ArkUI_ThemeColorMode](#arkui_themecolormode) { ARKUI_THEME_COLOR_MODE_SYSTEM = 0, ARKUI_THEME_COLOR_MODE_LIGHT, ARKUI_THEME_COLOR_MODE_DARK } | | -| [ArkUI_SwiperIndicatorType](#arkui_swiperindicatortype) { ARKUI_SWIPER_INDICATOR_TYPE_DOT, ARKUI_SWIPER_INDICATOR_TYPE_DIGIT } | Enumerates the navigation point indicator types of the **Swiper** component. | -| [ArkUI_AnimationDirection](#arkui_animationdirection) { ARKUI_ANIMATION_DIRECTION_NORMAL = 0, ARKUI_ANIMATION_DIRECTION_REVERSE, ARKUI_ANIMATION_DIRECTION_ALTERNATE, ARKUI_ANIMATION_DIRECTION_ALTERNATE_REVERSE } | Enumerates the animation playback modes. | -| [ArkUI_AnimationFill](#arkui_animationfill) { ARKUI_ANIMATION_FILL_NONE = 0, ARKUI_ANIMATION_FILL_FORWARDS, ARKUI_ANIMATION_FILL_BACKWARDS, ARKUI_ANIMATION_FILL_BOTH } | Enumerates the state of the animated target after the animation is executed. | -| [ArkUI_SwiperDisplayModeType](#arkui_swiperdisplaymodetype) { ARKUI_SWIPER_DISPLAY_MODE_STRETCH, ARKUI_SWIPER_DISPLAY_MODE_AUTO_LINEAR } | Enumerates the modes in which elements are displayed along the main axis of the **Swiper** component. | -| [ArkUI_ListItemSwipeActionState](#arkui_listitemswipeactionstate) { ARKUI_LIST_ITEM_SWIPE_ACTION_STATE_COLLAPSED = 0, ARKUI_LIST_ITEM_SWIPE_ACTION_STATE_EXPANDED, ARKUI_LIST_ITEM_SWIPE_ACTION_STATE_ACTIONING } | Enumerates the swipe action item states of list items. | -| [ArkUI_ListItemSwipeEdgeEffect](#arkui_listitemswipeedgeeffect) { ARKUI_LIST_ITEM_SWIPE_EDGE_EFFECT_SPRING = 0, ARKUI_LIST_ITEM_SWIPE_EDGE_EFFECT_NONE } | Enumerates the swipe action item edge effects of list items. | -| [ArkUI_AnimationStatus](#arkui_animationstatus) { ARKUI_ANIMATION_STATUS_INITIAL, ARKUI_ANIMATION_STATUS_RUNNING, ARKUI_ANIMATION_STATUS_PAUSED, ARKUI_ANIMATION_STATUS_STOPPED } | Enumerates the playback states of the frame-by-frame animation. | -| [ArkUI_AnimationFillMode](#arkui_animationfillmode) { ARKUI_ANIMATION_FILL_MODE_NONE, ARKUI_ANIMATION_FILL_MODE_FORWARDS, ARKUI_ANIMATION_FILL_MODE_BACKWARDS, ARKUI_ANIMATION_FILL_MODE_BOTH } | Enumerates the states before and after execution of the frame-by-frame animation. | -| [ArkUI_ErrorCode](#arkui_errorcode) {
ARKUI_ERROR_CODE_NO_ERROR = 0, ARKUI_ERROR_CODE_PARAM_INVALID = 401,
ARKUI_ERROR_CODE_FOCUS_NON_FOCUSABLE = 150001, -ARKUI_ERROR_CODE_FOCUS_NON_FOCUSABLE_ANCESTOR = 150002,ARKUI_ERROR_CODE_FOCUS_NON_EXISTENT = 150003,
ARKUI_ERROR_CODE_ATTRIBUTE_OR_EVENT_NOT_SUPPORTED = 106102, ARKUI_ERROR_CODE_NOT_SUPPROTED_FOR_ARKTS_NODE = 106103,
ARKUI_ERROR_CODE_NODE_ADAPTER_NONE_HOST = 106104, ARKUI_ERROR_CODE_NODE_ADAPTER_EXIST_IN_HOST = 106105, ARKUI_ERROR_CODE_NODE_ADAPTER_CHILD_NODE_EXIST = 106106, ARKUI_ERROR_CODE_NODE_EVENT_PARAM_INDEX_OUT_OF_RANGE = 106107,
ARKUI_ERROR_CODE_NODE_EVENT_PARAM_INVALID = 106108, ARKUI_ERROR_CODE_NODE_EVENT_NO_RETURN = 106109, ARKUI_ERROR_CODE_NODE_INDEX_INVALID = 106200, ARKUI_ERROR_CODE_GET_INFO_FAILED = 106201,
ARKUI_ERROR_CODE_BUFFER_SIZE_ERROR = 106202, ARKUI_ERROR_CODE_NON_SCROLLABLE_CONTAINER = 180001, ARKUI_ERROR_CODE_BUFFER_SIZE_NOT_ENOUGH = 180002, ARKUI_ERROR_CODE_INVALID_STYLED_STRING = 180101
} | Enumerates the error codes. | -| [ArkUI_ScrollSource](#arkui_scrollsource) {
ARKUI_SCROLL_SOURCE_DRAG = 0, ARKUI_SCROLL_SOURCE_FLING, ARKUI_SCROLL_SOURCE_EDGE_EFFECT, ARKUI_SCROLL_SOURCE_OTHER_USER_INPUT,
ARKUI_SCROLL_SOURCE_SCROLL_BAR, ARKUI_SCROLL_SOURCE_SCROLL_BAR_FLING, ARKUI_SCROLL_SOURCE_SCROLLER, ARKUI_SCROLL_SOURCE_ANIMATION
} | Enumerates the scrolling sources. | -| [ArkUI_SafeAreaType](#arkui_safeareatype) { ARKUI_SAFE_AREA_TYPE_SYSTEM = 1, ARKUI_SAFE_AREA_TYPE_CUTOUT = 1 << 1, ARKUI_SAFE_AREA_TYPE_KEYBOARD = 1 << 2 } | Enumerates the types of expanded safe areas. | -| [ArkUI_SafeAreaEdge](#arkui_safeareaedge) { ARKUI_SAFE_AREA_EDGE_TOP = 1, ARKUI_SAFE_AREA_EDGE_BOTTOM = 1 << 1, ARKUI_SAFE_AREA_EDGE_START = 1 << 2, ARKUI_SAFE_AREA_EDGE_END = 1 << 3 } | Enumerates the edges for expanding the safe area. | -| [ArkUI_NavDestinationState](#arkui_navdestinationstate) {
ARKUI_NAV_DESTINATION_STATE_ON_SHOW = 0, ARKUI_NAV_DESTINATION_STATE_ON_HIDE = 1, ARKUI_NAV_DESTINATION_STATE_ON_APPEAR = 2, ARKUI_NAV_DESTINATION_STATE_ON_DISAPPEAR = 3,
ARKUI_NAV_DESTINATION_STATE_ON_WILL_SHOW = 4, ARKUI_NAV_DESTINATION_STATE_ON_WILL_HIDE = 5, ARKUI_NAV_DESTINATION_STATE_ON_WILL_APPEAR = 6, ARKUI_NAV_DESTINATION_STATE_ON_WILL_DISAPPEAR = 7,
ARKUI_NAV_DESTINATION_STATE_ON_BACK_PRESS = 100
} | Enumerates the **NavDestination** component states. | -| [ArkUI_RouterPageState](#arkui_routerpagestate) {
ARKUI_ROUTER_PAGE_STATE_ON_WILL_APPEAR = 0, ARKUI_ROUTER_PAGE_STATE_ON_WILL_DISAPPEAR = 1, ARKUI_ROUTER_PAGE_STATE_ON_SHOW = 2, ARKUI_ROUTER_PAGE_STATE_ON_HIDE = 3,
ARKUI_ROUTER_PAGE_STATE_ON_BACK_PRESS = 4
} | Enumerates the states of a page during routing. | +| [ArkUI_SwiperIndicatorType](#arkui_swiperindicatortype) { ARKUI_SWIPER_INDICATOR_TYPE_DOT, ARKUI_SWIPER_INDICATOR_TYPE_DIGIT } | Enumerates the navigation indicator types of the **Swiper** component. | +| [ArkUI_AnimationDirection](#arkui_animationdirection) { ARKUI_ANIMATION_DIRECTION_NORMAL = 0, ARKUI_ANIMATION_DIRECTION_REVERSE, ARKUI_ANIMATION_DIRECTION_ALTERNATE, ARKUI_ANIMATION_DIRECTION_ALTERNATE_REVERSE } | Enumerates the animation playback modes. | +| [ArkUI_AnimationFill](#arkui_animationfill) { ARKUI_ANIMATION_FILL_NONE = 0, ARKUI_ANIMATION_FILL_FORWARDS, ARKUI_ANIMATION_FILL_BACKWARDS, ARKUI_ANIMATION_FILL_BOTH } | Enumerates the state of the animated target after the animation is executed. | +| [ArkUI_SwiperDisplayModeType](#arkui_swiperdisplaymodetype) { ARKUI_SWIPER_DISPLAY_MODE_STRETCH, ARKUI_SWIPER_DISPLAY_MODE_AUTO_LINEAR } | Enumerates the modes in which elements are displayed along the main axis of the **Swiper** component. | +| [ArkUI_ListItemSwipeActionState](#arkui_listitemswipeactionstate) { ARKUI_LIST_ITEM_SWIPE_ACTION_STATE_COLLAPSED = 0, ARKUI_LIST_ITEM_SWIPE_ACTION_STATE_EXPANDED, ARKUI_LIST_ITEM_SWIPE_ACTION_STATE_ACTIONING } | Enumerates the swipe action item states of list items. | +| [ArkUI_ListItemSwipeEdgeEffect](#arkui_listitemswipeedgeeffect) { ARKUI_LIST_ITEM_SWIPE_EDGE_EFFECT_SPRING = 0, ARKUI_LIST_ITEM_SWIPE_EDGE_EFFECT_NONE } | Enumerates the swipe action item edge effects of list items. | +| [ArkUI_AnimationStatus](#arkui_animationstatus) { ARKUI_ANIMATION_STATUS_INITIAL, ARKUI_ANIMATION_STATUS_RUNNING, ARKUI_ANIMATION_STATUS_PAUSED, ARKUI_ANIMATION_STATUS_STOPPED } | Enumerates the playback states of the frame-by-frame animation. | +| [ArkUI_AnimationFillMode](#arkui_animationfillmode) { ARKUI_ANIMATION_FILL_MODE_NONE, ARKUI_ANIMATION_FILL_MODE_FORWARDS, ARKUI_ANIMATION_FILL_MODE_BACKWARDS, ARKUI_ANIMATION_FILL_MODE_BOTH } | Enumerates the states before and after execution of the frame-by-frame animation. | +| [ArkUI_ErrorCode](#arkui_errorcode) {
ARKUI_ERROR_CODE_NO_ERROR = 0, ARKUI_ERROR_CODE_PARAM_INVALID = 401,
ARKUI_ERROR_CODE_FOCUS_NON_FOCUSABLE = 150001, ARKUI_ERROR_CODE_FOCUS_NON_FOCUSABLE_ANCESTOR = 150002, ARKUI_ERROR_CODE_FOCUS_NON_EXISTENT = 150003,
ARKUI_ERROR_CODE_ATTRIBUTE_OR_EVENT_NOT_SUPPORTED = 106102, ARKUI_ERROR_CODE_NOT_SUPPROTED_FOR_ARKTS_NODE = 106103,
ARKUI_ERROR_CODE_NODE_ADAPTER_NONE_HOST = 106104, ARKUI_ERROR_CODE_NODE_ADAPTER_EXIST_IN_HOST = 106105, ARKUI_ERROR_CODE_NODE_ADAPTER_CHILD_NODE_EXIST = 106106, ARKUI_ERROR_CODE_NODE_EVENT_PARAM_INDEX_OUT_OF_RANGE = 106107,
ARKUI_ERROR_CODE_NODE_EVENT_PARAM_INVALID = 106108, ARKUI_ERROR_CODE_NODE_EVENT_NO_RETURN = 106109, ARKUI_ERROR_CODE_NODE_INDEX_INVALID = 106200, ARKUI_ERROR_CODE_GET_INFO_FAILED = 106201,
ARKUI_ERROR_CODE_BUFFER_SIZE_ERROR = 106202, ARKUI_ERROR_CODE_NODE_NOT_ON_MAIN_TREE = 106203, ARKUI_ERROR_CODE_NON_SCROLLABLE_CONTAINER = 180001, ARKUI_ERROR_CODE_BUFFER_SIZE_NOT_ENOUGH = 180002, ARKUI_ERROR_CODE_NOT_CLONED_POINTER_EVENT = 180003, ARKUI_ERROR_CODE_POST_CLONED_COMPONENT_STATUS_ABNORMAL = 180004, ARKUI_ERROR_CODE_POST_CLONED_NO_COMPONENT_HIT_TO_RESPOND_TO_THE_EVENT = 180005, ARKUI_ERROR_CODE_INVALID_STYLED_STRING = 180101
} | Defines an enum for the error codes. | +| [ArkUI_ScrollSource](#arkui_scrollsource) {
ARKUI_SCROLL_SOURCE_DRAG = 0, ARKUI_SCROLL_SOURCE_FLING, ARKUI_SCROLL_SOURCE_EDGE_EFFECT, ARKUI_SCROLL_SOURCE_OTHER_USER_INPUT,
ARKUI_SCROLL_SOURCE_SCROLL_BAR, ARKUI_SCROLL_SOURCE_SCROLL_BAR_FLING, ARKUI_SCROLL_SOURCE_SCROLLER, ARKUI_SCROLL_SOURCE_ANIMATION
} | Enumerates the scrolling sources. | +| [ArkUI_SafeAreaType](#arkui_safeareatype) { ARKUI_SAFE_AREA_TYPE_SYSTEM = 1, ARKUI_SAFE_AREA_TYPE_CUTOUT = 1 << 1, ARKUI_SAFE_AREA_TYPE_KEYBOARD = 1 << 2 } | Enumerates the types of expanded safe areas. | +| [ArkUI_ListItemGroupArea](#arkui_listitemgrouparea) { ARKUI_LIST_ITEM_GROUP_AREA_OUTSIDE = 0, ARKUI_LIST_ITEM_SWIPE_AREA_NONE = 1, ARKUI_LIST_ITEM_SWIPE_AREA_ITEM = 2, ARKUI_LIST_ITEM_SWIPE_AREA_HEADER = 3, ARKUI_LIST_ITEM_SWIPE_AREA_FOOTER = 4
} | Enumerates the component areas.| +| [ArkUI_SafeAreaEdge](#arkui_safeareaedge) { ARKUI_SAFE_AREA_EDGE_TOP = 1, ARKUI_SAFE_AREA_EDGE_BOTTOM = 1 << 1, ARKUI_SAFE_AREA_EDGE_START = 1 << 2, ARKUI_SAFE_AREA_EDGE_END = 1 << 3 } | Enumerates the edges for expanding the safe area. | +| [ArkUI_NavDestinationState](#arkui_navdestinationstate) {
ARKUI_NAV_DESTINATION_STATE_ON_SHOW = 0, ARKUI_NAV_DESTINATION_STATE_ON_HIDE = 1, ARKUI_NAV_DESTINATION_STATE_ON_APPEAR = 2, ARKUI_NAV_DESTINATION_STATE_ON_DISAPPEAR = 3,
ARKUI_NAV_DESTINATION_STATE_ON_WILL_SHOW = 4, ARKUI_NAV_DESTINATION_STATE_ON_WILL_HIDE = 5, ARKUI_NAV_DESTINATION_STATE_ON_WILL_APPEAR = 6, ARKUI_NAV_DESTINATION_STATE_ON_WILL_DISAPPEAR = 7,
ARKUI_NAV_DESTINATION_STATE_ON_BACK_PRESS = 100
} | Defines an enum for the **NavDestination** component states. | +| [ArkUI_FocusMove](#arkui_focusmove) { ARKUI_FOCUS_MOVE_FORWARD = 0, ARKUI_FOCUS_MOVE_BACKWARD, ARKUI_FOCUS_MOVE_UP, ARKUI_FOCUS_MOVE_DOWN, ARKUI_FOCUS_MOVE_LEFT, ARKUI_FOCUS_MOVE_RIGHT, } | Enumerates the focus movement directions. | +| [ArkUI_RouterPageState](#arkui_routerpagestate) {
ARKUI_ROUTER_PAGE_STATE_ON_WILL_APPEAR = 0, ARKUI_ROUTER_PAGE_STATE_ON_WILL_DISAPPEAR = 1, ARKUI_ROUTER_PAGE_STATE_ON_SHOW = 2, ARKUI_ROUTER_PAGE_STATE_ON_HIDE = 3,
ARKUI_ROUTER_PAGE_STATE_ON_BACK_PRESS = 4
} | Enumerates the states of a page during routing. | | [ArkUI_DatePickerMode](#arkui_datepickermode) {
ARKUI_DATEPICKER_MODE_DATE = 0, ARKUI_DATEPICKER_YEAR_AND_MONTH = 1, ARKUI_DATEPICKER_MONTH_AND_DAY = 2
} | Enumerates the column display modes of the date picker. | + ### Functions -| Name| Description| +| Name| Description| | -------- | -------- | -| [ArkUI_DragEvent](#arkui_dragevent) \* [OH_ArkUI_NodeEvent_GetDragEvent](#oh_arkui_nodeevent_getdragevent) ([ArkUI_NodeEvent](#arkui_nodeevent-12) \*nodeEvent) | Obtains a **DragEvent** object from the specified **NodeEvent** object. | -| [ArkUI_PreDragStatus](#arkui_predragstatus) [OH_ArkUI_NodeEvent_GetPreDragStatus](#oh_arkui_nodeevent_getpredragstatus) ([ArkUI_NodeEvent](#arkui_nodeevent-12) \*nodeEvent) | Obtains the state prior to a drop and drop operation. | -| int32_t [OH_ArkUI_DragEvent_DisableDefaultDropAnimation](#oh_arkui_dragevent_disabledefaultdropanimation) ([ArkUI_DragEvent](#arkui_dragevent) \*event, bool disable) | Sets whether to disable the default drop animation, which is enabled by default. Use this API to apply a custom drop animation. | -| int32_t [OH_ArkUI_DragEvent_SetSuggestedDropOperation](#oh_arkui_dragevent_setsuggesteddropoperation) ([ArkUI_DragEvent](#arkui_dragevent) \*event, [ArkUI_DropProposal](#arkui_dropproposal) proposal) | Sets the data processing mode. | -| int32_t [OH_ArkUI_DragEvent_SetDragResult](#oh_arkui_dragevent_setdragresult) ([ArkUI_DragEvent](#arkui_dragevent) \*event, [ArkUI_DragResult](#arkui_dragresult) result) | Sets the result for a drag event. | -| int32_t [OH_ArkUI_DragEvent_SetData](#oh_arkui_dragevent_setdata) ([ArkUI_DragEvent](#arkui_dragevent) \*event, [OH_UdmfData](#oh_udmfdata) \*data) | Sets drag data for a drag event. | -| int32_t [OH_ArkUI_DragEvent_GetUdmfData](#oh_arkui_dragevent_getudmfdata) ([ArkUI_DragEvent](#arkui_dragevent) \*event, [OH_UdmfData](#oh_udmfdata) \*data) | Obtains the default drag data from a drag event. | -| int32_t [OH_ArkUI_DragEvent_GetDataTypesCount](#oh_arkui_dragevent_getdatatypescount) ([ArkUI_DragEvent](#arkui_dragevent) \*event, int32_t \*count) | Obtains the number of drag data types from a drag event. | -| int32_t [OH_ArkUI_DragEvent_GetDataTypes](#oh_arkui_dragevent_getdatatypes) ([ArkUI_DragEvent](#arkui_dragevent) \*event, char \*\*result[], int32_t length) | Obtains the type list of drag data types from a drag event. | -| int32_t [OH_ArkUI_DragEvent_GetDragResult](#oh_arkui_dragevent_getdragresult) ([ArkUI_DragEvent](#arkui_dragevent) \*event, [ArkUI_DragResult](#arkui_dragresult) \*result) | Obtains the drag and drop result from the drag event. | -| float [OH_ArkUI_DragEvent_GetPreviewTouchPointX](#oh_arkui_dragevent_getpreviewtouchpointx) ([ArkUI_DragEvent](#arkui_dragevent) \*event) | Obtains the X coordinate of the touch point for a drag preview from a drag event. | -| float [OH_ArkUI_DragEvent_GetPreviewTouchPointY](#oh_arkui_dragevent_getpreviewtouchpointy) ([ArkUI_DragEvent](#arkui_dragevent) \*event) | Obtains the Y coordinate of the touch point for a drag preview from a drag event. | -| float [OH_ArkUI_DragEvent_GetPreviewRectWidth](#oh_arkui_dragevent_getpreviewrectwidth) ([ArkUI_DragEvent](#arkui_dragevent) \*event) | Obtains the width of a drag preview from a drag event. | -| float [OH_ArkUI_DragEvent_GetPreviewRectHeight](#oh_arkui_dragevent_getpreviewrectheight) ([ArkUI_DragEvent](#arkui_dragevent) \*event) | Obtains the height of a drag preview from a drag event. | -| float [OH_ArkUI_DragEvent_GetTouchPointXToWindow](#oh_arkui_dragevent_gettouchpointxtowindow) ([ArkUI_DragEvent](#arkui_dragevent) \*event) | Obtains the X coordinate of the touch point relative to the window from a drag event. | -| float [OH_ArkUI_DragEvent_GetTouchPointYToWindow](#oh_arkui_dragevent_gettouchpointytowindow) ([ArkUI_DragEvent](#arkui_dragevent) \*event) | Obtains the Y coordinate of the touch point relative to the window from a drag event. | -| float [OH_ArkUI_DragEvent_GetTouchPointXToDisplay](#oh_arkui_dragevent_gettouchpointxtodisplay) ([ArkUI_DragEvent](#arkui_dragevent) \*event) | Obtains the X coordinate of the touch point relative to the display from a drag event. | -| float [OH_ArkUI_DragEvent_GetTouchPointYToDisplay](#oh_arkui_dragevent_gettouchpointytodisplay) ([ArkUI_DragEvent](#arkui_dragevent) \*event) | Obtains the Y coordinate of the touch point relative to the display from a drag event. | -| float [OH_ArkUI_DragEvent_GetVelocityX](#oh_arkui_dragevent_getvelocityx) ([ArkUI_DragEvent](#arkui_dragevent) \*event) | Obtains the dragging velocity along the x-axis. | -| float [OH_ArkUI_DragEvent_GetVelocityY](#oh_arkui_dragevent_getvelocityy) ([ArkUI_DragEvent](#arkui_dragevent) \*event) | Obtains the dragging velocity along the y-axis. | -| float [OH_ArkUI_DragEvent_GetVelocity](#oh_arkui_dragevent_getvelocity) ([ArkUI_DragEvent](#arkui_dragevent) \*event) | Obtains the dragging velocity along the main axis. | -| int32_t [OH_ArkUI_DragEvent_GetModifierKeyStates](#oh_arkui_dragevent_getmodifierkeystates) ([ArkUI_DragEvent](#arkui_dragevent) \*event, int64_t \*keys) | Obtains the pressed status of modifier keys from a drag event. | -| int32_t [OH_ArkUI_SetDragEventStrictReportWithNode](#oh_arkui_setdrageventstrictreportwithnode) ([ArkUI_NodeHandle](#arkui_nodehandle) node, bool enabled) | Sets whether to enable strict reporting on drag events. This feature is disabled by default, and you are advised to enable it. If this feature is disabled, the parent component is not notified when an item in it is dragged over its child component. If this feature is enabled, the component is notified of the dragged item's leaving, and the child component to which the dragged item is dropped is notified of the item's entering. This configuration is related to a specific UI instance. You can pass in a specific component node on the current UI instance for association. | -| int32_t [OH_ArkUI_SetDragEventStrictReportWithContext](#oh_arkui_setdrageventstrictreportwithcontext) ([ArkUI_ContextHandle](#arkui_contexthandle-12) uiContext, bool enabled) | Sets whether to enable strict reporting on drag events. This feature is disabled by default, and you are advised to enable it. If this feature is disabled, the parent component is not notified when an item in it is dragged over its child component. If this feature is enabled, the component is notified of the dragged item's leaving, and the child component to which the dragged item is dropped is notified of the item's entering. This configuration is related to a specific UI instance. You can pass in a specific UI instance for association. | -| int32_t [OH_ArkUI_SetNodeAllowedDropDataTypes](#oh_arkui_setnodealloweddropdatatypes) ([ArkUI_NodeHandle](#arkui_nodehandle) node, const char \*typesArray[], int32_t count) | Sets the types of data that can be dropped to the specified component. This API resets the settings configured through [OH_ArkUI_DisallowNodeAnyDropDataTypes](#oh_arkui_disallownodeanydropdatatypes) or [OH_ArkUI_AllowNodeAllDropDataTypes](#oh_arkui_allownodealldropdatatypes). | -| int32_t [OH_ArkUI_DisallowNodeAnyDropDataTypes](#oh_arkui_disallownodeanydropdatatypes) ([ArkUI_NodeHandle](#arkui_nodehandle) node) | Configures the specified component to disallow any data types. This API resets the settings configured through [OH_ArkUI_SetNodeAllowedDropDataTypes](#oh_arkui_setnodealloweddropdatatypes). | -| int32_t [OH_ArkUI_AllowNodeAllDropDataTypes](#oh_arkui_allownodealldropdatatypes) ([ArkUI_NodeHandle](#arkui_nodehandle) node) | Configures the specified component to allow any data types. This API resets the settings configured through [OH_ArkUI_SetNodeAllowedDropDataTypes](#oh_arkui_setnodealloweddropdatatypes). | -| int32_t [OH_ArkUI_SetNodeDraggable](#oh_arkui_setnodedraggable) ([ArkUI_NodeHandle](#arkui_nodehandle) node, bool enabled) | Sets whether the component is draggable. | -| int32_t [OH_ArkUI_SetNodeDragPreview](#oh_arkui_setnodedragpreview) ([ArkUI_NodeHandle](#arkui_nodehandle) node, [OH_PixelmapNative](#oh_pixelmapnative) \*preview) | Sets a custom drag preview for the specified component. | -| [ArkUI_DragPreviewOption](#arkui_dragpreviewoption) \* [OH_ArkUI_CreateDragPreviewOption](#oh_arkui_createdragpreviewoption) (void) | Creates an **ArkUI_DragPreviewOption** object. | -| void [OH_ArkUI_DragPreviewOption_Dispose](#oh_arkui_dragpreviewoption_dispose) ([ArkUI_DragPreviewOption](#arkui_dragpreviewoption) \*option) | Disposes of an **ArkUI_DragPreviewOption** object. | -| int32_t [OH_ArkUI_DragPreviewOption_SetScaleMode](#oh_arkui_dragpreviewoption_setscalemode) ([ArkUI_DragPreviewOption](#arkui_dragpreviewoption) \*option, [ArkUI_DragPreviewScaleMode](#arkui_dragpreviewscalemode) scaleMode) | Sets the scale mode for an **ArkUI_DragPreviewOption** object. | -| int32_t [OH_ArkUI_DragPreviewOption_SetDefaultShadowEnabled](#oh_arkui_dragpreviewoption_setdefaultshadowenabled) ([ArkUI_DragPreviewOption](#arkui_dragpreviewoption) \*option, bool enabled) | Sets whether to enable the shadow effect for an **ArkUI_DragPreviewOption** object. The shadow effect is enabled by default. | -| int32_t [OH_ArkUI_DragPreviewOption_SetDefaultRadiusEnabled](#oh_arkui_dragpreviewoption_setdefaultradiusenabled) ([ArkUI_DragPreviewOption](#arkui_dragpreviewoption) \*option, bool enabled) | Sets whether to enable the rounded corner effect for an **ArkUI_DragPreviewOption** object. The rounded corner effect is enabled by default. | -| int32_t [OH_ArkUI_DragPreviewOption_SetNumberBadgeEnabled](#oh_arkui_dragpreviewoption_setnumberbadgeenabled) ([ArkUI_DragPreviewOption](#arkui_dragpreviewoption) \*option, bool enabled) | Sets whether to enable the badge for an **ArkUI_DragPreviewOption** object. If this feature is enabled, a badge that contains the number of dragged items is displayed. | -| int32_t [OH_ArkUI_DragPreviewOption_SetBadgeNumber](#oh_arkui_dragpreviewoption_setbadgenumber) ([ArkUI_DragPreviewOption](#arkui_dragpreviewoption) \*option, uint32_t forcedNumber) | Sets the count on the badge. The settings will overwrite the value in the **SetDragPreviewNumberBadgeEnabled** API. | -| int32_t [OH_ArkUI_DragPreviewOption_SetDefaultAnimationBeforeLiftingEnabled](#oh_arkui_dragpreviewoption_setdefaultanimationbeforeliftingenabled) ([ArkUI_DragPreviewOption](#arkui_dragpreviewoption) \*option, bool enabled) | Sets whether to enable the default animation on a click or touch. | -| int32_t [OH_ArkUI_SetNodeDragPreviewOption](#oh_arkui_setnodedragpreviewoption) ([ArkUI_NodeHandle](#arkui_nodehandle) node, [ArkUI_DragPreviewOption](#arkui_dragpreviewoption) \*option) | Sets an **ArkUI_DragPreviewOption** object for the specified component. | -| [ArkUI_DragAction](#arkui_dragaction) \* [OH_ArkUI_CreateDragActionWithNode](#oh_arkui_createdragactionwithnode) ([ArkUI_NodeHandle](#arkui_nodehandle) node) | Creates a drag action object. The object needs to be associated with a UI instance, which can be specified by passing in a component node of the current UI instance. | -| [ArkUI_DragAction](#arkui_dragaction) \* [OH_ArkUI_CreateDragActionWithContext](#oh_arkui_createdragactionwithcontext) ([ArkUI_ContextHandle](#arkui_contexthandle-12) uiContext) | Creates a drag action object for the specified UI instance. | -| void [OH_ArkUI_DragAction_Dispose](#oh_arkui_dragaction_dispose) ([ArkUI_DragAction](#arkui_dragaction) \*dragAction) | Disposes of an **ArkUI_DragAction** object. | -| int32_t [OH_ArkUI_DragAction_SetPointerId](#oh_arkui_dragaction_setpointerid) ([ArkUI_DragAction](#arkui_dragaction) \*dragAction, int32_t pointer) | Sets the pointer ID. If only one finger is operating on the screen, the pointer ID is 0. In general cases, you can set the pointer ID to 0. | -| int32_t [OH_ArkUI_DragAction_SetPixelMaps](#oh_arkui_dragaction_setpixelmaps) ([ArkUI_DragAction](#arkui_dragaction) \*dragAction, [OH_PixelmapNative](#oh_pixelmapnative) \*pixelmapArray[], int32_t size) | Sets the drag previews for a drag action. | -| int32_t [OH_ArkUI_DragAction_SetTouchPointX](#oh_arkui_dragaction_settouchpointx) ([ArkUI_DragAction](#arkui_dragaction) \*dragAction, float x) | Sets the touch point relative to the upper left corner of the first drag preview (pixel map). | -| int32_t [OH_ArkUI_DragAction_SetTouchPointY](#oh_arkui_dragaction_settouchpointy) ([ArkUI_DragAction](#arkui_dragaction) \*dragAction, float y) | Sets the touch point relative to the upper left corner of the first drag preview (pixel map). | -| int32_t [OH_ArkUI_DragAction_SetData](#oh_arkui_dragaction_setdata) ([ArkUI_DragAction](#arkui_dragaction) \*dragAction, [OH_UdmfData](#oh_udmfdata) \*data) | Sets the drag data. | -| int32_t [OH_ArkUI_DragAction_SetDragPreviewOption](#oh_arkui_dragaction_setdragpreviewoption) ([ArkUI_DragAction](#arkui_dragaction) \*dragAction, [ArkUI_DragPreviewOption](#arkui_dragpreviewoption) \*option) | Sets an **ArkUI_DragPreviewOption** object for the specified drag action object. | -| int32_t [OH_ArkUI_DragAction_RegisterStatusListener](#oh_arkui_dragaction_registerstatuslistener) ([ArkUI_DragAction](#arkui_dragaction) \*dragAction, void \*userData, void(\*listener)([ArkUI_DragAndDropInfo](#arkui_draganddropinfo) \*dragAndDropInfo, void \*userData)) | Registers a drag status listener. This listener can be used to check whether the data is successfully received and processed. | -| void [OH_ArkUI_DragAction_UnregisterStatusListener](#oh_arkui_dragaction_unregisterstatuslistener) ([ArkUI_DragAction](#arkui_dragaction) \*dragAction) | Unregisters a drag status listener. | -| [ArkUI_DragStatus](#arkui_dragstatus) [OH_ArkUI_DragAndDropInfo_GetDragStatus](#oh_arkui_draganddropinfo_getdragstatus) ([ArkUI_DragAndDropInfo](#arkui_draganddropinfo) \*dragAndDropInfo) | Obtains the drag status of a drag action. | -| [ArkUI_DragEvent](#arkui_dragevent) \* [OH_ArkUI_DragAndDropInfo_GetDragEvent](#oh_arkui_draganddropinfo_getdragevent) ([ArkUI_DragAndDropInfo](#arkui_draganddropinfo) \*dragAndDropInfo) | Obtains a drag event based on the specified drag and drop information. The drag event can then be used to obtain the drag result. | -| int32_t [OH_ArkUI_StartDrag](#oh_arkui_startdrag) ([ArkUI_DragAction](#arkui_dragaction) \*dragAction) | Initiates a drag action through the specified **DragAction** object. | -| [ArkUI_DrawableDescriptor](#arkui_drawabledescriptor) \* [OH_ArkUI_DrawableDescriptor_CreateFromPixelMap](#oh_arkui_drawabledescriptor_createfrompixelmap) ([OH_PixelmapNativeHandle](#oh_pixelmapnativehandle) pixelMap) | Creates a **DrawableDescriptor** object from a **PixelMap** object. | -| [ArkUI_DrawableDescriptor](#arkui_drawabledescriptor) \* [OH_ArkUI_DrawableDescriptor_CreateFromAnimatedPixelMap](#oh_arkui_drawabledescriptor_createfromanimatedpixelmap) ([OH_PixelmapNativeHandle](#oh_pixelmapnativehandle) \*array, int32_t size) | Creates a **DrawableDescriptor** object from an array of **PixelMap** objects. | -| void [OH_ArkUI_DrawableDescriptor_Dispose](#oh_arkui_drawabledescriptor_dispose) ([ArkUI_DrawableDescriptor](#arkui_drawabledescriptor) \*drawableDescriptor) | Disposes of the pointer to a **DrawableDescriptor** object. | -| [OH_PixelmapNativeHandle](#oh_pixelmapnativehandle) [OH_ArkUI_DrawableDescriptor_GetStaticPixelMap](#oh_arkui_drawabledescriptor_getstaticpixelmap) ([ArkUI_DrawableDescriptor](#arkui_drawabledescriptor) \*drawableDescriptor) | Obtains the pointer to a **PixelMap** object. | -| [OH_PixelmapNativeHandle](#oh_pixelmapnativehandle) \* [OH_ArkUI_DrawableDescriptor_GetAnimatedPixelMapArray](#oh_arkui_drawabledescriptor_getanimatedpixelmaparray) ([ArkUI_DrawableDescriptor](#arkui_drawabledescriptor) \*drawableDescriptor) | Obtains an array of **PixelMap** objects for playing an animation. | -| int32_t [OH_ArkUI_DrawableDescriptor_GetAnimatedPixelMapArraySize](#oh_arkui_drawabledescriptor_getanimatedpixelmaparraysize) ([ArkUI_DrawableDescriptor](#arkui_drawabledescriptor) \*drawableDescriptor) | Obtains an array of **PixelMap** objects for playing an animation. | -| void [OH_ArkUI_DrawableDescriptor_SetAnimationDuration](#oh_arkui_drawabledescriptor_setanimationduration) ([ArkUI_DrawableDescriptor](#arkui_drawabledescriptor) \*drawableDescriptor, int32_t duration) | Sets the total playback duration for a pixel map image array. | -| int32_t [OH_ArkUI_DrawableDescriptor_GetAnimationDuration](#oh_arkui_drawabledescriptor_getanimationduration) ([ArkUI_DrawableDescriptor](#arkui_drawabledescriptor) \*drawableDescriptor) | Obtains the total playback duration for a pixel map image array. | -| void [OH_ArkUI_DrawableDescriptor_SetAnimationIteration](#oh_arkui_drawabledescriptor_setanimationiteration) ([ArkUI_DrawableDescriptor](#arkui_drawabledescriptor) \*drawableDescriptor, int32_t iteration) | Sets the number of times that a pixel map image array is played. | -| int32_t [OH_ArkUI_DrawableDescriptor_GetAnimationIteration](#oh_arkui_drawabledescriptor_getanimationiteration) ([ArkUI_DrawableDescriptor](#arkui_drawabledescriptor) \*drawableDescriptor) | Obtains the number of times that a pixel map image array is played. | -| [ArkUI_AnimateOption](#arkui_animateoption) \* [OH_ArkUI_AnimateOption_Create](#oh_arkui_animateoption_create) () | Creates an animation configuration. | -| void [OH_ArkUI_AnimateOption_Dispose](#oh_arkui_animateoption_dispose) ([ArkUI_AnimateOption](#arkui_animateoption) \*option) | Destroys an animation configuration. | -| int32_t [OH_ArkUI_AnimateOption_GetDuration](#oh_arkui_animateoption_getduration) ([ArkUI_AnimateOption](#arkui_animateoption) \*option) | Obtains the animation duration, in milliseconds. | -| float [OH_ArkUI_AnimateOption_GetTempo](#oh_arkui_animateoption_gettempo) ([ArkUI_AnimateOption](#arkui_animateoption) \*option) | Obtains the playback speed of an animation. | -| [ArkUI_AnimationCurve](#arkui_animationcurve) [OH_ArkUI_AnimateOption_GetCurve](#oh_arkui_animateoption_getcurve) ([ArkUI_AnimateOption](#arkui_animateoption) \*option) | Obtains an animation curve. | -| int32_t [OH_ArkUI_AnimateOption_GetDelay](#oh_arkui_animateoption_getdelay) ([ArkUI_AnimateOption](#arkui_animateoption) \*option) | Obtains the animation delay, in milliseconds. | -| int32_t [OH_ArkUI_AnimateOption_GetIterations](#oh_arkui_animateoption_getiterations) ([ArkUI_AnimateOption](#arkui_animateoption) \*option) | Obtains the number of times that an animation is played. | -| [ArkUI_AnimationPlayMode](#arkui_animationplaymode) [OH_ArkUI_AnimateOption_GetPlayMode](#oh_arkui_animateoption_getplaymode) ([ArkUI_AnimateOption](#arkui_animateoption) \*option) | Obtains the playback mode of an animation. | -| [ArkUI_ExpectedFrameRateRange](_ark_u_i___expected_frame_rate_range.md) \* [OH_ArkUI_AnimateOption_GetExpectedFrameRateRange](#oh_arkui_animateoption_getexpectedframeraterange) ([ArkUI_AnimateOption](#arkui_animateoption) \*option) | Obtains the expected frame rate range of an animation. | -| void [OH_ArkUI_AnimateOption_SetDuration](#oh_arkui_animateoption_setduration) ([ArkUI_AnimateOption](#arkui_animateoption) \*option, int32_t value) | Sets the animation duration. | -| void [OH_ArkUI_AnimateOption_SetTempo](#oh_arkui_animateoption_settempo) ([ArkUI_AnimateOption](#arkui_animateoption) \*option, float value) | Sets the playback speed of an animation. | -| void [OH_ArkUI_AnimateOption_SetCurve](#oh_arkui_animateoption_setcurve) ([ArkUI_AnimateOption](#arkui_animateoption) \*option, [ArkUI_AnimationCurve](#arkui_animationcurve) value) | Animation curve. | -| void [OH_ArkUI_AnimateOption_SetDelay](#oh_arkui_animateoption_setdelay) ([ArkUI_AnimateOption](#arkui_animateoption) \*option, int32_t value) | Sets the animation delay. | -| void [OH_ArkUI_AnimateOption_SetIterations](#oh_arkui_animateoption_setiterations) ([ArkUI_AnimateOption](#arkui_animateoption) \*option, int32_t value) | Number of times that the frame animation is played. | -| void [OH_ArkUI_AnimateOption_SetPlayMode](#oh_arkui_animateoption_setplaymode) ([ArkUI_AnimateOption](#arkui_animateoption) \*option, [ArkUI_AnimationPlayMode](#arkui_animationplaymode) value) | Sets the playback mode for an animation. | -| void [OH_ArkUI_AnimateOption_SetExpectedFrameRateRange](#oh_arkui_animateoption_setexpectedframeraterange) ([ArkUI_AnimateOption](#arkui_animateoption) \*option, [ArkUI_ExpectedFrameRateRange](_ark_u_i___expected_frame_rate_range.md) \*value) | Defines the expected frame rate range of the animation. | -| void [OH_ArkUI_AnimateOption_SetICurve](#oh_arkui_animateoption_seticurve) ([ArkUI_AnimateOption](#arkui_animateoption) \*option, [ArkUI_CurveHandle](#arkui_curvehandle) value) | Sets the animation curve for an animation. | -| [ArkUI_CurveHandle](#arkui_curvehandle) [OH_ArkUI_AnimateOption_GetICurve](#oh_arkui_animateoption_geticurve) ([ArkUI_AnimateOption](#arkui_animateoption) \*option) | Obtains the animation curve of an animation. | -| [ArkUI_KeyframeAnimateOption](#arkui_keyframeanimateoption) \* [OH_ArkUI_KeyframeAnimateOption_Create](#oh_arkui_keyframeanimateoption_create) (int32_t size) | Obtains the keyframe animation parameters. | -| void [OH_ArkUI_KeyframeAnimateOption_Dispose](#oh_arkui_keyframeanimateoption_dispose) ([ArkUI_KeyframeAnimateOption](#arkui_keyframeanimateoption) \*option) | Destroys a keyframe animation parameter object. | -| int32_t [OH_ArkUI_KeyframeAnimateOption_SetDelay](#oh_arkui_keyframeanimateoption_setdelay) ([ArkUI_KeyframeAnimateOption](#arkui_keyframeanimateoption) \*option, int32_t value) | Sets the overall delay of a keyframe animation, in milliseconds. By default, the keyframe animation is played without delay. | -| int32_t [OH_ArkUI_KeyframeAnimateOption_SetIterations](#oh_arkui_keyframeanimateoption_setiterations) ([ArkUI_KeyframeAnimateOption](#arkui_keyframeanimateoption) \*option, int32_t value) | Sets the number of times that the keyframe animation is played. By default, the animation is played once. The value **-1** indicates that the animation is played for an unlimited number of times. The value **0** indicates that there is no animation. | -| int32_t [OH_ArkUI_KeyframeAnimateOption_RegisterOnFinishCallback](#oh_arkui_keyframeanimateoption_registeronfinishcallback) ([ArkUI_KeyframeAnimateOption](#arkui_keyframeanimateoption) \*option, void \*userData, void(\*onFinish)(void \*userData)) | Sets the callback invoked when the keyframe animation playback is complete. This API is called after the keyframe animation has played for the specified number of times. | -| int32_t [OH_ArkUI_KeyframeAnimateOption_SetDuration](#oh_arkui_keyframeanimateoption_setduration) ([ArkUI_KeyframeAnimateOption](#arkui_keyframeanimateoption) \*option, int32_t value, int32_t index) | Sets the duration of a keyframe animation, in milliseconds. | -| int32_t [OH_ArkUI_KeyframeAnimateOption_SetCurve](#oh_arkui_keyframeanimateoption_setcurve) ([ArkUI_KeyframeAnimateOption](#arkui_keyframeanimateoption) \*option, [ArkUI_CurveHandle](#arkui_curvehandle) value, int32_t index) | Sets the animation curve for a specific keyframe in a keyframe animation. | -| int32_t [OH_ArkUI_KeyframeAnimateOption_RegisterOnEventCallback](#oh_arkui_keyframeanimateoption_registeroneventcallback) ([ArkUI_KeyframeAnimateOption](#arkui_keyframeanimateoption) \*option, void \*userData, void(\*event)(void \*userData), int32_t index) | Sets the closure function of the state at the time of the keyframe, that is, the state to be reached at the time of the keyframe. | -| int32_t [OH_ArkUI_KeyframeAnimateOption_GetDelay](#oh_arkui_keyframeanimateoption_getdelay) ([ArkUI_KeyframeAnimateOption](#arkui_keyframeanimateoption) \*option) | Obtains the overall delay of a keyframe animation | -| int32_t [OH_ArkUI_KeyframeAnimateOption_GetIterations](#oh_arkui_keyframeanimateoption_getiterations) ([ArkUI_KeyframeAnimateOption](#arkui_keyframeanimateoption) \*option) | Obtains the number of times that a keyframe animation is played. | -| int32_t [OH_ArkUI_KeyframeAnimateOption_GetDuration](#oh_arkui_keyframeanimateoption_getduration) ([ArkUI_KeyframeAnimateOption](#arkui_keyframeanimateoption) \*option, int32_t index) | Obtains the duration of a specific state in a keyframe animation. | -| [ArkUI_CurveHandle](#arkui_curvehandle) [OH_ArkUI_KeyframeAnimateOption_GetCurve](#oh_arkui_keyframeanimateoption_getcurve) ([ArkUI_KeyframeAnimateOption](#arkui_keyframeanimateoption) \*option, int32_t index) | Obtains the animation curve of a specific state in a keyframe animation. | -| [ArkUI_AnimatorOption](#arkui_animatoroption) \* [OH_ArkUI_AnimatorOption_Create](#oh_arkui_animatoroption_create) (int32_t keyframeSize) | Creates an animator parameter object. | -| void [OH_ArkUI_AnimatorOption_Dispose](#oh_arkui_animatoroption_dispose) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option) | Destroys an animator parameter object. | -| int32_t [OH_ArkUI_AnimatorOption_SetDuration](#oh_arkui_animatoroption_setduration) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option, int32_t value) | Sets the duration of an animation, in milliseconds. | -| int32_t [OH_ArkUI_AnimatorOption_SetDelay](#oh_arkui_animatoroption_setdelay) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option, int32_t value) | Sets the delay of animation playback, in milliseconds. | -| int32_t [OH_ArkUI_AnimatorOption_SetIterations](#oh_arkui_animatoroption_setiterations) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option, int32_t value) | Number of times that the frame animation is played. The value **0** means not to play the animation, and **-1** means to play the animation for an unlimited number of times. | -| int32_t [OH_ArkUI_AnimatorOption_SetFill](#oh_arkui_animatoroption_setfill) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option, [ArkUI_AnimationFill](#arkui_animationfill) value) | Sets whether the animator animation is restored to the initial state after being executed. | -| int32_t [OH_ArkUI_AnimatorOption_SetDirection](#oh_arkui_animatoroption_setdirection) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option, [ArkUI_AnimationDirection](#arkui_animationdirection) value) | Sets the playback direction. | -| int32_t [OH_ArkUI_AnimatorOption_SetCurve](#oh_arkui_animatoroption_setcurve) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option, [ArkUI_CurveHandle](#arkui_curvehandle) value) | Sets the interpolation curve for the animation of an animator. | -| int32_t [OH_ArkUI_AnimatorOption_SetBegin](#oh_arkui_animatoroption_setbegin) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option, float value) | Sets the interpolation start point for the animation of an animator. | -| int32_t [OH_ArkUI_AnimatorOption_SetEnd](#oh_arkui_animatoroption_setend) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option, float value) | Sets the interpolation end point for the animation of an animator. | -| int32_t [OH_ArkUI_AnimatorOption_SetExpectedFrameRateRange](#oh_arkui_animatoroption_setexpectedframeraterange) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option, [ArkUI_ExpectedFrameRateRange](_ark_u_i___expected_frame_rate_range.md) \*value) | Sets the expected frame rate range of an animation. | -| int32_t [OH_ArkUI_AnimatorOption_SetKeyframe](#oh_arkui_animatoroption_setkeyframe) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option, float time, float value, int32_t index) | Sets the keyframe parameters of an animation. | -| int32_t [OH_ArkUI_AnimatorOption_SetKeyframeCurve](#oh_arkui_animatoroption_setkeyframecurve) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option, [ArkUI_CurveHandle](#arkui_curvehandle) value, int32_t index) | Sets the keyframe curve type for the animation of an animator. | -| int32_t [OH_ArkUI_AnimatorOption_GetDuration](#oh_arkui_animatoroption_getduration) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option) | Obtains the duration for playing an animation. | -| int32_t [OH_ArkUI_AnimatorOption_GetDelay](#oh_arkui_animatoroption_getdelay) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option) | Obtains the delay for playing an animation. | -| int32_t [OH_ArkUI_AnimatorOption_GetIterations](#oh_arkui_animatoroption_getiterations) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option) | Obtains the number of times that an animation is played. | -| [ArkUI_AnimationFill](#arkui_animationfill) [OH_ArkUI_AnimatorOption_GetFill](#oh_arkui_animatoroption_getfill) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option) | Obtains whether the animator animation is restored to the initial state after being executed. | -| [ArkUI_AnimationDirection](#arkui_animationdirection) [OH_ArkUI_AnimatorOption_GetDirection](#oh_arkui_animatoroption_getdirection) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option) | Obtains the playback direction of an animation. | -| [ArkUI_CurveHandle](#arkui_curvehandle) [OH_ArkUI_AnimatorOption_GetCurve](#oh_arkui_animatoroption_getcurve) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option) | Obtains the interpolation curve of the animation of an animator. | -| float [OH_ArkUI_AnimatorOption_GetBegin](#oh_arkui_animatoroption_getbegin) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option) | Obtains the interpolation start point of an animation. | -| float [OH_ArkUI_AnimatorOption_GetEnd](#oh_arkui_animatoroption_getend) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option) | Obtains the interpolation end point of an animation. | -| [ArkUI_ExpectedFrameRateRange](_ark_u_i___expected_frame_rate_range.md) \* [OH_ArkUI_AnimatorOption_GetExpectedFrameRateRange](#oh_arkui_animatoroption_getexpectedframeraterange) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option) | Obtains the expected frame rate range of an animation. | -| float [OH_ArkUI_AnimatorOption_GetKeyframeTime](#oh_arkui_animatoroption_getkeyframetime) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option, int32_t index) | Obtains the keyframe time of an animation. | -| float [OH_ArkUI_AnimatorOption_GetKeyframeValue](#oh_arkui_animatoroption_getkeyframevalue) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option, int32_t index) | Obtains the keyframe value of an animation. | -| [ArkUI_CurveHandle](#arkui_curvehandle) [OH_ArkUI_AnimatorOption_GetKeyframeCurve](#oh_arkui_animatoroption_getkeyframecurve) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option, int32_t index) | Obtains the interpolation curve for a keyframe in the animation of an animator. | -| void \* [OH_ArkUI_AnimatorEvent_GetUserData](#oh_arkui_animatorevent_getuserdata) (ArkUI_AnimatorEvent \*event) | Obtains the custom object in an animation event object. | -| void \* [OH_ArkUI_AnimatorOnFrameEvent_GetUserData](#oh_arkui_animatoronframeevent_getuserdata) (ArkUI_AnimatorOnFrameEvent \*event) | Obtains the custom object in an animation event object. | -| float [OH_ArkUI_AnimatorOnFrameEvent_GetValue](#oh_arkui_animatoronframeevent_getvalue) (ArkUI_AnimatorOnFrameEvent \*event) | Obtains the current progress in an animation event object. | -| int32_t [OH_ArkUI_AnimatorOption_RegisterOnFrameCallback](#oh_arkui_animatoroption_registeronframecallback) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option, void \*userData, void(\*callback)(ArkUI_AnimatorOnFrameEvent \*event)) | Sets the callback invoked when the animator receives a frame. | -| int32_t [OH_ArkUI_AnimatorOption_RegisterOnFinishCallback](#oh_arkui_animatoroption_registeronfinishcallback) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option, void \*userData, void(\*callback)(ArkUI_AnimatorEvent \*event)) | Sets the callback invoked when the animation playback is complete. | -| int32_t [OH_ArkUI_AnimatorOption_RegisterOnCancelCallback](#oh_arkui_animatoroption_registeroncancelcallback) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option, void \*userData, void(\*callback)(ArkUI_AnimatorEvent \*event)) | Sets the callback invoked when the animation playback is canceled. | -| int32_t [OH_ArkUI_AnimatorOption_RegisterOnRepeatCallback](#oh_arkui_animatoroption_registeronrepeatcallback) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option, void \*userData, void(\*callback)(ArkUI_AnimatorEvent \*event)) | Sets the callback invoked when the animation playback is repeated. | -| int32_t [OH_ArkUI_Animator_ResetAnimatorOption](#oh_arkui_animator_resetanimatoroption) ([ArkUI_AnimatorHandle](#arkui_animatorhandle) animator, [ArkUI_AnimatorOption](#arkui_animatoroption) \*option) | Resets an animator configuration. | -| int32_t [OH_ArkUI_Animator_Play](#oh_arkui_animator_play) ([ArkUI_AnimatorHandle](#arkui_animatorhandle) animator) | Starts the animation of an animator. | -| int32_t [OH_ArkUI_Animator_Finish](#oh_arkui_animator_finish) ([ArkUI_AnimatorHandle](#arkui_animatorhandle) animator) | Ends the animation of an animator. | -| int32_t [OH_ArkUI_Animator_Pause](#oh_arkui_animator_pause) ([ArkUI_AnimatorHandle](#arkui_animatorhandle) animator) | Pauses the animation of an animator. | -| int32_t [OH_ArkUI_Animator_Cancel](#oh_arkui_animator_cancel) ([ArkUI_AnimatorHandle](#arkui_animatorhandle) animator) | Cancels the animation of an animator. | -| int32_t [OH_ArkUI_Animator_Reverse](#oh_arkui_animator_reverse) ([ArkUI_AnimatorHandle](#arkui_animatorhandle) animator) | Plays this animation in reverse order. | -| [ArkUI_CurveHandle](#arkui_curvehandle) [OH_ArkUI_Curve_CreateCurveByType](#oh_arkui_curve_createcurvebytype) ([ArkUI_AnimationCurve](#arkui_animationcurve) curve) | Implements initialization for the interpolation curve, which is used to create an interpolation curve based on the input parameter. | -| [ArkUI_CurveHandle](#arkui_curvehandle) [OH_ArkUI_Curve_CreateStepsCurve](#oh_arkui_curve_createstepscurve) (int32_t count, bool end) | Creates a step curve. | -| [ArkUI_CurveHandle](#arkui_curvehandle) [OH_ArkUI_Curve_CreateCubicBezierCurve](#oh_arkui_curve_createcubicbeziercurve) (float x1, float y1, float x2, float y2) | Creates a cubic Bezier curve. | -| [ArkUI_CurveHandle](#arkui_curvehandle) [OH_ArkUI_Curve_CreateSpringCurve](#oh_arkui_curve_createspringcurve) (float velocity, float mass, float stiffness, float damping) | Creates a spring curve. The curve shape is subject to the spring parameters, and the animation duration is subject to the **duration** parameter in **animation** and **animateTo**. | -| [ArkUI_CurveHandle](#arkui_curvehandle) [OH_ArkUI_Curve_CreateSpringMotion](#oh_arkui_curve_createspringmotion) (float response, float dampingFraction, float overlapDuration) | Creates a spring animation curve. If multiple spring animations are applied to the same attribute of an object, each animation replaces their predecessor and inherits the velocity. | -| [ArkUI_CurveHandle](#arkui_curvehandle) [OH_ArkUI_Curve_CreateResponsiveSpringMotion](#oh_arkui_curve_createresponsivespringmotion) (float response, float dampingFraction, float overlapDuration) | Creates a responsive spring animation curve. It is a special case of **springMotion**, with the only difference in the default values. It can be used together with **springMotion**. | -| [ArkUI_CurveHandle](#arkui_curvehandle) [OH_ArkUI_Curve_CreateInterpolatingSpring](#oh_arkui_curve_createinterpolatingspring) (float velocity, float mass, float stiffness, float damping) | Creates an interpolating spring curve animated from 0 to 1. The actual animation value is calculated based on the curve. | -| [ArkUI_CurveHandle](#arkui_curvehandle) [OH_ArkUI_Curve_CreateCustomCurve](#oh_arkui_curve_createcustomcurve) (void \*userData, float(\*interpolate)(float fraction, void \*userdata)) | Creates a custom curve. | -| void [OH_ArkUI_Curve_DisposeCurve](#oh_arkui_curve_disposecurve) ([ArkUI_CurveHandle](#arkui_curvehandle) curveHandle) | Disposes of a custom curve. | -| [ArkUI_TransitionEffect](#arkui_transitioneffect) \* [OH_ArkUI_CreateOpacityTransitionEffect](#oh_arkui_createopacitytransitioneffect) (float opacity) | Creates an opacity object for component transition. | -| [ArkUI_TransitionEffect](#arkui_transitioneffect) \* [OH_ArkUI_CreateTranslationTransitionEffect](#oh_arkui_createtranslationtransitioneffect) ([ArkUI_TranslationOptions](_ark_u_i___translation_options.md) \*translate) | Creates a translation object for component transition. | -| [ArkUI_TransitionEffect](#arkui_transitioneffect) \* [OH_ArkUI_CreateScaleTransitionEffect](#oh_arkui_createscaletransitioneffect) ([ArkUI_ScaleOptions](_ark_u_i___scale_options.md) \*scale) | Creates a scaling object for component transition. | -| [ArkUI_TransitionEffect](#arkui_transitioneffect) \* [OH_ArkUI_CreateRotationTransitionEffect](#oh_arkui_createrotationtransitioneffect) ([ArkUI_RotationOptions](_ark_u_i___rotation_options.md) \*rotate) | Creates a rotation object for component transition. | -| [ArkUI_TransitionEffect](#arkui_transitioneffect) \* [OH_ArkUI_CreateMovementTransitionEffect](#oh_arkui_createmovementtransitioneffect) ([ArkUI_TransitionEdge](#arkui_transitionedge) move) | Creates a movement object for component transition. | -| [ArkUI_TransitionEffect](#arkui_transitioneffect) \* [OH_ArkUI_CreateAsymmetricTransitionEffect](#oh_arkui_createasymmetrictransitioneffect) ([ArkUI_TransitionEffect](#arkui_transitioneffect) \*appear, [ArkUI_TransitionEffect](#arkui_transitioneffect) \*disappear) | Creates an asymmetric transition effect. | -| void [OH_ArkUI_TransitionEffect_Dispose](#oh_arkui_transitioneffect_dispose) ([ArkUI_TransitionEffect](#arkui_transitioneffect) \*option) | Disposes of a transition effect. | -| int32_t [OH_ArkUI_TransitionEffect_Combine](#oh_arkui_transitioneffect_combine) ([ArkUI_TransitionEffect](#arkui_transitioneffect) \*option, [ArkUI_TransitionEffect](#arkui_transitioneffect) \*combine) | Sets a combination of transition effects. | -| int32_t [OH_ArkUI_TransitionEffect_SetAnimation](#oh_arkui_transitioneffect_setanimation) ([ArkUI_TransitionEffect](#arkui_transitioneffect) \*option, [ArkUI_AnimateOption](#arkui_animateoption) \*animation) | Sets transition effect animation settings. | -| void [OH_ArkUI_DialogDismissEvent_SetShouldBlockDismiss](#oh_arkui_dialogdismissevent_setshouldblockdismiss) ([ArkUI_DialogDismissEvent](#arkui_dialogdismissevent) \*event, bool shouldBlockDismiss) | Sets whether to block the system behavior of dismissing a dialog box. | -| void \* [OH_ArkUI_DialogDismissEvent_GetUserData](#oh_arkui_dialogdismissevent_getuserdata) ([ArkUI_DialogDismissEvent](#arkui_dialogdismissevent) \*event) | Obtains the pointer to user data in a dialog box dismiss event object. | -| int32_t [OH_ArkUI_DialogDismissEvent_GetDismissReason](#oh_arkui_dialogdismissevent_getdismissreason) ([ArkUI_DialogDismissEvent](#arkui_dialogdismissevent) \*event) | Obtains the dismissal reason from a dialog box dismiss event object. | -| bool [OH_ArkUI_GestureInterruptInfo_GetSystemFlag](#oh_arkui_gestureinterruptinfo_getsystemflag) (const ArkUI_GestureInterruptInfo \*event) | Checks whether a gesture is a built-in gesture of the component. | -| ArkUI_GestureRecognizer \* [OH_ArkUI_GestureInterruptInfo_GetRecognizer](#oh_arkui_gestureinterruptinfo_getrecognizer) (const ArkUI_GestureInterruptInfo \*event) | Obtains the pointer to interrupted gesture recognizer. | -| ArkUI_GestureEvent \* [OH_ArkUI_GestureInterruptInfo_GetGestureEvent](#oh_arkui_gestureinterruptinfo_getgestureevent) (const ArkUI_GestureInterruptInfo \*event) | Obtains the pointer to the interrupted gesture event. | -| int32_t [OH_ArkUI_GestureInterruptInfo_GetSystemRecognizerType](#oh_arkui_gestureinterruptinfo_getsystemrecognizertype) (const ArkUI_GestureInterruptInfo \*event) | Obtains the type of the system gesture to trigger. | -| [ArkUI_GestureEventActionType](#arkui_gestureeventactiontype) [OH_ArkUI_GestureEvent_GetActionType](#oh_arkui_gestureevent_getactiontype) (const ArkUI_GestureEvent \*event) | Obtains the gesture event type. | -| [ArkUI_NodeHandle](#arkui_nodehandle) [OH_ArkUI_GestureEvent_GetResponseNode](#oh_arkui_gestureevent_getresponsenode) (ArkUI_GestureEvent \*event) | Obtains the node that responds to the gesture. | -| const [ArkUI_UIInputEvent](_ark_u_i___event_module.md#arkui_uiinputevent) \* [OH_ArkUI_GestureEvent_GetRawInputEvent](#oh_arkui_gestureevent_getrawinputevent) (const ArkUI_GestureEvent \*event) | Obtains gesture input. | -| int32_t [OH_ArkUI_LongPress_GetRepeatCount](#oh_arkui_longpress_getrepeatcount) (const ArkUI_GestureEvent \*event) | Obtains the number of times that a long press gesture is triggered periodically. | -| float [OH_ArkUI_PanGesture_GetVelocity](#oh_arkui_pangesture_getvelocity) (const ArkUI_GestureEvent \*event) | Obtains the velocity of a pan gesture along the main axis. | -| float [OH_ArkUI_PanGesture_GetVelocityX](#oh_arkui_pangesture_getvelocityx) (const ArkUI_GestureEvent \*event) | Obtains the velocity of a pan gesture along the x-axis. | -| float [OH_ArkUI_PanGesture_GetVelocityY](#oh_arkui_pangesture_getvelocityy) (const ArkUI_GestureEvent \*event) | Obtains the velocity of a pan gesture along the y-axis. | -| float [OH_ArkUI_PanGesture_GetOffsetX](#oh_arkui_pangesture_getoffsetx) (const ArkUI_GestureEvent \*event) | Obtains the relative offset of a pan gesture along the x-axis. | -| float [OH_ArkUI_PanGesture_GetOffsetY](#oh_arkui_pangesture_getoffsety) (const ArkUI_GestureEvent \*event) | Obtains the relative offset of a pan gesture along the y-axis. | -| float [OH_ArkUI_SwipeGesture_GetAngle](#oh_arkui_swipegesture_getangle) (const ArkUI_GestureEvent \*event) | Obtains the angle information of the swipe gesture. | -| float [OH_ArkUI_SwipeGesture_GetVelocity](#oh_arkui_swipegesture_getvelocity) (const ArkUI_GestureEvent \*event) | Obtains the average velocity of all fingers used in the swipe gesture. | -| float [OH_ArkUI_RotationGesture_GetAngle](#oh_arkui_rotationgesture_getangle) (const ArkUI_GestureEvent \*event) | Obtains the angle information of a rotation gesture. | -| float [OH_ArkUI_PinchGesture_GetScale](#oh_arkui_pinchgesture_getscale) (const ArkUI_GestureEvent \*event) | Obtains the scale ratio of a pinch gesture. | -| float [OH_ArkUI_PinchGesture_GetCenterX](#oh_arkui_pinchgesture_getcenterx) (const ArkUI_GestureEvent \*event) | Obtains the X coordinate of the center of the pinch gesture, in vp, relative to the upper left corner of the current component. | -| float [OH_ArkUI_PinchGesture_GetCenterY](#oh_arkui_pinchgesture_getcentery) (const ArkUI_GestureEvent \*event) | Obtains the Y coordinate of the center of the pinch gesture, in vp, relative to the upper left corner of the current component. | -| [ArkUI_NodeHandle](#arkui_nodehandle) [OH_ArkUI_GestureEvent_GetNode](#oh_arkui_gestureevent_getnode) (const ArkUI_GestureEvent \*event) | Obtains the ArkUI component to which the gesture is bound. | -| int32_t [OH_ArkUI_GetResponseRecognizersFromInterruptInfo](#oh_arkui_getresponserecognizersfrominterruptinfo) (const ArkUI_GestureInterruptInfo \*event, [ArkUI_GestureRecognizerHandleArray](#arkui_gesturerecognizerhandlearray) \*responseChain, int32_t \*count) | Obtains information about a gesture response chain. | -| int32_t [OH_ArkUI_SetGestureRecognizerEnabled](#oh_arkui_setgesturerecognizerenabled) (ArkUI_GestureRecognizer \*recognizer, bool enabled) | Sets the enabled state of a gesture recognizer. | -| bool [OH_ArkUI_GetGestureRecognizerEnabled](#oh_arkui_getgesturerecognizerenabled) (ArkUI_GestureRecognizer \*recognizer) | Obtains the enabled state of a gesture recognizer. | -| int32_t [OH_ArkUI_GetGestureRecognizerState](#oh_arkui_getgesturerecognizerstate) (ArkUI_GestureRecognizer \*recognizer, [ArkUI_GestureRecognizerState](#arkui_gesturerecognizerstate) \*state) | Obtains the state of a gesture recognizer. | -| int32_t [OH_ArkUI_GetGestureEventTargetInfo](#oh_arkui_getgestureeventtargetinfo) (ArkUI_GestureRecognizer \*recognizer, [ArkUI_GestureEventTargetInfo](#arkui_gestureeventtargetinfo) \*\*info) | Obtains the information about a gesture event target. | -| int32_t [OH_ArkUI_GestureEventTargetInfo_IsScrollBegin](#oh_arkui_gestureeventtargetinfo_isscrollbegin) ([ArkUI_GestureEventTargetInfo](#arkui_gestureeventtargetinfo) \*info, bool \*ret) | Obtains whether this scroll container is scrolled to the top. | -| int32_t [OH_ArkUI_GestureEventTargetInfo_IsScrollEnd](#oh_arkui_gestureeventtargetinfo_isscrollend) ([ArkUI_GestureEventTargetInfo](#arkui_gestureeventtargetinfo) \*info, bool \*ret) | Obtains whether this scroll container is scrolled to the bottom. | -| int32_t [OH_ArkUI_GetPanGestureDirectionMask](#oh_arkui_getpangesturedirectionmask) (ArkUI_GestureRecognizer \*recognizer, [ArkUI_GestureDirectionMask](#arkui_gesturedirectionmask) \*directionMask) | Obtains the direction of a pan gesture. | -| bool [OH_ArkUI_IsBuiltInGesture](#oh_arkui_isbuiltingesture) (ArkUI_GestureRecognizer \*recognizer) | Obtains whether a gesture is a built-in gesture. | -| int32_t [OH_ArkUI_GetGestureTag](#oh_arkui_getgesturetag) (ArkUI_GestureRecognizer \*recognizer, char \*buffer, int32_t bufferSize, int32_t \*result) | Obtains the tag of a gesture recognizer. | -| int32_t [OH_ArkUI_GetGestureBindNodeId](#oh_arkui_getgesturebindnodeid) (ArkUI_GestureRecognizer \*recognizer, char \*nodeId, int32_t size, int32_t \*result) | Obtains the ID of the component linked to a gesture recognizer. | -| bool [OH_ArkUI_IsGestureRecognizerValid](#oh_arkui_isgesturerecognizervalid) (ArkUI_GestureRecognizer \*recognizer) | Obtains whether a gesture recognizer is valid. | -| void \* [OH_ArkUI_ParallelInnerGestureEvent_GetUserData](#oh_arkui_parallelinnergestureevent_getuserdata) ([ArkUI_ParallelInnerGestureEvent](#arkui_parallelinnergestureevent) \*event) | Obtains custom data in the parallel internal gesture event. | -| ArkUI_GestureRecognizer \* [OH_ArkUI_ParallelInnerGestureEvent_GetCurrentRecognizer](#oh_arkui_parallelinnergestureevent_getcurrentrecognizer) ([ArkUI_ParallelInnerGestureEvent](#arkui_parallelinnergestureevent) \*event) | Obtains the current gesture recognizer in a parallel internal gesture event. | -| int32_t [OH_ArkUI_ParallelInnerGestureEvent_GetConflictRecognizers](#oh_arkui_parallelinnergestureevent_getconflictrecognizers) ([ArkUI_ParallelInnerGestureEvent](#arkui_parallelinnergestureevent) \*event, [ArkUI_GestureRecognizerHandleArray](#arkui_gesturerecognizerhandlearray) \*array, int32_t \*size) | Obtains the conflicting gesture recognizers in a parallel internal gesture event. | -| int32_t [OH_ArkUI_SetArkUIGestureRecognizerDisposeNotify](#oh_arkui_setarkuigesturerecognizerdisposenotify) (ArkUI_GestureRecognizer \*recognizer, [ArkUI_GestureRecognizerDestructNotifyCallback](#arkui_gesturerecognizerdestructnotifycallback) callback, void \*userData) | Sets a callback function for notifying gesture recognizer destruction. | -| void \* [OH_ArkUI_QueryModuleInterfaceByName](#oh_arkui_querymoduleinterfacebyname) ([ArkUI_NativeAPIVariantKind](#arkui_nativeapivariantkind) type, const char \*structName) | Obtains the native API set of a specified type. | +| [ArkUI_DragEvent](#arkui_dragevent) \* [OH_ArkUI_NodeEvent_GetDragEvent](#oh_arkui_nodeevent_getdragevent) ([ArkUI_NodeEvent](#arkui_nodeevent-12) \*nodeEvent) | Obtains a **DragEvent** object from the specified **NodeEvent** object. | +| [ArkUI_PreDragStatus](#arkui_predragstatus) [OH_ArkUI_NodeEvent_GetPreDragStatus](#oh_arkui_nodeevent_getpredragstatus) ([ArkUI_NodeEvent](#arkui_nodeevent-12) \*nodeEvent) | Obtains the state prior to a drop and drop operation. | +| int32_t [OH_ArkUI_DragEvent_DisableDefaultDropAnimation](#oh_arkui_dragevent_disabledefaultdropanimation) ([ArkUI_DragEvent](#arkui_dragevent) \*event, bool disable) | Sets whether to disable the default drop animation, which is enabled by default. Use this API to apply a custom drop animation. | +| int32_t [OH_ArkUI_DragEvent_SetSuggestedDropOperation](#oh_arkui_dragevent_setsuggesteddropoperation) ([ArkUI_DragEvent](#arkui_dragevent) \*event, [ArkUI_DropOperation](#arkui_dropoperation) dropOperation) | Sets the data processing mode. | +| int32_t [OH_ArkUI_DragEvent_SetDragResult](#oh_arkui_dragevent_setdragresult) ([ArkUI_DragEvent](#arkui_dragevent) \*event, [ArkUI_DragResult](#arkui_dragresult) result) | Sets the result for a drag event. | +| int32_t [OH_ArkUI_DragEvent_SetData](#oh_arkui_dragevent_setdata) ([ArkUI_DragEvent](#arkui_dragevent) \*event, [OH_UdmfData](#oh_udmfdata) \*data) | Sets drag data for a drag event. | +| int32_t [OH_ArkUI_DragEvent_GetUdmfData](#oh_arkui_dragevent_getudmfdata) ([ArkUI_DragEvent](#arkui_dragevent) \*event, [OH_UdmfData](#oh_udmfdata) \*data) | Obtains the default drag data from a drag event. | +| int32_t [OH_ArkUI_DragEvent_GetDataTypeCount](#oh_arkui_dragevent_getdatatypecount) ([ArkUI_DragEvent](#arkui_dragevent) \*event, int32_t \*count) | Obtains the number of drag data types from a drag event. | +| int32_t [OH_ArkUI_DragEvent_GetDataTypes](#oh_arkui_dragevent_getdatatypes) ([ArkUI_DragEvent](#arkui_dragevent) \*event, char \*\*result[], int32_t length) | Obtains the type list of drag data types from a drag event. | +| int32_t [OH_ArkUI_DragEvent_GetDragResult](#oh_arkui_dragevent_getdragresult) ([ArkUI_DragEvent](#arkui_dragevent) \*event, [ArkUI_DragResult](#arkui_dragresult) \*result) | Obtains the drag and drop result from the drag event. | +| int32_t [OH_ArkUI_DragEvent_GetDropOperation](#oh_arkui_dragevent_getdropoperation) ([ArkUI_DragEvent](#arkui_dragevent) \*event, [ArkUI_DropOperation](#arkui_dropoperation) \*operation) | Obtains the data handling method from the drag event. | +| float [OH_ArkUI_DragEvent_GetPreviewTouchPointX](#oh_arkui_dragevent_getpreviewtouchpointx) ([ArkUI_DragEvent](#arkui_dragevent) \*event) | Obtains the X coordinate of the touch point for a drag preview from a drag event. | +| float [OH_ArkUI_DragEvent_GetPreviewTouchPointY](#oh_arkui_dragevent_getpreviewtouchpointy) ([ArkUI_DragEvent](#arkui_dragevent) \*event) | Obtains the Y coordinate of the touch point for a drag preview from a drag event. | +| float [OH_ArkUI_DragEvent_GetPreviewRectWidth](#oh_arkui_dragevent_getpreviewrectwidth) ([ArkUI_DragEvent](#arkui_dragevent) \*event) | Obtains the width of a drag preview from a drag event. | +| float [OH_ArkUI_DragEvent_GetPreviewRectHeight](#oh_arkui_dragevent_getpreviewrectheight) ([ArkUI_DragEvent](#arkui_dragevent) \*event) | Obtains the height of a drag preview from a drag event. | +| float [OH_ArkUI_DragEvent_GetTouchPointXToWindow](#oh_arkui_dragevent_gettouchpointxtowindow) ([ArkUI_DragEvent](#arkui_dragevent) \*event) | Obtains the X coordinate of the touch point relative to the window from a drag event. | +| float [OH_ArkUI_DragEvent_GetTouchPointYToWindow](#oh_arkui_dragevent_gettouchpointytowindow) ([ArkUI_DragEvent](#arkui_dragevent) \*event) | Obtains the Y coordinate of the touch point relative to the window from a drag event. | +| float [OH_ArkUI_DragEvent_GetTouchPointXToDisplay](#oh_arkui_dragevent_gettouchpointxtodisplay) ([ArkUI_DragEvent](#arkui_dragevent) \*event) | Obtains the X coordinate of the touch point relative to the display from a drag event. | +| float [OH_ArkUI_DragEvent_GetTouchPointYToDisplay](#oh_arkui_dragevent_gettouchpointytodisplay) ([ArkUI_DragEvent](#arkui_dragevent) \*event) | Obtains the Y coordinate of the touch point relative to the display from a drag event. | +| float [OH_ArkUI_DragEvent_GetVelocityX](#oh_arkui_dragevent_getvelocityx) ([ArkUI_DragEvent](#arkui_dragevent) \*event) | Obtains the dragging velocity along the x-axis. | +| float [OH_ArkUI_DragEvent_GetVelocityY](#oh_arkui_dragevent_getvelocityy) ([ArkUI_DragEvent](#arkui_dragevent) \*event) | Obtains the dragging velocity along the y-axis. | +| float [OH_ArkUI_DragEvent_GetVelocity](#oh_arkui_dragevent_getvelocity) ([ArkUI_DragEvent](#arkui_dragevent) \*event) | Obtains the dragging velocity along the main axis. | +| int32_t [OH_ArkUI_DragEvent_GetModifierKeyStates](#oh_arkui_dragevent_getmodifierkeystates) ([ArkUI_DragEvent](#arkui_dragevent) \*event, uint64_t \*keys) | Obtains the pressed status of modifier keys from a drag event. | +| int32_t [OH_ArkUI_SetDragEventStrictReportWithNode](#oh_arkui_setdrageventstrictreportwithnode) ([ArkUI_NodeHandle](#arkui_nodehandle) node, bool enabled) | Sets whether to enable strict reporting on drag events. This feature is disabled by default, and you are advised to enable it. If this feature is disabled, the parent component is not notified when an item in it is dragged over its child component. If this feature is enabled, the component is notified of the dragged item's leaving, and the child component to which the dragged item is dropped is notified of the item's entering. This configuration is related to a specific UI instance. You can pass in a specific component node on the current UI instance for association. | +| int32_t [OH_ArkUI_SetDragEventStrictReportWithContext](#oh_arkui_setdrageventstrictreportwithcontext) ([ArkUI_ContextHandle](#arkui_contexthandle-12) uiContext, bool enabled) | Sets whether to enable strict reporting on drag events. This feature is disabled by default, and you are advised to enable it. If this feature is disabled, the parent component is not notified when an item in it is dragged over its child component. If this feature is enabled, the component is notified of the dragged item's leaving, and the child component to which the dragged item is dropped is notified of the item's entering. This configuration is related to a specific UI instance. You can pass in a specific UI instance for association. | +| int32_t [OH_ArkUI_SetNodeAllowedDropDataTypes](#oh_arkui_setnodealloweddropdatatypes) ([ArkUI_NodeHandle](#arkui_nodehandle) node, const char \*typesArray[], int32_t count) | Sets the types of data that can be dropped to the specified component. This API resets the settings configured through [OH_ArkUI_DisallowNodeAnyDropDataTypes](#oh_arkui_disallownodeanydropdatatypes) or [OH_ArkUI_AllowNodeAllDropDataTypes](#oh_arkui_allownodealldropdatatypes). | +| int32_t [OH_ArkUI_DisallowNodeAnyDropDataTypes](#oh_arkui_disallownodeanydropdatatypes) ([ArkUI_NodeHandle](#arkui_nodehandle) node) | Configures the specified component to disallow any data types. This API resets the settings configured through [OH_ArkUI_SetNodeAllowedDropDataTypes](#oh_arkui_setnodealloweddropdatatypes). | +| int32_t [OH_ArkUI_AllowNodeAllDropDataTypes](#oh_arkui_allownodealldropdatatypes) ([ArkUI_NodeHandle](#arkui_nodehandle) node) | Configures the specified component to allow any data types. This API resets the settings configured through [OH_ArkUI_SetNodeAllowedDropDataTypes](#oh_arkui_setnodealloweddropdatatypes). | +| int32_t [OH_ArkUI_SetNodeDraggable](#oh_arkui_setnodedraggable) ([ArkUI_NodeHandle](#arkui_nodehandle) node, bool enabled) | Sets whether the component is draggable. | +| int32_t [OH_ArkUI_SetNodeDragPreview](#oh_arkui_setnodedragpreview) ([ArkUI_NodeHandle](#arkui_nodehandle) node, [OH_PixelmapNative](#oh_pixelmapnative) \*preview) | Sets a custom drag preview for the specified component. | +| [ArkUI_DragPreviewOption](#arkui_dragpreviewoption) \* [OH_ArkUI_CreateDragPreviewOption](#oh_arkui_createdragpreviewoption) (void) | Creates an **ArkUI_DragPreviewOption** object. | +| void [OH_ArkUI_DragPreviewOption_Dispose](#oh_arkui_dragpreviewoption_dispose) ([ArkUI_DragPreviewOption](#arkui_dragpreviewoption) \*option) | Disposes of an **ArkUI_DragPreviewOption** object. | +| int32_t [OH_ArkUI_DragPreviewOption_SetScaleMode](#oh_arkui_dragpreviewoption_setscalemode) ([ArkUI_DragPreviewOption](#arkui_dragpreviewoption) \*option, [ArkUI_DragPreviewScaleMode](#arkui_dragpreviewscalemode) scaleMode) | Sets the scale mode for an **ArkUI_DragPreviewOption** object. | +| int32_t [OH_ArkUI_DragPreviewOption_SetDefaultShadowEnabled](#oh_arkui_dragpreviewoption_setdefaultshadowenabled) ([ArkUI_DragPreviewOption](#arkui_dragpreviewoption) \*option, bool enabled) | Sets whether to enable the shadow effect for an **ArkUI_DragPreviewOption** object. The shadow effect is enabled by default. | +| int32_t [OH_ArkUI_DragPreviewOption_SetDefaultRadiusEnabled](#oh_arkui_dragpreviewoption_setdefaultradiusenabled) ([ArkUI_DragPreviewOption](#arkui_dragpreviewoption) \*option, bool enabled) | Sets whether to enable the rounded corner effect for an **ArkUI_DragPreviewOption** object. The rounded corner effect is enabled by default. | +| int32_t [OH_ArkUI_DragPreviewOption_SetNumberBadgeEnabled](#oh_arkui_dragpreviewoption_setnumberbadgeenabled) ([ArkUI_DragPreviewOption](#arkui_dragpreviewoption) \*option, bool enabled) | Sets whether to enable the badge for an **ArkUI_DragPreviewOption** object. If this feature is enabled, a badge that contains the number of dragged items is displayed. | +| int32_t [OH_ArkUI_DragPreviewOption_SetBadgeNumber](#oh_arkui_dragpreviewoption_setbadgenumber) ([ArkUI_DragPreviewOption](#arkui_dragpreviewoption) \*option, uint32_t forcedNumber) | Sets the count on the badge. The settings will overwrite the value in the **SetDragPreviewNumberBadgeEnabled** API. | +| int32_t [OH_ArkUI_DragPreviewOption_SetDefaultAnimationBeforeLiftingEnabled](#oh_arkui_dragpreviewoption_setdefaultanimationbeforeliftingenabled) ([ArkUI_DragPreviewOption](#arkui_dragpreviewoption) \*option, bool enabled) | Sets whether to enable the default animation on a click or touch. | +| int32_t [OH_ArkUI_SetNodeDragPreviewOption](#oh_arkui_setnodedragpreviewoption) ([ArkUI_NodeHandle](#arkui_nodehandle) node, [ArkUI_DragPreviewOption](#arkui_dragpreviewoption) \*option) | Sets an **ArkUI_DragPreviewOption** object for the specified component. | +| [ArkUI_DragAction](#arkui_dragaction) \* [OH_ArkUI_CreateDragActionWithNode](#oh_arkui_createdragactionwithnode) ([ArkUI_NodeHandle](#arkui_nodehandle) node) | Creates a drag action object. The object needs to be associated with a UI instance, which can be specified by passing in a component node of the current UI instance. | +| [ArkUI_DragAction](#arkui_dragaction) \* [OH_ArkUI_CreateDragActionWithContext](#oh_arkui_createdragactionwithcontext) ([ArkUI_ContextHandle](#arkui_contexthandle-12) uiContext) | Creates a drag action object for the specified UI instance. | +| void [OH_ArkUI_DragAction_Dispose](#oh_arkui_dragaction_dispose) ([ArkUI_DragAction](#arkui_dragaction) \*dragAction) | Disposes of an **ArkUI_DragAction** object. | +| int32_t [OH_ArkUI_DragAction_SetPointerId](#oh_arkui_dragaction_setpointerid) ([ArkUI_DragAction](#arkui_dragaction) \*dragAction, int32_t pointer) | Sets the pointer ID. If only one finger is operating on the screen, the pointer ID is 0. In general cases, you can set the pointer ID to 0. | +| int32_t [OH_ArkUI_DragAction_SetPixelMaps](#oh_arkui_dragaction_setpixelmaps) ([ArkUI_DragAction](#arkui_dragaction) \*dragAction, [OH_PixelmapNative](#oh_pixelmapnative) \*pixelmapArray[], int32_t size) | Sets the drag previews for a drag action. | +| int32_t [OH_ArkUI_DragAction_SetTouchPointX](#oh_arkui_dragaction_settouchpointx) ([ArkUI_DragAction](#arkui_dragaction) \*dragAction, float x) | Sets the touch point relative to the upper left corner of the first drag preview (pixel map). | +| int32_t [OH_ArkUI_DragAction_SetTouchPointY](#oh_arkui_dragaction_settouchpointy) ([ArkUI_DragAction](#arkui_dragaction) \*dragAction, float y) | Sets the touch point relative to the upper left corner of the first drag preview (pixel map). | +| int32_t [OH_ArkUI_DragAction_SetData](#oh_arkui_dragaction_setdata) ([ArkUI_DragAction](#arkui_dragaction) \*dragAction, [OH_UdmfData](#oh_udmfdata) \*data) | Sets the drag data. | +| int32_t [OH_ArkUI_DragAction_SetDragPreviewOption](#oh_arkui_dragaction_setdragpreviewoption) ([ArkUI_DragAction](#arkui_dragaction) \*dragAction, [ArkUI_DragPreviewOption](#arkui_dragpreviewoption) \*option) | Sets an **ArkUI_DragPreviewOption** object for the specified drag action object. | +| int32_t [OH_ArkUI_DragAction_RegisterStatusListener](#oh_arkui_dragaction_registerstatuslistener) ([ArkUI_DragAction](#arkui_dragaction) \*dragAction, void \*userData, void(\*listener)([ArkUI_DragAndDropInfo](#arkui_draganddropinfo) \*dragAndDropInfo, void \*userData)) | Registers a drag status listener. This listener can be used to check whether the data is successfully received and processed. | +| void [OH_ArkUI_DragAction_UnregisterStatusListener](#oh_arkui_dragaction_unregisterstatuslistener) ([ArkUI_DragAction](#arkui_dragaction) \*dragAction) | Unregisters a drag status listener. | +| [ArkUI_DragStatus](#arkui_dragstatus) [OH_ArkUI_DragAndDropInfo_GetDragStatus](#oh_arkui_draganddropinfo_getdragstatus) ([ArkUI_DragAndDropInfo](#arkui_draganddropinfo) \*dragAndDropInfo) | Obtains the drag status of a drag action. | +| [ArkUI_DragEvent](#arkui_dragevent) \* [OH_ArkUI_DragAndDropInfo_GetDragEvent](#oh_arkui_draganddropinfo_getdragevent) ([ArkUI_DragAndDropInfo](#arkui_draganddropinfo) \*dragAndDropInfo) | Obtains a drag event based on the specified drag and drop information. The drag event can then be used to obtain the drag result. | +| int32_t [OH_ArkUI_StartDrag](#oh_arkui_startdrag) ([ArkUI_DragAction](#arkui_dragaction) \*dragAction) | Initiates a drag action through the specified **DragAction** object. | +| [ArkUI_DrawableDescriptor](#arkui_drawabledescriptor) \* [OH_ArkUI_DrawableDescriptor_CreateFromPixelMap](#oh_arkui_drawabledescriptor_createfrompixelmap) ([OH_PixelmapNativeHandle](#oh_pixelmapnativehandle) pixelMap) | Creates a **DrawableDescriptor** object from a **PixelMap** object. | +| [ArkUI_DrawableDescriptor](#arkui_drawabledescriptor) \* [OH_ArkUI_DrawableDescriptor_CreateFromAnimatedPixelMap](#oh_arkui_drawabledescriptor_createfromanimatedpixelmap) ([OH_PixelmapNativeHandle](#oh_pixelmapnativehandle) \*array, int32_t size) | Creates a **DrawableDescriptor** object from an array of **PixelMap** objects. | +| void [OH_ArkUI_DrawableDescriptor_Dispose](#oh_arkui_drawabledescriptor_dispose) ([ArkUI_DrawableDescriptor](#arkui_drawabledescriptor) \*drawableDescriptor) | Disposes of the pointer to a **DrawableDescriptor** object. | +| [OH_PixelmapNativeHandle](#oh_pixelmapnativehandle) [OH_ArkUI_DrawableDescriptor_GetStaticPixelMap](#oh_arkui_drawabledescriptor_getstaticpixelmap) ([ArkUI_DrawableDescriptor](#arkui_drawabledescriptor) \*drawableDescriptor) | Obtains the pointer to a **PixelMap** object. | +| [OH_PixelmapNativeHandle](#oh_pixelmapnativehandle) \* [OH_ArkUI_DrawableDescriptor_GetAnimatedPixelMapArray](#oh_arkui_drawabledescriptor_getanimatedpixelmaparray) ([ArkUI_DrawableDescriptor](#arkui_drawabledescriptor) \*drawableDescriptor) | Obtains an array of **PixelMap** objects for playing an animation. | +| int32_t [OH_ArkUI_DrawableDescriptor_GetAnimatedPixelMapArraySize](#oh_arkui_drawabledescriptor_getanimatedpixelmaparraysize) ([ArkUI_DrawableDescriptor](#arkui_drawabledescriptor) \*drawableDescriptor) | Obtains an array of **PixelMap** objects for playing an animation. | +| void [OH_ArkUI_DrawableDescriptor_SetAnimationDuration](#oh_arkui_drawabledescriptor_setanimationduration) ([ArkUI_DrawableDescriptor](#arkui_drawabledescriptor) \*drawableDescriptor, int32_t duration) | Sets the total playback duration for a pixel map image array. | +| int32_t [OH_ArkUI_DrawableDescriptor_GetAnimationDuration](#oh_arkui_drawabledescriptor_getanimationduration) ([ArkUI_DrawableDescriptor](#arkui_drawabledescriptor) \*drawableDescriptor) | Obtains the total playback duration for a pixel map image array. | +| void [OH_ArkUI_DrawableDescriptor_SetAnimationIteration](#oh_arkui_drawabledescriptor_setanimationiteration) ([ArkUI_DrawableDescriptor](#arkui_drawabledescriptor) \*drawableDescriptor, int32_t iteration) | Sets the number of times that a pixel map image array is played. | +| int32_t [OH_ArkUI_DrawableDescriptor_GetAnimationIteration](#oh_arkui_drawabledescriptor_getanimationiteration) ([ArkUI_DrawableDescriptor](#arkui_drawabledescriptor) \*drawableDescriptor) | Obtains the number of times that a pixel map image array is played. | +| [ArkUI_AnimateOption](#arkui_animateoption) \* [OH_ArkUI_AnimateOption_Create](#oh_arkui_animateoption_create) () | Creates an animation configuration. | +| void [OH_ArkUI_AnimateOption_Dispose](#oh_arkui_animateoption_dispose) ([ArkUI_AnimateOption](#arkui_animateoption) \*option) | Destroys an animation configuration. | +| int32_t [OH_ArkUI_AnimateOption_GetDuration](#oh_arkui_animateoption_getduration) ([ArkUI_AnimateOption](#arkui_animateoption) \*option) | Obtains the animation duration, in milliseconds. | +| float [OH_ArkUI_AnimateOption_GetTempo](#oh_arkui_animateoption_gettempo) ([ArkUI_AnimateOption](#arkui_animateoption) \*option) | Obtains the playback speed of an animation. | +| [ArkUI_AnimationCurve](#arkui_animationcurve) [OH_ArkUI_AnimateOption_GetCurve](#oh_arkui_animateoption_getcurve) ([ArkUI_AnimateOption](#arkui_animateoption) \*option) | Obtains an animation curve. | +| int32_t [OH_ArkUI_AnimateOption_GetDelay](#oh_arkui_animateoption_getdelay) ([ArkUI_AnimateOption](#arkui_animateoption) \*option) | Obtains the animation delay, in milliseconds. | +| int32_t [OH_ArkUI_AnimateOption_GetIterations](#oh_arkui_animateoption_getiterations) ([ArkUI_AnimateOption](#arkui_animateoption) \*option) | Obtains the number of times that an animation is played. | +| [ArkUI_AnimationPlayMode](#arkui_animationplaymode) [OH_ArkUI_AnimateOption_GetPlayMode](#oh_arkui_animateoption_getplaymode) ([ArkUI_AnimateOption](#arkui_animateoption) \*option) | Obtains the playback mode of an animation. | +| [ArkUI_ExpectedFrameRateRange](_ark_u_i___expected_frame_rate_range.md) \* [OH_ArkUI_AnimateOption_GetExpectedFrameRateRange](#oh_arkui_animateoption_getexpectedframeraterange) ([ArkUI_AnimateOption](#arkui_animateoption) \*option) | Obtains the expected frame rate range of an animation. | +| void [OH_ArkUI_AnimateOption_SetDuration](#oh_arkui_animateoption_setduration) ([ArkUI_AnimateOption](#arkui_animateoption) \*option, int32_t value) | Sets the animation duration. | +| void [OH_ArkUI_AnimateOption_SetTempo](#oh_arkui_animateoption_settempo) ([ArkUI_AnimateOption](#arkui_animateoption) \*option, float value) | Sets the playback speed of an animation. | +| void [OH_ArkUI_AnimateOption_SetCurve](#oh_arkui_animateoption_setcurve) ([ArkUI_AnimateOption](#arkui_animateoption) \*option, [ArkUI_AnimationCurve](#arkui_animationcurve) value) | Animation curve. | +| void [OH_ArkUI_AnimateOption_SetDelay](#oh_arkui_animateoption_setdelay) ([ArkUI_AnimateOption](#arkui_animateoption) \*option, int32_t value) | Sets the animation delay. | +| void [OH_ArkUI_AnimateOption_SetIterations](#oh_arkui_animateoption_setiterations) ([ArkUI_AnimateOption](#arkui_animateoption) \*option, int32_t value) | Number of times that the frame animation is played. | +| void [OH_ArkUI_AnimateOption_SetPlayMode](#oh_arkui_animateoption_setplaymode) ([ArkUI_AnimateOption](#arkui_animateoption) \*option, [ArkUI_AnimationPlayMode](#arkui_animationplaymode) value) | Sets the playback mode for an animation. | +| void [OH_ArkUI_AnimateOption_SetExpectedFrameRateRange](#oh_arkui_animateoption_setexpectedframeraterange) ([ArkUI_AnimateOption](#arkui_animateoption) \*option, [ArkUI_ExpectedFrameRateRange](_ark_u_i___expected_frame_rate_range.md) \*value) | Defines the expected frame rate range of the animation. | +| void [OH_ArkUI_AnimateOption_SetICurve](#oh_arkui_animateoption_seticurve) ([ArkUI_AnimateOption](#arkui_animateoption) \*option, [ArkUI_CurveHandle](#arkui_curvehandle) value) | Sets the animation curve for an animation. | +| [ArkUI_CurveHandle](#arkui_curvehandle) [OH_ArkUI_AnimateOption_GetICurve](#oh_arkui_animateoption_geticurve) ([ArkUI_AnimateOption](#arkui_animateoption) \*option) | Obtains the animation curve of an animation. | +| [ArkUI_KeyframeAnimateOption](#arkui_keyframeanimateoption) \* [OH_ArkUI_KeyframeAnimateOption_Create](#oh_arkui_keyframeanimateoption_create) (int32_t size) | Obtains the keyframe animation parameters. | +| void [OH_ArkUI_KeyframeAnimateOption_Dispose](#oh_arkui_keyframeanimateoption_dispose) ([ArkUI_KeyframeAnimateOption](#arkui_keyframeanimateoption) \*option) | Destroys a keyframe animation parameter object. | +| int32_t [OH_ArkUI_KeyframeAnimateOption_SetDelay](#oh_arkui_keyframeanimateoption_setdelay) ([ArkUI_KeyframeAnimateOption](#arkui_keyframeanimateoption) \*option, int32_t value) | Sets the overall delay of a keyframe animation, in milliseconds. By default, the keyframe animation is played without delay. | +| int32_t [OH_ArkUI_KeyframeAnimateOption_SetIterations](#oh_arkui_keyframeanimateoption_setiterations) ([ArkUI_KeyframeAnimateOption](#arkui_keyframeanimateoption) \*option, int32_t value) | Sets the number of times that the keyframe animation is played. By default, the animation is played once. The value **-1** indicates that the animation is played for an unlimited number of times. The value **0** indicates that there is no animation. | +| int32_t [OH_ArkUI_KeyframeAnimateOption_RegisterOnFinishCallback](#oh_arkui_keyframeanimateoption_registeronfinishcallback) ([ArkUI_KeyframeAnimateOption](#arkui_keyframeanimateoption) \*option, void \*userData, void(\*onFinish)(void \*userData)) | Sets the callback invoked when the keyframe animation playback is complete. This API is called after the keyframe animation has played for the specified number of times. | +| int32_t [OH_ArkUI_KeyframeAnimateOption_SetDuration](#oh_arkui_keyframeanimateoption_setduration) ([ArkUI_KeyframeAnimateOption](#arkui_keyframeanimateoption) \*option, int32_t value, int32_t index) | Sets the duration of a keyframe animation, in milliseconds. | +| int32_t [OH_ArkUI_KeyframeAnimateOption_SetCurve](#oh_arkui_keyframeanimateoption_setcurve) ([ArkUI_KeyframeAnimateOption](#arkui_keyframeanimateoption) \*option, [ArkUI_CurveHandle](#arkui_curvehandle) value, int32_t index) | Sets the animation curve for a specific keyframe in a keyframe animation. | +| int32_t [OH_ArkUI_KeyframeAnimateOption_RegisterOnEventCallback](#oh_arkui_keyframeanimateoption_registeroneventcallback) ([ArkUI_KeyframeAnimateOption](#arkui_keyframeanimateoption) \*option, void \*userData, void(\*event)(void \*userData), int32_t index) | Sets the closure function of the state at the time of the keyframe, that is, the state to be reached at the time of the keyframe. | +| int32_t [OH_ArkUI_KeyframeAnimateOption_GetDelay](#oh_arkui_keyframeanimateoption_getdelay) ([ArkUI_KeyframeAnimateOption](#arkui_keyframeanimateoption) \*option) | Obtains the overall delay of a keyframe animation | +| int32_t [OH_ArkUI_KeyframeAnimateOption_GetIterations](#oh_arkui_keyframeanimateoption_getiterations) ([ArkUI_KeyframeAnimateOption](#arkui_keyframeanimateoption) \*option) | Obtains the number of times that a keyframe animation is played. | +| int32_t [OH_ArkUI_KeyframeAnimateOption_GetDuration](#oh_arkui_keyframeanimateoption_getduration) ([ArkUI_KeyframeAnimateOption](#arkui_keyframeanimateoption) \*option, int32_t index) | Obtains the duration of a specific state in a keyframe animation. | +| [ArkUI_CurveHandle](#arkui_curvehandle) [OH_ArkUI_KeyframeAnimateOption_GetCurve](#oh_arkui_keyframeanimateoption_getcurve) ([ArkUI_KeyframeAnimateOption](#arkui_keyframeanimateoption) \*option, int32_t index) | Obtains the animation curve of a specific state in a keyframe animation. | +| [ArkUI_AnimatorOption](#arkui_animatoroption) \* [OH_ArkUI_AnimatorOption_Create](#oh_arkui_animatoroption_create) (int32_t keyframeSize) | Creates an animator parameter object. | +| void [OH_ArkUI_AnimatorOption_Dispose](#oh_arkui_animatoroption_dispose) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option) | Destroys an animator parameter object. | +| int32_t [OH_ArkUI_AnimatorOption_SetDuration](#oh_arkui_animatoroption_setduration) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option, int32_t value) | Sets the duration of an animation, in milliseconds. | +| int32_t [OH_ArkUI_AnimatorOption_SetDelay](#oh_arkui_animatoroption_setdelay) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option, int32_t value) | Sets the delay of animation playback, in milliseconds. | +| int32_t [OH_ArkUI_AnimatorOption_SetIterations](#oh_arkui_animatoroption_setiterations) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option, int32_t value) | Number of times that the frame animation is played. The value **0** means not to play the animation, and **-1** means to play the animation for an unlimited number of times. | +| int32_t [OH_ArkUI_AnimatorOption_SetFill](#oh_arkui_animatoroption_setfill) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option, [ArkUI_AnimationFill](#arkui_animationfill) value) | Sets whether the animator animation is restored to the initial state after being executed. | +| int32_t [OH_ArkUI_AnimatorOption_SetDirection](#oh_arkui_animatoroption_setdirection) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option, [ArkUI_AnimationDirection](#arkui_animationdirection) value) | Sets the playback direction. | +| int32_t [OH_ArkUI_AnimatorOption_SetCurve](#oh_arkui_animatoroption_setcurve) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option, [ArkUI_CurveHandle](#arkui_curvehandle) value) | Sets the interpolation curve for the animation of an animator. | +| int32_t [OH_ArkUI_AnimatorOption_SetBegin](#oh_arkui_animatoroption_setbegin) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option, float value) | Sets the interpolation start point for the animation of an animator. | +| int32_t [OH_ArkUI_AnimatorOption_SetEnd](#oh_arkui_animatoroption_setend) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option, float value) | Sets the interpolation end point for the animation of an animator. | +| int32_t [OH_ArkUI_AnimatorOption_SetExpectedFrameRateRange](#oh_arkui_animatoroption_setexpectedframeraterange) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option, [ArkUI_ExpectedFrameRateRange](_ark_u_i___expected_frame_rate_range.md) \*value) | Sets the expected frame rate range of an animation. | +| int32_t [OH_ArkUI_AnimatorOption_SetKeyframe](#oh_arkui_animatoroption_setkeyframe) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option, float time, float value, int32_t index) | Sets the keyframe parameters of an animation. | +| int32_t [OH_ArkUI_AnimatorOption_SetKeyframeCurve](#oh_arkui_animatoroption_setkeyframecurve) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option, [ArkUI_CurveHandle](#arkui_curvehandle) value, int32_t index) | Sets the keyframe curve type for the animation of an animator. | +| int32_t [OH_ArkUI_AnimatorOption_GetDuration](#oh_arkui_animatoroption_getduration) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option) | Obtains the duration for playing an animation. | +| int32_t [OH_ArkUI_AnimatorOption_GetDelay](#oh_arkui_animatoroption_getdelay) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option) | Obtains the delay for playing an animation. | +| int32_t [OH_ArkUI_AnimatorOption_GetIterations](#oh_arkui_animatoroption_getiterations) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option) | Obtains the number of times that an animation is played. | +| [ArkUI_AnimationFill](#arkui_animationfill) [OH_ArkUI_AnimatorOption_GetFill](#oh_arkui_animatoroption_getfill) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option) | Obtains whether the animator animation is restored to the initial state after being executed. | +| [ArkUI_AnimationDirection](#arkui_animationdirection) [OH_ArkUI_AnimatorOption_GetDirection](#oh_arkui_animatoroption_getdirection) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option) | Obtains the playback direction of an animation. | +| [ArkUI_CurveHandle](#arkui_curvehandle) [OH_ArkUI_AnimatorOption_GetCurve](#oh_arkui_animatoroption_getcurve) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option) | Obtains the interpolation curve of the animation of an animator. | +| float [OH_ArkUI_AnimatorOption_GetBegin](#oh_arkui_animatoroption_getbegin) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option) | Obtains the interpolation start point of an animation. | +| float [OH_ArkUI_AnimatorOption_GetEnd](#oh_arkui_animatoroption_getend) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option) | Obtains the interpolation end point of an animation. | +| [ArkUI_ExpectedFrameRateRange](_ark_u_i___expected_frame_rate_range.md) \* [OH_ArkUI_AnimatorOption_GetExpectedFrameRateRange](#oh_arkui_animatoroption_getexpectedframeraterange) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option) | Obtains the expected frame rate range of an animation. | +| float [OH_ArkUI_AnimatorOption_GetKeyframeTime](#oh_arkui_animatoroption_getkeyframetime) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option, int32_t index) | Obtains the keyframe time of an animation. | +| float [OH_ArkUI_AnimatorOption_GetKeyframeValue](#oh_arkui_animatoroption_getkeyframevalue) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option, int32_t index) | Obtains the keyframe value of an animation. | +| [ArkUI_CurveHandle](#arkui_curvehandle) [OH_ArkUI_AnimatorOption_GetKeyframeCurve](#oh_arkui_animatoroption_getkeyframecurve) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option, int32_t index) | Obtains the interpolation curve for a keyframe in the animation of an animator. | +| void \* [OH_ArkUI_AnimatorEvent_GetUserData](#oh_arkui_animatorevent_getuserdata) (ArkUI_AnimatorEvent \*event) | Obtains the custom object in an animation event object. | +| void \* [OH_ArkUI_AnimatorOnFrameEvent_GetUserData](#oh_arkui_animatoronframeevent_getuserdata) (ArkUI_AnimatorOnFrameEvent \*event) | Obtains the custom object in an animation event object. | +| float [OH_ArkUI_AnimatorOnFrameEvent_GetValue](#oh_arkui_animatoronframeevent_getvalue) (ArkUI_AnimatorOnFrameEvent \*event) | Obtains the current progress in an animation event object. | +| int32_t [OH_ArkUI_AnimatorOption_RegisterOnFrameCallback](#oh_arkui_animatoroption_registeronframecallback) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option, void \*userData, void(\*callback)(ArkUI_AnimatorOnFrameEvent \*event)) | Sets the callback invoked when the animator receives a frame. | +| int32_t [OH_ArkUI_AnimatorOption_RegisterOnFinishCallback](#oh_arkui_animatoroption_registeronfinishcallback) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option, void \*userData, void(\*callback)(ArkUI_AnimatorEvent \*event)) | Sets the callback invoked when the animation playback is complete. | +| int32_t [OH_ArkUI_AnimatorOption_RegisterOnCancelCallback](#oh_arkui_animatoroption_registeroncancelcallback) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option, void \*userData, void(\*callback)(ArkUI_AnimatorEvent \*event)) | Sets the callback invoked when the animation playback is canceled. | +| int32_t [OH_ArkUI_AnimatorOption_RegisterOnRepeatCallback](#oh_arkui_animatoroption_registeronrepeatcallback) ([ArkUI_AnimatorOption](#arkui_animatoroption) \*option, void \*userData, void(\*callback)(ArkUI_AnimatorEvent \*event)) | Sets the callback invoked when the animation playback is repeated. | +| int32_t [OH_ArkUI_Animator_ResetAnimatorOption](#oh_arkui_animator_resetanimatoroption) ([ArkUI_AnimatorHandle](#arkui_animatorhandle) animator, [ArkUI_AnimatorOption](#arkui_animatoroption) \*option) | Resets an animator configuration. | +| int32_t [OH_ArkUI_Animator_Play](#oh_arkui_animator_play) ([ArkUI_AnimatorHandle](#arkui_animatorhandle) animator) | Starts the animation of an animator. | +| int32_t [OH_ArkUI_Animator_Finish](#oh_arkui_animator_finish) ([ArkUI_AnimatorHandle](#arkui_animatorhandle) animator) | Ends the animation of an animator. | +| int32_t [OH_ArkUI_Animator_Pause](#oh_arkui_animator_pause) ([ArkUI_AnimatorHandle](#arkui_animatorhandle) animator) | Pauses the animation of an animator. | +| int32_t [OH_ArkUI_Animator_Cancel](#oh_arkui_animator_cancel) ([ArkUI_AnimatorHandle](#arkui_animatorhandle) animator) | Cancels the animation of an animator. | +| int32_t [OH_ArkUI_Animator_Reverse](#oh_arkui_animator_reverse) ([ArkUI_AnimatorHandle](#arkui_animatorhandle) animator) | Plays this animation in reverse order. | +| [ArkUI_CurveHandle](#arkui_curvehandle) [OH_ArkUI_Curve_CreateCurveByType](#oh_arkui_curve_createcurvebytype) ([ArkUI_AnimationCurve](#arkui_animationcurve) curve) | Implements initialization for the interpolation curve, which is used to create an interpolation curve based on the input parameter. | +| [ArkUI_CurveHandle](#arkui_curvehandle) [OH_ArkUI_Curve_CreateStepsCurve](#oh_arkui_curve_createstepscurve) (int32_t count, bool end) | Creates a step curve. | +| [ArkUI_CurveHandle](#arkui_curvehandle) [OH_ArkUI_Curve_CreateCubicBezierCurve](#oh_arkui_curve_createcubicbeziercurve) (float x1, float y1, float x2, float y2) | Creates a cubic Bezier curve. | +| [ArkUI_CurveHandle](#arkui_curvehandle) [OH_ArkUI_Curve_CreateSpringCurve](#oh_arkui_curve_createspringcurve) (float velocity, float mass, float stiffness, float damping) | Creates a spring curve. The curve shape is subject to the spring parameters, and the animation duration is subject to the **duration** parameter in **animation** and **animateTo**. | +| [ArkUI_CurveHandle](#arkui_curvehandle) [OH_ArkUI_Curve_CreateSpringMotion](#oh_arkui_curve_createspringmotion) (float response, float dampingFraction, float overlapDuration) | Creates a spring animation curve. If multiple spring animations are applied to the same attribute of an object, each animation replaces their predecessor and inherits the velocity. | +| [ArkUI_CurveHandle](#arkui_curvehandle) [OH_ArkUI_Curve_CreateResponsiveSpringMotion](#oh_arkui_curve_createresponsivespringmotion) (float response, float dampingFraction, float overlapDuration) | Creates a responsive spring animation curve. It is a special case of **springMotion**, with the only difference in the default values. It can be used together with **springMotion**. | +| [ArkUI_CurveHandle](#arkui_curvehandle) [OH_ArkUI_Curve_CreateInterpolatingSpring](#oh_arkui_curve_createinterpolatingspring) (float velocity, float mass, float stiffness, float damping) | Creates an interpolating spring curve animated from 0 to 1. The actual animation value is calculated based on the curve. | +| [ArkUI_CurveHandle](#arkui_curvehandle) [OH_ArkUI_Curve_CreateCustomCurve](#oh_arkui_curve_createcustomcurve) (void \*userData, float(\*interpolate)(float fraction, void \*userdata)) | Creates a custom curve. | +| void [OH_ArkUI_Curve_DisposeCurve](#oh_arkui_curve_disposecurve) ([ArkUI_CurveHandle](#arkui_curvehandle) curveHandle) | Disposes of a custom curve. | +| [ArkUI_TransitionEffect](#arkui_transitioneffect) \* [OH_ArkUI_CreateOpacityTransitionEffect](#oh_arkui_createopacitytransitioneffect) (float opacity) | Creates an opacity object for component transition. | +| [ArkUI_TransitionEffect](#arkui_transitioneffect) \* [OH_ArkUI_CreateTranslationTransitionEffect](#oh_arkui_createtranslationtransitioneffect) ([ArkUI_TranslationOptions](_ark_u_i___translation_options.md) \*translate) | Creates a translation object for component transition. | +| [ArkUI_TransitionEffect](#arkui_transitioneffect) \* [OH_ArkUI_CreateScaleTransitionEffect](#oh_arkui_createscaletransitioneffect) ([ArkUI_ScaleOptions](_ark_u_i___scale_options.md) \*scale) | Creates a scaling object for component transition. | +| [ArkUI_TransitionEffect](#arkui_transitioneffect) \* [OH_ArkUI_CreateRotationTransitionEffect](#oh_arkui_createrotationtransitioneffect) ([ArkUI_RotationOptions](_ark_u_i___rotation_options.md) \*rotate) | Creates a rotation object for component transition. | +| [ArkUI_TransitionEffect](#arkui_transitioneffect) \* [OH_ArkUI_CreateMovementTransitionEffect](#oh_arkui_createmovementtransitioneffect) ([ArkUI_TransitionEdge](#arkui_transitionedge) move) | Creates a movement object for component transition. | +| [ArkUI_TransitionEffect](#arkui_transitioneffect) \* [OH_ArkUI_CreateAsymmetricTransitionEffect](#oh_arkui_createasymmetrictransitioneffect) ([ArkUI_TransitionEffect](#arkui_transitioneffect) \*appear, [ArkUI_TransitionEffect](#arkui_transitioneffect) \*disappear) | Creates an asymmetric transition effect. | +| void [OH_ArkUI_TransitionEffect_Dispose](#oh_arkui_transitioneffect_dispose) ([ArkUI_TransitionEffect](#arkui_transitioneffect) \*option) | Disposes of a transition effect. | +| int32_t [OH_ArkUI_TransitionEffect_Combine](#oh_arkui_transitioneffect_combine) ([ArkUI_TransitionEffect](#arkui_transitioneffect) \*option, [ArkUI_TransitionEffect](#arkui_transitioneffect) \*combine) | Sets a combination of transition effects. | +| int32_t [OH_ArkUI_TransitionEffect_SetAnimation](#oh_arkui_transitioneffect_setanimation) ([ArkUI_TransitionEffect](#arkui_transitioneffect) \*option, [ArkUI_AnimateOption](#arkui_animateoption) \*animation) | Sets transition effect animation settings. | +| void [OH_ArkUI_DialogDismissEvent_SetShouldBlockDismiss](#oh_arkui_dialogdismissevent_setshouldblockdismiss) ([ArkUI_DialogDismissEvent](#arkui_dialogdismissevent) \*event, bool shouldBlockDismiss) | Sets whether to block the system behavior of dismissing a dialog box. | +| void \* [OH_ArkUI_DialogDismissEvent_GetUserData](#oh_arkui_dialogdismissevent_getuserdata) ([ArkUI_DialogDismissEvent](#arkui_dialogdismissevent) \*event) | Obtains the pointer to user data in a dialog box dismiss event object. | +| int32_t [OH_ArkUI_DialogDismissEvent_GetDismissReason](#oh_arkui_dialogdismissevent_getdismissreason) ([ArkUI_DialogDismissEvent](#arkui_dialogdismissevent) \*event) | Obtains the dismissal reason from a dialog box dismiss event object. | +| int32_t [OH_ArkUI_CustomDialog_OpenDialog](#oh_arkui_customdialog_opendialog) ([ArkUI_CustomDialogOptions](#arkui_customdialogoptions) \*options, void (\*callback)(int32_t dialogId)) | Displays a custom dialog box. | +| int32_t [OH_ArkUI_CustomDialog_UpdateDialog](#oh_arkui_customdialog_updatedialog) ([ArkUI_CustomDialogOptions](#arkui_customdialogoptions) \*options, void (\*callback)(int32_t dialogId)) | Updates a custom dialog box. | +| int32_t [OH_ArkUI_CustomDialog_CloseDialog](#oh_arkui_customdialog_closedialog) (int32_t dialogId) | Closes a custom dialog box. | +| ArkUI_CustomDialogOptions\* [OH_ArkUI_CustomDialog_CreateOptions](#oh_arkui_customdialog_createoptions) ([ArkUI_NodeHandle](#arkui_nodehandle) content) | Creates options for a custom dialog. | +| void [OH_ArkUI_CustomDialog_DisposeOptions](#oh_arkui_customdialog_disposeoptions) ([ArkUI_CustomDialogOptions](#arkui_customdialogoptions) \*options) | Destroys custom dialog box options. | +| int32_t [OH_ArkUI_CustomDialog_SetLevelMode](#oh_arkui_customdialog_setlevelmode) ([ArkUI_CustomDialogOptions](#arkui_customdialogoptions) \*options, [ArkUI_LevelMode](#arkui_levelmode) levelMode) | Sets the display level of the dialog box. | +| int32_t [OH_ArkUI_CustomDialog_SetLevelUniqueId](#oh_arkui_customdialog_setleveluniqueid) ([ArkUI_CustomDialogOptions](#arkui_customdialogoptions) \*options, int32_t uniqueId) | Sets the ID of the node under the dialog box's display level. | +| int32_t [OH_ArkUI_CustomDialog_SetImmersiveMode](#oh_arkui_customdialog_setimmersivemode) ([ArkUI_CustomDialogOptions](#arkui_customdialogoptions) \*options, [ArkUI_ImmersiveMode](#arkui_immersivemode) immersiveMode) | Sets the display area of the embedded dialog box overlay. | +| int32_t [OH_ArkUI_CustomDialog_SetBackgroundColor](#oh_arkui_customdialog_setbackgroundcolor) ([ArkUI_CustomDialogOptions](#arkui_customdialogoptions) \*options, uint32_t backgroundColor) | Sets the background color of a dialog box. | +| int32_t [OH_ArkUI_CustomDialog_SetCornerRadius](#oh_arkui_customdialog_setcornerradius) ([ArkUI_CustomDialogOptions](#arkui_customdialogoptions) \*options, float topLeft, float topRight, float bottomLeft, float bottomRight) | Sets the corner radius for a custom dialog box. | +| int32_t [OH_ArkUI_CustomDialog_SetBorderWidth](#oh_arkui_customdialog_setborderwidth) ([ArkUI_CustomDialogOptions](#arkui_customdialogoptions) \*options, float top, float right, float bottom, float left, [ArkUI_LengthMetricUnit](#arkui_lengthmetricunit) unit) | Sets the border width of a dialog box. | +| int32_t [OH_ArkUI_CustomDialog_SetBorderColor](#oh_arkui_customdialog_setbordercolor) ([ArkUI_CustomDialogOptions](#arkui_customdialogoptions) \*options, uint32_t top, uint32_t right, uint32_t bottom, uint32_t left) | Sets the border color of the dialog box. | +| int32_t [OH_ArkUI_CustomDialog_SetBorderStyle](#oh_arkui_customdialog_setborderstyle) ([ArkUI_CustomDialogOptions](#arkui_customdialogoptions) \*options, int32_t top, int32_t right, int32_t bottom, int32_t left) | Sets the border style of a dialog box. | +| int32_t [OH_ArkUI_CustomDialog_SetWidth](#oh_arkui_customdialog_setwidth) ([ArkUI_CustomDialogOptions](#arkui_customdialogoptions) \*options, float width, [ArkUI_LengthMetricUnit](#arkui_lengthmetricunit) unit) | Sets the width of the dialog box background. | +| int32_t [OH_ArkUI_CustomDialog_SetHeight](#oh_arkui_customdialog_setheight) ([ArkUI_CustomDialogOptions](#arkui_customdialogoptions) \*options, float height, [ArkUI_LengthMetricUnit](#arkui_lengthmetricunit) unit) | Sets the height of the dialog box background. | +| int32_t [OH_ArkUI_CustomDialog_SetShadow](#oh_arkui_customdialog_setshadow) ([ArkUI_CustomDialogOptions](#arkui_customdialogoptions) \*options, [ArkUI_ShadowStyle](#arkui_shadowstyle) shadow) | Sets the shadow of the dialog box background. | +| int32_t [OH_ArkUI_CustomDialog_SetCustomShadow](#oh_arkui_customdialog_setcustomshadow) ([ArkUI_CustomDialogOptions](#arkui_customdialogoptions) \*options, const [ArkUI_AttributeItem](_ark_u_i___attribute_item.md#arkui_attributeitem) \*customShadow) | Sets the custom shadow of the dialog box background. | +| int32_t [OH_ArkUI_CustomDialog_SetBackgroundBlurStyle](#oh_arkui_customdialog_setbackgroundblurstyle) ([ArkUI_CustomDialogOptions](#arkui_customdialogoptions) \*options, [ArkUI_BlurStyle](#arkui_blurstyle) blurStyle) | Sets the background blur style of the dialog box. | +| int32_t [OH_ArkUI_CustomDialog_SetAlignment](#oh_arkui_customdialog_setalignment) ([ArkUI_CustomDialogOptions](#arkui_customdialogoptions) \*options, int32_t alignment, float offsetX, float offsetY) | Sets the alignment mode of a dialog box. | +| int32_t [OH_ArkUI_CustomDialog_SetModalMode](#oh_arkui_customdialog_setmodalmode) ([ArkUI_CustomDialogOptions](#arkui_customdialogoptions) \*options, bool isModal) | Sets the modal mode for a custom dialog box. | +| int32_t [OH_ArkUI_CustomDialog_SetAutoCancel](#oh_arkui_customdialog_setautocancel) ([ArkUI_CustomDialogOptions](#arkui_customdialogoptions) \*options, bool autoCancel) | Specifies whether to allow users to touch the mask to dismiss the custom dialog box. | +| int32_t [OH_ArkUI_CustomDialog_SetSubwindowMode](#oh_arkui_customdialog_setsubwindowmode) ([ArkUI_CustomDialogOptions](#arkui_customdialogoptions) \*options, bool showInSubwindow) | Sets whether to display the dialog box in a subwindow. | +| int32_t [OH_ArkUI_CustomDialog_SetMask](#oh_arkui_customdialog_setmask) ([ArkUI_CustomDialogOptions](#arkui_customdialogoptions) \*options, uint32_t maskColor, const [ArkUI_Rect](_ark_u_i___rect.md#arkui_rect) \*maskRect) | Sets the mask for a custom dialog box. | +| int32_t [OH_ArkUI_CustomDialog_SetKeyboardAvoidMode](#oh_arkui_customdialog_setkeyboardavoidmode) ([ArkUI_CustomDialogOptions](#arkui_customdialogoptions) \*options, [ArkUI_KeyboardAvoidMode](_ark_u_i___native_module.md#arkui_keyboardavoidmode) keyboardAvoidMode) | Sets the keyboard avoidance mode of a dialog box. | +| int32_t [OH_ArkUI_CustomDialog_SetHoverModeEnabled](#oh_arkui_customdialog_sethovermodeenabled) ([ArkUI_CustomDialogOptions](#arkui_customdialogoptions) \*options, bool enabled) | Sets whether to enable the hover mode for a dialog box. | +| int32_t [OH_ArkUI_CustomDialog_SetHoverModeArea](#oh_arkui_customdialog_sethovermodearea) ([ArkUI_CustomDialogOptions](#arkui_customdialogoptions) \*options, [ArkUI_HoverModeAreaType](#arkui_hovermodeareatype) hoverModeAreaType) | Sets the default display area of a dialog box in hover mode. | +| int32_t [OH_ArkUI_CustomDialog_RegisterOnWillDismissCallback](#oh_arkui_customdialog_registeronwilldismisscallback) ([ArkUI_CustomDialogOptions](#arkui_customdialogoptions) \*options, void\* userData, void (\*callback)([ArkUI_DialogDismissEvent](#arkui_dialogdismissevent) \*event)) | Registers a callback for the dismissal event of a custom dialog box. | +| int32_t [OH_ArkUI_CustomDialog_RegisterOnWillAppearCallback](#oh_arkui_customdialog_registeronwillappearcallback) ([ArkUI_CustomDialogOptions](#arkui_customdialogoptions) \*options, void\* userData, void (\*callback)(void\* userData)) | Registers a callback to be invoked when the specified custom dialog box is about to appear. | +| int32_t [OH_ArkUI_CustomDialog_RegisterOnDidAppearCallback](#oh_arkui_customdialog_registerondidappearcallback) ([ArkUI_CustomDialogOptions](#arkui_customdialogoptions) \*options, void\* userData, void (\*callback)(void\* userData)) | Registers a callback to be invoked when the specifiedcustom dialog box appears. | +| int32_t [OH_ArkUI_CustomDialog_RegisterOnWillDisappearCallback](#oh_arkui_customdialog_registeronwilldisappearcallback) ([ArkUI_CustomDialogOptions](#arkui_customdialogoptions) \*options, void\* userData, void (\*callback)(void\* userData)) | Registers a callback to be invoked when the specified custom dialog box is about to disappear. | +| int32_t [OH_ArkUI_CustomDialog_RegisterOnDidDisappearCallback](#oh_arkui_customdialog_registerondiddisappearcallback) ([ArkUI_CustomDialogOptions](#arkui_customdialogoptions) \*options, void\* userData, void (\*callback)(void\* userData)) | Registers a callback to be invoked when the specified custom dialog box disappears. | +| bool [OH_ArkUI_GestureInterruptInfo_GetSystemFlag](#oh_arkui_gestureinterruptinfo_getsystemflag) (const ArkUI_GestureInterruptInfo \*event) | Checks whether a gesture is a built-in gesture of the component. | +| ArkUI_GestureRecognizer \* [OH_ArkUI_GestureInterruptInfo_GetRecognizer](#oh_arkui_gestureinterruptinfo_getrecognizer) (const ArkUI_GestureInterruptInfo \*event) | Obtains the pointer to interrupted gesture recognizer. | +| ArkUI_GestureEvent \* [OH_ArkUI_GestureInterruptInfo_GetGestureEvent](#oh_arkui_gestureinterruptinfo_getgestureevent) (const ArkUI_GestureInterruptInfo \*event) | Obtains the pointer to the interrupted gesture event. | +| int32_t [OH_ArkUI_GestureInterruptInfo_GetSystemRecognizerType](#oh_arkui_gestureinterruptinfo_getsystemrecognizertype) (const ArkUI_GestureInterruptInfo \*event) | Obtains the type of the system gesture to trigger. | +| int32_t [OH_ArkUI_GestureInterruptInfo_GetTouchRecognizers](#oh_arkui_gestureinterruptinfo_gettouchrecognizers) (const ArkUI_GestureInterruptInfo \*info, ArkUI_TouchRecognizerHandleArray\* recognizers, int32_t\* size) | Obtains touch recognizers from gesture interruption information. | +| int32_t [OH_ArkUI_TouchRecognizer_GetNodeHandle](#oh_arkui_touchrecognizer_getnodehandle) (const ArkUI_TouchRecognizerHandle recognizer) | Obtains the component handle corresponding to a touch recognizer. | +| int32_t [OH_ArkUI_TouchRecognizer_CancelTouch](#oh_arkui_touchrecognizer_canceltouch) (ArkUI_TouchRecognizerHandle recognizer, ArkUI_GestureInterruptInfo\* info) | Sends a cancel touch event to a touch recognizer in a gesture interruption callback. | +| [ArkUI_GestureEventActionType](#arkui_gestureeventactiontype) [OH_ArkUI_GestureEvent_GetActionType](#oh_arkui_gestureevent_getactiontype) (const ArkUI_GestureEvent \*event) | Obtains the gesture event type. | +| [ArkUI_NodeHandle](#arkui_nodehandle) [OH_ArkUI_GestureEvent_GetResponseNode](#oh_arkui_gestureevent_getresponsenode) (ArkUI_GestureEvent \*event) | Obtains the node that responds to the gesture. | +| const [ArkUI_UIInputEvent](_ark_u_i___event_module.md#arkui_uiinputevent) \* [OH_ArkUI_GestureEvent_GetRawInputEvent](#oh_arkui_gestureevent_getrawinputevent) (const ArkUI_GestureEvent \*event) | Obtains gesture input. | +| int32_t [OH_ArkUI_LongPress_GetRepeatCount](#oh_arkui_longpress_getrepeatcount) (const ArkUI_GestureEvent \*event) | Obtains the number of times that a long press gesture is triggered periodically. | +| float [OH_ArkUI_PanGesture_GetVelocity](#oh_arkui_pangesture_getvelocity) (const ArkUI_GestureEvent \*event) | Obtains the velocity of a pan gesture along the main axis. | +| float [OH_ArkUI_PanGesture_GetVelocityX](#oh_arkui_pangesture_getvelocityx) (const ArkUI_GestureEvent \*event) | Obtains the velocity of a pan gesture along the x-axis. | +| float [OH_ArkUI_PanGesture_GetVelocityY](#oh_arkui_pangesture_getvelocityy) (const ArkUI_GestureEvent \*event) | Obtains the velocity of a pan gesture along the y-axis. | +| float [OH_ArkUI_PanGesture_GetOffsetX](#oh_arkui_pangesture_getoffsetx) (const ArkUI_GestureEvent \*event) | Obtains the relative offset of a pan gesture along the x-axis. | +| float [OH_ArkUI_PanGesture_GetOffsetY](#oh_arkui_pangesture_getoffsety) (const ArkUI_GestureEvent \*event) | Obtains the relative offset of a pan gesture along the y-axis. | +| float [OH_ArkUI_SwipeGesture_GetAngle](#oh_arkui_swipegesture_getangle) (const ArkUI_GestureEvent \*event) | Obtains the angle information of the swipe gesture. | +| float [OH_ArkUI_SwipeGesture_GetVelocity](#oh_arkui_swipegesture_getvelocity) (const ArkUI_GestureEvent \*event) | Obtains the average velocity of all fingers used in the swipe gesture. | +| float [OH_ArkUI_RotationGesture_GetAngle](#oh_arkui_rotationgesture_getangle) (const ArkUI_GestureEvent \*event) | Obtains the angle information of a rotation gesture. | +| float [OH_ArkUI_PinchGesture_GetScale](#oh_arkui_pinchgesture_getscale) (const ArkUI_GestureEvent \*event) | Obtains the scale ratio of a pinch gesture. | +| float [OH_ArkUI_PinchGesture_GetCenterX](#oh_arkui_pinchgesture_getcenterx) (const ArkUI_GestureEvent \*event) | Obtains the X coordinate of the center of the pinch gesture, in vp, relative to the upper left corner of the current component. | +| float [OH_ArkUI_PinchGesture_GetCenterY](#oh_arkui_pinchgesture_getcentery) (const ArkUI_GestureEvent \*event) | Obtains the Y coordinate of the center of the pinch gesture, in vp, relative to the upper left corner of the current component. | +| [ArkUI_NodeHandle](#arkui_nodehandle) [OH_ArkUI_GestureEvent_GetNode](#oh_arkui_gestureevent_getnode) (const ArkUI_GestureEvent \*event) | Obtains the ArkUI component to which the gesture is bound. | +| int32_t [OH_ArkUI_GetResponseRecognizersFromInterruptInfo](#oh_arkui_getresponserecognizersfrominterruptinfo) (const ArkUI_GestureInterruptInfo \*event, [ArkUI_GestureRecognizerHandleArray](#arkui_gesturerecognizerhandlearray) \*responseChain, int32_t \*count) | Obtains information about a gesture response chain. | +| int32_t [OH_ArkUI_SetGestureRecognizerEnabled](#oh_arkui_setgesturerecognizerenabled) (ArkUI_GestureRecognizer \*recognizer, bool enabled) | Sets the enabled state of a gesture recognizer. | +| int32_t(\* [OH_ArkUI_SetGestureRecognizerLimitFingerCount](#oh_arkui_setgesturerecognizerlimitfingercount) )(ArkUI_GestureRecognizer \*recognizer, bool limitFingerCount) | Sets whether to check the number of fingers touching the screen. | +| bool [OH_ArkUI_GetGestureRecognizerEnabled](#oh_arkui_getgesturerecognizerenabled) (ArkUI_GestureRecognizer \*recognizer) | Obtains the enabled state of a gesture recognizer. | +| int32_t [OH_ArkUI_GetGestureRecognizerState](#oh_arkui_getgesturerecognizerstate) (ArkUI_GestureRecognizer \*recognizer, [ArkUI_GestureRecognizerState](#arkui_gesturerecognizerstate) \*state) | Obtains the state of a gesture recognizer. | +| int32_t [OH_ArkUI_GetGestureEventTargetInfo](#oh_arkui_getgestureeventtargetinfo) (ArkUI_GestureRecognizer \*recognizer, [ArkUI_GestureEventTargetInfo](#arkui_gestureeventtargetinfo) \*\*info) | Obtains the information about a gesture event target. | +| int32_t [OH_ArkUI_GestureEventTargetInfo_IsScrollBegin](#oh_arkui_gestureeventtargetinfo_isscrollbegin) ([ArkUI_GestureEventTargetInfo](#arkui_gestureeventtargetinfo) \*info, bool \*ret) | Obtains whether this scroll container is scrolled to the top. | +| int32_t [OH_ArkUI_GestureEventTargetInfo_IsScrollEnd](#oh_arkui_gestureeventtargetinfo_isscrollend) ([ArkUI_GestureEventTargetInfo](#arkui_gestureeventtargetinfo) \*info, bool \*ret) | Obtains whether this scroll container is scrolled to the bottom. | +| int32_t [OH_ArkUI_GetPanGestureDirectionMask](#oh_arkui_getpangesturedirectionmask) (ArkUI_GestureRecognizer \*recognizer, [ArkUI_GestureDirectionMask](#arkui_gesturedirectionmask) \*directionMask) | Obtains the direction of a pan gesture. | +| bool [OH_ArkUI_IsBuiltInGesture](#oh_arkui_isbuiltingesture) (ArkUI_GestureRecognizer \*recognizer) | Obtains whether a gesture is a built-in gesture. | +| int32_t [OH_ArkUI_GetGestureTag](#oh_arkui_getgesturetag) (ArkUI_GestureRecognizer \*recognizer, char \*buffer, int32_t bufferSize, int32_t \*result) | Obtains the tag of a gesture recognizer. | +| int32_t [OH_ArkUI_GetGestureBindNodeId](#oh_arkui_getgesturebindnodeid) (ArkUI_GestureRecognizer \*recognizer, char \*nodeId, int32_t size, int32_t \*result) | Obtains the ID of the component linked to a gesture recognizer. | +| bool [OH_ArkUI_IsGestureRecognizerValid](#oh_arkui_isgesturerecognizervalid) (ArkUI_GestureRecognizer \*recognizer) | Obtains whether a gesture recognizer is valid. | +| void \* [OH_ArkUI_ParallelInnerGestureEvent_GetUserData](#oh_arkui_parallelinnergestureevent_getuserdata) ([ArkUI_ParallelInnerGestureEvent](#arkui_parallelinnergestureevent) \*event) | Obtains custom data in the parallel internal gesture event. | +| void* [OH_ArkUI_GestureInterrupter_GetUserData](#oh_arkui_gestureinterrupter_getuserdata) ([ArkUI_GestureInterruptInfo](#arkui_gestureinterruptinfo)* event) | Obtains the custom data from a gesture interruption event.| +| ArkUI_GestureRecognizer \* [OH_ArkUI_ParallelInnerGestureEvent_GetCurrentRecognizer](#oh_arkui_parallelinnergestureevent_getcurrentrecognizer) ([ArkUI_ParallelInnerGestureEvent](#arkui_parallelinnergestureevent) \*event) | Obtains the current gesture recognizer in a parallel internal gesture event. | +| int32_t [OH_ArkUI_ParallelInnerGestureEvent_GetConflictRecognizers](#oh_arkui_parallelinnergestureevent_getconflictrecognizers) ([ArkUI_ParallelInnerGestureEvent](#arkui_parallelinnergestureevent) \*event, [ArkUI_GestureRecognizerHandleArray](#arkui_gesturerecognizerhandlearray) \*array, int32_t \*size) | Obtains the conflicting gesture recognizers in a parallel internal gesture event. | +| int32_t [OH_ArkUI_SetArkUIGestureRecognizerDisposeNotify](#oh_arkui_setarkuigesturerecognizerdisposenotify) (ArkUI_GestureRecognizer \*recognizer, [ArkUI_GestureRecognizerDestructNotifyCallback](#arkui_gesturerecognizerdestructnotifycallback) callback, void \*userData) | Sets a callback function for notifying gesture recognizer destruction. | +| void \* [OH_ArkUI_QueryModuleInterfaceByName](#oh_arkui_querymoduleinterfacebyname) ([ArkUI_NativeAPIVariantKind](#arkui_nativeapivariantkind) type, const char \*structName) | Obtains the native API set of a specified type. | | [ArkUI_KeyEventType](#arkui_keyeventtype) [OH_ArkUI_KeyEvent_GetType](#oh_arkui_keyevent_gettype) (const [ArkUI_UIInputEvent](_ark_u_i___event_module.md#arkui_uiinputevent) \*event) | Obtains the type of a key event. | | int32_t [OH_ArkUI_KeyEvent_GetKeyCode](#oh_arkui_keyevent_getkeycode) (const [ArkUI_UIInputEvent](_ark_u_i___event_module.md#arkui_uiinputevent) \*event) | Obtains the key code from a key event. | | const char \* [OH_ArkUI_KeyEvent_GetKeyText](#oh_arkui_keyevent_getkeytext) (const [ArkUI_UIInputEvent](_ark_u_i___event_module.md#arkui_uiinputevent) \*event) | Obtains the key value from a key event. | | [ArkUI_KeySourceType](#arkui_keysourcetype) [OH_ArkUI_KeyEvent_GetKeySource](#oh_arkui_keyevent_getkeysource) (const [ArkUI_UIInputEvent](_ark_u_i___event_module.md#arkui_uiinputevent) \*event) | Obtains the type of input device that triggers a key event. | | void [OH_ArkUI_KeyEvent_StopPropagation](#oh_arkui_keyevent_stoppropagation) (const [ArkUI_UIInputEvent](_ark_u_i___event_module.md#arkui_uiinputevent) \*event, bool stopPropagation) | Stops a key event from bubbling upwards or downwards. | -| void [OH_ArkUI_KeyEvent_Dispatch](#oh_arkui_keyevent_dispatch) ([ArkUI_NodeHandle](#arkui_nodehandle) \*node, const [ArkUI_UIInputEvent](_ark_u_i___event_module.md#arkui_uiinputevent) \*event) | Dispatches a key event to a specific node. | +| void [OH_ArkUI_KeyEvent_Dispatch](#oh_arkui_keyevent_dispatch) ([ArkUI_NodeHandle](#arkui_nodehandle) \*node, const [ArkUI_UIInputEvent](_ark_u_i___event_module.md#arkui_uiinputevent) \*event) | Dispatches a key event to a specific node. | | [ArkUI_KeyIntension](#arkui_keyintension) [OH_ArkUI_KeyEvent_GetKeyIntensionCode](#oh_arkui_keyevent_getkeyintensioncode) (const [ArkUI_UIInputEvent](_ark_u_i___event_module.md#arkui_uiinputevent) \*event) | Obtains the intention code associated with a key event. | | uint32_t [OH_ArkUI_KeyEvent_GetUnicode](#oh_arkui_keyevent_getunicode) (const [ArkUI_UIInputEvent](_ark_u_i___event_module.md#arkui_uiinputevent) \*event) | Obtains the Unicode value of a key event. Non-space basic Latin characters in the 0x0021-0x007E range are supported. Characters with a value of 0 are not supported. In the case of key combination, this API returns the Unicode value of the key corresponding to the key event. | | void [OH_ArkUI_KeyEvent_SetConsumed](#oh_arkui_keyevent_setconsumed) (const [ArkUI_UIInputEvent](_ark_u_i___event_module.md#arkui_uiinputevent) \*event, bool isConsumed) | Sets whether a key event is consumed in the key event callback. | -| [ArkUI_NodeEventType](#arkui_nodeeventtype) [OH_ArkUI_NodeEvent_GetEventType](#oh_arkui_nodeevent_geteventtype) ([ArkUI_NodeEvent](#arkui_nodeevent-12) \*event) | Obtains the type of a component event. | -| int32_t [OH_ArkUI_NodeEvent_GetTargetId](#oh_arkui_nodeevent_gettargetid) ([ArkUI_NodeEvent](#arkui_nodeevent-12) \*event) | Obtains the custom ID of a component event. | -| [ArkUI_NodeHandle](#arkui_nodehandle) [OH_ArkUI_NodeEvent_GetNodeHandle](#oh_arkui_nodeevent_getnodehandle) ([ArkUI_NodeEvent](#arkui_nodeevent-12) \*event) | Obtains the component object that triggers an event. | -| [ArkUI_UIInputEvent](_ark_u_i___event_module.md#arkui_uiinputevent) \* [OH_ArkUI_NodeEvent_GetInputEvent](#oh_arkui_nodeevent_getinputevent) ([ArkUI_NodeEvent](#arkui_nodeevent-12) \*event) | Obtains input event (for example, touch event) data for a component event. | -| [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) \* [OH_ArkUI_NodeEvent_GetNodeComponentEvent](#oh_arkui_nodeevent_getnodecomponentevent) ([ArkUI_NodeEvent](#arkui_nodeevent-12) \*event) | Obtains the numerical data in a component event. | -| [ArkUI_StringAsyncEvent](_ark_u_i___string_async_event.md) \* [OH_ArkUI_NodeEvent_GetStringAsyncEvent](#oh_arkui_nodeevent_getstringasyncevent) ([ArkUI_NodeEvent](#arkui_nodeevent-12) \*event) | Obtains the string data in a component event. | -| void \* [OH_ArkUI_NodeEvent_GetUserData](#oh_arkui_nodeevent_getuserdata) ([ArkUI_NodeEvent](#arkui_nodeevent-12) \*event) | Obtains the custom data in a component event. | -| int32_t [OH_ArkUI_NodeEvent_GetNumberValue](#oh_arkui_nodeevent_getnumbervalue) ([ArkUI_NodeEvent](#arkui_nodeevent-12) \*event, int32_t index, [ArkUI_NumberValue](union_ark_u_i___number_value.md) \*value) | Obtains the numeric-type parameter of a component event. | -| int32_t [OH_ArkUI_NodeEvent_GetStringValue](#oh_arkui_nodeevent_getstringvalue) ([ArkUI_NodeEvent](#arkui_nodeevent-12) \*event, int32_t index, char \*\*string, int32_t \*stringSize) | Obtains the string-type parameter of a component event. The string data is valid only during an event callback. To use it outside an event callback, you are advised to copy the string data. | -| int32_t [OH_ArkUI_NodeEvent_SetReturnNumberValue](#oh_arkui_nodeevent_setreturnnumbervalue) ([ArkUI_NodeEvent](#arkui_nodeevent-12) \*event, [ArkUI_NumberValue](union_ark_u_i___number_value.md) \*value, int32_t size) | Sets the return value for a component event. | -| [ArkUI_NodeAdapterHandle](#arkui_nodeadapterhandle) [OH_ArkUI_NodeAdapter_Create](#oh_arkui_nodeadapter_create) () | Creates a component adapter. | -| void [OH_ArkUI_NodeAdapter_Dispose](#oh_arkui_nodeadapter_dispose) ([ArkUI_NodeAdapterHandle](#arkui_nodeadapterhandle) handle) | Destroys a component adapter. | -| int32_t [OH_ArkUI_NodeAdapter_SetTotalNodeCount](#oh_arkui_nodeadapter_settotalnodecount) ([ArkUI_NodeAdapterHandle](#arkui_nodeadapterhandle) handle, uint32_t size) | Sets the total number of elements in the specified adapter. | -| uint32_t [OH_ArkUI_NodeAdapter_GetTotalNodeCount](#oh_arkui_nodeadapter_gettotalnodecount) ([ArkUI_NodeAdapterHandle](#arkui_nodeadapterhandle) handle) | Obtains the total number of elements in the specified adapter. | -| int32_t [OH_ArkUI_NodeAdapter_RegisterEventReceiver](#oh_arkui_nodeadapter_registereventreceiver) ([ArkUI_NodeAdapterHandle](#arkui_nodeadapterhandle) handle, void \*userData, void(\*receiver)([ArkUI_NodeAdapterEvent](#arkui_nodeadapterevent) \*event)) | Registers an event callback for the specified adapter. | -| void [OH_ArkUI_NodeAdapter_UnregisterEventReceiver](#oh_arkui_nodeadapter_unregistereventreceiver) ([ArkUI_NodeAdapterHandle](#arkui_nodeadapterhandle) handle) | Unregisters an event callback for the specified adapter. | -| int32_t [OH_ArkUI_NodeAdapter_ReloadAllItems](#oh_arkui_nodeadapter_reloadallitems) ([ArkUI_NodeAdapterHandle](#arkui_nodeadapterhandle) handle) | Instructs the specified adapter to reload all elements. | -| int32_t [OH_ArkUI_NodeAdapter_ReloadItem](#oh_arkui_nodeadapter_reloaditem) ([ArkUI_NodeAdapterHandle](#arkui_nodeadapterhandle) handle, uint32_t startPosition, uint32_t itemCount) | Instructs the specified adapter to reload certain elements. | -| int32_t [OH_ArkUI_NodeAdapter_RemoveItem](#oh_arkui_nodeadapter_removeitem) ([ArkUI_NodeAdapterHandle](#arkui_nodeadapterhandle) handle, uint32_t startPosition, uint32_t itemCount) | Instructs the specified adapter to remove certain elements. | -| int32_t [OH_ArkUI_NodeAdapter_InsertItem](#oh_arkui_nodeadapter_insertitem) ([ArkUI_NodeAdapterHandle](#arkui_nodeadapterhandle) handle, uint32_t startPosition, uint32_t itemCount) | Instructs the specified adapter to insert certain elements. | -| int32_t [OH_ArkUI_NodeAdapter_MoveItem](#oh_arkui_nodeadapter_moveitem) ([ArkUI_NodeAdapterHandle](#arkui_nodeadapterhandle) handle, uint32_t from, uint32_t to) | Instructs the specified adapter to move certain elements. | -| int32_t [OH_ArkUI_NodeAdapter_GetAllItems](#oh_arkui_nodeadapter_getallitems) ([ArkUI_NodeAdapterHandle](#arkui_nodeadapterhandle) handle, [ArkUI_NodeHandle](#arkui_nodehandle) \*\*items, uint32_t \*size) | Obtains all elements stored in the specified adapter. | -| void \* [OH_ArkUI_NodeAdapterEvent_GetUserData](#oh_arkui_nodeadapterevent_getuserdata) ([ArkUI_NodeAdapterEvent](#arkui_nodeadapterevent) \*event) | Obtains the custom data passed in during registration of the specified event. | -| [ArkUI_NodeAdapterEventType](#arkui_nodeadaptereventtype) [OH_ArkUI_NodeAdapterEvent_GetType](#oh_arkui_nodeadapterevent_gettype) ([ArkUI_NodeAdapterEvent](#arkui_nodeadapterevent) \*event) | Obtains the event type. | -| [ArkUI_NodeHandle](#arkui_nodehandle) [OH_ArkUI_NodeAdapterEvent_GetRemovedNode](#oh_arkui_nodeadapterevent_getremovednode) ([ArkUI_NodeAdapterEvent](#arkui_nodeadapterevent) \*event) | Obtains the element to be removed for the event to be destroyed. | -| uint32_t [OH_ArkUI_NodeAdapterEvent_GetItemIndex](#oh_arkui_nodeadapterevent_getitemindex) ([ArkUI_NodeAdapterEvent](#arkui_nodeadapterevent) \*event) | Obtains the index of the element to be operated for the specified adapter event. | -| [ArkUI_NodeHandle](#arkui_nodehandle) [OH_ArkUI_NodeAdapterEvent_GetHostNode](#oh_arkui_nodeadapterevent_gethostnode) ([ArkUI_NodeAdapterEvent](#arkui_nodeadapterevent) \*event) | Obtains the scrollable container node that uses the specified adapter. | -| int32_t [OH_ArkUI_NodeAdapterEvent_SetItem](#oh_arkui_nodeadapterevent_setitem) ([ArkUI_NodeAdapterEvent](#arkui_nodeadapterevent) \*event, [ArkUI_NodeHandle](#arkui_nodehandle) node) | Sets the component to be added to the specified adapter. | -| int32_t [OH_ArkUI_NodeAdapterEvent_SetNodeId](#oh_arkui_nodeadapterevent_setnodeid) ([ArkUI_NodeAdapterEvent](#arkui_nodeadapterevent) \*event, int32_t id) | Sets the component ID to be generated. | -| [ArkUI_LayoutConstraint](#arkui_layoutconstraint) \* [OH_ArkUI_NodeCustomEvent_GetLayoutConstraintInMeasure](#oh_arkui_nodecustomevent_getlayoutconstraintinmeasure) ([ArkUI_NodeCustomEvent](#arkui_nodecustomevent) \*event) | Obtains the size constraint for measurement through a custom component event. | -| [ArkUI_IntOffset](_ark_u_i___int_offset.md) [OH_ArkUI_NodeCustomEvent_GetPositionInLayout](#oh_arkui_nodecustomevent_getpositioninlayout) ([ArkUI_NodeCustomEvent](#arkui_nodecustomevent) \*event) | Obtains the expected position of a component relative to its parent component in the layout phase through a custom component event. | -| [ArkUI_DrawContext](#arkui_drawcontext) \* [OH_ArkUI_NodeCustomEvent_GetDrawContextInDraw](#oh_arkui_nodecustomevent_getdrawcontextindraw) ([ArkUI_NodeCustomEvent](#arkui_nodecustomevent) \*event) | Obtains the drawing context through a custom component event. | -| int32_t [OH_ArkUI_NodeCustomEvent_GetEventTargetId](#oh_arkui_nodecustomevent_geteventtargetid) ([ArkUI_NodeCustomEvent](#arkui_nodecustomevent) \*event) | Obtains the ID of a custom component event. | -| void \* [OH_ArkUI_NodeCustomEvent_GetUserData](#oh_arkui_nodecustomevent_getuserdata) ([ArkUI_NodeCustomEvent](#arkui_nodecustomevent) \*event) | Obtains custom event parameters through a custom component event. | -| [ArkUI_NodeHandle](#arkui_nodehandle) [OH_ArkUI_NodeCustomEvent_GetNodeHandle](#oh_arkui_nodecustomevent_getnodehandle) ([ArkUI_NodeCustomEvent](#arkui_nodecustomevent) \*event) | Obtains a component object through a custom component event. | -| [ArkUI_NodeCustomEventType](#arkui_nodecustomeventtype) [OH_ArkUI_NodeCustomEvent_GetEventType](#oh_arkui_nodecustomevent_geteventtype) ([ArkUI_NodeCustomEvent](#arkui_nodecustomevent) \*event) | Obtains the event type through a custom component event. | -| int32_t [OH_ArkUI_NodeCustomEvent_GetCustomSpanMeasureInfo](#oh_arkui_nodecustomevent_getcustomspanmeasureinfo) ([ArkUI_NodeCustomEvent](#arkui_nodecustomevent) \*event, [ArkUI_CustomSpanMeasureInfo](#arkui_customspanmeasureinfo) \*info) | Obtains the measurement information of a custom span through a custom component event. | -| int32_t [OH_ArkUI_NodeCustomEvent_SetCustomSpanMetrics](#oh_arkui_nodecustomevent_setcustomspanmetrics) ([ArkUI_NodeCustomEvent](#arkui_nodecustomevent) \*event, [ArkUI_CustomSpanMetrics](#arkui_customspanmetrics) \*metrics) | Sets the measurement metrics of a custom span through a custom component event. | -| int32_t [OH_ArkUI_NodeCustomEvent_GetCustomSpanDrawInfo](#oh_arkui_nodecustomevent_getcustomspandrawinfo) ([ArkUI_NodeCustomEvent](#arkui_nodecustomevent) \*event, [ArkUI_CustomSpanDrawInfo](#arkui_customspandrawinfo) \*info) | Obtains the drawing information of a custom span through a custom component event. | -| int32_t [OH_ArkUI_NodeContent_RegisterCallback](#oh_arkui_nodecontent_registercallback) ([ArkUI_NodeContentHandle](#arkui_nodecontenthandle) content, [ArkUI_NodeContentCallback](#arkui_nodecontentcallback) callback) | Registers the callback for the NodeContent event. | -| [ArkUI_NodeContentEventType](#arkui_nodecontenteventtype) [OH_ArkUI_NodeContentEvent_GetEventType](#oh_arkui_nodecontentevent_geteventtype) ([ArkUI_NodeContentEvent](#arkui_nodecontentevent) \*event) | Obtains the type of the specified NodeContent event. | -| [ArkUI_NodeContentHandle](#arkui_nodecontenthandle) [OH_ArkUI_NodeContentEvent_GetNodeContentHandle](#oh_arkui_nodecontentevent_getnodecontenthandle) ([ArkUI_NodeContentEvent](#arkui_nodecontentevent) \*event) | Obtains the object that triggers the specified NodeContent event. | -| int32_t [OH_ArkUI_NodeContent_SetUserData](#oh_arkui_nodecontent_setuserdata) ([ArkUI_NodeContentHandle](#arkui_nodecontenthandle) content, void \*userData) | Saves custom data to the specified NodeContent object. | -| void \* [OH_ArkUI_NodeContent_GetUserData](#oh_arkui_nodecontent_getuserdata) ([ArkUI_NodeContentHandle](#arkui_nodecontenthandle) content) | Obtains the custom data saved on the specified NodeContent object. | -| int32_t [OH_ArkUI_NodeContent_AddNode](#oh_arkui_nodecontent_addnode) ([ArkUI_NodeContentHandle](#arkui_nodecontenthandle) content, [ArkUI_NodeHandle](#arkui_nodehandle) node) | Adds an ArkUI component node to the specified NodeContent object. | -| int32_t [OH_ArkUI_NodeContent_RemoveNode](#oh_arkui_nodecontent_removenode) ([ArkUI_NodeContentHandle](#arkui_nodecontenthandle) content, [ArkUI_NodeHandle](#arkui_nodehandle) node) | Removes an ArkUI component node from the specified NodeContent object. | -| int32_t [OH_ArkUI_NodeContent_InsertNode](#oh_arkui_nodecontent_insertnode) ([ArkUI_NodeContentHandle](#arkui_nodecontenthandle) content, [ArkUI_NodeHandle](#arkui_nodehandle) node, int32_t position) | Inserts an ArkUI component node into a specific position of the specified NodeContent object. | -| int32_t [OH_ArkUI_NodeUtils_GetLayoutSize](#oh_arkui_nodeutils_getlayoutsize) ([ArkUI_NodeHandle](#arkui_nodehandle) node, [ArkUI_IntSize](_ark_u_i___int_size.md) \*size) | Obtains the layout area size of a component. The size does not count in transformation attributes, such as scale. | -| int32_t [OH_ArkUI_NodeUtils_GetLayoutPosition](#oh_arkui_nodeutils_getlayoutposition) ([ArkUI_NodeHandle](#arkui_nodehandle) node, [ArkUI_IntOffset](_ark_u_i___int_offset.md) \*localOffset) | Obtains the position of the component's layout area relative to its parent component. The relative position does not count in transformation attributes, such as translate. | -| int32_t [OH_ArkUI_NodeUtils_GetLayoutPositionInWindow](#oh_arkui_nodeutils_getlayoutpositioninwindow) ([ArkUI_NodeHandle](#arkui_nodehandle) node, [ArkUI_IntOffset](_ark_u_i___int_offset.md) \*globalOffset) | Obtains the position of the component's layout area relative to the window. The relative position does not count in transformation attributes, such as translate. | -| int32_t [OH_ArkUI_NodeUtils_GetLayoutPositionInScreen](#oh_arkui_nodeutils_getlayoutpositioninscreen) ([ArkUI_NodeHandle](#arkui_nodehandle) node, [ArkUI_IntOffset](_ark_u_i___int_offset.md) \*screenOffset) | Obtains the position of the component's layout area relative to the screen. The relative position does not count in transformation attributes, such as translate. | -| int32_t [OH_ArkUI_NodeUtils_GetPositionWithTranslateInWindow](#oh_arkui_nodeutils_getpositionwithtranslateinwindow) ([ArkUI_NodeHandle](#arkui_nodehandle) node, [ArkUI_IntOffset](_ark_u_i___int_offset.md) \*translateOffset) | Obtains the position of the component in the window, including the translate attribute. | -| int32_t [OH_ArkUI_NodeUtils_GetPositionWithTranslateInScreen](#oh_arkui_nodeutils_getpositionwithtranslateinscreen) ([ArkUI_NodeHandle](#arkui_nodehandle) node, [ArkUI_IntOffset](_ark_u_i___int_offset.md) \*translateOffset) | Obtains the position of the component on the screen, including the translate attribute. | -| void [OH_ArkUI_NodeUtils_AddCustomProperty](#oh_arkui_nodeutils_addcustomproperty) ([ArkUI_NodeHandle](#arkui_nodehandle) node, const char \*name, const char \*value) | Sets a custom property for this component. This API takes effect only in the main thread. | -| void [OH_ArkUI_NodeUtils_RemoveCustomProperty](#oh_arkui_nodeutils_removecustomproperty) ([ArkUI_NodeHandle](#arkui_nodehandle) node, const char \*name) | Removes a custom property that has been set for the specified component. | +| [ArkUI_NodeEventType](#arkui_nodeeventtype) [OH_ArkUI_NodeEvent_GetEventType](#oh_arkui_nodeevent_geteventtype) ([ArkUI_NodeEvent](#arkui_nodeevent-12) \*event) | Obtains the type of a component event. | +| int32_t [OH_ArkUI_NodeEvent_GetTargetId](#oh_arkui_nodeevent_gettargetid) ([ArkUI_NodeEvent](#arkui_nodeevent-12) \*event) | Obtains the custom ID of a component event. | +| [ArkUI_NodeHandle](#arkui_nodehandle) [OH_ArkUI_NodeEvent_GetNodeHandle](#oh_arkui_nodeevent_getnodehandle) ([ArkUI_NodeEvent](#arkui_nodeevent-12) \*event) | Obtains the component object that triggers an event. | +| [ArkUI_UIInputEvent](_ark_u_i___event_module.md#arkui_uiinputevent) \* [OH_ArkUI_NodeEvent_GetInputEvent](#oh_arkui_nodeevent_getinputevent) ([ArkUI_NodeEvent](#arkui_nodeevent-12) \*event) | Obtains input event (for example, touch event) data for a component event. | +| [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) \* [OH_ArkUI_NodeEvent_GetNodeComponentEvent](#oh_arkui_nodeevent_getnodecomponentevent) ([ArkUI_NodeEvent](#arkui_nodeevent-12) \*event) | Obtains the numerical data in a component event. | +| [ArkUI_StringAsyncEvent](_ark_u_i___string_async_event.md) \* [OH_ArkUI_NodeEvent_GetStringAsyncEvent](#oh_arkui_nodeevent_getstringasyncevent) ([ArkUI_NodeEvent](#arkui_nodeevent-12) \*event) | Obtains the string data in a component event. | +| void \* [OH_ArkUI_NodeEvent_GetUserData](#oh_arkui_nodeevent_getuserdata) ([ArkUI_NodeEvent](#arkui_nodeevent-12) \*event) | Obtains the custom data in a component event. | +| int32_t [OH_ArkUI_NodeEvent_GetNumberValue](#oh_arkui_nodeevent_getnumbervalue) ([ArkUI_NodeEvent](#arkui_nodeevent-12) \*event, int32_t index, [ArkUI_NumberValue](union_ark_u_i___number_value.md) \*value) | Obtains the numeric-type parameter of a component event. | +| int32_t [OH_ArkUI_NodeEvent_GetStringValue](#oh_arkui_nodeevent_getstringvalue) ([ArkUI_NodeEvent](#arkui_nodeevent-12) \*event, int32_t index, char \*\*string, int32_t \*stringSize) | Obtains the string-type parameter of a component event. The string data is valid only during an event callback. To use it outside an event callback, you are advised to copy the string data. | +| int32_t [OH_ArkUI_NodeEvent_SetReturnNumberValue](#oh_arkui_nodeevent_setreturnnumbervalue) ([ArkUI_NodeEvent](#arkui_nodeevent-12) \*event, [ArkUI_NumberValue](union_ark_u_i___number_value.md) \*value, int32_t size) | Sets the return value for a component event. | +| [ArkUI_NodeAdapterHandle](#arkui_nodeadapterhandle) [OH_ArkUI_NodeAdapter_Create](#oh_arkui_nodeadapter_create) () | Creates a component adapter. | +| void [OH_ArkUI_NodeAdapter_Dispose](#oh_arkui_nodeadapter_dispose) ([ArkUI_NodeAdapterHandle](#arkui_nodeadapterhandle) handle) | Destroys a component adapter. | +| int32_t [OH_ArkUI_NodeAdapter_SetTotalNodeCount](#oh_arkui_nodeadapter_settotalnodecount) ([ArkUI_NodeAdapterHandle](#arkui_nodeadapterhandle) handle, uint32_t size) | Sets the total number of elements in the specified adapter. | +| uint32_t [OH_ArkUI_NodeAdapter_GetTotalNodeCount](#oh_arkui_nodeadapter_gettotalnodecount) ([ArkUI_NodeAdapterHandle](#arkui_nodeadapterhandle) handle) | Obtains the total number of elements in the specified adapter. | +| int32_t [OH_ArkUI_NodeAdapter_RegisterEventReceiver](#oh_arkui_nodeadapter_registereventreceiver) ([ArkUI_NodeAdapterHandle](#arkui_nodeadapterhandle) handle, void \*userData, void(\*receiver)([ArkUI_NodeAdapterEvent](#arkui_nodeadapterevent) \*event)) | Registers an event callback for the specified adapter. | +| void [OH_ArkUI_NodeAdapter_UnregisterEventReceiver](#oh_arkui_nodeadapter_unregistereventreceiver) ([ArkUI_NodeAdapterHandle](#arkui_nodeadapterhandle) handle) | Unregisters an event callback for the specified adapter. | +| int32_t [OH_ArkUI_NodeAdapter_ReloadAllItems](#oh_arkui_nodeadapter_reloadallitems) ([ArkUI_NodeAdapterHandle](#arkui_nodeadapterhandle) handle) | Instructs the specified adapter to reload all elements. | +| int32_t [OH_ArkUI_NodeAdapter_ReloadItem](#oh_arkui_nodeadapter_reloaditem) ([ArkUI_NodeAdapterHandle](#arkui_nodeadapterhandle) handle, uint32_t startPosition, uint32_t itemCount) | Instructs the specified adapter to reload certain elements. | +| int32_t [OH_ArkUI_NodeAdapter_RemoveItem](#oh_arkui_nodeadapter_removeitem) ([ArkUI_NodeAdapterHandle](#arkui_nodeadapterhandle) handle, uint32_t startPosition, uint32_t itemCount) | Instructs the specified adapter to remove certain elements. | +| int32_t [OH_ArkUI_NodeAdapter_InsertItem](#oh_arkui_nodeadapter_insertitem) ([ArkUI_NodeAdapterHandle](#arkui_nodeadapterhandle) handle, uint32_t startPosition, uint32_t itemCount) | Instructs the specified adapter to insert certain elements. | +| int32_t [OH_ArkUI_NodeAdapter_MoveItem](#oh_arkui_nodeadapter_moveitem) ([ArkUI_NodeAdapterHandle](#arkui_nodeadapterhandle) handle, uint32_t from, uint32_t to) | Instructs the specified adapter to move certain elements. | +| int32_t [OH_ArkUI_NodeAdapter_GetAllItems](#oh_arkui_nodeadapter_getallitems) ([ArkUI_NodeAdapterHandle](#arkui_nodeadapterhandle) handle, [ArkUI_NodeHandle](#arkui_nodehandle) \*\*items, uint32_t \*size) | Obtains all elements stored in the specified adapter. | +| void \* [OH_ArkUI_NodeAdapterEvent_GetUserData](#oh_arkui_nodeadapterevent_getuserdata) ([ArkUI_NodeAdapterEvent](#arkui_nodeadapterevent) \*event) | Obtains the custom data passed in during registration of the specified event. | +| [ArkUI_NodeAdapterEventType](#arkui_nodeadaptereventtype) [OH_ArkUI_NodeAdapterEvent_GetType](#oh_arkui_nodeadapterevent_gettype) ([ArkUI_NodeAdapterEvent](#arkui_nodeadapterevent) \*event) | Obtains the event type. | +| [ArkUI_NodeHandle](#arkui_nodehandle) [OH_ArkUI_NodeAdapterEvent_GetRemovedNode](#oh_arkui_nodeadapterevent_getremovednode) ([ArkUI_NodeAdapterEvent](#arkui_nodeadapterevent) \*event) | Obtains the element to be removed for the event to be destroyed. | +| uint32_t [OH_ArkUI_NodeAdapterEvent_GetItemIndex](#oh_arkui_nodeadapterevent_getitemindex) ([ArkUI_NodeAdapterEvent](#arkui_nodeadapterevent) \*event) | Obtains the index of the element to be operated for the specified adapter event. | +| [ArkUI_NodeHandle](#arkui_nodehandle) [OH_ArkUI_NodeAdapterEvent_GetHostNode](#oh_arkui_nodeadapterevent_gethostnode) ([ArkUI_NodeAdapterEvent](#arkui_nodeadapterevent) \*event) | Obtains the scrollable container node that uses the specified adapter. | +| int32_t [OH_ArkUI_NodeAdapterEvent_SetItem](#oh_arkui_nodeadapterevent_setitem) ([ArkUI_NodeAdapterEvent](#arkui_nodeadapterevent) \*event, [ArkUI_NodeHandle](#arkui_nodehandle) node) | Sets the component to be added to the specified adapter. | +| int32_t [OH_ArkUI_NodeAdapterEvent_SetNodeId](#oh_arkui_nodeadapterevent_setnodeid) ([ArkUI_NodeAdapterEvent](#arkui_nodeadapterevent) \*event, int32_t id) | Sets the component ID to be generated. | +| [ArkUI_LayoutConstraint](#arkui_layoutconstraint) \* [OH_ArkUI_NodeCustomEvent_GetLayoutConstraintInMeasure](#oh_arkui_nodecustomevent_getlayoutconstraintinmeasure) ([ArkUI_NodeCustomEvent](#arkui_nodecustomevent) \*event) | Obtains the size constraint for measurement through a custom component event. | +| [ArkUI_IntOffset](_ark_u_i___int_offset.md) [OH_ArkUI_NodeCustomEvent_GetPositionInLayout](#oh_arkui_nodecustomevent_getpositioninlayout) ([ArkUI_NodeCustomEvent](#arkui_nodecustomevent) \*event) | Obtains the expected position of a component relative to its parent component in the layout phase through a custom component event. | +| [ArkUI_DrawContext](#arkui_drawcontext) \* [OH_ArkUI_NodeCustomEvent_GetDrawContextInDraw](#oh_arkui_nodecustomevent_getdrawcontextindraw) ([ArkUI_NodeCustomEvent](#arkui_nodecustomevent) \*event) | Obtains the drawing context through a custom component event. | +| int32_t [OH_ArkUI_NodeCustomEvent_GetEventTargetId](#oh_arkui_nodecustomevent_geteventtargetid) ([ArkUI_NodeCustomEvent](#arkui_nodecustomevent) \*event) | Obtains the ID of a custom component event. | +| void \* [OH_ArkUI_NodeCustomEvent_GetUserData](#oh_arkui_nodecustomevent_getuserdata) ([ArkUI_NodeCustomEvent](#arkui_nodecustomevent) \*event) | Obtains custom event parameters through a custom component event. | +| [ArkUI_NodeHandle](#arkui_nodehandle) [OH_ArkUI_NodeCustomEvent_GetNodeHandle](#oh_arkui_nodecustomevent_getnodehandle) ([ArkUI_NodeCustomEvent](#arkui_nodecustomevent) \*event) | Obtains a component object through a custom component event. | +| [ArkUI_NodeCustomEventType](#arkui_nodecustomeventtype) [OH_ArkUI_NodeCustomEvent_GetEventType](#oh_arkui_nodecustomevent_geteventtype) ([ArkUI_NodeCustomEvent](#arkui_nodecustomevent) \*event) | Obtains the event type through a custom component event. | +| int32_t [OH_ArkUI_NodeCustomEvent_GetCustomSpanMeasureInfo](#oh_arkui_nodecustomevent_getcustomspanmeasureinfo) ([ArkUI_NodeCustomEvent](#arkui_nodecustomevent) \*event, [ArkUI_CustomSpanMeasureInfo](#arkui_customspanmeasureinfo) \*info) | Obtains the measurement information of a custom span through a custom component event. | +| int32_t [OH_ArkUI_NodeCustomEvent_SetCustomSpanMetrics](#oh_arkui_nodecustomevent_setcustomspanmetrics) ([ArkUI_NodeCustomEvent](#arkui_nodecustomevent) \*event, [ArkUI_CustomSpanMetrics](#arkui_customspanmetrics) \*metrics) | Sets the measurement metrics of a custom span through a custom component event. | +| int32_t [OH_ArkUI_NodeCustomEvent_GetCustomSpanDrawInfo](#oh_arkui_nodecustomevent_getcustomspandrawinfo) ([ArkUI_NodeCustomEvent](#arkui_nodecustomevent) \*event, [ArkUI_CustomSpanDrawInfo](#arkui_customspandrawinfo) \*info) | Obtains the drawing information of a custom span through a custom component event. | +| int32_t [OH_ArkUI_NodeContent_RegisterCallback](#oh_arkui_nodecontent_registercallback) ([ArkUI_NodeContentHandle](#arkui_nodecontenthandle) content, [ArkUI_NodeContentCallback](#arkui_nodecontentcallback) callback) | Registers the callback for the NodeContent event. | +| [ArkUI_NodeContentEventType](#arkui_nodecontenteventtype) [OH_ArkUI_NodeContentEvent_GetEventType](#oh_arkui_nodecontentevent_geteventtype) ([ArkUI_NodeContentEvent](#arkui_nodecontentevent) \*event) | Obtains the type of the specified NodeContent event. | +| [ArkUI_NodeContentHandle](#arkui_nodecontenthandle) [OH_ArkUI_NodeContentEvent_GetNodeContentHandle](#oh_arkui_nodecontentevent_getnodecontenthandle) ([ArkUI_NodeContentEvent](#arkui_nodecontentevent) \*event) | Obtains the object that triggers the specified NodeContent event. | +| int32_t [OH_ArkUI_NodeContent_SetUserData](#oh_arkui_nodecontent_setuserdata) ([ArkUI_NodeContentHandle](#arkui_nodecontenthandle) content, void \*userData) | Saves custom data to the specified NodeContent object. | +| void \* [OH_ArkUI_NodeContent_GetUserData](#oh_arkui_nodecontent_getuserdata) ([ArkUI_NodeContentHandle](#arkui_nodecontenthandle) content) | Obtains the custom data saved on the specified NodeContent object. | +| int32_t [OH_ArkUI_NodeContent_AddNode](#oh_arkui_nodecontent_addnode) ([ArkUI_NodeContentHandle](#arkui_nodecontenthandle) content, [ArkUI_NodeHandle](#arkui_nodehandle) node) | Adds an ArkUI component node to the specified NodeContent object. | +| int32_t [OH_ArkUI_NodeContent_RemoveNode](#oh_arkui_nodecontent_removenode) ([ArkUI_NodeContentHandle](#arkui_nodecontenthandle) content, [ArkUI_NodeHandle](#arkui_nodehandle) node) | Removes an ArkUI component node from the specified NodeContent object. | +| int32_t [OH_ArkUI_NodeContent_InsertNode](#oh_arkui_nodecontent_insertnode) ([ArkUI_NodeContentHandle](#arkui_nodecontenthandle) content, [ArkUI_NodeHandle](#arkui_nodehandle) node, int32_t position) | Inserts an ArkUI component node into a specific position of the specified NodeContent object. | +| int32_t [OH_ArkUI_NodeUtils_GetLayoutSize](#oh_arkui_nodeutils_getlayoutsize) ([ArkUI_NodeHandle](#arkui_nodehandle) node, [ArkUI_IntSize](_ark_u_i___int_size.md) \*size) | Obtains the layout area size of a component. The size does not count in transformation attributes, such as scale. | +| int32_t [OH_ArkUI_NodeUtils_GetLayoutPosition](#oh_arkui_nodeutils_getlayoutposition) ([ArkUI_NodeHandle](#arkui_nodehandle) node, [ArkUI_IntOffset](_ark_u_i___int_offset.md) \*localOffset) | Obtains the position of the component's layout area relative to its parent component. The relative position does not count in transformation attributes, such as translate. | +| int32_t [OH_ArkUI_NodeUtils_GetLayoutPositionInWindow](#oh_arkui_nodeutils_getlayoutpositioninwindow) ([ArkUI_NodeHandle](#arkui_nodehandle) node, [ArkUI_IntOffset](_ark_u_i___int_offset.md) \*globalOffset) | Obtains the position of the component's layout area relative to the window. The relative position does not count in transformation attributes, such as translate. | +| int32_t [OH_ArkUI_NodeUtils_GetLayoutPositionInScreen](#oh_arkui_nodeutils_getlayoutpositioninscreen) ([ArkUI_NodeHandle](#arkui_nodehandle) node, [ArkUI_IntOffset](_ark_u_i___int_offset.md) \*screenOffset) | Obtains the position of the component's layout area relative to the screen. The relative position does not count in transformation attributes, such as translate. | +| int32_t [OH_ArkUI_NodeUtils_GetPositionWithTranslateInWindow](#oh_arkui_nodeutils_getpositionwithtranslateinwindow) ([ArkUI_NodeHandle](#arkui_nodehandle) node, [ArkUI_IntOffset](_ark_u_i___int_offset.md) \*translateOffset) | Obtains the position of the component in the window, including the translate attribute. | +| int32_t [OH_ArkUI_NodeUtils_GetPositionWithTranslateInScreen](#oh_arkui_nodeutils_getpositionwithtranslateinscreen) ([ArkUI_NodeHandle](#arkui_nodehandle) node, [ArkUI_IntOffset](_ark_u_i___int_offset.md) \*translateOffset) | Obtains the position of the component on the screen, including the translate attribute. | +| void [OH_ArkUI_NodeUtils_AddCustomProperty](#oh_arkui_nodeutils_addcustomproperty) ([ArkUI_NodeHandle](#arkui_nodehandle) node, const char \*name, const char \*value) | Sets a custom property for this component. This API takes effect only in the main thread. | +| void [OH_ArkUI_NodeUtils_RemoveCustomProperty](#oh_arkui_nodeutils_removecustomproperty) ([ArkUI_NodeHandle](#arkui_nodehandle) node, const char \*name) | Removes a custom property that has been set for the specified component. | | int32_t [OH_ArkUI_NodeUtils_GetCustomProperty](#oh_arkui_nodeutils_getcustomproperty) ([ArkUI_NodeHandle](#arkui_nodehandle) node, const char \*name, ArkUI_CustomProperty \*\*handle) | Obtains the value of a custom property of the specified component. | | [ArkUI_NodeHandle](#arkui_nodehandle) [OH_ArkUI_NodeUtils_GetParentInPageTree](#oh_arkui_nodeutils_getparentinpagetree) ([ArkUI_NodeHandle](#arkui_nodehandle) node) | Obtains the parent node, which can be a component node created with ArkTS. | | int32_t [OH_ArkUI_NodeUtils_GetActiveChildrenInfo](#oh_arkui_nodeutils_getactivechildreninfo) ([ArkUI_NodeHandle](#arkui_nodehandle) head, ArkUI_ActiveChildrenInfo \*\*handle) | Obtains all active child nodes of the specified node. Spans are not counted as child nodes. | | [ArkUI_NodeHandle](#arkui_nodehandle) [OH_ArkUI_NodeUtils_GetCurrentPageRootNode](#oh_arkui_nodeutils_getcurrentpagerootnode) ([ArkUI_NodeHandle](#arkui_nodehandle) node) | Obtains the root node of the current page. | | bool [OH_ArkUI_NodeUtils_IsCreatedByNDK](#oh_arkui_nodeutils_iscreatedbyndk) ([ArkUI_NodeHandle](#arkui_nodehandle) node) | Checks whether the specified component is created with the C API. | | int32_t [OH_ArkUI_NodeUtils_GetNodeType](#oh_arkui_nodeutils_getnodetype) ([ArkUI_NodeHandle](#arkui_nodehandle) node) | Obtains the type of the specified node. | -| int32_t [OH_ArkUI_List_CloseAllSwipeActions](#oh_arkui_list_closeallswipeactions) ([ArkUI_NodeHandle](#arkui_nodehandle) node, void \*userData, void(\*onFinish)(void \*userData)) | Collapses the list items in the expanded state. | -| [ArkUI_ContextHandle](#arkui_contexthandle-12) [OH_ArkUI_GetContextByNode](#oh_arkui_getcontextbynode) ([ArkUI_NodeHandle](#arkui_nodehandle) node) | Obtains the pointer to the UI context object of the specified node. | -| int32_t [OH_ArkUI_RegisterSystemColorModeChangeEvent](#oh_arkui_registersystemcolormodechangeevent) ([ArkUI_NodeHandle](#arkui_nodehandle) node, void \*userData, void(\*onColorModeChange)([ArkUI_SystemColorMode](#arkui_systemcolormode) colorMode, void \*userData)) | Registers an event listener for system color mode changes. A single component can only register one callback for system color mode changes. | -| void [OH_ArkUI_UnregisterSystemColorModeChangeEvent](#oh_arkui_unregistersystemcolormodechangeevent) ([ArkUI_NodeHandle](#arkui_nodehandle) node) | Unregisters the event listener for system color mode changes. | -| int32_t [OH_ArkUI_RegisterSystemFontStyleChangeEvent](#oh_arkui_registersystemfontstylechangeevent) ([ArkUI_NodeHandle](#arkui_nodehandle) node, void \*userData, void(\*onFontStyleChange)([ArkUI_SystemFontStyleEvent](#arkui_systemfontstyleevent) \*event, void \*userData)) | Registers an event listener for system font style changes. A single component can only register one callback for system font style changes. | -| void [OH_ArkUI_UnregisterSystemFontStyleChangeEvent](#oh_arkui_unregistersystemfontstylechangeevent) ([ArkUI_NodeHandle](#arkui_nodehandle) node) | Unregisters the event listener for system font style changes. | -| float [OH_ArkUI_SystemFontStyleEvent_GetFontSizeScale](#oh_arkui_systemfontstyleevent_getfontsizescale) (const [ArkUI_SystemFontStyleEvent](#arkui_systemfontstyleevent) \*event) | Obtains the font size from the system font style change event. | -| float [OH_ArkUI_SystemFontStyleEvent_GetFontWeightScale](#oh_arkui_systemfontstyleevent_getfontweightscale) (const [ArkUI_SystemFontStyleEvent](#arkui_systemfontstyleevent) \*event) | Obtains the font weight from the system font style change event. | -| int32_t [OH_ArkUI_GetNodeHandleFromNapiValue](#oh_arkui_getnodehandlefromnapivalue) (napi_env env, napi_value frameNode, [ArkUI_NodeHandle](#arkui_nodehandle) \*handle) | Obtains a **FrameNode** object on the ArkTS side and maps it to an **ArkUI_NodeHandle** object on the native side. | -| int32_t [OH_ArkUI_GetContextFromNapiValue](#oh_arkui_getcontextfromnapivalue) (napi_env env, napi_value value, [ArkUI_ContextHandle](#arkui_contexthandle-12) \*context) | Obtains a **UIContext** object on the ArkTS side and maps it to an **ArkUI_ContextHandle** object on the native side. | -| int32_t [OH_ArkUI_GetNodeContentFromNapiValue](#oh_arkui_getnodecontentfromnapivalue) (napi_env env, napi_value value, [ArkUI_NodeContentHandle](#arkui_nodecontenthandle) \*content) | Obtains a **NodeContent** object on the ArkTS side and maps it to an **ArkUI_NodeContentHandle** object on the native side. | -| int32_t [OH_ArkUI_GetDrawableDescriptorFromNapiValue](#oh_arkui_getdrawabledescriptorfromnapivalue) (napi_env env, napi_value value, [ArkUI_DrawableDescriptor](#arkui_drawabledescriptor) \*\*drawableDescriptor) | Maps a **DrawableDescriptor** object on the ArkTS side to an **ArkUI_DrawableDescriptor** object on the native side. | -| int32_t [OH_ArkUI_GetDrawableDescriptorFromResourceNapiValue](#oh_arkui_getdrawabledescriptorfromresourcenapivalue) (napi_env env, napi_value value, [ArkUI_DrawableDescriptor](#arkui_drawabledescriptor) \*\*drawableDescriptor) | Maps an $r resource object on the ArkTS side to an **ArkUI_DrawableDescriptor** object on the native side. | -| [ArkUI_ErrorCode](#arkui_errorcode) [OH_ArkUI_GetNavigationId](#oh_arkui_getnavigationid) ([ArkUI_NodeHandle](#arkui_nodehandle) node, char \*buffer, int32_t bufferSize, int32_t \*writeLength) | Obtains the ID of the **Navigation** component where the specified node is located. | -| [ArkUI_ErrorCode](#arkui_errorcode) [OH_ArkUI_GetNavDestinationName](#oh_arkui_getnavdestinationname) ([ArkUI_NodeHandle](#arkui_nodehandle) node, char \*buffer, int32_t bufferSize, int32_t \*writeLength) | Obtains the name of the **NavDestination** component where the specified node is located. | -| [ArkUI_ErrorCode](#arkui_errorcode) [OH_ArkUI_GetNavStackLength](#oh_arkui_getnavstacklength) ([ArkUI_NodeHandle](#arkui_nodehandle) node, int32_t \*length) | Obtains the length of the navigation stack where the specified node is located. | -| [ArkUI_ErrorCode](#arkui_errorcode) [OH_ArkUI_GetNavDestinationNameByIndex](#oh_arkui_getnavdestinationnamebyindex) ([ArkUI_NodeHandle](#arkui_nodehandle) node, int32_t index, char \*buffer, int32_t bufferSize, int32_t \*writeLength) | Obtains the page name that matches the specified index in the navigation stack where the specified node is located. The index starts from 0, which indicates the bottom of the stack. | -| [ArkUI_ErrorCode](#arkui_errorcode) [OH_ArkUI_GetNavDestinationId](#oh_arkui_getnavdestinationid) ([ArkUI_NodeHandle](#arkui_nodehandle) node, char \*buffer, int32_t bufferSize, int32_t \*writeLength) | Obtains the ID of the **NavDestination** component where the specified node is located. | -| [ArkUI_ErrorCode](#arkui_errorcode) [OH_ArkUI_GetNavDestinationState](#oh_arkui_getnavdestinationstate) ([ArkUI_NodeHandle](#arkui_nodehandle) node, [ArkUI_NavDestinationState](#arkui_navdestinationstate) \*state) | Obtains the state of the **NavDestination** component where the specified node is located. | -| [ArkUI_ErrorCode](#arkui_errorcode) [OH_ArkUI_GetNavDestinationIndex](#oh_arkui_getnavdestinationindex) ([ArkUI_NodeHandle](#arkui_nodehandle) node, int32_t \*index) | Obtains the index of the **NavDestination** component where the specified node is located in the navigation stack. | -| napi_value [OH_ArkUI_GetNavDestinationParam](#oh_arkui_getnavdestinationparam) ([ArkUI_NodeHandle](#arkui_nodehandle) node) | Obtains the parameters of the **NavDestination** component where the specified node is located. | -| [ArkUI_ErrorCode](#arkui_errorcode) [OH_ArkUI_GetRouterPageIndex](#oh_arkui_getrouterpageindex) ([ArkUI_NodeHandle](#arkui_nodehandle) node, int32_t \*index) | Obtains the index of the page where the specified node is located in the page stack for routing. | -| [ArkUI_ErrorCode](#arkui_errorcode) [OH_ArkUI_GetRouterPageName](#oh_arkui_getrouterpagename) ([ArkUI_NodeHandle](#arkui_nodehandle) node, char \*buffer, int32_t bufferSize, int32_t \*writeLength) | Obtains the name of the page where the specified node is located. | -| [ArkUI_ErrorCode](#arkui_errorcode) [OH_ArkUI_GetRouterPagePath](#oh_arkui_getrouterpagepath) ([ArkUI_NodeHandle](#arkui_nodehandle) node, char \*buffer, int32_t bufferSize, int32_t \*writeLength) | Obtains the path to the page where the specified node is located. | -| [ArkUI_ErrorCode](#arkui_errorcode) [OH_ArkUI_GetRouterPageState](#oh_arkui_getrouterpagestate) ([ArkUI_NodeHandle](#arkui_nodehandle) node, [ArkUI_RouterPageState](#arkui_routerpagestate) \*state) | Obtains the state of the page where the specified node is located. | -| [ArkUI_ErrorCode](#arkui_errorcode) [OH_ArkUI_GetRouterPageId](#oh_arkui_getrouterpageid) ([ArkUI_NodeHandle](#arkui_nodehandle) node, char \*buffer, int32_t bufferSize, int32_t \*writeLength) | Obtains the ID of the page where the specified node is located. | -| [ArkUI_LayoutConstraint](#arkui_layoutconstraint) \* [OH_ArkUI_LayoutConstraint_Create](#oh_arkui_layoutconstraint_create) () | Creates a size constraint. | -| [ArkUI_LayoutConstraint](#arkui_layoutconstraint) \* [OH_ArkUI_LayoutConstraint_Copy](#oh_arkui_layoutconstraint_copy) (const [ArkUI_LayoutConstraint](#arkui_layoutconstraint) \*Constraint) | Performs a deep copy of a size constraint. | -| void \* [OH_ArkUI_LayoutConstraint_Dispose](#oh_arkui_layoutconstraint_dispose) ([ArkUI_LayoutConstraint](#arkui_layoutconstraint) \*Constraint) | Disposes of the pointer to a size constraint. | -| int32_t [OH_ArkUI_LayoutConstraint_GetMaxWidth](#oh_arkui_layoutconstraint_getmaxwidth) (const [ArkUI_LayoutConstraint](#arkui_layoutconstraint) \*Constraint) | Obtains the maximum width for a size constraint, in px. | -| int32_t [OH_ArkUI_LayoutConstraint_GetMinWidth](#oh_arkui_layoutconstraint_getminwidth) (const [ArkUI_LayoutConstraint](#arkui_layoutconstraint) \*Constraint) | Obtains the minimum width for a size constraint, in px. | -| int32_t [OH_ArkUI_LayoutConstraint_GetMaxHeight](#oh_arkui_layoutconstraint_getmaxheight) (const [ArkUI_LayoutConstraint](#arkui_layoutconstraint) \*Constraint) | Obtains the maximum height for a size constraint, in px. | -| int32_t [OH_ArkUI_LayoutConstraint_GetMinHeight](#oh_arkui_layoutconstraint_getminheight) (const [ArkUI_LayoutConstraint](#arkui_layoutconstraint) \*Constraint) | Obtains the minimum height for a size constraint, in px. | -| int32_t [OH_ArkUI_LayoutConstraint_GetPercentReferenceWidth](#oh_arkui_layoutconstraint_getpercentreferencewidth) (const [ArkUI_LayoutConstraint](#arkui_layoutconstraint) \*Constraint) | Obtains the width percentage reference for a size constraint, in px. | -| int32_t [OH_ArkUI_LayoutConstraint_GetPercentReferenceHeight](#oh_arkui_layoutconstraint_getpercentreferenceheight) (const [ArkUI_LayoutConstraint](#arkui_layoutconstraint) \*Constraint) | Obtains the height percentage reference for a size constraint, in px. | -| void [OH_ArkUI_LayoutConstraint_SetMaxWidth](#oh_arkui_layoutconstraint_setmaxwidth) ([ArkUI_LayoutConstraint](#arkui_layoutconstraint) \*Constraint, int32_t value) | Sets the maximum width. | -| void [OH_ArkUI_LayoutConstraint_SetMinWidth](#oh_arkui_layoutconstraint_setminwidth) ([ArkUI_LayoutConstraint](#arkui_layoutconstraint) \*Constraint, int32_t value) | Sets the minimum width. | -| void [OH_ArkUI_LayoutConstraint_SetMaxHeight](#oh_arkui_layoutconstraint_setmaxheight) ([ArkUI_LayoutConstraint](#arkui_layoutconstraint) \*Constraint, int32_t value) | Sets the maximum height. | -| void [OH_ArkUI_LayoutConstraint_SetMinHeight](#oh_arkui_layoutconstraint_setminheight) ([ArkUI_LayoutConstraint](#arkui_layoutconstraint) \*Constraint, int32_t value) | Sets the minimum height. | -| void [OH_ArkUI_LayoutConstraint_SetPercentReferenceWidth](#oh_arkui_layoutconstraint_setpercentreferencewidth) ([ArkUI_LayoutConstraint](#arkui_layoutconstraint) \*Constraint, int32_t value) | Sets the width percentage reference. | -| void [OH_ArkUI_LayoutConstraint_SetPercentReferenceHeight](#oh_arkui_layoutconstraint_setpercentreferenceheight) ([ArkUI_LayoutConstraint](#arkui_layoutconstraint) \*Constraint, int32_t value) | Sets the height percentage reference. | -| void \* [OH_ArkUI_DrawContext_GetCanvas](#oh_arkui_drawcontext_getcanvas) ([ArkUI_DrawContext](#arkui_drawcontext) \*context) | Obtains the pointer to a canvas for drawing, which can be converted into the **OH_Drawing_Canvas** in the **Drawing** module. | -| [ArkUI_IntSize](_ark_u_i___int_size.md) [OH_ArkUI_DrawContext_GetSize](#oh_arkui_drawcontext_getsize) ([ArkUI_DrawContext](#arkui_drawcontext) \*context) | Obtains the size of a drawing area. | -| [ArkUI_WaterFlowSectionOption](#arkui_waterflowsectionoption) \* [OH_ArkUI_WaterFlowSectionOption_Create](#oh_arkui_waterflowsectionoption_create) () | Creates a water flow section configuration. | -| void [OH_ArkUI_WaterFlowSectionOption_Dispose](#oh_arkui_waterflowsectionoption_dispose) ([ArkUI_WaterFlowSectionOption](#arkui_waterflowsectionoption) \*option) | Disposes of the pointer to a water flow section configuration. | -| void [OH_ArkUI_WaterFlowSectionOption_SetSize](#oh_arkui_waterflowsectionoption_setsize) ([ArkUI_WaterFlowSectionOption](#arkui_waterflowsectionoption) \*option, int32_t size) | Sets the array length for a water flow section configuration. | -| int32_t [OH_ArkUI_WaterFlowSectionOption_GetSize](#oh_arkui_waterflowsectionoption_getsize) ([ArkUI_WaterFlowSectionOption](#arkui_waterflowsectionoption) \*option) | Sets the array length for a water flow section configuration. | -| void [OH_ArkUI_WaterFlowSectionOption_SetItemCount](#oh_arkui_waterflowsectionoption_setitemcount) ([ArkUI_WaterFlowSectionOption](#arkui_waterflowsectionoption) \*option, int32_t index, int32_t itemCount) | Sets the number of items in a water flow section. | -| int32_t [OH_ArkUI_WaterFlowSectionOption_GetItemCount](#oh_arkui_waterflowsectionoption_getitemcount) ([ArkUI_WaterFlowSectionOption](#arkui_waterflowsectionoption) \*option, int32_t index) | Obtains the number of items in the water flow section that matches the specified index. | -| void [OH_ArkUI_WaterFlowSectionOption_SetCrossCount](#oh_arkui_waterflowsectionoption_setcrosscount) ([ArkUI_WaterFlowSectionOption](#arkui_waterflowsectionoption) \*option, int32_t index, int32_t crossCount) | Sets the number of columns (in a vertical layout) or rows (in a horizontal layout) of a water flow. | -| int32_t [OH_ArkUI_WaterFlowSectionOption_GetCrossCount](#oh_arkui_waterflowsectionoption_getcrosscount) ([ArkUI_WaterFlowSectionOption](#arkui_waterflowsectionoption) \*option, int32_t index) | Obtains the number of columns (in a vertical layout) or rows (in a horizontal layout) of a water flow. | -| void [OH_ArkUI_WaterFlowSectionOption_SetColumnGap](#oh_arkui_waterflowsectionoption_setcolumngap) ([ArkUI_WaterFlowSectionOption](#arkui_waterflowsectionoption) \*, int32_t index, float columnGap) | Sets the gap between columns in the specified water flow section. | -| float [OH_ArkUI_WaterFlowSectionOption_GetColumnGap](#oh_arkui_waterflowsectionoption_getcolumngap) ([ArkUI_WaterFlowSectionOption](#arkui_waterflowsectionoption) \*option, int32_t index) | Obtains the gap between columns in the water flow section that matches the specified index. | -| void [OH_ArkUI_WaterFlowSectionOption_SetRowGap](#oh_arkui_waterflowsectionoption_setrowgap) ([ArkUI_WaterFlowSectionOption](#arkui_waterflowsectionoption) \*option, int32_t index, float rowGap) | Sets the gap between rows in the specified water flow section. | -| float [OH_ArkUI_WaterFlowSectionOption_GetRowGap](#oh_arkui_waterflowsectionoption_getrowgap) ([ArkUI_WaterFlowSectionOption](#arkui_waterflowsectionoption) \*option, int32_t index) | Obtains the gap between rows in the water flow section that matches the specified index. | -| void [OH_ArkUI_WaterFlowSectionOption_SetMargin](#oh_arkui_waterflowsectionoption_setmargin) ([ArkUI_WaterFlowSectionOption](#arkui_waterflowsectionoption) \*option, int32_t index, float marginTop, float marginRight, float marginBottom, float marginLeft) | Sets the margins for the specified water flow section. | -| [ArkUI_Margin](_ark_u_i___margin.md) [OH_ArkUI_WaterFlowSectionOption_GetMargin](#oh_arkui_waterflowsectionoption_getmargin) ([ArkUI_WaterFlowSectionOption](#arkui_waterflowsectionoption) \*option, int32_t index) | Obtains the margins of the water flow section that matches the specified index. | -| void [OH_ArkUI_WaterFlowSectionOption_RegisterGetItemMainSizeCallbackByIndex](#oh_arkui_waterflowsectionoption_registergetitemmainsizecallbackbyindex) ([ArkUI_WaterFlowSectionOption](#arkui_waterflowsectionoption) \*option, int32_t index, float(\*callback)(int32_t itemIndex)) | Obtains the main axis size of a specified item based on **flowItemIndex** through a water flow section configuration. | -| void [OH_ArkUI_WaterFlowSectionOption_RegisterGetItemMainSizeCallbackByIndexWithUserData](#oh_arkui_waterflowsectionoption_registergetitemmainsizecallbackbyindexwithuserdata) ([ArkUI_WaterFlowSectionOption](#arkui_waterflowsectionoption) \*option, int32_t index, void \*userData, float(\*callback)(int32_t itemIndex, void \*userData)) | Obtains the main axis size of a specified item based on **flowItemIndex** through a water flow section configuration. | -| [ArkUI_GuidelineOption](#arkui_guidelineoption) \* [OH_ArkUI_GuidelineOption_Create](#oh_arkui_guidelineoption_create) (int32_t size) | Creates a guideline configuration for this **RelativeContainer** component. | -| void [OH_ArkUI_GuidelineOption_Dispose](#oh_arkui_guidelineoption_dispose) ([ArkUI_GuidelineOption](#arkui_guidelineoption) \*guideline) | Disposes of a guideline configuration. | -| void [OH_ArkUI_GuidelineOption_SetId](#oh_arkui_guidelineoption_setid) ([ArkUI_GuidelineOption](#arkui_guidelineoption) \*guideline, const char \*value, int32_t index) | Sets the ID of a guideline. | -| void [OH_ArkUI_GuidelineOption_SetDirection](#oh_arkui_guidelineoption_setdirection) ([ArkUI_GuidelineOption](#arkui_guidelineoption) \*guideline, [ArkUI_Axis](#arkui_axis) value, int32_t index) | Sets the direction of a guideline. | -| void [OH_ArkUI_GuidelineOption_SetPositionStart](#oh_arkui_guidelineoption_setpositionstart) ([ArkUI_GuidelineOption](#arkui_guidelineoption) \*guideline, float value, int32_t index) | Sets the distance between a guideline and the left or top of the container. | -| void [OH_ArkUI_GuidelineOption_SetPositionEnd](#oh_arkui_guidelineoption_setpositionend) ([ArkUI_GuidelineOption](#arkui_guidelineoption) \*guideline, float value, int32_t index) | Sets the distance between a guideline and the right or bottom of the container. | -| const char \* [OH_ArkUI_GuidelineOption_GetId](#oh_arkui_guidelineoption_getid) ([ArkUI_GuidelineOption](#arkui_guidelineoption) \*guideline, int32_t index) | Obtains the ID of a guideline. | -| [ArkUI_Axis](#arkui_axis) [OH_ArkUI_GuidelineOption_GetDirection](#oh_arkui_guidelineoption_getdirection) ([ArkUI_GuidelineOption](#arkui_guidelineoption) \*guideline, int32_t index) | Obtains the direction of a guideline. | -| float [OH_ArkUI_GuidelineOption_GetPositionStart](#oh_arkui_guidelineoption_getpositionstart) ([ArkUI_GuidelineOption](#arkui_guidelineoption) \*guideline, int32_t index) | Obtains the distance between a guideline and the left or top of the container. | -| float [OH_ArkUI_GuidelineOption_GetPositionEnd](#oh_arkui_guidelineoption_getpositionend) ([ArkUI_GuidelineOption](#arkui_guidelineoption) \*guideline, int32_t index) | Obtains the distance between a guideline and the right or bottom of the container. | -| [ArkUI_BarrierOption](#arkui_barrieroption) \* [OH_ArkUI_BarrierOption_Create](#oh_arkui_barrieroption_create) (int32_t size) | Creates a barrier configuration for this **RelativeContainer** component. | -| void [OH_ArkUI_BarrierOption_Dispose](#oh_arkui_barrieroption_dispose) ([ArkUI_BarrierOption](#arkui_barrieroption) \*barrierStyle) | Disposes of a barrier configuration. | -| void [OH_ArkUI_BarrierOption_SetId](#oh_arkui_barrieroption_setid) ([ArkUI_BarrierOption](#arkui_barrieroption) \*barrierStyle, const char \*value, int32_t index) | Sets the ID of a barrier. | -| void [OH_ArkUI_BarrierOption_SetDirection](#oh_arkui_barrieroption_setdirection) ([ArkUI_BarrierOption](#arkui_barrieroption) \*barrierStyle, [ArkUI_BarrierDirection](#arkui_barrierdirection) value, int32_t index) | Sets the direction of a barrier. | -| void [OH_ArkUI_BarrierOption_SetReferencedId](#oh_arkui_barrieroption_setreferencedid) ([ArkUI_BarrierOption](#arkui_barrieroption) \*barrierStyle, const char \*value, int32_t index) | Sets the referenced components of a barrier. | -| const char \* [OH_ArkUI_BarrierOption_GetId](#oh_arkui_barrieroption_getid) ([ArkUI_BarrierOption](#arkui_barrieroption) \*barrierStyle, int32_t index) | Obtains the ID of a barrier. | -| [ArkUI_BarrierDirection](#arkui_barrierdirection) [OH_ArkUI_BarrierOption_GetDirection](#oh_arkui_barrieroption_getdirection) ([ArkUI_BarrierOption](#arkui_barrieroption) \*barrierStyle, int32_t index) | Obtains the direction of a barrier. | -| const char \* [OH_ArkUI_BarrierOption_GetReferencedId](#oh_arkui_barrieroption_getreferencedid) ([ArkUI_BarrierOption](#arkui_barrieroption) \*barrierStyle, int32_t index, int32_t referencedIndex) | Obtains the referenced components of a barrier. | -| int32_t [OH_ArkUI_BarrierOption_GetReferencedIdSize](#oh_arkui_barrieroption_getreferencedidsize) ([ArkUI_BarrierOption](#arkui_barrieroption) \*barrierStyle, int32_t index) | Obtains the number of referenced components of a barrier. | -| [ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \* [OH_ArkUI_AlignmentRuleOption_Create](#oh_arkui_alignmentruleoption_create) () | Creates an alignment rule configuration for this **RelativeContainer** component. | -| void [OH_ArkUI_AlignmentRuleOption_Dispose](#oh_arkui_alignmentruleoption_dispose) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option) | Disposes of an alignment rule configuration of this **RelativeContainer** component. | -| void [OH_ArkUI_AlignmentRuleOption_SetStart](#oh_arkui_alignmentruleoption_setstart) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option, const char \*id, [ArkUI_HorizontalAlignment](#arkui_horizontalalignment) alignment) | Sets the left alignment parameters. | -| void [OH_ArkUI_AlignmentRuleOption_SetEnd](#oh_arkui_alignmentruleoption_setend) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option, const char \*id, [ArkUI_HorizontalAlignment](#arkui_horizontalalignment) alignment) | Sets the right alignment parameters. | -| void [OH_ArkUI_AlignmentRuleOption_SetCenterHorizontal](#oh_arkui_alignmentruleoption_setcenterhorizontal) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option, const char \*id, [ArkUI_HorizontalAlignment](#arkui_horizontalalignment) alignment) | Sets the horizontal center alignment parameters. | -| void [OH_ArkUI_AlignmentRuleOption_SetTop](#oh_arkui_alignmentruleoption_settop) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option, const char \*id, [ArkUI_VerticalAlignment](#arkui_verticalalignment) alignment) | Sets the top alignment parameters. | -| void [OH_ArkUI_AlignmentRuleOption_SetBottom](#oh_arkui_alignmentruleoption_setbottom) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option, const char \*id, [ArkUI_VerticalAlignment](#arkui_verticalalignment) alignment) | Sets the bottom alignment parameters. | -| void [OH_ArkUI_AlignmentRuleOption_SetCenterVertical](#oh_arkui_alignmentruleoption_setcentervertical) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option, const char \*id, [ArkUI_VerticalAlignment](#arkui_verticalalignment) alignment) | Sets the vertical center alignment parameters. | -| void [OH_ArkUI_AlignmentRuleOption_SetBiasHorizontal](#oh_arkui_alignmentruleoption_setbiashorizontal) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option, float horizontal) | Sets the bias value of the component in the horizontal direction under the anchor constraints. | -| void [OH_ArkUI_AlignmentRuleOption_SetBiasVertical](#oh_arkui_alignmentruleoption_setbiasvertical) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option, float vertical) | Sets the bias value of the component in the vertical direction under the anchor constraints. | -| const char \* [OH_ArkUI_AlignmentRuleOption_GetStartId](#oh_arkui_alignmentruleoption_getstartid) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option) | Obtains the ID in the left alignment parameters. | -| [ArkUI_HorizontalAlignment](#arkui_horizontalalignment) [OH_ArkUI_AlignmentRuleOption_GetStartAlignment](#oh_arkui_alignmentruleoption_getstartalignment) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option) | Obtains the alignment mode in left alignment parameters. | -| const char \* [OH_ArkUI_AlignmentRuleOption_GetEndId](#oh_arkui_alignmentruleoption_getendid) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option) | Obtains the ID in the right alignment parameters. | -| [ArkUI_HorizontalAlignment](#arkui_horizontalalignment) [OH_ArkUI_AlignmentRuleOption_GetEndAlignment](#oh_arkui_alignmentruleoption_getendalignment) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option) | Obtains the ID in the right alignment parameters. | -| const char \* [OH_ArkUI_AlignmentRuleOption_GetCenterIdHorizontal](#oh_arkui_alignmentruleoption_getcenteridhorizontal) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option) | Obtains the ID in horizontal center alignment parameters. | -| [ArkUI_HorizontalAlignment](#arkui_horizontalalignment) [OH_ArkUI_AlignmentRuleOption_GetCenterAlignmentHorizontal](#oh_arkui_alignmentruleoption_getcenteralignmenthorizontal) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option) | Obtains the ID in horizontal center alignment parameters. | -| const char \* [OH_ArkUI_AlignmentRuleOption_GetTopId](#oh_arkui_alignmentruleoption_gettopid) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option) | Obtains the ID in top alignment parameters. | -| [ArkUI_VerticalAlignment](#arkui_verticalalignment) [OH_ArkUI_AlignmentRuleOption_GetTopAlignment](#oh_arkui_alignmentruleoption_gettopalignment) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option) | Obtains the ID in top alignment parameters. | -| const char \* [OH_ArkUI_AlignmentRuleOption_GetBottomId](#oh_arkui_alignmentruleoption_getbottomid) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option) | Obtains the ID in bottom alignment parameters. | -| [ArkUI_VerticalAlignment](#arkui_verticalalignment) [OH_ArkUI_AlignmentRuleOption_GetBottomAlignment](#oh_arkui_alignmentruleoption_getbottomalignment) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option) | Obtains the ID in bottom alignment parameters. | -| const char \* [OH_ArkUI_AlignmentRuleOption_GetCenterIdVertical](#oh_arkui_alignmentruleoption_getcenteridvertical) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option) | Obtains the ID in vertical center alignment parameters. | -| [ArkUI_VerticalAlignment](#arkui_verticalalignment) [OH_ArkUI_AlignmentRuleOption_GetCenterAlignmentVertical](#oh_arkui_alignmentruleoption_getcenteralignmentvertical) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option) | Obtains the ID in vertical center alignment parameters. | -| float [OH_ArkUI_AlignmentRuleOption_GetBiasHorizontal](#oh_arkui_alignmentruleoption_getbiashorizontal) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option) | Obtains the bias value in the horizontal direction. | -| float [OH_ArkUI_AlignmentRuleOption_GetBiasVertical](#oh_arkui_alignmentruleoption_getbiasvertical) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option) | Obtains the bias value in the vertical direction. | -| [ArkUI_SwiperIndicator](#arkui_swiperindicator) \* [OH_ArkUI_SwiperIndicator_Create](#oh_arkui_swiperindicator_create) ([ArkUI_SwiperIndicatorType](#arkui_swiperindicatortype) type) | Creates a navigation point indicator for this **Swiper** component. | -| void [OH_ArkUI_SwiperIndicator_Dispose](#oh_arkui_swiperindicator_dispose) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator) | Disposes of the navigation point indicator of this **Swiper** component. | -| void [OH_ArkUI_SwiperIndicator_SetStartPosition](#oh_arkui_swiperindicator_setstartposition) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator, float value) | Sets the distance between the navigation point indicator and the left edge of the **Swiper** component. | -| float [OH_ArkUI_SwiperIndicator_GetStartPosition](#oh_arkui_swiperindicator_getstartposition) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator) | Obtains the distance between a navigation point indicator and the left edge of the **Swiper** component. | -| void [OH_ArkUI_SwiperIndicator_SetTopPosition](#oh_arkui_swiperindicator_settopposition) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator, float value) | Sets the distance between the navigation point indicator and the top edge of the **Swiper** component. | -| float [OH_ArkUI_SwiperIndicator_GetTopPosition](#oh_arkui_swiperindicator_gettopposition) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator) | Obtains the distance between the navigation point indicator and the top edge of the **Swiper** component. | -| void [OH_ArkUI_SwiperIndicator_SetEndPosition](#oh_arkui_swiperindicator_setendposition) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator, float value) | Sets the distance between the navigation point indicator and the right edge of the **Swiper** component. | -| float [OH_ArkUI_SwiperIndicator_GetEndPosition](#oh_arkui_swiperindicator_getendposition) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator) | Obtains the distance between the navigation point indicator and the right edge of the **Swiper** component. | -| void [OH_ArkUI_SwiperIndicator_SetBottomPosition](#oh_arkui_swiperindicator_setbottomposition) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator, float value) | Sets the distance between the navigation point indicator and the bottom edge of the **Swiper** component. | -| float [OH_ArkUI_SwiperIndicator_GetBottomPosition](#oh_arkui_swiperindicator_getbottomposition) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator) | Obtains the distance between the navigation point indicator and the bottom edge of the **Swiper** component. | -| void [OH_ArkUI_SwiperIndicator_SetItemWidth](#oh_arkui_swiperindicator_setitemwidth) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator, float value) | Sets the width of a navigation point indicator of the dot style for the **Swiper** component. | -| float [OH_ArkUI_SwiperIndicator_GetItemWidth](#oh_arkui_swiperindicator_getitemwidth) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator) | Obtains the width of a navigation point indicator of the dot style of the **Swiper** component. | -| void [OH_ArkUI_SwiperIndicator_SetItemHeight](#oh_arkui_swiperindicator_setitemheight) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator, float value) | Sets the height of a navigation point indicator of the dot style for the **Swiper** component. | -| float [OH_ArkUI_SwiperIndicator_GetItemHeight](#oh_arkui_swiperindicator_getitemheight) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator) | Obtains the height of a navigation point indicator of the dot style of the **Swiper** component. | -| void [OH_ArkUI_SwiperIndicator_SetSelectedItemWidth](#oh_arkui_swiperindicator_setselecteditemwidth) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator, float value) | Sets the width of the selected navigation point indicator of the dot style for the **Swiper** component. | -| float [OH_ArkUI_SwiperIndicator_GetSelectedItemWidth](#oh_arkui_swiperindicator_getselecteditemwidth) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator) | Obtains the width of the selected navigation point indicator of the dot style of the **Swiper** component. | -| void [OH_ArkUI_SwiperIndicator_SetSelectedItemHeight](#oh_arkui_swiperindicator_setselecteditemheight) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator, float value) | Sets the height of the selected navigation point indicator of the dot style for the **Swiper** component. | -| float [OH_ArkUI_SwiperIndicator_GetSelectedItemHeight](#oh_arkui_swiperindicator_getselecteditemheight) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator) | Obtains the height of the selected navigation point indicator of the dot style of the **Swiper** component. | -| void [OH_ArkUI_SwiperIndicator_SetMask](#oh_arkui_swiperindicator_setmask) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator, int32_t mask) | Sets whether to enable the mask for a navigation point indicator of the dot style for the **Swiper** component. | -| int32_t [OH_ArkUI_SwiperIndicator_GetMask](#oh_arkui_swiperindicator_getmask) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator) | Obtains whether the mask is enabled for a navigation point indicator of the dot style of the **Swiper** component. | -| void [OH_ArkUI_SwiperIndicator_SetColor](#oh_arkui_swiperindicator_setcolor) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator, uint32_t color) | Sets the color of a navigation point indicator of the dot style for the **Swiper** component. | -| uint32_t [OH_ArkUI_SwiperIndicator_GetColor](#oh_arkui_swiperindicator_getcolor) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator) | Obtains the color of a navigation point indicator of the dot style of the **Swiper** component. | -| void [OH_ArkUI_SwiperIndicator_SetSelectedColor](#oh_arkui_swiperindicator_setselectedcolor) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator, uint32_t selectedColor) | Sets the color of the selected navigation point indicator of the dot style for the **Swiper** component. | -| uint32_t [OH_ArkUI_SwiperIndicator_GetSelectedColor](#oh_arkui_swiperindicator_getselectedcolor) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator) | Obtains the color of the selected navigation point indicator of the dot style of the **Swiper** component. | -| int32_t [OH_ArkUI_SwiperIndicator_SetMaxDisplayCount](#oh_arkui_swiperindicator_setmaxdisplaycount) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator, int32_t maxDisplayCount) | Sets the maximum number of dots for the navigation point indicator of the dot style. | -| int32_t [OH_ArkUI_SwiperIndicator_GetMaxDisplayCount](#oh_arkui_swiperindicator_getmaxdisplaycount) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator) | Obtains the maximum number of points for the navigation point indicator. | -| [ArkUI_ListItemSwipeActionItem](#arkui_listitemswipeactionitem) \* [OH_ArkUI_ListItemSwipeActionItem_Create](#oh_arkui_listitemswipeactionitem_create) () | Creates a **ListItemSwipeActionItem** instance. | -| void [OH_ArkUI_ListItemSwipeActionItem_Dispose](#oh_arkui_listitemswipeactionitem_dispose) ([ArkUI_ListItemSwipeActionItem](#arkui_listitemswipeactionitem) \*item) | Disposes of a **ListItemSwipeActionItem** instance. | -| void [OH_ArkUI_ListItemSwipeActionItem_SetContent](#oh_arkui_listitemswipeactionitem_setcontent) ([ArkUI_ListItemSwipeActionItem](#arkui_listitemswipeactionitem) \*item, [ArkUI_NodeHandle](#arkui_nodehandle) node) | Sets the layout content for a **ListItemSwipeActionItem** instance. | -| void [OH_ArkUI_ListItemSwipeActionItem_SetActionAreaDistance](#oh_arkui_listitemswipeactionitem_setactionareadistance) ([ArkUI_ListItemSwipeActionItem](#arkui_listitemswipeactionitem) \*item, float distance) | Sets the swipe distance threshold for deleting the list item. | -| float [OH_ArkUI_ListItemSwipeActionItem_GetActionAreaDistance](#oh_arkui_listitemswipeactionitem_getactionareadistance) ([ArkUI_ListItemSwipeActionItem](#arkui_listitemswipeactionitem) \*item) | Obtains the swipe distance threshold for deleting the list item. | -| void [OH_ArkUI_ListItemSwipeActionItem_SetOnEnterActionArea](#oh_arkui_listitemswipeactionitem_setonenteractionarea) ([ArkUI_ListItemSwipeActionItem](#arkui_listitemswipeactionitem) \*item, void(\*callback)()) | Sets the callback invoked each time the list item enters the delete area. | -| void [OH_ArkUI_ListItemSwipeActionItem_SetOnEnterActionAreaWithUserData](#oh_arkui_listitemswipeactionitem_setonenteractionareawithuserdata) ([ArkUI_ListItemSwipeActionItem](#arkui_listitemswipeactionitem) \*item, void \*userData, void(\*callback)(void \*userData)) | Sets the callback invoked each time the list item enters the delete area. | -| void [OH_ArkUI_ListItemSwipeActionItem_SetOnAction](#oh_arkui_listitemswipeactionitem_setonaction) ([ArkUI_ListItemSwipeActionItem](#arkui_listitemswipeactionitem) \*item, void(\*callback)()) | Sets the callback invoked when the list item is deleted while in the delete area. | -| void [OH_ArkUI_ListItemSwipeActionItem_SetOnActionWithUserData](#oh_arkui_listitemswipeactionitem_setonactionwithuserdata) ([ArkUI_ListItemSwipeActionItem](#arkui_listitemswipeactionitem) \*item, void \*userData, void(\*callback)(void \*userData)) | Sets the callback invoked when the list item is deleted while in the delete area. | -| void [OH_ArkUI_ListItemSwipeActionItem_SetOnExitActionArea](#oh_arkui_listitemswipeactionitem_setonexitactionarea) ([ArkUI_ListItemSwipeActionItem](#arkui_listitemswipeactionitem) \*item, void(\*callback)()) | Sets the callback invoked each time the list item exits the delete area. | -| void [OH_ArkUI_ListItemSwipeActionItem_SetOnExitActionAreaWithUserData](#oh_arkui_listitemswipeactionitem_setonexitactionareawithuserdata) ([ArkUI_ListItemSwipeActionItem](#arkui_listitemswipeactionitem) \*item, void \*userData, void(\*callback)(void \*userData)) | Sets the callback invoked each time the list item exits the delete area. | -| void [OH_ArkUI_ListItemSwipeActionItem_SetOnStateChange](#oh_arkui_listitemswipeactionitem_setonstatechange) ([ArkUI_ListItemSwipeActionItem](#arkui_listitemswipeactionitem) \*item, void(\*callback)([ArkUI_ListItemSwipeActionState](#arkui_listitemswipeactionstate) swipeActionState)) | Sets the callback invoked when the swipe state of the list item changes. | -| void [OH_ArkUI_ListItemSwipeActionItem_SetOnStateChangeWithUserData](#oh_arkui_listitemswipeactionitem_setonstatechangewithuserdata) ([ArkUI_ListItemSwipeActionItem](#arkui_listitemswipeactionitem) \*item, void \*userData, void(\*callback)([ArkUI_ListItemSwipeActionState](#arkui_listitemswipeactionstate) swipeActionState, void \*userData)) | Sets the callback invoked when the swipe state of the list item changes. | -| [ArkUI_ListItemSwipeActionOption](#arkui_listitemswipeactionoption) \* [OH_ArkUI_ListItemSwipeActionOption_Create](#oh_arkui_listitemswipeactionoption_create) () | Creates a **ListItemSwipeActionOption** instance. | -| void [OH_ArkUI_ListItemSwipeActionOption_Dispose](#oh_arkui_listitemswipeactionoption_dispose) ([ArkUI_ListItemSwipeActionOption](#arkui_listitemswipeactionoption) \*option) | Disposes of a **ListItemSwipeActionOption** instance. | -| void [OH_ArkUI_ListItemSwipeActionOption_SetStart](#oh_arkui_listitemswipeactionoption_setstart) ([ArkUI_ListItemSwipeActionOption](#arkui_listitemswipeactionoption) \*option, [ArkUI_ListItemSwipeActionItem](#arkui_listitemswipeactionitem) \*item) | Sets the layout content for the left edge (for a vertical layout) or top edge (for a horizontal layout) of a **ListItemSwipeActionOption** instance. | -| void [OH_ArkUI_ListItemSwipeActionOption_SetEnd](#oh_arkui_listitemswipeactionoption_setend) ([ArkUI_ListItemSwipeActionOption](#arkui_listitemswipeactionoption) \*option, [ArkUI_ListItemSwipeActionItem](#arkui_listitemswipeactionitem) \*item) | Sets the layout content for the right edge (for a vertical layout) or bottom edge (for a horizontal layout) of a **ListItemSwipeActionItem** instance. | -| void [OH_ArkUI_ListItemSwipeActionOption_SetEdgeEffect](#oh_arkui_listitemswipeactionoption_setedgeeffect) ([ArkUI_ListItemSwipeActionOption](#arkui_listitemswipeactionoption) \*option, [ArkUI_ListItemSwipeEdgeEffect](#arkui_listitemswipeedgeeffect) edgeEffect) | Sets the edge effect used when the boundary of the scrolling area is reached. | -| int32_t [OH_ArkUI_ListItemSwipeActionOption_GetEdgeEffect](#oh_arkui_listitemswipeactionoption_getedgeeffect) ([ArkUI_ListItemSwipeActionOption](#arkui_listitemswipeactionoption) \*option) | Obtains the edge effect used when the boundary of the scrolling area is reached. | -| void [OH_ArkUI_ListItemSwipeActionOption_SetOnOffsetChange](#oh_arkui_listitemswipeactionoption_setonoffsetchange) ([ArkUI_ListItemSwipeActionOption](#arkui_listitemswipeactionoption) \*option, void(\*callback)(float offset)) | Sets the callback invoked when the scroll offset changes. | -| void [OH_ArkUI_ListItemSwipeActionOption_SetOnOffsetChangeWithUserData](#oh_arkui_listitemswipeactionoption_setonoffsetchangewithuserdata) ([ArkUI_ListItemSwipeActionOption](#arkui_listitemswipeactionoption) \*option, void \*userData, void(\*callback)(float offset, void \*userData)) | Sets the callback invoked when the scroll offset changes. | -| [ArkUI_AccessibilityState](#arkui_accessibilitystate) \* [OH_ArkUI_AccessibilityState_Create](#oh_arkui_accessibilitystate_create) (void) | Creates an accessibility state. | -| void [OH_ArkUI_AccessibilityState_Dispose](#oh_arkui_accessibilitystate_dispose) ([ArkUI_AccessibilityState](#arkui_accessibilitystate) \*state) | Disposes of the pointer to an accessibility state. | -| void [OH_ArkUI_AccessibilityState_SetDisabled](#oh_arkui_accessibilitystate_setdisabled) ([ArkUI_AccessibilityState](#arkui_accessibilitystate) \*state, int32_t isDisabled) | Sets whether an accessibility state is disabled. | -| int32_t [OH_ArkUI_AccessibilityState_IsDisabled](#oh_arkui_accessibilitystate_isdisabled) ([ArkUI_AccessibilityState](#arkui_accessibilitystate) \*state) | Obtains whether an accessibility state is disabled. | -| void [OH_ArkUI_AccessibilityState_SetSelected](#oh_arkui_accessibilitystate_setselected) ([ArkUI_AccessibilityState](#arkui_accessibilitystate) \*state, int32_t isSelected) | Sets whether an accessibility state is selected. | -| int32_t [OH_ArkUI_AccessibilityState_IsSelected](#oh_arkui_accessibilitystate_isselected) ([ArkUI_AccessibilityState](#arkui_accessibilitystate) \*state) | Obtains whether an accessibility state is selected. | -| void [OH_ArkUI_AccessibilityState_SetCheckedState](#oh_arkui_accessibilitystate_setcheckedstate) ([ArkUI_AccessibilityState](#arkui_accessibilitystate) \*state, int32_t checkedState) | Sets the check box state of an accessibility state. | -| int32_t [OH_ArkUI_AccessibilityState_GetCheckedState](#oh_arkui_accessibilitystate_getcheckedstate) ([ArkUI_AccessibilityState](#arkui_accessibilitystate) \*state) | Obtains the check box state of an accessibility state. | -| [ArkUI_AccessibilityValue](#arkui_accessibilityvalue) \* [OH_ArkUI_AccessibilityValue_Create](#oh_arkui_accessibilityvalue_create) (void) | Creates an **AccessibilityValue** instance. | -| void [OH_ArkUI_AccessibilityValue_Dispose](#oh_arkui_accessibilityvalue_dispose) ([ArkUI_AccessibilityValue](#arkui_accessibilityvalue) \*value) | Disposes of the pointer to an **AccessibilityValue** instance. | -| void [OH_ArkUI_AccessibilityValue_SetMin](#oh_arkui_accessibilityvalue_setmin) ([ArkUI_AccessibilityValue](#arkui_accessibilityvalue) \*value, int32_t min) | Sets the minimum accessibility value. | -| int32_t [OH_ArkUI_AccessibilityValue_GetMin](#oh_arkui_accessibilityvalue_getmin) ([ArkUI_AccessibilityValue](#arkui_accessibilityvalue) \*value) | Obtains the minimum accessibility value. | -| void [OH_ArkUI_AccessibilityValue_SetMax](#oh_arkui_accessibilityvalue_setmax) ([ArkUI_AccessibilityValue](#arkui_accessibilityvalue) \*value, int32_t max) | Sets the maximum accessibility value. | -| int32_t [OH_ArkUI_AccessibilityValue_GetMax](#oh_arkui_accessibilityvalue_getmax) ([ArkUI_AccessibilityValue](#arkui_accessibilityvalue) \*value) | Obtains the maximum accessibility value. | -| void [OH_ArkUI_AccessibilityValue_SetCurrent](#oh_arkui_accessibilityvalue_setcurrent) ([ArkUI_AccessibilityValue](#arkui_accessibilityvalue) \*value, int32_t current) | Sets the current accessibility value. | -| int32_t [OH_ArkUI_AccessibilityValue_GetCurrent](#oh_arkui_accessibilityvalue_getcurrent) ([ArkUI_AccessibilityValue](#arkui_accessibilityvalue) \*value) | Obtains the current accessibility value. | -| void [OH_ArkUI_AccessibilityValue_SetText](#oh_arkui_accessibilityvalue_settext) ([ArkUI_AccessibilityValue](#arkui_accessibilityvalue) \*value, const char \*text) | Sets the text description of an **AccessibilityValue** instance. | -| const char \* [OH_ArkUI_AccessibilityValue_GetText](#oh_arkui_accessibilityvalue_gettext) ([ArkUI_AccessibilityValue](#arkui_accessibilityvalue) \*value) | Obtains the text description of an **AccessibilityValue** instance. | -| [ArkUI_ImageAnimatorFrameInfo](#arkui_imageanimatorframeinfo) \* [OH_ArkUI_ImageAnimatorFrameInfo_CreateFromString](#oh_arkui_imageanimatorframeinfo_createfromstring) (char \*src) | Creates an image frame information object based on an image path, with the image format being SVG, PNG, or JPG. | -| [ArkUI_ImageAnimatorFrameInfo](#arkui_imageanimatorframeinfo) \* [OH_ArkUI_ImageAnimatorFrameInfo_CreateFromDrawableDescriptor](#oh_arkui_imageanimatorframeinfo_createfromdrawabledescriptor) ([ArkUI_DrawableDescriptor](#arkui_drawabledescriptor) \*drawable) | Creates an image frame information object based on a **DrawableDescriptor** object, with the image format being Resource or PixelMap. | -| void [OH_ArkUI_ImageAnimatorFrameInfo_Dispose](#oh_arkui_imageanimatorframeinfo_dispose) ([ArkUI_ImageAnimatorFrameInfo](#arkui_imageanimatorframeinfo) \*imageInfo) | Disposes of the pointer to an image frame information object. | -| void [OH_ArkUI_ImageAnimatorFrameInfo_SetWidth](#oh_arkui_imageanimatorframeinfo_setwidth) ([ArkUI_ImageAnimatorFrameInfo](#arkui_imageanimatorframeinfo) \*imageInfo, int32_t width) | Sets the image width. | -| int32_t [OH_ArkUI_ImageAnimatorFrameInfo_GetWidth](#oh_arkui_imageanimatorframeinfo_getwidth) ([ArkUI_ImageAnimatorFrameInfo](#arkui_imageanimatorframeinfo) \*imageInfo) | Obtains the image width. | -| void [OH_ArkUI_ImageAnimatorFrameInfo_SetHeight](#oh_arkui_imageanimatorframeinfo_setheight) ([ArkUI_ImageAnimatorFrameInfo](#arkui_imageanimatorframeinfo) \*imageInfo, int32_t height) | Sets the image height. | -| int32_t [OH_ArkUI_ImageAnimatorFrameInfo_GetHeight](#oh_arkui_imageanimatorframeinfo_getheight) ([ArkUI_ImageAnimatorFrameInfo](#arkui_imageanimatorframeinfo) \*imageInfo) | Obtains the image height. | -| void [OH_ArkUI_ImageAnimatorFrameInfo_SetTop](#oh_arkui_imageanimatorframeinfo_settop) ([ArkUI_ImageAnimatorFrameInfo](#arkui_imageanimatorframeinfo) \*imageInfo, int32_t top) | Sets the vertical coordinate of an image relative to the upper left corner of the component. | -| int32_t [OH_ArkUI_ImageAnimatorFrameInfo_GetTop](#oh_arkui_imageanimatorframeinfo_gettop) ([ArkUI_ImageAnimatorFrameInfo](#arkui_imageanimatorframeinfo) \*imageInfo) | Obtains the vertical coordinate of an image relative to the upper left corner of the component. | -| void [OH_ArkUI_ImageAnimatorFrameInfo_SetLeft](#oh_arkui_imageanimatorframeinfo_setleft) ([ArkUI_ImageAnimatorFrameInfo](#arkui_imageanimatorframeinfo) \*imageInfo, int32_t left) | Sets the horizontal coordinate of an image relative to the upper left corner of the component. | -| int32_t [OH_ArkUI_ImageAnimatorFrameInfo_GetLeft](#oh_arkui_imageanimatorframeinfo_getleft) ([ArkUI_ImageAnimatorFrameInfo](#arkui_imageanimatorframeinfo) \*imageInfo) | Obtains the horizontal coordinate of an image relative to the upper left corner of the component. | -| void [OH_ArkUI_ImageAnimatorFrameInfo_SetDuration](#oh_arkui_imageanimatorframeinfo_setduration) ([ArkUI_ImageAnimatorFrameInfo](#arkui_imageanimatorframeinfo) \*imageInfo, int32_t duration) | Sets the playback duration of an image. | -| int32_t [OH_ArkUI_ImageAnimatorFrameInfo_GetDuration](#oh_arkui_imageanimatorframeinfo_getduration) ([ArkUI_ImageAnimatorFrameInfo](#arkui_imageanimatorframeinfo) \*imageInfo) | Obtains the playback duration of an image. | -| [ArkUI_ListChildrenMainSize](#arkui_listchildrenmainsize) \* [OH_ArkUI_ListChildrenMainSizeOption_Create](#oh_arkui_listchildrenmainsizeoption_create) () | Creates a **ListChildrenMainSize** instance. | -| void [OH_ArkUI_ListChildrenMainSizeOption_Dispose](#oh_arkui_listchildrenmainsizeoption_dispose) ([ArkUI_ListChildrenMainSize](#arkui_listchildrenmainsize) \*option) | Disposes of a **ListChildrenMainSize** instance. | -| int32_t [OH_ArkUI_ListChildrenMainSizeOption_SetDefaultMainSize](#oh_arkui_listchildrenmainsizeoption_setdefaultmainsize) ([ArkUI_ListChildrenMainSize](#arkui_listchildrenmainsize) \*option, float defaultMainSize) | Sets the default size in a **ListChildrenMainSize** instance. | -| float [OH_ArkUI_ListChildrenMainSizeOption_GetDefaultMainSize](#oh_arkui_listchildrenmainsizeoption_getdefaultmainsize) ([ArkUI_ListChildrenMainSize](#arkui_listchildrenmainsize) \*option) | Obtains the default size in a **ListChildrenMainSize** instance. | -| void [OH_ArkUI_ListChildrenMainSizeOption_Resize](#oh_arkui_listchildrenmainsizeoption_resize) ([ArkUI_ListChildrenMainSize](#arkui_listchildrenmainsize) \*option, int32_t totalSize) | Resets the array size in a **ListChildrenMainSize** instance. | -| int32_t [OH_ArkUI_ListChildrenMainSizeOption_Splice](#oh_arkui_listchildrenmainsizeoption_splice) ([ArkUI_ListChildrenMainSize](#arkui_listchildrenmainsize) \*option, int32_t index, int32_t deleteCount, int32_t addCount) | Changes the content of a **ChildrenMainSizeOption** array. | -| int32_t [OH_ArkUI_ListChildrenMainSizeOption_UpdateSize](#oh_arkui_listchildrenmainsizeoption_updatesize) ([ArkUI_ListChildrenMainSize](#arkui_listchildrenmainsize) \*option, int32_t index, float mainSize) | Updates the values of a **ChildrenMainSizeOption** array. | -| float [OH_ArkUI_ListChildrenMainSizeOption_GetMainSize](#oh_arkui_listchildrenmainsizeoption_getmainsize) ([ArkUI_ListChildrenMainSize](#arkui_listchildrenmainsize) \*option, int32_t index) | Obtains the values of a **ChildrenMainSizeOption** array. | -| [ArkUI_CustomSpanMeasureInfo](#arkui_customspanmeasureinfo) \* [OH_ArkUI_CustomSpanMeasureInfo_Create](#oh_arkui_customspanmeasureinfo_create) (void) | Creates measurement information for this custom span. | -| void [OH_ArkUI_CustomSpanMeasureInfo_Dispose](#oh_arkui_customspanmeasureinfo_dispose) ([ArkUI_CustomSpanMeasureInfo](#arkui_customspanmeasureinfo) \*info) | Disposes of measurement information of a custom span. | -| float [OH_ArkUI_CustomSpanMeasureInfo_GetFontSize](#oh_arkui_customspanmeasureinfo_getfontsize) ([ArkUI_CustomSpanMeasureInfo](#arkui_customspanmeasureinfo) \*info) | Obtains the font size of the parent text node of a custom span. | -| [ArkUI_CustomSpanMetrics](#arkui_customspanmetrics) \* [OH_ArkUI_CustomSpanMetrics_Create](#oh_arkui_customspanmetrics_create) (void) | Creates measurement metrics for this custom span. | -| void [OH_ArkUI_CustomSpanMetrics_Dispose](#oh_arkui_customspanmetrics_dispose) ([ArkUI_CustomSpanMetrics](#arkui_customspanmetrics) \*metrics) | Disposes of measurement metrics of this custom span. | -| int32_t [OH_ArkUI_CustomSpanMetrics_SetWidth](#oh_arkui_customspanmetrics_setwidth) ([ArkUI_CustomSpanMetrics](#arkui_customspanmetrics) \*metrics, float width) | Sets the width for a custom span. | -| int32_t [OH_ArkUI_CustomSpanMetrics_SetHeight](#oh_arkui_customspanmetrics_setheight) ([ArkUI_CustomSpanMetrics](#arkui_customspanmetrics) \*metrics, float height) | Sets the height for a custom span. | -| [ArkUI_CustomSpanDrawInfo](#arkui_customspandrawinfo) \* [OH_ArkUI_CustomSpanDrawInfo_Create](#oh_arkui_customspandrawinfo_create) (void) | Creates drawing information for this custom span. | -| void [OH_ArkUI_CustomSpanDrawInfo_Dispose](#oh_arkui_customspandrawinfo_dispose) ([ArkUI_CustomSpanDrawInfo](#arkui_customspandrawinfo) \*info) | Disposes of drawing information for this custom span. | -| float [OH_ArkUI_CustomSpanDrawInfo_GetXOffset](#oh_arkui_customspandrawinfo_getxoffset) ([ArkUI_CustomSpanDrawInfo](#arkui_customspandrawinfo) \*info) | Obtains the x-axis offset of the custom span relative to the mounted component. | -| float [OH_ArkUI_CustomSpanDrawInfo_GetLineTop](#oh_arkui_customspandrawinfo_getlinetop) ([ArkUI_CustomSpanDrawInfo](#arkui_customspandrawinfo) \*info) | Obtains the top margin of the custom span relative to the mounted component. | -| float [OH_ArkUI_CustomSpanDrawInfo_GetLineBottom](#oh_arkui_customspandrawinfo_getlinebottom) ([ArkUI_CustomSpanDrawInfo](#arkui_customspandrawinfo) \*info) | Obtains the bottom margin of the custom span relative to the mounted component. | -| float [OH_ArkUI_CustomSpanDrawInfo_GetBaseline](#oh_arkui_customspandrawinfo_getbaseline) ([ArkUI_CustomSpanDrawInfo](#arkui_customspandrawinfo) \*info) | Obtains the baseline offset of the custom span relative to the mounted component. | +| int32_t [OH_ArkUI_List_CloseAllSwipeActions](#oh_arkui_list_closeallswipeactions) ([ArkUI_NodeHandle](#arkui_nodehandle) node, void \*userData, void(\*onFinish)(void \*userData)) | Collapses the list items in the expanded state. | +| [ArkUI_ContextHandle](#arkui_contexthandle-12) [OH_ArkUI_GetContextByNode](#oh_arkui_getcontextbynode) ([ArkUI_NodeHandle](#arkui_nodehandle) node) | Obtains the pointer to the UI context object of the specified node. | +| int32_t [OH_ArkUI_RegisterSystemColorModeChangeEvent](#oh_arkui_registersystemcolormodechangeevent) ([ArkUI_NodeHandle](#arkui_nodehandle) node, void \*userData, void(\*onColorModeChange)([ArkUI_SystemColorMode](#arkui_systemcolormode) colorMode, void \*userData)) | Registers an event listener for system color mode changes. A single component can only register one callback for system color mode changes. | +| void [OH_ArkUI_UnregisterSystemColorModeChangeEvent](#oh_arkui_unregistersystemcolormodechangeevent) ([ArkUI_NodeHandle](#arkui_nodehandle) node) | Unregisters the event listener for system color mode changes. | +| int32_t [OH_ArkUI_RegisterSystemFontStyleChangeEvent](#oh_arkui_registersystemfontstylechangeevent) ([ArkUI_NodeHandle](#arkui_nodehandle) node, void \*userData, void(\*onFontStyleChange)([ArkUI_SystemFontStyleEvent](#arkui_systemfontstyleevent) \*event, void \*userData)) | Registers an event listener for system font style changes. A single component can only register one callback for system font style changes. | +| void [OH_ArkUI_UnregisterSystemFontStyleChangeEvent](#oh_arkui_unregistersystemfontstylechangeevent) ([ArkUI_NodeHandle](#arkui_nodehandle) node) | Unregisters the event listener for system font style changes. | +| float [OH_ArkUI_SystemFontStyleEvent_GetFontSizeScale](#oh_arkui_systemfontstyleevent_getfontsizescale) (const [ArkUI_SystemFontStyleEvent](#arkui_systemfontstyleevent) \*event) | Obtains the font size from the system font style change event. | +| float [OH_ArkUI_SystemFontStyleEvent_GetFontWeightScale](#oh_arkui_systemfontstyleevent_getfontweightscale) (const [ArkUI_SystemFontStyleEvent](#arkui_systemfontstyleevent) \*event) | Obtains the font weight from the system font style change event. | +| int32_t [OH_ArkUI_GetNodeHandleFromNapiValue](#oh_arkui_getnodehandlefromnapivalue) (napi_env env, napi_value frameNode, [ArkUI_NodeHandle](#arkui_nodehandle) \*handle) | Obtains a **FrameNode** object on the ArkTS side and maps it to an **ArkUI_NodeHandle** object on the native side. | +| int32_t [OH_ArkUI_GetContextFromNapiValue](#oh_arkui_getcontextfromnapivalue) (napi_env env, napi_value value, [ArkUI_ContextHandle](#arkui_contexthandle-12) \*context) | Obtains a **UIContext** object on the ArkTS side and maps it to an **ArkUI_ContextHandle** object on the native side. | +| int32_t [OH_ArkUI_GetNodeContentFromNapiValue](#oh_arkui_getnodecontentfromnapivalue) (napi_env env, napi_value value, [ArkUI_NodeContentHandle](#arkui_nodecontenthandle) \*content) | Obtains a **NodeContent** object on the ArkTS side and maps it to an **ArkUI_NodeContentHandle** object on the native side. | +| int32_t [OH_ArkUI_GetDrawableDescriptorFromNapiValue](#oh_arkui_getdrawabledescriptorfromnapivalue) (napi_env env, napi_value value, [ArkUI_DrawableDescriptor](#arkui_drawabledescriptor) \*\*drawableDescriptor) | Maps a **DrawableDescriptor** object on the ArkTS side to an **ArkUI_DrawableDescriptor** object on the native side. | +| int32_t [OH_ArkUI_GetDrawableDescriptorFromResourceNapiValue](#oh_arkui_getdrawabledescriptorfromresourcenapivalue) (napi_env env, napi_value value, [ArkUI_DrawableDescriptor](#arkui_drawabledescriptor) \*\*drawableDescriptor) | Maps an $r resource object on the ArkTS side to an **ArkUI_DrawableDescriptor** object on the native side. | +| [ArkUI_ErrorCode](#arkui_errorcode) [OH_ArkUI_GetNavigationId](#oh_arkui_getnavigationid) ([ArkUI_NodeHandle](#arkui_nodehandle) node, char \*buffer, int32_t bufferSize, int32_t \*writeLength) | Obtains the ID of the **Navigation** component where the specified node is located. | +| [ArkUI_ErrorCode](#arkui_errorcode) [OH_ArkUI_GetNavDestinationName](#oh_arkui_getnavdestinationname) ([ArkUI_NodeHandle](#arkui_nodehandle) node, char \*buffer, int32_t bufferSize, int32_t \*writeLength) | Obtains the name of the **NavDestination** component where the specified node is located. | +| [ArkUI_ErrorCode](#arkui_errorcode) [OH_ArkUI_GetNavStackLength](#oh_arkui_getnavstacklength) ([ArkUI_NodeHandle](#arkui_nodehandle) node, int32_t \*length) | Obtains the length of the navigation stack where the specified node is located. | +| [ArkUI_ErrorCode](#arkui_errorcode) [OH_ArkUI_GetNavDestinationNameByIndex](#oh_arkui_getnavdestinationnamebyindex) ([ArkUI_NodeHandle](#arkui_nodehandle) node, int32_t index, char \*buffer, int32_t bufferSize, int32_t \*writeLength) | Obtains the page name that matches the specified index in the navigation stack where the specified node is located. The index starts from 0, which indicates the bottom of the stack. | +| [ArkUI_ErrorCode](#arkui_errorcode) [OH_ArkUI_GetNavDestinationId](#oh_arkui_getnavdestinationid) ([ArkUI_NodeHandle](#arkui_nodehandle) node, char \*buffer, int32_t bufferSize, int32_t \*writeLength) | Obtains the ID of the **NavDestination** component where the specified node is located. | +| [ArkUI_ErrorCode](#arkui_errorcode) [OH_ArkUI_GetNavDestinationState](#oh_arkui_getnavdestinationstate) ([ArkUI_NodeHandle](#arkui_nodehandle) node, [ArkUI_NavDestinationState](#arkui_navdestinationstate) \*state) | Obtains the state of the **NavDestination** component where the specified node is located. | +| [ArkUI_ErrorCode](#arkui_errorcode) [OH_ArkUI_GetNavDestinationIndex](#oh_arkui_getnavdestinationindex) ([ArkUI_NodeHandle](#arkui_nodehandle) node, int32_t \*index) | Obtains the index of the **NavDestination** component where the specified node is located in the navigation stack. | +| napi_value [OH_ArkUI_GetNavDestinationParam](#oh_arkui_getnavdestinationparam) ([ArkUI_NodeHandle](#arkui_nodehandle) node) | Obtains the parameters of the **NavDestination** component where the specified node is located. | +| [ArkUI_ErrorCode](#arkui_errorcode) [OH_ArkUI_GetRouterPageIndex](#oh_arkui_getrouterpageindex) ([ArkUI_NodeHandle](#arkui_nodehandle) node, int32_t \*index) | Obtains the index of the page where the specified node is located in the page stack for routing. | +| [ArkUI_ErrorCode](#arkui_errorcode) [OH_ArkUI_GetRouterPageName](#oh_arkui_getrouterpagename) ([ArkUI_NodeHandle](#arkui_nodehandle) node, char \*buffer, int32_t bufferSize, int32_t \*writeLength) | Obtains the name of the page where the specified node is located. | +| [ArkUI_ErrorCode](#arkui_errorcode) [OH_ArkUI_GetRouterPagePath](#oh_arkui_getrouterpagepath) ([ArkUI_NodeHandle](#arkui_nodehandle) node, char \*buffer, int32_t bufferSize, int32_t \*writeLength) | Obtains the path to the page where the specified node is located. | +| [ArkUI_ErrorCode](#arkui_errorcode) [OH_ArkUI_GetRouterPageState](#oh_arkui_getrouterpagestate) ([ArkUI_NodeHandle](#arkui_nodehandle) node, [ArkUI_RouterPageState](#arkui_routerpagestate) \*state) | Obtains the state of the page where the specified node is located. | +| [ArkUI_ErrorCode](#arkui_errorcode) [OH_ArkUI_GetRouterPageId](#oh_arkui_getrouterpageid) ([ArkUI_NodeHandle](#arkui_nodehandle) node, char \*buffer, int32_t bufferSize, int32_t \*writeLength) | Obtains the ID of the page where the specified node is located. | +| [ArkUI_LayoutConstraint](#arkui_layoutconstraint) \* [OH_ArkUI_LayoutConstraint_Create](#oh_arkui_layoutconstraint_create) () | Creates a size constraint. | +| [ArkUI_LayoutConstraint](#arkui_layoutconstraint) \* [OH_ArkUI_LayoutConstraint_Copy](#oh_arkui_layoutconstraint_copy) (const [ArkUI_LayoutConstraint](#arkui_layoutconstraint) \*Constraint) | Performs a deep copy of a size constraint. | +| void \* [OH_ArkUI_LayoutConstraint_Dispose](#oh_arkui_layoutconstraint_dispose) ([ArkUI_LayoutConstraint](#arkui_layoutconstraint) \*Constraint) | Disposes of the pointer to a size constraint. | +| int32_t [OH_ArkUI_LayoutConstraint_GetMaxWidth](#oh_arkui_layoutconstraint_getmaxwidth) (const [ArkUI_LayoutConstraint](#arkui_layoutconstraint) \*Constraint) | Obtains the maximum width for a size constraint, in px. | +| int32_t [OH_ArkUI_LayoutConstraint_GetMinWidth](#oh_arkui_layoutconstraint_getminwidth) (const [ArkUI_LayoutConstraint](#arkui_layoutconstraint) \*Constraint) | Obtains the minimum width for a size constraint, in px. | +| int32_t [OH_ArkUI_LayoutConstraint_GetMaxHeight](#oh_arkui_layoutconstraint_getmaxheight) (const [ArkUI_LayoutConstraint](#arkui_layoutconstraint) \*Constraint) | Obtains the maximum height for a size constraint, in px. | +| int32_t [OH_ArkUI_LayoutConstraint_GetMinHeight](#oh_arkui_layoutconstraint_getminheight) (const [ArkUI_LayoutConstraint](#arkui_layoutconstraint) \*Constraint) | Obtains the minimum height for a size constraint, in px. | +| int32_t [OH_ArkUI_LayoutConstraint_GetPercentReferenceWidth](#oh_arkui_layoutconstraint_getpercentreferencewidth) (const [ArkUI_LayoutConstraint](#arkui_layoutconstraint) \*Constraint) | Obtains the width percentage reference for a size constraint, in px. | +| int32_t [OH_ArkUI_LayoutConstraint_GetPercentReferenceHeight](#oh_arkui_layoutconstraint_getpercentreferenceheight) (const [ArkUI_LayoutConstraint](#arkui_layoutconstraint) \*Constraint) | Obtains the height percentage reference for a size constraint, in px. | +| void [OH_ArkUI_LayoutConstraint_SetMaxWidth](#oh_arkui_layoutconstraint_setmaxwidth) ([ArkUI_LayoutConstraint](#arkui_layoutconstraint) \*Constraint, int32_t value) | Sets the maximum width. | +| void [OH_ArkUI_LayoutConstraint_SetMinWidth](#oh_arkui_layoutconstraint_setminwidth) ([ArkUI_LayoutConstraint](#arkui_layoutconstraint) \*Constraint, int32_t value) | Sets the minimum width. | +| void [OH_ArkUI_LayoutConstraint_SetMaxHeight](#oh_arkui_layoutconstraint_setmaxheight) ([ArkUI_LayoutConstraint](#arkui_layoutconstraint) \*Constraint, int32_t value) | Sets the maximum height. | +| void [OH_ArkUI_LayoutConstraint_SetMinHeight](#oh_arkui_layoutconstraint_setminheight) ([ArkUI_LayoutConstraint](#arkui_layoutconstraint) \*Constraint, int32_t value) | Sets the minimum height. | +| void [OH_ArkUI_LayoutConstraint_SetPercentReferenceWidth](#oh_arkui_layoutconstraint_setpercentreferencewidth) ([ArkUI_LayoutConstraint](#arkui_layoutconstraint) \*Constraint, int32_t value) | Sets the width percentage reference. | +| void [OH_ArkUI_LayoutConstraint_SetPercentReferenceHeight](#oh_arkui_layoutconstraint_setpercentreferenceheight) ([ArkUI_LayoutConstraint](#arkui_layoutconstraint) \*Constraint, int32_t value) | Sets the height percentage reference. | +| void \* [OH_ArkUI_DrawContext_GetCanvas](#oh_arkui_drawcontext_getcanvas) ([ArkUI_DrawContext](#arkui_drawcontext) \*context) | Obtains the pointer to a canvas for drawing, which can be converted into the **OH_Drawing_Canvas** in the **Drawing** module. | +| [ArkUI_IntSize](_ark_u_i___int_size.md) [OH_ArkUI_DrawContext_GetSize](#oh_arkui_drawcontext_getsize) ([ArkUI_DrawContext](#arkui_drawcontext) \*context) | Obtains the size of a drawing area. | +| [ArkUI_WaterFlowSectionOption](#arkui_waterflowsectionoption) \* [OH_ArkUI_WaterFlowSectionOption_Create](#oh_arkui_waterflowsectionoption_create) () | Creates a water flow section configuration. | +| void [OH_ArkUI_WaterFlowSectionOption_Dispose](#oh_arkui_waterflowsectionoption_dispose) ([ArkUI_WaterFlowSectionOption](#arkui_waterflowsectionoption) \*option) | Disposes of the pointer to a water flow section configuration. | +| void [OH_ArkUI_WaterFlowSectionOption_SetSize](#oh_arkui_waterflowsectionoption_setsize) ([ArkUI_WaterFlowSectionOption](#arkui_waterflowsectionoption) \*option, int32_t size) | Sets the array length for a water flow section configuration. | +| int32_t [OH_ArkUI_WaterFlowSectionOption_GetSize](#oh_arkui_waterflowsectionoption_getsize) ([ArkUI_WaterFlowSectionOption](#arkui_waterflowsectionoption) \*option) | Sets the array length for a water flow section configuration. | +| void [OH_ArkUI_WaterFlowSectionOption_SetItemCount](#oh_arkui_waterflowsectionoption_setitemcount) ([ArkUI_WaterFlowSectionOption](#arkui_waterflowsectionoption) \*option, int32_t index, int32_t itemCount) | Sets the number of items in a water flow section. | +| int32_t [OH_ArkUI_WaterFlowSectionOption_GetItemCount](#oh_arkui_waterflowsectionoption_getitemcount) ([ArkUI_WaterFlowSectionOption](#arkui_waterflowsectionoption) \*option, int32_t index) | Obtains the number of items in the water flow section that matches the specified index. | +| void [OH_ArkUI_WaterFlowSectionOption_SetCrossCount](#oh_arkui_waterflowsectionoption_setcrosscount) ([ArkUI_WaterFlowSectionOption](#arkui_waterflowsectionoption) \*option, int32_t index, int32_t crossCount) | Sets the number of columns (in a vertical layout) or rows (in a horizontal layout) of a water flow. | +| int32_t [OH_ArkUI_WaterFlowSectionOption_GetCrossCount](#oh_arkui_waterflowsectionoption_getcrosscount) ([ArkUI_WaterFlowSectionOption](#arkui_waterflowsectionoption) \*option, int32_t index) | Obtains the number of columns (in a vertical layout) or rows (in a horizontal layout) of a water flow. | +| void [OH_ArkUI_WaterFlowSectionOption_SetColumnGap](#oh_arkui_waterflowsectionoption_setcolumngap) ([ArkUI_WaterFlowSectionOption](#arkui_waterflowsectionoption) \*, int32_t index, float columnGap) | Sets the gap between columns in the specified water flow section. | +| float [OH_ArkUI_WaterFlowSectionOption_GetColumnGap](#oh_arkui_waterflowsectionoption_getcolumngap) ([ArkUI_WaterFlowSectionOption](#arkui_waterflowsectionoption) \*option, int32_t index) | Obtains the gap between columns in the water flow section that matches the specified index. | +| void [OH_ArkUI_WaterFlowSectionOption_SetRowGap](#oh_arkui_waterflowsectionoption_setrowgap) ([ArkUI_WaterFlowSectionOption](#arkui_waterflowsectionoption) \*option, int32_t index, float rowGap) | Sets the gap between rows in the specified water flow section. | +| float [OH_ArkUI_WaterFlowSectionOption_GetRowGap](#oh_arkui_waterflowsectionoption_getrowgap) ([ArkUI_WaterFlowSectionOption](#arkui_waterflowsectionoption) \*option, int32_t index) | Obtains the gap between rows in the water flow section that matches the specified index. | +| void [OH_ArkUI_WaterFlowSectionOption_SetMargin](#oh_arkui_waterflowsectionoption_setmargin) ([ArkUI_WaterFlowSectionOption](#arkui_waterflowsectionoption) \*option, int32_t index, float marginTop, float marginRight, float marginBottom, float marginLeft) | Sets the margins for the specified water flow section. | +| [ArkUI_Margin](_ark_u_i___margin.md) [OH_ArkUI_WaterFlowSectionOption_GetMargin](#oh_arkui_waterflowsectionoption_getmargin) ([ArkUI_WaterFlowSectionOption](#arkui_waterflowsectionoption) \*option, int32_t index) | Obtains the margins of the water flow section that matches the specified index. | +| void [OH_ArkUI_WaterFlowSectionOption_RegisterGetItemMainSizeCallbackByIndex](#oh_arkui_waterflowsectionoption_registergetitemmainsizecallbackbyindex) ([ArkUI_WaterFlowSectionOption](#arkui_waterflowsectionoption) \*option, int32_t index, float(\*callback)(int32_t itemIndex)) | Obtains the main axis size of a specified item based on **flowItemIndex** through a water flow section configuration. | +| void [OH_ArkUI_WaterFlowSectionOption_RegisterGetItemMainSizeCallbackByIndexWithUserData](#oh_arkui_waterflowsectionoption_registergetitemmainsizecallbackbyindexwithuserdata) ([ArkUI_WaterFlowSectionOption](#arkui_waterflowsectionoption) \*option, int32_t index, void \*userData, float(\*callback)(int32_t itemIndex, void \*userData)) | Obtains the main axis size of a specified item based on **flowItemIndex** through a water flow section configuration. | +| [ArkUI_GuidelineOption](#arkui_guidelineoption) \* [OH_ArkUI_GuidelineOption_Create](#oh_arkui_guidelineoption_create) (int32_t size) | Creates a guideline configuration for this **RelativeContainer** component. | +| void [OH_ArkUI_GuidelineOption_Dispose](#oh_arkui_guidelineoption_dispose) ([ArkUI_GuidelineOption](#arkui_guidelineoption) \*guideline) | Disposes of a guideline configuration. | +| void [OH_ArkUI_GuidelineOption_SetId](#oh_arkui_guidelineoption_setid) ([ArkUI_GuidelineOption](#arkui_guidelineoption) \*guideline, const char \*value, int32_t index) | Sets the ID of a guideline. | +| void [OH_ArkUI_GuidelineOption_SetDirection](#oh_arkui_guidelineoption_setdirection) ([ArkUI_GuidelineOption](#arkui_guidelineoption) \*guideline, [ArkUI_Axis](#arkui_axis) value, int32_t index) | Sets the direction of a guideline. | +| void [OH_ArkUI_GuidelineOption_SetPositionStart](#oh_arkui_guidelineoption_setpositionstart) ([ArkUI_GuidelineOption](#arkui_guidelineoption) \*guideline, float value, int32_t index) | Sets the distance between a guideline and the left or top of the container. | +| void [OH_ArkUI_GuidelineOption_SetPositionEnd](#oh_arkui_guidelineoption_setpositionend) ([ArkUI_GuidelineOption](#arkui_guidelineoption) \*guideline, float value, int32_t index) | Sets the distance between a guideline and the right or bottom of the container. | +| const char \* [OH_ArkUI_GuidelineOption_GetId](#oh_arkui_guidelineoption_getid) ([ArkUI_GuidelineOption](#arkui_guidelineoption) \*guideline, int32_t index) | Obtains the ID of a guideline. | +| [ArkUI_Axis](#arkui_axis) [OH_ArkUI_GuidelineOption_GetDirection](#oh_arkui_guidelineoption_getdirection) ([ArkUI_GuidelineOption](#arkui_guidelineoption) \*guideline, int32_t index) | Obtains the direction of a guideline. | +| float [OH_ArkUI_GuidelineOption_GetPositionStart](#oh_arkui_guidelineoption_getpositionstart) ([ArkUI_GuidelineOption](#arkui_guidelineoption) \*guideline, int32_t index) | Obtains the distance between a guideline and the left or top of the container. | +| float [OH_ArkUI_GuidelineOption_GetPositionEnd](#oh_arkui_guidelineoption_getpositionend) ([ArkUI_GuidelineOption](#arkui_guidelineoption) \*guideline, int32_t index) | Obtains the distance between a guideline and the right or bottom of the container. | +| [ArkUI_BarrierOption](#arkui_barrieroption) \* [OH_ArkUI_BarrierOption_Create](#oh_arkui_barrieroption_create) (int32_t size) | Creates a barrier configuration for this **RelativeContainer** component. | +| void [OH_ArkUI_BarrierOption_Dispose](#oh_arkui_barrieroption_dispose) ([ArkUI_BarrierOption](#arkui_barrieroption) \*barrierStyle) | Disposes of a barrier configuration. | +| void [OH_ArkUI_BarrierOption_SetId](#oh_arkui_barrieroption_setid) ([ArkUI_BarrierOption](#arkui_barrieroption) \*barrierStyle, const char \*value, int32_t index) | Sets the ID of a barrier. | +| void [OH_ArkUI_BarrierOption_SetDirection](#oh_arkui_barrieroption_setdirection) ([ArkUI_BarrierOption](#arkui_barrieroption) \*barrierStyle, [ArkUI_BarrierDirection](#arkui_barrierdirection) value, int32_t index) | Sets the direction of a barrier. | +| void [OH_ArkUI_BarrierOption_SetReferencedId](#oh_arkui_barrieroption_setreferencedid) ([ArkUI_BarrierOption](#arkui_barrieroption) \*barrierStyle, const char \*value, int32_t index) | Sets the referenced components of a barrier. | +| const char \* [OH_ArkUI_BarrierOption_GetId](#oh_arkui_barrieroption_getid) ([ArkUI_BarrierOption](#arkui_barrieroption) \*barrierStyle, int32_t index) | Obtains the ID of a barrier. | +| [ArkUI_BarrierDirection](#arkui_barrierdirection) [OH_ArkUI_BarrierOption_GetDirection](#oh_arkui_barrieroption_getdirection) ([ArkUI_BarrierOption](#arkui_barrieroption) \*barrierStyle, int32_t index) | Obtains the direction of a barrier. | +| const char \* [OH_ArkUI_BarrierOption_GetReferencedId](#oh_arkui_barrieroption_getreferencedid) ([ArkUI_BarrierOption](#arkui_barrieroption) \*barrierStyle, int32_t index, int32_t referencedIndex) | Obtains the referenced components of a barrier. | +| int32_t [OH_ArkUI_BarrierOption_GetReferencedIdSize](#oh_arkui_barrieroption_getreferencedidsize) ([ArkUI_BarrierOption](#arkui_barrieroption) \*barrierStyle, int32_t index) | Obtains the number of referenced components of a barrier. | +| [ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \* [OH_ArkUI_AlignmentRuleOption_Create](#oh_arkui_alignmentruleoption_create) () | Creates an alignment rule configuration for this **RelativeContainer** component. | +| void [OH_ArkUI_AlignmentRuleOption_Dispose](#oh_arkui_alignmentruleoption_dispose) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option) | Disposes of an alignment rule configuration of this **RelativeContainer** component. | +| void [OH_ArkUI_AlignmentRuleOption_SetStart](#oh_arkui_alignmentruleoption_setstart) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option, const char \*id, [ArkUI_HorizontalAlignment](#arkui_horizontalalignment) alignment) | Sets the left alignment parameters. | +| void [OH_ArkUI_AlignmentRuleOption_SetEnd](#oh_arkui_alignmentruleoption_setend) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option, const char \*id, [ArkUI_HorizontalAlignment](#arkui_horizontalalignment) alignment) | Sets the right alignment parameters. | +| void [OH_ArkUI_AlignmentRuleOption_SetCenterHorizontal](#oh_arkui_alignmentruleoption_setcenterhorizontal) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option, const char \*id, [ArkUI_HorizontalAlignment](#arkui_horizontalalignment) alignment) | Sets the horizontal center alignment parameters. | +| void [OH_ArkUI_AlignmentRuleOption_SetTop](#oh_arkui_alignmentruleoption_settop) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option, const char \*id, [ArkUI_VerticalAlignment](#arkui_verticalalignment) alignment) | Sets the top alignment parameters. | +| void [OH_ArkUI_AlignmentRuleOption_SetBottom](#oh_arkui_alignmentruleoption_setbottom) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option, const char \*id, [ArkUI_VerticalAlignment](#arkui_verticalalignment) alignment) | Sets the bottom alignment parameters. | +| void [OH_ArkUI_AlignmentRuleOption_SetCenterVertical](#oh_arkui_alignmentruleoption_setcentervertical) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option, const char \*id, [ArkUI_VerticalAlignment](#arkui_verticalalignment) alignment) | Sets the vertical center alignment parameters. | +| void [OH_ArkUI_AlignmentRuleOption_SetBiasHorizontal](#oh_arkui_alignmentruleoption_setbiashorizontal) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option, float horizontal) | Sets the bias value of the component in the horizontal direction under the anchor constraints. | +| void [OH_ArkUI_AlignmentRuleOption_SetBiasVertical](#oh_arkui_alignmentruleoption_setbiasvertical) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option, float vertical) | Sets the bias value of the component in the vertical direction under the anchor constraints. | +| const char \* [OH_ArkUI_AlignmentRuleOption_GetStartId](#oh_arkui_alignmentruleoption_getstartid) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option) | Obtains the ID in the left alignment parameters. | +| [ArkUI_HorizontalAlignment](#arkui_horizontalalignment) [OH_ArkUI_AlignmentRuleOption_GetStartAlignment](#oh_arkui_alignmentruleoption_getstartalignment) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option) | Obtains the alignment mode in left alignment parameters. | +| const char \* [OH_ArkUI_AlignmentRuleOption_GetEndId](#oh_arkui_alignmentruleoption_getendid) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option) | Obtains the ID in the right alignment parameters. | +| [ArkUI_HorizontalAlignment](#arkui_horizontalalignment) [OH_ArkUI_AlignmentRuleOption_GetEndAlignment](#oh_arkui_alignmentruleoption_getendalignment) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option) | Obtains the ID in the right alignment parameters. | +| const char \* [OH_ArkUI_AlignmentRuleOption_GetCenterIdHorizontal](#oh_arkui_alignmentruleoption_getcenteridhorizontal) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option) | Obtains the ID in horizontal center alignment parameters. | +| [ArkUI_HorizontalAlignment](#arkui_horizontalalignment) [OH_ArkUI_AlignmentRuleOption_GetCenterAlignmentHorizontal](#oh_arkui_alignmentruleoption_getcenteralignmenthorizontal) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option) | Obtains the ID in horizontal center alignment parameters. | +| const char \* [OH_ArkUI_AlignmentRuleOption_GetTopId](#oh_arkui_alignmentruleoption_gettopid) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option) | Obtains the ID in top alignment parameters. | +| [ArkUI_VerticalAlignment](#arkui_verticalalignment) [OH_ArkUI_AlignmentRuleOption_GetTopAlignment](#oh_arkui_alignmentruleoption_gettopalignment) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option) | Obtains the ID in top alignment parameters. | +| const char \* [OH_ArkUI_AlignmentRuleOption_GetBottomId](#oh_arkui_alignmentruleoption_getbottomid) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option) | Obtains the ID in bottom alignment parameters. | +| [ArkUI_VerticalAlignment](#arkui_verticalalignment) [OH_ArkUI_AlignmentRuleOption_GetBottomAlignment](#oh_arkui_alignmentruleoption_getbottomalignment) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option) | Obtains the ID in bottom alignment parameters. | +| const char \* [OH_ArkUI_AlignmentRuleOption_GetCenterIdVertical](#oh_arkui_alignmentruleoption_getcenteridvertical) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option) | Obtains the ID in vertical center alignment parameters. | +| [ArkUI_VerticalAlignment](#arkui_verticalalignment) [OH_ArkUI_AlignmentRuleOption_GetCenterAlignmentVertical](#oh_arkui_alignmentruleoption_getcenteralignmentvertical) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option) | Obtains the ID in vertical center alignment parameters. | +| float [OH_ArkUI_AlignmentRuleOption_GetBiasHorizontal](#oh_arkui_alignmentruleoption_getbiashorizontal) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option) | Obtains the bias value in the horizontal direction. | +| float [OH_ArkUI_AlignmentRuleOption_GetBiasVertical](#oh_arkui_alignmentruleoption_getbiasvertical) ([ArkUI_AlignmentRuleOption](#arkui_alignmentruleoption) \*option) | Obtains the bias value in the vertical direction. | +| [ArkUI_SwiperIndicator](#arkui_swiperindicator) \* [OH_ArkUI_SwiperIndicator_Create](#oh_arkui_swiperindicator_create) ([ArkUI_SwiperIndicatorType](#arkui_swiperindicatortype) type) | Creates a navigation indicator for this **Swiper** component. | +| void [OH_ArkUI_SwiperIndicator_Dispose](#oh_arkui_swiperindicator_dispose) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator) | Disposes of the navigation indicator of this **Swiper** component. | +| void [OH_ArkUI_SwiperIndicator_SetStartPosition](#oh_arkui_swiperindicator_setstartposition) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator, float value) | Sets the distance between the navigation indicator and the left edge of the **Swiper** component. | +| float [OH_ArkUI_SwiperIndicator_GetStartPosition](#oh_arkui_swiperindicator_getstartposition) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator) | Obtains the distance between a navigation indicator and the left edge of the **Swiper** component. | +| void [OH_ArkUI_SwiperIndicator_SetTopPosition](#oh_arkui_swiperindicator_settopposition) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator, float value) | Sets the distance between the navigation indicator and the top edge of the **Swiper** component. | +| float [OH_ArkUI_SwiperIndicator_GetTopPosition](#oh_arkui_swiperindicator_gettopposition) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator) | Obtains the distance between the navigation indicator and the top edge of the **Swiper** component. | +| void [OH_ArkUI_SwiperIndicator_SetEndPosition](#oh_arkui_swiperindicator_setendposition) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator, float value) | Sets the distance between the navigation indicator and the right edge of the **Swiper** component. | +| float [OH_ArkUI_SwiperIndicator_GetEndPosition](#oh_arkui_swiperindicator_getendposition) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator) | Obtains the distance between the navigation indicator and the right edge of the **Swiper** component. | +| void [OH_ArkUI_SwiperIndicator_SetBottomPosition](#oh_arkui_swiperindicator_setbottomposition) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator, float value) | Sets the distance between the navigation indicator and the bottom edge of the **Swiper** component. | +| float [OH_ArkUI_SwiperIndicator_GetBottomPosition](#oh_arkui_swiperindicator_getbottomposition) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator) | Obtains the distance between the navigation indicator and the bottom edge of the **Swiper** component. | +| void [OH_ArkUI_SwiperIndicator_SetItemWidth](#oh_arkui_swiperindicator_setitemwidth) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator, float value) | Sets the width of a dot-style navigation indicator for the **Swiper** component. | +| float [OH_ArkUI_SwiperIndicator_GetItemWidth](#oh_arkui_swiperindicator_getitemwidth) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator) | Obtains the width of a dot-style navigation indicator of the **Swiper** component. | +| void [OH_ArkUI_SwiperIndicator_SetItemHeight](#oh_arkui_swiperindicator_setitemheight) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator, float value) | Sets the height of a dot-style navigation indicator for the **Swiper** component. | +| float [OH_ArkUI_SwiperIndicator_GetItemHeight](#oh_arkui_swiperindicator_getitemheight) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator) | Obtains the height of a dot-style navigation indicator of the **Swiper** component. | +| void [OH_ArkUI_SwiperIndicator_SetSelectedItemWidth](#oh_arkui_swiperindicator_setselecteditemwidth) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator, float value) | Sets the width of the selected dot-style navigation indicator for the **Swiper** component. | +| float [OH_ArkUI_SwiperIndicator_GetSelectedItemWidth](#oh_arkui_swiperindicator_getselecteditemwidth) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator) | Obtains the width of the selected dot-style navigation indicator of the **Swiper** component. | +| void [OH_ArkUI_SwiperIndicator_SetSelectedItemHeight](#oh_arkui_swiperindicator_setselecteditemheight) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator, float value) | Sets the height of the selected dot-style navigation indicator for the **Swiper** component. | +| float [OH_ArkUI_SwiperIndicator_GetSelectedItemHeight](#oh_arkui_swiperindicator_getselecteditemheight) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator) | Obtains the height of the selected dot-style navigation indicator of the **Swiper** component. | +| void [OH_ArkUI_SwiperIndicator_SetMask](#oh_arkui_swiperindicator_setmask) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator, int32_t mask) | Sets whether to enable the mask for a dot-style navigation indicator for the **Swiper** component. | +| int32_t [OH_ArkUI_SwiperIndicator_GetMask](#oh_arkui_swiperindicator_getmask) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator) | Obtains whether the mask is enabled for a dot-style navigation indicator of the **Swiper** component. | +| void [OH_ArkUI_SwiperIndicator_SetColor](#oh_arkui_swiperindicator_setcolor) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator, uint32_t color) | Sets the color of a dot-style navigation indicator for the **Swiper** component. | +| uint32_t [OH_ArkUI_SwiperIndicator_GetColor](#oh_arkui_swiperindicator_getcolor) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator) | Obtains the color of a dot-style navigation indicator of the **Swiper** component. | +| void [OH_ArkUI_SwiperIndicator_SetSelectedColor](#oh_arkui_swiperindicator_setselectedcolor) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator, uint32_t selectedColor) | Sets the color of the selected dot-style navigation indicator for the **Swiper** component. | +| uint32_t [OH_ArkUI_SwiperIndicator_GetSelectedColor](#oh_arkui_swiperindicator_getselectedcolor) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator) | Obtains the color of the selected dot-style navigation indicator of the **Swiper** component. | +| int32_t [OH_ArkUI_SwiperIndicator_SetMaxDisplayCount](#oh_arkui_swiperindicator_setmaxdisplaycount) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator, int32_t maxDisplayCount) | Sets the maximum number of dots for the dot-style navigation indicator. | +| int32_t [OH_ArkUI_SwiperIndicator_GetMaxDisplayCount](#oh_arkui_swiperindicator_getmaxdisplaycount) ([ArkUI_SwiperIndicator](#arkui_swiperindicator) \*indicator) | Obtains the maximum number of points for the navigation indicator. | +| [ArkUI_SwiperDigitIndicator](#arkui_swiperdigitindicator)* [OH_ArkUI_SwiperDigitIndicator_Create](#oh_arkui_swiperdigitindicator_create)() | Creates a digit-style navigation indicator for this **Swiper** component. | +| void [OH_ArkUI_SwiperDigitIndicator_SetStartPosition](#oh_arkui_swiperdigitindicator_setstartposition)([ArkUI_SwiperDigitIndicator](#arkui_swiperdigitindicator)* indicator, float value) | Sets the start position of the digit-style navigation indicator for the **Swiper** component. This determines the distance from the left edge of the **Swiper** component. For right-to-left scripts, this determines the distance from the right edge. | +| float [OH_ArkUI_SwiperDigitIndicator_GetStartPosition](#oh_arkui_swiperdigitindicator_getstartposition)([ArkUI_SwiperDigitIndicator](#arkui_swiperdigitindicator)* indicator) | Obtains the start position of the digit-style navigation indicator for the **Swiper** component. This indicates the distance from the left edge of the **Swiper** component. For right-to-left scripts, this indicates the distance from the right edge. | +| void [OH_ArkUI_SwiperDigitIndicator_SetTopPosition](#oh_arkui_swiperdigitindicator_settopposition)([ArkUI_SwiperDigitIndicator](#arkui_swiperdigitindicator)* indicator, float value) | Sets the distance from the digit-style navigation indicator to the top of the **Swiper** component.| +| float [OH_ArkUI_SwiperDigitIndicator_GetTopPosition](#oh_arkui_swiperdigitindicator_gettopposition)([ArkUI_SwiperDigitIndicator](#arkui_swiperdigitindicator)* indicator) | Obtains the distance from the digit-style navigation indicator to the top of the **Swiper** component. | +| void [OH_ArkUI_SwiperDigitIndicator_SetEndPosition](#oh_arkui_swiperdigitindicator_setendposition)([ArkUI_SwiperDigitIndicator](#arkui_swiperdigitindicator)* indicator, float value) | Sets the end position of the digit-style navigation indicator for the **Swiper** component. This determines the distance from the right edge of the **Swiper** component. For right-to-left scripts, this determines the distance from the left edge.| +| float [OH_ArkUI_SwiperDigitIndicator_GetEndPosition](#oh_arkui_swiperdigitindicator_getendposition)([ArkUI_SwiperDigitIndicator](#arkui_swiperdigitindicator)* indicator) | Obtains the end position of the digit-style navigation indicator for the **Swiper** component. This indicates the distance from the right edge of the **Swiper** component. For right-to-left scripts, this indicates the distance from the left edge. | +| void [OH_ArkUI_SwiperDigitIndicator_SetBottomPosition](#oh_arkui_swiperdigitindicator_setbottomposition)([ArkUI_SwiperDigitIndicator](#arkui_swiperdigitindicator)* indicator, float value) | Sets the distance from the digit-style navigation indicator to the bottom of the **Swiper** component.| +| float [OH_ArkUI_SwiperDigitIndicator_GetBottomPosition](#oh_arkui_swiperdigitindicator_getbottomposition)([ArkUI_SwiperDigitIndicator](#arkui_swiperdigitindicator)* indicator) | Obtains the distance from the digit-style navigation indicator to the bottom of the **Swiper** component. | +| void [OH_ArkUI_SwiperDigitIndicator_SetFontColor](#oh_arkui_swiperdigitindicator_setfontcolor)([ArkUI_SwiperDigitIndicator](#arkui_swiperdigitindicator)* indicator, uint32_t color) | Sets the font color of the digit-style navigation indicator for the **Swiper** component.| +| uint32_t [OH_ArkUI_SwiperDigitIndicator_GetFontColor](#oh_arkui_swiperdigitindicator_getfontcolor)([ArkUI_SwiperDigitIndicator](#arkui_swiperdigitindicator)* indicator) | Obtains the font color of the digit-style navigation indicator for the **Swiper** component. | +| void [OH_ArkUI_SwiperDigitIndicator_SetSelectedFontColor](#oh_arkui_swiperdigitindicator_setselectedfontcolor)([ArkUI_SwiperDigitIndicator](#arkui_swiperdigitindicator)* indicator, uint32_t selectedColor) | Sets the font color of the selected digit-style navigation indicator for the **Swiper** component.| +| uint32_t [OH_ArkUI_SwiperDigitIndicator_GetSelectedFontColor](#oh_arkui_swiperdigitindicator_getselectedfontcolor)([ArkUI_SwiperDigitIndicator](#arkui_swiperdigitindicator)* indicator) | Obtains the font color of the selected digit-style navigation indicator for the **Swiper** component. | +| void [OH_ArkUI_SwiperDigitIndicator_SetFontSize](#oh_arkui_swiperdigitindicator_setfontsize)([ArkUI_SwiperDigitIndicator](#arkui_swiperdigitindicator)* indicator, float size) | Sets the font size of the digit-style navigation indicator for the **Swiper** component.| +| float [OH_ArkUI_SwiperDigitIndicator_GetFontSize](#oh_arkui_swiperdigitindicator_getfontsize)([ArkUI_SwiperDigitIndicator](#arkui_swiperdigitindicator)* indicator) | Obtains the font size of the digit-style navigation indicator for the **Swiper** component. | +| void [OH_ArkUI_SwiperDigitIndicator_SetSelectedFontSize](#oh_arkui_swiperdigitindicator_setselectedfontsize)([ArkUI_SwiperDigitIndicator](#arkui_swiperdigitindicator)* indicator, float size) | Sets the font size of the selected digit-style navigation indicator for the **Swiper** component.| +| float [OH_ArkUI_SwiperDigitIndicator_GetSelectedFontSize](#oh_arkui_swiperdigitindicator_getselectedfontsize)([ArkUI_SwiperDigitIndicator](#arkui_swiperdigitindicator)* indicator) | Obtains the font size of the selected digit-style navigation indicator for the **Swiper** component. | +| void [OH_ArkUI_SwiperDigitIndicator_SetFontWeight](#oh_arkui_swiperdigitindicator_setfontweight)([ArkUI_SwiperDigitIndicator](#arkui_swiperdigitindicator)* indicator, [ArkUI_FontWeight](#arkui_fontweight) fontWeight) | Sets the font weight of the digit-style navigation indicator for the **Swiper** component.| +| [ArkUI_FontWeight](#arkui_fontweight) [OH_ArkUI_SwiperDigitIndicator_GetFontWeight](#oh_arkui_swiperdigitindicator_getfontweight)([ArkUI_SwiperDigitIndicator](#arkui_swiperdigitindicator)* indicator) | Obtains the font weight of the digit-style navigation indicator for the **Swiper** component. | +| void [OH_ArkUI_SwiperDigitIndicator_SetSelectedFontWeight](#oh_arkui_swiperdigitindicator_setselectedfontweight)([ArkUI_SwiperDigitIndicator](#arkui_swiperdigitindicator)* indicator, [ArkUI_FontWeight](#arkui_fontweight) selectedFontWeight) | Sets the font weight of the selected digit-style navigation indicator for the **Swiper** component.| +| [ArkUI_FontWeight](#arkui_fontweight) [OH_ArkUI_SwiperDigitIndicator_GetSelectedFontWeight](#oh_arkui_swiperdigitindicator_getselectedfontweight)([ArkUI_SwiperDigitIndicator](#arkui_swiperdigitindicator)* indicator) | Obtains the font weight of the selected digit-style navigation indicator for the **Swiper** component. | +|void [OH_ArkUI_SwiperDigitIndicator_Dispose](#oh_arkui_swiperdigitindicator_dispose)() | Disposes of the digit-style navigation indicator of this **Swiper** component. | +| [ArkUI_SwiperArrowStyle](#arkui_swiperarrowstyle)* [OH_ArkUI_SwiperArrowStyle_Create](#oh_arkui_swiperarrowstyle_create)() | Creates an arrow style for the **Swiper** component. | +| void [OH_ArkUI_SwiperArrowStyle_SetShowBackground](#oh_arkui_swiperarrowstyle_setshowbackground)([ArkUI_SwiperArrowStyle](#arkui_swiperarrowstyle)* indicator, int32_t showBackground) | Sets whether to display the background of the arrow for the **Swiper** component.| +| int32_t [OH_ArkUI_SwiperArrowStyle_GetShowBackground](#oh_arkui_swiperarrowstyle_getshowbackground)([ArkUI_SwiperArrowStyle](#arkui_swiperarrowstyle)* indicator) | Checks whether the background of the arrow is displayed for the **Swiper** component. | +| void [OH_ArkUI_SwiperArrowStyle_SetShowSidebarMiddle](#oh_arkui_swiperarrowstyle_setshowsidebarmiddle)([ArkUI_SwiperArrowStyle](#arkui_swiperarrowstyle)* indicator, int32_t showSidebarMiddle) | Sets the position of the arrow for the **Swiper** component.| +| int32_t [OH_ArkUI_SwiperArrowStyle_GetShowSidebarMiddle](#oh_arkui_swiperarrowstyle_getshowsidebarmiddle)([ArkUI_SwiperArrowStyle](#arkui_swiperarrowstyle)* indicator) | Obtains the position of the arrow for the **Swiper** component. | +| void [OH_ArkUI_SwiperArrowStyle_SetBackgroundSize](#oh_arkui_swiperarrowstyle_setbackgroundsize)([ArkUI_SwiperArrowStyle](#arkui_swiperarrowstyle)* indicator, float backgroundSize) | Sets the background size for the arrow of the **Swiper** component.| +| float [OH_ArkUI_SwiperArrowStyle_GetBackgroundSize](#oh_arkui_swiperarrowstyle_getbackgroundsize)([ArkUI_SwiperArrowStyle](#arkui_swiperarrowstyle)* indicator) | Obtains the background size for the arrow of the **Swiper** component. | +| void [OH_ArkUI_SwiperArrowStyle_SetBackgroundColor](#oh_arkui_swiperarrowstyle_setbackgroundcolor)([ArkUI_SwiperArrowStyle](#arkui_swiperarrowstyle)* indicator, uint32_t backgroundColor) | Sets the background color for the arrow of the **Swiper** component.| +| uint32_t [OH_ArkUI_SwiperArrowStyle_GetBackgroundColor](#oh_arkui_swiperarrowstyle_getbackgroundcolor)([ArkUI_SwiperArrowStyle](#arkui_swiperarrowstyle)* indicator) | Obtains the background color for the arrow of the **Swiper** component. | +| void [OH_ArkUI_SwiperArrowStyle_SetArrowSize](#oh_arkui_swiperarrowstyle_setarrowsize)([ArkUI_SwiperArrowStyle](#arkui_swiperarrowstyle)* indicator, float arrowSize) | Sets the size for the arrow of the **Swiper** component.| +| float [OH_ArkUI_SwiperArrowStyle_GetArrowSize](#oh_arkui_swiperarrowstyle_getarrowsize)([ArkUI_SwiperArrowStyle](#arkui_swiperarrowstyle)* indicator) | Obtains the size of the arrow of the **Swiper** component. | +| void [OH_ArkUI_SwiperArrowStyle_SetArrowColor](#oh_arkui_swiperarrowstyle_setarrowcolor)([ArkUI_SwiperArrowStyle](#arkui_swiperarrowstyle)* indicator, uint32_t arrowColor) | Sets the color for the arrow of the **Swiper** component.| +| uint32_t [OH_ArkUI_SwiperArrowStyle_GetArrowColor](#oh_arkui_swiperarrowstyle_getarrowcolor)([ArkUI_SwiperArrowStyle](#arkui_swiperarrowstyle)* indicator) | Obtains the color of the arrow of the **Swiper** component. | +|void [OH_ArkUI_SwiperArrowStyle_Dispose](#oh_arkui_swiperarrowstyle_dispose)() | Disposes of the arrow style of the **Swiper** component. | +| [ArkUI_ListItemSwipeActionItem](#arkui_listitemswipeactionitem) \* [OH_ArkUI_ListItemSwipeActionItem_Create](#oh_arkui_listitemswipeactionitem_create) () | Creates a **ListItemSwipeActionItem** instance. | +| void [OH_ArkUI_ListItemSwipeActionItem_Dispose](#oh_arkui_listitemswipeactionitem_dispose) ([ArkUI_ListItemSwipeActionItem](#arkui_listitemswipeactionitem) \*item) | Disposes of a **ListItemSwipeActionItem** instance. | +| void [OH_ArkUI_ListItemSwipeActionItem_SetContent](#oh_arkui_listitemswipeactionitem_setcontent) ([ArkUI_ListItemSwipeActionItem](#arkui_listitemswipeactionitem) \*item, [ArkUI_NodeHandle](#arkui_nodehandle) node) | Sets the layout content for a **ListItemSwipeActionItem** instance. | +| void [OH_ArkUI_ListItemSwipeActionItem_SetActionAreaDistance](#oh_arkui_listitemswipeactionitem_setactionareadistance) ([ArkUI_ListItemSwipeActionItem](#arkui_listitemswipeactionitem) \*item, float distance) | Sets the swipe distance threshold for deleting the list item. | +| float [OH_ArkUI_ListItemSwipeActionItem_GetActionAreaDistance](#oh_arkui_listitemswipeactionitem_getactionareadistance) ([ArkUI_ListItemSwipeActionItem](#arkui_listitemswipeactionitem) \*item) | Obtains the swipe distance threshold for deleting the list item. | +| void [OH_ArkUI_ListItemSwipeActionItem_SetOnEnterActionArea](#oh_arkui_listitemswipeactionitem_setonenteractionarea) ([ArkUI_ListItemSwipeActionItem](#arkui_listitemswipeactionitem) \*item, void(\*callback)()) | Sets the callback invoked each time the list item enters the delete area. | +| void [OH_ArkUI_ListItemSwipeActionItem_SetOnEnterActionAreaWithUserData](#oh_arkui_listitemswipeactionitem_setonenteractionareawithuserdata) ([ArkUI_ListItemSwipeActionItem](#arkui_listitemswipeactionitem) \*item, void \*userData, void(\*callback)(void \*userData)) | Sets the callback invoked each time the list item enters the delete area. | +| void [OH_ArkUI_ListItemSwipeActionItem_SetOnAction](#oh_arkui_listitemswipeactionitem_setonaction) ([ArkUI_ListItemSwipeActionItem](#arkui_listitemswipeactionitem) \*item, void(\*callback)()) | Sets the callback invoked when the list item is deleted while in the delete area. | +| void [OH_ArkUI_ListItemSwipeActionItem_SetOnActionWithUserData](#oh_arkui_listitemswipeactionitem_setonactionwithuserdata) ([ArkUI_ListItemSwipeActionItem](#arkui_listitemswipeactionitem) \*item, void \*userData, void(\*callback)(void \*userData)) | Sets the callback invoked when the list item is deleted while in the delete area. | +| void [OH_ArkUI_ListItemSwipeActionItem_SetOnExitActionArea](#oh_arkui_listitemswipeactionitem_setonexitactionarea) ([ArkUI_ListItemSwipeActionItem](#arkui_listitemswipeactionitem) \*item, void(\*callback)()) | Sets the callback invoked each time the list item exits the delete area. | +| void [OH_ArkUI_ListItemSwipeActionItem_SetOnExitActionAreaWithUserData](#oh_arkui_listitemswipeactionitem_setonexitactionareawithuserdata) ([ArkUI_ListItemSwipeActionItem](#arkui_listitemswipeactionitem) \*item, void \*userData, void(\*callback)(void \*userData)) | Sets the callback invoked each time the list item exits the delete area. | +| void [OH_ArkUI_ListItemSwipeActionItem_SetOnStateChange](#oh_arkui_listitemswipeactionitem_setonstatechange) ([ArkUI_ListItemSwipeActionItem](#arkui_listitemswipeactionitem) \*item, void(\*callback)([ArkUI_ListItemSwipeActionState](#arkui_listitemswipeactionstate) swipeActionState)) | Sets the callback invoked when the swipe state of the list item changes. | +| void [OH_ArkUI_ListItemSwipeActionItem_SetOnStateChangeWithUserData](#oh_arkui_listitemswipeactionitem_setonstatechangewithuserdata) ([ArkUI_ListItemSwipeActionItem](#arkui_listitemswipeactionitem) \*item, void \*userData, void(\*callback)([ArkUI_ListItemSwipeActionState](#arkui_listitemswipeactionstate) swipeActionState, void \*userData)) | Sets the callback invoked when the swipe state of the list item changes. | +| [ArkUI_ListItemSwipeActionOption](#arkui_listitemswipeactionoption) \* [OH_ArkUI_ListItemSwipeActionOption_Create](#oh_arkui_listitemswipeactionoption_create) () | Creates a **ListItemSwipeActionOption** instance. | +| void [OH_ArkUI_ListItemSwipeActionOption_Dispose](#oh_arkui_listitemswipeactionoption_dispose) ([ArkUI_ListItemSwipeActionOption](#arkui_listitemswipeactionoption) \*option) | Disposes of a **ListItemSwipeActionOption** instance. | +| void [OH_ArkUI_ListItemSwipeActionOption_SetStart](#oh_arkui_listitemswipeactionoption_setstart) ([ArkUI_ListItemSwipeActionOption](#arkui_listitemswipeactionoption) \*option, [ArkUI_ListItemSwipeActionItem](#arkui_listitemswipeactionitem) \*item) | Sets the layout content for the left edge (for a vertical layout) or top edge (for a horizontal layout) of a **ListItemSwipeActionOption** instance. | +| void [OH_ArkUI_ListItemSwipeActionOption_SetEnd](#oh_arkui_listitemswipeactionoption_setend) ([ArkUI_ListItemSwipeActionOption](#arkui_listitemswipeactionoption) \*option, [ArkUI_ListItemSwipeActionItem](#arkui_listitemswipeactionitem) \*item) | Sets the layout content for the right edge (for a vertical layout) or bottom edge (for a horizontal layout) of a **ListItemSwipeActionItem** instance. | +| void [OH_ArkUI_ListItemSwipeActionOption_SetEdgeEffect](#oh_arkui_listitemswipeactionoption_setedgeeffect) ([ArkUI_ListItemSwipeActionOption](#arkui_listitemswipeactionoption) \*option, [ArkUI_ListItemSwipeEdgeEffect](#arkui_listitemswipeedgeeffect) edgeEffect) | Sets the edge effect used when the boundary of the scrolling area is reached. | +| int32_t [OH_ArkUI_ListItemSwipeActionOption_GetEdgeEffect](#oh_arkui_listitemswipeactionoption_getedgeeffect) ([ArkUI_ListItemSwipeActionOption](#arkui_listitemswipeactionoption) \*option) | Obtains the edge effect used when the boundary of the scrolling area is reached. | +| void [OH_ArkUI_ListItemSwipeActionOption_SetOnOffsetChange](#oh_arkui_listitemswipeactionoption_setonoffsetchange) ([ArkUI_ListItemSwipeActionOption](#arkui_listitemswipeactionoption) \*option, void(\*callback)(float offset)) | Sets the callback invoked when the scroll offset changes. | +| void [OH_ArkUI_ListItemSwipeActionOption_SetOnOffsetChangeWithUserData](#oh_arkui_listitemswipeactionoption_setonoffsetchangewithuserdata) ([ArkUI_ListItemSwipeActionOption](#arkui_listitemswipeactionoption) \*option, void \*userData, void(\*callback)(float offset, void \*userData)) | Sets the callback invoked when the scroll offset changes. | +| [ArkUI_AccessibilityState](#arkui_accessibilitystate) \* [OH_ArkUI_AccessibilityState_Create](#oh_arkui_accessibilitystate_create) (void) | Creates an accessibility state. | +| void [OH_ArkUI_AccessibilityState_Dispose](#oh_arkui_accessibilitystate_dispose) ([ArkUI_AccessibilityState](#arkui_accessibilitystate) \*state) | Disposes of the pointer to an accessibility state. | +| void [OH_ArkUI_AccessibilityState_SetDisabled](#oh_arkui_accessibilitystate_setdisabled) ([ArkUI_AccessibilityState](#arkui_accessibilitystate) \*state, int32_t isDisabled) | Sets whether an accessibility state is disabled. | +| int32_t [OH_ArkUI_AccessibilityState_IsDisabled](#oh_arkui_accessibilitystate_isdisabled) ([ArkUI_AccessibilityState](#arkui_accessibilitystate) \*state) | Obtains whether an accessibility state is disabled. | +| void [OH_ArkUI_AccessibilityState_SetSelected](#oh_arkui_accessibilitystate_setselected) ([ArkUI_AccessibilityState](#arkui_accessibilitystate) \*state, int32_t isSelected) | Sets whether an accessibility state is selected. | +| int32_t [OH_ArkUI_AccessibilityState_IsSelected](#oh_arkui_accessibilitystate_isselected) ([ArkUI_AccessibilityState](#arkui_accessibilitystate) \*state) | Obtains whether an accessibility state is selected. | +| void [OH_ArkUI_AccessibilityState_SetCheckedState](#oh_arkui_accessibilitystate_setcheckedstate) ([ArkUI_AccessibilityState](#arkui_accessibilitystate) \*state, int32_t checkedState) | Sets the check box state of an accessibility state. | +| int32_t [OH_ArkUI_AccessibilityState_GetCheckedState](#oh_arkui_accessibilitystate_getcheckedstate) ([ArkUI_AccessibilityState](#arkui_accessibilitystate) \*state) | Obtains the check box state of an accessibility state. | +| [ArkUI_AccessibilityValue](#arkui_accessibilityvalue) \* [OH_ArkUI_AccessibilityValue_Create](#oh_arkui_accessibilityvalue_create) (void) | Creates an **AccessibilityValue** instance. | +| void [OH_ArkUI_AccessibilityValue_Dispose](#oh_arkui_accessibilityvalue_dispose) ([ArkUI_AccessibilityValue](#arkui_accessibilityvalue) \*value) | Disposes of the pointer to an **AccessibilityValue** instance. | +| void [OH_ArkUI_AccessibilityValue_SetMin](#oh_arkui_accessibilityvalue_setmin) ([ArkUI_AccessibilityValue](#arkui_accessibilityvalue) \*value, int32_t min) | Sets the minimum accessibility value. | +| int32_t [OH_ArkUI_AccessibilityValue_GetMin](#oh_arkui_accessibilityvalue_getmin) ([ArkUI_AccessibilityValue](#arkui_accessibilityvalue) \*value) | Obtains the minimum accessibility value. | +| void [OH_ArkUI_AccessibilityValue_SetMax](#oh_arkui_accessibilityvalue_setmax) ([ArkUI_AccessibilityValue](#arkui_accessibilityvalue) \*value, int32_t max) | Sets the maximum accessibility value. | +| int32_t [OH_ArkUI_AccessibilityValue_GetMax](#oh_arkui_accessibilityvalue_getmax) ([ArkUI_AccessibilityValue](#arkui_accessibilityvalue) \*value) | Obtains the maximum accessibility value. | +| void [OH_ArkUI_AccessibilityValue_SetCurrent](#oh_arkui_accessibilityvalue_setcurrent) ([ArkUI_AccessibilityValue](#arkui_accessibilityvalue) \*value, int32_t current) | Sets the current accessibility value. | +| int32_t [OH_ArkUI_AccessibilityValue_GetCurrent](#oh_arkui_accessibilityvalue_getcurrent) ([ArkUI_AccessibilityValue](#arkui_accessibilityvalue) \*value) | Obtains the current accessibility value. | +| void [OH_ArkUI_AccessibilityValue_SetText](#oh_arkui_accessibilityvalue_settext) ([ArkUI_AccessibilityValue](#arkui_accessibilityvalue) \*value, const char \*text) | Sets the text description of an **AccessibilityValue** instance. | +| const char \* [OH_ArkUI_AccessibilityValue_GetText](#oh_arkui_accessibilityvalue_gettext) ([ArkUI_AccessibilityValue](#arkui_accessibilityvalue) \*value) | Obtains the text description of an **AccessibilityValue** instance. | +| [ArkUI_ImageAnimatorFrameInfo](#arkui_imageanimatorframeinfo) \* [OH_ArkUI_ImageAnimatorFrameInfo_CreateFromString](#oh_arkui_imageanimatorframeinfo_createfromstring) (char \*src) | Creates an image frame information object based on an image path, with the image format being SVG, PNG, or JPG. | +| [ArkUI_ImageAnimatorFrameInfo](#arkui_imageanimatorframeinfo) \* [OH_ArkUI_ImageAnimatorFrameInfo_CreateFromDrawableDescriptor](#oh_arkui_imageanimatorframeinfo_createfromdrawabledescriptor) ([ArkUI_DrawableDescriptor](#arkui_drawabledescriptor) \*drawable) | Creates an image frame information object based on a **DrawableDescriptor** object, with the image format being Resource or PixelMap. | +| void [OH_ArkUI_ImageAnimatorFrameInfo_Dispose](#oh_arkui_imageanimatorframeinfo_dispose) ([ArkUI_ImageAnimatorFrameInfo](#arkui_imageanimatorframeinfo) \*imageInfo) | Disposes of the pointer to an image frame information object. | +| void [OH_ArkUI_ImageAnimatorFrameInfo_SetWidth](#oh_arkui_imageanimatorframeinfo_setwidth) ([ArkUI_ImageAnimatorFrameInfo](#arkui_imageanimatorframeinfo) \*imageInfo, int32_t width) | Sets the image width. | +| int32_t [OH_ArkUI_ImageAnimatorFrameInfo_GetWidth](#oh_arkui_imageanimatorframeinfo_getwidth) ([ArkUI_ImageAnimatorFrameInfo](#arkui_imageanimatorframeinfo) \*imageInfo) | Obtains the image width. | +| void [OH_ArkUI_ImageAnimatorFrameInfo_SetHeight](#oh_arkui_imageanimatorframeinfo_setheight) ([ArkUI_ImageAnimatorFrameInfo](#arkui_imageanimatorframeinfo) \*imageInfo, int32_t height) | Sets the image height. | +| int32_t [OH_ArkUI_ImageAnimatorFrameInfo_GetHeight](#oh_arkui_imageanimatorframeinfo_getheight) ([ArkUI_ImageAnimatorFrameInfo](#arkui_imageanimatorframeinfo) \*imageInfo) | Obtains the image height. | +| void [OH_ArkUI_ImageAnimatorFrameInfo_SetTop](#oh_arkui_imageanimatorframeinfo_settop) ([ArkUI_ImageAnimatorFrameInfo](#arkui_imageanimatorframeinfo) \*imageInfo, int32_t top) | Sets the vertical coordinate of an image relative to the upper left corner of the component. | +| int32_t [OH_ArkUI_ImageAnimatorFrameInfo_GetTop](#oh_arkui_imageanimatorframeinfo_gettop) ([ArkUI_ImageAnimatorFrameInfo](#arkui_imageanimatorframeinfo) \*imageInfo) | Obtains the vertical coordinate of an image relative to the upper left corner of the component. | +| void [OH_ArkUI_ImageAnimatorFrameInfo_SetLeft](#oh_arkui_imageanimatorframeinfo_setleft) ([ArkUI_ImageAnimatorFrameInfo](#arkui_imageanimatorframeinfo) \*imageInfo, int32_t left) | Sets the horizontal coordinate of an image relative to the upper left corner of the component. | +| int32_t [OH_ArkUI_ImageAnimatorFrameInfo_GetLeft](#oh_arkui_imageanimatorframeinfo_getleft) ([ArkUI_ImageAnimatorFrameInfo](#arkui_imageanimatorframeinfo) \*imageInfo) | Obtains the horizontal coordinate of an image relative to the upper left corner of the component. | +| void [OH_ArkUI_ImageAnimatorFrameInfo_SetDuration](#oh_arkui_imageanimatorframeinfo_setduration) ([ArkUI_ImageAnimatorFrameInfo](#arkui_imageanimatorframeinfo) \*imageInfo, int32_t duration) | Sets the playback duration of an image. | +| int32_t [OH_ArkUI_ImageAnimatorFrameInfo_GetDuration](#oh_arkui_imageanimatorframeinfo_getduration) ([ArkUI_ImageAnimatorFrameInfo](#arkui_imageanimatorframeinfo) \*imageInfo) | Obtains the playback duration of an image. | +| [ArkUI_ListChildrenMainSize](#arkui_listchildrenmainsize) \* [OH_ArkUI_ListChildrenMainSizeOption_Create](#oh_arkui_listchildrenmainsizeoption_create) () | Creates a **ListChildrenMainSize** instance. | +| void [OH_ArkUI_ListChildrenMainSizeOption_Dispose](#oh_arkui_listchildrenmainsizeoption_dispose) ([ArkUI_ListChildrenMainSize](#arkui_listchildrenmainsize) \*option) | Disposes of a **ListChildrenMainSize** instance. | +| int32_t [OH_ArkUI_ListChildrenMainSizeOption_SetDefaultMainSize](#oh_arkui_listchildrenmainsizeoption_setdefaultmainsize) ([ArkUI_ListChildrenMainSize](#arkui_listchildrenmainsize) \*option, float defaultMainSize) | Sets the default size in a **ListChildrenMainSize** instance. | +| float [OH_ArkUI_ListChildrenMainSizeOption_GetDefaultMainSize](#oh_arkui_listchildrenmainsizeoption_getdefaultmainsize) ([ArkUI_ListChildrenMainSize](#arkui_listchildrenmainsize) \*option) | Obtains the default size in a **ListChildrenMainSize** instance. | +| void [OH_ArkUI_ListChildrenMainSizeOption_Resize](#oh_arkui_listchildrenmainsizeoption_resize) ([ArkUI_ListChildrenMainSize](#arkui_listchildrenmainsize) \*option, int32_t totalSize) | Resets the array size in a **ListChildrenMainSize** instance. | +| int32_t [OH_ArkUI_ListChildrenMainSizeOption_Splice](#oh_arkui_listchildrenmainsizeoption_splice) ([ArkUI_ListChildrenMainSize](#arkui_listchildrenmainsize) \*option, int32_t index, int32_t deleteCount, int32_t addCount) | Changes the content of a **ChildrenMainSizeOption** array. | +| int32_t [OH_ArkUI_ListChildrenMainSizeOption_UpdateSize](#oh_arkui_listchildrenmainsizeoption_updatesize) ([ArkUI_ListChildrenMainSize](#arkui_listchildrenmainsize) \*option, int32_t index, float mainSize) | Updates the values of a **ChildrenMainSizeOption** array. | +| float [OH_ArkUI_ListChildrenMainSizeOption_GetMainSize](#oh_arkui_listchildrenmainsizeoption_getmainsize) ([ArkUI_ListChildrenMainSize](#arkui_listchildrenmainsize) \*option, int32_t index) | Obtains the values of a **ChildrenMainSizeOption** array. | +| [ArkUI_CustomSpanMeasureInfo](#arkui_customspanmeasureinfo) \* [OH_ArkUI_CustomSpanMeasureInfo_Create](#oh_arkui_customspanmeasureinfo_create) (void) | Creates measurement information for this custom span. | +| void [OH_ArkUI_CustomSpanMeasureInfo_Dispose](#oh_arkui_customspanmeasureinfo_dispose) ([ArkUI_CustomSpanMeasureInfo](#arkui_customspanmeasureinfo) \*info) | Disposes of measurement information of a custom span. | +| float [OH_ArkUI_CustomSpanMeasureInfo_GetFontSize](#oh_arkui_customspanmeasureinfo_getfontsize) ([ArkUI_CustomSpanMeasureInfo](#arkui_customspanmeasureinfo) \*info) | Obtains the font size of the parent text node of a custom span. | +| [ArkUI_CustomSpanMetrics](#arkui_customspanmetrics) \* [OH_ArkUI_CustomSpanMetrics_Create](#oh_arkui_customspanmetrics_create) (void) | Creates measurement metrics for this custom span. | +| void [OH_ArkUI_CustomSpanMetrics_Dispose](#oh_arkui_customspanmetrics_dispose) ([ArkUI_CustomSpanMetrics](#arkui_customspanmetrics) \*metrics) | Disposes of measurement metrics of this custom span. | +| int32_t [OH_ArkUI_CustomSpanMetrics_SetWidth](#oh_arkui_customspanmetrics_setwidth) ([ArkUI_CustomSpanMetrics](#arkui_customspanmetrics) \*metrics, float width) | Sets the width for a custom span. | +| int32_t [OH_ArkUI_CustomSpanMetrics_SetHeight](#oh_arkui_customspanmetrics_setheight) ([ArkUI_CustomSpanMetrics](#arkui_customspanmetrics) \*metrics, float height) | Sets the height for a custom span. | +| [ArkUI_CustomSpanDrawInfo](#arkui_customspandrawinfo) \* [OH_ArkUI_CustomSpanDrawInfo_Create](#oh_arkui_customspandrawinfo_create) (void) | Creates drawing information for this custom span. | +| void [OH_ArkUI_CustomSpanDrawInfo_Dispose](#oh_arkui_customspandrawinfo_dispose) ([ArkUI_CustomSpanDrawInfo](#arkui_customspandrawinfo) \*info) | Disposes of drawing information for this custom span. | +| float [OH_ArkUI_CustomSpanDrawInfo_GetXOffset](#oh_arkui_customspandrawinfo_getxoffset) ([ArkUI_CustomSpanDrawInfo](#arkui_customspandrawinfo) \*info) | Obtains the x-axis offset of the custom span relative to the mounted component. | +| float [OH_ArkUI_CustomSpanDrawInfo_GetLineTop](#oh_arkui_customspandrawinfo_getlinetop) ([ArkUI_CustomSpanDrawInfo](#arkui_customspandrawinfo) \*info) | Obtains the top margin of the custom span relative to the mounted component. | +| float [OH_ArkUI_CustomSpanDrawInfo_GetLineBottom](#oh_arkui_customspandrawinfo_getlinebottom) ([ArkUI_CustomSpanDrawInfo](#arkui_customspandrawinfo) \*info) | Obtains the bottom margin of the custom span relative to the mounted component. | +| float [OH_ArkUI_CustomSpanDrawInfo_GetBaseline](#oh_arkui_customspandrawinfo_getbaseline) ([ArkUI_CustomSpanDrawInfo](#arkui_customspandrawinfo) \*info) | Obtains the baseline offset of the custom span relative to the mounted component. | | void [OH_ArkUI_CustomProperty_Destroy](#oh_arkui_customproperty_destroy) (ArkUI_CustomProperty \*handle) | Destroys a **CustomProperty** instance. | | const char \* [OH_ArkUI_CustomProperty_GetStringValue](#oh_arkui_customproperty_getstringvalue) (ArkUI_CustomProperty \*handle) | Obtains the value of a custom property. | | void [OH_ArkUI_ActiveChildrenInfo_Destroy](#oh_arkui_activechildreninfo_destroy) (ArkUI_ActiveChildrenInfo \*handle) | Destroys an **ActiveChildrenInfo** instance. | | [ArkUI_NodeHandle](#arkui_nodehandle) [OH_ArkUI_ActiveChildrenInfo_GetNodeByIndex](#oh_arkui_activechildreninfo_getnodebyindex) (ArkUI_ActiveChildrenInfo \*handle, int32_t index) | Obtains the child node at the specified index in the specified **ActiveChildrenInfo** instance. | | int32_t [OH_ArkUI_ActiveChildrenInfo_GetCount](#oh_arkui_activechildreninfo_getcount) (ArkUI_ActiveChildrenInfo \*handle) | Obtains the number of nodes in the specified **ActiveChildrenInfo** instance. | -| [ArkUI_StyledString](#arkui_styledstring) \* [OH_ArkUI_StyledString_Create](#oh_arkui_styledstring_create) (OH_Drawing_TypographyStyle \*style, OH_Drawing_FontCollection \*collection) | Creates an **OH_Drawing_TextStyle** object. | -| void [OH_ArkUI_StyledString_Destroy](#oh_arkui_styledstring_destroy) ([ArkUI_StyledString](#arkui_styledstring) \*handle) | Destroys an **OH_Drawing_FontCollection** object and reclaims the memory occupied by the object. | -| void [OH_ArkUI_StyledString_PushTextStyle](#oh_arkui_styledstring_pushtextstyle) ([ArkUI_StyledString](#arkui_styledstring) \*handle, OH_Drawing_TextStyle \*style) | Pushes a text style to the top of the style stack of a styled string. | -| void [OH_ArkUI_StyledString_AddText](#oh_arkui_styledstring_addtext) ([ArkUI_StyledString](#arkui_styledstring) \*handle, const char \*content) | Adds text for a styled string. | -| void [OH_ArkUI_StyledString_PopTextStyle](#oh_arkui_styledstring_poptextstyle) ([ArkUI_StyledString](#arkui_styledstring) \*handle) | Pops the style at the top of the style stack of a styled string. | -| OH_Drawing_Typography \* [OH_ArkUI_StyledString_CreateTypography](#oh_arkui_styledstring_createtypography) ([ArkUI_StyledString](#arkui_styledstring) \*handle) | Creates an **OH_Drawing_Typography** object based on an **ArkUI_StyledString** object. | -| void [OH_ArkUI_StyledString_AddPlaceholder](#oh_arkui_styledstring_addplaceholder) ([ArkUI_StyledString](#arkui_styledstring) \*handle, OH_Drawing_PlaceholderSpan \*placeholder) | Adds a placeholder. | +| [ArkUI_StyledString](#arkui_styledstring) \* [OH_ArkUI_StyledString_Create](#oh_arkui_styledstring_create) (OH_Drawing_TypographyStyle \*style, OH_Drawing_FontCollection \*collection) | Creates an **OH_Drawing_TextStyle** object. | +| void [OH_ArkUI_StyledString_Destroy](#oh_arkui_styledstring_destroy) ([ArkUI_StyledString](#arkui_styledstring) \*handle) | Destroys an **OH_Drawing_FontCollection** object and reclaims the memory occupied by the object. | +| void [OH_ArkUI_StyledString_PushTextStyle](#oh_arkui_styledstring_pushtextstyle) ([ArkUI_StyledString](#arkui_styledstring) \*handle, OH_Drawing_TextStyle \*style) | Pushes a text style to the top of the style stack of a styled string. | +| void [OH_ArkUI_StyledString_AddText](#oh_arkui_styledstring_addtext) ([ArkUI_StyledString](#arkui_styledstring) \*handle, const char \*content) | Adds text for a styled string. | +| void [OH_ArkUI_StyledString_PopTextStyle](#oh_arkui_styledstring_poptextstyle) ([ArkUI_StyledString](#arkui_styledstring) \*handle) | Pops the style at the top of the style stack of a styled string. | +| OH_Drawing_Typography \* [OH_ArkUI_StyledString_CreateTypography](#oh_arkui_styledstring_createtypography) ([ArkUI_StyledString](#arkui_styledstring) \*handle) | Creates an **OH_Drawing_Typography** object based on an **ArkUI_StyledString** object. | +| void [OH_ArkUI_StyledString_AddPlaceholder](#oh_arkui_styledstring_addplaceholder) ([ArkUI_StyledString](#arkui_styledstring) \*handle, OH_Drawing_PlaceholderSpan \*placeholder) | Adds a placeholder. | | [ArkUI_StyledString_Descriptor](#arkui_styledstring_descriptor) \* [OH_ArkUI_StyledString_Descriptor_Create](#oh_arkui_styledstring_descriptor_create) (void) | Creates an **ArkUI_StyledString_Descriptor** object. | -| void [OH_ArkUI_StyledString_Descriptor_Destroy](#oh_arkui_styledstring_descriptor_destroy) ([ArkUI_StyledString_Descriptor](#arkui_styledstring_descriptor) \*descriptor) | Destroys an **ArkUI_StyledString_Descriptor** object and reclaims the memory occupied by the object. | +| void [OH_ArkUI_StyledString_Descriptor_Destroy](#oh_arkui_styledstring_descriptor_destroy) ([ArkUI_StyledString_Descriptor](#arkui_styledstring_descriptor) \*descriptor) | Destroys an **ArkUI_StyledString_Descriptor** object and reclaims the memory occupied by the object. | | int32_t [OH_ArkUI_UnmarshallStyledStringDescriptor](#oh_arkui_unmarshallstyledstringdescriptor) (uint8_t \*buffer, size_t bufferSize, [ArkUI_StyledString_Descriptor](#arkui_styledstring_descriptor) \*descriptor, size_t \*resultSize) | Deserializes a byte array containing styled string information into a styled string. | | int32_t [OH_ArkUI_MarshallStyledStringDescriptor](#oh_arkui_marshallstyledstringdescriptor) (uint8_t \*buffer, size_t bufferSize, [ArkUI_StyledString_Descriptor](#arkui_styledstring_descriptor) \*descriptor) | Serializes the styled string information into a byte array. | -| const char \* [OH_ArkUI_ConvertToHtml](#oh_arkui_converttohtml) ([ArkUI_StyledString_Descriptor](#arkui_styledstring_descriptor) \*descriptor) | Converts styled string information into HTML. | +| const char \* [OH_ArkUI_ConvertToHtml](#oh_arkui_converttohtml) ([ArkUI_StyledString_Descriptor](#arkui_styledstring_descriptor) \*descriptor) | Converts styled string information into HTML. | | int32_t [OH_ArkUI_PostFrameCallback](#oh_arkui_postframecallback)([ArkUI_ContextHandle](#arkui_contexthandle-12) uiContext, void\* userData, void (\*callback)(uint64_t nanoTimestamp, uint32_t frameCount, void\* userData))| Registers a callback to be executed after the next frame is rendered. This callback must not be called from a non-UI thread. The application will abort if a non-UI thread call is detected.| | int32_t [OH_ArkUI_RegisterLayoutCallbackOnNodeHandle](#oh_arkui_registerlayoutcallbackonnodehandle)([ArkUI_NodeHandle](#arkui_nodehandle) node, void\* userData, void (\*onLayoutCompleted)(void\* userData))| Registers a layout completion callback function for a specific component. Only one layout completion callback can be registered per component. | | int32_t [OH_ArkUI_RegisterDrawCallbackOnNodeHandle](#oh_arkui_registerdrawcallbackonnodehandle)([ArkUI_NodeHandle](#arkui_nodehandle) node, void\* userData, void (\*onDrawCompleted)(void\* userData))| Registers a drawing completion callback function for a specific component. Only one drawing completion callback can be registered per component. | @@ -757,6 +842,33 @@ ARKUI_ERROR_CODE_FOCUS_NON_FOCUSABLE_ANCESTOR = 150002,ARKUI_ERROR_CODE_FOCUS_NO | void OH_ArkUI_FocusClear([ArkUI_ContextHandle](_ark_u_i___native_module.md#arkui_contexthandle-12) uiContext); | Clears the focus to the root container node.| | void OH_ArkUI_FocusActivate([ArkUI_ContextHandle](_ark_u_i___native_module.md#arkui_contexthandle-12) uiContext, bool isActive, bool isAutoInactive); | Sets the focus activation state for the current page. When activated, the focused node displays a focus box.| | void OH_ArkUI_FocusSetAutoTransfer([ArkUI_ContextHandle](_ark_u_i___native_module.md#arkui_contexthandle-12) uiContext, bool autoTransfer); | Configures the focus transfer behavior when pages are switched.| +| void OH_ArkUI_FocusSetKeyProcessingMode([ArkUI_ContextHandle](_ark_u_i___native_module.md#arkui_contexthandle-12) uiContext, ArkUI_KeyProcessingMode mode); | Sets the mode for processing key events.| +| void [OH_ArkUI_DragEvent_StartDataLoading](#oh_arkui_dragevent_startdataloading)([ArkUI_DragEvent](_ark_u_i___native_module.md#arkui_dragevent)\* event, [OH_UdmfGetDataParams](#oh_udmfgetdataparams)\* options, char\* key, unsigned int keyLen); | Sets whether to enable data prefetching for drag and drop operations on a specified node.| +| void OH_ArkUI_[CancelDataLoading](#oh_arkui_canceldataloading)([ArkUI_Context](_ark_u_i___native_module.md#arkui_context) uiContext, const char\* key); | Cancels the asynchronous obtaining of drag data.| +| void OH_ArkUI_[DisableDropDataPrefetchOnNode](#oh_arkui_disabledropdataprefetchonnode)([ArkUI_NodeHandle](_ark_u_i___native_module.md#arkui_nodehandle) node, bool disable); | Sets whether to enable data prefetching for drag and drop operations on a specified node. The value **true** means to disable data prefetching, and **false** means to enable data prefetching. The default value is **false**.| +| [ArkUI_ProgressLinearStyleOption](#arkui_progresslinearstyleoption)\* [OH_ArkUI_ProgressLinearStyleOption_Create](#oh_arkui_progresslinearstyleoption_create)(void) | Creates a **ProgressLinearStyleOption** instance.| +| void [OH_ArkUI_ProgressLinearStyleOption_Destroy](#oh_arkui_progresslinearstyleoption_destroy)([ArkUI_ProgressLinearStyleOption](#arkui_progresslinearstyleoption)* option) | Destroys a **ProgressLinearStyleOption** instance.| +| void [OH_ArkUI_ProgressLinearStyleOption_SetScanEffectEnabled](#oh_arkui_progresslinearstyleoption_setscaneffectenabled)([ArkUI_ProgressLinearStyleOption](#arkui_progresslinearstyleoption)\* option, bool enabled) | Sets whether to enable the smooth progress effect for the linear progress indicator.| +| void [OH_ArkUI_ProgressLinearStyleOption_SetSmoothEffectEnabled](#oh_arkui_progresslinearstyleoption_setsmootheffectenabled)([ArkUI_ProgressLinearStyleOption](#arkui_progresslinearstyleoption)\* option, bool enabled) | Sets whether to enable the scan effect for the linear progress indicator.| +| void [OH_ArkUI_ProgressLinearStyleOption_SetStrokeWidth](#oh_arkui_progresslinearstyleoption_setstrokewidth)([ArkUI_ProgressLinearStyleOption](#arkui_progresslinearstyleoption)\* option, float strokeWidth) | Sets the stroke width of the linear progress indicator.| +| void [OH_ArkUI_ProgressLinearStyleOption_SetStrokeRadius](#oh_arkui_progresslinearstyleoption_setstrokeradius)([ArkUI_ProgressLinearStyleOption](#arkui_progresslinearstyleoption)\* option, float strokeRadius) | Sets the corner radius of the linear progress indicator.| +| bool [OH_ArkUI_ProgressLinearStyleOption_GetScanEffectEnabled](#oh_arkui_progresslinearstyleoption_getscaneffectenabled)([ArkUI_ProgressLinearStyleOption](#arkui_progresslinearstyleoption)\* option) | Obtains the enabled status of the smooth progress effect for the linear progress indicator.| +| bool [OH_ArkUI_ProgressLinearStyleOption_GetSmoothEffectEnabled](#oh_arkui_progresslinearstyleoption_getsmootheffectenabled)([ArkUI_ProgressLinearStyleOption](#arkui_progresslinearstyleoption)\* option) | Obtains the enabled status of the scan effect for the linear progress indicator.| +| float [OH_ArkUI_ProgressLinearStyleOption_GetStrokeWidth](#oh_arkui_progresslinearstyleoption_getstrokewidth)([ArkUI_ProgressLinearStyleOption](#arkui_progresslinearstyleoption)\* option) | Obtains the stroke width of the linear progress indicator.| +| float [OH_ArkUI_ProgressLinearStyleOption_GetStrokeRadius](#oh_arkui_progresslinearstyleoption_getstrokeradius)([ArkUI_ProgressLinearStyleOption](#arkui_progresslinearstyleoption)\* option) | Obtains the corner radius of the linear progress indicator.| +| int32_t [OH_ArkUI_NodeUtils_GetPositionToParent](#oh_arkui_nodeutils_getpositiontoparent) ([ArkUI_NodeHandle](#arkui_nodehandle) node, [ArkUI_IntOffset](_ark_u_i___int_offset.md)\* globalOffset) | Obtains the offset of a specific node relative to its parent node. | +| int32_t [OH_ArkUI_GetGestureParam_DirectMask](#oh_arkui_getgestureparam_directmask) (ArkUI_GestureRecognizer \*recognizer, [ArkUI_GestureDirectionMask](#arkui_gesturedirectionmask)\* directMask) | Obtains the swipe direction of a gesture recognizer.| +| int32_t [OH_ArkUI_GetGestureParam_FingerCount](#oh_arkui_getgestureparam_fingercount) (ArkUI_GestureRecognizer \*recognizer, int\* finger) | Obtains the number of fingers used by a gesture recognizer.| +| int32_t [OH_ArkUI_GetGestureParam_limitFingerCount](#oh_arkui_getgestureparam_limitfingercount) (ArkUI_GestureRecognizer \*recognizer, bool\* isLimited) | Checks whether a gesture recognizer has a finger count limit. | +| int32_t [OH_ArkUI_GetGestureParam_repeat](#oh_arkui_getgestureparam_repeat) (ArkUI_GestureRecognizer \*recognizer, bool\* isRepeat) | Checks whether a gesture recognizer supports repeated event callbacks.| +| int32_t [OH_ArkUI_GetGestureParam_distance](#oh_arkui_getgestureparam_distance) (ArkUI_GestureRecognizer \*recognizer, double\* distance) | Obtains the allowed movement distance range for a gesture recognizer.| +| int32_t [OH_ArkUI_GetGestureParam_speed](#oh_arkui_getgestureparam_speed) (ArkUI_GestureRecognizer \*recognizer, double\* speed) | Obtains the minimum swipe speed recognized by a gesture recognizer.| +| int32_t [OH_ArkUI_GetGestureParam_duration](#oh_arkui_getgestureparam_duration) (ArkUI_GestureRecognizer \*recognizer, int\* duration) | Obtains the minimum duration required to trigger a long press by a gesture recognizer.| +| int32_t [OH_ArkUI_GetGestureParam_angle](#oh_arkui_getgestureparam_angle) (ArkUI_GestureRecognizer \*recognizer, double\* angle) | Obtains the minimum angle change required for a rotation gesture to be recognized by a gesture recognizer.| +| int32_t [OH_ArkUI_GetGestureParam_distanceThreshold](#oh_arkui_getgestureparam_distancethreshold) (ArkUI_GestureRecognizer \*recognizer, double\* distanceThreshold) | Obtains the movement threshold for gestures to be recognized by a gesture recognizer.| +|int32_t [OH_ArkUI_DragEvent_RequestDragEndPending](#oh_arkui_dragevent_requestdragendpending)([ArkUI_DragEvent](_ark_u_i___native_module.md#arkui_dragevent)\* event, int32_t* requestIdentify); | Requests a delayed execution of the end of the drag and drop operation.| +|int32_t [OH_ArkUI_NotifyDragResult](#oh_arkui_notifydragresult)(int32_t requestIdentify, [ArkUI_DragResult](#arkui_dragresult) \* result); | Notifies the system of the drag result.| +|int32_t [OH_ArkUI_NotifyDragEndPendingDone](#oh_arkui_notifydragendpendingdone)(int32_t requestIdentify);| Notifies that the drag delay execution is complete.| ## Macro Description @@ -970,6 +1082,17 @@ Defines a struct for a dialog box dismiss event. **Since**: 12 +### ArkUI_CustomDialogOptions + +``` +typedef struct ArkUI_CustomDialogOptions ArkUI_CustomDialogOptions +``` +**Description** + +Defines a struct for custom dialog box options. + +**Since**: 16 + ### ArkUI_DragAction @@ -994,7 +1117,6 @@ Defines a struct for drag and drop information returned through a drag status li **Since**: 12 - ### ArkUI_DragEvent ``` @@ -1117,6 +1239,29 @@ Defines the gesture recognizer handle array. **Since**: 12 +### ArkUI_TouchRecognizerHandle + +``` +typedef ArkUI_TouchRecognizer* ArkUI_TouchRecognizerHandle +``` +**Description** + +Defines the gesture recognizer handle. + +**Since**: 15 + + +### ArkUI_TouchRecognizerHandleArray + +``` +typedef ArkUI_TouchRecognizerHandle* ArkUI_TouchRecognizerHandleArray +``` +**Description** + +Defines an array of gesture recognizer handles. + +**Since**: 15 + ### ArkUI_GuidelineOption ``` @@ -1345,6 +1490,19 @@ Defines a parallel internal gesture event. **Since**: 12 +### ArkUI_GestureInterruptInfo + +``` +typedef struct ArkUI_GestureInterruptInfo ArkUI_GestureInterruptInfo +``` + +**Description** + +Defines the gesture interruption information. + +**Since**: 12 + + ### ArkUI_StyledString ``` @@ -1376,7 +1534,7 @@ typedef struct ArkUI_SwiperIndicator ArkUI_SwiperIndicator ``` **Description** -Defines the navigation point indicator style of the **Swiper** component. +Defines the navigation indicator style of the **Swiper** component. **Since**: 12 @@ -1392,6 +1550,27 @@ Defines a struct for the system font style event. **Since**: 12 +### ArkUI_SwiperDigitIndicator + +``` +typedef struct ArkUI_SwiperDigitIndicator ArkUI_SwiperDigitIndicator +``` +**Description** + +Defines the digit-style navigation indicator of the **Swiper** component. + +**Since**: 15 + +### ArkUI_SwiperArrowStyle + +``` +typedef struct ArkUI_SwiperArrowStyle ArkUI_SwiperArrowStyle +``` +**Description** + +Defines the arrow style for the **Swiper** component. + +**Since**: 15 ### ArkUI_TransitionEffect @@ -1453,6 +1632,73 @@ Defines a struct for UDMF unified data. **Since**: 12 +### ArkUI_ProgressLinearStyleOption + +``` +typedef struct ArkUI_ProgressLinearStyleOption ArkUI_ProgressLinearStyleOption +``` +**Description** + +Defines the style information for a linear progress indicator in the **Progress** component. + +**Since**: 15 + +### OH_HostWindowInfo + +``` +typedef struct ArkUI_HostWindowInfo ArkUI_HostWindowInfo +``` +**Description** + +Defines a struct for the host window information. + +**Since**: 15 + + +### OH_UdmfGetDataParams + +``` +typedef struct OH_UdmfGetDataParams OH_UdmfGetDataParams +``` +**Description** + +Defines the parameters used for obtaining data from UDMF. + +**Since**: 15 + +### ArkUI_VisibleAreaEventOptions + +``` +typedef struct ArkUI_VisibleAreaEventOptions ArkUI_VisibleAreaEventOptions +``` +**Description** + +Defines the parameters for visible area change events. + +**Since**: 18 + + +### ArkUI_TextPickerRangeContentArray +``` +typedef struct ArkUI_TextPickerRangeContentArray ArkUI_TextPickerRangeContentArray +``` +**Description** + +Defines the data selection list for the text picker. + +**Since**: 18 + +### ArkUI_TextCascadePickerRangeContentArray + +``` +typedef struct ArkUI_TextCascadePickerRangeContentArray ArkUI_TextCascadePickerRangeContentArray +``` +**Description** + +Defines the content array for a multi-column cascading data picker. + +**Since**: 18 + ## Enum Description @@ -1467,13 +1713,13 @@ Defines an enum for the accessibility action types. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_ACCESSIBILITY_ACTION_CLICK | Tapping. | -| ARKUI_ACCESSIBILITY_ACTION_LONG_CLICK | Long press. | -| ARKUI_ACCESSIBILITY_ACTION_CUT | Cut. | -| ARKUI_ACCESSIBILITY_ACTION_COPY | Copy. | -| ARKUI_ACCESSIBILITY_ACTION_PASTE | Paste. | +| ARKUI_ACCESSIBILITY_ACTION_CLICK | Tapping | +| ARKUI_ACCESSIBILITY_ACTION_LONG_CLICK | Long press | +| ARKUI_ACCESSIBILITY_ACTION_CUT | Cut. | +| ARKUI_ACCESSIBILITY_ACTION_COPY | | +| ARKUI_ACCESSIBILITY_ACTION_PASTE | Paste. | ### ArkUI_AccessibilityCheckedState @@ -1487,10 +1733,10 @@ Enumerates the accessibility check box states. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_ACCESSIBILITY_UNCHECKED | The check box is not selected. | -| ARKUI_ACCESSIBILITY_CHECKED | The check box is selected. | +| ARKUI_ACCESSIBILITY_UNCHECKED | The check box is not selected. | +| ARKUI_ACCESSIBILITY_CHECKED | The check box is selected. | ### ArkUI_AccessibilityMode @@ -1504,12 +1750,12 @@ Enumerates the accessibility modes. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_ACCESSIBILITY_MODE_AUTO | The mode is automatically set to enabled or disabled based on the component. | -| ARKUI_ACCESSIBILITY_MODE_ENABLED | The component can be identified by the accessibility service. | -| ARKUI_ACCESSIBILITY_MODE_DISABLED | The component cannot be identified by the accessibility service. | -| ARKUI_ACCESSIBILITY_MODE_DISABLED_FOR_DESCENDANTS | The component and all its child components cannot be identified by the accessibility service. | +| ARKUI_ACCESSIBILITY_MODE_AUTO | The mode is automatically set to enabled or disabled based on the component. | +| ARKUI_ACCESSIBILITY_MODE_ENABLED | The component can be identified by the accessibility service. | +| ARKUI_ACCESSIBILITY_MODE_DISABLED | The component cannot be identified by the accessibility service. | +| ARKUI_ACCESSIBILITY_MODE_DISABLED_FOR_DESCENDANTS | The component and all its child components cannot be identified by the accessibility service. | ### ArkUI_AdaptiveColor @@ -1523,10 +1769,10 @@ Enumerates the adaptive color modes. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_ADAPTIVE_COLOR_DEFAULT | Adaptive color mode is not used. | -| ARKUI_ADAPTIVE_COLOR_AVERAGE | Adaptive color mode is used. | +| ARKUI_ADAPTIVE_COLOR_DEFAULT | Adaptive color mode is not used. | +| ARKUI_ADAPTIVE_COLOR_AVERAGE | Adaptive color mode is used. | ### ArkUI_Alignment @@ -1540,17 +1786,17 @@ Enumerates the alignment modes. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_ALIGNMENT_TOP_START | Top start. | -| ARKUI_ALIGNMENT_TOP | Top center. | -| ARKUI_ALIGNMENT_TOP_END | Top end. | -| ARKUI_ALIGNMENT_START | Vertically centered start. | -| ARKUI_ALIGNMENT_CENTER | Horizontally and vertically centered. | -| ARKUI_ALIGNMENT_END | Vertically centered end. | -| ARKUI_ALIGNMENT_BOTTOM_START | Bottom start. | -| ARKUI_ALIGNMENT_BOTTOM | Horizontally centered on the bottom. | -| ARKUI_ALIGNMENT_BOTTOM_END | Bottom end. | +| ARKUI_ALIGNMENT_TOP_START | Top start. | +| ARKUI_ALIGNMENT_TOP | Top center. | +| ARKUI_ALIGNMENT_TOP_END | Top end. | +| ARKUI_ALIGNMENT_START | Vertically centered start. | +| ARKUI_ALIGNMENT_CENTER | Horizontally and vertically centered. | +| ARKUI_ALIGNMENT_END | Vertically centered end. | +| ARKUI_ALIGNMENT_BOTTOM_START | Bottom start. | +| ARKUI_ALIGNMENT_BOTTOM | Horizontally centered on the bottom. | +| ARKUI_ALIGNMENT_BOTTOM_END | Bottom end. | ### ArkUI_AnimationCurve @@ -1564,21 +1810,21 @@ Enumerates the animation curves. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_CURVE_LINEAR | The animation speed keeps unchanged. | -| ARKUI_CURVE_EASE | The animation starts slowly, accelerates, and then slows down towards the end. | -| ARKUI_CURVE_EASE_IN | The animation starts at a low speed and then picks up speed until the end. | -| ARKUI_CURVE_EASE_OUT | The animation ends at a low speed. | -| ARKUI_CURVE_EASE_IN_OUT | The animation starts and ends at a low speed. | -| ARKUI_CURVE_FAST_OUT_SLOW_IN | The animation uses the standard curve | -| ARKUI_CURVE_LINEAR_OUT_SLOW_IN | The animation uses the deceleration curve. | -| ARKUI_CURVE_FAST_OUT_LINEAR_IN | The animation uses the acceleration curve. | -| ARKUI_CURVE_EXTREME_DECELERATION | The animation uses the extreme deceleration curve. | -| ARKUI_CURVE_SHARP | The animation uses the sharp curve. | -| ARKUI_CURVE_RHYTHM | The animation uses the rhythm curve. | -| ARKUI_CURVE_SMOOTH | The animation uses the smooth curve. | -| ARKUI_CURVE_FRICTION | The animation uses the friction curve | +| ARKUI_CURVE_LINEAR | The animation speed keeps unchanged. | +| ARKUI_CURVE_EASE | The animation starts slowly, accelerates, and then slows down towards the end. | +| ARKUI_CURVE_EASE_IN | The animation starts at a low speed and then picks up speed until the end. | +| ARKUI_CURVE_EASE_OUT | The animation ends at a low speed. | +| ARKUI_CURVE_EASE_IN_OUT | The animation starts and ends at a low speed. | +| ARKUI_CURVE_FAST_OUT_SLOW_IN | The animation uses the standard curve | +| ARKUI_CURVE_LINEAR_OUT_SLOW_IN | The animation uses the deceleration curve. | +| ARKUI_CURVE_FAST_OUT_LINEAR_IN | The animation uses the acceleration curve. | +| ARKUI_CURVE_EXTREME_DECELERATION | The animation uses the extreme deceleration curve. | +| ARKUI_CURVE_SHARP | The animation uses the sharp curve. | +| ARKUI_CURVE_RHYTHM | The animation uses the rhythm curve. | +| ARKUI_CURVE_SMOOTH | The animation uses the smooth curve. | +| ARKUI_CURVE_FRICTION | The animation uses the friction curve | ### ArkUI_AnimationDirection @@ -1592,12 +1838,12 @@ Enumerates the animation playback modes. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_ANIMATION_DIRECTION_NORMAL | The animation plays in forward loop mode. | -| ARKUI_ANIMATION_DIRECTION_REVERSE | The animation plays in reverse loop mode. | -| ARKUI_ANIMATION_DIRECTION_ALTERNATE | The animation plays in alternating loop mode. When the animation is played for an odd number of times, the playback is in forward direction. When the animation is played for an even number of times, the playback is in reverse direction. | -| ARKUI_ANIMATION_DIRECTION_ALTERNATE_REVERSE | The animation plays in reverse alternating loop mode. When the animation is played for an odd number of times, the playback is in reverse direction. When the animation is played for an even number of times, the playback is in forward direction. | +| ARKUI_ANIMATION_DIRECTION_NORMAL | The animation plays in forward loop mode. | +| ARKUI_ANIMATION_DIRECTION_REVERSE | The animation plays in reverse loop mode. | +| ARKUI_ANIMATION_DIRECTION_ALTERNATE | The animation plays in alternating loop mode. When the animation is played for an odd number of times, the playback is in forward direction. When the animation is played for an even number of times, the playback is in reverse direction. | +| ARKUI_ANIMATION_DIRECTION_ALTERNATE_REVERSE | The animation plays in reverse alternating loop mode. When the animation is played for an odd number of times, the playback is in reverse direction. When the animation is played for an even number of times, the playback is in forward direction. | ### ArkUI_AnimationFill @@ -1611,12 +1857,12 @@ Enumerates the state of the animated target after the animation is executed. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_ANIMATION_FILL_NONE | No style is applied to the target before or after the animation is executed. | -| ARKUI_ANIMATION_FILL_FORWARDS | The target keeps the state at the end of the animation (defined in the last key frame) after the animation is executed. | -| ARKUI_ANIMATION_FILL_BACKWARDS | The animation uses the value defined in the first key frame during the duration defined by **animation-delay**. | -| ARKUI_ANIMATION_FILL_BOTH | The animation follows the **forwards** and **backwards** rules. | +| ARKUI_ANIMATION_FILL_NONE | No style is applied to the target before or after the animation is executed. | +| ARKUI_ANIMATION_FILL_FORWARDS | The target keeps the state at the end of the animation (defined in the last key frame) after the animation is executed. | +| ARKUI_ANIMATION_FILL_BACKWARDS | The animation uses the value defined in the first key frame during the duration defined by **animation-delay**. | +| ARKUI_ANIMATION_FILL_BOTH | The animation follows the **forwards** and **backwards** rules. | ### ArkUI_AnimationFillMode @@ -1630,12 +1876,12 @@ Enumerates the states before and after execution of the frame-by-frame animation **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_ANIMATION_FILL_MODE_NONE | Before execution, the animation does not apply any styles to the target component. After execution, the animation restores the target component to its default state. | -| ARKUI_ANIMATION_FILL_MODE_FORWARDS | The target component retains the state set by the last keyframe encountered during execution of the animation. | -| ARKUI_ANIMATION_FILL_MODE_BACKWARDS | The animation applies the values defined in the first relevant keyframe once it is applied to the target component, and retains the values during the period set by **delay**. | -| ARKUI_ANIMATION_FILL_MODE_BOTH | The animation follows the rules for both **Forwards** and **Backwards**, extending the animation attributes in both directions. | +| ARKUI_ANIMATION_FILL_MODE_NONE | Before execution, the animation does not apply any styles to the target component. After execution, the animation restores the target component to its default state. | +| ARKUI_ANIMATION_FILL_MODE_FORWARDS | The target component retains the state set by the last keyframe encountered during execution of the animation. | +| ARKUI_ANIMATION_FILL_MODE_BACKWARDS | The animation applies the values defined in the first relevant keyframe once it is applied to the target component, and retains the values during the period set by **delay**. | +| ARKUI_ANIMATION_FILL_MODE_BOTH | The animation follows the rules for both **Forwards** and **Backwards**, extending the animation attributes in both directions. | ### ArkUI_AnimationPlayMode @@ -1649,12 +1895,12 @@ Enumerates the animation playback modes. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_ANIMATION_PLAY_MODE_NORMAL | The animation is played forwards. | -| ARKUI_ANIMATION_PLAY_MODE_REVERSE | The animation is played backwards. | -| ARKUI_ANIMATION_PLAY_MODE_ALTERNATE | The animation is played forwards for an odd number of times (1, 3, 5...) and backwards for an even number of times (2, 4, 6...). | -| ARKUI_ANIMATION_PLAY_MODE_ALTERNATE_REVERSE | The animation is played backwards for an odd number of times (1, 3, 5...) and forwards for an even number of times (2, 4, 6...). | +| ARKUI_ANIMATION_PLAY_MODE_NORMAL | The animation is played forwards. | +| ARKUI_ANIMATION_PLAY_MODE_REVERSE | The animation is played backwards. | +| ARKUI_ANIMATION_PLAY_MODE_ALTERNATE | The animation is played forwards for an odd number of times (1, 3, 5...) and backwards for an even number of times (2, 4, 6...). | +| ARKUI_ANIMATION_PLAY_MODE_ALTERNATE_REVERSE | The animation is played backwards for an odd number of times (1, 3, 5...) and forwards for an even number of times (2, 4, 6...). | ### ArkUI_AnimationStatus @@ -1668,12 +1914,12 @@ Enumerates the playback states of the frame-by-frame animation. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_ANIMATION_STATUS_INITIAL | The animation is in the initial state. | -| ARKUI_ANIMATION_STATUS_RUNNING | The animation is being played. | -| ARKUI_ANIMATION_STATUS_PAUSED | The animation is paused. | -| ARKUI_ANIMATION_STATUS_STOPPED | The animation is stopped. | +| ARKUI_ANIMATION_STATUS_INITIAL | The animation is in the initial state. | +| ARKUI_ANIMATION_STATUS_RUNNING | The animation is being played. | +| ARKUI_ANIMATION_STATUS_PAUSED | The animation is paused. | +| ARKUI_ANIMATION_STATUS_STOPPED | The animation is stopped. | ### ArkUI_Axis @@ -1687,10 +1933,10 @@ Enumerates the scroll directions. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_AXIS_VERTICAL | Only vertical scrolling is supported. | -| ARKUI_AXIS_HORIZONTAL | Only horizontal scrolling is supported. | +| ARKUI_AXIS_VERTICAL | Only vertical scrolling is supported. | +| ARKUI_AXIS_HORIZONTAL | Only horizontal scrolling is supported. | ### ArkUI_BarrierDirection @@ -1704,12 +1950,12 @@ Enumerates the barrier directions. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_BARRIER_DIRECTION_START | The barrier is on the left side of all the referenced components specified by referencedId. | -| ARKUI_BARRIER_DIRECTION_END | The barrier is on the right side of all the referenced components specified by referencedId. | -| ARKUI_BARRIER_DIRECTION_TOP | The barrier is at the top of all the referenced components specified by referencedId. | -| ARKUI_BARRIER_DIRECTION_BOTTOM | The barrier is at the bottom of all the referenced components specified by referencedId. | +| ARKUI_BARRIER_DIRECTION_START | The barrier is on the left side of all the referenced components specified by referencedId. | +| ARKUI_BARRIER_DIRECTION_END | The barrier is on the right side of all the referenced components specified by referencedId. | +| ARKUI_BARRIER_DIRECTION_TOP | The barrier is at the top of all the referenced components specified by referencedId. | +| ARKUI_BARRIER_DIRECTION_BOTTOM | The barrier is at the bottom of all the referenced components specified by referencedId. | ### ArkUI_BlendApplyType @@ -1723,10 +1969,10 @@ Defines how the specified blend mode is applied. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| BLEND_APPLY_TYPE_FAST | The content of the view is blended in sequence on the target image. | -| BLEND_APPLY_TYPE_OFFSCREEN | The content of the component and its child components are drawn on the offscreen canvas, and then blended with the existing content on the canvas. | +| BLEND_APPLY_TYPE_FAST | The content of the view is blended in sequence on the target image. | +| BLEND_APPLY_TYPE_OFFSCREEN | The content of the component and its child components are drawn on the offscreen canvas, and then blended with the existing content on the canvas. | ### ArkUI_BlendMode @@ -1740,38 +1986,38 @@ Enumerates the blend modes. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_BLEND_MODE_NONE | The top image is superimposed on the bottom image without any blending. | -| ARKUI_BLEND_MODE_CLEAR | The target pixels covered by the source pixels are erased by being turned to completely transparent. | -| ARKUI_BLEND_MODE_SRC | r = s: Only the source pixels are displayed. | -| ARKUI_BLEND_MODE_DST | r = d: Only the target pixels are displayed. | -| ARKUI_BLEND_MODE_SRC_OVER | r = s + (1 - sa) \d: The source pixels are blended based on opacity and cover the target pixels. | -| ARKUI_BLEND_MODE_DST_OVER | r = d + (1 - da) *\ s: The target pixels are blended based on opacity and cover on the source pixels. | -| ARKUI_BLEND_MODE_SRC_IN | r = s \* da: Only the part of the source pixels that overlap with the target pixels is displayed. | -| ARKUI_BLEND_MODE_DST_IN | r = d \* sa: Only the part of the target pixels that overlap with the source pixels is displayed. | -| ARKUI_BLEND_MODE_SRC_OUT | r = s \* (1 - da): Only the part of the source pixels that do not overlap with the target pixels is displayed. | -| ARKUI_BLEND_MODE_DST_OUT | r = d \* (1 - sa): Only the part of the target pixels that do not overlap with the source pixels is displayed. | -| ARKUI_BLEND_MODE_SRC_ATOP | r = s \da + d \(1 - sa): The part of the source pixels that overlap with the target pixels is displayed and the part of the target pixels that do not overlap with the source pixels are displayed. | -| ARKUI_BLEND_MODE_DST_ATOP | r = d \sa + s \(1 - da): The part of the target pixels that overlap with the source pixels and the part of the source pixels that do not overlap with the target pixels are displayed. | -| ARKUI_BLEND_MODE_XOR | r = s \* (1 - da) + d \* (1 - sa): Only the non-overlapping part between the source pixels and the target pixels is displayed. | -| ARKUI_BLEND_MODE_PLUS | r = min(s + d, 1): New pixels resulting from adding the source pixels to the target pixels are displayed. | -| ARKUI_BLEND_MODE_MODULATE | r = s \* d: New pixels resulting from multiplying the source pixels with the target pixels are displayed. | -| ARKUI_BLEND_MODE_SCREEN | r = s + d - s \* d: Pixels are blended by adding the source pixels to the target pixels and subtracting the product of their multiplication. | -| ARKUI_BLEND_MODE_OVERLAY | The MULTIPLY or SCREEN mode is used based on the target pixels. | -| ARKUI_BLEND_MODE_DARKEN | rc = s + d - max(s \da, d \sa), ra = kSrcOver: When two colors overlap, whichever is darker is used. | -| ARKUI_BLEND_MODE_LIGHTEN | rc = s + d - min(s \da, d \sa), ra = kSrcOver: The darker of the pixels (source and target) is used. | -| ARKUI_BLEND_MODE_COLOR_DODGE | The colors of the target pixels are lightened to reflect the source pixels. | -| ARKUI_BLEND_MODE_COLOR_BURN | The colors of the target pixels are darkened to reflect the source pixels. | -| ARKUI_BLEND_MODE_HARD_LIGHT | The MULTIPLY or SCREEN mode is used, depending on the source pixels. | -| ARKUI_BLEND_MODE_SOFT_LIGHT | The LIGHTEN or DARKEN mode is used, depending on the source pixels. | -| ARKUI_BLEND_MODE_DIFFERENCE | rc = s + d - 2 \* (min(s \* da, d \vsa)), ra = kSrcOver: The final pixel is the result of subtracting the darker of the two pixels (source and target) from the lighter one. | -| ARKUI_BLEND_MODE_EXCLUSION | rc = s + d - two(s \* d), ra = kSrcOver: The final pixel is similar to **DIFFERENCE**, but with less contrast. | -| ARKUI_BLEND_MODE_MULTIPLY | r = s \* (1 - da) + d \* (1 - sa) + s \* d: The final pixel is the result of multiplying the source pixel by the target pixel.| -| ARKUI_BLEND_MODE_HUE | The resultant image is created with the luminance and saturation of the source image and the hue of the target image. | -| ARKUI_BLEND_MODE_SATURATION | The resultant image is created with the luminance and hue of the target image and the saturation of the source image. | -| ARKUI_BLEND_MODE_COLOR | The resultant image is created with the saturation and hue of the source image and the luminance of the target image. | -| ARKUI_BLEND_MODE_LUMINOSITY | The resultant image is created with the saturation and hue of the target image and the luminance of the source image. | +| ARKUI_BLEND_MODE_NONE | The top image is superimposed on the bottom image without any blending. | +| ARKUI_BLEND_MODE_CLEAR | The target pixels covered by the source pixels are erased by being turned to completely transparent. | +| ARKUI_BLEND_MODE_SRC | r = s: Only the source pixels are displayed. | +| ARKUI_BLEND_MODE_DST | r = d: Only the target pixels are displayed. | +| ARKUI_BLEND_MODE_SRC_OVER | r = s + (1 - sa) \d: The source pixels are blended based on opacity and cover the target pixels. | +| ARKUI_BLEND_MODE_DST_OVER | r = d + (1 - da) *\ s: The target pixels are blended based on opacity and cover on the source pixels. | +| ARKUI_BLEND_MODE_SRC_IN | r = s \* da: Only the part of the source pixels that overlap with the target pixels is displayed. | +| ARKUI_BLEND_MODE_DST_IN | r = d \* sa: Only the part of the target pixels that overlap with the source pixels is displayed. | +| ARKUI_BLEND_MODE_SRC_OUT | r = s \* (1 - da): Only the part of the source pixels that do not overlap with the target pixels is displayed. | +| ARKUI_BLEND_MODE_DST_OUT | r = d \* (1 - sa): Only the part of the target pixels that do not overlap with the source pixels is displayed. | +| ARKUI_BLEND_MODE_SRC_ATOP | r = s \da + d \(1 - sa): The part of the source pixels that overlap with the target pixels is displayed and the part of the target pixels that do not overlap with the source pixels are displayed. | +| ARKUI_BLEND_MODE_DST_ATOP | r = d \sa + s \(1 - da): The part of the target pixels that overlap with the source pixels and the part of the source pixels that do not overlap with the target pixels are displayed. | +| ARKUI_BLEND_MODE_XOR | r = s \* (1 - da) + d \* (1 - sa): Only the non-overlapping part between the source pixels and the target pixels is displayed. | +| ARKUI_BLEND_MODE_PLUS | r = min(s + d, 1): New pixels resulting from adding the source pixels to the target pixels are displayed. | +| ARKUI_BLEND_MODE_MODULATE | r = s \* d: New pixels resulting from multiplying the source pixels with the target pixels are displayed. | +| ARKUI_BLEND_MODE_SCREEN | r = s + d - s \* d: Pixels are blended by adding the source pixels to the target pixels and subtracting the product of their multiplication. | +| ARKUI_BLEND_MODE_OVERLAY | The MULTIPLY or SCREEN mode is used based on the target pixels. | +| ARKUI_BLEND_MODE_DARKEN | rc = s + d - max(s \da, d \sa), ra = kSrcOver: When two colors overlap, whichever is darker is used. | +| ARKUI_BLEND_MODE_LIGHTEN | rc = s + d - min(s \da, d \sa), ra = kSrcOver: The darker of the pixels (source and target) is used. | +| ARKUI_BLEND_MODE_COLOR_DODGE | The colors of the target pixels are lightened to reflect the source pixels. | +| ARKUI_BLEND_MODE_COLOR_BURN | The colors of the target pixels are darkened to reflect the source pixels. | +| ARKUI_BLEND_MODE_HARD_LIGHT | The MULTIPLY or SCREEN mode is used, depending on the source pixels. | +| ARKUI_BLEND_MODE_SOFT_LIGHT | The LIGHTEN or DARKEN mode is used, depending on the source pixels. | +| ARKUI_BLEND_MODE_DIFFERENCE | rc = s + d - 2 \* (min(s \* da, d \vsa)), ra = kSrcOver: The final pixel is the result of subtracting the darker of the two pixels (source and target) from the lighter one. | +| ARKUI_BLEND_MODE_EXCLUSION | rc = s + d - two(s \* d), ra = kSrcOver: The final pixel is similar to **DIFFERENCE**, but with less contrast. | +| ARKUI_BLEND_MODE_MULTIPLY | r = s \* (1 - da) + d \* (1 - sa) + s \* d: The final pixel is the result of multiplying the source pixel by the target pixel.| +| ARKUI_BLEND_MODE_HUE | The resultant image is created with the luminance and saturation of the source image and the hue of the target image. | +| ARKUI_BLEND_MODE_SATURATION | The resultant image is created with the luminance and hue of the target image and the saturation of the source image. | +| ARKUI_BLEND_MODE_COLOR | The resultant image is created with the saturation and hue of the source image and the luminance of the target image. | +| ARKUI_BLEND_MODE_LUMINOSITY | The resultant image is created with the saturation and hue of the target image and the luminance of the source image. | ### ArkUI_BlurStyle @@ -1785,21 +2031,21 @@ Enumerates the blur styles. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_BLUR_STYLE_THIN | Thin material. | -| ARKUI_BLUR_STYLE_REGULAR | Regular material. | -| ARKUI_BLUR_STYLE_THICK | Thick material. | -| ARKUI_BLUR_STYLE_BACKGROUND_THIN | Material that creates the minimum depth of field effect. | -| ARKUI_BLUR_STYLE_BACKGROUND_REGULAR | Material that creates a medium shallow depth of field effect. | -| ARKUI_BLUR_STYLE_BACKGROUND_THICK | Material that creates a high shallow depth of field effect. | -| ARKUI_BLUR_STYLE_BACKGROUND_ULTRA_THICK | Material that creates the maximum depth of field effect. | -| ARKUI_BLUR_STYLE_NONE | No blur. | -| ARKUI_BLUR_STYLE_COMPONENT_ULTRA_THIN | Component ultra-thin material. | -| ARKUI_BLUR_STYLE_COMPONENT_THIN | Component thin material. | -| ARKUI_BLUR_STYLE_COMPONENT_REGULAR | Component regular material. | -| ARKUI_BLUR_STYLE_COMPONENT_THICK | Component thick material. | -| ARKUI_BLUR_STYLE_COMPONENT_ULTRA_THICK | Component ultra-thick material. | +| ARKUI_BLUR_STYLE_THIN | Thin material. | +| ARKUI_BLUR_STYLE_REGULAR | Regular material. | +| ARKUI_BLUR_STYLE_THICK | Thick material. | +| ARKUI_BLUR_STYLE_BACKGROUND_THIN | Material that creates the minimum depth of field effect. | +| ARKUI_BLUR_STYLE_BACKGROUND_REGULAR | Material that creates a medium shallow depth of field effect. | +| ARKUI_BLUR_STYLE_BACKGROUND_THICK | Material that creates a high shallow depth of field effect. | +| ARKUI_BLUR_STYLE_BACKGROUND_ULTRA_THICK | Material that creates the maximum depth of field effect. | +| ARKUI_BLUR_STYLE_NONE | No blur. | +| ARKUI_BLUR_STYLE_COMPONENT_ULTRA_THIN | Component ultra-thin material. | +| ARKUI_BLUR_STYLE_COMPONENT_THIN | Component thin material. | +| ARKUI_BLUR_STYLE_COMPONENT_REGULAR | Component regular material. | +| ARKUI_BLUR_STYLE_COMPONENT_THICK | Component thick material. | +| ARKUI_BLUR_STYLE_COMPONENT_ULTRA_THICK | Component ultra-thick material. | ### ArkUI_BorderStyle @@ -1813,11 +2059,11 @@ Enumerates the border styles. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_BORDER_STYLE_SOLID | Solid border. | -| ARKUI_BORDER_STYLE_DASHED | Dashed border. | -| ARKUI_BORDER_STYLE_DOTTED | Dotted border. | +| ARKUI_BORDER_STYLE_SOLID | Solid border. | +| ARKUI_BORDER_STYLE_DASHED | Dashed border. | +| ARKUI_BORDER_STYLE_DOTTED | Dotted border. | ### ArkUI_ButtonType @@ -1831,11 +2077,11 @@ Enumerates the button types. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_BUTTON_TYPE_NORMAL | Normal button (without rounded corners by default). | -| ARKUI_BUTTON_TYPE_CAPSULE | Capsule-type button (the round corner is half of the height by default). | -| ARKUI_BUTTON_TYPE_CIRCLE | Circle button. | +| ARKUI_BUTTON_TYPE_NORMAL | Normal button (without rounded corners by default). | +| ARKUI_BUTTON_TYPE_CAPSULE | Capsule-type button (the round corner is half of the height by default). | +| ARKUI_BUTTON_TYPE_CIRCLE | Circle button. | ### ArkUI_CalendarAlignment @@ -1849,11 +2095,11 @@ Enumerates the alignment modes between the calendar picker and the entry compone **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_CALENDAR_ALIGNMENT_START | Left aligned. | -| ARKUI_CALENDAR_ALIGNMENT_CENTER | Center aligned. | -| ARKUI_CALENDAR_ALIGNMENT_END | Right aligned. | +| ARKUI_CALENDAR_ALIGNMENT_START | Left aligned. | +| ARKUI_CALENDAR_ALIGNMENT_CENTER | Center aligned. | +| ARKUI_CALENDAR_ALIGNMENT_END | Right aligned. | ### ArkUI_CancelButtonStyle @@ -1867,11 +2113,11 @@ Enumerates the styles of the Cancel button. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_CANCELBUTTON_STYLE_CONSTANT | The Cancel button is always displayed. | -| ARKUI_CANCELBUTTON_STYLE_INVISIBLE | The Cancel button is always hidden. | -| ARKUI_CANCELBUTTON_STYLE_INPUT | The Cancel button is displayed when there is text input. | +| ARKUI_CANCELBUTTON_STYLE_CONSTANT | The Cancel button is always displayed. | +| ARKUI_CANCELBUTTON_STYLE_INVISIBLE | The Cancel button is always hidden. | +| ARKUI_CANCELBUTTON_STYLE_INPUT | The Cancel button is displayed when there is text input. | ### ArkUI_CheckboxShape @@ -1885,10 +2131,10 @@ Enumerates the shapes of the check box. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ArkUI_CHECKBOX_SHAPE_CIRCLE | Circle. | -| ArkUI_CHECKBOX_SHAPE_ROUNDED_SQUARE | Rounded square. | +| ArkUI_CHECKBOX_SHAPE_CIRCLE | Circle. | +| ArkUI_CHECKBOX_SHAPE_ROUNDED_SQUARE | Rounded square. | ### ArkUI_ClipType @@ -1902,12 +2148,12 @@ Enumerates the clipping region types. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_CLIP_TYPE_RECTANGLE | Rectangle. | -| ARKUI_CLIP_TYPE_CIRCLE | **(circle)** | -| ARKUI_CLIP_TYPE_ELLIPSE | Ellipse. | -| ARKUI_CLIP_TYPE_PATH | Path Type | +| ARKUI_CLIP_TYPE_RECTANGLE | Rectangle. | +| ARKUI_CLIP_TYPE_CIRCLE | **(circle)** | +| ARKUI_CLIP_TYPE_ELLIPSE | Ellipse. | +| ARKUI_CLIP_TYPE_PATH | Path Type | ### ArkUI_ColorMode @@ -1921,11 +2167,11 @@ Enumerates the color modes. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_COLOR_MODE_SYSTEM | Following the system color mode. | -| ARKUI_COLOR_MODE_LIGHT | Light color mode. | -| ARKUI_COLOR_MODE_DARK | Dark color mode. | +| ARKUI_COLOR_MODE_SYSTEM | Following the system color mode. | +| ARKUI_COLOR_MODE_LIGHT | Light color mode. | +| ARKUI_COLOR_MODE_DARK | Dark color mode. | ### ArkUI_ColorStrategy @@ -1939,11 +2185,11 @@ Enumerates the foreground colors. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_COLOR_STRATEGY_INVERT | The foreground colors are the inverse of the component background colors. | -| ARKUI_COLOR_STRATEGY_AVERAGE | The shadow colors of the component are the average color obtained from the component background shadow area. | -| ARKUI_COLOR_STRATEGY_PRIMARY | The shadow colors of the component are the primary color obtained from the component background shadow area. | +| ARKUI_COLOR_STRATEGY_INVERT | The foreground colors are the inverse of the component background colors. | +| ARKUI_COLOR_STRATEGY_AVERAGE | The shadow colors of the component are the average color obtained from the component background shadow area. | +| ARKUI_COLOR_STRATEGY_PRIMARY | The shadow colors of the component are the primary color obtained from the component background shadow area. | ### ArkUI_CopyOptions @@ -1957,12 +2203,12 @@ Enumerates the text copy and paste modes. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_COPY_OPTIONS_NONE | Copy is not allowed. | -| ARKUI_COPY_OPTIONS_IN_APP | Intra-application copy is allowed. | -| ARKUI_COPY_OPTIONS_LOCAL_DEVICE | Intra-device copy is allowed. | -| ARKUI_COPY_OPTIONS_CROSS_DEVICE | Cross-device copy is allowed. | +| ARKUI_COPY_OPTIONS_NONE | Copy is not allowed. | +| ARKUI_COPY_OPTIONS_IN_APP | Intra-application copy is allowed. | +| ARKUI_COPY_OPTIONS_LOCAL_DEVICE | Intra-device copy is allowed. | +| ARKUI_COPY_OPTIONS_CROSS_DEVICE | Cross-device copy is allowed. | ### ArkUI_Direction @@ -1976,11 +2222,11 @@ Enumerates the modes in which components are laid out along the main axis of the **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_DIRECTION_LTR | Components are arranged from left to right. | -| ARKUI_DIRECTION_RTL | Components are arranged from right to left. | -| ARKUI_DIRECTION_AUTO | The default layout direction is used. | +| ARKUI_DIRECTION_LTR | Components are arranged from left to right. | +| ARKUI_DIRECTION_RTL | Components are arranged from right to left. | +| ARKUI_DIRECTION_AUTO | The default layout direction is used. | ### ArkUI_DismissReason @@ -1994,12 +2240,45 @@ Enumerates the actions for triggering closure of the dialog box. **Since**: 12 -| Enum| Description| +| Enum| Description| +| -------- | -------- | +| DIALOG_DISMISS_BACK_PRESS | Touching the system-defined Back button or pressing the Esc key. | +| DIALOG_DISMISS_TOUCH_OUTSIDE | Touching the mask. | +| DIALOG_DISMISS_CLOSE_BUTTON | Touching the Close button. | +| DIALOG_DISMISS_SLIDE_DOWN | Sliding down. | + + +### ArkUI_LevelMode + +``` +enum ArkUI_LevelMode +``` +**Description** + +Enumerates the display level modes of the dialog box. + +**Since**: 15 + +| Enum| Description| +| -------- | -------- | +| ARKUI_LEVEL_MODE_OVERLAY | The dialog box is displayed on top of all other application content. | +| ARKUI_LEVEL_MODE_EMBEDDED | The dialog box is embedded within the application's page content. | + +### ArkUI_ImmersiveMode + +``` +enum ArkUI_ImmersiveMode +``` +**Description** + +Enumerates the display areas of the embedded dialog box overlay. + +**Since**: 15 + +| Enum| Description| | -------- | -------- | -| DIALOG_DISMISS_BACK_PRESS | Touching the system-defined Back button or pressing the Esc key. | -| DIALOG_DISMISS_TOUCH_OUTSIDE | Touching the mask. | -| DIALOG_DISMISS_CLOSE_BUTTON | Touching the Close button. | -| DIALOG_DISMISS_SLIDE_DOWN | Sliding down. | +| ARKUI_IMMERSIVE_MODE_DEFAULT | The dialog box overlay follows the layout constraints of its parent node. | +| ARKUI_IMMERSIVE_MODE_EXTEND | The dialog box overlay can extend to cover the status bar and navigation bar for a more immersive look. | ### ArkUI_DragPreviewScaleMode @@ -2012,10 +2291,10 @@ Defines an enum for drag preview scale modes. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_DRAG_PREVIEW_SCALE_AUTO | The system automatically changes the position of the dragged point based on the scenario and scales the drag preview based on set rules. | -| ARKUI_DRAG_PREVIEW_SCALE_DISABLED | The system does not scale the drag preview. | +| ARKUI_DRAG_PREVIEW_SCALE_AUTO | The system automatically changes the position of the dragged point based on the scenario and scales the drag preview based on set rules. | +| ARKUI_DRAG_PREVIEW_SCALE_DISABLED | The system does not scale the drag preview. | ### ArkUI_DragResult @@ -2029,11 +2308,11 @@ Defines an enum for drag results, which are set by the data receiver and transfe **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_DRAG_RESULT_SUCCESSFUL | The drag and drop operation succeeded. | -| ARKUI_DRAG_RESULT_FAILED | The drag and drop operation failed. | -| ARKUI_DRAG_RESULT_CANCELED | The drag and drop operation was canceled. | +| ARKUI_DRAG_RESULT_SUCCESSFUL | The drag and drop operation succeeded. | +| ARKUI_DRAG_RESULT_FAILED | The drag and drop operation failed. | +| ARKUI_DRAG_RESULT_CANCELED | The drag and drop operation was canceled. | ### ArkUI_DragStatus @@ -2047,17 +2326,17 @@ Enumerates dragging states. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ArkUI_DRAG_STATUS_UNKNOWN | Unknown. | -| ArkUI_DRAG_STATUS_STARTED | Started. | -| ArkUI_DRAG_STATUS_ENDED | Ended. | +| ArkUI_DRAG_STATUS_UNKNOWN | Unknown. | +| ArkUI_DRAG_STATUS_STARTED | Started. | +| ArkUI_DRAG_STATUS_ENDED | Ended. | -### ArkUI_DropProposal +### ArkUI_DropOperation ``` -enum ArkUI_DropProposal +enum ArkUI_DropOperation ``` **Description** @@ -2065,10 +2344,10 @@ Defines an enum for data processing modes used when data is dropped, which affec **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_DROP_PROPOSAL_COPY | Copy. | -| ARKUI_DROP_PROPOSAL_MOVE | Cut. | +| ARKUI_DROP_OPERATION_COPY | Copy. | +| ARKUI_DROP_OPERATION_MOVE | Cut. | ### ArkUI_EdgeEffect @@ -2082,11 +2361,11 @@ Enumerates the effects used at the edges of the component when the boundary of t **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_EDGE_EFFECT_SPRING | Spring effect. When at one of the edges, the component can move beyond the bounds through touches, and produces a bounce effect when the user releases their finger. | -| ARKUI_EDGE_EFFECT_FADE | Fade effect. When at one of the edges, the component produces a fade effect. | -| ARKUI_EDGE_EFFECT_NONE | No effect when the component is at one of the edges. | +| ARKUI_EDGE_EFFECT_SPRING | Spring effect. When at one of the edges, the component can move beyond the bounds through touches, and produces a bounce effect when the user releases their finger. | +| ARKUI_EDGE_EFFECT_FADE | Fade effect. When at one of the edges, the component produces a fade effect. | +| ARKUI_EDGE_EFFECT_NONE | No effect when the component is at one of the edges. | ### ArkUI_EffectEdge @@ -2117,11 +2396,11 @@ Enumerates the ellipsis positions. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_ELLIPSIS_MODE_START | An ellipsis is used at the start of the line of text. | -| ARKUI_ELLIPSIS_MODE_CENTER | An ellipsis is used at the center of the line of text. | -| ARKUI_ELLIPSIS_MODE_END | An ellipsis is used at the end of the line of text. | +| ARKUI_ELLIPSIS_MODE_START | An ellipsis is used at the start of the line of text. | +| ARKUI_ELLIPSIS_MODE_CENTER | An ellipsis is used at the center of the line of text. | +| ARKUI_ELLIPSIS_MODE_END | An ellipsis is used at the end of the line of text. | ### ArkUI_EnterKeyType @@ -2135,15 +2414,15 @@ Enumerates the types of the Enter key for a single-line text box. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_ENTER_KEY_TYPE_GO | The Enter key is labeled "Go." | -| ARKUI_ENTER_KEY_TYPE_SEARCH | The Enter key is labeled "Search." | -| ARKUI_ENTER_KEY_TYPE_SEND | The Enter key is labeled "Send." | -| ARKUI_ENTER_KEY_TYPE_NEXT | The Enter key is labeled "Next." | -| ARKUI_ENTER_KEY_TYPE_DONE | The Enter key is labeled "Done." | -| ARKUI_ENTER_KEY_TYPE_PREVIOUS | The Enter key is labeled "Previous." | -| ARKUI_ENTER_KEY_TYPE_NEW_LINE | The Enter key is labeled "Return." | +| ARKUI_ENTER_KEY_TYPE_GO | The Enter key is labeled "Go." | +| ARKUI_ENTER_KEY_TYPE_SEARCH | The Enter key is labeled "Search." | +| ARKUI_ENTER_KEY_TYPE_SEND | The Enter key is labeled "Send." | +| ARKUI_ENTER_KEY_TYPE_NEXT | The Enter key is labeled "Next." | +| ARKUI_ENTER_KEY_TYPE_DONE | The Enter key is labeled "Done." | +| ARKUI_ENTER_KEY_TYPE_PREVIOUS | The Enter key is labeled "Previous." | +| ARKUI_ENTER_KEY_TYPE_NEW_LINE | The Enter key is labeled "Return." | ### ArkUI_ErrorCode @@ -2157,27 +2436,28 @@ Defines an enum for the error codes. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_ERROR_CODE_NO_ERROR | No error. | -| ARKUI_ERROR_CODE_PARAM_INVALID | Parameter error. | -| ARKUI_ERROR_CODE_ATTRIBUTE_OR_EVENT_NOT_SUPPORTED | The component does not support specific attributes or events. | -| ARKUI_ERROR_CODE_NOT_SUPPROTED_FOR_ARKTS_NODE | The specific operation is not allowed on the node created by ArkTS. | -| ARKUI_ERROR_CODE_NODE_ADAPTER_NONE_HOST | The adapter for lazy loading is not bound to the component. | -| ARKUI_ERROR_CODE_NODE_ADAPTER_EXIST_IN_HOST | The adapter already exists. | -| ARKUI_ERROR_CODE_NODE_ADAPTER_CHILD_NODE_EXIST | Failed to add the adapter because the corresponding node already has a subnode. | -| ARKUI_ERROR_CODE_NODE_EVENT_PARAM_INDEX_OUT_OF_RANGE | The parameter length in the parameter event exceeds the limit. | -| ARKUI_ERROR_CODE_NODE_EVENT_PARAM_INVALID | The data does not exist in the component event. | -| ARKUI_ERROR_CODE_NODE_EVENT_NO_RETURN | The component event does not support return values. | -| ARKUI_ERROR_CODE_NODE_INDEX_INVALID | Invalid index. | -| ARKUI_ERROR_CODE_GET_INFO_FAILED | Failed to obtain the route navigation information. | -| ARKUI_ERROR_CODE_BUFFER_SIZE_ERROR | Buffer size error. | +| ARKUI_ERROR_CODE_NO_ERROR | No error. | +| ARKUI_ERROR_CODE_PARAM_INVALID | Parameter error. | +| ARKUI_ERROR_CODE_ATTRIBUTE_OR_EVENT_NOT_SUPPORTED | The component does not support specific attributes or events. | +| ARKUI_ERROR_CODE_NOT_SUPPROTED_FOR_ARKTS_NODE | The specific operation is not allowed on the node created by ArkTS. | +| ARKUI_ERROR_CODE_NODE_ADAPTER_NONE_HOST | The adapter for lazy loading is not bound to the component. | +| ARKUI_ERROR_CODE_NODE_ADAPTER_EXIST_IN_HOST | The adapter already exists. | +| ARKUI_ERROR_CODE_NODE_ADAPTER_CHILD_NODE_EXIST | Failed to add the adapter because the corresponding node already has a subnode. | +| ARKUI_ERROR_CODE_NODE_EVENT_PARAM_INDEX_OUT_OF_RANGE | The parameter length in the parameter event exceeds the limit. | +| ARKUI_ERROR_CODE_NODE_EVENT_PARAM_INVALID | The data does not exist in the component event. | +| ARKUI_ERROR_CODE_NODE_EVENT_NO_RETURN | The component event does not support return values. | +| ARKUI_ERROR_CODE_NODE_INDEX_INVALID | Invalid index. | +| ARKUI_ERROR_CODE_GET_INFO_FAILED | Failed to obtain the route navigation information. | +| ARKUI_ERROR_CODE_BUFFER_SIZE_ERROR | Buffer size error. | | ARKUI_ERROR_CODE_FOCUS_NON_FOCUSABLE | The current node is not focusable.| | ARKUI_ERROR_CODE_FOCUS_NON_FOCUSABLE_ANCESTOR | An ancestor of the current node is not focusable.| | ARKUI_ERROR_CODE_FOCUS_NON_EXISTENT | The current node does not exist.| -| ARKUI_ERROR_CODE_NON_SCROLLABLE_CONTAINER | The component is not a scrollable container. | -| ARKUI_ERROR_CODE_BUFFER_SIZE_NOT_ENOUGH | The buffer is not large enough. | -| ARKUI_ERROR_CODE_INVALID_STYLED_STRING | Invalid styled string. | +| ARKUI_ERROR_CODE_NON_SCROLLABLE_CONTAINER | The component is not a scrollable container. | +| ARKUI_ERROR_CODE_BUFFER_SIZE_NOT_ENOUGH | The buffer is not large enough. | +| ARKUI_ERROR_CODE_INVALID_STYLED_STRING | Invalid styled string. | +| ARKUI_ERROR_CODE_RECOGNIZER_TYPE_NOT_SUPPORTED | The gesture recognizer type is not supported. | ### ArkUI_FinishCallbackType @@ -2191,10 +2471,10 @@ Enumerates the animation **onFinish** callback types. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_FINISH_CALLBACK_REMOVED | The callback is invoked when the entire animation is removed once it has finished. | -| ARKUI_FINISH_CALLBACK_LOGICALLY | The callback is invoked when the animation logically enters the falling state, though it may still be in its long tail state. | +| ARKUI_FINISH_CALLBACK_REMOVED | The callback is invoked when the entire animation is removed once it has finished. | +| ARKUI_FINISH_CALLBACK_LOGICALLY | The callback is invoked when the animation logically enters the falling state, though it may still be in its long tail state. | ### ArkUI_FlexAlignment @@ -2208,14 +2488,14 @@ Enumerates the vertical alignment modes. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_FLEX_ALIGNMENT_START | The child components are aligned with the start edge of the main axis. | -| ARKUI_FLEX_ALIGNMENT_CENTER | The child components are aligned in the center of the main axis. | -| ARKUI_FLEX_ALIGNMENT_END | The child components are aligned with the end edge of the main axis. | -| ARKUI_FLEX_ALIGNMENT_SPACE_BETWEEN | The child components are evenly distributed along the main axis. The space between any two adjacent components is the same. The first component is aligned with the main-start, and the last component is aligned with the main-end. | -| ARKUI_FLEX_ALIGNMENT_SPACE_AROUND | The child components are evenly distributed along the main axis. The space between any two adjacent components is the same. The space between the first component and main-start, and that between the last component and cross-main are both half the size of the space between two adjacent components. | -| ARKUI_FLEX_ALIGNMENT_SPACE_EVENLY | The child components are evenly distributed along the main axis. The space between the first component and main-start, the space between the last component and main-end, and the space between any two adjacent components are the same. | +| ARKUI_FLEX_ALIGNMENT_START | The child components are aligned with the start edge of the main axis. | +| ARKUI_FLEX_ALIGNMENT_CENTER | The child components are aligned in the center of the main axis. | +| ARKUI_FLEX_ALIGNMENT_END | The child components are aligned with the end edge of the main axis. | +| ARKUI_FLEX_ALIGNMENT_SPACE_BETWEEN | The child components are evenly distributed along the main axis. The space between any two adjacent components is the same. The first component is aligned with the main-start, and the last component is aligned with the main-end. | +| ARKUI_FLEX_ALIGNMENT_SPACE_AROUND | The child components are evenly distributed along the main axis. The space between any two adjacent components is the same. The space between the first component and main-start, and that between the last component and cross-main are both half the size of the space between two adjacent components. | +| ARKUI_FLEX_ALIGNMENT_SPACE_EVENLY | The child components are evenly distributed along the main axis. The space between the first component and main-start, the space between the last component and main-end, and the space between any two adjacent components are the same. | ### ArkUI_FlexDirection @@ -2229,12 +2509,12 @@ Enumerates the directions of the main axis in the flex container. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_FLEX_DIRECTION_ROW | The child components are arranged in the same direction as the main axis runs along the rows. | -| ARKUI_FLEX_DIRECTION_COLUMN | The child components are arranged in the same direction as the main axis runs down the columns. | -| ARKUI_FLEX_DIRECTION_ROW_REVERSE | The child components are arranged opposite to the **ROW** direction. | -| ARKUI_FLEX_DIRECTION_COLUMN_REVERSE | The child components are arranged opposite to the **COLUMN** direction. | +| ARKUI_FLEX_DIRECTION_ROW | The child components are arranged in the same direction as the main axis runs along the rows. | +| ARKUI_FLEX_DIRECTION_COLUMN | The child components are arranged in the same direction as the main axis runs down the columns. | +| ARKUI_FLEX_DIRECTION_ROW_REVERSE | The child components are arranged opposite to the **ROW** direction. | +| ARKUI_FLEX_DIRECTION_COLUMN_REVERSE | The child components are arranged opposite to the **COLUMN** direction. | ### ArkUI_FlexWrap @@ -2248,11 +2528,11 @@ Defines whether the flex container has a single line or multiple lines. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_FLEX_WRAP_NO_WRAP | The child components in the flex container are arranged in a single line, and they cannot overflow. | -| ARKUI_FLEX_WRAP_WRAP | The child components in the flex container are arranged in multiple lines, and they may overflow. | -| ARKUI_FLEX_WRAP_WRAP_REVERSE | The child components in the flex container are reversely arranged in multiple lines, and they may overflow. | +| ARKUI_FLEX_WRAP_NO_WRAP | The child components in the flex container are arranged in a single line, and they cannot overflow. | +| ARKUI_FLEX_WRAP_WRAP | The child components in the flex container are arranged in multiple lines, and they may overflow. | +| ARKUI_FLEX_WRAP_WRAP_REVERSE | The child components in the flex container are reversely arranged in multiple lines, and they may overflow. | ### ArkUI_FontStyle @@ -2266,10 +2546,10 @@ Enumerates the font styles. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_FONT_STYLE_NORMAL | Standard font style. | -| ARKUI_FONT_STYLE_ITALIC | Italic font style. | +| ARKUI_FONT_STYLE_NORMAL | Standard font style. | +| ARKUI_FONT_STYLE_ITALIC | Italic font style. | ### ArkUI_FontWeight @@ -2283,23 +2563,23 @@ Enumerates the font weights. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_FONT_WEIGHT_W100 | 100 | -| ARKUI_FONT_WEIGHT_W200 | 200 | -| ARKUI_FONT_WEIGHT_W300 | 300 | -| ARKUI_FONT_WEIGHT_W400 | 400 | -| ARKUI_FONT_WEIGHT_W500 | 500 | -| ARKUI_FONT_WEIGHT_W600 | 600 | -| ARKUI_FONT_WEIGHT_W700 | 700 | -| ARKUI_FONT_WEIGHT_W800 | 800 | -| ARKUI_FONT_WEIGHT_W900 | 900 | -| ARKUI_FONT_WEIGHT_BOLD | The font weight is bold. | -| ARKUI_FONT_WEIGHT_NORMAL | The font weight is normal. | -| ARKUI_FONT_WEIGHT_BOLDER | The font weight is bolder. | -| ARKUI_FONT_WEIGHT_LIGHTER | The font weight is lighter. | -| ARKUI_FONT_WEIGHT_MEDIUM | The font weight is medium. | -| ARKUI_FONT_WEIGHT_REGULAR | The font weight is normal. | +| ARKUI_FONT_WEIGHT_W100 | 100 | +| ARKUI_FONT_WEIGHT_W200 | 200 | +| ARKUI_FONT_WEIGHT_W300 | 300 | +| ARKUI_FONT_WEIGHT_W400 | 400 | +| ARKUI_FONT_WEIGHT_W500 | 500 | +| ARKUI_FONT_WEIGHT_W600 | 600 | +| ARKUI_FONT_WEIGHT_W700 | 700 | +| ARKUI_FONT_WEIGHT_W800 | 800 | +| ARKUI_FONT_WEIGHT_W900 | 900 | +| ARKUI_FONT_WEIGHT_BOLD | The font weight is bold. | +| ARKUI_FONT_WEIGHT_NORMAL | The font weight is normal. | +| ARKUI_FONT_WEIGHT_BOLDER | The font weight is bolder. | +| ARKUI_FONT_WEIGHT_LIGHTER | The font weight is lighter. | +| ARKUI_FONT_WEIGHT_MEDIUM | The font weight is medium. | +| ARKUI_FONT_WEIGHT_REGULAR | The font weight is normal. | ### ArkUI_GestureDirection @@ -2313,16 +2593,16 @@ Enumerates gesture directions. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| GESTURE_DIRECTION_ALL | All directions. | -| GESTURE_DIRECTION_HORIZONTAL | Horizontal direction. | -| GESTURE_DIRECTION_VERTICAL | Vertical direction. | -| GESTURE_DIRECTION_LEFT | Leftward. | -| GESTURE_DIRECTION_RIGHT | Rightward. | -| GESTURE_DIRECTION_UP | Upward. | -| GESTURE_DIRECTION_DOWN | Downward. | -| GESTURE_DIRECTION_NONE | None. | +| GESTURE_DIRECTION_ALL | All directions. | +| GESTURE_DIRECTION_HORIZONTAL | Horizontal direction. | +| GESTURE_DIRECTION_VERTICAL | Vertical direction. | +| GESTURE_DIRECTION_LEFT | Leftward. | +| GESTURE_DIRECTION_RIGHT | Rightward. | +| GESTURE_DIRECTION_UP | Upward. | +| GESTURE_DIRECTION_DOWN | Downward. | +| GESTURE_DIRECTION_NONE | None. | ### ArkUI_GestureEventActionType @@ -2336,12 +2616,12 @@ Enumerates gesture event types. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| GESTURE_EVENT_ACTION_ACCEPT | Triggered. | -| GESTURE_EVENT_ACTION_UPDATE | Updated. | -| GESTURE_EVENT_ACTION_END | Ended. | -| GESTURE_EVENT_ACTION_CANCEL | Canceled. | +| GESTURE_EVENT_ACTION_ACCEPT | Triggered. | +| GESTURE_EVENT_ACTION_UPDATE | Updated. | +| GESTURE_EVENT_ACTION_END | Ended. | +| GESTURE_EVENT_ACTION_CANCEL | Canceled. | ### ArkUI_GestureInterruptResult @@ -2355,10 +2635,10 @@ Enumerates gesture interruption results. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| GESTURE_INTERRUPT_RESULT_CONTINUE | The gesture recognition process continues. | -| GESTURE_INTERRUPT_RESULT_REJECT | The gesture recognition process is paused. | +| GESTURE_INTERRUPT_RESULT_CONTINUE | The gesture recognition process continues. | +| GESTURE_INTERRUPT_RESULT_REJECT | The gesture recognition process is paused. | ### ArkUI_GestureMask @@ -2372,10 +2652,10 @@ Enumerates gesture masking modes. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| NORMAL_GESTURE_MASK | The gestures of child components are enabled and recognized based on the default gesture recognition sequence. | -| IGNORE_INTERNAL_GESTURE_MASK | The gestures of child components are disabled, including the built-in gestures. | +| NORMAL_GESTURE_MASK | The gestures of child components are enabled and recognized based on the default gesture recognition sequence. | +| IGNORE_INTERNAL_GESTURE_MASK | The gestures of child components are disabled, including the built-in gestures. | ### ArkUI_GesturePriority @@ -2389,11 +2669,11 @@ Enumerates gesture event modes. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| NORMAL | Normal. | -| PRIORITY | High-priority. | -| PARALLEL | Parallel. | +| NORMAL | Normal. | +| PRIORITY | High-priority. | +| PARALLEL | Parallel. | ### ArkUI_GestureRecognizerState @@ -2407,14 +2687,14 @@ Enumerates the gesture recognizer states. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_GESTURE_RECOGNIZER_STATE_REDAY | Prepared. | -| ARKUI_GESTURE_RECOGNIZER_STATE_DETECTING | Check status. | -| ARKUI_GESTURE_RECOGNIZER_STATE_PENDING | Waiting | -| ARKUI_GESTURE_RECOGNIZER_STATE_BLOCKED | Blocked. | -| ARKUI_GESTURE_RECOGNIZER_STATE_SUCCESSFUL | (Success status) | -| ARKUI_GESTURE_RECOGNIZER_STATE_FAILED | Failed. | +| ARKUI_GESTURE_RECOGNIZER_STATE_REDAY | Prepared. | +| ARKUI_GESTURE_RECOGNIZER_STATE_DETECTING | Check status. | +| ARKUI_GESTURE_RECOGNIZER_STATE_PENDING | Waiting | +| ARKUI_GESTURE_RECOGNIZER_STATE_BLOCKED | Blocked. | +| ARKUI_GESTURE_RECOGNIZER_STATE_SUCCESSFUL | (Success status) | +| ARKUI_GESTURE_RECOGNIZER_STATE_FAILED | Failed. | ### ArkUI_GestureRecognizerType @@ -2428,15 +2708,15 @@ Enumerates gesture recognizer types. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| TAP_GESTURE | Tap. | -| LONG_PRESS_GESTURE | Long press gesture. | -| PAN_GESTURE | Pan gesture. | -| PINCH_GESTURE | Pinch gesture. | -| ROTATION_GESTURE | Rotation gesture. | -| SWIPE_GESTURE | Swipe gesture. | -| GROUP_GESTURE | A group of gestures. | +| TAP_GESTURE | Tap. | +| LONG_PRESS_GESTURE | Long press gesture. | +| PAN_GESTURE | Pan gesture. | +| PINCH_GESTURE | Pinch gesture. | +| ROTATION_GESTURE | Rotation gesture. | +| SWIPE_GESTURE | Swipe gesture. | +| GROUP_GESTURE | A group of gestures. | ### ArkUI_GroupGestureMode @@ -2450,11 +2730,11 @@ Enumerates gesture group modes. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| SEQUENTIAL_GROUP | Sequential recognition. Gestures are recognized in the registration sequence until all gestures are recognized successfully. Once one gesture fails to be recognized, all subsequent gestures fail to be recognized. Only the last gesture in the gesture group can respond to the end event. | -| PARALLEL_GROUP | Parallel recognition. Registered gestures are recognized concurrently until all gestures are recognized. The recognition result of each gesture does not affect each other. | -| EXCLUSIVE_GROUP | Exclusive recognition. Registered gestures are identified concurrently. If one gesture is successfully recognized, gesture recognition ends. | +| SEQUENTIAL_GROUP | Sequential recognition. Gestures are recognized in the registration sequence until all gestures are recognized successfully. Once one gesture fails to be recognized, all subsequent gestures fail to be recognized. Only the last gesture in the gesture group can respond to the end event. | +| PARALLEL_GROUP | Parallel recognition. Registered gestures are recognized concurrently until all gestures are recognized. The recognition result of each gesture does not affect each other. | +| EXCLUSIVE_GROUP | Exclusive recognition. Registered gestures are identified concurrently. If one gesture is successfully recognized, gesture recognition ends. | ### ArkUI_HitTestMode @@ -2468,12 +2748,12 @@ Enumerates the hit test modes. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_HIT_TEST_MODE_DEFAULT | Both the node and its child node respond to the hit test of a touch event, but its sibling node is blocked from the hit test. | -| ARKUI_HIT_TEST_MODE_BLOCK | The node responds to the hit test of a touch event, but its child node and sibling node are blocked from the hit test. | -| ARKUI_HIT_TEST_MODE_TRANSPARENT | Both the node and its child node respond to the hit test of a touch event, and its sibling node is also considered during the hit test. | -| ARKUI_HIT_TEST_MODE_NONE | The node does not respond to the hit test of a touch event. | +| ARKUI_HIT_TEST_MODE_DEFAULT | Both the node and its child node respond to the hit test of a touch event, but its sibling node is blocked from the hit test. | +| ARKUI_HIT_TEST_MODE_BLOCK | The node responds to the hit test of a touch event, but its child node and sibling node are blocked from the hit test. | +| ARKUI_HIT_TEST_MODE_TRANSPARENT | Both the node and its child node respond to the hit test of a touch event, and its sibling node is also considered during the hit test. | +| ARKUI_HIT_TEST_MODE_NONE | The node does not respond to the hit test of a touch event. | ### ArkUI_HorizontalAlignment @@ -2487,11 +2767,11 @@ Enumerates the alignment mode in the horizontal direction. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_HORIZONTAL_ALIGNMENT_START | Aligned with the start edge in the same direction as the language in use. | -| ARKUI_HORIZONTAL_ALIGNMENT_CENTER | Aligned with the center. This is the default alignment mode. | -| ARKUI_HORIZONTAL_ALIGNMENT_END | Aligned with the end edge in the same direction as the language in use. | +| ARKUI_HORIZONTAL_ALIGNMENT_START | Aligned with the start edge in the same direction as the language in use. | +| ARKUI_HORIZONTAL_ALIGNMENT_CENTER | Aligned with the center. This is the default alignment mode. | +| ARKUI_HORIZONTAL_ALIGNMENT_END | Aligned with the end edge in the same direction as the language in use. | ### ArkUI_ImageInterpolation @@ -2505,12 +2785,12 @@ Enumerates the image interpolation effects. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_IMAGE_INTERPOLATION_NONE | No image interpolation. | -| ARKUI_IMAGE_INTERPOLATION_LOW | Low quality interpolation. | -| ARKUI_IMAGE_INTERPOLATION_MEDIUM | Medium quality interpolation. | -| ARKUI_IMAGE_INTERPOLATION_HIGH | High quality interpolation. This mode produces scaled images of the highest possible quality. | +| ARKUI_IMAGE_INTERPOLATION_NONE | No image interpolation. | +| ARKUI_IMAGE_INTERPOLATION_LOW | Low quality interpolation. | +| ARKUI_IMAGE_INTERPOLATION_MEDIUM | Medium quality interpolation. | +| ARKUI_IMAGE_INTERPOLATION_HIGH | High quality interpolation. This mode produces scaled images of the highest possible quality. | ### ArkUI_ImageRenderMode @@ -2524,10 +2804,10 @@ Enumerates the image rendering modes. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_IMAGE_RENDER_MODE_ORIGINAL | Render image pixels as they are in the original source image. | -| ARKUI_IMAGE_RENDER_MODE_TEMPLATE | Render image pixels to create a monochrome template image. | +| ARKUI_IMAGE_RENDER_MODE_ORIGINAL | Render image pixels as they are in the original source image. | +| ARKUI_IMAGE_RENDER_MODE_TEMPLATE | Render image pixels to create a monochrome template image. | ### ArkUI_ImageRepeat @@ -2541,12 +2821,12 @@ Enumerates the image repeat patterns. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_IMAGE_REPEAT_NONE | The image is not repeatedly drawn. | -| ARKUI_IMAGE_REPEAT_X | The image is repeatedly drawn only along the x-axis. | -| ARKUI_IMAGE_REPEAT_Y | The image is repeatedly drawn only along the y-axis. | -| ARKUI_IMAGE_REPEAT_XY | The image is repeatedly drawn along both axes. | +| ARKUI_IMAGE_REPEAT_NONE | The image is not repeatedly drawn. | +| ARKUI_IMAGE_REPEAT_X | The image is repeatedly drawn only along the x-axis. | +| ARKUI_IMAGE_REPEAT_Y | The image is repeatedly drawn only along the y-axis. | +| ARKUI_IMAGE_REPEAT_XY | The image is repeatedly drawn along both axes. | ### ArkUI_ImageSize @@ -2560,11 +2840,11 @@ Defines the image size. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_IMAGE_SIZE_AUTO | The original image aspect ratio is retained. | -| ARKUI_IMAGE_SIZE_COVER | Default value. The image is scaled with its aspect ratio retained for both sides to be greater than or equal to the display boundaries. | -| ARKUI_IMAGE_SIZE_CONTAIN | The image is scaled with its aspect ratio retained for the content to be completely displayed within the display boundaries. | +| ARKUI_IMAGE_SIZE_AUTO | The original image aspect ratio is retained. | +| ARKUI_IMAGE_SIZE_COVER | Default value. The image is scaled with its aspect ratio retained for both sides to be greater than or equal to the display boundaries. | +| ARKUI_IMAGE_SIZE_CONTAIN | The image is scaled with its aspect ratio retained for the content to be completely displayed within the display boundaries. | ### ArkUI_ImageSpanAlignment @@ -2578,12 +2858,12 @@ Enumerates the alignment mode of the image with the text. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_IMAGE_SPAN_ALIGNMENT_BASELINE | The image is bottom aligned with the text baseline. | -| ARKUI_IMAGE_SPAN_ALIGNMENT_BOTTOM | The image is bottom aligned with the text. | -| ARKUI_IMAGE_SPAN_ALIGNMENT_CENTER | The image is centered aligned with the text. | -| ARKUI_IMAGE_SPAN_ALIGNMENT_TOP | The image is top aligned with the text. | +| ARKUI_IMAGE_SPAN_ALIGNMENT_BASELINE | The image is bottom aligned with the text baseline. | +| ARKUI_IMAGE_SPAN_ALIGNMENT_BOTTOM | The image is bottom aligned with the text. | +| ARKUI_IMAGE_SPAN_ALIGNMENT_CENTER | The image is centered aligned with the text. | +| ARKUI_IMAGE_SPAN_ALIGNMENT_TOP | The image is top aligned with the text. | ### ArkUI_ItemAlignment @@ -2597,14 +2877,14 @@ Enumerates the modes in which components are laid out along the cross axis of th **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_ITEM_ALIGNMENT_AUTO | The default configuration of the flex container is used. | -| ARKUI_ITEM_ALIGNMENT_START | The items in the flex container are aligned with the cross-start edge. | -| ARKUI_ITEM_ALIGNMENT_CENTER | The items in the flex container are centered along the cross axis. | -| ARKUI_ITEM_ALIGNMENT_END | The items in the flex container are aligned with the cross-end edge. | -| ARKUI_ITEM_ALIGNMENT_STRETCH | The items in the flex container are stretched and padded along the cross axis. | -| ARKUI_ITEM_ALIGNMENT_BASELINE | The items in the flex container are aligned in such a manner that their text baselines are aligned along the cross axis. | +| ARKUI_ITEM_ALIGNMENT_AUTO | The default configuration of the flex container is used. | +| ARKUI_ITEM_ALIGNMENT_START | The items in the flex container are aligned with the cross-start edge. | +| ARKUI_ITEM_ALIGNMENT_CENTER | The items in the flex container are centered along the cross axis. | +| ARKUI_ITEM_ALIGNMENT_END | The items in the flex container are aligned with the cross-end edge. | +| ARKUI_ITEM_ALIGNMENT_STRETCH | The items in the flex container are stretched and padded along the cross axis. | +| ARKUI_ITEM_ALIGNMENT_BASELINE | The items in the flex container are aligned in such a manner that their text baselines are aligned along the cross axis. | ### ArkUI_KeyCode @@ -2845,12 +3125,12 @@ Enumerates the component units. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_LENGTH_METRIC_UNIT_DEFAULT | Default, which is fp for fonts and vp for non-fonts. | -| ARKUI_LENGTH_METRIC_UNIT_PX | px. | -| ARKUI_LENGTH_METRIC_UNIT_VP | vp. | -| ARKUI_LENGTH_METRIC_UNIT_FP | fp. | +| ARKUI_LENGTH_METRIC_UNIT_DEFAULT | Default, which is fp for fonts and vp for non-fonts. | +| ARKUI_LENGTH_METRIC_UNIT_PX | px. | +| ARKUI_LENGTH_METRIC_UNIT_VP | vp. | +| ARKUI_LENGTH_METRIC_UNIT_FP | fp. | ### ArkUI_LinearGradientDirection @@ -2864,18 +3144,18 @@ Enumerates the gradient directions. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_LINEAR_GRADIENT_DIRECTION_LEFT | From right to left. | -| ARKUI_LINEAR_GRADIENT_DIRECTION_TOP | From bottom to top. | -| ARKUI_LINEAR_GRADIENT_DIRECTION_RIGHT | From left to right. | -| ARKUI_LINEAR_GRADIENT_DIRECTION_BOTTOM | From top to bottom. | -| ARKUI_LINEAR_GRADIENT_DIRECTION_LEFT_TOP | From lower right to upper left. | -| ARKUI_LINEAR_GRADIENT_DIRECTION_LEFT_BOTTOM | From upper right to lower left. | -| ARKUI_LINEAR_GRADIENT_DIRECTION_RIGHT_TOP | From lower left to upper right. | -| ARKUI_LINEAR_GRADIENT_DIRECTION_RIGHT_BOTTOM | From upper left to lower right. | -| ARKUI_LINEAR_GRADIENT_DIRECTION_NONE | No gradient. | -| ARKUI_LINEAR_GRADIENT_DIRECTION_CUSTOM | Custom direction. | +| ARKUI_LINEAR_GRADIENT_DIRECTION_LEFT | From right to left. | +| ARKUI_LINEAR_GRADIENT_DIRECTION_TOP | From bottom to top. | +| ARKUI_LINEAR_GRADIENT_DIRECTION_RIGHT | From left to right. | +| ARKUI_LINEAR_GRADIENT_DIRECTION_BOTTOM | From top to bottom. | +| ARKUI_LINEAR_GRADIENT_DIRECTION_LEFT_TOP | From lower right to upper left. | +| ARKUI_LINEAR_GRADIENT_DIRECTION_LEFT_BOTTOM | From upper right to lower left. | +| ARKUI_LINEAR_GRADIENT_DIRECTION_RIGHT_TOP | From lower left to upper right. | +| ARKUI_LINEAR_GRADIENT_DIRECTION_RIGHT_BOTTOM | From upper left to lower right. | +| ARKUI_LINEAR_GRADIENT_DIRECTION_NONE | No gradient. | +| ARKUI_LINEAR_GRADIENT_DIRECTION_CUSTOM | Custom direction. | ### ArkUI_ListItemAlignment @@ -2889,11 +3169,11 @@ Enumerates the alignment modes of items along the cross axis. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_LIST_ITEM_ALIGNMENT_START | The list items are packed toward the start edge of the **List** component along the cross axis. | -| ARKUI_LIST_ITEM_ALIGNMENT_CENTER | The list items are centered in the **List** component along the cross axis. | -| ARKUI_LIST_ITEM_ALIGNMENT_END | The list items are packed toward the end edge of the **List** component along the cross axis. | +| ARKUI_LIST_ITEM_ALIGNMENT_START | The list items are packed toward the start edge of the **List** component along the cross axis. | +| ARKUI_LIST_ITEM_ALIGNMENT_CENTER | The list items are centered in the **List** component along the cross axis. | +| ARKUI_LIST_ITEM_ALIGNMENT_END | The list items are packed toward the end edge of the **List** component along the cross axis. | ### ArkUI_ListItemSwipeActionState @@ -2907,11 +3187,11 @@ Enumerates the swipe action item states of list items. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_LIST_ITEM_SWIPE_ACTION_STATE_COLLAPSED | Collapsed state. When the list item is swiped in the opposite direction of the main axis, the swipe action item is hidden. | -| ARKUI_LIST_ITEM_SWIPE_ACTION_STATE_EXPANDED | Expanded state. When the list item is swiped in the opposite direction of the main axis, the swipe action item is shown. | -| ARKUI_LIST_ITEM_SWIPE_ACTION_STATE_ACTIONING | In-action state. The list item is in this state when it enters the delete area. | +| ARKUI_LIST_ITEM_SWIPE_ACTION_STATE_COLLAPSED | Collapsed state. When the list item is swiped in the opposite direction of the main axis, the swipe action item is hidden. | +| ARKUI_LIST_ITEM_SWIPE_ACTION_STATE_EXPANDED | Expanded state. When the list item is swiped in the opposite direction of the main axis, the swipe action item is shown. | +| ARKUI_LIST_ITEM_SWIPE_ACTION_STATE_ACTIONING | In-action state. The list item is in this state when it enters the delete area. | ### ArkUI_ListItemSwipeEdgeEffect @@ -2925,10 +3205,10 @@ Enumerates the swipe action item edge effects of list items. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_LIST_ITEM_SWIPE_EDGE_EFFECT_SPRING | When the list item scrolls to the edge of the list, it can continue to scroll for a distance. | -| ARKUI_LIST_ITEM_SWIPE_EDGE_EFFECT_NONE | The list item cannot scroll beyond the edge of the list. | +| ARKUI_LIST_ITEM_SWIPE_EDGE_EFFECT_SPRING | When the list item scrolls to the edge of the list, it can continue to scroll for a distance. | +| ARKUI_LIST_ITEM_SWIPE_EDGE_EFFECT_NONE | The list item cannot scroll beyond the edge of the list. | ### ArkUI_MaskType @@ -2942,13 +3222,13 @@ Enumerates the mask types. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_MASK_TYPE_RECTANGLE | Rectangle. | -| ARKUI_MASK_TYPE_CIRCLE | **(circle)** | -| ARKUI_MASK_TYPE_ELLIPSE | Ellipse. | -| ARKUI_MASK_TYPE_PATH | Path Type | -| ARKUI_MASK_TYPE_PROGRESS | Progress indicator. | +| ARKUI_MASK_TYPE_RECTANGLE | Rectangle. | +| ARKUI_MASK_TYPE_CIRCLE | **(circle)** | +| ARKUI_MASK_TYPE_ELLIPSE | Ellipse. | +| ARKUI_MASK_TYPE_PATH | Path Type | +| ARKUI_MASK_TYPE_PROGRESS | Progress indicator. | ### ArkUI_NativeAPIVariantKind @@ -2962,12 +3242,12 @@ Defines the native API types. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_NATIVE_NODE | API related to UI components. For details, see the struct definition in <arkui/native_node.h>. | +| ARKUI_NATIVE_NODE | API related to UI components. For details, see the struct definition in <arkui/native_node.h>. | | ARKUI_NATIVE_DIALOG | API related to dialog boxes. For details, see the struct definition in <arkui/native_dialog.h>. | | ARKUI_NATIVE_GESTURE | API related to gestures. For details, see the struct definition in <arkui/native_gesture.h>. | -| ARKUI_NATIVE_ANIMATE | API related to animations. For details, see the struct definition in <arkui/native_animate.h>. | +| ARKUI_NATIVE_ANIMATE | API related to animations. For details, see the struct definition in <arkui/native_animate.h>. | ### ArkUI_NavDestinationState @@ -2981,17 +3261,17 @@ Defines an enum for the **NavDestination** component states. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_NAV_DESTINATION_STATE_ON_SHOW | The **NavDestination** component is displayed. | -| ARKUI_NAV_DESTINATION_STATE_ON_HIDE | The **NavDestination** component is hidden. | -| ARKUI_NAV_DESTINATION_STATE_ON_APPEAR | The **NavDestination** component is mounted to the component tree. | -| ARKUI_NAV_DESTINATION_STATE_ON_DISAPPEAR | The **NavDestination** component is unmounted from the component tree. | -| ARKUI_NAV_DESTINATION_STATE_ON_WILL_SHOW | The **NavDestination** is about to be displayed. | -| ARKUI_NAV_DESTINATION_STATE_ON_WILL_HIDE | The **NavDestination** is about to be hidden. | -| ARKUI_NAV_DESTINATION_STATE_ON_WILL_APPEAR | The **NavDestination** is about to be mounted to the component tree. | -| ARKUI_NAV_DESTINATION_STATE_ON_WILL_DISAPPEAR | The **NavDestination** component is about to be unmounted from the component tree. | -| ARKUI_NAV_DESTINATION_STATE_ON_BACK_PRESS | The back button is pressed for the **NavDestination** component. | +| ARKUI_NAV_DESTINATION_STATE_ON_SHOW | The **NavDestination** component is displayed. | +| ARKUI_NAV_DESTINATION_STATE_ON_HIDE | The **NavDestination** component is hidden. | +| ARKUI_NAV_DESTINATION_STATE_ON_APPEAR | The **NavDestination** component is mounted to the component tree. | +| ARKUI_NAV_DESTINATION_STATE_ON_DISAPPEAR | The **NavDestination** component is unmounted from the component tree. | +| ARKUI_NAV_DESTINATION_STATE_ON_WILL_SHOW | The **NavDestination** is about to be displayed. | +| ARKUI_NAV_DESTINATION_STATE_ON_WILL_HIDE | The **NavDestination** is about to be hidden. | +| ARKUI_NAV_DESTINATION_STATE_ON_WILL_APPEAR | The **NavDestination** is about to be mounted to the component tree. | +| ARKUI_NAV_DESTINATION_STATE_ON_WILL_DISAPPEAR | The **NavDestination** component is about to be unmounted from the component tree. | +| ARKUI_NAV_DESTINATION_STATE_ON_BACK_PRESS | The back button is pressed for the **NavDestination** component. | ### ArkUI_NodeAdapterEventType @@ -3005,14 +3285,13 @@ Enumerates node adapter events. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| NODE_ADAPTER_EVENT_WILL_ATTACH_TO_NODE | This event occurs when the component is attached to the adapter. | -| NODE_ADAPTER_EVENT_WILL_DETACH_FROM_NODE | This event occurs when the component is detached from the adapter. | -| NODE_ADAPTER_EVENT_ON_GET_NODE_ID | This event occurs when the adapter obtains the unique ID of the new element to add. | -| NODE_ADAPTER_EVENT_ON_ADD_NODE_TO_ADAPTER | This event occurs when the adapter obtains the content of the new element to add. | -| NODE_ADAPTER_EVENT_ON_REMOVE_NODE_FROM_ADAPTER | This event occurs when the adapter removes an element. | - +| NODE_ADAPTER_EVENT_WILL_ATTACH_TO_NODE | This event occurs when the component is attached to the adapter. | +| NODE_ADAPTER_EVENT_WILL_DETACH_FROM_NODE | This event occurs when the component is detached from the adapter. | +| NODE_ADAPTER_EVENT_ON_GET_NODE_ID | This event occurs when the adapter obtains the unique ID of the new element to add. | +| NODE_ADAPTER_EVENT_ON_ADD_NODE_TO_ADAPTER | This event occurs when the adapter obtains the content of the new element to add. | +| NODE_ADAPTER_EVENT_ON_REMOVE_NODE_FROM_ADAPTER | This event occurs when the adapter removes an element. | ### ArkUI_NodeAttributeType @@ -3025,51 +3304,52 @@ Defines the ArkUI style attributes that can be set on the native side. **Since**: 12 + | Enum| Description| | -------- | -------- | -| NODE_WIDTH | Defines the width attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: width, in vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: width, in vp.| -| NODE_HEIGHT | Defines the height attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: height, in vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: height, in vp.| -| NODE_BACKGROUND_COLOR | Defines the background color attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: background color, in 0xARGB format. For example, 0xFFFF0000 indicates red.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: background color, in 0xARGB format. For example, 0xFFFF0000 indicates red.| +| NODE_WIDTH | Defines the width attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: width, in vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: width, in vp.| +| NODE_HEIGHT | Defines the height attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: height, in vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: height, in vp.| +| NODE_BACKGROUND_COLOR | Defines the background color attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: background color, in 0xARGB format. For example, 0xFFFF0000 indicates red.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: background color, in 0xARGB format. For example, 0xFFFF0000 indicates red.| | NODE_BACKGROUND_IMAGE | Defines the background image attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: image address, which can be an online URL, a local path, a Base64-encoded string, or a PixelMap object. Note that SVG images are not supported.
.value[0]?.i32: whether to repeat the image. Optional. The parameter type is [ArkUI_ImageRepeat](#arkui_imagerepeat). The default value is **ARKUI_IMAGE_REPEAT_NONE**.
.object: **PixelMap** object. The parameter type is [ArkUI_DrawableDescriptor](#arkui_drawabledescriptor).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: image address, which can be an online URL, a local path, a Base64-encoded string, or a PixelMap object. Note that SVG images are not supported.
.value[0].i32: whether to repeat the image. The parameter type is [ArkUI_ImageRepeat](#arkui_imagerepeat).
.object: **PixelMap** object. The parameter type is [ArkUI_DrawableDescriptor](#arkui_drawabledescriptor). Either **.object** or **.string** must be set.| -| NODE_PADDING | Defines the padding attribute, which can be set, reset, and obtained as required through APIs.
There are two formats of [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) for setting the attribute value:
1: Specify the same padding for the four directions.
.value[0].f32: padding, in vp.
2: Specify different paddings for different directions.
.value[0].f32: top padding, in vp.
.value[1].f32: right padding, in vp.
.value[2].f32: bottom padding, in vp.
.value[3].f32: left padding, in vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: top padding, in vp.
.value[1].f32: right padding, in vp.
.value[2].f32: bottom padding, in vp.
.value[3].f32: left padding, in vp.| -| NODE_ID | Defines the component ID attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: component ID.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: component ID.| -| NODE_ENABLED | Defines the interactivity attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: The value **true** means that the component can interact with users, and **false** means the opposite.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: The value **1** means that the component can interact with users, and **0** means the opposite. | -| NODE_MARGIN | Defines the margin attribute, which can be set, reset, and obtained as required through APIs.
There are two formats of [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) for setting the attribute value:
1: Specify the same margin for the four directions.
.value[0].f32: margin, in vp.
2: Specify different margins for different directions.
.value[0].f32: top margin, in vp.
.value[1].f32: right margin, in vp.
.value[2].f32: bottom margin, in vp.
.value[3].f32: left margin, in vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: top margin, in vp.
.value[1].f32: right margin, in vp.
.value[2].f32: bottom margin, in vp.
.value[3].f32: left margin, in vp.| +| NODE_PADDING | Defines the padding attribute, which can be set, reset, and obtained as required through APIs.
There are two formats of [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) for setting the attribute value:
1: Specify the same padding for the four directions.
.value[0].f32: padding, in vp.
2: Specify different paddings for different directions.
.value[0].f32: top padding, in vp.
.value[1].f32: right padding, in vp.
.value[2].f32: bottom padding, in vp.
.value[3].f32: left padding, in vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: top padding, in vp.
.value[1].f32: right padding, in vp.
.value[2].f32: bottom padding, in vp.
.value[3].f32: left padding, in vp.| +| NODE_ID | Defines the component ID attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: component ID.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: component ID.| +| NODE_ENABLED | Defines the interactivity attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: The value **true** means that the component can interact with users, and **false** means the opposite.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: The value **1** means that the component can interact with users, and **0** means the opposite. | +| NODE_MARGIN | Defines the margin attribute, which can be set, reset, and obtained as required through APIs.
There are two formats of [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) for setting the attribute value:
1: Specify the same margin for the four directions.
.value[0].f32: margin, in vp.
2: Specify different margins for different directions.
.value[0].f32: top margin, in vp.
.value[1].f32: right margin, in vp.
.value[2].f32: bottom margin, in vp.
.value[3].f32: left margin, in vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: top margin, in vp.
.value[1].f32: right margin, in vp.
.value[2].f32: bottom margin, in vp.
.value[3].f32: left margin, in vp.| | NODE_TRANSLATE | Defines the translate attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: distance to translate along the x-axis, in vp. The default value is **0**.
.value[1].f32: distance to translate along the y-axis, in vp. The default value is **0**.
.value[2].f32: distance to translate along the z-axis, in vp. The default value is **0**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: distance to translate along the x-axis, in vp.
.value[1].f32: distance to translate along the y-axis, in vp.
.value[2].f32: distance to translate along the z-axis, in vp.
**NOTE**
If more than three parameters are set, the setting does not take effect and no error code is returned.| -| NODE_SCALE | Defines the scale attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: scale factor along the x-axis. The default value is **1**.
.value[1].f32: scale factor along the y-axis. The default value is **1**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: scale factor along the x-axis.
.value[1].f32: scale factor along the y-axis.| -| NODE_ROTATE | Defines the rotate attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: X-coordinate of the rotation axis vector. The default value is **0**.
.value[1].f32: Y-coordinate of the rotation axis vector. The default value is **0**.
.value[2].f32: Z-coordinate of the rotation axis vector. The default value is **0**.
.value[3].f32: rotation angle. The default value is **0**.
.value[4].f32: line of sight, that is, the distance from the viewpoint to the z=0 plane, in vp. The default value is **0**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: X-coordinate of the rotation axis vector.
.value[1].f32: Y-coordinate of the rotation axis vector.
.value[2].f32: Z-coordinate of the rotation axis vector.
.value[3].f32: rotation angle.
.value[4].f32: line of sight, that is, the distance from the viewpoint to the z=0 plane, in vp.| -| NODE_BRIGHTNESS | Sets the brightness attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: brightness value. The default value is **1.0**, and the recommended value range is [0, 2].
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: brightness value.| -| NODE_SATURATION | Sets the saturation attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: saturation value. The default value is **1.0**, and the recommended value range is [0, 50).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: saturation value.| +| NODE_SCALE | Defines the scale attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: scale factor along the x-axis. The default value is **1**.
.value[1].f32: scale factor along the y-axis. The default value is **1**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: scale factor along the x-axis.
.value[1].f32: scale factor along the y-axis.| +| NODE_ROTATE | Defines the rotate attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: X-coordinate of the rotation axis vector. The default value is **0**.
.value[1].f32: Y-coordinate of the rotation axis vector. The default value is **0**.
.value[2].f32: Z-coordinate of the rotation axis vector. The default value is **0**.
.value[3].f32: rotation angle. The default value is **0**.
.value[4].f32: line of sight, that is, the distance from the viewpoint to the z=0 plane, in vp. The default value is **0**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: X-coordinate of the rotation axis vector.
.value[1].f32: Y-coordinate of the rotation axis vector.
.value[2].f32: Z-coordinate of the rotation axis vector.
.value[3].f32: rotation angle.
.value[4].f32: line of sight, that is, the distance from the viewpoint to the z=0 plane, in vp.| +| NODE_BRIGHTNESS | Sets the brightness attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: brightness value. The default value is **1.0**, and the recommended value range is [0, 2].
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: brightness value.| +| NODE_SATURATION | Sets the saturation attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: saturation value. The default value is **1.0**, and the recommended value range is [0, 50).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: saturation value.| | NODE_BLUR | Sets the blur attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: blur radius. A larger value indicates a higher blur degree. If the value is **0**, the component is not blurred. If the value is less than 0, it is treated as **0** and no error code is returned. The unit is px. The default value is **0.0**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: blur radius. The larger the fuzzy radius, the more blurred the image. If the value is **0**, the image is not blurred. The unit is px.| | NODE_LINEAR_GRADIENT | Sets the gradient attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: start angle of the linear gradient. This attribute takes effect only when [ArkUI_LinearGradientDirection](#arkui_lineargradientdirection) is set to **ARKUI_LINEAR_GRADIENT_DIRECTION_CUSTOM**. A positive value indicates a clockwise rotation from the origin, (0, 0). The default value is **180**.
.value[1].i32: direction of the linear gradient. When it is set to any value other than **ARKUI_LINEAR_GRADIENT_DIRECTION_CUSTOM**, the **angle** setting becomes ineffective. The data type is [ArkUI_LinearGradientDirection](#arkui_lineargradientdirection)
.value[2].i32: whether the colors are repeated. The default value is **false**.
.object: The parameter type is [ArkUI_ColorStop](_ark_u_i___color_stop.md). - **colors**: array of color stops, each of which consists of a color and its stop position. Invalid colors are automatically skipped.
**colors**: colors of the color stops.
**stops**: stop positions of the color stops.
**size**: number of colors.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: start angle of the linear gradient. The set value is used only when **ArkUI_LinearGradientDirection** is set to **ARKUI_LINEAR_GRADIENT_DIRECTION_CUSTOM**. In other cases, the default value is used.
.value[1].i32: direction of the linear gradient.
.value[2].i32: whether the colors are repeated.
.object: - **colors**: array of color stops, each of which consists of a color and its stop position. Invalid colors are automatically skipped.
**colors**: colors of the color stops.
**stops**: stop positions of the color stops.
**size**: number of colors.| -| NODE_ALIGNMENT | Sets the alignment attribute, which can be set, reset, and obtained as required through APIs.
In the **Stack** component, this attribute has the same effect as **NODE_STACK_ALIGN_CONTENT**, which means that it sets the alignment mode of child components in the container.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: alignment mode. The parameter type is [ArkUI_Alignment](#arkui_alignment). The default value is **ARKUI_ALIGNMENT_CENTER**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: alignment mode. The parameter type is [ArkUI_Alignment](#arkui_alignment).| -| NODE_OPACITY | Defines the opacity attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: opacity value. The value ranges from 0 to 1.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: opacity value. The value ranges from 0 to 1.| -| NODE_BORDER_WIDTH | Defines the border width attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
1: .value[0].f32: width of the four borders.
2: .value[0].f32: width of the top border.
.value[1].f32: width of the right border.
.value[2].f32: width of the bottom border.
.value[3].f32: width of the left border.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: width of the top border.
.value[1].f32: width of the right border.
.value[2].f32: width of the bottom border.
.value[3].f32: width of the left border.| -| NODE_BORDER_RADIUS | Defines the border corner radius attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
1: .value[0].f32: radius of the four corners.
2: .value[0].f32: radius of the upper left corner.
.value[1].f32: radius of the upper right corner.
.value[2].f32: radius of the lower left corner.
.value[3].f32: radius of the lower right corner.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: radius of the upper left corner.
.value[1].f32: radius of the upper right corner.
.value[2].f32: radius of the lower left corner.
.value[3].f32: radius of the lower right corner.| -| NODE_BORDER_COLOR | Defines the border color attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
1: .value[0].u32: color of the four borders, in 0xARGB format, for example, **0xFFFF11FF**.
2: .value[0].u32: color of the top border, in 0xARGB format, for example, **0xFFFF11FF**.
.value[1].u32: color of the right border, in 0xARGB format, for example, **0xFFFF11FF**.
.value[2].u32: color of the lower border, in 0xARGB format, for example, **0xFFFF11FF**.
.value[3].u32: color of the left border, in 0xARGB format, for example, **0xFFFF11FF**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color of the top border, in 0xARGB format, for example, **0xFFFF11FF**.
.value[1].u32: color of the right border, in 0xARGB format, for example, **0xFFFF11FF**.
.value[2].u32: color of the lower border, in 0xARGB format, for example, **0xFFFF11FF**.
.value[3].u32: color of the left border, in 0xARGB format, for example, **0xFFFF11FF**.| -| NODE_BORDER_STYLE | Defines the border line style attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
1: .value[0].i32: line style of the four borders. The parameter type is [ArkUI_BorderStyle](#arkui_borderstyle). The default value is **ARKUI_BORDER_STYLE_SOLID**.
2: .value[0].i32: line style of the top border. The parameter type is **ArkUI_BorderStyle**. The default value is **ARKUI_BORDER_STYLE_SOLID**.
.value[1].i32: line style of the right border. The parameter type is [ArkUI_BorderStyle](#arkui_borderstyle). The default value is **ARKUI_BORDER_STYLE_SOLID**.
.value[2].i32: line style of the bottom border. The parameter type is [ArkUI_BorderStyle](#arkui_borderstyle). The default value is **ARKUI_BORDER_STYLE_SOLID**.
.value[3].i32: line style of the left border. The parameter type is [ArkUI_BorderStyle](#arkui_borderstyle). The default value is **ARKUI_BORDER_STYLE_SOLID**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: line style of the top border.
.value[1].i32: line style of the right border.
.value[2].i32: line style of the bottom border.
.value[3].i32: line style of the left border.| +| NODE_ALIGNMENT | Sets the alignment attribute, which can be set, reset, and obtained as required through APIs.
In the **Stack** component, this attribute has the same effect as **NODE_STACK_ALIGN_CONTENT**, which means that it sets the alignment mode of child components in the container.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: alignment mode. The parameter type is [ArkUI_Alignment](#arkui_alignment). The default value is **ARKUI_ALIGNMENT_CENTER**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: alignment mode. The parameter type is [ArkUI_Alignment](#arkui_alignment).| +| NODE_OPACITY | Defines the opacity attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: opacity value. The value ranges from 0 to 1.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: opacity value. The value ranges from 0 to 1.| +| NODE_BORDER_WIDTH | Defines the border width attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
1: .value[0].f32: width of the four borders.
2: .value[0].f32: width of the top border.
.value[1].f32: width of the right border.
.value[2].f32: width of the bottom border.
.value[3].f32: width of the left border.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: width of the top border.
.value[1].f32: width of the right border.
.value[2].f32: width of the bottom border.
.value[3].f32: width of the left border.| +| NODE_BORDER_RADIUS | Defines the border corner radius attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
1: .value[0].f32: radius of the four corners.
2: .value[0].f32: radius of the upper left corner.
.value[1].f32: radius of the upper right corner.
.value[2].f32: radius of the lower left corner.
.value[3].f32: radius of the lower right corner.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: radius of the upper left corner.
.value[1].f32: radius of the upper right corner.
.value[2].f32: radius of the lower left corner.
.value[3].f32: radius of the lower right corner.| +| NODE_BORDER_COLOR | Defines the border color attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
1: .value[0].u32: color of the four borders, in 0xARGB format, for example, **0xFFFF11FF**.
2: .value[0].u32: color of the top border, in 0xARGB format, for example, **0xFFFF11FF**.
.value[1].u32: color of the right border, in 0xARGB format, for example, **0xFFFF11FF**.
.value[2].u32: color of the lower border, in 0xARGB format, for example, **0xFFFF11FF**.
.value[3].u32: color of the left border, in 0xARGB format, for example, **0xFFFF11FF**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color of the top border, in 0xARGB format, for example, **0xFFFF11FF**.
.value[1].u32: color of the right border, in 0xARGB format, for example, **0xFFFF11FF**.
.value[2].u32: color of the lower border, in 0xARGB format, for example, **0xFFFF11FF**.
.value[3].u32: color of the left border, in 0xARGB format, for example, **0xFFFF11FF**.| +| NODE_BORDER_STYLE | Defines the border line style attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
1: .value[0].i32: line style of the four borders. The parameter type is [ArkUI_BorderStyle](#arkui_borderstyle). The default value is **ARKUI_BORDER_STYLE_SOLID**.
2: .value[0].i32: line style of the top border. The parameter type is **ArkUI_BorderStyle**. The default value is **ARKUI_BORDER_STYLE_SOLID**.
.value[1].i32: line style of the right border. The parameter type is [ArkUI_BorderStyle](#arkui_borderstyle). The default value is **ARKUI_BORDER_STYLE_SOLID**.
.value[2].i32: line style of the bottom border. The parameter type is [ArkUI_BorderStyle](#arkui_borderstyle). The default value is **ARKUI_BORDER_STYLE_SOLID**.
.value[3].i32: line style of the left border. The parameter type is [ArkUI_BorderStyle](#arkui_borderstyle). The default value is **ARKUI_BORDER_STYLE_SOLID**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: line style of the top border.
.value[1].i32: line style of the right border.
.value[2].i32: line style of the bottom border.
.value[3].i32: line style of the left border.| | NODE_Z_INDEX | Defines the z-index attribute for the stack sequence. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: z-index value.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: z-index value.| -| NODE_VISIBILITY | Defines the visibility attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to show or hide the component. The parameter type is [ArkUI_Visibility](#arkui_visibility). The default value is **ARKUI_VISIBILITY_VISIBLE**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to show or hide the component. The parameter type is [ArkUI_Visibility](#arkui_visibility). The default value is **ARKUI_VISIBILITY_VISIBLE**.| -| NODE_CLIP | Defines the clip attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to clip the component based on the parent container bounds. The value **0** means to clip the component, and **1** means the opposite.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to clip the component based on the parent container bounds. The value **0** means to clip the component, and **1** means the opposite.| -| NODE_CLIP_SHAPE | Defines the clipping region on the component. This attribute can be set and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute, which supports five types of shapes:
1. Rectangle:
.value[0].i32: type of shape. The parameter type is [ArkUI_ClipType](#arkui_cliptype). The value is **ARKUI_CLIP_TYPE_RECTANGLE** for the rectangle shape.
.value[1].f32: width of the rectangle.
.value[2].f32: height of the rectangle.
.value[3].f32: width of the rounded corner of the rectangle.
.value[4].f32: height of the rounded corner of the rectangle.
.value[5]?.f32: radius of the upper left corner of the rectangle.
.value[6]?.f32: radius of the lower left corner of the rectangle.
.value[7]?.f32: radius of the upper right corner of the rectangle.
.value[8]?.f32: radius of the lower right corner of the rectangle.
2. Circle:
.value[0].i32: type of shape. The parameter type is [ArkUI_ClipType](#arkui_cliptype). The value is **ARKUI_CLIP_TYPE_CIRCLE** for the circle shape.
.value[1].f32: width of the circle.
.value[2].f32: height of the circle.
3. Ellipse:
.value[0].i32: type of shape. The parameter type is [ArkUI_ClipType](#arkui_cliptype). The value is **ARKUI_CLIP_TYPE_ELLIPSE** for the ellipse shape.
.value[1].f32: width of the ellipse.
.value[2].f32: height of the ellipse.
4. Path:
.value[0].i32: type of shape. The parameter type is [ArkUI_ClipType](#arkui_cliptype). The value is **ARKUI_CLIP_TYPE_PATH** for the path shape.
.value[1].f32: width of the path.
.value[2].f32: height of the path.
.string: command for drawing the path.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md), which supports five types of shapes:
1. Rectangle:
.value[0].i32: type of shape. The parameter type is [ArkUI_ClipType](#arkui_cliptype). The value is **ARKUI_CLIP_TYPE_RECTANGLE** for the rectangle shape.
.value[1].f32: width of the rectangle.
.value[2].f32: height of the rectangle.
.value[3].f32: width of the rounded corner of the rectangle.
.value[4].f32: height of the rounded corner of the rectangle.
.value[5]?.f32: radius of the upper left corner of the rectangle.
.value[6]?.f32: radius of the lower left corner of the rectangle.
.value[7]?.f32: radius of the upper right corner of the rectangle.
.value[8]?.f32: radius of the lower right corner of the rectangle.
2. Circle:
.value[0].i32: type of shape. The parameter type is [ArkUI_ClipType](#arkui_cliptype). The value is **ARKUI_CLIP_TYPE_CIRCLE** for the circle shape.
.value[1].f32: width of the circle.
.value[2].f32: height of the circle.
3. Ellipse:
.value[0].i32: type of shape. The parameter type is [ArkUI_ClipType](#arkui_cliptype). The value is **ARKUI_CLIP_TYPE_ELLIPSE** for the ellipse shape.
.value[1].f32: width of the ellipse.
.value[2].f32: height of the ellipse.
4. Path:
.value[0].i32: type of shape. The parameter type is [ArkUI_ClipType](#arkui_cliptype). The value is **ARKUI_CLIP_TYPE_PATH** for the path shape.
.value[1].f32: width of the path.
.value[2].f32: height of the path.
.string: command for drawing the path.| +| NODE_VISIBILITY | Defines the visibility attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to show or hide the component. The parameter type is [ArkUI_Visibility](#arkui_visibility). The default value is **ARKUI_VISIBILITY_VISIBLE**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to show or hide the component. The parameter type is [ArkUI_Visibility](#arkui_visibility). The default value is **ARKUI_VISIBILITY_VISIBLE**.| +| NODE_CLIP | Defines the clip attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to clip the component based on the parent container bounds. The value **0** means to clip the component, and **1** means the opposite.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to clip the component based on the parent container bounds. The value **0** means to clip the component, and **1** means the opposite.| +| NODE_CLIP_SHAPE | Defines the clipping region on the component. This attribute can be set and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute, which supports five types of shapes:
1. Rectangle:
.value[0].i32: type of shape. The parameter type is [ArkUI_ClipType](#arkui_cliptype). The value is **ARKUI_CLIP_TYPE_RECTANGLE** for the rectangle shape.
.value[1].f32: width of the rectangle.
.value[2].f32: height of the rectangle.
.value[3].f32: width of the rounded corner of the rectangle.
.value[4].f32: height of the rounded corner of the rectangle.
.value[5]?.f32: radius of the upper left corner of the rectangle.
.value[6]?.f32: radius of the lower left corner of the rectangle.
.value[7]?.f32: radius of the upper right corner of the rectangle.
.value[8]?.f32: radius of the lower right corner of the rectangle.
2. Circle:
.value[0].i32: type of shape. The parameter type is [ArkUI_ClipType](#arkui_cliptype). The value is **ARKUI_CLIP_TYPE_CIRCLE** for the circle shape.
.value[1].f32: width of the circle.
.value[2].f32: height of the circle.
3. Ellipse:
.value[0].i32: type of shape. The parameter type is [ArkUI_ClipType](#arkui_cliptype). The value is **ARKUI_CLIP_TYPE_ELLIPSE** for the ellipse shape.
.value[1].f32: width of the ellipse.
.value[2].f32: height of the ellipse.
4. Path:
.value[0].i32: type of shape. The parameter type is [ArkUI_ClipType](#arkui_cliptype). The value is **ARKUI_CLIP_TYPE_PATH** for the path shape.
.value[1].f32: width of the path.
.value[2].f32: height of the path.
.string: command for drawing the path.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md), which supports five types of shapes:
1. Rectangle:
.value[0].i32: type of shape. The parameter type is [ArkUI_ClipType](#arkui_cliptype). The value is **ARKUI_CLIP_TYPE_RECTANGLE** for the rectangle shape.
.value[1].f32: width of the rectangle.
.value[2].f32: height of the rectangle.
.value[3].f32: width of the rounded corner of the rectangle.
.value[4].f32: height of the rounded corner of the rectangle.
.value[5]?.f32: radius of the upper left corner of the rectangle.
.value[6]?.f32: radius of the lower left corner of the rectangle.
.value[7]?.f32: radius of the upper right corner of the rectangle.
.value[8]?.f32: radius of the lower right corner of the rectangle.
2. Circle:
.value[0].i32: type of shape. The parameter type is [ArkUI_ClipType](#arkui_cliptype). The value is **ARKUI_CLIP_TYPE_CIRCLE** for the circle shape.
.value[1].f32: width of the circle.
.value[2].f32: height of the circle.
3. Ellipse:
.value[0].i32: type of shape. The parameter type is [ArkUI_ClipType](#arkui_cliptype). The value is **ARKUI_CLIP_TYPE_ELLIPSE** for the ellipse shape.
.value[1].f32: width of the ellipse.
.value[2].f32: height of the ellipse.
4. Path:
.value[0].i32: type of shape. The parameter type is [ArkUI_ClipType](#arkui_cliptype). The value is **ARKUI_CLIP_TYPE_PATH** for the path shape.
.value[1].f32: width of the path.
.value[2].f32: height of the path.
.string: command for drawing the path.| | NODE_TRANSFORM | Defines the transform attribute, which can be used to translate, rotate, and scale images. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0...15].f32: 16 floating-point numbers.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0...15].f32: 16 floating-point numbers.| -| NODE_HIT_TEST_BEHAVIOR | Defines the hit test behavior attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: hit test mode. The parameter type is [ArkUI_HitTestMode](#arkui_hittestmode). The default value is **ARKUI_HIT_TEST_MODE_DEFAULT**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: hit test mode. The parameter type is **ArkKUI_HitTestMode**. The default value is **ARKUI_HIT_TEST_MODE_DEFAULT**.| -| NODE_POSITION | Defines the offset attribute, which specifies the offset of the component's upper left corner relative to the parent container's. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: X coordinate.
.value[1].f32: Y coordinate.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: X coordinate.
.value[1].f32: Y coordinate.| -| NODE_SHADOW | Defines the shadow attribute. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: shadow effect. The parameter type is [ArkUI_ShadowStyle](#arkui_shadowstyle).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: shadow effect. The parameter type is [ArkUI_ShadowStyle](#arkui_shadowstyle).| -| NODE_CUSTOM_SHADOW | Defines the custom shadow effect. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0]?.f32: blur radius of the shadow, in vp.
.value[1]?.i32: whether to enable the coloring strategy. The value **1** means to enable the coloring strategy, and **0** (default value) means the opposite.
.value[2]?.f32: offset of the shadow along the x-axis, in px.
.value[3]?.f32: offset of the shadow along the y-axis, in px.
.value[4]?.i32: shadow type [ArkUI_ShadowType](#arkui_shadowtype). The default value is **ARKUI_SHADOW_TYPE_COLOR**.
.value[5]?.u32: shadow color, in 0xARGB format. For example, 0xFFFF0000 indicates red.
.value[6]?.u32: whether to fill the shadow. The value 1 means to fill the shadow, and 0 means the opposite.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: blur radius of the shadow, in vp.
.value[1].i32: whether to enable the coloring strategy.
.value[2].f32: offset of the shadow along the x-axis, in px.
.value[3].f32: offset of the shadow along the y-axis, in px.
.value[4].i32: shadow type [ArkUI_ShadowType](#arkui_shadowtype). The default value is **ARKUI_SHADOW_TYPE_COLOR**.
.value[5].u32: shadow color, in 0xARGB format. For example, 0xFFFF0000 indicates red.
.value[6].u32: whether to fill the shadow. The value **1** means to fill the shadow, and **0** means the opposite.| +| NODE_HIT_TEST_BEHAVIOR | Defines the hit test behavior attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: hit test mode. The parameter type is [ArkUI_HitTestMode](#arkui_hittestmode). The default value is **ARKUI_HIT_TEST_MODE_DEFAULT**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: hit test mode. The parameter type is **ArkKUI_HitTestMode**. The default value is **ARKUI_HIT_TEST_MODE_DEFAULT**.| +| NODE_POSITION | Defines the offset attribute, which specifies the offset of the component's upper left corner relative to the parent container's. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: X coordinate.
.value[1].f32: Y coordinate.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: X coordinate.
.value[1].f32: Y coordinate.| +| NODE_SHADOW | Defines the shadow attribute. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: shadow effect. The parameter type is [ArkUI_ShadowStyle](#arkui_shadowstyle).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: shadow effect. The parameter type is [ArkUI_ShadowStyle](#arkui_shadowstyle).| +| NODE_CUSTOM_SHADOW | Defines the custom shadow effect. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0]?.f32: blur radius of the shadow, in vp.
.value[1]?.i32: whether to enable the coloring strategy. The value **1** means to enable the coloring strategy, and **0** (default value) means the opposite.
.value[2]?.f32: offset of the shadow along the x-axis, in px.
.value[3]?.f32: offset of the shadow along the y-axis, in px.
.value[4]?.i32: shadow type [ArkUI_ShadowType](#arkui_shadowtype). The default value is **ARKUI_SHADOW_TYPE_COLOR**.
.value[5]?.u32: shadow color, in 0xARGB format. For example, 0xFFFF0000 indicates red.
.value[6]?.u32: whether to fill the shadow. The value 1 means to fill the shadow, and 0 means the opposite.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: blur radius of the shadow, in vp.
.value[1].i32: whether to enable the coloring strategy.
.value[2].f32: offset of the shadow along the x-axis, in px.
.value[3].f32: offset of the shadow along the y-axis, in px.
.value[4].i32: shadow type [ArkUI_ShadowType](#arkui_shadowtype). The default value is **ARKUI_SHADOW_TYPE_COLOR**.
.value[5].u32: shadow color, in 0xARGB format. For example, 0xFFFF0000 indicates red.
.value[6].u32: whether to fill the shadow. The value **1** means to fill the shadow, and **0** means the opposite.| | NODE_BACKGROUND_IMAGE_SIZE | Defines the background image width and height. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: width of the image. The value range is [0, +∞), and the unit is vp.
.value[1].f32: height of the image. The value range is [0, +∞), and the unit is vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: width of the image, in vp.
.value[1].f32: height of the image, in vp.| | NODE_BACKGROUND_IMAGE_SIZE_WITH_STYLE | Defines the background image size. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: size of the background image. The value is an enumerated value of [ArkUI_ImageSize](#arkui_imagesize).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: size of the background image. The value is an enumerated value of [ArkUI_ImageSize](#arkui_imagesize).| -| NODE_BACKGROUND_BLUR_STYLE | Defines the background blur attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: blur type. The value is an enumerated value of [ArkUI_BlurStyle](#arkui_blurstyle).
.value[1]?.i32: color mode. The value is an enumerated value of [ArkUI_ColorMode](#arkui_colormode).
.value[2]?.i32: adaptive color mode. The value is an enumerated value of [ArkUI_AdaptiveColor](#arkui_adaptivecolor).
.value[3]?.f32: blur degree. The value range is [0.0, 1.0].
.value[4]?.f32: start boundary of grayscale blur.
.value[5]?.f32: end boundary of grayscale blur.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: blur type. The value is an enumerated value of [ArkUI_BlurStyle](#arkui_blurstyle).
.value[1].i32: color mode. The value is an enumerated value of [ArkUI_ColorMode](#arkui_colormode).
.value[2].i32: adaptive color mode. The value is an enumerated value of [ArkUI_AdaptiveColor](#arkui_adaptivecolor).
.value[3].f32: blur degree. The value range is [0.0, 1.0].
.value[4].f32: start boundary of grayscale blur.
.value[5].f32: end boundary of grayscale blur.| -| NODE_TRANSFORM_CENTER | Defines the transform center attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0]?.f32: X coordinate of the center point, in vp.
.value[1]?.f32: Y coordinate of the center point, in vp.
.value[2]?.f32: Z coordinate of the center point, in vp.
.value[3]?.f32 : X coordinate of the center point, expressed in a number that represents a percentage. For example, 0.2 indicates 20%. This attribute overwrites value[0].f32. The default value is **0.5f**.
.value[4]?.f32 : Y coordinate of the center point, expressed in a number that represents a percentage. For example, 0.2 indicates 20%. This attribute overwrites value[1].f32. The default value is **0.5f**.
.value[5]?.f32 : Z coordinate of the center point, expressed in a number that represents a percentage. For example, 0.2 indicates 20%. This attribute overwrites value[2].f32. The default value is **0.0f**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: X coordinate of the center point, in vp.
.value[1].f32: Y coordinate of the center point, in vp.
.value[2].f32: Z coordinate of the center point, in vp.
Note: If the coordinate is expressed in a number that represents a percentage, the attribute obtaining API returns the calculated value in vp.| -| NODE_OPACITY_TRANSITION | Defines the transition opacity attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: opacity values of the start and end points.
.value[1].i32: animation duration, in milliseconds.
.value[2].i32: animation curve type. The value is an enumerated value of [ArkUI_AnimationCurve](#arkui_animationcurve).
.value[3]?.i32: animation delay duration, in milliseconds.
.value[4]?.i32: number of times that the animation is played.
.value[5]?.i32: animation playback mode. The value is an enumerated value of [ArkUI_AnimationPlayMode](#arkui_animationplaymode).
.value[6]?.f32: animation playback speed.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: opacity values of the start and end points.
.value[1].i32: animation duration, in milliseconds.
.value[2].i32: animation curve type. The value is an enumerated value of [ArkUI_AnimationCurve](#arkui_animationcurve).
.value[3].i32: animation delay duration, in milliseconds.
.value[4].i32: number of times that the animation is played.
.value[5].i32: animation playback mode. The value is an enumerated value of [ArkUI_AnimationPlayMode](#arkui_animationplaymode).
.value[6].f32: animation playback speed.| -| NODE_ROTATE_TRANSITION | Defines the transition rotation attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: X-component of the rotation vector.
.value[1].f32: Y-component of the rotation vector.
.value[2].f32: Z-component of the rotation vector
.value[3].f32: angle.
.value[4].f32: line of sight. The default value is **0.0f**.
.value[5].i32: animation duration, in milliseconds.
.value[6].i32: animation curve type. The value is an enumerated value of [ArkUI_AnimationCurve](#arkui_animationcurve).
.value[7]?.i32: animation delay duration, in milliseconds.
.value[8]?.i32: number of times that the animation is played.
.value[9]?.i32: animation playback mode. The value is an enumerated value of [ArkUI_AnimationPlayMode](#arkui_animationplaymode).
.value[10]?.f32: animation playback speed.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: X-component of the rotation vector.
.value[1].f32: Y-component of the rotation vector.
.value[2].f32: Z-component of the rotation vector
.value[3].f32: angle.
.value[4].f32: line of sight.
.value[5].i32: animation duration, in milliseconds.
.value[6].i32: animation curve type. The value is an enumerated value of [ArkUI_AnimationCurve](#arkui_animationcurve).
.value[7].i32: animation delay duration, in milliseconds.
.value[8].i32: number of times that the animation is played.
.value[9].i32: animation playback mode. The value is an enumerated value of [ArkUI_AnimationPlayMode](#arkui_animationplaymode).
.value[10].f32: animation playback speed.| -| NODE_SCALE_TRANSITION | Defines the transition scaling attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: scale factor along the x-axis.
.value[1].f32: scale factor along the y-axis.
.value[2].f32: scale factor along the z-axis.
value[3].i32: animation duration, in milliseconds.
.value[4].i32: animation curve type. The value is an enumerated value of [ArkUI_AnimationCurve](#arkui_animationcurve).
.value[5]?.i32: animation delay duration, in milliseconds.
.value[6]?.i32: number of times that the animation is played.
.value[7]?.i32: animation playback mode. The value is an enumerated value of [ArkUI_AnimationPlayMode](#arkui_animationplaymode).
value[8]?.f32: animation playback speed.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: scale factor along the x-axis.
.value[1].f32: scale factor along the y-axis.
.value[2].f32: scale factor along the z-axis.
value[3].i32: animation duration, in milliseconds.
.value[4].i32: animation curve type. The value is an enumerated value of [ArkUI_AnimationCurve](#arkui_animationcurve).
value[5].i32: animation delay duration, in milliseconds.
value[6].i32: number of times that the animation is played.
.value[7].i32: animation playback mode. The value is an enumerated value of [ArkUI_AnimationPlayMode](#arkui_animationplaymode).
value[8].f32: animation playback speed.| -| NODE_TRANSLATE_TRANSITION | Defines the transition translation attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
value[0].f32: translation distance along the x-axis, in vp.
value[1].f32: translation distance along the y-axis, in vp.
value[2].f32: translation distance along the z-axis, in vp.
value[3].i32: animation duration, in milliseconds.
value[4].i32: animation curve type. The value is an enumerated value of [ArkUI_AnimationCurve](#arkui_animationcurve).
value[5]?.i32: animation delay duration, in milliseconds.
value[6]?.i32: number of times that the animation is played.
value[7]?.i32: animation playback mode. The value is an enumerated value of [ArkUI_AnimationPlayMode](#arkui_animationplaymode).
value[8]?.f32: animation playback speed.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
value[0].f32: translation distance along the x-axis, in vp.
value[1].f32: translation distance along the y-axis, in vp.
value[2].f32: translation distance along the z-axis, in vp.
value[3].i32: animation duration, in milliseconds.
value[4].i32: animation curve type. The value is an enumerated value of [ArkUI_AnimationCurve](#arkui_animationcurve).
value[5].i32: animation delay duration, in milliseconds.
value[6].i32: number of times that the animation is played.
value[7].i32: animation playback mode. The value is an enumerated value of [ArkUI_AnimationPlayMode](#arkui_animationplaymode).
value[8].f32: animation playback speed.| -| NODE_MOVE_TRANSITION | Defines the slide-in and slide-out of the component from the screen edge during transition. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: [ArkUI_TransitionEdge](#arkui_transitionedge) type.
.value[1].i32: animation duration, in milliseconds.
.value[2].i32: animation curve type. The value is an enumerated value of [ArkUI_AnimationCurve](#arkui_animationcurve).
.value[3]?.i32: animation delay duration, in milliseconds.
.value[4]?.i32: number of times that the animation is played.
.value[5]?.i32: animation playback mode. The value is an enumerated value of [ArkUI_AnimationPlayMode](#arkui_animationplaymode).
.value[6]?.f32: animation playback speed.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: [ArkUI_TransitionEdge](#arkui_transitionedge) type.
.value[1].i32: animation duration, in milliseconds.
.value[2].i32: animation curve type. The value is an enumerated value of [ArkUI_AnimationCurve](#arkui_animationcurve).
.value[3].i32: animation delay duration, in milliseconds.
.value[4].i32: number of times that the animation is played.
.value[5].i32: animation playback mode. The value is an enumerated value of [ArkUI_AnimationPlayMode](#arkui_animationplaymode).
.value[6].f32: animation playback speed.| -| NODE_FOCUSABLE | Defines the focus attribute, which can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: The parameter type is 1 or 0.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: The parameter type is 1 or 0.| -| NODE_DEFAULT_FOCUS | Defines the default focus attribute, which can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
value[0].i32: The parameter type is 1 or 0.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
value[0].i32: The parameter type is 1 or 0.| -| NODE_RESPONSE_REGION | Defines the touch target attribute, which can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.data[0].f32: X coordinate of the touch point relative to the upper left corner of the component, in vp.
.data[1].f32: Y coordinate of the touch point relative to the upper left corner of the component, in vp.
.data[2].f32: width of the touch target, in percentage.
.data[3].f32: height of the touch target, in percentage.
.data[4...].f32: Multiple touch targets can be set. The sequence of the parameters is the same as the preceding.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.data[0].f32: X coordinate of the touch point relative to the upper left corner of the component, in vp.
.data[1].f32: Y coordinate of the touch point relative to the upper left corner of the component, in vp.
.data[2].f32: width of the touch target, in percentage.
.data[3].f32: height of the touch target, in percentage.
.data[4...].f32: Multiple touch targets can be set. The sequence of the parameters is the same as the preceding.| -| NODE_OVERLAY | Defines the overlay attribute, which can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: mask text.
.value[0]?.i32: position of the overlay relative to the component. Optional. The parameter type is [ArkUI_Alignment](#arkui_alignment). The default value is **ARKUI_ALIGNMENT_TOP_START**.
.value[1]?.f32: offset of the overlay relative to the upper left corner of itself on the x-axis, in vp. Optional.
.value[2]?.f32: offset of the overlay relative to the upper left corner of itself on the y-axis, in vp. Optional.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: mask text.
.value[0].i32: position of the overlay relative to the component. The parameter type is [ArkUI_Alignment](#arkui_alignment). The default value is **ARKUI_ALIGNMENT_TOP_START**.
.value[1].f32: offset of the overlay relative to the upper left corner of itself on the x-axis, in vp.
.value[2].f32: offset of the overlay relative to the upper left corner of itself on the y-axis, in vp.| +| NODE_BACKGROUND_BLUR_STYLE | Defines the background blur attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: blur type. The value is an enumerated value of [ArkUI_BlurStyle](#arkui_blurstyle).
.value[1]?.i32: color mode. The value is an enumerated value of [ArkUI_ColorMode](#arkui_colormode).
.value[2]?.i32: adaptive color mode. The value is an enumerated value of [ArkUI_AdaptiveColor](#arkui_adaptivecolor).
.value[3]?.f32: blur degree. The value range is [0.0, 1.0].
.value[4]?.f32: start boundary of grayscale blur.
.value[5]?.f32: end boundary of grayscale blur.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: blur type. The value is an enumerated value of [ArkUI_BlurStyle](#arkui_blurstyle).
.value[1].i32: color mode. The value is an enumerated value of [ArkUI_ColorMode](#arkui_colormode).
.value[2].i32: adaptive color mode. The value is an enumerated value of [ArkUI_AdaptiveColor](#arkui_adaptivecolor).
.value[3].f32: blur degree. The value range is [0.0, 1.0].
.value[4].f32: start boundary of grayscale blur.
.value[5].f32: end boundary of grayscale blur.| +| NODE_TRANSFORM_CENTER | Defines the transform center attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0]?.f32: X coordinate of the center point, in vp.
.value[1]?.f32: Y coordinate of the center point, in vp.
.value[2]?.f32: Z coordinate of the center point, in vp.
.value[3]?.f32 : X coordinate of the center point, expressed in a number that represents a percentage. For example, 0.2 indicates 20%. This attribute overwrites value[0].f32. The default value is **0.5f**.
.value[4]?.f32 : Y coordinate of the center point, expressed in a number that represents a percentage. For example, 0.2 indicates 20%. This attribute overwrites value[1].f32. The default value is **0.5f**.
.value[5]?.f32 : Z coordinate of the center point, expressed in a number that represents a percentage. For example, 0.2 indicates 20%. This attribute overwrites value[2].f32. The default value is **0.0f**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: X coordinate of the center point, in vp.
.value[1].f32: Y coordinate of the center point, in vp.
.value[2].f32: Z coordinate of the center point, in vp.
Note: If the coordinate is expressed in a number that represents a percentage, the attribute obtaining API returns the calculated value in vp.| +| NODE_OPACITY_TRANSITION | Defines the transition opacity attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: opacity values of the start and end points.
.value[1].i32: animation duration, in milliseconds.
.value[2].i32: animation curve type. The value is an enumerated value of [ArkUI_AnimationCurve](#arkui_animationcurve).
.value[3]?.i32: animation delay duration, in milliseconds.
.value[4]?.i32: number of times that the animation is played.
.value[5]?.i32: animation playback mode. The value is an enumerated value of [ArkUI_AnimationPlayMode](#arkui_animationplaymode).
.value[6]?.f32: animation playback speed.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: opacity values of the start and end points.
.value[1].i32: animation duration, in milliseconds.
.value[2].i32: animation curve type. The value is an enumerated value of [ArkUI_AnimationCurve](#arkui_animationcurve).
.value[3].i32: animation delay duration, in milliseconds.
.value[4].i32: number of times that the animation is played.
.value[5].i32: animation playback mode. The value is an enumerated value of [ArkUI_AnimationPlayMode](#arkui_animationplaymode).
.value[6].f32: animation playback speed.| +| NODE_ROTATE_TRANSITION | Defines the transition rotation attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: X-component of the rotation vector.
.value[1].f32: Y-component of the rotation vector.
.value[2].f32: Z-component of the rotation vector
.value[3].f32: angle.
.value[4].f32: line of sight. The default value is **0.0f**.
.value[5].i32: animation duration, in milliseconds.
.value[6].i32: animation curve type. The value is an enumerated value of [ArkUI_AnimationCurve](#arkui_animationcurve).
.value[7]?.i32: animation delay duration, in milliseconds.
.value[8]?.i32: number of times that the animation is played.
.value[9]?.i32: animation playback mode. The value is an enumerated value of [ArkUI_AnimationPlayMode](#arkui_animationplaymode).
.value[10]?.f32: animation playback speed.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: X-component of the rotation vector.
.value[1].f32: Y-component of the rotation vector.
.value[2].f32: Z-component of the rotation vector
.value[3].f32: angle.
.value[4].f32: line of sight.
.value[5].i32: animation duration, in milliseconds.
.value[6].i32: animation curve type. The value is an enumerated value of [ArkUI_AnimationCurve](#arkui_animationcurve).
.value[7].i32: animation delay duration, in milliseconds.
.value[8].i32: number of times that the animation is played.
.value[9].i32: animation playback mode. The value is an enumerated value of [ArkUI_AnimationPlayMode](#arkui_animationplaymode).
.value[10].f32: animation playback speed.| +| NODE_SCALE_TRANSITION | Defines the transition scaling attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: scale factor along the x-axis.
.value[1].f32: scale factor along the y-axis.
.value[2].f32: scale factor along the z-axis.
value[3].i32: animation duration, in milliseconds.
.value[4].i32: animation curve type. The value is an enumerated value of [ArkUI_AnimationCurve](#arkui_animationcurve).
.value[5]?.i32: animation delay duration, in milliseconds.
.value[6]?.i32: number of times that the animation is played.
.value[7]?.i32: animation playback mode. The value is an enumerated value of [ArkUI_AnimationPlayMode](#arkui_animationplaymode).
value[8]?.f32: animation playback speed.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: scale factor along the x-axis.
.value[1].f32: scale factor along the y-axis.
.value[2].f32: scale factor along the z-axis.
value[3].i32: animation duration, in milliseconds.
.value[4].i32: animation curve type. The value is an enumerated value of [ArkUI_AnimationCurve](#arkui_animationcurve).
value[5].i32: animation delay duration, in milliseconds.
value[6].i32: number of times that the animation is played.
.value[7].i32: animation playback mode. The value is an enumerated value of [ArkUI_AnimationPlayMode](#arkui_animationplaymode).
value[8].f32: animation playback speed.| +| NODE_TRANSLATE_TRANSITION | Defines the transition translation attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
value[0].f32: translation distance along the x-axis, in vp.
value[1].f32: translation distance along the y-axis, in vp.
value[2].f32: translation distance along the z-axis, in vp.
value[3].i32: animation duration, in milliseconds.
value[4].i32: animation curve type. The value is an enumerated value of [ArkUI_AnimationCurve](#arkui_animationcurve).
value[5]?.i32: animation delay duration, in milliseconds.
value[6]?.i32: number of times that the animation is played.
value[7]?.i32: animation playback mode. The value is an enumerated value of [ArkUI_AnimationPlayMode](#arkui_animationplaymode).
value[8]?.f32: animation playback speed.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
value[0].f32: translation distance along the x-axis, in vp.
value[1].f32: translation distance along the y-axis, in vp.
value[2].f32: translation distance along the z-axis, in vp.
value[3].i32: animation duration, in milliseconds.
value[4].i32: animation curve type. The value is an enumerated value of [ArkUI_AnimationCurve](#arkui_animationcurve).
value[5].i32: animation delay duration, in milliseconds.
value[6].i32: number of times that the animation is played.
value[7].i32: animation playback mode. The value is an enumerated value of [ArkUI_AnimationPlayMode](#arkui_animationplaymode).
value[8].f32: animation playback speed.| +| NODE_MOVE_TRANSITION | Defines the slide-in and slide-out of the component from the screen edge during transition. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: [ArkUI_TransitionEdge](#arkui_transitionedge) type.
.value[1].i32: animation duration, in milliseconds.
.value[2].i32: animation curve type. The value is an enumerated value of [ArkUI_AnimationCurve](#arkui_animationcurve).
.value[3]?.i32: animation delay duration, in milliseconds.
.value[4]?.i32: number of times that the animation is played.
.value[5]?.i32: animation playback mode. The value is an enumerated value of [ArkUI_AnimationPlayMode](#arkui_animationplaymode).
.value[6]?.f32: animation playback speed.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: [ArkUI_TransitionEdge](#arkui_transitionedge) type.
.value[1].i32: animation duration, in milliseconds.
.value[2].i32: animation curve type. The value is an enumerated value of [ArkUI_AnimationCurve](#arkui_animationcurve).
.value[3].i32: animation delay duration, in milliseconds.
.value[4].i32: number of times that the animation is played.
.value[5].i32: animation playback mode. The value is an enumerated value of [ArkUI_AnimationPlayMode](#arkui_animationplaymode).
.value[6].f32: animation playback speed.| +| NODE_FOCUSABLE | Defines the focus attribute, which can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: The parameter type is 1 or 0.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: The parameter type is 1 or 0.| +| NODE_DEFAULT_FOCUS | Defines the default focus attribute, which can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
value[0].i32: The parameter type is 1 or 0.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
value[0].i32: The parameter type is 1 or 0.| +| NODE_RESPONSE_REGION | Defines the touch target attribute, which can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.data[0].f32: X coordinate of the touch point relative to the upper left corner of the component, in vp.
.data[1].f32: Y coordinate of the touch point relative to the upper left corner of the component, in vp.
.data[2].f32: width of the touch target, in percentage.
.data[3].f32: height of the touch target, in percentage.
.data[4...].f32: Multiple touch targets can be set. The sequence of the parameters is the same as the preceding.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.data[0].f32: X coordinate of the touch point relative to the upper left corner of the component, in vp.
.data[1].f32: Y coordinate of the touch point relative to the upper left corner of the component, in vp.
.data[2].f32: width of the touch target, in percentage.
.data[3].f32: height of the touch target, in percentage.
.data[4...].f32: Multiple touch targets can be set. The sequence of the parameters is the same as the preceding.| +| NODE_OVERLAY | Defines the overlay attribute, which can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: mask text.
.value[0]?.i32: position of the overlay relative to the component. Optional. The parameter type is [ArkUI_Alignment](#arkui_alignment). The default value is **ARKUI_ALIGNMENT_TOP_START**.
.value[1]?.f32: offset of the overlay relative to the upper left corner of itself on the x-axis, in vp. Optional.
.value[2]?.f32: offset of the overlay relative to the upper left corner of itself on the y-axis, in vp. Optional.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: mask text.
.value[0].i32: position of the overlay relative to the component. The parameter type is [ArkUI_Alignment](#arkui_alignment). The default value is **ARKUI_ALIGNMENT_TOP_START**.
.value[1].f32: offset of the overlay relative to the upper left corner of itself on the x-axis, in vp.
.value[2].f32: offset of the overlay relative to the upper left corner of itself on the y-axis, in vp.| | NODE_SWEEP_GRADIENT | Defines the sweep gradient effect. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0]?.f32: X coordinate of the sweep gradient center relative to the upper left corner of the component.
.value[1]?.f32: Y coordinate of the sweep gradient center relative to the upper left corner of the component.
.value[2]?.f32: start point of the sweep gradient. The default value is **0**.
.value[3]?.f32: end point of the sweep gradient. The default value is **0**.
.value[4]?.f32: rotation angle of the sweep gradient. The default value is **0**.
.value[5]?.i32: whether the colors are repeated. The value **1** means that the colors are repeated, and **0** means the opposite.
.object: The parameter type is [ArkUI_ColorStop](_ark_u_i___color_stop.md). - **colors**: array of color stops, each of which consists of a color and its stop position. Invalid colors are automatically skipped.
**colors**: colors of the color stops.
**stops**: stop positions of the color stops.
**size**: number of colors.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: X coordinate of the sweep gradient center relative to the upper left corner of the component.
.value[1].f32: Y coordinate of the sweep gradient center relative to the upper left corner of the component.
.value[2].f32: start point of the sweep gradient. The default value is **0**.
.value[3].f32: end point of the sweep gradient. The default value is **0**.
.value[4].f32: rotation angle of the sweep gradient. The default value is **0**.
.value[5].i32: whether the colors are repeated. The value **1** means that the colors are repeated, and **0** means the opposite.
.object: The parameter type is [ArkUI_ColorStop](_ark_u_i___color_stop.md). - **colors**: array of color stops, each of which consists of a color and its stop position. Invalid colors are automatically skipped.
**colors**: colors of the color stops.
**stops**: stop positions of the color stops.
**size**: number of colors.| | NODE_RADIAL_GRADIENT | Defines the radial gradient effect. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0]?.f32: X coordinate of the radial gradient center relative to the upper left corner of the component.
.value[1]?.f32: Y coordinate of the radial gradient center relative to the upper left corner of the component.
.value[2]?.f32: radius of the radial gradient. The default value is **0**.
.value[3]?.i32: whether the colors are repeated. The value **1** means that the colors are repeated, and **0** means the opposite.
.object: The parameter type is [ArkUI_ColorStop](_ark_u_i___color_stop.md). - **colors**: array of color stops, each of which consists of a color and its stop position. Invalid colors are automatically skipped.
**colors**: colors of the color stops.
**stops**: stop positions of the color stops.
**size**: number of colors.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: X coordinate of the radial gradient center relative to the upper left corner of the component.
.value[1].f32: Y coordinate of the radial gradient center relative to the upper left corner of the component.
.value[2].f32: radius of the radial gradient. The default value is **0**.
.value[3].i32: whether the colors are repeated. The value **1** means that the colors are repeated, and **0** means the opposite.
.object: The parameter type is [ArkUI_ColorStop](_ark_u_i___color_stop.md). - **colors**: array of color stops, each of which consists of a color and its stop position. Invalid colors are automatically skipped.
**colors**: colors of the color stops.
**stops**: stop positions of the color stops.
**size**: number of colors.| | NODE_MASK | Adds a mask of the specified shape to the component. APIs are provided for setting and obtaining the attribute value.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute, which supports five types of shapes:
1. Rectangle:
.value[0].u32 fill color, in 0xARGB format.
.value[1].u32: stroke color, in 0xARGB format.
.value[2].f32: stroke width, in vp.
.value[3].i32: mask type. The parameter type is [ArkUI_MaskType](#arkui_masktype). The value is **ARKUI_MASK_TYPE_RECTANGLE** for the rectangle shape.
.value[4].f32: width of the rectangle.
.value[5].f32: height of the rectangle.
.value[6].f32: width of the rounded corner of the rectangle.
.value[7].f32: height of the rounded corner of the rectangle.
.value[8]?.f32: radius of the upper left corner of the rectangle.
.value[9]?.f32: radius of the lower left corner of the rectangle.
.value[10]?.f32: radius of the upper right corner of the rectangle.
.value[11]?.f32: radius of the lower right corner of the rectangle.
2. Circle:
.value[0].u32 fill color, in 0xARGB format.
.value[1].u32: stroke color, in 0xARGB format.
.value[2].f32: stroke width, in vp.
.value[3].i32: mask type. The parameter type is [ArkUI_MaskType](#arkui_masktype). The value is **ARKUI_MASK_TYPE_CIRCLE** for the circle shape.
.value[4].f32: width of the circle.
.value[5].f32: height of the circle.
3. Ellipse:
.value[0].u32 fill color, in 0xARGB format.
.value[1].u32: stroke color, in 0xARGB format.
.value[2].f32: stroke width, in vp.
.value[3].i32: mask type. The parameter type is [ArkUI_MaskType](#arkui_masktype). The value is **ARKUI_MASK_TYPE_ELLIPSE** for the ellipse shape.
.value[4].f32: width of the ellipse.
.value[5].f32: height of the ellipse.
4. Path:
.value[0].u32 fill color, in 0xARGB format.
.value[1].u32: stroke color, in 0xARGB format.
.value[2].f32: stroke width, in vp.
.value[3].i32: mask type. The parameter type is [ArkUI_MaskType](#arkui_masktype). The value is **ARKUI_MASK_TYPE_PATH** for the path shape.
.value[4].f32: width of the path.
.value[5].f32: height of the path.
.string: command for drawing the path.
5. Progress:
.value[0].i32: mask type. The parameter type is [ArkUI_MaskType](#arkui_masktype). The value is **ARKUI_MASK_TYPE_PROGRESS** for the progress shape.
.value[1].f32: current value of the progress indicator.
.value[2].f32: maximum value of the progress indicator.
.value[3].u32: color of the progress indicator.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md), which supports five types of shapes:
1. Rectangle:
.value[0].u32 fill color, in 0xARGB format.
.value[1].u32: stroke color, in 0xARGB format.
.value[2].f32: stroke width, in vp.
.value[3].i32: mask type.
.value[4].f32: width of the rectangle.
.value[5].f32: height of the rectangle.
.value[6].f32: width of the rounded corner of the rectangle.
.value[7].f32: height of the rounded corner of the rectangle.
.value[8]?.f32: radius of the upper left corner of the rectangle.
.value[9]?.f32: radius of the lower left corner of the rectangle.
.value[10]?.f32: radius of the upper right corner of the rectangle.
.value[11]?.f32: radius of the lower right corner of the rectangle.
2. Circle:
.value[0].u32 fill color, in 0xARGB format.
.value[1].u32: stroke color, in 0xARGB format.
.value[2].f32: stroke width, in vp.
.value[3].i32: mask type.
.value[4].f32: width of the circle.
.value[5].f32: height of the circle.
3. Ellipse:
.value[0].u32 fill color, in 0xARGB format.
.value[1].u32: stroke color, in 0xARGB format.
.value[2].f32: stroke width, in vp.
.value[3].i32: mask type.
.value[4].f32: width of the ellipse.
.value[5].f32: height of the ellipse.
4. Path:
.value[0].u32 fill color, in 0xARGB format.
.value[1].u32: stroke color, in 0xARGB format.
.value[2].f32: stroke width, in vp.
.value[3].i32: mask type.
.value[4].f32: width of the path.
.value[5].f32: height of the path.
.string: command for drawing the path.
5. Progress:
.value[0].i32: mask type.
.value[1].f32: current value of the progress indicator.
.value[2].f32: maximum value of the progress indicator.
.value[3].u32: color of the progress indicator.| @@ -3093,320 +3373,341 @@ Defines the ArkUI style attributes that can be set on the native side. | NODE_ACCESSIBILITY_TEXT | Sets the accessibility text. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: accessibility text.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: accessibility text.| | NODE_ACCESSIBILITY_MODE | Defines the accessibility mode. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: auxiliary service mode. The parameter type is [ArkUI_AccessibilityMode](#arkui_accessibilitymode).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: auxiliary service mode. The parameter type is [ArkUI_AccessibilityMode](#arkui_accessibilitymode).| | NODE_ACCESSIBILITY_DESCRIPTION | Sets the accessibility description. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: accessibility description.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: accessibility description.| -| NODE_FOCUS_STATUS | This interface is used to obtain focus attributes. Attributes can be set and obtained.
**NOTE**
Setting the parameter to **0** shifts focus from the currently focused component on the current level of the page to the root container.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: The parameter type is 1 or 0.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
value[0].i32: The parameter type is 1 or 0.| -| NODE_ASPECT_RATIO | Defines the aspect ratio attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: aspect ratio of the component, in width/height format.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: aspect ratio of the component, in width/height format.| -| NODE_LAYOUT_WEIGHT | Defines the weight of the component within its row, column, or flex container for proportional distribution of available space within the container. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: weight of the component along the main axis.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: weight of the component along the main axis.| -| NODE_DISPLAY_PRIORITY | Sets the display priority for the component in the row, column, or flex (single-line) container. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: display priority of the component in the container.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: display priority of the component in the container.| -| NODE_OUTLINE_WIDTH | Sets the thickness of an element's outline.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: thickness of the left outline.
.value[1].f32: thickness of the top outline.
.value[2].f32: thickness of the right outline.
.value[3].f32: thickness of the bottom outline.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: thickness of the left outline.
.value[1].f32: thickness of the top outline.
.value[2].f32: thickness of the right outline.
.value[3].f32: thickness of the bottom outline.| -| NODE_WIDTH_PERCENT | Defines the width attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: width, in percentage.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: width, in percentage. | -| NODE_HEIGHT_PERCENT | Defines the height attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: height, in percentage.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: height, in percentage. | -| NODE_PADDING_PERCENT | Defines the padding attribute, which can be set, reset, and obtained as required through APIs.
There are two formats of [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) for setting the attribute value:
1: Specify the same padding for the four directions.
.value[0].f32: padding, in percentage.
2: Specify different paddings for different directions.
.value[0].f32: top padding, in percentage.
.value[1].f32: right padding, in percentage.
.value[2].f32: bottom padding, in percentage.
.value[3].f32: left padding, in percentage.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: top padding, in percentage.
.value[1].f32: right padding, in percentage.
.value[2].f32: bottom padding, in percentage.
.value[3].f32: left padding, in percentage. | -| NODE_MARGIN_PERCENT | Defines the margin attribute, which can be set, reset, and obtained as required through APIs.
There are two formats of [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) for setting the attribute value:
1: Specify the same margin for the four directions.
.value[0].f32: margin, in percentage.
2: Specify different margins for different directions.
.value[0].f32: top margin, in percentage.
.value[1].f32: right margin, in percentage.
.value[2].f32: bottom margin, in percentage.
.value[3].f32: left margin, in percentage.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: top margin, in percentage.
.value[1].f32: right margin, in percentage.
.value[2].f32: bottom margin, in percentage.
.value[3].f32: left margin, in percentage. | -| NODE_GEOMETRY_TRANSITION | Implements an implicit shared element transition. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: two components bound to the shared element. The parameter type is 1 or 0. By default, the out component does not continue to participate in the shared element animation when not yet deleted, which means that it stays in its original position.
.string: ID used to set up a binding relationship. If this attribute is set to an empty string **""**, the binding relationship is cleared. The value can be dynamically changed to refresh the binding relationship. One ID can be bound to only two components, which function as in and out components.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: two components bound to the shared element. The parameter type is 1 or 0. By default, the out component does not continue to participate in the shared element animation when not yet deleted, which means that it stays in its original position.
.string: ID used to set up a binding relationship. If this attribute is set to an empty string **""**, the binding relationship is cleared. The value can be dynamically changed to refresh the binding relationship. One ID can be bound to only two components, which function as in and out components.| -| NODE_RELATIVE_LAYOUT_CHAIN_MODE | Specifies the parameters of the chain formed by the component as the chain head. The attribute setting, attribute resetting, and attribute obtaining interfaces are supported.
This attribute has effect only when the parent container is **RelativeContainer**.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: direction of the chain. Enumeration [ArkUI_Axis](#arkui_axis).
.value[1].i32: style of the chain. Enumeration [ArkUI_RelativeLayoutChainStyle](#arkui_relativelayoutchainstyle).
.value[0].i32: direction of the chain. Enumeration [ArkUI_Axis](#arkui_axis).
.value[1].i32: style of the chain. Enumeration [ArkUI_RelativeLayoutChainStyle](#arkui_relativelayoutchainstyle).| -| NODE_RENDER_FIT | Sets how the final state of the component's content is rendered during its width and height animation process. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32 Content filling mode. The enumerated values of [ArkUI_RenderFit](#arkui_renderfit) are used.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32 Content filling mode. The enumerated values of [ArkUI_RenderFit](#arkui_renderfit) are used.| -| NODE_OUTLINE_COLOR | Defines the border color attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
1: .value[0].u32: color of the four borders, in 0xARGB format, for example, **0xFFFF11FF**.
2: .value[0].u32: color of the top border, in 0xARGB format, for example, **0xFFFF11FF**.
.value[1].u32: color of the right border, in 0xARGB format, for example, **0xFFFF11FF**.
.value[2].u32: color of the lower border, in 0xARGB format, for example, **0xFFFF11FF**.
.value[3].u32: color of the left border, in 0xARGB format, for example, **0xFFFF11FF**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color of the top border, in 0xARGB format, for example, **0xFFFF11FF**.
.value[1].u32: color of the right border, in 0xARGB format, for example, **0xFFFF11FF**.
.value[2].u32: color of the lower border, in 0xARGB format, for example, **0xFFFF11FF**.
.value[3].u32: color of the left border, in 0xARGB format, for example, **0xFFFF11FF**.| -| NODE_SIZE | Sets the size. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: width, in vp.
.value[1].f32: height, in vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: width, in vp.
.value[1].f32: height, in vp.| -| NODE_RENDER_GROUP | Sets whether the component and its child components are rendered off the screen and then drawn together with its parent. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: The parameter type is 1 or 0.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
value[0].i32: The parameter type is 1 or 0.| -| NODE_COLOR_BLEND | The color overlay effect is added to the component. The attribute setting, attribute resetting, and attribute obtaining interfaces are supported.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: color to blend with the component, in 0xARGB format, for example, **0xFFFF11FF**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color to blend with the component, in 0xARGB format, for example, **0xFFFF11FF**.| -| NODE_FOREGROUND_BLUR_STYLE | Applies a foreground blur style to the component. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: foreground blur style. The value is an enum of [ArkUI_BlurStyle](#arkui_blurstyle).
.value[1]?.i32: color mode used for the foreground blur. The value is an enum of [ArkUI_ColorMode](#arkui_colormode).
.value[2]?.i32: adaptive color mode used for the foreground blur. The value is an enum of [ArkUI_AdaptiveColor](#arkui_adaptivecolor).
.value[3]?.f32: blur degree. The value range is [0.0, 1.0].
.value[4]?.i32: brightness of black in the grayscale blur. The value range is [0, 127].
.value[5]?.i32: degree of darkening the white color in the grayscale blur. The value range is [0, 127].
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: foreground blur style. The value is an enum of [ArkUI_BlurStyle](#arkui_blurstyle).
.value[1].i32: color mode used for the foreground blur. The value is an enum of [ArkUI_ColorMode](#arkui_colormode).
.value[2].i32: adaptive color mode used for the foreground blur. The value is an enum of [ArkUI_AdaptiveColor](#arkui_adaptivecolor).
.value[3].f32: blur degree. The value range is [0.0, 1.0].
.value[4].i32: brightness of black in the grayscale blur. The value range is [0, 127].
.value[5].i32: degree of darkening the white color in the grayscale blur. The value range is [0, 127].| -| NODE_LAYOUT_RECT | Defines the component size and position for layout. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: X coordinate of the component, in px.
.value[1].i32: Y coordinate of the component, in px.
.value[2].i32: width of the component, in px.
.value[3].i32: height of the component, in px.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: X coordinate of the component, in px.
.value[1].i32: Y coordinate of the component, in px.
.value[2].i32: width of the component, in px.
.value[3].i32: height of the component, in px. | -| NODE_FOCUS_ON_TOUCH | Sets whether the component is focusable on touch. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: The parameter type is 1 or 0.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
value[0].i32: The parameter type is 1 or 0.| -| NODE_BORDER_WIDTH_PERCENT | Defines the border width attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
1: .value[0].f32: width of the four borders, in percentage.
2: .value[0].f32: width of the top border, in percentage.
.value[1].f32: width of the right border, in percentage.
.value[2].f32: width of the bottom border, in percentage.
.value[3].f32: width of the left border, in percentage.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: width of the top border, in percentage.
.value[1].f32: width of the right border, in percentage.
.value[2].f32: width of the bottom border, in percentage.
.value[3].f32: width of the left border, in percentage.| -| NODE_BORDER_RADIUS_PERCENT | Defines the border corner radius attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
1: .value[0].f32: radius of the four corners, in percentage.
2: .value[0].f32: radius of the upper left corner, in percentage.
.value[1].f32: radius of the upper right corner, in percentage.
.value[2].f32: radius of the lower left corner, in percentage.
.value[3].f32: radius of the lower right corner, in percentage.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: radius of the upper left corner, in percentage.
.value[1].f32: radius of the upper right corner, in percentage.
.value[2].f32: radius of the lower left corner, in percentage.
.value[3].f32: radius of the lower right corner, in percentage.| -| NODE_ACCESSIBILITY_ID | Sets the custom accessibility ID. This attribute can be obtained.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: custom accessibility ID.| -| NODE_ACCESSIBILITY_ACTIONS | Sets the accessibility action type. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: accessibility operation type. The parameter type is [ArkUI_AccessibilityActionType](#arkui_accessibilityactiontype).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: accessibility operation type. The parameter type is [ArkUI_AccessibilityActionType](#arkui_accessibilityactiontype).| -| NODE_ACCESSIBILITY_ROLE | Defines supported accessibility component types. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: Accessibility component type. The parameter type is [ArkUI_NodeType](#arkui_nodetype).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: Accessibility component type. The parameter type is [ArkUI_NodeType](#arkui_nodetype).| -| NODE_ACCESSIBILITY_STATE | Sets the accessibility state. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: accessibility state. The parameter type is [ArkUI_AccessibilityState](#arkui_accessibilitystate).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: accessibility state. The parameter type is [ArkUI_AccessibilityState](#arkui_accessibilitystate).| -| NODE_ACCESSIBILITY_VALUE | Sets the accessibility value. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: accessibility value. The parameter type is [ArkUI_AccessibilityValue](#arkui_accessibilityvalue).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: accessibility value. The parameter type is [ArkUI_AccessibilityValue](#arkui_accessibilityvalue).| -| NODE_EXPAND_SAFE_AREA | Sets the safe area to be expanded to. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0]?.u32: types of the expanded safe area, which are enumerated values of [ArkUI_SafeAreaType](#arkui_safeareatype). Example: ARKUI_SAFE_AREA_TYPE_SYSTEM \| ARKUI_SAFE_AREA_TYPE_CUTOUT.
.value[1]?.u32: edges for expanding the safe area, which are enumerated values of [ArkUI_SafeAreaEdge](#arkui_safeareaedge).
Example: ARKUI_SAFE_AREA_EDGE_TOP \| ARKUI_SAFE_AREA_EDGE_BOTTOM.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: expanded safe area.
.
.value[1].u32: edges for expanding the safe area.
| -| NODE_VISIBLE_AREA_CHANGE_RATIO | Defines the visible area ratio (visible area/total area of the component) threshold for invoking the visible area change event of the component.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[...].f32: threshold array. The value ranges from 0 to 1.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[...].f32: threshold array.
| -| NODE_TRANSITION | Sets the transition effect when the component is inserted or deleted. This attribute can be set and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: transition effect. The parameter type is [ArkUI_TransitionEffect](#arkui_transitioneffect).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: transition effect. The parameter type is [ArkUI_TransitionEffect](#arkui_transitioneffect).| -| NODE_UNIQUE_ID | Defines the component ID. This attribute can be obtained through APIs.
**NOTE**
The component ID is read-only and unique in a process.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: component ID.| +| NODE_FOCUS_STATUS | This interface is used to obtain focus attributes. Attributes can be set and obtained.
**NOTE**
Setting the parameter to **0** shifts focus from the currently focused component on the current level of the page to the root container.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: The parameter type is 1 or 0.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
value[0].i32: The parameter type is 1 or 0.| +| NODE_ASPECT_RATIO | Defines the aspect ratio attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: aspect ratio of the component, in width/height format.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: aspect ratio of the component, in width/height format.| +| NODE_LAYOUT_WEIGHT | Defines the weight of the component within its row, column, or flex container for proportional distribution of available space within the container. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: weight of the component along the main axis.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: weight of the component along the main axis.| +| NODE_DISPLAY_PRIORITY | Sets the display priority for the component in the row, column, or flex (single-line) container. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: display priority of the component in the container.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: display priority of the component in the container.| +| NODE_OUTLINE_WIDTH | Sets the thickness of an element's outline.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: thickness of the left outline.
.value[1].f32: thickness of the top outline.
.value[2].f32: thickness of the right outline.
.value[3].f32: thickness of the bottom outline.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: thickness of the left outline.
.value[1].f32: thickness of the top outline.
.value[2].f32: thickness of the right outline.
.value[3].f32: thickness of the bottom outline.| +| NODE_WIDTH_PERCENT | Defines the width attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: width, in percentage.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: width, in percentage. | +| NODE_HEIGHT_PERCENT | Defines the height attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: height, in percentage.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: height, in percentage. | +| NODE_PADDING_PERCENT | Defines the padding attribute, which can be set, reset, and obtained as required through APIs.
There are two formats of [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) for setting the attribute value:
1: Specify the same padding for the four directions.
.value[0].f32: padding, in percentage.
2: Specify different paddings for different directions.
.value[0].f32: top padding, in percentage.
.value[1].f32: right padding, in percentage.
.value[2].f32: bottom padding, in percentage.
.value[3].f32: left padding, in percentage.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: top padding, in percentage.
.value[1].f32: right padding, in percentage.
.value[2].f32: bottom padding, in percentage.
.value[3].f32: left padding, in percentage. | +| NODE_MARGIN_PERCENT | Defines the margin attribute, which can be set, reset, and obtained as required through APIs.
There are two formats of [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) for setting the attribute value:
1: Specify the same margin for the four directions.
.value[0].f32: margin, in percentage.
2: Specify different margins for different directions.
.value[0].f32: top margin, in percentage.
.value[1].f32: right margin, in percentage.
.value[2].f32: bottom margin, in percentage.
.value[3].f32: left margin, in percentage.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: top margin, in percentage.
.value[1].f32: right margin, in percentage.
.value[2].f32: bottom margin, in percentage.
.value[3].f32: left margin, in percentage. | +| NODE_GEOMETRY_TRANSITION | Implements an implicit shared element transition. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: two components bound to the shared element. The parameter type is 1 or 0. By default, the out component does not continue to participate in the shared element animation when not yet deleted, which means that it stays in its original position.
.string: ID used to set up a binding relationship. If this attribute is set to an empty string **""**, the binding relationship is cleared. The value can be dynamically changed to refresh the binding relationship. One ID can be bound to only two components, which function as in and out components.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: two components bound to the shared element. The parameter type is 1 or 0. By default, the out component does not continue to participate in the shared element animation when not yet deleted, which means that it stays in its original position.
.string: ID used to set up a binding relationship. If this attribute is set to an empty string **""**, the binding relationship is cleared. The value can be dynamically changed to refresh the binding relationship. One ID can be bound to only two components, which function as in and out components.| +| NODE_RELATIVE_LAYOUT_CHAIN_MODE | Specifies the parameters of the chain formed by the component as the chain head. The attribute setting, attribute resetting, and attribute obtaining interfaces are supported.
This attribute has effect only when the parent container is **RelativeContainer**.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: direction of the chain. Enumeration [ArkUI_Axis](#arkui_axis).
.value[1].i32: style of the chain. Enumeration [ArkUI_RelativeLayoutChainStyle](#arkui_relativelayoutchainstyle).
.value[0].i32: direction of the chain. Enumeration [ArkUI_Axis](#arkui_axis).
.value[1].i32: style of the chain. Enumeration [ArkUI_RelativeLayoutChainStyle](#arkui_relativelayoutchainstyle).| +| NODE_RENDER_FIT | Sets how the final state of the component's content is rendered during its width and height animation process. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32 Content filling mode. The enumerated values of [ArkUI_RenderFit](#arkui_renderfit) are used.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32 Content filling mode. The enumerated values of [ArkUI_RenderFit](#arkui_renderfit) are used.| +| NODE_OUTLINE_COLOR | Defines the border color attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
1: .value[0].u32: color of the four borders, in 0xARGB format, for example, **0xFFFF11FF**.
2: .value[0].u32: color of the top border, in 0xARGB format, for example, **0xFFFF11FF**.
.value[1].u32: color of the right border, in 0xARGB format, for example, **0xFFFF11FF**.
.value[2].u32: color of the lower border, in 0xARGB format, for example, **0xFFFF11FF**.
.value[3].u32: color of the left border, in 0xARGB format, for example, **0xFFFF11FF**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color of the top border, in 0xARGB format, for example, **0xFFFF11FF**.
.value[1].u32: color of the right border, in 0xARGB format, for example, **0xFFFF11FF**.
.value[2].u32: color of the lower border, in 0xARGB format, for example, **0xFFFF11FF**.
.value[3].u32: color of the left border, in 0xARGB format, for example, **0xFFFF11FF**.| +| NODE_SIZE | Sets the size. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: width, in vp.
.value[1].f32: height, in vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: width, in vp.
.value[1].f32: height, in vp.| +| NODE_RENDER_GROUP | Sets whether the component and its child components are rendered off the screen and then drawn together with its parent. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: The parameter type is 1 or 0.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
value[0].i32: The parameter type is 1 or 0.| +| NODE_COLOR_BLEND | The color overlay effect is added to the component. The attribute setting, attribute resetting, and attribute obtaining interfaces are supported.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: color to blend with the component, in 0xARGB format, for example, **0xFFFF11FF**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color to blend with the component, in 0xARGB format, for example, **0xFFFF11FF**.| +| NODE_FOREGROUND_BLUR_STYLE | Applies a foreground blur style to the component. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: foreground blur style. The value is an enum of [ArkUI_BlurStyle](#arkui_blurstyle).
.value[1]?.i32: color mode used for the foreground blur. The value is an enum of [ArkUI_ColorMode](#arkui_colormode).
.value[2]?.i32: adaptive color mode used for the foreground blur. The value is an enum of [ArkUI_AdaptiveColor](#arkui_adaptivecolor).
.value[3]?.f32: blur degree. The value range is [0.0, 1.0].
.value[4]?.i32: brightness of black in the grayscale blur. The value range is [0, 127].
.value[5]?.i32: degree of darkening the white color in the grayscale blur. The value range is [0, 127].
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: foreground blur style. The value is an enum of [ArkUI_BlurStyle](#arkui_blurstyle).
.value[1].i32: color mode used for the foreground blur. The value is an enum of [ArkUI_ColorMode](#arkui_colormode).
.value[2].i32: adaptive color mode used for the foreground blur. The value is an enum of [ArkUI_AdaptiveColor](#arkui_adaptivecolor).
.value[3].f32: blur degree. The value range is [0.0, 1.0].
.value[4].i32: brightness of black in the grayscale blur. The value range is [0, 127].
.value[5].i32: degree of darkening the white color in the grayscale blur. The value range is [0, 127].| +| NODE_LAYOUT_RECT | Defines the component size and position for layout. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: X coordinate of the component, in px.
.value[1].i32: Y coordinate of the component, in px.
.value[2].i32: width of the component, in px.
.value[3].i32: height of the component, in px.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: X coordinate of the component, in px.
.value[1].i32: Y coordinate of the component, in px.
.value[2].i32: width of the component, in px.
.value[3].i32: height of the component, in px. | +| NODE_FOCUS_ON_TOUCH | Sets whether the component is focusable on touch. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: The parameter type is 1 or 0.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
value[0].i32: The parameter type is 1 or 0.| +| NODE_BORDER_WIDTH_PERCENT | Defines the border width attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
1: .value[0].f32: width of the four borders, in percentage.
2: .value[0].f32: width of the top border, in percentage.
.value[1].f32: width of the right border, in percentage.
.value[2].f32: width of the bottom border, in percentage.
.value[3].f32: width of the left border, in percentage.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: width of the top border, in percentage.
.value[1].f32: width of the right border, in percentage.
.value[2].f32: width of the bottom border, in percentage.
.value[3].f32: width of the left border, in percentage.| +| NODE_BORDER_RADIUS_PERCENT | Defines the border corner radius attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
1: .value[0].f32: radius of the four corners, in percentage.
2: .value[0].f32: radius of the upper left corner, in percentage.
.value[1].f32: radius of the upper right corner, in percentage.
.value[2].f32: radius of the lower left corner, in percentage.
.value[3].f32: radius of the lower right corner, in percentage.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: radius of the upper left corner, in percentage.
.value[1].f32: radius of the upper right corner, in percentage.
.value[2].f32: radius of the lower left corner, in percentage.
.value[3].f32: radius of the lower right corner, in percentage.| +| NODE_ACCESSIBILITY_ID | Sets the custom accessibility ID. This attribute can be obtained.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: custom accessibility ID.| +| NODE_ACCESSIBILITY_ACTIONS | Sets the accessibility action type. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: accessibility operation type. The parameter type is [ArkUI_AccessibilityActionType](#arkui_accessibilityactiontype).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: accessibility operation type. The parameter type is [ArkUI_AccessibilityActionType](#arkui_accessibilityactiontype).| +| NODE_ACCESSIBILITY_ROLE | Defines supported accessibility component types. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: Accessibility component type. The parameter type is [ArkUI_NodeType](#arkui_nodetype).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: Accessibility component type. The parameter type is [ArkUI_NodeType](#arkui_nodetype).| +| NODE_ACCESSIBILITY_STATE | Sets the accessibility state. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: accessibility state. The parameter type is [ArkUI_AccessibilityState](#arkui_accessibilitystate).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: accessibility state. The parameter type is [ArkUI_AccessibilityState](#arkui_accessibilitystate).| +| NODE_ACCESSIBILITY_VALUE | Sets the accessibility value. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: accessibility value. The parameter type is [ArkUI_AccessibilityValue](#arkui_accessibilityvalue).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: accessibility value. The parameter type is [ArkUI_AccessibilityValue](#arkui_accessibilityvalue).| +| NODE_EXPAND_SAFE_AREA | Sets the safe area to be expanded to. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0]?.u32: types of the expanded safe area, which are enumerated values of [ArkUI_SafeAreaType](#arkui_safeareatype). Example: ARKUI_SAFE_AREA_TYPE_SYSTEM \| ARKUI_SAFE_AREA_TYPE_CUTOUT.
.value[1]?.u32: edges for expanding the safe area, which are enumerated values of [ArkUI_SafeAreaEdge](#arkui_safeareaedge).
Example: ARKUI_SAFE_AREA_EDGE_TOP \| ARKUI_SAFE_AREA_EDGE_BOTTOM.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: expanded safe area.
.
.value[1].u32: edges for expanding the safe area.
| +| NODE_VISIBLE_AREA_CHANGE_RATIO | Defines the visible area ratio (visible area/total area of the component) threshold for invoking the visible area change event of the component.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[...].f32: threshold array. The value ranges from 0 to 1.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[...].f32: threshold array.
| +| NODE_TRANSITION | Sets the transition effect when the component is inserted or deleted. This attribute can be set and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: transition effect. The parameter type is [ArkUI_TransitionEffect](#arkui_transitioneffect).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: transition effect. The parameter type is [ArkUI_TransitionEffect](#arkui_transitioneffect).| +| NODE_UNIQUE_ID | Defines the component ID. This attribute can be obtained through APIs.
**NOTE**
The component ID is read-only and unique in a process.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: component ID.| | NODE_FOCUS_BOX | Sets the style of the system focus box for this component.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: distance between the focus box and the edge of the component A positive number indicates the outside, and a negative number indicates the inside. The value cannot be in percentage.
.value[1].f32: width of the focus box. Negative numbers and percentages are not supported.
.value[2].u32: color of the focus box.| -| NODE_CLICK_DISTANCE | Defines the moving distance limit for the component-bound tap gesture. This attribute can be set as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: allowed moving distance of a finger, in vp.| +| NODE_CLICK_DISTANCE | Defines the moving distance limit for the component-bound tap gesture. This attribute can be set as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: allowed moving distance of a finger, in vp.| | NODE_TAB_STOP | Sets whether the focus can be placed on this component. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: The parameter type is 1 or 0.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: The parameter type is 1 or 0.| -| NODE_TEXT_CONTENT | Defines the text content attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: text content.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: text content.| -| NODE_FONT_COLOR | Defines the font color attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: font color, in 0xARGB format. For example, 0xFFFF0000 indicates red.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: font color value, in 0xARGB format.| -| NODE_FONT_SIZE | Defines the font size attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: font size, in fp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: font size, in fp.| -| NODE_FONT_STYLE | Defines the font style attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: font style [ArkUI_FontStyle](#arkui_fontstyle). The default value is **ARKUI_FONT_STYLE_NORMAL**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: font style [ArkUI_FontStyle](#arkui_fontstyle).| -| NODE_FONT_WEIGHT | Defines the font weight attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: font weight [ArkUI_FontWeight](#arkui_fontweight). The default value is **ARKUI_FONT_WEIGHT_NORMAL**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: font weight [ArkUI_FontWeight](#arkui_fontweight).| -| NODE_TEXT_LINE_HEIGHT | Defines the text line height attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: line height, in fp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: line height, in fp.| -| NODE_TEXT_DECORATION | Defines the text decoration style and color. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: text decoration type [ArkUI_TextDecorationType](#arkui_textdecorationtype). The default value is **ARKUI_TEXT_DECORATION_TYPE_NONE**.
.value[1]?.u32: text decoration color, in 0xARGB format. For example, 0xFFFF0000 indicates red. Optional.
.value[2]?.i32: text decoration style [ArkUI_TextDecorationStyle](#arkui_textdecorationstyle).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: text decoration type [ArkUI_TextDecorationType](#arkui_textdecorationtype).
.value[1].u32: text decoration color, in 0xARGB format.
.value[2].i32: text decoration style [ArkUI_TextDecorationStyle](#arkui_textdecorationstyle).| -| NODE_TEXT_CASE | Defines the text case attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: text case.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: text case.| -| NODE_TEXT_LETTER_SPACING | Defines the letter spacing attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: letter spacing, in fp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: letter spacing, in fp.| +| NODE_BACKGROUND_IMAGE_RESIZABLE_WITH_SLICE | Sets the resizable attribute of a background image when it is stretched. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: pixel value of the image that remains unchanged when the left side of the image is stretched, in vp.
.value[1].f32: pixel value of the image that remains unchanged when the top side of the image is stretched, in vp.
.value[2].f32: pixel value of the image that remains unchanged when the right side of the image is stretched, in vp.
.value[3].f32: pixel value of the image that remains unchanged when the bottom side of the image is stretched, in vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: pixel value of the image that remains unchanged when the left side of the image is stretched, in vp.
.value[1].f32: pixel value of the image that remains unchanged when the top side of the image is stretched, in vp.
.value[2].f32: pixel value of the image that remains unchanged when the right side of the image is stretched, in vp.
.value[3].f32: pixel value of the image that remains unchanged when the bottom side of the image is stretched, in vp.
**Since**
18 | +| NODE_VISIBLE_AREA_APPROXIMATE_CHANGE_RATIO | Sets the threshold ratio for triggering a visible area change event.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: parameter for visible area change events. The parameter type is **ArkUI_VisibleAreaEventOptions**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
object: parameter for visible area change events. The parameter type is **ArkUI_VisibleAreaEventOptions**.
**Since**
18 | +| NODE_TEXT_CONTENT | Defines the text content attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: text content.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: text content.| +| NODE_FONT_COLOR | Defines the font color attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: font color, in 0xARGB format. For example, 0xFFFF0000 indicates red.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: font color value, in 0xARGB format.| +| NODE_FONT_SIZE | Defines the font size attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: font size, in fp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: font size, in fp.| +| NODE_FONT_STYLE | Defines the font style attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: font style [ArkUI_FontStyle](#arkui_fontstyle). The default value is **ARKUI_FONT_STYLE_NORMAL**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: font style [ArkUI_FontStyle](#arkui_fontstyle).| +| NODE_FONT_WEIGHT | Defines the font weight attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: font weight [ArkUI_FontWeight](#arkui_fontweight). The default value is **ARKUI_FONT_WEIGHT_NORMAL**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: font weight [ArkUI_FontWeight](#arkui_fontweight).| +| NODE_TEXT_LINE_HEIGHT | Defines the text line height attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: line height, in fp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: line height, in fp.| +| NODE_TEXT_DECORATION | Defines the text decoration style and color. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: text decoration type [ArkUI_TextDecorationType](#arkui_textdecorationtype). The default value is **ARKUI_TEXT_DECORATION_TYPE_NONE**.
.value[1]?.u32: text decoration color, in 0xARGB format. For example, 0xFFFF0000 indicates red. Optional.
.value[2]?.i32: text decoration style [ArkUI_TextDecorationStyle](#arkui_textdecorationstyle).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: text decoration type [ArkUI_TextDecorationType](#arkui_textdecorationtype).
.value[1].u32: text decoration color, in 0xARGB format.
.value[2].i32: text decoration style [ArkUI_TextDecorationStyle](#arkui_textdecorationstyle).| +| NODE_TEXT_CASE | Defines the text case attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: text case.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: text case.| +| NODE_TEXT_LETTER_SPACING | Defines the letter spacing attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: letter spacing, in fp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: letter spacing, in fp.| | NODE_TEXT_MAX_LINES | Sets the maximum number of lines in the text. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: maximum number of lines in the text.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: maximum number of lines in the text.| -| NODE_TEXT_ALIGN | Horizontal alignment mode of the text. The interfaces for setting, resetting, and obtaining attributes are supported.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: horizontal alignment mode of the text. The value is an enum of [ArkUI_TextAlignment](#arkui_textalignment).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: horizontal alignment mode of the text. The value is an enum of [ArkUI_TextAlignment](#arkui_textalignment).| -| NODE_TEXT_OVERFLOW | Defines the text overflow attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: display mode when the text is too long.{\@ArkUI_TextOverflow}
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: display mode when the text is too long.{\@ArkUI_TextOverflow} | -| NODE_FONT_FAMILY | Defines the font family attribute, which can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: fonts, separated by commas (,).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: fonts, separated by commas (,).| -| NODE_TEXT_COPY_OPTION | Defines the copy option attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: copy option [ArkUI_CopyOptions](#arkui_copyoptions). The default value is **ARKUI_COPY_OPTIONS_NONE**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: copy option [ArkUI_CopyOptions](#arkui_copyoptions).| -| NODE_TEXT_BASELINE_OFFSET | Defines the text baseline offset attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: baseline offset, in fp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: baseline offset, in fp.| -| NODE_TEXT_TEXT_SHADOW | Defines the shadow attribute. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: blur radius of the shadow, in vp.
.value[1].i32: shadow type [ArkUI_ShadowType](#arkui_shadowtype). The default value is **ARKUI_SHADOW_TYPE_COLOR**.
.value[2].u32: shadow color, in 0xARGB format. For example, 0xFFFF0000 indicates red.
.value[3].f32: offset of the shadow along the x-axis, in vp.
.value[4].f32: offset of the shadow along the y-axis, in vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: blur radius of the shadow, in vp.
.value[1].i32: shadow type [ArkUI_ShadowType](#arkui_shadowtype).
.value[2].u32: shadow color, in 0xARGB format.
.value[3].f32: offset of the shadow along the x-axis, in vp.
.value[4].f32: offset of the shadow along the y-axis, in vp.| -| NODE_TEXT_MIN_FONT_SIZE | Defines the minimum font size attribute, which can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: minimum font size, in fp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: minimum font size, in fp.| -| NODE_TEXT_MAX_FONT_SIZE | Defines the maximum font size attribute, which can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: maximum font size, in fp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: maximum font size, in fp.| -| NODE_TEXT_FONT | Defines the text style attribute, which can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string?: font family. Optional. Use commas (,) to separate multiple fonts.
.value[0].f32: font size, in fp.
.value[1]? .i32: font weight. Optional. The parameter type is [ArkUI_FontWeight](#arkui_fontweight). The default value is **ARKUI_FONT_WEIGHT_NORMAL**.
.value[2]?.i32: font style. Optional. The parameter type is [ArkUI_FontStyle](#arkui_fontstyle). The default value is **ARKUI_FONT_STYLE_NORMAL**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: font family. Use commas (,) to separate multiple fonts.
.value[0].f32: font size, in fp.
.value[1].i32: font weight. The parameter type is [ArkUI_FontWeight](#arkui_fontweight). The default value is **ARKUI_FONT_WEIGHT_NORMAL**.
.value[2].i32: font style. The parameter type is [ArkUI_FontStyle](#arkui_fontstyle). The default value is **ARKUI_FONT_STYLE_NORMAL**.| -| NODE_TEXT_HEIGHT_ADAPTIVE_POLICY | Defines how the adaptive height is determined for the text. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: how the adaptive height is determined for the text. The parameter type is [ArkUI_TextHeightAdaptivePolicy](#arkui_textheightadaptivepolicy).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: how the adaptive height is determined for the text. The parameter type is [ArkUI_TextHeightAdaptivePolicy](#arkui_textheightadaptivepolicy).| -| NODE_TEXT_INDENT | Defines the indentation of the first line. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: indentation of the first line.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: indentation of the first line.| -| NODE_TEXT_WORD_BREAK | Defines the line break rule. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: line break rule. The parameter type is [ArkUI_WordBreak](#arkui_wordbreak).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: line break rule. The parameter type is [ArkUI_WordBreak](#arkui_wordbreak).| -| NODE_TEXT_ELLIPSIS_MODE | Defines the ellipsis position. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: ellipsis position. The parameter type is [ArkUI_EllipsisMode](#arkui_ellipsismode).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: ellipsis position. The parameter type is [ArkUI_EllipsisMode](#arkui_ellipsismode).| -| NODE_TEXT_LINE_SPACING | Defines the line spacing attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: line spacing, in fp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: line spacing, in fp. | -| NODE_FONT_FEATURE | Sets the font feature. **NODE_FONT_FEATURE** provides advanced typographic features in OpenType fonts.
These features such as hyphenation and monospace are generally used in custom fonts and require support from the respective fonts. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: string that complies with the text feature format. The format is normal\.| <feature-tag-value>,
Syntax for <feature-tag-value>: <string> [ <integer> \| on \| off ],
There can be multiple **feature-tag-value** values, separated by commas (,). For example, for the monospace feature, you can pass in **ss01 on**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: font feature. Multiple font features are separated by commas (,).| -| NODE_TEXT_ENABLE_DATA_DETECTOR | Sets whether to enable text recognition.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to enable text recognition. The default value is **false**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to enable text recognition.| -| NODE_TEXT_ENABLE_DATA_DETECTOR_CONFIG | Configures text recognition settings.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0...].i32: entity type array. The parameter type is [ArkUI_TextDataDetectorType](#arkui_textdatadetectortype).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0...].i32: entity type array. The parameter type is [ArkUI_TextDataDetectorType](#arkui_textdatadetectortype).| -| NODE_TEXT_SELECTED_BACKGROUND_COLOR | Defines the background color of the selected text. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: color value, in 0xARGB format. For example, 0xFFFF0000 indicates red.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color value, in 0xARGB format.| -| NODE_TEXT_CONTENT_WITH_STYLED_STRING | Sets the string to use in the styled string. This attribute can be set and obtained as required through APIs. When a custom **OH_Drawing_Typography** object is configured for a **Text** component, the layout measurement phase of the **Text** component is skipped. Below are some tips to handle this issue:
1. Ensure that the lifecycle of the **OH_ArkUI_StyledString** object and the **OH_Drawing_Typography** object follows that of the **Text** component. Reset the **OH_ArkUI_StyledString** object when the **Text** component is destroyed; otherwise, a null pointer crash may occur in the application.
2. Ensure that the **OH_Drawing_TypographyLayout** API is called before the layout measurement of the **Text** component.
3. When releasing the **OH_ArkUI_StyledString** object and the **OH_Drawing_Typography** object, call the **reset** API of the **Text** component. Otherwise, a null pointer crash may occur in the application
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.object: string to use in the styled string. The parameter type is [ArkUI_StyledString](#arkui_styledstring).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: string to use in the styled string. The parameter type is [ArkUI_StyledString](#arkui_styledstring).| -| NODE_TEXT_HALF_LEADING | Sets whether to center text vertically in the **Text** component.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to center text vertically. The default value is **false**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to center text vertically.| +| NODE_TEXT_ALIGN | Horizontal alignment mode of the text. The interfaces for setting, resetting, and obtaining attributes are supported.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: horizontal alignment mode of the text. The value is an enum of [ArkUI_TextAlignment](#arkui_textalignment).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: horizontal alignment mode of the text. The value is an enum of [ArkUI_TextAlignment](#arkui_textalignment).| +| NODE_TEXT_OVERFLOW | Defines the text overflow attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: display mode when the text is too long.{\@ArkUI_TextOverflow}
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: display mode when the text is too long.{\@ArkUI_TextOverflow} | +| NODE_FONT_FAMILY | Defines the font family attribute, which can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: fonts, separated by commas (,).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: fonts, separated by commas (,).| +| NODE_TEXT_COPY_OPTION | Defines the copy option attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: copy option [ArkUI_CopyOptions](#arkui_copyoptions). The default value is **ARKUI_COPY_OPTIONS_NONE**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: copy option [ArkUI_CopyOptions](#arkui_copyoptions).| +| NODE_TEXT_BASELINE_OFFSET | Defines the text baseline offset attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: baseline offset, in fp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: baseline offset, in fp.| +| NODE_TEXT_TEXT_SHADOW | Defines the shadow attribute. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: blur radius of the shadow, in vp.
.value[1].i32: shadow type [ArkUI_ShadowType](#arkui_shadowtype). The default value is **ARKUI_SHADOW_TYPE_COLOR**.
.value[2].u32: shadow color, in 0xARGB format. For example, 0xFFFF0000 indicates red.
.value[3].f32: offset of the shadow along the x-axis, in vp.
.value[4].f32: offset of the shadow along the y-axis, in vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: blur radius of the shadow, in vp.
.value[1].i32: shadow type [ArkUI_ShadowType](#arkui_shadowtype).
.value[2].u32: shadow color, in 0xARGB format.
.value[3].f32: offset of the shadow along the x-axis, in vp.
.value[4].f32: offset of the shadow along the y-axis, in vp.| +| NODE_TEXT_MIN_FONT_SIZE | Defines the minimum font size attribute, which can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: minimum font size, in fp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: minimum font size, in fp.| +| NODE_TEXT_MAX_FONT_SIZE | Defines the maximum font size attribute, which can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: maximum font size, in fp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: maximum font size, in fp.| +| NODE_TEXT_FONT | Defines the text style attribute, which can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string?: font family. Optional. Use commas (,) to separate multiple fonts.
.value[0].f32: font size, in fp.
.value[1]? .i32: font weight. Optional. The parameter type is [ArkUI_FontWeight](#arkui_fontweight). The default value is **ARKUI_FONT_WEIGHT_NORMAL**.
.value[2]?.i32: font style. Optional. The parameter type is [ArkUI_FontStyle](#arkui_fontstyle). The default value is **ARKUI_FONT_STYLE_NORMAL**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: font family. Use commas (,) to separate multiple fonts.
.value[0].f32: font size, in fp.
.value[1].i32: font weight. The parameter type is [ArkUI_FontWeight](#arkui_fontweight). The default value is **ARKUI_FONT_WEIGHT_NORMAL**.
.value[2].i32: font style. The parameter type is [ArkUI_FontStyle](#arkui_fontstyle). The default value is **ARKUI_FONT_STYLE_NORMAL**.| +| NODE_TEXT_HEIGHT_ADAPTIVE_POLICY | Defines how the adaptive height is determined for the text. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: how the adaptive height is determined for the text. The parameter type is [ArkUI_TextHeightAdaptivePolicy](#arkui_textheightadaptivepolicy).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: how the adaptive height is determined for the text. The parameter type is [ArkUI_TextHeightAdaptivePolicy](#arkui_textheightadaptivepolicy).| +| NODE_TEXT_INDENT | Defines the indentation of the first line. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: indentation of the first line.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: indentation of the first line.| +| NODE_TEXT_WORD_BREAK | Defines the line break rule. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: line break rule. The parameter type is [ArkUI_WordBreak](#arkui_wordbreak).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: line break rule. The parameter type is [ArkUI_WordBreak](#arkui_wordbreak).| +| NODE_TEXT_ELLIPSIS_MODE | Defines the ellipsis position. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: ellipsis position. The parameter type is [ArkUI_EllipsisMode](#arkui_ellipsismode).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: ellipsis position. The parameter type is [ArkUI_EllipsisMode](#arkui_ellipsismode).| +| NODE_TEXT_LINE_SPACING | Defines the line spacing attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: line spacing, in fp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: line spacing, in fp. | +| NODE_FONT_FEATURE | Sets the font feature. **NODE_FONT_FEATURE** provides advanced typographic features in OpenType fonts.
These features such as hyphenation and monospace are generally used in custom fonts and require support from the respective fonts. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: string that complies with the text feature format. The format is normal\.| <feature-tag-value>,
Syntax for <feature-tag-value>: <string> [ <integer> \| on \| off ],
There can be multiple **feature-tag-value** values, separated by commas (,). For example, for the monospace feature, you can pass in **ss01 on**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: font feature. Multiple font features are separated by commas (,).| +| NODE_TEXT_ENABLE_DATA_DETECTOR | Sets whether to enable text recognition.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to enable text recognition. The default value is **false**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to enable text recognition.| +| NODE_TEXT_ENABLE_DATA_DETECTOR_CONFIG | Configures text recognition settings.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0...].i32: entity type array. The parameter type is [ArkUI_TextDataDetectorType](#arkui_textdatadetectortype).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0...].i32: entity type array. The parameter type is [ArkUI_TextDataDetectorType](#arkui_textdatadetectortype).| +| NODE_TEXT_SELECTED_BACKGROUND_COLOR | Defines the background color of the selected text. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: color value, in 0xARGB format. For example, 0xFFFF0000 indicates red.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color value, in 0xARGB format.| +| NODE_TEXT_CONTENT_WITH_STYLED_STRING | Sets the string to use in the styled string. This attribute can be set and obtained as required through APIs. When a custom **OH_Drawing_Typography** object is configured for a **Text** component, the layout measurement phase of the **Text** component is skipped. Below are some tips to handle this issue:
1. Ensure that the lifecycle of the **OH_ArkUI_StyledString** object and the **OH_Drawing_Typography** object follows that of the **Text** component. Reset the **OH_ArkUI_StyledString** object when the **Text** component is destroyed; otherwise, a null pointer crash may occur in the application.
2. Ensure that the **OH_Drawing_TypographyLayout** API is called before the layout measurement of the **Text** component.
3. When releasing the **OH_ArkUI_StyledString** object and the **OH_Drawing_Typography** object, call the **reset** API of the **Text** component. Otherwise, a null pointer crash may occur in the application
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.object: string to use in the styled string. The parameter type is [ArkUI_StyledString](#arkui_styledstring).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: string to use in the styled string. The parameter type is [ArkUI_StyledString](#arkui_styledstring).| +| NODE_TEXT_HALF_LEADING | Sets whether to center text vertically in the **Text** component.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to center text vertically. The default value is **false**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to center text vertically.| | NODE_IMMUTABLE_FONT_WEIGHT | Defines the font weight attribute, which can be set, reset, and obtained as required through APIs. The font weight specified by this API is not affected by any changes in the system font weight settings.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: font weight [ArkUI_FontWeight](#arkui_fontweight). The default value is **ARKUI_FONT_WEIGHT_NORMAL**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: font weight [ArkUI_FontWeight](#arkui_fontweight).| -| NODE_SPAN_CONTENT | Defines the text content attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: content of the text span.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: content of the text span.| -| NODE_SPAN_TEXT_BACKGROUND_STYLE | Defines the text background style. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: color of the text background, in 0xARGB format, for example, **0xFFFF0000** indicating red.
The second parameter is used to set the rounded corner of the text background. The options are as follows:
1: .value[1].f32: The radiuses of rounded corners in the four directions are set in a unified manner. The unit is vp.
2: .value[1].f32: radius of the upper left corner, in vp.
.value[2].f32: radius of the upper right corner, in vp.
.value[3].f32: radius of the lower left corner, in vp.
.value[4].f32: radius of the lower right corner, in vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color of the text background, in 0xARGB format.
.value[1].f32: radius of the upper left corner, in vp.
.value[2].f32: radius of the upper right corner, in vp.
.value[3].f32: radius of the lower left corner, in vp.
.value[4].f32: radius of the lower right corner, in vp.| -| NODE_SPAN_BASELINE_OFFSET | Defines the text baseline offset attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: baseline offset, in fp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: baseline offset, in fp.| -| NODE_IMAGE_SPAN_SRC | Defines the image source for an image span. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: image address of the image span.
.object: **PixelMap** object. The parameter type is [ArkUI_DrawableDescriptor](#arkui_drawabledescriptor).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: image address of the image span.
.object: **PixelMap** object. The parameter type is [ArkUI_DrawableDescriptor](#arkui_drawabledescriptor). Either **.object** or **.string** must be set.| -| NODE_IMAGE_SPAN_VERTICAL_ALIGNMENT | Defines the alignment mode of the image with the text. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32 indicates the text-based image alignment mode. The enumerated values of [ArkUI_ImageSpanAlignment](#arkui_imagespanalignment) are used.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32 indicates the text-based image alignment mode. The enumerated values of [ArkUI_ImageSpanAlignment](#arkui_imagespanalignment) are used.| -| NODE_IMAGE_SPAN_ALT | Defines the image source for an image span. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: placeholder image address for the image span. GIF images are not supported.
.object: **PixelMap** object. The parameter type is [ArkUI_DrawableDescriptor](#arkui_drawabledescriptor). Either **.object** or **.string** must be set.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: image source for the image span.
.object: **PixelMap** object. The parameter type is [ArkUI_DrawableDescriptor](#arkui_drawabledescriptor).| -| NODE_IMAGE_SPAN_BASELINE_OFFSET | Defines the baseline offset attribute of the **ImageSpan** component. This attribute can be set, reset, and obtained as required through APIs. A positive value means an upward offset, while a negative value means a downward offset. The default value is **0**, and the unit is fp.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: baseline offset, in fp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: baseline offset, in fp.| -| NODE_IMAGE_SRC | Defines the image source of the **Image** component. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: image source.
.object: **PixelMap** object. The parameter type is [ArkUI_DrawableDescriptor](#arkui_drawabledescriptor). Either **.object** or **.string** must be set.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: image source.
.object: **PixelMap** object. The parameter type is [ArkUI_DrawableDescriptor](#arkui_drawabledescriptor).| -| NODE_IMAGE_OBJECT_FIT | Defines how the image is resized to fit its container. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32 indicates the image filling effect. The enumerated values of [ArkUI_ObjectFit](#arkui_objectfit) are used.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32 indicates the image filling effect. The enumerated values of [ArkUI_ObjectFit](#arkui_objectfit) are used.| -| NODE_IMAGE_INTERPOLATION | Defines the interpolation effect of the image. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32 indicates the interpolation effect. The enumerated values of [ArkUI_ImageInterpolation](#arkui_imageinterpolation) are used.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32 indicates the interpolation effect. The enumerated values of [ArkUI_ImageInterpolation](#arkui_imageinterpolation) are used.| -| NODE_IMAGE_OBJECT_REPEAT | Defines how the image is repeated. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32 indicates the image repetition style. The enumerated values of [ArkUI_ImageRepeat](#arkui_imagerepeat) are used.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32 indicates the image repetition style. The enumerated values of [ArkUI_ImageRepeat](#arkui_imagerepeat) are used.| -| NODE_IMAGE_COLOR_FILTER | Defines the color filter of the image. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32 to .value[19].f32: filter matrix array.
.size: 5 x 4 filter array size.
.object: pointer to the color filter. The parameter type is **OH_Drawing_ColorFilter**. Either .object or .size can be set.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32 to .value[19].f32: filter matrix array.
.size: 5 x 4 filter array size.
.object: pointer to the color filter. The parameter type is **OH_Drawing_ColorFilter**.| -| NODE_IMAGE_AUTO_RESIZE | Defines the auto resize attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32 : whether to resize the image source.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32 : whether to resize the image source.| -| NODE_IMAGE_ALT | Defines the placeholder image source. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: image source for the image span.
.object: **PixelMap** object. The parameter type is [ArkUI_DrawableDescriptor](#arkui_drawabledescriptor). Either **.object** or **.string** must be set.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: image source for the image span.
.object: **PixelMap** object. The parameter type is [ArkUI_DrawableDescriptor](#arkui_drawabledescriptor).| -| NODE_IMAGE_DRAGGABLE | Defines whether the image is draggable. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether the image is draggable. The value **true** means that the image is draggable.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether the image is draggable.| -| NODE_IMAGE_RENDER_MODE | Defines the image rendering mode. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: The parameter type is [ArkUI_ImageRenderMode](#arkui_imagerendermode).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: The parameter type is [ArkUI_ImageRenderMode](#arkui_imagerendermode).| -| NODE_IMAGE_FIT_ORIGINAL_SIZE | Sets whether to fit the component to the size of the image source when the component size is not set. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: indicates whether the display size of an image follows the size of the image source. The value 1 indicates that the display size follows the size of the image source, and the value 0 indicates that the display size does not follow the size of the image source. The default value is 0.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: The value **1** means to fit the component to the size of the image source, and **0** means the opposite.| -| NODE_IMAGE_FILL_COLOR | Sets the fill color to be superimposed on the image. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: fill color. The value is in 0xARGB format. For example, 0xFFFF0000 indicates red.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: fill color. The value is in 0xARGB format.| -| NODE_IMAGE_RESIZABLE | Sets the resizable image options.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: width of the left edge. The unit is vp.
.value[1].f32: width of the top edge. The unit is vp.
.value[2].f32: width of the right edge. The unit is vp.
.value[3].f32: width of the bottom edge. The unit is vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: width of the left edge. The unit is vp.
.value[1].f32: width of the top edge. The unit is vp.
.value[2].f32: width of the right edge. The unit is vp.
.value[3].f32: width of the bottom edge. The unit is vp.| -| NODE_TOGGLE_SELECTED_COLOR | Defines the color of the component when it is selected. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: background color, in 0xARGB format. For example, 0xFFFF0000 indicates red.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: background color, in 0xARGB format.| -| NODE_TOGGLE_SWITCH_POINT_COLOR | Defines the color of the circular slider for the component of the switch type. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: color of the circular slider, in 0xARGB format. For example, 0xFFFF0000 indicates red.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color of the circular slider, in 0xARGB format.| -| NODE_TOGGLE_VALUE | Defines the toggle switch value. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to enable the toggle. The value **true** means to enable the toggle.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to enable the toggle.| -| NODE_TOGGLE_UNSELECTED_COLOR | Defines the color of the component when it is deselected. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: background color, in 0xARGB format. For example, 0xFFFF0000 indicates red.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: background color, in 0xARGB format.| -| NODE_LOADING_PROGRESS_COLOR | Defines the foreground color of the loading progress bar. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: foreground color, in 0xARGB format. For example, 0xFFFF0000 indicates red.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: foreground color, in 0xARGB format.| -| NODE_LOADING_PROGRESS_ENABLE_LOADING | Defines whether to show the loading animation for the **LoadingProgress** component. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to show the loading animation. The value **true** means to show the loading animation, and **false** means the opposite.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to show the loading animation. The value **true** means to show the loading animation, and **false** means the opposite.| -| NODE_TEXT_INPUT_PLACEHOLDER | Defines the default placeholder text of the single-line text box. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: default placeholder text.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: default placeholder text.| -| NODE_TEXT_INPUT_TEXT | Defines the default text content of the single-line text box. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: default text content.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: default text content.| -| NODE_TEXT_INPUT_CARET_COLOR | Defines the border color attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: caret color, in 0xARGB format. For example, 0xFFFF0000 indicates red.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: caret color, in 0xARGB format. | -| NODE_TEXT_INPUT_CARET_STYLE | Defines the caret style attribute. APIs are provided for setting, resetting, and obtaining the attribute value.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: caret width, in vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: caret width, in vp.| -| NODE_TEXT_INPUT_SHOW_UNDERLINE | Defines the underline attribute of the single-line text box. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to show an underline. The value **true** means to show an underline, and **false** means the opposite.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: The value **1** means to show an underline, and **0** means the opposite.| -| NODE_TEXT_INPUT_MAX_LENGTH | Defines the maximum number of characters in the text input. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: maximum number of characters in the text input, without a unit.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: maximum number of characters in the text input.| -| NODE_TEXT_INPUT_ENTER_KEY_TYPE | Defines the type of the Enter key. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: Enter key type enumeration [ArkUI_EnterKeyType](#arkui_enterkeytype). The default value is ARKUI_ENTER_KEY_TYPE_DONE.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: type of the Enter key. The value is an enum of [ArkUI_EnterKeyType](#arkui_enterkeytype).| -| NODE_TEXT_INPUT_PLACEHOLDER_COLOR | Defines the placeholder text color. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: color value, in 0xARGB format. For example, 0xFFFF0000 indicates red.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color value, in 0xARGB format.| -| NODE_TEXT_INPUT_PLACEHOLDER_FONT | Defines the placeholder text font. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0]?.f32: font size, in fp. Optional. The default value is **16.0**.
.value[1]?.i32: font style [ArkUI_FontStyle](#arkui_fontstyle). Optional. The default value is **ARKUI_FONT_STYLE_NORMAL**.
.value[2]?.i32: font weight [ArkUI_FontWeight](#arkui_fontweight). Optional. The default value is **ARKUI_FONT_WEIGHT_NORMAL**.
?.string: font family. Multiple font families are separated by commas (,). For example, "font weight; font family 1, font family 2".
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: font size, in fp.
.value[1].i32: font style [ArkUI_FontStyle](#arkui_fontstyle).
.value[2].i32: font weight [ArkUI_FontWeight](#arkui_fontweight).
.string: font family. Multiple font families are separated by commas (,).| -| NODE_TEXT_INPUT_ENABLE_KEYBOARD_ON_FOCUS | Defines whether to enable the input method when the component obtains focus. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to enable the input method when the component obtains focus. The value **true** means to enable the input method, and **false** means the opposite.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to enable the input method when the component obtains focus. The value **1** means to enable the input method when the component obtains focus, and **0** means the opposite.| -| NODE_TEXT_INPUT_TYPE | Defines the text box type. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: input box type enumeration [ArkUI_TextInputType](#arkui_textinputtype). The default value is ARKUI_TEXTINPUT_TYPE_NORMAL.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: input box type enumeration [ArkUI_TextInputType](#arkui_textinputtype).| -| NODE_TEXT_INPUT_SELECTED_BACKGROUND_COLOR | Defines the background color of the selected text. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: color value, in 0xARGB format. For example, 0xFFFF0000 indicates red.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color value, in 0xARGB format.| -| NODE_TEXT_INPUT_SHOW_PASSWORD_ICON | Defines whether to display the password icon at the end of the password text box. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to display the password icon at the end of the password text box. The value **true** means to display the password icon, and **false** means the opposite.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: The value **1** means to display the password icon at the end of the password text box, and **0** means the opposite.| -| NODE_TEXT_INPUT_EDITING | Defines the editable state for the single-line text box. This attribute can be set as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to remain in the editable state. The value **true** means to remain in the editable state, and **false** means to exit the editable state.
The format of the attribute obtaining method parameter [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) is as follows:
.value[0].i32: whether to remain in the editable state. The value **true** means to remain in the editable state, and **false** means to exit the editable state.| -| NODE_TEXT_INPUT_CANCEL_BUTTON | Defines the style of the cancel button on the right of the single-line text box. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: button style [ArkUI_CancelButtonStyle](#arkui_cancelbuttonstyle). The default value is ARKUI_CANCELBUTTON_STYLE_INPUT.
.value[1]?.f32: button icon size, in vp.
.value[2]?.u32: button icon color, in 0xARGB format. For example, 0xFFFF0000 indicates red.
?.string: button icon image source. The value is the local address of the image, for example, /pages/icon.png.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: button style [ArkUI_CancelButtonStyle](#arkui_cancelbuttonstyle).
.value[1].f32: icon size, in vp.
.value[2].u32: button icon color, in 0xARGB format.
.string: button icon image source.| -| NODE_TEXT_INPUT_TEXT_SELECTION | Sets the text selection area, which will be highlighted. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: start position of the text selection.
.value[1].i32: end position of the text selection.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: start position of the text selection.
.value[1].i32: end position of the text selection. | -| NODE_TEXT_INPUT_UNDERLINE_COLOR | Sets the color of the underline when it is shown.
The default underline color configured for the theme is **'0x33182431'**.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: color of the underline applied to the text being typed in. The value is in 0xARGB format.
.value[1].u32: color of the underline applied to the text in the normal state. The value is in 0xARGB format.
.value[2].u32: color of the underline applied to the text when an error is detected. The value is in 0xARGB format.
.value[3].u32: color of the underline applied to the text when it is disabled. The value is in 0xARGB format.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color of the underline applied to the text being typed in. The value is in 0xARGB format.
.value[1].u32: color of the underline applied to the text in the normal state. The value is in 0xARGB format.
.value[2].u32: color of the underline applied to the text when an error is detected. The value is in 0xARGB format.
.value[3].u32: color of the underline applied to the text when it is disabled. The value is in 0xARGB format. | -| NODE_TEXT_INPUT_ENABLE_AUTO_FILL | Sets whether to enable autofill.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to enable autofill. The default value is **true**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to enable autofill.| -| NODE_TEXT_INPUT_CONTENT_TYPE | Sets the autofill type.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: autofill type. The parameter type is [ArkUI_TextInputContentType](#arkui_textinputcontenttype).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: autofill type. The parameter type is [ArkUI_TextInputContentType](#arkui_textinputcontenttype).| -| NODE_TEXT_INPUT_PASSWORD_RULES | Defines the rules for generating passwords. When autofill is used, these rules are transparently transmitted to Password Vault for generating a new password.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: rules for generating passwords.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: rules for generating passwords.| -| NODE_TEXT_INPUT_SELECT_ALL | Sets whether to select all text in the initial state. This attribute is not available for the inline input style.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to select all text in the initial state. The default value is **false**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to select all text in the initial state.| -| NODE_TEXT_INPUT_INPUT_FILTER | Sets the regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are filtered out. The specified regular expression can match single characters, but not strings.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: regular expression.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: regular expression.| -| NODE_TEXT_INPUT_STYLE | Sets the text box to the default style or inline input style.
For the inline input style, only **InputType.Normal** is supported.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: text input style. The parameter type is [ArkUI_TextInputStyle](#arkui_textinputstyle).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: text input style. The parameter type is [ArkUI_TextInputStyle](#arkui_textinputstyle).| -| NODE_TEXT_INPUT_CARET_OFFSET | Sets or obtains the caret position.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
Sets the position of the caret. .value[0].i32: length from the start of the string to the position where the input cursor is located.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
Returns the position information of the caret. If this API is called when the cursor position is updated in the current frame, value[0].i32 (index value of the cursor position) does not take effect.
value[1].f32: X coordinate of the cursor relative to the text box.
value[2].f32: Y coordinate of the cursor relative to the text box.| -| NODE_TEXT_INPUT_CONTENT_RECT | Position of the edited text area relative to the component and its size.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
value[0].f32: horizontal coordinate.
value[1].f32: vertical coordinate.
value[2].f32: content width.
value[3].f32: content height.| -| NODE_TEXT_INPUT_CONTENT_LINE_COUNT | Obtains the number of lines of the edited text.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
value[0].i32: number of lines in the edited text.| -| NODE_TEXT_INPUT_SELECTION_MENU_HIDDEN | Sets whether to hide the text selection menu when the text box is long-pressed, double-click, or right-clicked. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to hide the text selection menu when the text box is long-pressed, double-click, or right-clicked. The default value is **false**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to hide the text selection menu when the text box is long-pressed, double-click, or right-clicked.| -| NODE_TEXT_INPUT_BLUR_ON_SUBMIT | Sets whether the text box loses focus after the Enter key is pressed to submit information.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether the text box loses focus.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether the text box loses focus.| -| NODE_TEXT_INPUT_CUSTOM_KEYBOARD | Sets a custom keyboard.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.object: custom keyboard. The parameter type is **ArkUI_NodeHandle**.
.value[0]?.i32: whether the custom keyboard supports avoidance. The default value is **false**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: custom keyboard. The parameter type is **ArkUI_NodeHandle**.
.value[0].i32: whether the custom keyboard supports avoidance.| -| NODE_TEXT_INPUT_WORD_BREAK | Defines the line break rule. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: line break rule. The parameter type is [ArkUI_WordBreak](#arkui_wordbreak).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: line break rule. The parameter type is [ArkUI_WordBreak](#arkui_wordbreak).| -| NODE_TEXT_INPUT_NUMBER_OF_LINES | Sets the number of lines in **TextInput** component, which can be used to work out the height of the component.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: number of lines.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: number of lines.| -| NODE_TEXT_INPUT_SHOW_KEYBOARD_ON_FOCUS | Sets whether to show the keyboard when the text box obtains focus. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to show the keyboard when the text box obtains focus.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to show the keyboard when the text box obtains focus.| +| NODE_SPAN_CONTENT | Defines the text content attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: content of the text span.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: content of the text span.| +| NODE_SPAN_TEXT_BACKGROUND_STYLE | Defines the text background style. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: color of the text background, in 0xARGB format, for example, **0xFFFF0000** indicating red.
The second parameter is used to set the rounded corner of the text background. The options are as follows:
1: .value[1].f32: The radiuses of rounded corners in the four directions are set in a unified manner. The unit is vp.
2: .value[1].f32: radius of the upper left corner, in vp.
.value[2].f32: radius of the upper right corner, in vp.
.value[3].f32: radius of the lower left corner, in vp.
.value[4].f32: radius of the lower right corner, in vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color of the text background, in 0xARGB format.
.value[1].f32: radius of the upper left corner, in vp.
.value[2].f32: radius of the upper right corner, in vp.
.value[3].f32: radius of the lower left corner, in vp.
.value[4].f32: radius of the lower right corner, in vp.| +| NODE_SPAN_BASELINE_OFFSET | Defines the text baseline offset attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: baseline offset, in fp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: baseline offset, in fp.| +| NODE_IMAGE_SPAN_SRC | Defines the image source for an image span. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: image address of the image span.
.object: **PixelMap** object. The parameter type is [ArkUI_DrawableDescriptor](#arkui_drawabledescriptor).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: image address of the image span.
.object: **PixelMap** object. The parameter type is [ArkUI_DrawableDescriptor](#arkui_drawabledescriptor). Either **.object** or **.string** must be set.| +| NODE_IMAGE_SPAN_VERTICAL_ALIGNMENT | Defines the alignment mode of the image with the text. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32 indicates the text-based image alignment mode. The enumerated values of [ArkUI_ImageSpanAlignment](#arkui_imagespanalignment) are used.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32 indicates the text-based image alignment mode. The enumerated values of [ArkUI_ImageSpanAlignment](#arkui_imagespanalignment) are used.| +| NODE_IMAGE_SPAN_ALT | Defines the image source for an image span. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: placeholder image address for the image span. GIF images are not supported.
.object: **PixelMap** object. The parameter type is [ArkUI_DrawableDescriptor](#arkui_drawabledescriptor). Either **.object** or **.string** must be set.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: image source for the image span.
.object: **PixelMap** object. The parameter type is [ArkUI_DrawableDescriptor](#arkui_drawabledescriptor).| +| NODE_IMAGE_SPAN_BASELINE_OFFSET | Defines the baseline offset attribute of the **ImageSpan** component. This attribute can be set, reset, and obtained as required through APIs. A positive value means an upward offset, while a negative value means a downward offset. The default value is **0**, and the unit is fp.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: baseline offset, in fp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: baseline offset, in fp.| +| NODE_IMAGE_SRC | Defines the image source of the **Image** component. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: image source.
.object: **PixelMap** object. The parameter type is [ArkUI_DrawableDescriptor](#arkui_drawabledescriptor). Either **.object** or **.string** must be set.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: image source.
.object: **PixelMap** object. The parameter type is [ArkUI_DrawableDescriptor](#arkui_drawabledescriptor).| +| NODE_IMAGE_OBJECT_FIT | Defines how the image is resized to fit its container. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32 indicates the image filling effect. The enumerated values of [ArkUI_ObjectFit](#arkui_objectfit) are used.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32 indicates the image filling effect. The enumerated values of [ArkUI_ObjectFit](#arkui_objectfit) are used.| +| NODE_IMAGE_INTERPOLATION | Defines the interpolation effect of the image. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32 indicates the interpolation effect. The enumerated values of [ArkUI_ImageInterpolation](#arkui_imageinterpolation) are used.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32 indicates the interpolation effect. The enumerated values of [ArkUI_ImageInterpolation](#arkui_imageinterpolation) are used.| +| NODE_IMAGE_OBJECT_REPEAT | Defines how the image is repeated. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32 indicates the image repetition style. The enumerated values of [ArkUI_ImageRepeat](#arkui_imagerepeat) are used.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32 indicates the image repetition style. The enumerated values of [ArkUI_ImageRepeat](#arkui_imagerepeat) are used.| +| NODE_IMAGE_COLOR_FILTER | Defines the color filter of the image. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32 to .value[19].f32: filter matrix array.
.size: 5 x 4 filter array size.
.object: pointer to the color filter. The parameter type is **OH_Drawing_ColorFilter**. Either .object or .size can be set.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32 to .value[19].f32: filter matrix array.
.size: 5 x 4 filter array size.
.object: pointer to the color filter. The parameter type is **OH_Drawing_ColorFilter**.| +| NODE_IMAGE_AUTO_RESIZE | Defines the auto resize attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32 : whether to resize the image source.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32 : whether to resize the image source.| +| NODE_IMAGE_ALT | Defines the placeholder image source. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: image source for the image span.
.object: **PixelMap** object. The parameter type is [ArkUI_DrawableDescriptor](#arkui_drawabledescriptor). Either **.object** or **.string** must be set.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: image source for the image span.
.object: **PixelMap** object. The parameter type is [ArkUI_DrawableDescriptor](#arkui_drawabledescriptor).| +| NODE_IMAGE_DRAGGABLE | Defines whether the image is draggable. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether the image is draggable. The value **true** means that the image is draggable.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether the image is draggable.| +| NODE_IMAGE_RENDER_MODE | Defines the image rendering mode. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: The parameter type is [ArkUI_ImageRenderMode](#arkui_imagerendermode).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: The parameter type is [ArkUI_ImageRenderMode](#arkui_imagerendermode).| +| NODE_IMAGE_FIT_ORIGINAL_SIZE | Sets whether to fit the component to the size of the image source when the component size is not set. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: indicates whether the display size of an image follows the size of the image source. The value 1 indicates that the display size follows the size of the image source, and the value 0 indicates that the display size does not follow the size of the image source. The default value is 0.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: The value **1** means to fit the component to the size of the image source, and **0** means the opposite.| +| NODE_IMAGE_FILL_COLOR | Sets the fill color to be superimposed on the image. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: fill color. The value is in 0xARGB format. For example, 0xFFFF0000 indicates red.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: fill color. The value is in 0xARGB format.| +| NODE_IMAGE_RESIZABLE | Sets the resizable image options.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: width of the left edge. The unit is vp.
.value[1].f32: width of the top edge. The unit is vp.
.value[2].f32: width of the right edge. The unit is vp.
.value[3].f32: width of the bottom edge. The unit is vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: width of the left edge. The unit is vp.
.value[1].f32: width of the top edge. The unit is vp.
.value[2].f32: width of the right edge. The unit is vp.
.value[3].f32: width of the bottom edge. The unit is vp.| +| NODE_TOGGLE_SELECTED_COLOR | Defines the color of the component when it is selected. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: background color, in 0xARGB format. For example, 0xFFFF0000 indicates red.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: background color, in 0xARGB format.| +| NODE_TOGGLE_SWITCH_POINT_COLOR | Defines the color of the circular slider for the component of the switch type. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: color of the circular slider, in 0xARGB format. For example, 0xFFFF0000 indicates red.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color of the circular slider, in 0xARGB format.| +| NODE_TOGGLE_VALUE | Defines the toggle switch value. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to enable the toggle. The value **true** means to enable the toggle.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to enable the toggle.| +| NODE_TOGGLE_UNSELECTED_COLOR | Defines the color of the component when it is deselected. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: background color, in 0xARGB format. For example, 0xFFFF0000 indicates red.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: background color, in 0xARGB format.| +| NODE_LOADING_PROGRESS_COLOR | Defines the foreground color of the loading progress bar. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: foreground color, in 0xARGB format. For example, 0xFFFF0000 indicates red.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: foreground color, in 0xARGB format.| +| NODE_LOADING_PROGRESS_ENABLE_LOADING | Defines whether to show the loading animation for the **LoadingProgress** component. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to show the loading animation. The value **true** means to show the loading animation, and **false** means the opposite.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to show the loading animation. The value **true** means to show the loading animation, and **false** means the opposite.| +| NODE_TEXT_INPUT_PLACEHOLDER | Defines the default placeholder text of the single-line text box. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: default placeholder text.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: default placeholder text.| +| NODE_TEXT_INPUT_TEXT | Defines the default text content of the single-line text box. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: default text content.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: default text content.| +| NODE_TEXT_INPUT_CARET_COLOR | Defines the border color attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: caret color, in 0xARGB format. For example, 0xFFFF0000 indicates red.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: caret color, in 0xARGB format. | +| NODE_TEXT_INPUT_CARET_STYLE | Defines the caret style attribute. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: caret width, in vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: caret width, in vp.| +| NODE_TEXT_INPUT_SHOW_UNDERLINE | Defines the underline attribute of the single-line text box. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to show an underline. The value **true** means to show an underline, and **false** means the opposite.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: The value **1** means to show an underline, and **0** means the opposite.| +| NODE_TEXT_INPUT_MAX_LENGTH | Defines the maximum number of characters in the text input. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: maximum number of characters in the text input, without a unit.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: maximum number of characters in the text input.| +| NODE_TEXT_INPUT_ENTER_KEY_TYPE | Defines the type of the Enter key. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: Enter key type enumeration [ArkUI_EnterKeyType](#arkui_enterkeytype). The default value is ARKUI_ENTER_KEY_TYPE_DONE.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: type of the Enter key. The value is an enum of [ArkUI_EnterKeyType](#arkui_enterkeytype).| +| NODE_TEXT_INPUT_PLACEHOLDER_COLOR | Defines the placeholder text color. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: color value, in 0xARGB format. For example, 0xFFFF0000 indicates red.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color value, in 0xARGB format.| +| NODE_TEXT_INPUT_PLACEHOLDER_FONT | Defines the placeholder text font. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0]?.f32: font size, in fp. Optional. The default value is **16.0**.
.value[1]?.i32: font style [ArkUI_FontStyle](#arkui_fontstyle). Optional. The default value is **ARKUI_FONT_STYLE_NORMAL**.
.value[2]?.i32: font weight [ArkUI_FontWeight](#arkui_fontweight). Optional. The default value is **ARKUI_FONT_WEIGHT_NORMAL**.
?.string: font family. Multiple font families are separated by commas (,). For example, "font weight; font family 1, font family 2".
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: font size, in fp.
.value[1].i32: font style [ArkUI_FontStyle](#arkui_fontstyle).
.value[2].i32: font weight [ArkUI_FontWeight](#arkui_fontweight).
.string: font family. Multiple font families are separated by commas (,).| +| NODE_TEXT_INPUT_ENABLE_KEYBOARD_ON_FOCUS | Defines whether to enable the input method when the component obtains focus. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to enable the input method when the component obtains focus. The value **true** means to enable the input method, and **false** means the opposite.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to enable the input method when the component obtains focus. The value **1** means to enable the input method when the component obtains focus, and **0** means the opposite.| +| NODE_TEXT_INPUT_TYPE | Defines the text box type. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: input box type enumeration [ArkUI_TextInputType](#arkui_textinputtype). The default value is ARKUI_TEXTINPUT_TYPE_NORMAL.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: input box type enumeration [ArkUI_TextInputType](#arkui_textinputtype).| +| NODE_TEXT_INPUT_SELECTED_BACKGROUND_COLOR | Defines the background color of the selected text. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: color value, in 0xARGB format. For example, 0xFFFF0000 indicates red.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color value, in 0xARGB format.| +| NODE_TEXT_INPUT_SHOW_PASSWORD_ICON | Defines whether to display the password icon at the end of the password text box. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to display the password icon at the end of the password text box. The value **true** means to display the password icon, and **false** means the opposite.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: The value **1** means to display the password icon at the end of the password text box, and **0** means the opposite.| +| NODE_TEXT_INPUT_EDITING | Defines the editable state for the single-line text box. This attribute can be set as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to remain in the editable state. The value **true** means to remain in the editable state, and **false** means to exit the editable state.
The format of the attribute obtaining method parameter [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) is as follows:
.value[0].i32: whether to remain in the editable state. The value **true** means to remain in the editable state, and **false** means to exit the editable state.| +| NODE_TEXT_INPUT_CANCEL_BUTTON | Defines the style of the cancel button on the right of the single-line text box. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: button style [ArkUI_CancelButtonStyle](#arkui_cancelbuttonstyle). The default value is ARKUI_CANCELBUTTON_STYLE_INPUT.
.value[1]?.f32: button icon size, in vp.
.value[2]?.u32: button icon color, in 0xARGB format. For example, 0xFFFF0000 indicates red.
?.string: button icon image source. The value is the local address of the image, for example, /pages/icon.png.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: button style [ArkUI_CancelButtonStyle](#arkui_cancelbuttonstyle).
.value[1].f32: icon size, in vp.
.value[2].u32: button icon color, in 0xARGB format.
.string: button icon image source.| +| NODE_TEXT_INPUT_TEXT_SELECTION | Sets the text selection area, which will be highlighted. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: start position of the text selection.
.value[1].i32: end position of the text selection.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: start position of the text selection.
.value[1].i32: end position of the text selection. | +| NODE_TEXT_INPUT_UNDERLINE_COLOR | Sets the color of the underline when it is shown.
The default underline color configured for the theme is **'0x33182431'**.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: color of the underline applied to the text being typed in. The value is in 0xARGB format.
.value[1].u32: color of the underline applied to the text in the normal state. The value is in 0xARGB format.
.value[2].u32: color of the underline applied to the text when an error is detected. The value is in 0xARGB format.
.value[3].u32: color of the underline applied to the text when it is disabled. The value is in 0xARGB format.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color of the underline applied to the text being typed in. The value is in 0xARGB format.
.value[1].u32: color of the underline applied to the text in the normal state. The value is in 0xARGB format.
.value[2].u32: color of the underline applied to the text when an error is detected. The value is in 0xARGB format.
.value[3].u32: color of the underline applied to the text when it is disabled. The value is in 0xARGB format. | +| NODE_TEXT_INPUT_ENABLE_AUTO_FILL | Sets whether to enable autofill.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to enable autofill. The default value is **true**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to enable autofill.| +| NODE_TEXT_INPUT_CONTENT_TYPE | Sets the autofill type.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: autofill type. The parameter type is [ArkUI_TextInputContentType](#arkui_textinputcontenttype).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: autofill type. The parameter type is [ArkUI_TextInputContentType](#arkui_textinputcontenttype).| +| NODE_TEXT_INPUT_PASSWORD_RULES | Defines the rules for generating passwords. When autofill is used, these rules are transparently transmitted to Password Vault for generating a new password.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: rules for generating passwords.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: rules for generating passwords.| +| NODE_TEXT_INPUT_SELECT_ALL | Sets whether to select all text in the initial state. This attribute is not available for the inline input style.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to select all text in the initial state. The default value is b>false.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to select all text in the initial state.| +| NODE_TEXT_INPUT_INPUT_FILTER | Sets the regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are filtered out. The specified regular expression can match single characters, but not strings.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: regular expression.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: regular expression.| +| NODE_TEXT_INPUT_STYLE | Sets the text box to the default style or inline input style.
For the inline input style, only **InputType.Normal** is supported.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: text input style. The parameter type is [ArkUI_TextInputStyle](#arkui_textinputstyle).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: text input style. The parameter type is [ArkUI_TextInputStyle](#arkui_textinputstyle).| +| NODE_TEXT_INPUT_CARET_OFFSET | Sets or obtains the caret position.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
Sets the position of the caret. .value[0].i32: length from the start of the string to the position where the input cursor is located.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
Returns the position information of the caret. If this API is called when the cursor position is updated in the current frame, value[0].i32 (index value of the cursor position) does not take effect.
value[1].f32: X coordinate of the cursor relative to the text box.
value[2].f32: Y coordinate of the cursor relative to the text box.| +| NODE_TEXT_INPUT_CONTENT_RECT | Position of the edited text area relative to the component and its size.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
value[0].f32: horizontal coordinate.
value[1].f32: vertical coordinate.
value[2].f32: content width.
value[3].f32: content height.| +| NODE_TEXT_INPUT_CONTENT_LINE_COUNT | Obtains the number of lines of the edited text.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
value[0].i32: number of lines in the edited text.| +| NODE_TEXT_INPUT_SELECTION_MENU_HIDDEN | Sets whether to hide the text selection menu when the text box is long-pressed, double-click, or right-clicked. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to hide the text selection menu when the text box is long-pressed, double-click, or right-clicked. The default value is **false**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to hide the text selection menu when the text box is long-pressed, double-click, or right-clicked.| +| NODE_TEXT_INPUT_BLUR_ON_SUBMIT | Sets whether the text box loses focus after the Enter key is pressed to submit information.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether the text box loses focus.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether the text box loses focus.| +| NODE_TEXT_INPUT_CUSTOM_KEYBOARD | Sets a custom keyboard.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.object: custom keyboard. The parameter type is **ArkUI_NodeHandle**.
.value[0]?.i32: whether the custom keyboard supports avoidance. The default value is **false**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: custom keyboard. The parameter type is **ArkUI_NodeHandle**.
.value[0].i32: whether the custom keyboard supports avoidance.| +| NODE_TEXT_INPUT_WORD_BREAK | Defines the line break rule. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: line break rule. The parameter type is [ArkUI_WordBreak](#arkui_wordbreak).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: line break rule. The parameter type is [ArkUI_WordBreak](#arkui_wordbreak).| +| NODE_TEXT_INPUT_NUMBER_OF_LINES | Sets the number of lines in **TextInput** component, which can be used to work out the height of the component.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: number of lines.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: number of lines.| +| NODE_TEXT_INPUT_SHOW_KEYBOARD_ON_FOCUS | Sets whether to show the keyboard when the text box obtains focus. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to show the keyboard when the text box obtains focus.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to show the keyboard when the text box obtains focus.| | NODE_TEXT_INPUT_LETTER_SPACING | Sets the letter spacing attribute. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: letter spacing. The default unit is fp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: letter spacing. The default unit is fp.| | NODE_TEXT_INPUT_ENABLE_PREVIEW_TEXT | Sets whether to enable preview text for the text box. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to enable preview tex.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to enable preview tex.| -| NODE_TEXT_AREA_PLACEHOLDER | Defines the default placeholder text of the single-line text box. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: default placeholder text.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: default placeholder text.| -| NODE_TEXT_AREA_TEXT | Defines the default text content for the multi-line text box. The attribute setting, attribute resetting, and attribute obtaining interfaces are supported.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: default text content.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: default text content.| -| NODE_TEXT_AREA_MAX_LENGTH | Defines the maximum number of characters in the text input. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: maximum number of characters in the text input.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: maximum number of characters in the text input.| -| NODE_TEXT_AREA_PLACEHOLDER_COLOR | Defines the placeholder text color. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: color value, in 0xARGB format. For example, 0xFFFF0000 indicates red.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color value, in 0xARGB format.| -| NODE_TEXT_AREA_PLACEHOLDER_FONT | Defines the placeholder text font. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0]?.f32: font size, in fp. Optional. The default value is **16.0**.
.value[1]?.i32: font style [ArkUI_FontStyle](#arkui_fontstyle). Optional. The default value is **ARKUI_FONT_STYLE_NORMAL**.
.value[2]?.i32: font weight [ArkUI_FontWeight](#arkui_fontweight). Optional. The default value is **ARKUI_FONT_WEIGHT_NORMAL**.
?.string: font family. Multiple font families are separated by commas (,). For example, "font weight; font family 1, font family 2".
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: font size, in fp.
.value[1].i32: font style [ArkUI_FontStyle](#arkui_fontstyle).
.value[2].i32: font weight [ArkUI_FontWeight](#arkui_fontweight).
.string: font family. Multiple font families are separated by commas (,).| -| NODE_TEXT_AREA_CARET_COLOR | Defines the border color attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: background color, in 0xARGB format. For example, 0xFFFF0000 indicates red.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: background color, in 0xARGB format.| -| NODE_TEXT_AREA_EDITING | Defines the editable state for the multi-line text box. This attribute can be set as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to remain in the editable state. The value **true** means to remain in the editable state, and **false** means to exit the editable state.
The format of the attribute obtaining method parameter [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) is as follows:
.value[0].i32: whether to remain in the editable state. The value **true** means to remain in the editable state, and **false** means to exit the editable state.| -| NODE_TEXT_AREA_TYPE | Defines the text box type. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: input box type enumeration [ArkUI_TextAreaType](#arkui_textareatype). The default value is ARKUI_TEXTAREA_TYPE_NORMAL.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: input box type enumeration [ArkUI_TextAreaType](#arkui_textareatype).| -| NODE_TEXT_AREA_SHOW_COUNTER | Defines the counter settings. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to show a character counter. The value **true** means to show a character counter.
.value[1]?.f32: threshold percentage for displaying the character counter. The character counter is displayed when the number of characters that have been entered is greater than the maximum number of characters multiplied by the threshold percentage value. The value range is 1 to 100. If the value is a decimal, it is rounded down.
.value[2]?.i32: whether to highlight the border when the number of entered characters reaches the maximum.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to show a character counter.
.value[1].f32: threshold percentage for displaying the character counter. The character counter is displayed when the number of characters that have been entered is greater than the maximum number of characters multiplied by the threshold percentage value. The value range is 1 to 100.
.value[2].i32: whether to highlight the border when the number of entered characters reaches the maximum. The default value is **true**.| -| NODE_TEXT_AREA_SELECTION_MENU_HIDDEN | Sets whether to hide the text selection menu when the text box is long-pressed, double-click, or right-clicked. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to hide the text selection menu when the text box is long-pressed, double-click, or right-clicked. The default value is **false**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to hide the text selection menu when the text box is long-pressed, double-click, or right-clicked.| -| NODE_TEXT_AREA_BLUR_ON_SUBMIT | Sets whether the multi-line text box loses focus after the Enter key is pressed to submit information.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether the text box loses focus.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether the text box loses focus.| -| NODE_TEXT_AREA_INPUT_FILTER | Sets the regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are filtered out. The specified regular expression can match single characters, but not strings.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: regular expression.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: regular expression.| -| NODE_TEXT_AREA_SELECTED_BACKGROUND_COLOR | Sets the background color of the selected text. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: color value, in 0xARGB format. For example, 0xFFFF0000 indicates red.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color value, in 0xARGB format.| -| NODE_TEXT_AREA_ENTER_KEY_TYPE | Defines the type of the Enter key. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: Enter key type enumeration [ArkUI_EnterKeyType](#arkui_enterkeytype). The default value is ARKUI_ENTER_KEY_TYPE_DONE.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: type of the Enter key. The value is an enum of [ArkUI_EnterKeyType](#arkui_enterkeytype).| -| NODE_TEXT_AREA_ENABLE_KEYBOARD_ON_FOCUS | Sets whether to enable the input method when the multi-line text box obtains focus in a way other than clicking. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to enable the input method when the multi-line text box obtains focus in a way other than clicking. The value **true** means to enable the input method, and **false** means the opposite. The default value is **false**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to enable the input method when the component obtains focus. The value **1** means to enable the input method when the component obtains focus, and **0** means the opposite.| -| NODE_TEXT_AREA_CARET_OFFSET | Sets or obtains the caret position.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
Sets the position of the caret. .value[0].i32: length from the start of the string to the position where the input cursor is located.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
Returns the position information of the caret. If this API is called when the cursor position is updated in the current frame, value[0].i32 (index value of the cursor position) does not take effect.
value[1].f32: X coordinate of the cursor relative to the text box.
value[2].f32: Y coordinate of the cursor relative to the text box.| -| NODE_TEXT_AREA_CONTENT_RECT | Position of the edited text area relative to the component and its size.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
value[0].f32: horizontal coordinate.
value[1].f32: vertical coordinate.
value[2].f32: content width.
value[3].f32: content height.| -| NODE_TEXT_AREA_CONTENT_LINE_COUNT | Obtains the number of lines of the edited text.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
value[0].i32: number of lines in the edited text.| -| NODE_TEXT_AREA_TEXT_SELECTION | Sets the text selection range and highlights the selected text when the component is focused. This API works only when the value of **selectionStart** is less than that of **selectionEnd**.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: start position of the text selection.
.value[1].i32: end position of the text selection.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: start position of the text selection.
.value[1].i32: end position of the text selection. | -| NODE_TEXT_AREA_ENABLE_AUTO_FILL | Sets whether to enable autofill.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to enable autofill. The default value is **true**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to enable autofill.| -| NODE_TEXT_AREA_CONTENT_TYPE | Enumerates the content types for autofill.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: autofill type. The parameter type is [ArkUI_TextInputContentType](#arkui_textinputcontenttype).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: autofill type. The parameter type is [ArkUI_TextInputContentType](#arkui_textinputcontenttype).| -| NODE_TEXT_AREA_NUMBER_OF_LINES | Sets the number of lines in **TextArea** component, which can be used to work out the height of the component.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: number of lines.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: number of lines.| -| NODE_TEXT_AREA_SHOW_KEYBOARD_ON_FOCUS | Sets whether to show the keyboard when the text box obtains focus. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to show the keyboard when the text box obtains focus.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to show the keyboard when the text box obtains focus.| +| NODE_TEXT_INPUT_KEYBOARD_APPEARANCE | Sets the appearance of the keyboard when the text box is focused.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: appearance of the keyboard, specified by an enumeration value of [ArkUI_KeyboardAppearance](#arkui_keyboardappearance).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: appearance of the keyboard, specified by an enumeration value of [ArkUI_KeyboardAppearance](#arkui_keyboardappearance).
**Since**
15 | +| NODE_TEXT_AREA_PLACEHOLDER | Defines the default placeholder text of the single-line text box. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: default placeholder text.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: default placeholder text.| +| NODE_TEXT_AREA_TEXT | Defines the default text content for the multi-line text box. The attribute setting, attribute resetting, and attribute obtaining interfaces are supported.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: default text content.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: default text content.| +| NODE_TEXT_AREA_MAX_LENGTH | Defines the maximum number of characters in the text input. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: maximum number of characters in the text input.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: maximum number of characters in the text input.| +| NODE_TEXT_AREA_PLACEHOLDER_COLOR | Defines the placeholder text color. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: color value, in 0xARGB format. For example, 0xFFFF0000 indicates red.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color value, in 0xARGB format.| +| NODE_TEXT_AREA_PLACEHOLDER_FONT | Defines the placeholder text font. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0]?.f32: font size, in fp. Optional. The default value is **16.0**.
.value[1]?.i32: font style [ArkUI_FontStyle](#arkui_fontstyle). Optional. The default value is **ARKUI_FONT_STYLE_NORMAL**.
.value[2]?.i32: font weight [ArkUI_FontWeight](#arkui_fontweight). Optional. The default value is **ARKUI_FONT_WEIGHT_NORMAL**.
?.string: font family. Multiple font families are separated by commas (,). For example, "font weight; font family 1, font family 2".
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: font size, in fp.
.value[1].i32: font style [ArkUI_FontStyle](#arkui_fontstyle).
.value[2].i32: font weight [ArkUI_FontWeight](#arkui_fontweight).
.string: font family. Multiple font families are separated by commas (,).| +| NODE_TEXT_AREA_CARET_COLOR | Defines the border color attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: background color, in 0xARGB format. For example, 0xFFFF0000 indicates red.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: background color, in 0xARGB format.| +| NODE_TEXT_AREA_EDITING | Defines the editable state for the multi-line text box. This attribute can be set as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to remain in the editable state. The value **true** means to remain in the editable state, and **false** means to exit the editable state.
The format of the attribute obtaining method parameter [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) is as follows:
.value[0].i32: whether to remain in the editable state. The value **true** means to remain in the editable state, and **false** means to exit the editable state.| +| NODE_TEXT_AREA_TYPE | Defines the text box type. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: input box type enumeration [ArkUI_TextAreaType](#arkui_textareatype). The default value is ARKUI_TEXTAREA_TYPE_NORMAL.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: input box type enumeration [ArkUI_TextAreaType](#arkui_textareatype).| +| NODE_TEXT_AREA_SHOW_COUNTER | Defines the counter settings. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to show a character counter. The value **true** means to show a character counter.
.value[1]?.f32: threshold percentage for displaying the character counter. The character counter is displayed when the number of characters that have been entered is greater than the maximum number of characters multiplied by the threshold percentage value. The value range is 1 to 100. If the value is a decimal, it is rounded down.
.value[2]?.i32: whether to highlight the border when the number of entered characters reaches the maximum.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to show a character counter.
.value[1].f32: threshold percentage for displaying the character counter. The character counter is displayed when the number of characters that have been entered is greater than the maximum number of characters multiplied by the threshold percentage value. The value range is 1 to 100.
.value[2].i32: whether to highlight the border when the number of entered characters reaches the maximum. The default value is **true**.| +| NODE_TEXT_AREA_SELECTION_MENU_HIDDEN | Sets whether to hide the text selection menu when the text box is long-pressed, double-click, or right-clicked. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to hide the text selection menu when the text box is long-pressed, double-click, or right-clicked. The default value is **false**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to hide the text selection menu when the text box is long-pressed, double-click, or right-clicked.| +| NODE_TEXT_AREA_BLUR_ON_SUBMIT | Sets whether the multi-line text box loses focus after the Enter key is pressed to submit information.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether the text box loses focus.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether the text box loses focus.| +| NODE_TEXT_AREA_INPUT_FILTER | Sets the regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are filtered out. The specified regular expression can match single characters, but not strings.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: regular expression.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: regular expression.| +| NODE_TEXT_AREA_SELECTED_BACKGROUND_COLOR | Sets the background color of the selected text. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: color value, in 0xARGB format. For example, 0xFFFF0000 indicates red.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color value, in 0xARGB format.| +| NODE_TEXT_AREA_ENTER_KEY_TYPE | Defines the type of the Enter key. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: Enter key type enumeration [ArkUI_EnterKeyType](#arkui_enterkeytype). The default value is ARKUI_ENTER_KEY_TYPE_DONE.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: type of the Enter key. The value is an enum of [ArkUI_EnterKeyType](#arkui_enterkeytype).| +| NODE_TEXT_AREA_ENABLE_KEYBOARD_ON_FOCUS | Sets whether to enable the input method when the multi-line text box obtains focus in a way other than clicking. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to enable the input method when the multi-line text box obtains focus in a way other than clicking. The value **true** means to enable the input method, and **false** means the opposite. The default value is **false**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to enable the input method when the component obtains focus. The value **1** means to enable the input method when the component obtains focus, and **0** means the opposite.| +| NODE_TEXT_AREA_CARET_OFFSET | Sets or obtains the caret position.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
Sets the position of the caret. .value[0].i32: length from the start of the string to the position where the input cursor is located.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
Returns the position information of the caret. If this API is called when the cursor position is updated in the current frame, value[0].i32 (index value of the cursor position) does not take effect.
value[1].f32: X coordinate of the cursor relative to the text box.
value[2].f32: Y coordinate of the cursor relative to the text box.| +| NODE_TEXT_AREA_CONTENT_RECT | Position of the edited text area relative to the component and its size.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
value[0].f32: horizontal coordinate.
value[1].f32: vertical coordinate.
value[2].f32: content width.
value[3].f32: content height.| +| NODE_TEXT_AREA_CONTENT_LINE_COUNT | Obtains the number of lines of the edited text.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
value[0].i32: number of lines in the edited text.| +| NODE_TEXT_AREA_TEXT_SELECTION | Sets the text selection range and highlights the selected text when the component is focused. This API works only when the value of **selectionStart** is less than that of **selectionEnd**.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: start position of the text selection.
.value[1].i32: end position of the text selection.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: start position of the text selection.
.value[1].i32: end position of the text selection. | +| NODE_TEXT_AREA_ENABLE_AUTO_FILL | Sets whether to enable autofill.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to enable autofill. The default value is **true**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to enable autofill.| +| NODE_TEXT_AREA_CONTENT_TYPE | Enumerates the content types for autofill.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: autofill type. The parameter type is [ArkUI_TextInputContentType](#arkui_textinputcontenttype).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: autofill type. The parameter type is [ArkUI_TextInputContentType](#arkui_textinputcontenttype).| +| NODE_TEXT_AREA_NUMBER_OF_LINES | Sets the number of lines in **TextArea** component, which can be used to work out the height of the component.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: number of lines.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: number of lines.| +| NODE_TEXT_AREA_SHOW_KEYBOARD_ON_FOCUS | Sets whether to show the keyboard when the text box obtains focus. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to show the keyboard when the text box obtains focus.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to show the keyboard when the text box obtains focus.| | NODE_TEXT_AREA_LETTER_SPACING | Sets the letter spacing attribute. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: letter spacing. The default unit is fp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: letter spacing. The default unit is fp.| | NODE_TEXT_AREA_ENABLE_PREVIEW_TEXT | Sets whether to enable preview text for the text box. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to enable preview tex.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to enable preview tex.| -| NODE_BUTTON_LABEL | Defines the button text content. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: default text content.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: default text content.| -| NODE_BUTTON_TYPE | Sets the button type. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: button style. The parameter type is [ArkUI_ButtonType](#arkui_buttontype). The default value is ARKUI_BUTTON_TYPE_CAPSULE.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: Obtains the style of the button. The parameter type is [ArkUI_ButtonType](#arkui_buttontype). The default value is ARKUI_BUTTON_TYPE_CAPSULE.| +| NODE_TEXT_AREA_KEYBOARD_APPEARANCE | Sets the appearance of the keyboard when the text box is focused.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: appearance of the keyboard, specified by an enumeration value of [ArkUI_KeyboardAppearance](#arkui_keyboardappearance).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: appearance of the keyboard, specified by an enumeration value of [ArkUI_KeyboardAppearance](#arkui_keyboardappearance).
**Since**
15 | +| NODE_BUTTON_LABEL | Defines the button text content. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: default text content.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: default text content.| +| NODE_BUTTON_TYPE | Sets the button type. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: button style. The parameter type is [ArkUI_ButtonType](#arkui_buttontype). The default value is ARKUI_BUTTON_TYPE_CAPSULE.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: Obtains the style of the button. The parameter type is [ArkUI_ButtonType](#arkui_buttontype). The default value is ARKUI_BUTTON_TYPE_CAPSULE.| | NODE_BUTTON_MIN_FONT_SCALE | Sets the minimum font scale factor for the button. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
* .value[0].f32: minimum font scale factor. The default unit is fp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: minimum font scale factor. The default unit is fp.| | NODE_BUTTON_MAX_FONT_SCALE | Sets the maximum font scale factor for the button. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
* .value[0].f32: maximum font scale factor. The default unit is fp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: maximum font scale factor. The default unit is fp.| -| NODE_PROGRESS_VALUE | Defines the current value of the progress indicator. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: current value of the progress indicator.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: current value of the progress indicator.| -| NODE_PROGRESS_TOTAL | Defines the total value of the progress indicator. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: total value of the progress indicator.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: total value of the progress indicator.| -| NODE_PROGRESS_COLOR | Defines the color for the progress value on the progress indicator. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: color value, in 0xARGB format. For example, 0xFFFF0000 indicates red.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color value, in 0xARGB format.| -| NODE_PROGRESS_TYPE | Defines the type of the progress indicator. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: progress bar type. The enumerated value is [ArkUI_ProgressType](#arkui_progresstype). The default value is ARKUI_PROGRESS_TYPE_LINEAR.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: progress bar type enumeration value [ArkUI_ProgressType](#arkui_progresstype).| -| NODE_CHECKBOX_SELECT | Defines whether the check box is selected. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether the check box is selected. The value **1** means that the check box is selected, and **0** means the opposite.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether the check box is selected. The value **1** means that the check box is selected, and **0** means the opposite.| -| NODE_CHECKBOX_SELECT_COLOR | Defines the color of the check box when it is selected. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color of the check box when it is selected, in 0xARGB format, for example, **0xFF1122FF**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color of the check box when it is selected, in 0xARGB format, for example, **0xFF1122FF**.| -| NODE_CHECKBOX_UNSELECT_COLOR | Defines the border color of the check box when it is not selected. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: border color, in 0xARGB format, for example, **0xFF1122FF**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: border color, in 0xARGB format, for example, **0xFF1122FF**.| -| NODE_CHECKBOX_MARK | Defines the internal icon style of the check box. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: border color, in 0xARGB format, for example, **0xFF1122FF**.
.value[1]?.f32: size of the internal mark, in vp. Optional.
.value[2]?.f32: stroke width of the internal mark, in vp. Optional. The default value is **2**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: border color, in 0xARGB format, for example, **0xFF1122FF**.
.value[1].f32: size of the internal mark, in vp.
.value[2].f32: stroke width of the internal mark, in vp. The default value is **2**.| -| NODE_CHECKBOX_SHAPE | Defines the shape of the check box. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: component shape. The parameter type is [ArkUI_CheckboxShape](#arkui_checkboxshape).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: component shape. The parameter type is [ArkUI_CheckboxShape](#arkui_checkboxshape).| +| NODE_PROGRESS_VALUE | Defines the current value of the progress indicator. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: current value of the progress indicator.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: current value of the progress indicator.| +| NODE_PROGRESS_TOTAL | Defines the total value of the progress indicator. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: total value of the progress indicator.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: total value of the progress indicator.| +| NODE_PROGRESS_COLOR | Defines the color for the progress value on the progress indicator. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: color value, in 0xARGB format. For example, 0xFFFF0000 indicates red.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color value, in 0xARGB format.| +| NODE_PROGRESS_TYPE | Defines the type of the progress indicator. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: progress bar type. The enumerated value is [ArkUI_ProgressType](#arkui_progresstype). The default value is ARKUI_PROGRESS_TYPE_LINEAR.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: progress bar type enumeration value [ArkUI_ProgressType](#arkui_progresstype).| +| NODE_PROGRESS_LINEAR_STYLE | Defines the linear progress indicator style. This attribute can be set, reset, and obtained as required through APIs. Note that the settings are effective only if the progress indicator type is linear.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.object: [ArkUI_ProgressLinearStyleOption](#arkui_progresslinearstyleoption) object that defines the linear progress indicator style.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: [ArkUI_ProgressLinearStyleOption](#arkui_progresslinearstyleoption) object that defines the linear progress indicator style.| +| NODE_CHECKBOX_SELECT | Defines whether the check box is selected. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether the check box is selected. The value **1** means that the check box is selected, and **0** means the opposite.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether the check box is selected. The value **1** means that the check box is selected, and **0** means the opposite.| +| NODE_CHECKBOX_SELECT_COLOR | Defines the color of the check box when it is selected. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color of the check box when it is selected, in 0xARGB format, for example, **0xFF1122FF**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color of the check box when it is selected, in 0xARGB format, for example, **0xFF1122FF**.| +| NODE_CHECKBOX_UNSELECT_COLOR | Defines the border color of the check box when it is not selected. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: border color, in 0xARGB format, for example, **0xFF1122FF**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: border color, in 0xARGB format, for example, **0xFF1122FF**.| +| NODE_CHECKBOX_MARK | Defines the internal icon style of the check box. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: border color, in 0xARGB format, for example, **0xFF1122FF**.
.value[1]?.f32: size of the internal mark, in vp. Optional.
.value[2]?.f32: stroke width of the internal mark, in vp. Optional. The default value is **2**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: border color, in 0xARGB format, for example, **0xFF1122FF**.
.value[1].f32: size of the internal mark, in vp.
.value[2].f32: stroke width of the internal mark, in vp. The default value is **2**.| +| NODE_CHECKBOX_SHAPE | Defines the shape of the check box. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: component shape. The parameter type is [ArkUI_CheckboxShape](#arkui_checkboxshape).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: component shape. The parameter type is [ArkUI_CheckboxShape](#arkui_checkboxshape).| | NODE_CHECKBOX_NAME | Sets the name of the check box. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: name of the check box.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: name of the check box.| | NODE_CHECKBOX_GROUP | Sets the name of the check box group to which the check box belongs. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: name of the check box group.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: name of the check box group.| -| NODE_XCOMPONENT_ID | Defines the ID of the **XComponent** component. This attribute can be set and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: component ID.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: component ID.| -| NODE_XCOMPONENT_TYPE | Defines the type of the **XComponent** component. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: type. The parameter type is [ArkUI_XComponentType](#arkui_xcomponenttype). The default value is **ARKUI_XCOMPONENT_TYPE_SURFACE**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: type. The parameter type is [ArkUI_XComponentType](#arkui_xcomponenttype).| -| NODE_XCOMPONENT_SURFACE_SIZE | Defines the width and height of the **XComponent** component. This attribute can be set and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: width, in px.
.value[1].u32: height, in px.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: width, in px.
.value[1].u32: height, in px. | -| NODE_DATE_PICKER_LUNAR | Defines whether to display the lunar calendar in the date picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to display the lunar calendar in the date picker. The default value is **false**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to display the lunar calendar in the date picker.| -| NODE_DATE_PICKER_START | Defines the start date of the date picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: date. The default value is **"1970-1-1"**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: date.| -| NODE_DATE_PICKER_END | Defines the end date of the date picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: date. The default value is **"2100-12-31"**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: date.| -| NODE_DATE_PICKER_SELECTED | Defines the selected date of the date picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: date. The default value is **"2024-01-22"**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: date.| -| NODE_DATE_PICKER_DISAPPEAR_TEXT_STYLE | Defines the font color, font size, and font weight for the top and bottom items in the date picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: array of five parameters of the string type, separated by semicolons (;).
Parameter 1: font color, in ::argb format.
Parameter 2: font size, in fp. The value is a number.
Parameter 3: font weight. Available options are ("bold", "normal", "bolder", "lighter", "medium", "regular").
Parameter 4: fonts, separated by commas (,).
Parameter 5: font style. Available options are ("normal", "italic").
Example: **"\#ff182431;14;normal;Arial,HarmonyOS Sans;normal"**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: array of five parameters of the string type, separated by semicolons (;).
Parameter 1: font color, in ::argb format.
Parameter 2: font size, in fp. The value is a number.
Parameter 3: font weight. Available options are ("bold", "normal", "bolder", "lighter", "medium", "regular").
Parameter 4: fonts, separated by commas (,).
Parameter 5: font style. Available options are ("normal", "italic").
Example: **"\#ff182431;14;normal;Arial,HarmonyOS Sans;normal"**.| -| NODE_DATE_PICKER_TEXT_STYLE | Defines the font color, font size, and font weight of all items except the top, bottom, and selected items in the date picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: array of five parameters of the string type, separated by semicolons (;).
Parameter 1: font color, in ::argb format.
Parameter 2: font size, in fp. The value is a number.
Parameter 3: font weight. Available options are ("bold", "normal", "bolder", "lighter", "medium", "regular").
Parameter 4: fonts, separated by commas (,).
Parameter 5: font style. Available options are ("normal", "italic").
Example: **"\#ff182431;14;normal;Arial,HarmonyOS Sans;normal"**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: array of five parameters of the string type, separated by semicolons (;).
Parameter 1: font color, in ::argb format.
Parameter 2: font size, in fp. The value is a number.
Parameter 3: font weight. Available options are ("bold", "normal", "bolder", "lighter", "medium", "regular").
Parameter 4: fonts, separated by commas (,).
Parameter 5: font style. Available options are ("normal", "italic").
Example: **"\#ff182431;14;normal;Arial,HarmonyOS Sans;normal"**.| -| NODE_DATE_PICKER_SELECTED_TEXT_STYLE | Defines the font color, font size, and font weight of the selected item in the date picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: array of five parameters of the string type, separated by semicolons (;).
Parameter 1: font color, in ::argb format.
Parameter 2: font size, in fp. The value is a number.
Parameter 3: font weight. Available options are ("bold", "normal", "bolder", "lighter", "medium", "regular").
Parameter 4: fonts, separated by commas (,).
Parameter 5: font style. Available options are ("normal", "italic").
Example: **"\#ff182431;14;normal;Arial,HarmonyOS Sans;normal"**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: array of five parameters of the string type, separated by semicolons (;).
Parameter 1: font color, in ::argb format.
Parameter 2: font size, in fp. The value is a number.
Parameter 3: font weight. Available options are ("bold", "normal", "bolder", "lighter", "medium", "regular").
Parameter 4: fonts, separated by commas (,).
Parameter 5: font style. Available options are ("normal", "italic").
Example: **"\#ff182431;14;normal;Arial,HarmonyOS Sans;normal"**.| +| NODE_XCOMPONENT_ID | Defines the ID of the **XComponent** component. This attribute can be set and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: component ID.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: component ID.| +| NODE_XCOMPONENT_TYPE | Defines the type of the **XComponent** component. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: type. The parameter type is [ArkUI_XComponentType](#arkui_xcomponenttype). The default value is **ARKUI_XCOMPONENT_TYPE_SURFACE**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: type. The parameter type is [ArkUI_XComponentType](#arkui_xcomponenttype).| +| NODE_XCOMPONENT_SURFACE_SIZE | Defines the width and height of the **XComponent** component. This attribute can be set and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: width, in px.
.value[1].u32: height, in px.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: width, in px.
.value[1].u32: height, in px. | +| NODE_XCOMPONENT_SURFACE_RECT | Sets the rectangle for the surface held by the **XComponent**. This API works only when type of the **XComponent** is set to **SURFACE("surface")** or **TEXTURE**.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: X coordinate of the surface display area relative to the upper left corner of the **XComponent** component, in px.
.value[1].i32: Y coordinate of the surface display area relative to the upper left corner of the **XComponent** component, in px.
.value[2].i32: width of the surface display area, in px.
.value[3].i32: height of the surface display area, in px.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: X coordinate of the surface display area relative to the upper left corner of the **XComponent** component, in px.
.value[1].i32: Y coordinate of the surface display area relative to the upper left corner of the **XComponent** component, in px.
.value[2].i32: width of the surface display area, in px.
.value[3].i32: height of the surface display area, in px.| +| NODE_XCOMPONENT_ENABLE_ANALYZER | Sets whether to enable the AI analyzer, which supports subject recognition, text recognition, and object lookup. For the settings to take effect, this API must be used together with **StartImageAnalyzer** and StopImageAnalyzer of **XComponentController**. This feature cannot be used together with the **overlay** attribute. If both are set, the **CustomBuilder** property in **overlay** has no effect. This feature also depends on device capabilities.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to enable the AI image analyzer.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to enable the AI image analyzer. +| NODE_DATE_PICKER_LUNAR | Defines whether to display the lunar calendar in the date picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to display the lunar calendar in the date picker. The default value is **false**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to display the lunar calendar in the date picker.| +| NODE_DATE_PICKER_START | Defines the start date of the date picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: date. The default value is **"1970-1-1"**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: date.| +| NODE_DATE_PICKER_END | Defines the end date of the date picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: date. The default value is **"2100-12-31"**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: date.| +| NODE_DATE_PICKER_SELECTED | Defines the selected date of the date picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: date. The default value is **"2024-01-22"**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: date.| +| NODE_DATE_PICKER_DISAPPEAR_TEXT_STYLE | Defines the font color, font size, and font weight for the top and bottom items in the date picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: array of five parameters of the string type, separated by semicolons (;).
Parameter 1: font color, in ::argb format.
Parameter 2: font size, in fp. The value is a number.
Parameter 3: font weight. Available options are ("bold", "normal", "bolder", "lighter", "medium", "regular").
Parameter 4: fonts, separated by commas (,).
Parameter 5: font style. Available options are ("normal", "italic").
Example: **"\#ff182431;14;normal;Arial,HarmonyOS Sans;normal"**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: array of five parameters of the string type, separated by semicolons (;).
Parameter 1: font color, in ::argb format.
Parameter 2: font size, in fp. The value is a number.
Parameter 3: font weight. Available options are ("bold", "normal", "bolder", "lighter", "medium", "regular").
Parameter 4: fonts, separated by commas (,).
Parameter 5: font style. Available options are ("normal", "italic").
Example: **"\#ff182431;14;normal;Arial,HarmonyOS Sans;normal"**.| +| NODE_DATE_PICKER_TEXT_STYLE | Defines the font color, font size, and font weight of all items except the top, bottom, and selected items in the date picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: array of five parameters of the string type, separated by semicolons (;).
Parameter 1: font color, in ::argb format.
Parameter 2: font size, in fp. The value is a number.
Parameter 3: font weight. Available options are ("bold", "normal", "bolder", "lighter", "medium", "regular").
Parameter 4: fonts, separated by commas (,).
Parameter 5: font style. Available options are ("normal", "italic").
Example: **"\#ff182431;14;normal;Arial,HarmonyOS Sans;normal"**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: array of five parameters of the string type, separated by semicolons (;).
Parameter 1: font color, in ::argb format.
Parameter 2: font size, in fp. The value is a number.
Parameter 3: font weight. Available options are ("bold", "normal", "bolder", "lighter", "medium", "regular").
Parameter 4: fonts, separated by commas (,).
Parameter 5: font style. Available options are ("normal", "italic").
Example: **"\#ff182431;14;normal;Arial,HarmonyOS Sans;normal"**.| +| NODE_DATE_PICKER_SELECTED_TEXT_STYLE | Defines the font color, font size, and font weight of the selected item in the date picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: array of five parameters of the string type, separated by semicolons (;).
Parameter 1: font color, in ::argb format.
Parameter 2: font size, in fp. The value is a number.
Parameter 3: font weight. Available options are ("bold", "normal", "bolder", "lighter", "medium", "regular").
Parameter 4: fonts, separated by commas (,).
Parameter 5: font style. Available options are ("normal", "italic").
Example: **"\#ff182431;14;normal;Arial,HarmonyOS Sans;normal"**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: array of five parameters of the string type, separated by semicolons (;).
Parameter 1: font color, in ::argb format.
Parameter 2: font size, in fp. The value is a number.
Parameter 3: font weight. Available options are ("bold", "normal", "bolder", "lighter", "medium", "regular").
Parameter 4: fonts, separated by commas (,).
Parameter 5: font style. Available options are ("normal", "italic").
Example: **"\#ff182431;14;normal;Arial,HarmonyOS Sans;normal"**.| | NODE_DATE_PICKER_MODE | Sets the date columns to be displayed. This attribute can be set, reset, and obtained as required through APIs. **DatePicker** displays different styles of date columns.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: type of date column to be displayed. The parameter type is [ArkUI_DatePickerMode](#arkui_datepickermode).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: type of date column to be displayed. The parameter type is [ArkUI_DatePickerMode](#arkui_datepickermode).| | NODE_DATE_PICKER_ENABLE_HAPTIC_FEEDBACK | Specifies whether to enable haptic feedback. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to enable haptic feedback. The default value is **true**. The value **true** means to enable haptic feedback, and **false** means the opposite.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to enable haptic feedback. -| NODE_TIME_PICKER_SELECTED | Defines the time of the selected item. in the timer picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: time. The default value is the current system time.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: time.| -| NODE_TIME_PICKER_USE_MILITARY_TIME | Defines whether the display time is in 24-hour format. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether the display time is in 24-hour format. The default value is **false**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether the display time is in 24-hour format.| -| NODE_TIME_PICKER_DISAPPEAR_TEXT_STYLE | Defines the font color, font size, and font weight for the top and bottom items in the time picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: array of five parameters of the string type, separated by semicolons (;).
Parameter 1: font color, in ::argb format.
Parameter 2: font size, in fp. The value is a number.
Parameter 3: font weight. Available options are ("bold", "normal", "bolder", "lighter", "medium", "regular").
Parameter 4: fonts, separated by commas (,).
Parameter 5: font style. Available options are ("normal", "italic").
Example: **"\#ff182431;14;normal;Arial,HarmonyOS Sans;normal"**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: array of five parameters of the string type, separated by semicolons (;).
Parameter 1: font color, in ::argb format.
Parameter 2: font size, in fp. The value is a number.
Parameter 3: font weight. Available options are ("bold", "normal", "bolder", "lighter", "medium", "regular").
Parameter 4: fonts, separated by commas (,).
Parameter 5: font style. Available options are ("normal", "italic").
Example: **"\#ff182431;14;normal;Arial,HarmonyOS Sans;normal"**.| -| NODE_TIME_PICKER_TEXT_STYLE | Defines the font color, font size, and font weight of all items except the top, bottom, and selected items in the time picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: array of five parameters of the string type, separated by semicolons (;).
Parameter 1: font color, in ::argb format.
Parameter 2: font size, in fp. The value is a number.
Parameter 3: font weight. Available options are ("bold", "normal", "bolder", "lighter", "medium", "regular").
Parameter 4: fonts, separated by commas (,).
Parameter 5: font style. Available options are ("normal", "italic").
Example: **"\#ff182431;14;normal;Arial,HarmonyOS Sans;normal"**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: array of five parameters of the string type, separated by semicolons (;).
Parameter 1: font color, in ::argb format.
Parameter 2: font size, in fp. The value is a number.
Parameter 3: font weight. Available options are ("bold", "normal", "bolder", "lighter", "medium", "regular").
Parameter 4: fonts, separated by commas (,).
Parameter 5: font style. Available options are ("normal", "italic").
Example: **"\#ff182431;14;normal;Arial,HarmonyOS Sans;normal"**.| -| NODE_TIME_PICKER_SELECTED_TEXT_STYLE | Defines the font color, font size, and font weight of the selected item in the time picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: array of five parameters of the string type, separated by semicolons (;).
Parameter 1: font color, in ::argb format.
Parameter 2: font size, in fp. The value is a number.
Parameter 3: font weight. Available options are ("bold", "normal", "bolder", "lighter", "medium", "regular").
Parameter 4: fonts, separated by commas (,).
Parameter 5: font style. Available options are ("normal", "italic").
Example: **"\#ff182431;14;normal;Arial,HarmonyOS Sans;normal"**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: array of five parameters of the string type, separated by semicolons (;).
Parameter 1: font color, in ::argb format.
Parameter 2: font size, in fp. The value is a number.
Parameter 3: font weight. Available options are ("bold", "normal", "bolder", "lighter", "medium", "regular").
Parameter 4: fonts, separated by commas (,).
Parameter 5: font style. Available options are ("normal", "italic").
Example: **"\#ff182431;14;normal;Arial,HarmonyOS Sans;normal"**.| -| NODE_TIME_PICKER_START | Sets the start time for the timer picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: time. The default value is **"1970-01-01 00:00:00"**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: time. The default value is **"1970-01-01 00:00:00"**.| -| NODE_TIME_PICKER_END | Sets the end time for the timer picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: time. The default value is **"1970-01-01 23:59:59"**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: time. The default value is **"1970-01-01 23:59:59"**.| +| NODE_TIME_PICKER_SELECTED | Defines the time of the selected item. in the timer picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: time. The default value is the current system time.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: time.| +| NODE_TIME_PICKER_USE_MILITARY_TIME | Defines whether the display time is in 24-hour format. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether the display time is in 24-hour format. The default value is **false**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether the display time is in 24-hour format.| +| NODE_TIME_PICKER_DISAPPEAR_TEXT_STYLE | Defines the font color, font size, and font weight for the top and bottom items in the time picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: array of five parameters of the string type, separated by semicolons (;).
Parameter 1: font color, in ::argb format.
Parameter 2: font size, in fp. The value is a number.
Parameter 3: font weight. Available options are ("bold", "normal", "bolder", "lighter", "medium", "regular").
Parameter 4: fonts, separated by commas (,).
Parameter 5: font style. Available options are ("normal", "italic").
Example: **"\#ff182431;14;normal;Arial,HarmonyOS Sans;normal"**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: array of five parameters of the string type, separated by semicolons (;).
Parameter 1: font color, in ::argb format.
Parameter 2: font size, in fp. The value is a number.
Parameter 3: font weight. Available options are ("bold", "normal", "bolder", "lighter", "medium", "regular").
Parameter 4: fonts, separated by commas (,).
Parameter 5: font style. Available options are ("normal", "italic").
Example: **"\#ff182431;14;normal;Arial,HarmonyOS Sans;normal"**.| +| NODE_TIME_PICKER_TEXT_STYLE | Defines the font color, font size, and font weight of all items except the top, bottom, and selected items in the time picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: array of five parameters of the string type, separated by semicolons (;).
Parameter 1: font color, in ::argb format.
Parameter 2: font size, in fp. The value is a number.
Parameter 3: font weight. Available options are ("bold", "normal", "bolder", "lighter", "medium", "regular").
Parameter 4: fonts, separated by commas (,).
Parameter 5: font style. Available options are ("normal", "italic").
Example: **"\#ff182431;14;normal;Arial,HarmonyOS Sans;normal"**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: array of five parameters of the string type, separated by semicolons (;).
Parameter 1: font color, in ::argb format.
Parameter 2: font size, in fp. The value is a number.
Parameter 3: font weight. Available options are ("bold", "normal", "bolder", "lighter", "medium", "regular").
Parameter 4: fonts, separated by commas (,).
Parameter 5: font style. Available options are ("normal", "italic").
Example: **"\#ff182431;14;normal;Arial,HarmonyOS Sans;normal"**.| +| NODE_TIME_PICKER_SELECTED_TEXT_STYLE | Defines the font color, font size, and font weight of the selected item in the time picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: array of five parameters of the string type, separated by semicolons (;).
Parameter 1: font color, in ::argb format.
Parameter 2: font size, in fp. The value is a number.
Parameter 3: font weight. Available options are ("bold", "normal", "bolder", "lighter", "medium", "regular").
Parameter 4: fonts, separated by commas (,).
Parameter 5: font style. Available options are ("normal", "italic").
Example: **"\#ff182431;14;normal;Arial,HarmonyOS Sans;normal"**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: array of five parameters of the string type, separated by semicolons (;).
Parameter 1: font color, in ::argb format.
Parameter 2: font size, in fp. The value is a number.
Parameter 3: font weight. Available options are ("bold", "normal", "bolder", "lighter", "medium", "regular").
Parameter 4: fonts, separated by commas (,).
Parameter 5: font style. Available options are ("normal", "italic").
Example: **"\#ff182431;14;normal;Arial,HarmonyOS Sans;normal"**.| +| NODE_TIME_PICKER_START | Sets the start time for the timer picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: time. The default value is **"1970-01-01 00:00:00"**. Only the hour and minute parts of the time are effective.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: time. The default value is **"1970-01-01 00:00:00"**.| +| NODE_TIME_PICKER_END | Sets the end time for the timer picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: time. The default value is **"1970-01-01 23:59:59"**. Only the hour and minute parts of the time are effective.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: time. The default value is **"1970-01-01 23:59:59"**.| | NODE_TIME_PICKER_ENABLE_CASCADE | Sets whether the AM/PM indicator automatically switches based on the hour in 12-hour format.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether the AM/PM indicator automatically switches based on the hour in 12-hour format. The default value is **false**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether the AM/PM indicator automatically switches based on the hour in 12-hour format.| -| NODE_TEXT_PICKER_OPTION_RANGE | Defines the data selection range of the text picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: type of the used selector [ArkUI_TextPickerRangeType](#arkui_textpickerrangetype). The default value is ARKUI_TEXTPICKER_RANGETYPE_SINGLE.
?.string: string input, whose format varies by picker type.
1: single-column picker. The input format is a group of strings separated by semicolons (;).
2: multi-column picker. Multiple pairs of plain text strings are supported. The pairs are separated by semicolons (;), and strings within each pair are separated by commas (,).
?.object: Object input, whose format varies by picker type.
1: A single column supports the image selector. The input structure is [ARKUI_TextPickerRangeContent](_a_r_k_u_i___text_picker_range_content.md).
2: multi-column linkage selector. The input structure is [ARKUI_TextPickerCascadeRangeContent](_a_r_k_u_i___text_picker_cascade_range_content.md).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: type of the text picker [ArkUI_TextPickerRangeType](#arkui_textpickerrangetype).
?.string: string output, whose format varies by picker type.
1: single-column picker. The output format is a group of strings separated by semicolons (;).
2: multi-column picker. Multiple pairs of plain text strings are supported. The pairs are separated by semicolons (;), and strings within each pair are separated by commas (,).
?.string: Object output, whose format varies by picker type.
1: A single column supports the image selector. The output structure is [ARKUI_TextPickerRangeContent](_a_r_k_u_i___text_picker_range_content.md).
2: multi-column linkage selector. The output structure is [ARKUI_TextPickerCascadeRangeContent](_a_r_k_u_i___text_picker_cascade_range_content.md).| -| NODE_TEXT_PICKER_OPTION_SELECTED | Defines the index of the default selected item in the data selection range of the text picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: index. If there are multiple index values, add them one by one.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: index. If there are multiple index values, add them one by one.| -| NODE_TEXT_PICKER_OPTION_VALUE | Defines the value of the default selected item in the text picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: value of the selected item. If there are multiple values, add them one by one and separate them with semicolons (;).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: value of the selected item. If there are multiple values, add them one by one and separate them with semicolons (;).| -| NODE_TEXT_PICKER_DISAPPEAR_TEXT_STYLE | Defines the font color, font size, and font weight for the top and bottom items in the text picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: array of five parameters of the string type, separated by semicolons (;).
Parameter 1: font color, in ::argb format.
Parameter 2: font size, in fp. The value is a number.
Parameter 3: font weight. Available options are ("bold", "normal", "bolder", "lighter", "medium", "regular").
Parameter 4: fonts, separated by commas (,).
Parameter 5: font style. Available options are ("normal", "italic").
Example: **"\#ff182431;14;normal;Arial,HarmonyOS Sans;normal"**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: array of five parameters of the string type, separated by semicolons (;).
Parameter 1: font color, in ::argb format.
Parameter 2: font size, in fp. The value is a number.
Parameter 3: font weight. Available options are ("bold", "normal", "bolder", "lighter", "medium", "regular").
Parameter 4: fonts, separated by commas (,).
Parameter 5: font style. Available options are ("normal", "italic").
Example: **"\#ff182431;14;normal;Arial,HarmonyOS Sans;normal"**.| -| NODE_TEXT_PICKER_TEXT_STYLE | Defines the font color, font size, and font weight for all items except the top, bottom, and selected items in the text picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: array of five parameters of the string type, separated by semicolons (;).
Parameter 1: font color, in ::argb format.
Parameter 2: font size, in fp. The value is a number.
Parameter 3: font weight. Available options are ("bold", "normal", "bolder", "lighter", "medium", "regular").
Parameter 4: fonts, separated by commas (,).
Parameter 5: font style. Available options are ("normal", "italic").
Example: **"\#ff182431;14;normal;Arial,HarmonyOS Sans;normal"**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: array of five parameters of the string type, separated by semicolons (;).
Parameter 1: font color, in ::argb format.
Parameter 2: font size, in fp. The value is a number.
Parameter 3: font weight. Available options are ("bold", "normal", "bolder", "lighter", "medium", "regular").
Parameter 4: fonts, separated by commas (,).
Parameter 5: font style. Available options are ("normal", "italic").
Example: **"\#ff182431;14;normal;Arial,HarmonyOS Sans;normal"**.| -| NODE_TEXT_PICKER_SELECTED_TEXT_STYLE | Defines the font color, font size, and font weight of the selected item in the text picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: array of five parameters of the string type, separated by semicolons (;).
Input parameter 1: text color. The value is of the argb type.
Input parameter 2: text size, in fp. The value is a number.
Parameter 3: font weight. Available options are ("bold", "normal", "bolder", "lighter", "medium", "regular").
Parameter 4: fonts, separated by commas (,).
Parameter 5: font style. Available options are ("normal", "italic").
Example: **"\#ff182431;14;normal;Arial,HarmonyOS Sans;normal"**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: array of five parameters of the string type, separated by semicolons (;).
Parameter 1: text color. The value is of the argb type.
Parameter 2: text size. The value is a number, and the unit is fp.
Parameter 3: font weight. Available options are ("bold", "normal", "bolder", "lighter", "medium", "regular").
Parameter 4: text font list, which is separated by commas (,).
Parameter 5: text style, string enumeration ("normal", "italic")
Example: **"\#ff182431;14;normal;Arial,HarmonyOS Sans;normal"**.| -| NODE_TEXT_PICKER_SELECTED_INDEX | Defines the index of the default selected item in the data selection range of the text picker. This attribute can be set, reset, and obtained as required through APIs.
[ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter type. The options are as follows:
.value[0...].i32: index of the default item in the data selection range.| -| NODE_TEXT_PICKER_CAN_LOOP | Defines whether to support scroll looping for the text picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to support scroll looping. The value **true** means to support scroll looping, and **false** means the opposite.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
value[0].i32: The value **1** means to support scroll looping, and **0** means the opposite.| -| NODE_TEXT_PICKER_DEFAULT_PICKER_ITEM_HEIGHT | Defines the height of each item in the picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
value[0].f32: item height, in vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
value[0].f32: item height, in vp.| +| NODE_TEXT_PICKER_OPTION_RANGE | Defines the data selection range of the text picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: type of the used selector [ArkUI_TextPickerRangeType](#arkui_textpickerrangetype). The default value is ARKUI_TEXTPICKER_RANGETYPE_SINGLE.
?.string: string input, whose format varies by picker type.
1: single-column picker. The input format is a group of strings separated by semicolons (;).
2: multi-column picker. Multiple pairs of plain text strings are supported. The pairs are separated by semicolons (;), and strings within each pair are separated by commas (,).
?.object: Object input, whose format varies by picker type.
1: A single column supports the image selector. The input structure is [ARKUI_TextPickerRangeContent](_a_r_k_u_i___text_picker_range_content.md).
2: multi-column linkage selector. The input structure is [ARKUI_TextPickerCascadeRangeContent](_a_r_k_u_i___text_picker_cascade_range_content.md).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: type of the text picker [ArkUI_TextPickerRangeType](#arkui_textpickerrangetype).
?.string: string output, whose format varies by picker type.
1: single-column picker. The output format is a group of strings separated by semicolons (;).
2: multi-column picker. Multiple pairs of plain text strings are supported. The pairs are separated by semicolons (;), and strings within each pair are separated by commas (,).
?.string: Object output, whose format varies by picker type.
1: A single column supports the image selector. The output structure is [ARKUI_TextPickerRangeContent](_a_r_k_u_i___text_picker_range_content.md).
2: multi-column linkage selector. The output structure is [ARKUI_TextPickerCascadeRangeContent](_a_r_k_u_i___text_picker_cascade_range_content.md).| +| NODE_TEXT_PICKER_OPTION_SELECTED | Defines the index of the default selected item in the data selection range of the text picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: index. If there are multiple index values, add them one by one.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: index. If there are multiple index values, add them one by one.| +| NODE_TEXT_PICKER_OPTION_VALUE | Defines the value of the default selected item in the text picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: value of the selected item. If there are multiple values, add them one by one and separate them with semicolons (;).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: value of the selected item. If there are multiple values, add them one by one and separate them with semicolons (;).| +| NODE_TEXT_PICKER_DISAPPEAR_TEXT_STYLE | Defines the font color, font size, and font weight for the top and bottom items in the text picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: array of five parameters of the string type, separated by semicolons (;).
Parameter 1: font color, in ::argb format.
Parameter 2: font size, in fp. The value is a number.
Parameter 3: font weight. Available options are ("bold", "normal", "bolder", "lighter", "medium", "regular").
Parameter 4: fonts, separated by commas (,).
Parameter 5: font style. Available options are ("normal", "italic").
Example: **"\#ff182431;14;normal;Arial,HarmonyOS Sans;normal"**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: array of five parameters of the string type, separated by semicolons (;).
Parameter 1: font color, in ::argb format.
Parameter 2: font size, in fp. The value is a number.
Parameter 3: font weight. Available options are ("bold", "normal", "bolder", "lighter", "medium", "regular").
Parameter 4: fonts, separated by commas (,).
Parameter 5: font style. Available options are ("normal", "italic").
Example: **"\#ff182431;14;normal;Arial,HarmonyOS Sans;normal"**.| +| NODE_TEXT_PICKER_TEXT_STYLE | Defines the font color, font size, and font weight for all items except the top, bottom, and selected items in the text picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: array of five parameters of the string type, separated by semicolons (;).
Parameter 1: font color, in ::argb format.
Parameter 2: font size, in fp. The value is a number.
Parameter 3: font weight. Available options are ("bold", "normal", "bolder", "lighter", "medium", "regular").
Parameter 4: fonts, separated by commas (,).
Parameter 5: font style. Available options are ("normal", "italic").
Example: **"\#ff182431;14;normal;Arial,HarmonyOS Sans;normal"**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: array of five parameters of the string type, separated by semicolons (;).
Parameter 1: font color, in ::argb format.
Parameter 2: font size, in fp. The value is a number.
Parameter 3: font weight. Available options are ("bold", "normal", "bolder", "lighter", "medium", "regular").
Parameter 4: fonts, separated by commas (,).
Parameter 5: font style. Available options are ("normal", "italic").
Example: **"\#ff182431;14;normal;Arial,HarmonyOS Sans;normal"**.| +| NODE_TEXT_PICKER_SELECTED_TEXT_STYLE | Defines the font color, font size, and font weight of the selected item in the text picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: array of five parameters of the string type, separated by semicolons (;).
Input parameter 1: text color. The value is of the argb type.
Input parameter 2: text size, in fp. The value is a number.
Parameter 3: font weight. Available options are ("bold", "normal", "bolder", "lighter", "medium", "regular").
Parameter 4: fonts, separated by commas (,).
Parameter 5: font style. Available options are ("normal", "italic").
Example: **"\#ff182431;14;normal;Arial,HarmonyOS Sans;normal"**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: array of five parameters of the string type, separated by semicolons (;).
Parameter 1: text color. The value is of the argb type.
Parameter 2: text size. The value is a number, and the unit is fp.
Parameter 3: font weight. Available options are ("bold", "normal", "bolder", "lighter", "medium", "regular").
Parameter 4: text font list, which is separated by commas (,).
Parameter 5: text style, string enumeration ("normal", "italic")
Example: **"\#ff182431;14;normal;Arial,HarmonyOS Sans;normal"**.| +| NODE_TEXT_PICKER_SELECTED_INDEX | Defines the index of the default selected item in the data selection range of the text picker. This attribute can be set, reset, and obtained as required through APIs.
[ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter type. The options are as follows:
.value[0...].i32: index of the default item in the data selection range.| +| NODE_TEXT_PICKER_CAN_LOOP | Defines whether to support scroll looping for the text picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to support scroll looping. The value **true** means to support scroll looping, and **false** means the opposite.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
value[0].i32: The value **1** means to support scroll looping, and **0** means the opposite.| +| NODE_TEXT_PICKER_DEFAULT_PICKER_ITEM_HEIGHT | Defines the height of each item in the picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
value[0].f32: item height, in vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
value[0].f32: item height, in vp.| | NODE_TEXT_PICKER_ENABLE_HAPTIC_FEEDBACK | Specifies whether to enable haptic feedback. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to enable haptic feedback. The value **true** means to enable haptic feedback, and **false** means the opposite. The default value is **true**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to enable haptic feedback.| -| NODE_CALENDAR_PICKER_HINT_RADIUS | Defines the style of the background in the selected state of the calendar picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: radius of the rounded corner of the bottom plate when the calendar is selected. The value range is [0, +∞). The value 0 indicates that the bottom plate style is a right-angle rectangle. The value range is (0, 16), indicating that the bottom plate style is a rounded rectangle. If the value range is [16, +∞), the bottom plate style is round.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: radius of the rounded corner of the bottom plate when the calendar is selected. The value range is [0, +∞). The value 0 indicates that the bottom plate style is a right-angle rectangle. The value range is (0, 16), indicating that the bottom plate style is a rounded rectangle. If the value range is [16, +∞), the bottom plate style is round.| -| NODE_CALENDAR_PICKER_SELECTED_DATE | Defines the date of the selected item in the calendar picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: year of the selected date.
.value[1].u32: month of the selected date.
.value[2].u32: day of the selected date.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: year of the selected date.
.value[1].u32: month of the selected date.
.value[2].u32: day of the selected date.| -| NODE_CALENDAR_PICKER_EDGE_ALIGNMENT | Defines how the calendar picker is aligned with the entry component. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: alignment mode type. The parameter type is [ArkUI_CalendarAlignment](#arkui_calendaralignment).
.value[1].f32: offset of the picker relative to the entry component along the x-axis after alignment based on the specified alignment mode.
.value[2].f32: offset of the picker relative to the entry component along the y-axis after alignment based on the specified alignment mode.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: alignment mode type. The parameter type is [ArkUI_CalendarAlignment](#arkui_calendaralignment).
.value[1].f32: offset of the picker relative to the entry component along the x-axis after alignment based on the specified alignment mode.
.value[2].f32: offset of the picker relative to the entry component along the y-axis after alignment based on the specified alignment mode.| -| NODE_CALENDAR_PICKER_TEXT_STYLE | Defines the font color, font size, and font weight in the entry area of the calendar picker.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0]?.u32: font color of the entry area.
.value[1]?.f32: font size of the entry area, in fp.
.value[2]?.i32: font weight of the text in the entry area. The parameter type is [ArkUI_FontWeight](#arkui_fontweight).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: font color of the entry area.
.value[1].f32: font size of the entry area, in fp.
.value[2].i32: font weight of the text in the entry area. The parameter type is [ArkUI_FontWeight](#arkui_fontweight).| +| NODE_CALENDAR_PICKER_HINT_RADIUS | Defines the style of the background in the selected state of the calendar picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: radius of the rounded corner of the bottom plate when the calendar is selected. The value range is [0, +∞). The value 0 indicates that the bottom plate style is a right-angle rectangle. The value range is (0, 16), indicating that the bottom plate style is a rounded rectangle. If the value range is [16, +∞), the bottom plate style is round.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: radius of the rounded corner of the bottom plate when the calendar is selected. The value range is [0, +∞). The value 0 indicates that the bottom plate style is a right-angle rectangle. The value range is (0, 16), indicating that the bottom plate style is a rounded rectangle. If the value range is [16, +∞), the bottom plate style is round.| +| NODE_CALENDAR_PICKER_SELECTED_DATE | Defines the date of the selected item in the calendar picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: year of the selected date.
.value[1].u32: month of the selected date.
.value[2].u32: day of the selected date.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: year of the selected date.
.value[1].u32: month of the selected date.
.value[2].u32: day of the selected date.| +| NODE_CALENDAR_PICKER_EDGE_ALIGNMENT | Defines how the calendar picker is aligned with the entry component. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: alignment mode type. The parameter type is [ArkUI_CalendarAlignment](#arkui_calendaralignment).
.value[1].f32: offset of the picker relative to the entry component along the x-axis after alignment based on the specified alignment mode.
.value[2].f32: offset of the picker relative to the entry component along the y-axis after alignment based on the specified alignment mode.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: alignment mode type. The parameter type is [ArkUI_CalendarAlignment](#arkui_calendaralignment).
.value[1].f32: offset of the picker relative to the entry component along the x-axis after alignment based on the specified alignment mode.
.value[2].f32: offset of the picker relative to the entry component along the y-axis after alignment based on the specified alignment mode.| +| NODE_CALENDAR_PICKER_TEXT_STYLE | Defines the font color, font size, and font weight in the entry area of the calendar picker.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0]?.u32: font color of the entry area.
.value[1]?.f32: font size of the entry area, in fp.
.value[2]?.i32: font weight of the text in the entry area. The parameter type is [ArkUI_FontWeight](#arkui_fontweight).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: font color of the entry area.
.value[1].f32: font size of the entry area, in fp.
.value[2].i32: font weight of the text in the entry area. The parameter type is [ArkUI_FontWeight](#arkui_fontweight).| | NODE_CALENDAR_PICKER_START16+ | Sets the start date for the calendar picker.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: year.
.value[1].u32: month.
.value[2].u32: day.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: year.
.value[1].u32: month.
.value[2].u32: day. | NODE_CALENDAR_PICKER_END16+ | Sets the end date for the calendar picker.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: year.
.value[1].u32: month.
.value[2].u32: day.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: year.
.value[1].u32: month.
.value[2].u32: day. -| NODE_SLIDER_BLOCK_COLOR | Defines the color of the slider. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color of the slider, in 0xARGB format, for example, **0xFF1122FF**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color of the slider, in 0xARGB format, for example, **0xFF1122FF**.| -| NODE_SLIDER_TRACK_COLOR | Defines the background color of the slider. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: background color, in 0xARGB format, for example, **0xFF1122FF**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: background color, in 0xARGB format, for example, **0xFF1122FF**.| -| NODE_SLIDER_SELECTED_COLOR | Defines the color of the selected part of the slider track. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color of the selected part of the slider track, in 0xARGB format, for example, **0xFF1122FF**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color of the selected part of the slider track, in 0xARGB format, for example, **0xFF1122FF**.| -| NODE_SLIDER_SHOW_STEPS | Sets whether to display the step scale value. Attributes can be set, reset, and obtained.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to display the stepping value. The value **1** means to display the stepping value, and **0** (default value) means the opposite.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to display the stepping value. The value **1** means to display the stepping value, and **0** (default value) means the opposite.| -| NODE_SLIDER_BLOCK_STYLE | Defines the slider shape, which can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: shape. The parameter type is [ArkUI_SliderBlockStyle](#arkui_sliderblockstyle).
.string? depending on the shape. Optional.
ARKUI_SLIDER_BLOCK_STYLE_IMAGE: image resource of the slider. Example: /pages/common/icon.png.
ARKUI_SLIDER_BLOCK_STYLE_SHAPE: custom shape of the slider.
There are five types:
1. Rectangle:
.value[1].i32: cropping type. The parameter type is [ArkUI_ShapeType](#arkui_shapetype), ARKUI_SHAPE_TYPE_RECTANGLE.
.value[2].f32: height of the rectangle.
.value[3].f32: height of the rectangle.
.value[4].f32: height of the rounded corner of the rectangle.
.value[5].f32: height of the rounded corner of the rectangle.
2. Circle:
.value[1].i32: cropping type. The parameter type is [ArkUI_ShapeType](#arkui_shapetype), ARKUI_SHAPE_TYPE_CIRCLE.
.value[2].f32: height of the circle.
.value[3].f32: height of the circle.
3. Ellipse:
.value[1].i32: cropping type. The parameter type is [ArkUI_ShapeType](#arkui_shapetype), ARKUI_SHAPE_TYPE_ELLIPSE.
.value[2].f32: height of the ellipse.
.value[3].f32: height of the ellipse.
4. Path:
.value[1].i32: cropping type. The parameter type is [ArkUI_ShapeType](#arkui_shapetype), ARKUI_SHAPE_TYPE_PATH.
.value[2].f32: width of the path.
.value[3].f32: height of the path.
.string: command for drawing the path.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: shape. The parameter type is [ArkUI_SliderBlockStyle](#arkui_sliderblockstyle).
.string? depending on the shape. Optional.
ARKUI_SLIDER_BLOCK_STYLE_IMAGE: image resource of the slider. Example: /pages/common/icon.png.
ARKUI_SLIDER_BLOCK_STYLE_SHAPE: custom shape of the slider.
There are five types:
1. Rectangle:
.value[1].i32: cropping type. The parameter type is [ArkUI_ShapeType](#arkui_shapetype), ARKUI_SHAPE_TYPE_RECTANGLE.
.value[2].f32: height of the rectangle.
.value[3].f32: height of the rectangle.
.value[4].f32: height of the rounded corner of the rectangle.
.value[5].f32: height of the rounded corner of the rectangle.
2. Circle:
.value[1].i32: cropping type. The parameter type is [ArkUI_ShapeType](#arkui_shapetype), ARKUI_SHAPE_TYPE_CIRCLE.
.value[2].f32: height of the circle.
.value[3].f32: height of the circle.
3. Ellipse:
.value[1].i32: cropping type. The parameter type is [ArkUI_ShapeType](#arkui_shapetype), ARKUI_SHAPE_TYPE_ELLIPSE.
.value[2].f32: height of the ellipse.
.value[3].f32: height of the ellipse.
4. Path:
.value[1].i32: cropping type. The parameter type is [ArkUI_ShapeType](#arkui_shapetype), ARKUI_SHAPE_TYPE_PATH.
.value[2].f32: width of the path.
.value[3].f32: height of the path.
.string: command for drawing the path.| -| NODE_SLIDER_VALUE | Defines the current value of the slider. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: current value.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: current value.| -| NODE_SLIDER_MIN_VALUE | Defines the minimum value of the slider. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: minimum value.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: minimum value.| -| NODE_SLIDER_MAX_VALUE | Defines the maximum value of the slider. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: maximum value.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: maximum value.| -| NODE_SLIDER_STEP | Defines the step of the slider. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: step. The value range is [0.01, 100].
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: step. The value range is [0.01, 100].| -| NODE_SLIDER_DIRECTION | Defines whether the slider moves horizontally or vertically. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: display style. The parameter type is [ArkUI_SliderDirection](#arkui_sliderdirection).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: display style. The parameter type is [ArkUI_SliderDirection](#arkui_sliderdirection).| -| NODE_SLIDER_REVERSE | Defines whether the slider values are reversed. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether the slider values are reversed. The value **1** means that the slider values are reversed, and **0** means the opposite.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether the slider values are reversed. The value **1** means that the slider values are reversed, and **0** means the opposite.| -| NODE_SLIDER_STYLE | Defines the style of the slider thumb and track. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: display style. The parameter type is [ArkUI_SliderStyle](#arkui_sliderstyle).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: display style. The parameter type is [ArkUI_SliderStyle](#arkui_sliderstyle).| -| NODE_SLIDER_TRACK_THICKNESS | Sets the track thickness of the slider. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: track thickness of the slider, in vp. The default value is 4.0 vp when **NODE_SLIDER_STYLE** is set to **ARKUI_SLIDER_STYLE_OUT_SET** and 20.0 vp when **NODE_SLIDER_STYLE** is set to **ARKUI_SLIDER_STYLE_IN_SET**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: track thickness of the slider, in vp. | -| NODE_RADIO_CHECKED | Sets whether the radio button is selected. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether the radio button is selected. The default value is **false**. Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether the radio button is selected.| -| NODE_RADIO_STYLE | Sets the style of the radio button in selected or deselected state. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0]?.u32: color of the background when the radio button is selected, in 0xARGB format. The default value is **0xFF007DFF**.
.value[1]?.u32: color of the border when the radio button is deselected, in 0xARGB format. The default value is **0xFF182431**.
.value[2]?.u32: color of the indicator when the radio button is selected, in 0xARGB format. The default value is **0xFFFFFFFF**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color of the background when the radio button is selected, in 0xARGB format. The default value is **0xFF007DFF**.
.value[1].u32: color of the border when the radio button is deselected, in 0xARGB format. The default value is **0xFF182431**.
.value[2].u32: color of the indicator when the radio button is selected, in 0xARGB format. The default value is **0xFFFFFFF**.| -| NODE_RADIO_VALUE | Sets the current value of the radio button. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: value of the option button.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: value of the option button.| -| NODE_RADIO_GROUP | Sets the name of the group to which the radio button belongs. Only one radio button in a given group can be selected at a time. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: name of the group to which the radio button belongs.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: name of the group to which the radio button belongs. | +| NODE_CALENDAR_PICKER_DISABLED_DATE_RANGE16+ | Sets the disabled date ranges for the calendar picker. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.string: string representing the disabled date ranges. The format is "start_date,end_date" for each range, with multiple ranges separated by commas (,).
Example: "1910-01-01,1910-12-31,2020-01-01,2020-12-31".
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: string representing the disabled date ranges.| +| NODE_CALENDAR_PICKER_MARK_TODAY16+ | Sets whether to highlight the current system date. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: true indicates that the calendar selector is highlighted when the current date is displayed. and **false** means the opposite. The default value is **false**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to highlight the current system date in the calendar picker. The value **1** means to highlight the current system date, and **0** means the opposite.| +| NODE_SLIDER_BLOCK_COLOR | Defines the color of the slider. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color of the slider, in 0xARGB format, for example, **0xFF1122FF**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color of the slider, in 0xARGB format, for example, **0xFF1122FF**.| +| NODE_SLIDER_TRACK_COLOR | Defines the background color of the slider. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: background color, in 0xARGB format, for example, **0xFF1122FF**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: background color, in 0xARGB format, for example, **0xFF1122FF**.| +| NODE_SLIDER_SELECTED_COLOR | Defines the color of the selected part of the slider track. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color of the selected part of the slider track, in 0xARGB format, for example, **0xFF1122FF**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color of the selected part of the slider track, in 0xARGB format, for example, **0xFF1122FF**.| +| NODE_SLIDER_SHOW_STEPS | Sets whether to display the step scale value. Attributes can be set, reset, and obtained.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to display the stepping value. The value **1** means to display the stepping value, and **0** (default value) means the opposite.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to display the stepping value. The value **1** means to display the stepping value, and **0** (default value) means the opposite.| +| NODE_SLIDER_BLOCK_STYLE | Defines the slider shape, which can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: shape. The parameter type is [ArkUI_SliderBlockStyle](#arkui_sliderblockstyle).
.string? depending on the shape. Optional.
ARKUI_SLIDER_BLOCK_STYLE_IMAGE: image resource of the slider. Example: /pages/common/icon.png.
ARKUI_SLIDER_BLOCK_STYLE_SHAPE: custom shape of the slider.
There are five types:
1. Rectangle:
.value[1].i32: cropping type. The parameter type is [ArkUI_ShapeType](#arkui_shapetype), ARKUI_SHAPE_TYPE_RECTANGLE.
.value[2].f32: height of the rectangle.
.value[3].f32: height of the rectangle.
.value[4].f32: height of the rounded corner of the rectangle.
.value[5].f32: height of the rounded corner of the rectangle.
2. Circle:
.value[1].i32: cropping type. The parameter type is [ArkUI_ShapeType](#arkui_shapetype), ARKUI_SHAPE_TYPE_CIRCLE.
.value[2].f32: height of the circle.
.value[3].f32: height of the circle.
3. Ellipse:
.value[1].i32: cropping type. The parameter type is [ArkUI_ShapeType](#arkui_shapetype), ARKUI_SHAPE_TYPE_ELLIPSE.
.value[2].f32: height of the ellipse.
.value[3].f32: height of the ellipse.
4. Path:
.value[1].i32: cropping type. The parameter type is [ArkUI_ShapeType](#arkui_shapetype), ARKUI_SHAPE_TYPE_PATH.
.value[2].f32: width of the path.
.value[3].f32: height of the path.
.string: command for drawing the path.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: shape. The parameter type is [ArkUI_SliderBlockStyle](#arkui_sliderblockstyle).
.string? depending on the shape. Optional.
ARKUI_SLIDER_BLOCK_STYLE_IMAGE: image resource of the slider. Example: /pages/common/icon.png.
ARKUI_SLIDER_BLOCK_STYLE_SHAPE: custom shape of the slider.
There are five types:
1. Rectangle:
.value[1].i32: cropping type. The parameter type is [ArkUI_ShapeType](#arkui_shapetype), ARKUI_SHAPE_TYPE_RECTANGLE.
.value[2].f32: height of the rectangle.
.value[3].f32: height of the rectangle.
.value[4].f32: height of the rounded corner of the rectangle.
.value[5].f32: height of the rounded corner of the rectangle.
2. Circle:
.value[1].i32: cropping type. The parameter type is [ArkUI_ShapeType](#arkui_shapetype), ARKUI_SHAPE_TYPE_CIRCLE.
.value[2].f32: height of the circle.
.value[3].f32: height of the circle.
3. Ellipse:
.value[1].i32: cropping type. The parameter type is [ArkUI_ShapeType](#arkui_shapetype), ARKUI_SHAPE_TYPE_ELLIPSE.
.value[2].f32: height of the ellipse.
.value[3].f32: height of the ellipse.
4. Path:
.value[1].i32: cropping type. The parameter type is [ArkUI_ShapeType](#arkui_shapetype), ARKUI_SHAPE_TYPE_PATH.
.value[2].f32: width of the path.
.value[3].f32: height of the path.
.string: command for drawing the path.| +| NODE_SLIDER_VALUE | Defines the current value of the slider. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: current value.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: current value.| +| NODE_SLIDER_MIN_VALUE | Defines the minimum value of the slider. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: minimum value.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: minimum value.| +| NODE_SLIDER_MAX_VALUE | Defines the maximum value of the slider. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: maximum value.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: maximum value.| +| NODE_SLIDER_STEP | Defines the step of the slider. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: step. The value range is [0.01, 100].
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: step. The value range is [0.01, 100].| +| NODE_SLIDER_DIRECTION | Defines whether the slider moves horizontally or vertically. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: display style. The parameter type is [ArkUI_SliderDirection](#arkui_sliderdirection).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: display style. The parameter type is [ArkUI_SliderDirection](#arkui_sliderdirection).| +| NODE_SLIDER_REVERSE | Defines whether the slider values are reversed. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether the slider values are reversed. The value **1** means that the slider values are reversed, and **0** means the opposite.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether the slider values are reversed. The value **1** means that the slider values are reversed, and **0** means the opposite.| +| NODE_SLIDER_STYLE | Defines the style of the slider thumb and track. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: display style. The parameter type is [ArkUI_SliderStyle](#arkui_sliderstyle).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: display style. The parameter type is [ArkUI_SliderStyle](#arkui_sliderstyle).| +| NODE_SLIDER_TRACK_THICKNESS | Sets the track thickness of the slider. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: track thickness of the slider, in vp. The default value is 4.0 vp when **NODE_SLIDER_STYLE** is set to **ARKUI_SLIDER_STYLE_OUT_SET** and 20.0 vp when **NODE_SLIDER_STYLE** is set to **ARKUI_SLIDER_STYLE_IN_SET**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: track thickness of the slider, in vp. | +| NODE_SLIDER_ENABLE_HAPTIC_FEEDBACK | Specifies whether to enable haptic feedback. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to enable haptic feedback. The value **true** means to enable haptic feedback, and **false** means the opposite. The default value is **true**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to enable haptic feedback.| +| NODE_RADIO_CHECKED | Sets whether the radio button is selected. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether the radio button is selected. The default value is **false**. Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether the radio button is selected.| +| NODE_RADIO_STYLE | Sets the style of the radio button in selected or deselected state. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0]?.u32: color of the background when the radio button is selected, in 0xARGB format. The default value is **0xFF007DFF**.
.value[1]?.u32: color of the border when the radio button is deselected, in 0xARGB format. The default value is **0xFF182431**.
.value[2]?.u32: color of the indicator when the radio button is selected, in 0xARGB format. The default value is **0xFFFFFFFF**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color of the background when the radio button is selected, in 0xARGB format. The default value is **0xFF007DFF**.
.value[1].u32: color of the border when the radio button is deselected, in 0xARGB format. The default value is **0xFF182431**.
.value[2].u32: color of the indicator when the radio button is selected, in 0xARGB format. The default value is **0xFFFFFFF**.| +| NODE_RADIO_VALUE | Sets the current value of the radio button. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: value of the option button.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: value of the option button.| +| NODE_RADIO_GROUP | Sets the name of the group to which the radio button belongs. Only one radio button in a given group can be selected at a time. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: name of the group to which the radio button belongs.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: name of the group to which the radio button belongs. | | NODE_CHECKBOX_GROUP_NAME | Sets the name of the check box group. This attribute can be set, reset, and obtained as required through APIs. If there are multiple check box groups with the same group name, only the first check box group takes effect.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: name of the check box group.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: name of the check box group.| | NODE_CHECKBOX_GROUP_SELECT_ALL | Sets whether to select all check boxes in the check box group. This attribute can be set, reset, and obtained as required through APIs. If the **select** attribute is set for a check box in the group, the setting of the check box has a higher priority.
Default value: **false**
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether all check boxes are selected in the check box group. The value **1** means all check boxes are selected in the check box group, and **0** means the opposite.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether all check boxes are selected in the check box group. The value **1** means all check boxes are selected in the check box group, and **0** means the opposite.| | NODE_CHECKBOX_GROUP_SELECTED_COLOR | Sets the color for the selected state of the check box group. This attribute can be set, reset, and obtained as required through APIs.
Default value: **false**
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color of the selected state in 0xARGB format, for example, **0xFF1122FF**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color of the selected state in 0xARGB format, for example, **0xFF1122FF**.| | NODE_CHECKBOX_GROUP_UNSELECTED_COLOR | Sets the color for the unselected state of the check box group. This attribute can be set, reset, and obtained as required through APIs.
Default value: **false**
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: border color, in 0xARGB format, for example, **0xFF1122FF**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: border color, in 0xARGB format, for example, **0xFF1122FF**.| | NODE_CHECKBOX_GROUP_MARK | Sets the check mark style of the check box group. This attribute can be set, reset, and obtained as required through APIs.
Default value: **false**
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: border color, in 0xARGB format, for example, **0xFF1122FF**.
.value[1]?.f32: size of the check mark, in vp. Optional.
.value[2]?.f32: stroke width of the internal mark, in vp. Optional. The default value is **2**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: border color, in 0xARGB format, for example, **0xFF1122FF**.
.value[1]?.f32: size of the check mark, in vp. Optional.
.value[2]?.f32: stroke width of the internal mark, in vp. Optional. The default value is **2**.| | NODE_CHECKBOX_GROUP_SHAPE | Sets the shape of the check box group. This attribute can be set, reset, and obtained as required through APIs.
Default value: **false**
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: component shape. The parameter type is [ArkUI_CheckboxShape](#arkui_checkboxshape).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: component shape. The parameter type is [ArkUI_CheckboxShape](#arkui_checkboxshape).| -| NODE_STACK_ALIGN_CONTENT | Defines the alignment mode of the child components in the container. This attribute can be set, reset, and obtained as required through APIs.
If this attribute and the universal attribute **NODE_ALIGNMENT** are both set, whichever is set later takes effect.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: alignment mode. The parameter type is [ArkUI_Alignment](#arkui_alignment). The default value is **ARKUI_ALIGNMENT_CENTER**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: alignment mode. The parameter type is [ArkUI_Alignment](#arkui_alignment).| -| NODE_SCROLL_BAR_DISPLAY_MODE | Defines the scrollbar status. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: scroll bar status. The data type is [ArkUI_ScrollBarDisplayMode](#arkui_scrollbardisplaymode), and the default value is ARKUI_SCROLL_BAR_DISPLAY_MODE_AUTO.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: scroll bar status. The data type is [ArkUI_ScrollBarDisplayMode](#arkui_scrollbardisplaymode).| -| NODE_SCROLL_BAR_WIDTH | Defines the width of the scrollbar. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: width of the scrollbar, in vp. The default value is **4**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: width of the scrollbar, in vp.| -| NODE_SCROLL_BAR_COLOR | Defines the color of the scrollbar. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.data[0].u32: color of the scrollbar, in 0xARGB format.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.data[0].u32: color of the scrollbar, in 0xARGB format.| -| NODE_SCROLL_SCROLL_DIRECTION | Defines the scroll direction. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: scrolling direction. The data type is [ArkUI_ScrollDirection](#arkui_scrolldirection), and the default value is ARKUI_SCROLL_DIRECTION_VERTICAL.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: scrolling direction. The data type is [ArkUI_ScrollDirection](#arkui_scrolldirection).| +| NODE_STACK_ALIGN_CONTENT | Defines the alignment mode of the child components in the container. This attribute can be set, reset, and obtained as required through APIs.
If this attribute and the universal attribute **NODE_ALIGNMENT** are both set, whichever is set later takes effect.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: alignment mode. The parameter type is [ArkUI_Alignment](#arkui_alignment). The default value is **ARKUI_ALIGNMENT_CENTER**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: alignment mode. The parameter type is [ArkUI_Alignment](#arkui_alignment).| +| NODE_SCROLL_BAR_DISPLAY_MODE | Defines the scrollbar status. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: scroll bar status. The data type is [ArkUI_ScrollBarDisplayMode](#arkui_scrollbardisplaymode), and the default value is ARKUI_SCROLL_BAR_DISPLAY_MODE_AUTO.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: scroll bar status. The data type is [ArkUI_ScrollBarDisplayMode](#arkui_scrollbardisplaymode).| +| NODE_SCROLL_BAR_WIDTH | Defines the width of the scrollbar. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: width of the scrollbar, in vp. The default value is **4**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: width of the scrollbar, in vp.| +| NODE_SCROLL_BAR_COLOR | Defines the color of the scrollbar. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.data[0].u32: color of the scrollbar, in 0xARGB format.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.data[0].u32: color of the scrollbar, in 0xARGB format.| +| NODE_SCROLL_SCROLL_DIRECTION | Defines the scroll direction. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: scrolling direction. The data type is [ArkUI_ScrollDirection](#arkui_scrolldirection), and the default value is ARKUI_SCROLL_DIRECTION_VERTICAL.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: scrolling direction. The data type is [ArkUI_ScrollDirection](#arkui_scrolldirection).| | NODE_SCROLL_EDGE_EFFECT | Defines the effect used at the edges of the component when the boundary of the scrollable content is reached. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: edge sliding effect. The parameter type is [ArkUI_EdgeEffect](#arkui_edgeeffect). The default value is ARKUI_EDGE_EFFECT_NONE.
.value[1]?.i32: whether to enable the scroll effect when the component content size is smaller than the component itself. Optional. The value **1** means to enable the scroll effect, and **0** means the opposite. The default value is **1**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: edge sliding effect. The parameter type is [ArkUI_EdgeEffect](#arkui_edgeeffect).
.value[1].i32: whether to enable the scroll effect when the component content size is smaller than the component itself. The value **1** means to enable the scroll effect, and **0** means the opposite.
Sets the effect used at the edges of the component when the boundary of the scrollable content is reached. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: edge sliding effect. The parameter type is [ArkUI_EdgeEffect](#arkui_edgeeffect). The default value is ARKUI_EDGE_EFFECT_NONE.
.value[1]?.i32: whether to enable the scroll effect when the component content size is smaller than the component itself. Optional. The value **1** means to enable the scroll effect, and **0** means the opposite. The default value is **1**.
.value[2]?.i32: direction in which the effect takes effect. The parameter type is [ArkUI_EffectEdge](#arkui_effectedge). The default value is ARKUI_EFFECT_EDGE_START \| ARKUI_EFFECT_EDGE_END.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: edge sliding effect. The parameter type is [ArkUI_EdgeEffect](#arkui_edgeeffect).
.value[1].i32: whether to enable the scroll effect when the component content size is smaller than the component itself. The value **1** means to enable the scroll effect, and **0** means the opposite.
.value[2].i32: direction in which the effect takes effect. The parameter type is [ArkUI_EffectEdge](#arkui_effectedge).
**Since**
17 | -| NODE_SCROLL_ENABLE_SCROLL_INTERACTION | Sets whether to support scroll gestures. When this attribute is set to **false**, scrolling by finger or mouse is not supported, but the scroll controller API is not affected.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to support scroll gestures. The default value is **true**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to support scroll gestures.| -| NODE_SCROLL_FRICTION | Sets the friction coefficient. It applies only to gestures in the scrolling area, and it affects only indirectly the scroll chaining during the inertial scrolling process.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: friction coefficient. The default value is **0.6** for non-wearable devices and **0.9** for wearable devices.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: friction coefficient.| -| NODE_SCROLL_SNAP | Defines the scroll snapping mode. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: limit scrolling mode of the scroll component. The data type is [ArkUI_ScrollSnapAlign](#arkui_scrollsnapalign), and the default value is ARKUI_SCROLL_SNAP_ALIGN_NONE.
.value[1].i32: whether to enable the snap to start feature. When scroll snapping is defined for the **Scroll** component, setting this attribute to **false** enables the component to scroll between the start edge and the first snap point. The default value is **true**. It is valid only when there are multiple snap points.
.value[2].i32: Whether to enable the snap to end feature. When scroll snapping is defined for the **Scroll** component, setting this attribute to **false** enables the component to scroll between the end edge and the last snap point. The default value is **true**. It is valid only when there are multiple snap points.
.value[3...].f32: snap points for the **Scroll** component. Each snap point defines the offset from an edge to which the **Scroll** component can scroll. The value can be one or more.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: alignment mode for the scroll snap position. The parameter type is [ArkUI_ScrollSnapAlign](#arkui_scrollsnapalign).
.value[1].i32: whether to enable the snap to start feature. When scroll snapping is defined for the **Scroll** component, setting this attribute to **false** enables the component to scroll between the start edge and the first snap point.
.value[2].i32: Whether to enable the snap to end feature. When scroll snapping is defined for the **Scroll** component, setting this attribute to **false** enables the component to scroll between the end edge and the last snap point.
.value[3...].f32: snap points for the **Scroll** component. Each snap point defines the offset from an edge to which the **Scroll** component can scroll.| -| NODE_SCROLL_NESTED_SCROLL | Defines the nested scrolling options. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: nested scrolling when the scrollable component scrolls to the end. The parameter type is [ArkUI_ScrollNestedMode](#arkui_scrollnestedmode).
.value[1].i32: nested scrolling when the scrollable component scrolls to the start end. The parameter type is [ArkUI_ScrollNestedMode](#arkui_scrollnestedmode).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: nested scrolling when the scrollable component scrolls to the end. The parameter type is [ArkUI_ScrollNestedMode](#arkui_scrollnestedmode).
.value[1].i32: nested scrolling when the scrollable component scrolls to the start end. The parameter type is [ArkUI_ScrollNestedMode](#arkui_scrollnestedmode).| -| NODE_SCROLL_OFFSET | Defines the specified position to scroll to. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: horizontal scrolling offset, in vp.
.value[1].f32: vertical scrolling offset, in vp.
.value[2]?.i32: scrolling duration, in milliseconds. Optional.
.value[3]?.i32: (optional) scrolling curve. The parameter type is [ArkUI_AnimationCurve](#arkui_animationcurve). The default value is **ARKUI_CURVE_EASE**.
.value[4]?.i32: whether to enable the default spring animation. Optional. The default value **0** means not to enable the default spring animation.
.value[5]?.i32: whether to enable overscroll. Optional.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: horizontal scrolling offset, in vp.
.value[1].f32: vertical scrolling offset, in vp.| -| NODE_SCROLL_EDGE | Defines the edge position to scroll to. This attribute can be set and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: container edge. The parameter type is [ArkUI_ScrollEdge](#arkui_scrolledge).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: indicates whether the container is on the edge. The value -1 indicates that the container is not on the edge. If the container is on the edge, the status parameter type is [ArkUI_ScrollEdge](#arkui_scrolledge).| -| NODE_SCROLL_ENABLE_PAGING | Defines whether to enable the swipe-to-turn-pages feature. This attribute can be set, reset, and obtained as required through APIs.
If both **enablePaging** and **scrollSnap** are set, **scrollSnap** takes effect, but **enablePaging** does not.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to enable the swipe-to-turn-pages feature. The default value is **false**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to enable the swipe-to-turn-pages feature.| -| NODE_SCROLL_PAGE | Scrolls to the next or previous page.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to scroll to the next page. The value **0** means to scroll to the next page, and **1** means to scroll to the previous page.
.value[1]?.i32: whether to enable the page turning animation. The value **1** means to enable the page turning animation, and **0** means the opposite. Default value: 0.| -| NODE_SCROLL_BY | Scrolls by the specified amount.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: amount to scroll by in the horizontal direction, in vp by default.
.value[1].f32: amount to scroll by in the vertical direction, in vp by default.| -| NODE_SCROLL_FLING | Performs inertial scrolling based on the initial velocity passed in.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: initial velocity of inertial scrolling. The default unit is vp/s. If the value specified is 0, it is considered as invalid, and the scrolling for this instance will not take effect. If the value is positive, the scroll will move downward; if the value is negative, the scroll will move upward.| +| NODE_SCROLL_ENABLE_SCROLL_INTERACTION | Sets whether to support scroll gestures. When this attribute is set to **false**, scrolling by finger or mouse is not supported, but the scroll controller API is not affected.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to support scroll gestures. The default value is **true**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to support scroll gestures.| +| NODE_SCROLL_FRICTION | Sets the friction coefficient. It applies only to gestures in the scrolling area, and it affects only indirectly the scroll chaining during the inertial scrolling process.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: friction coefficient. The default value is **0.6** for non-wearable devices and **0.9** for wearable devices.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: friction coefficient.| +| NODE_SCROLL_SNAP | Defines the scroll snapping mode. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: limit scrolling mode of the scroll component. The data type is [ArkUI_ScrollSnapAlign](#arkui_scrollsnapalign), and the default value is ARKUI_SCROLL_SNAP_ALIGN_NONE.
.value[1].i32: whether to enable the snap to start feature. When scroll snapping is defined for the **Scroll** component, setting this attribute to **false** enables the component to scroll between the start edge and the first snap point. The default value is **true**. It is valid only when there are multiple snap points.
.value[2].i32: Whether to enable the snap to end feature. When scroll snapping is defined for the **Scroll** component, setting this attribute to **false** enables the component to scroll between the end edge and the last snap point. The default value is **true**. It is valid only when there are multiple snap points.
.value[3...].f32: snap points for the **Scroll** component. Each snap point defines the offset from an edge to which the **Scroll** component can scroll. The value can be one or more.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: alignment mode for the scroll snap position. The parameter type is [ArkUI_ScrollSnapAlign](#arkui_scrollsnapalign).
.value[1].i32: whether to enable the snap to start feature. When scroll snapping is defined for the **Scroll** component, setting this attribute to **false** enables the component to scroll between the start edge and the first snap point.
.value[2].i32: Whether to enable the snap to end feature. When scroll snapping is defined for the **Scroll** component, setting this attribute to **false** enables the component to scroll between the end edge and the last snap point.
.value[3...].f32: snap points for the **Scroll** component. Each snap point defines the offset from an edge to which the **Scroll** component can scroll.| +| NODE_SCROLL_NESTED_SCROLL | Defines the nested scrolling options. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: nested scrolling when the scrollable component scrolls to the end. The parameter type is [ArkUI_ScrollNestedMode](#arkui_scrollnestedmode).
.value[1].i32: nested scrolling when the scrollable component scrolls to the start end. The parameter type is [ArkUI_ScrollNestedMode](#arkui_scrollnestedmode).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: nested scrolling when the scrollable component scrolls to the end. The parameter type is [ArkUI_ScrollNestedMode](#arkui_scrollnestedmode).
.value[1].i32: nested scrolling when the scrollable component scrolls to the start end. The parameter type is [ArkUI_ScrollNestedMode](#arkui_scrollnestedmode).| +| NODE_SCROLL_OFFSET | Defines the specified position to scroll to. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: horizontal scrolling offset, in vp.
.value[1].f32: vertical scrolling offset, in vp.
.value[2]?.i32: scrolling duration, in milliseconds. Optional.
.value[3]?.i32: (optional) scrolling curve. The parameter type is [ArkUI_AnimationCurve](#arkui_animationcurve). The default value is **ARKUI_CURVE_EASE**.
.value[4]?.i32: whether to enable the default spring animation. Optional. The default value **0** means not to enable the default spring animation.
.value[5]?.i32: whether to enable overscroll. Optional.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: horizontal scrolling offset, in vp.
.value[1].f32: vertical scrolling offset, in vp.| +| NODE_SCROLL_EDGE | Defines the edge position to scroll to. This attribute can be set and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: container edge. The parameter type is [ArkUI_ScrollEdge](#arkui_scrolledge).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: indicates whether the container is on the edge. The value -1 indicates that the container is not on the edge. If the container is on the edge, the status parameter type is [ArkUI_ScrollEdge](#arkui_scrolledge).| +| NODE_SCROLL_ENABLE_PAGING | Defines whether to enable the swipe-to-turn-pages feature. This attribute can be set, reset, and obtained as required through APIs.
If both **enablePaging** and **scrollSnap** are set, **scrollSnap** takes effect, but **enablePaging** does not.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to enable the swipe-to-turn-pages feature. The default value is **false**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to enable the swipe-to-turn-pages feature.| +| NODE_SCROLL_PAGE | Scrolls to the next or previous page.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to scroll to the next page. The value **0** means to scroll to the next page, and **1** means to scroll to the previous page.
.value[1]?.i32: whether to enable the page turning animation. The value **1** means to enable the page turning animation, and **0** means the opposite. Default value: 0.| +| NODE_SCROLL_BY | Scrolls by the specified amount.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: amount to scroll by in the horizontal direction, in vp by default.
.value[1].f32: amount to scroll by in the vertical direction, in vp by default.| +| NODE_SCROLL_FLING | Performs inertial scrolling based on the initial velocity passed in.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: initial velocity of inertial scrolling. The default unit is vp/s. If the value specified is 0, it is considered as invalid, and the scrolling for this instance will not take effect. If the value is positive, the scroll will move downward; if the value is negative, the scroll will move upward.| | NODE_SCROLL_FADING_EDGE | Sets the edge fade effect for the scrollable component.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to enable the edge fade effect. The value **0** means to disable edge fade effect, and **1** means the opposite.
.value[1]?.f32: length of the edge fade effect, in vp. The default value is **32**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to enable the edge fade effect. The value **0** means to disable edge fade effect, and **1** means the opposite.
.value[1].f32: length of the edge fade effect, in vp.
**Since**
14 | | NODE_SCROLL_SIZE | Obtains the total size of all child components when fully expanded in the scrollable component.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: total width of all child components when fully expanded in the scrollable component. The default unit is vp.
.value[1].f32: total height of all child components when fully expanded in the scrollable component. The default unit is vp.
When **NODE_PADDING**, **NODE_MARGIN**, **NODE_BORDER_WIDTH** is set, the values are rounded to the nearest pixel when being converted from vp to px. The return values are calculated based on these rounded pixel values.
**Since**
14 | -| NODE_LIST_DIRECTION | Defines the direction in which the list items are arranged. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: direction in which the list items are arranged. The parameter type is [ArkUI_Axis](#arkui_axis). The default value is **ARKUI_AXIS_VERTICAL**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: direction in which the list items are arranged. The parameter type is [ArkUI_Axis](#arkui_axis).| -| NODE_LIST_STICKY | Defines whether to pin the header to the top or the footer to the bottom in the **ListItemGroup** component. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to pin the header to the top or the footer to the bottom in the **ListItemGroup** component. It is used together with the **ListItemGroup** component. Data type [ArkUI_StickyStyle](#arkui_stickystyle). The default value is **ARKUI_STICKY_STYLE_NONE**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to pin the header to the top or the footer to the bottom in the **ListItemGroup** component. It is used together with the **ListItemGroup** component. The parameter type is [ArkUI_StickyStyle](#arkui_stickystyle).| -| NODE_LIST_SPACE | Defines the spacing between list items. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: spacing between list items along the main axis. The default value is **0**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: spacing between list items along the main axis.| -| NODE_LIST_NODE_ADAPTER | Defines the list adapter. The attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.object: **ArkUI_NodeAdapter** object as the adapter.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: **ArkUI_NodeAdapter** object.| -| NODE_LIST_CACHED_COUNT | Sets the number of cached items in the list adapter. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: number of cached items in the list adapter.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: number of cached items in the list adapter.| -| NODE_LIST_SCROLL_TO_INDEX | Slide to the specified index.
When **smooth** is set to **true**, all passed items are loaded and counted in layout calculation. This may result in performance issues if a large number of items are involved.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: index of the item to be scrolled to in the container.
.value[1]?.i32: whether to enable the smooth animation for scrolling to the item with the specified index. The value **1** means to enable the animation, and **0** means the opposite. Default value: 0.
.value[2]?.i32: how the item to scroll to is aligned with the container. The parameter type is [ArkUI_ScrollAlignment](#arkui_scrollalignment). The default value is **ARKUI_SCROLL_ALIGNMENT_START**.| -| NODE_LIST_ALIGN_LIST_ITEM | Sets the alignment mode of list items along the cross axis when the cross-axis width of the list is greater than the cross-axis width of list items multiplied by the value of lanes. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: alignment mode of list items along the cross axis. The parameter type is **ArkUI_ListItemAlign**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: alignment mode of list items along the cross axis. The parameter type is **ArkUI_ListItemAlign**.| -| NODE_LIST_CHILDREN_MAIN_SIZE | Sets the default main axis size of the child components in this list.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
object: **ArkUI_ListChildrenMainSize** object.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: The parameter format is **ArkUI_ListChildrenMainSize**.| -| NODE_LIST_INITIAL_INDEX | Sets the item displayed at the beginning of the viewport when the current list is loaded for the first time, that is, the first item to be displayed. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: index value the item displayed at the beginning of the viewport when the current list is loaded for the first time. The default value is **0**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: index value the item displayed at the beginning of the viewport when the current list is loaded for the first time. The default value is **0**.| -| NODE_LIST_DIVIDER | Defines the style of the divider for the list items. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: color of the divider, in 0xARGB format.
.value[1].f32: stroke width of the divider.
.value[2].f32: distance between the divider and the start of the list, in vp.
.value[3].f32: distance between the divider and the end of the list, in vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color of the divider, in 0xARGB format.
.value[1].f32: stroke width of the divider.
.value[2].f32: distance between the divider and the start of the list, in vp.
.value[3].f32: distance between the divider and the end of the list, in vp.| -| NODE_SWIPER_LOOP | Defines whether to enable loop playback for the swiper. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to enable loop playback. The value **1** means to enable loop playback, and **0** means the opposite. The default value is **1**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to enable loop playback. The value **1** means to enable loop playback, and **0** means the opposite. The default value is **1**.| -| NODE_SWIPER_AUTO_PLAY | Defines whether to enable automatic playback for child component switching in the swiper. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to enable automatic playback for child component switching. The value **1** means to enable automatic playback, and **0** means the opposite. The default value is **0**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to enable automatic playback for child component switching. The value **1** means to enable automatic playback, and **0** means the opposite. The default value is **0**.| -| NODE_SWIPER_SHOW_INDICATOR | Defines whether to enable the navigation point indicator for the swiper. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to enable the navigation point indicator. The value **1** means to enable the navigation point indicator, and **0** means the opposite. The default value is **1**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to enable the navigation point indicator. The value **1** means to enable the navigation point indicator, and **0** means the opposite. The default value is **1**.| -| NODE_SWIPER_INTERVAL | Defines the interval for automatic playback. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: interval for automatic playback, in milliseconds.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: interval for automatic playback, in milliseconds.| -| NODE_SWIPER_VERTICAL | Defines whether vertical swiping is used for the swiper. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether vertical swiping is used. The value **1** means that vertical swiping is used, and **0** means the opposite. The default value is **0**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether vertical swiping is used. The value **1** means that vertical swiping is used, and **0** means the opposite. The default value is **0**.| -| NODE_SWIPER_DURATION | Defines the duration of the animation for switching child components. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: duration of the animation for switching child components, in milliseconds. The default value is **400**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: duration of the animation for switching child components, in milliseconds. The default value is **400**.| -| NODE_SWIPER_CURVE | Defines the animation curve for the swiper. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: Sets the animation curve parameter. The parameter type is [ArkUI_AnimationCurve](#arkui_animationcurve). The default value is ARKUI_CURVE_LINEAR.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: Sets the animation curve parameter. The parameter type is [ArkUI_AnimationCurve](#arkui_animationcurve). The default value is ARKUI_CURVE_LINEAR.| -| NODE_SWIPER_ITEM_SPACE | Defines the spacing between child components in the swiper. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: spacing between child components.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: spacing between child components.| -| NODE_SWIPER_INDEX | Defines the index of the child component currently displayed in the swiper. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: number of elements to display per page.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: number of elements to display per page.| -| NODE_SWIPER_DISPLAY_COUNT | Defines the number of elements to display per page. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: number of elements to display per page.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: number of elements to display per page.| -| NODE_SWIPER_DISABLE_SWIPE | This interface is used to disable the sliding switching function of the Swiper component. The attribute setting, attribute resetting, and attribute obtaining interfaces are supported.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to disable the swipe feature. The value **1** means to disable the swipe feature, and **0** means the opposite. The default value is **0**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to disable the swipe feature. The value **1** means to disable the swipe feature, and **0** means the opposite. The default value is **0**.| -| NODE_SWIPER_SHOW_DISPLAY_ARROW | Defines whether to show the arrow when the mouse pointer hovers over the navigation point indicator. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: indicates whether to display the navigation arrow. The parameter type is [ArkUI_SwiperArrow](#arkui_swiperarrow).
The default value is **ARKUI_SWIPER_ARROW_HIDE**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: indicates whether to display the navigation arrow. The parameter type is [ArkUI_SwiperArrow](#arkui_swiperarrow).
The default value is **ARKUI_SWIPER_ARROW_HIDE**.| -| NODE_SWIPER_EDGE_EFFECT_MODE | Defines the effect used at the edges of the swiper when the boundary of the scrollable content is reached. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: effect used at the edges of the swiper when the boundary of the scrollable content is reached. The parameter type is [ArkUI_EdgeEffect](#arkui_edgeeffect).
The default value is **ARKUI_EDGE_EFFECT_SPRING**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: effect used at the edges of the swiper when the boundary of the scrollable content is reached. The parameter type is [ArkUI_EdgeEffect](#arkui_edgeeffect).| -| NODE_SWIPER_NODE_ADAPTER | Defines the swiper adapter. The attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.object: **ArkUI_NodeAdapter** object as the adapter.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: The format of the return value is ArkUI_NodeAdapter.| -| NODE_SWIPER_CACHED_COUNT | Sets the number of cached items in the swiper adapter. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: number of cached items in the swiper adapter.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: number of cached items in the list adapter.| -| NODE_SWIPER_PREV_MARGIN | Sets the previous margin of the swiper. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: previous margin, in vp. The default value is **0**.
.value[1].i32: whether to ignore blank areas. The value **1** means to ignore blank areas, and **0** means the opposite.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: previous margin, in vp. .value[1].i32: whether to ignore blank areas. The value **1** means to ignore blank areas, and **0** means the opposite.| -| NODE_SWIPER_NEXT_MARGIN | Sets the next margin of the swiper. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: next margin, in vp. The default value is **0**.
.value[1].i32: whether to ignore blank areas. The value **1** means to ignore blank areas, and **0** means the opposite.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: next margin, in vp. .value[1].i32: whether to ignore blank areas. The value **1** means to ignore blank areas, and **0** means the opposite.| -| NODE_SWIPER_INDICATOR | Sets the navigation indicator type of the Swiper component. The attribute setting, attribute resetting, and attribute obtaining interfaces are supported.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: navigation indicator type. The parameter type is [ArkUI_SwiperIndicatorType](#arkui_swiperindicatortype).
.object: The parameter type is [ArkUI_SwiperIndicator](#arkui_swiperindicator).
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: navigation indicator type. The parameter type is [ArkUI_SwiperIndicatorType](#arkui_swiperindicatortype).
.object: The parameter type is [ArkUI_SwiperIndicator](#arkui_swiperindicator).| -| NODE_SWIPER_NESTED_SCROLL | Sets the nested scrolling mode of the **Swiper** component and its parent container.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: nested scrolling mode of the Swiper component and parent component. The parameter type is [ArkUI_SwiperNestedScrollMode](#arkui_swipernestedscrollmode).
The default value is **ARKUI_SWIPER_NESTED_SCROLL_SELF_ONLY**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: nested scrolling mode of the Swiper component and parent component. The parameter type is [ArkUI_SwiperNestedScrollMode](#arkui_swipernestedscrollmode).| -| NODE_SWIPER_SWIPE_TO_INDEX | Sets the swiper to switch to the specified page.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: index of the target page in the swiper.
.value[1]?.i32: whether to use an animation for when the target page is reached. The value 1 indicates that the dynamic effect is enabled, and the value 0 indicates that the dynamic effect is disabled. The default value is 0.| -| NODE_SWIPER_INDICATOR_INTERACTIVE | Sets whether the navigation point indicator is interactive.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether the navigation point indicator is interactive. The default value **true** means that the navigation point indicator is interactive.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether the navigation point indicator is interactive.| +| NODE_SCROLL_CONTENT_START_OFFSET | Sets the offset from the start of the list content to the boundary of the list display area. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: offset from the start of the list content. The default value is **0**, and the unit is vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: offset from the start of the list content, in vp.| +| NODE_SCROLL_CONTENT_END_OFFSET | Sets the offset from the end of the list content to the boundary of the list display area. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: offset from the end of the list content. The default value is **0**, and the unit is vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: offset from the end of the list content, in vp.| +| NODE_LIST_DIRECTION | Defines the direction in which the list items are arranged. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: direction in which the list items are arranged. The parameter type is [ArkUI_Axis](#arkui_axis). The default value is **ARKUI_AXIS_VERTICAL**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: direction in which the list items are arranged. The parameter type is [ArkUI_Axis](#arkui_axis).| +| NODE_LIST_STICKY | Defines whether to pin the header to the top or the footer to the bottom in the **ListItemGroup** component. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to pin the header to the top or the footer to the bottom in the **ListItemGroup** component. It is used together with the **ListItemGroup** component. Data type [ArkUI_StickyStyle](#arkui_stickystyle). The default value is **ARKUI_STICKY_STYLE_NONE**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to pin the header to the top or the footer to the bottom in the **ListItemGroup** component. It is used together with the **ListItemGroup** component. The parameter type is [ArkUI_StickyStyle](#arkui_stickystyle).| +| NODE_LIST_SPACE | Defines the spacing between list items. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: spacing between list items along the main axis. The default value is **0**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: spacing between list items along the main axis.| +| NODE_LIST_NODE_ADAPTER | Defines the list adapter. The attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.object: **ArkUI_NodeAdapter** object as the adapter.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: **ArkUI_NodeAdapter** object.| +| NODE_LIST_CACHED_COUNT | Sets the number of cached items in the list adapter. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: number of cached items in the list adapter.
.value[1].i32: whether to show cached items. The value **0** means to hide cached items, and **1** means to show cached items. Default value: 0.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: number of cached items in the list adapter.
.value[1].i32: whether to show cached items. The value **0** means to hide cached items, and **1** means to show cached items. Default value: 0.| +| NODE_LIST_SCROLL_TO_INDEX | Slide to the specified index.
When **smooth** is set to **true**, all passed items are loaded and counted in layout calculation. This may result in performance issues if a large number of items are involved.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: index of the item to be scrolled to in the container.
.value[1]?.i32: whether to enable the smooth animation for scrolling to the item with the specified index. The value **1** means to enable the animation, and **0** means the opposite. Default value: 0.
.value[2]?.i32: how the item to scroll to is aligned with the container. The parameter type is [ArkUI_ScrollAlignment](#arkui_scrollalignment). The default value is **ARKUI_SCROLL_ALIGNMENT_START**.
.value[3]?.f32: Options for scrolling to a specified index, for example, an extra offset for the scroll. The unit is vp.| +| NODE_LIST_ALIGN_LIST_ITEM | Sets the alignment mode of list items along the cross axis when the cross-axis width of the list is greater than the cross-axis width of list items multiplied by the value of lanes. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: alignment mode of list items along the cross axis. The parameter type is **ArkUI_ListItemAlign**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: alignment mode of list items along the cross axis. The parameter type is **ArkUI_ListItemAlign**.| +| NODE_LIST_CHILDREN_MAIN_SIZE | Sets the default main axis size of the child components in this list.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
object: **ArkUI_ListChildrenMainSize** object.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: The parameter format is **ArkUI_ListChildrenMainSize**.| +| NODE_LIST_INITIAL_INDEX | Sets the item displayed at the beginning of the viewport when the current list is loaded for the first time, that is, the first item to be displayed. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: index value the item displayed at the beginning of the viewport when the current list is loaded for the first time. The default value is **0**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: index value the item displayed at the beginning of the viewport when the current list is loaded for the first time. The default value is **0**.| +| NODE_LIST_DIVIDER | Defines the style of the divider for the list items. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: color of the divider, in 0xARGB format.
.value[1].f32: stroke width of the divider.
.value[2].f32: distance between the divider and the start of the list, in vp.
.value[3].f32: distance between the divider and the end of the list, in vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color of the divider, in 0xARGB format.
.value[1].f32: stroke width of the divider.
.value[2].f32: distance between the divider and the start of the list, in vp.
.value[3].f32: distance between the divider and the end of the list, in vp.| +| NODE_LIST_SCROLL_TO_INDEX_IN_GROUP | Scrolls to the specified list item in the specified list item group.
When **smooth** is set to **true**, all passed items are loaded and counted in layout calculation. This may result in performance issues if a large number of items are involved.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: index of the list item group in the current container that contains the target list item.
.value[1].i32: index of the target list item in the list item group.
.value[2]?.i32: whether to enable the smooth animation for scrolling to the item with the specified index. The value **1** means to enable the animation, and **0** means the opposite. Default value: 0.
.value[3]?.i32: how the target item to scroll to is aligned with the container. The parameter type is [ArkUI_ScrollAlignment](#arkui_scrollalignment). The default value is **ARKUI_SCROLL_ALIGNMENT_START**.| +| NODE_LIST_LANES | Sets the number of lanes (columns or rows) in the list. This attribute can be set, reset, and obtained as required through APIs.
Observe the following when using this API:
If the value is set to a number, the column width is calculated by dividing the cross-axis width of the **List** component by the specified number.
If the value is set to {minLength, maxLength}, the number of columns is adjusted adaptively based on the width of the **List** component, ensuring that the width respects the {minLength, maxLength} constraints during adaptation. The **minLength** constraint is prioritized to ensure that the cross-axis size of the list item meets the minimum requirement. If the cross-axis width constraint of the parent component is infinite, the parent component is arranged by column, and the column width is calculated based on the largest list item in the display area. Each list item group occupies one row in multi-column mode. Its child list items are arranged based on the **lanes** attribute of the list. The number of columns is calculated based on the cross-axis width of the list item group. If the cross-axis width of the list item group is different from that of the list, the number of columns in the list item group may be different from that in the list.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: number of lanes (rows or columns) in the list. The default value is **0**.
.value[1]?.f32: minimum length of the list item. The default value is **1**, and the unit is vp.
.value[2]?.f32: maximum length of the list item. The default value is **1**, and the unit is vp.
.value[3]?.f32: column spacing of the list item. This parameter is effective when the number of columns is greater than 1. The default value is **1**. The unit is vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: number of lanes (rows or columns) in the list. If {minLength, maxLength} is set, the return value is **1**.
.value[1].f32: minimum length of the list item, in vp.
.value[2].f32: maximum length of the list item, in vp.
.value[3].f32: column spacing of the list item, in vp.| +| NODE_LIST_SCROLL_SNAP_ALIGN | Sets the scroll snap alignment effect for list items. This effect aligns list items to the nearest snap point when scrolling ends. This attribute is effective only when all list items have the same height. It does not take effect when scrolling ends using a touchpad or mouse device. During the alignment animation, the scroll operation source type reported by the **onWillScroll** event is **ScrollSource.FLING**. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: alignment mode of the scroll snap position. Data type: [ArkUI_ScrollSnapAlign] (#arkui_scrollsnapalign). The default value is ARKUI_SCROLL_SNAP_ALIGN_NONE.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: alignment mode of the scroll snap position. The parameter type is [ArkUI_ScrollSnapAlign](#arkui_scrollsnapalign).| +| NODE_LIST_MAINTAIN_VISIBLE_CONTENT_POSITION | Sets whether to maintain the visible content's position when data is inserted or deleted outside the display area of the component.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to maintain the visible content's position when data is inserted or deleted outside the display area of the component. The value **0** means not to maintain the visible content's position, and **1** means the opposite. The default value is **0**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to maintain the visible content's position when data is inserted or deleted outside the display area of the component. The value **0** means not to maintain the visible content's position, and **1** means the opposite.| +| NODE_LIST_STACK_FROM_END | Sets whether the **List** component starts layout from the end.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether the **List** component starts layout from the end. The value **0** means layout starts from the top, and **1** means layout starts from the end. The default value is **0**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether the **List** component starts layout from the end. The value **0** means layout starts from the top, and **1** means layout starts from the end.| +| NODE_SWIPER_LOOP | Defines whether to enable loop playback for the swiper. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to enable loop playback. The value **1** means to enable loop playback, and **0** means the opposite. The default value is **1**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to enable loop playback. The value **1** means to enable loop playback, and **0** means the opposite. The default value is **1**.| +| NODE_SWIPER_AUTO_PLAY | Defines whether to enable automatic playback for child component switching in the swiper. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to enable automatic playback for child component switching. The value **1** means to enable automatic playback, and **0** means the opposite. The default value is **0**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to enable automatic playback for child component switching. The value **1** means to enable automatic playback, and **0** means the opposite. The default value is **0**.| +| NODE_SWIPER_SHOW_INDICATOR | Defines whether to enable the navigation indicator for the swiper. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to enable the navigation indicator. The value **1** means to enable the navigation indicator, and **0** means the opposite. The default value is **1**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to enable the navigation indicator. The value **1** means to enable the navigation indicator, and **0** means the opposite. The default value is **1**.| +| NODE_SWIPER_INTERVAL | Defines the interval for automatic playback. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: interval for automatic playback, in milliseconds.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: interval for automatic playback, in milliseconds.| +| NODE_SWIPER_VERTICAL | Defines whether vertical swiping is used for the swiper. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether vertical swiping is used. The value **1** means that vertical swiping is used, and **0** means the opposite. The default value is **0**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether vertical swiping is used. The value **1** means that vertical swiping is used, and **0** means the opposite. The default value is **0**.| +| NODE_SWIPER_DURATION | Defines the duration of the animation for switching child components. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: duration of the animation for switching child components, in milliseconds. The default value is **400**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: duration of the animation for switching child components, in milliseconds. The default value is **400**.| +| NODE_SWIPER_CURVE | Defines the animation curve for the swiper. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: Sets the animation curve parameter. The parameter type is [ArkUI_AnimationCurve](#arkui_animationcurve). The default value is ARKUI_CURVE_LINEAR.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: Sets the animation curve parameter. The parameter type is [ArkUI_AnimationCurve](#arkui_animationcurve). The default value is ARKUI_CURVE_LINEAR.| +| NODE_SWIPER_ITEM_SPACE | Defines the spacing between child components in the swiper. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: spacing between child components.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: spacing between child components.| +| NODE_SWIPER_INDEX | Defines the index of the child component currently displayed in the swiper. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: number of elements to display per page.
.value[1]?.i32: switching animation mode. The parameter type is [ArkUI_SwiperAnimationMode] (#arkui_swiperanimationmode). The setting is only effective for the current call.
This parameter is supported since API version 15.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: number of elements to display per page.| +| NODE_SWIPER_DISPLAY_COUNT | Defines the number of elements to display per page. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: number of elements to display within the viewport.
.value[1]?.i32: whether to paginate by group. The value **0** means to paginate by individual child elements, and **1** means to paginate by groups of child elements displayed within the viewport. The default value is **0**.
**Since**
15
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: number of elements to display within the viewport.
.value[1].i32: whether to paginate by group.
**Since**
15| +| NODE_SWIPER_DISABLE_SWIPE | This interface is used to disable the sliding switching function of the Swiper component. The attribute setting, attribute resetting, and attribute obtaining interfaces are supported.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to disable the swipe feature. The value **1** means to disable the swipe feature, and **0** means the opposite. The default value is **0**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to disable the swipe feature. The value **1** means to disable the swipe feature, and **0** means the opposite. The default value is **0**.| +| NODE_SWIPER_SHOW_DISPLAY_ARROW | Defines whether to show the arrow when the mouse pointer hovers over the navigation indicator. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether to show the arrow when the mouse pointer hovers over the navigation indicator. The parameter type is [ArkUI_SwiperArrow](#arkui_swiperarrow).
The default value is **ARKUI_SWIPER_ARROW_HIDE**.
.?object: style of the arrow displayed when the mouse pointer hovers over the navigation indicator. The parameter type is [ArkUI_SwiperArrowStyle](#arkui_swiperarrowstyle).
**Since**
15
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: indicates whether to display the navigation arrow. The parameter type is [ArkUI_SwiperArrow](#arkui_swiperarrow).
The default value is **ARKUI_SWIPER_ARROW_HIDE**.
.object: style of the arrow displayed when the mouse pointer hovers over the navigation indicator. The parameter type is [ArkUI_SwiperArrowStyle](#arkui_swiperarrowstyle).
**Since**
15 | +| NODE_SWIPER_EDGE_EFFECT_MODE | Defines the effect used at the edges of the swiper when the boundary of the scrollable content is reached. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: effect used at the edges of the swiper when the boundary of the scrollable content is reached. The parameter type is [ArkUI_EdgeEffect](#arkui_edgeeffect).
The default value is **ARKUI_EDGE_EFFECT_SPRING**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: effect used at the edges of the swiper when the boundary of the scrollable content is reached. The parameter type is [ArkUI_EdgeEffect](#arkui_edgeeffect).| +| NODE_SWIPER_NODE_ADAPTER | Defines the swiper adapter. The attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.object: **ArkUI_NodeAdapter** object as the adapter.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: The format of the return value is ArkUI_NodeAdapter.| +| NODE_SWIPER_CACHED_COUNT | Sets the number of cached items in the swiper adapter. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: number of cached items in the swiper adapter.
.value[1]?.i32: whether to show cached items. The value **0** means to hide cached items, and **1** means to show cached items. The default value is **0**.
**Since**
15
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: number of cached items in the list adapter.
.value[1].i32: whether to show cached items. The value **0** means to hide cached items, and **1** means to show cached items.
**Since**
15 | +| NODE_SWIPER_PREV_MARGIN | Sets the previous margin of the swiper. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: previous margin, in vp. The default value is **0**.
.value[1].i32: whether to ignore blank areas. The value **1** means to ignore blank areas, and **0** means the opposite.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: previous margin, in vp. .value[1].i32: whether to ignore blank areas. The value **1** means to ignore blank areas, and **0** means the opposite.| +| NODE_SWIPER_NEXT_MARGIN | Sets the next margin of the swiper. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: next margin, in vp. The default value is **0**.
.value[1].i32: whether to ignore blank areas. The value **1** means to ignore blank areas, and **0** means the opposite.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: next margin, in vp. .value[1].i32: whether to ignore blank areas. The value **1** means to ignore blank areas, and **0** means the opposite.| +| NODE_SWIPER_INDICATOR | Sets the navigation indicator type of the Swiper component. The attribute setting, attribute resetting, and attribute obtaining interfaces are supported.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: navigation indicator type. The parameter type is [ArkUI_SwiperIndicatorType](#arkui_swiperindicatortype).
.object: additional configuration for the navigation indicator, depending on the type. For [ArkUI_SwiperIndicator](#arkui_swiperindicator), the parameter type is [ArkUI_SwiperIndicator](#arkui_swiperindicator).
For **ARKUI_SWIPER_INDICATOR_TYPE_DIGIT**, the parameter type is [ArkUI_SwiperDigitIndicator](#arkui_swiperdigitindicator).

**Since**
15
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: navigation indicator type. The parameter type is [ArkUI_SwiperIndicatorType](#arkui_swiperindicatortype).
.object: additional configuration for the navigation indicator, depending on the type. For [ArkUI_SwiperIndicator](#arkui_swiperindicator), the parameter type is [ArkUI_SwiperIndicator](#arkui_swiperindicator).
For **ARKUI_SWIPER_INDICATOR_TYPE_DIGIT**, the parameter type is [ArkUI_SwiperDigitIndicator](#arkui_swiperdigitindicator).

**Since**
15 | +| NODE_SWIPER_NESTED_SCROLL | Sets the nested scrolling mode of the **Swiper** component and its parent container.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: nested scrolling mode of the Swiper component and parent component. The parameter type is [ArkUI_SwiperNestedScrollMode](#arkui_swipernestedscrollmode).
The default value is **ARKUI_SWIPER_NESTED_SCROLL_SELF_ONLY**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: nested scrolling mode of the Swiper component and parent component. The parameter type is [ArkUI_SwiperNestedScrollMode](#arkui_swipernestedscrollmode).| +| NODE_SWIPER_SWIPE_TO_INDEX | Sets the swiper to switch to the specified page.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: index of the target page in the swiper.
.value[1]?.i32: whether to use an animation for when the target page is reached. The value 1 indicates that the dynamic effect is enabled, and the value 0 indicates that the dynamic effect is disabled. The default value is 0.| +| NODE_SWIPER_INDICATOR_INTERACTIVE | Sets whether the navigation indicator is interactive.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether the navigation indicator is interactive. The default value **true** means that the navigation indicator is interactive.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether the navigation indicator is interactive.| | NODE_SWIPER_PAGE_FLIP_MODE | Sets the page flipping mode using the mouse wheel.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: page flipping mode using the mouse wheel. The parameter type is [ArkUI_PageFlipMode](#arkui_pageflipmode).
Format of the return value [ArkUI_PageFlipMode](#arkui_pageflipmode)):
.value[0].i32: page flipping mode using the mouse wheel.
**Since**
14 | -| NODE_LIST_ITEM_SWIPE_ACTION | Sets the swipe action item displayed when the list item is swiped out from the screen edge. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.object: [ArkUI_ListItemSwipeActionOption](#arkui_listitemswipeactionoption) object.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: [ArkUI_ListItemSwipeActionOption](#arkui_listitemswipeactionoption) object.| -| NODE_LIST_ITEM_GROUP_SET_HEADER | Defines the header of the list item group. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.object: Use the [ArkUI_NodeHandle](#arkui_nodehandle) object as the ListItemGroup header component.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: Use the [ArkUI_NodeHandle](#arkui_nodehandle) object as the ListItemGroup header component.| -| NODE_LIST_ITEM_GROUP_SET_FOOTER | Defines the footer of the list item group. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.object: [ArkUI_NodeHandle](#arkui_nodehandle) object to be used as the footer of the list item group.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: [ArkUI_NodeHandle](#arkui_nodehandle) object to be used as the footer of the list item group.| -| NODE_LIST_ITEM_GROUP_SET_DIVIDER | Defines the style of the divider for the list items. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: color of the divider, in 0xARGB format.
.value[1].f32: stroke width of the divider, in vp.
.value[2].f32: distance between the divider and the start of the list, in vp.
.value[3].f32: distance between the divider and the end of the list, in vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color of the divider, in 0xARGB format.
.value[1].f32: stroke width of the divider, in vp.
.value[2].f32: distance between the divider and the start of the list, in vp.
.value[3].f32: distance between the divider and the end of the list, in vp.| -| NODE_LIST_ITEM_GROUP_CHILDREN_MAIN_SIZE | Sets the default spindle size of the ListItemGroup child component.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
object: **ArkUI_ListChildrenMainSize** object.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: **ArkUI_ListChildrenMainSize** object.| -| NODE_COLUMN_ALIGN_ITEMS | Defines the horizontal alignment mode of child components in the column. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: horizontal alignment format of a child component. The data type is [ArkUI_HorizontalAlignment](#arkui_horizontalalignment).
Default value: **ARKUI_HORIZONTAL_ALIGNMENT_CENTER**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: horizontal alignment format of a child component. The data type is [ArkUI_HorizontalAlignment](#arkui_horizontalalignment).| -| NODE_COLUMN_JUSTIFY_CONTENT | Defines the vertical alignment mode of child components in the column. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: vertical alignment format of the child component. The data type is [ArkUI_FlexAlignment](#arkui_flexalignment).
Default value: **ARKUI_FLEX_ALIGNMENT_START**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: vertical alignment format of a child component. The data type is [ArkUI_FlexAlignment](#arkui_flexalignment).| -| NODE_ROW_ALIGN_ITEMS | Defines the vertical alignment mode of child components in the row. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: vertical alignment format of a child component. The data type is [ArkUI_VerticalAlignment](#arkui_verticalalignment).
Default value: **ARKUI_VERTICAL_ALIGNMENT_CENTER**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: vertical alignment format of a child component. The data type is [ArkUI_VerticalAlignment](#arkui_verticalalignment).| -| NODE_ROW_JUSTIFY_CONTENT | Defines the horizontal alignment mode of child components in the row. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: horizontal alignment format of a child component. The data type is [ArkUI_FlexAlignment](#arkui_flexalignment).
Default value: **ARKUI_FLEX_ALIGNMENT_START**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: horizontal alignment format of a child component. The data type is [ArkUI_FlexAlignment](#arkui_flexalignment).| -| NODE_FLEX_OPTION | Defines the opacity attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0]?.i32: arrangement direction of child components on the Flex container [ArkUI_FlexDirection](#arkui_flexdirection). The default value is ARKUI_FLEX_DIRECTION_ROW.
.value[1]?.i32: arrangement rule [ArkUI_FlexWrap](#arkui_flexwrap). The default value is ARKUI_FLEX_WRAP_NO_WRAP.
.value[2]?.i32: alignment format on the principal axis [ArkUI_FlexAlignment](#arkui_flexalignment). The default value is ARKUI_FLEX_ALIGNMENT_START.
.value[3]?.i32: alignment format on the cross axis [ArkUI_ItemAlignment](#arkui_itemalignment). The default value is ARKUI_ITEM_ALIGNMENT_START.
.value[4]?.i32: alignment mode of multiple lines when there is extra space in the cross axis [ArkUI_FlexAlignment](#arkui_flexalignment). The default value is ARKUI_FLEX_ALIGNMENT_START.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: direction in which flex items are arranged.
.value[1].i32: how the flex items are wrapped.
.value[2].i32: alignment mode along the main axis.
.value[3].i32: alignment mode along the cross axis.
.value[4].i32: alignment mode along the cross axis for multi-line content.| -| NODE_REFRESH_REFRESHING | Sets whether a component is being refreshed. Attributes can be set and obtained.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: The parameter type is 1 or 0.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
value[0].i32: The parameter type is 1 or 0.| -| NODE_REFRESH_CONTENT | Sets the custom content in the pull-down area. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: The parameter type is **ArkUI_NodeHandle**.| -| NODE_REFRESH_PULL_DOWN_RATIO | Sets the pull-down and hand coefficients. The interfaces for setting, resetting, and obtaining attributes are supported.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: pull-down ratio. The value is in the range from 0 to 1.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: pull-down ratio. The value is in the range from 0 to 1.| -| NODE_REFRESH_OFFSET | Sets the pull-down offset that initiates a refresh. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: pull-down offset, in vp. The default value is 64 vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: pull-down offset, in vp. The default value is 64 vp.| -| NODE_REFRESH_PULL_TO_REFRESH | Sets whether to initiate a refresh when the pull-down distance exceeds the value of **refreshOffset**. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to initiate a refresh. The value **true** means to initiate a refresh, and **false** means the opposite.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to initiate a refresh. The value **1** means to initiate a refresh, and **0** means the opposite.| -| NODE_WATER_FLOW_LAYOUT_DIRECTION | Defines the main axis direction of the waterfall component layout. Attributes can be set, reset, and obtained.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: main axis direction. The parameter type is **ArkUI_FlexDirection**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: main axis direction. The parameter type is **ArkUI_FlexDirection**.| -| NODE_WATER_FLOW_COLUMN_TEMPLATE | Sets the number of columns in the water flow layout. If this parameter is not set, one column is used by default. This attribute can be set, reset, and obtained as required through APIs. For example, **'1fr 1fr 2fr'** indicates three columns, with the first column taking up 1/4 of the parent component's full width, the second column 1/4, and the third column 2/4. You can use **columnsTemplate('repeat(auto-fill,track-size)')** to automatically calculate the number of rows based on the specified row height **track-size**. **repeat** and **auto-fill** are keywords. The units for **track-size** can be px, vp (default), %, or a valid number.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: number of layout columns.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: number of layout columns.| -| NODE_WATER_FLOW_ROW_TEMPLATE | Sets the number of rows in the water flow layout. If this parameter is not set, one row is used by default. This attribute can be set, reset, and obtained as required through APIs. For example, **'1fr 1fr 2fr'** indicates three rows, with the first row taking up 1/4 of the parent component's full height, the second row 1/4, and the third row 2/4. You can use **rowsTemplate('repeat(auto-fill,track-size)')** to automatically calculate the number of rows based on the specified row height **track-size**. **repeat** and **auto-fill** are keywords. The units for **track-size** can be px, vp (default), %, or a valid number.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: number of layout rows.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: number of layout rows.| -| NODE_WATER_FLOW_COLUMN_GAP | Sets the gap between columns. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: gap between columns, in vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: gap between columns, in vp.| -| NODE_WATER_FLOW_ROW_GAP | Sets the gap between rows. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: gap between lines, in vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: gap between lines, in vp.| -| NODE_WATER_FLOW_SECTION_OPTION | Defines the water flow section configuration. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: zero-based index of the water flow item section to update. The value is converted to an integer.
.object: **ArkUI_WaterFlowSectionOption** object.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: **ArkUI_WaterFlowSectionOption** object.| -| NODE_WATER_FLOW_NODE_ADAPTER | Defines the water flow adapter. The attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.object: **ArkUI_NodeAdapter** object as the adapter.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: **ArkUI_NodeAdapter** object.| +| NODE_SWIPER_AUTO_FILL | Configures the **Swiper** component to automatically adjust the number of elements displayed per page based on the minimum width of the elements. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: minimum width of the elements to be displayed, in vp.
.value[1]?.i32: whether to paginate by group. The value **0** means to paginate by individual child elements, and **1** means to paginate by groups of child elements displayed within the viewport. The default value is **0**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: minimum width of the elements to be displayed, in vp.
.value[1].i32: whether to paginate by group.
**Since**
15 | +| NODE_LIST_ITEM_SWIPE_ACTION | Sets the swipe action item displayed when the list item is swiped out from the screen edge. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.object: [ArkUI_ListItemSwipeActionOption](#arkui_listitemswipeactionoption) object.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: [ArkUI_ListItemSwipeActionOption](#arkui_listitemswipeactionoption) object.| +| NODE_LIST_ITEM_GROUP_SET_HEADER | Defines the header of the list item group. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.object: Use the [ArkUI_NodeHandle](#arkui_nodehandle) object as the ListItemGroup header component.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: Use the [ArkUI_NodeHandle](#arkui_nodehandle) object as the ListItemGroup header component.| +| NODE_LIST_ITEM_GROUP_SET_FOOTER | Defines the footer of the list item group. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.object: [ArkUI_NodeHandle](#arkui_nodehandle) object to be used as the footer of the list item group.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: [ArkUI_NodeHandle](#arkui_nodehandle) object to be used as the footer of the list item group.| +| NODE_LIST_ITEM_GROUP_SET_DIVIDER | Defines the style of the divider for the list items. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].u32: color of the divider, in 0xARGB format.
.value[1].f32: stroke width of the divider, in vp.
.value[2].f32: distance between the divider and the start of the list, in vp.
.value[3].f32: distance between the divider and the end of the list, in vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].u32: color of the divider, in 0xARGB format.
.value[1].f32: stroke width of the divider, in vp.
.value[2].f32: distance between the divider and the start of the list, in vp.
.value[3].f32: distance between the divider and the end of the list, in vp.| +| NODE_LIST_ITEM_GROUP_CHILDREN_MAIN_SIZE | Sets the default spindle size of the ListItemGroup child component.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
object: **ArkUI_ListChildrenMainSize** object.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: The parameter format is **ArkUI_ListChildrenMainSize**.| +| NODE_LIST_ITEM_GROUP_NODE_ADAPTER | Defines the list item group adapter. The attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.object: **ArkUI_NodeAdapter** object as the adapter.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: **ArkUI_NodeAdapter** object. | +| NODE_COLUMN_ALIGN_ITEMS | Defines the horizontal alignment mode of child components in the column. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: horizontal alignment format of a child component. The data type is [ArkUI_HorizontalAlignment](#arkui_horizontalalignment).
Default value: **ARKUI_HORIZONTAL_ALIGNMENT_CENTER**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: horizontal alignment format of a child component. The data type is [ArkUI_HorizontalAlignment](#arkui_horizontalalignment).| +| NODE_COLUMN_JUSTIFY_CONTENT | Defines the vertical alignment mode of child components in the column. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: vertical alignment format of the child component. The data type is [ArkUI_FlexAlignment](#arkui_flexalignment).
Default value: **ARKUI_FLEX_ALIGNMENT_START**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: vertical alignment format of a child component. The data type is [ArkUI_FlexAlignment](#arkui_flexalignment).| +| NODE_ROW_ALIGN_ITEMS | Defines the vertical alignment mode of child components in the row. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: vertical alignment format of a child component. The data type is [ArkUI_VerticalAlignment](#arkui_verticalalignment).
Default value: **ARKUI_VERTICAL_ALIGNMENT_CENTER**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: vertical alignment format of a child component. The data type is [ArkUI_VerticalAlignment](#arkui_verticalalignment).| +| NODE_ROW_JUSTIFY_CONTENT | Defines the horizontal alignment mode of child components in the row. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: horizontal alignment format of a child component. The data type is [ArkUI_FlexAlignment](#arkui_flexalignment).
Default value: **ARKUI_FLEX_ALIGNMENT_START**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: horizontal alignment format of a child component. The data type is [ArkUI_FlexAlignment](#arkui_flexalignment).| +| NODE_FLEX_OPTION | Defines the opacity attribute, which can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0]?.i32: arrangement direction of child components on the Flex container [ArkUI_FlexDirection](#arkui_flexdirection). The default value is ARKUI_FLEX_DIRECTION_ROW.
.value[1]?.i32: arrangement rule [ArkUI_FlexWrap](#arkui_flexwrap). The default value is ARKUI_FLEX_WRAP_NO_WRAP.
.value[2]?.i32: alignment format on the principal axis [ArkUI_FlexAlignment](#arkui_flexalignment). The default value is ARKUI_FLEX_ALIGNMENT_START.
.value[3]?.i32: alignment format on the cross axis [ArkUI_ItemAlignment](#arkui_itemalignment). The default value is ARKUI_ITEM_ALIGNMENT_START.
.value[4]?.i32: alignment mode of multiple lines when there is extra space in the cross axis [ArkUI_FlexAlignment](#arkui_flexalignment). The default value is ARKUI_FLEX_ALIGNMENT_START.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: direction in which flex items are arranged.
.value[1].i32: how the flex items are wrapped.
.value[2].i32: alignment mode along the main axis.
.value[3].i32: alignment mode along the cross axis.
.value[4].i32: alignment mode along the cross axis for multi-line content.| +| NODE_REFRESH_REFRESHING | Sets whether a component is being refreshed. Attributes can be set and obtained.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: The parameter type is 1 or 0.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
value[0].i32: The parameter type is 1 or 0.| +| NODE_REFRESH_CONTENT | Sets the custom content in the pull-down area. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: The parameter type is **ArkUI_NodeHandle**.| +| NODE_REFRESH_PULL_DOWN_RATIO | Sets the pull-down and hand coefficients. The interfaces for setting, resetting, and obtaining attributes are supported.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: pull-down ratio. The value is in the range from 0 to 1.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: pull-down ratio. The value is in the range from 0 to 1.| +| NODE_REFRESH_OFFSET | Sets the pull-down offset that initiates a refresh. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: pull-down offset, in vp. The default value is 64 vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: pull-down offset, in vp. The default value is 64 vp.| +| NODE_REFRESH_PULL_TO_REFRESH | Sets whether to initiate a refresh when the pull-down distance exceeds the value of **refreshOffset**. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to initiate a refresh. The value **true** means to initiate a refresh, and **false** means the opposite.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether to initiate a refresh. The value **1** means to initiate a refresh, and **0** means the opposite.| +| NODE_WATER_FLOW_LAYOUT_DIRECTION | Defines the main axis direction of the waterfall component layout. Attributes can be set, reset, and obtained.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: main axis direction. The parameter type is **ArkUI_FlexDirection**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: main axis direction. The parameter type is **ArkUI_FlexDirection**.| +| NODE_WATER_FLOW_COLUMN_TEMPLATE | Sets the number of columns in the water flow layout. If this parameter is not set, one column is used by default. This attribute can be set, reset, and obtained as required through APIs. For example, **'1fr 1fr 2fr'** indicates three columns, with the first column taking up 1/4 of the parent component's full width, the second column 1/4, and the third column 2/4. You can use **columnsTemplate('repeat(auto-fill,track-size)')** to automatically calculate the number of rows based on the specified row height **track-size**. **repeat** and **auto-fill** are keywords. The units for **track-size** can be px, vp (default), %, or a valid number.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: number of layout columns.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: number of layout columns.| +| NODE_WATER_FLOW_ROW_TEMPLATE | Sets the number of rows in the water flow layout. If this parameter is not set, one row is used by default. This attribute can be set, reset, and obtained as required through APIs. For example, **'1fr 1fr 2fr'** indicates three rows, with the first row taking up 1/4 of the parent component's full height, the second row 1/4, and the third row 2/4. You can use **rowsTemplate('repeat(auto-fill,track-size)')** to automatically calculate the number of rows based on the specified row height **track-size**. **repeat** and **auto-fill** are keywords. The units for **track-size** can be px, vp (default), %, or a valid number.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: number of layout rows.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: number of layout rows.| +| NODE_WATER_FLOW_COLUMN_GAP | Sets the gap between columns. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: gap between columns, in vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: gap between columns, in vp.| +| NODE_WATER_FLOW_ROW_GAP | Sets the gap between rows. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: gap between lines, in vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: gap between lines, in vp.| +| NODE_WATER_FLOW_SECTION_OPTION | Defines the water flow section configuration. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: zero-based index of the water flow item section to update. The value is converted to an integer.
.object: **ArkUI_WaterFlowSectionOption** object.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: **ArkUI_WaterFlowSectionOption** object.| +| NODE_WATER_FLOW_NODE_ADAPTER | Defines the water flow adapter. The attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.object: **ArkUI_NodeAdapter** object as the adapter.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: **ArkUI_NodeAdapter** object.| | NODE_WATER_FLOW_CACHED_COUNT | Sets the number of cached items in the water flow adapter. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: number of cached items in the water flow adapter.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: number of cached items in the list adapter.| -| NODE_WATER_FLOW_FOOTER | Sets the custom footer for the water flow container.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: custom footer. The parameter type is [ArkUI_NodeHandle](#arkui_nodehandle).| -| NODE_WATER_FLOW_SCROLL_TO_INDEX | Scrolls to the item with the specified index.
When **smooth** is set to **true**, all passed items are loaded and counted in layout calculation. This may result in performance issues if a large number of items are involved.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: index of the item to be scrolled to in the container.
.value[1]?.i32: whether to enable the smooth animation for scrolling to the item with the specified index. The value **1** means to enable the animation, and **0** means the opposite. The default value is **0**.
.value[2]?.i32: how the item to scroll to is aligned with the container. The parameter type is [ArkUI_ScrollAlignment](#arkui_scrollalignment). The default value is **ARKUI_SCROLL_ALIGNMENT_START**.| -| NODE_WATER_FLOW_ITEM_CONSTRAINT_SIZE | Defines the size constraints to apply to water flow items. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: minimum width. The value **-1** indicates that the minimum width is not set.
.value[1].f32: maximum width. The value **-1** indicates that the maximum width is not set.
.value[2].f32: minimum height. The value **-1** indicates that the minimum height is not set.
.value[3].f32: maximum height. The value **-1** indicates that the maximum height is not set.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: minimum width. The value **-1** indicates that the minimum width is not set.
.value[1].f32: maximum width. The value **-1** indicates that the maximum width is not set.
.value[2].f32: minimum height. The value **-1** indicates that the minimum height is not set.
.value[3].f32: maximum height. The value **-1** indicates that the maximum height is not set. | -| NODE_RELATIVE_CONTAINER_GUIDE_LINE | Sets the guideline in the **RelativeContainer**. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.object: guideline in the **RelativeContainer**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: guideline in the **RelativeContainer**.| -| NODE_RELATIVE_CONTAINER_BARRIER | Sets the barrier in the **RelativeContainer**. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.object: guideline in the **RelativeContainer**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: barrier in the **RelativeContainer** component.| -| NODE_GRID_COLUMN_TEMPLATE | Sets the number of columns in the water flow layout. If this parameter is not set, one column is used by default. This attribute can be set, reset, and obtained as required through APIs. For example, **'1fr 1fr 2fr'** indicates three columns, with the first column taking up 1/4 of the parent component's full width, the second column 1/4, and the third column 2/4. You can use **columnsTemplate('repeat(auto-fill,track-size)')** to automatically calculate the number of rows based on the specified row height **track-size**. **repeat** and **auto-fill** are keywords. The units for **track-size** can be px, vp (default), %, or a valid number.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: number of layout columns.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: number of layout columns.| -| NODE_GRID_ROW_TEMPLATE | Sets the number of rows or the minimum row height in the grid layout. If this parameter is not set, one row is used by default. This attribute can be set, reset, and obtained as required through APIs. For example, **'1fr 1fr 2fr'** indicates three rows, with the first row taking up 1/4 of the parent component's full height, the second row 1/4, and the third row 2/4. You can use **rowsTemplate('repeat(auto-fill,track-size)')** to automatically calculate the number of rows based on the specified row height **track-size**. **repeat** and **auto-fill** are keywords. The units for **track-size** can be px, vp (default), %, or a valid number.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: number of layout rows.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: number of layout rows.| -| NODE_GRID_COLUMN_GAP | Sets the gap between columns. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: gap between columns, in vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: gap between columns, in vp.| -| NODE_GRID_ROW_GAP | Sets the gap between rows. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: gap between lines, in vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: gap between lines, in vp.| -| NODE_GRID_NODE_ADAPTER | Defines the grid adapter. The attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.object: **ArkUI_NodeAdapter** object as the adapter.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: The format of the return value is ArkUI_NodeAdapter.| -| NODE_GRID_CACHED_COUNT | Sets the number of cached items in the grid adapter. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: number of cached items in the water flow adapter. | +| NODE_WATER_FLOW_FOOTER | Sets the custom footer for the water flow container.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: custom footer. The parameter type is [ArkUI_NodeHandle](#arkui_nodehandle).| +| NODE_WATER_FLOW_SCROLL_TO_INDEX | Scrolls to the item with the specified index.
When **smooth** is set to **true**, all passed items are loaded and counted in layout calculation. This may result in performance issues if a large number of items are involved.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: index of the item to be scrolled to in the container.
.value[1]?.i32: whether to enable the smooth animation for scrolling to the item with the specified index. The value **1** means to enable the animation, and **0** means the opposite. The default value is **0**.
.value[2]?.i32: how the item to scroll to is aligned with the container. The parameter type is [ArkUI_ScrollAlignment](#arkui_scrollalignment). The default value is **ARKUI_SCROLL_ALIGNMENT_START**.| +| NODE_WATER_FLOW_ITEM_CONSTRAINT_SIZE | Defines the size constraints to apply to water flow items. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: minimum width. The value **-1** indicates that the minimum width is not set.
.value[1].f32: maximum width. The value **-1** indicates that the maximum width is not set.
.value[2].f32: minimum height. The value **-1** indicates that the minimum height is not set.
.value[3].f32: maximum height. The value **-1** indicates that the maximum height is not set.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: minimum width. The value **-1** indicates that the minimum width is not set.
.value[1].f32: maximum width. The value **-1** indicates that the maximum width is not set.
.value[2].f32: minimum height. The value **-1** indicates that the minimum height is not set.
.value[3].f32: maximum height. The value **-1** indicates that the maximum height is not set. | +| NODE_RELATIVE_CONTAINER_GUIDE_LINE | Sets the guideline in the **RelativeContainer**. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.object: guideline in the **RelativeContainer**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: guideline in the **RelativeContainer**.| +| NODE_RELATIVE_CONTAINER_BARRIER | Sets the barrier in the **RelativeContainer**. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.object: guideline in the **RelativeContainer**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: barrier in the **RelativeContainer** component.| +| NODE_GRID_COLUMN_TEMPLATE | Sets the number of columns in the water flow layout. If this parameter is not set, one column is used by default. This attribute can be set, reset, and obtained as required through APIs. For example, **'1fr 1fr 2fr'** indicates three columns, with the first column taking up 1/4 of the parent component's full width, the second column 1/4, and the third column 2/4. You can use **columnsTemplate('repeat(auto-fill,track-size)')** to automatically calculate the number of rows based on the specified row height **track-size**. **repeat** and **auto-fill** are keywords. The units for **track-size** can be px, vp (default), %, or a valid number.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: number of layout columns.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: number of layout columns.| +| NODE_GRID_ROW_TEMPLATE | Sets the number of rows or the minimum row height in the grid layout. If this parameter is not set, one row is used by default. This attribute can be set, reset, and obtained as required through APIs. For example, **'1fr 1fr 2fr'** indicates three rows, with the first row taking up 1/4 of the parent component's full height, the second row 1/4, and the third row 2/4. You can use **rowsTemplate('repeat(auto-fill,track-size)')** to automatically calculate the number of rows based on the specified row height **track-size**. **repeat** and **auto-fill** are keywords. The units for **track-size** can be px, vp (default), %, or a valid number.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: number of layout rows.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.string: number of layout rows.| +| NODE_GRID_COLUMN_GAP | Sets the gap between columns. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: gap between columns, in vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: gap between columns, in vp.| +| NODE_GRID_ROW_GAP | Sets the gap between rows. This attribute can be set, reset, and obtained as required through APIs.
Parameter format of the attribute setting method [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: gap between lines, in vp.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: gap between lines, in vp.| +| NODE_GRID_NODE_ADAPTER | Defines the grid adapter. The attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.object: **ArkUI_NodeAdapter** object as the adapter.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.object: The format of the return value is ArkUI_NodeAdapter.| +| NODE_GRID_CACHED_COUNT | Sets the number of cached items in the grid adapter. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: number of cached items in the water flow adapter. | | NODE_TEXT_PICKER_COLUMN_WIDTHS16+ | Sets the width of columns in the picker.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: width of the first column, specified as a percentage of the total width. By default, all columns have equal widths.
.value[1]?.f32: width of the second column, specified as a percentage of the total width. By default, all columns have equal widths.
.value[2]?.f32: width of the third column, specified as a percentage of the total width. By default, all columns have equal widths.
...
.value[n]?.f32: width of the (n+1)-th column, specified as a percentage of the total width. By default, all columns have equal widths.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: width of the first column as a percentage of the total width.
.value[1].f32: width of the second column as a percentage of the total width.
.value[2].f32: width of the third column as a percentage of the total width.
...
.value[n].f32: width of the (n+1)-th column as a percentage of the total width.| -| NODE_IMAGE_ANIMATOR_IMAGES | Sets the image frame information set of the frame animation component. Dynamic update is not supported. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.size: number of image frames;
.object: image frame array. The parameter type is **ArkUI_ImageAnimatorFrameInfo**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.size: number of image frames;
.object: image frame array. The parameter type is **ArkUI_ImageAnimatorFrameInfo**. | -| NODE_IMAGE_ANIMATOR_STATE | Sets the playback status of the frame-by-frame animation. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: controls the playing status of the animation. The parameter type is [ArkUI_AnimationStatus](#arkui_animationstatus). The default value is the initial status.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: controls the playing status of the animation. The parameter type is [ArkUI_AnimationStatus](#arkui_animationstatus).| -| NODE_IMAGE_ANIMATOR_DURATION | Sets the playback duration of the frame-by-frame animation. This attribute does not take effect when a separate duration is set for any of the image frames. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: playback duration, in milliseconds. The default value is **1000**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: playback duration, in milliseconds. The default value is **1000**.| -| NODE_IMAGE_ANIMATOR_REVERSE | Sets the playback direction of the frame-by-frame animation. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: playback direction. The value **0** indicates that images are played from the first one to the last one, and **1** indicates that images are played from the last one to the first one. The default value is **0**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: playback direction. The value **0** indicates that images are played from the first one to the last one, and **1** indicates that images are played from the last one to the first one.| -| NODE_IMAGE_ANIMATOR_FIXED_SIZE | Sets whether the image size is fixed at the component size.
This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether the image size is the fixed at the component size. The value **1** indicates that the image size is fixed at the component size. The value **0** indicates that the width, height, top, and left attributes of each image must be set separately. The default value is **1**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether the image size is the fixed at the component size. The value **1** indicates that the image size is fixed at the component size. The value **0** indicates that the width, height, top, and left attributes of each image must be set separately.| -| NODE_IMAGE_ANIMATOR_FILL_MODE | Sets the status before and after execution of the frame-by-frame animation in the current playback direction. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: status before and after execution of the frame-by-frame animation in the current playback direction. The parameter type is **ArkUI_AnimationFillMode**. The default value is **FORWARDS**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: status before and after execution of the frame-by-frame animation in the current playback direction. The parameter type is **ArkUI_AnimationFillMode**.| -| NODE_IMAGE_ANIMATOR_ITERATION | Sets the number of times that the frame-by-frame animation is played. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: number of times that the animation is played.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: number of times that the animation is played. | +| NODE_IMAGE_ANIMATOR_IMAGES | Sets the image frame information set of the frame animation component. Dynamic update is not supported. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.size: number of image frames;
.object: image frame array. The parameter type is **ArkUI_ImageAnimatorFrameInfo**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.size: number of image frames;
.object: image frame array. The parameter type is **ArkUI_ImageAnimatorFrameInfo**. | +| NODE_IMAGE_ANIMATOR_STATE | Sets the playback status of the frame-by-frame animation. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: controls the playing status of the animation. The parameter type is [ArkUI_AnimationStatus](#arkui_animationstatus). The default value is the initial status.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: controls the playing status of the animation. The parameter type is [ArkUI_AnimationStatus](#arkui_animationstatus).| +| NODE_IMAGE_ANIMATOR_DURATION | Sets the playback duration of the frame-by-frame animation. This attribute does not take effect when a separate duration is set for any of the image frames. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: playback duration, in milliseconds. The default value is **1000**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: playback duration, in milliseconds. The default value is **1000**.| +| NODE_IMAGE_ANIMATOR_REVERSE | Sets the playback direction of the frame-by-frame animation. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: playback direction. The value **0** indicates that images are played from the first one to the last one, and **1** indicates that images are played from the last one to the first one. The default value is **0**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: playback direction. The value **0** indicates that images are played from the first one to the last one, and **1** indicates that images are played from the last one to the first one.| +| NODE_IMAGE_ANIMATOR_FIXED_SIZE | Whether the image size is fixed at the component size.
This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: whether the image size is the fixed at the component size. The value **1** indicates that the image size is fixed at the component size. The value **0** indicates that the width, height, top, and left attributes of each image must be set separately. The default value is **1**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: whether the image size is the fixed at the component size. The value **1** indicates that the image size is fixed at the component size. The value **0** indicates that the width, height, top, and left attributes of each image must be set separately.| +| NODE_IMAGE_ANIMATOR_FILL_MODE | Sets the status before and after execution of the frame-by-frame animation in the current playback direction. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: status before and after execution of the frame-by-frame animation in the current playback direction. The parameter type is **ArkUI_AnimationFillMode**. The default value is **FORWARDS**.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: status before and after execution of the frame-by-frame animation in the current playback direction. The parameter type is **ArkUI_AnimationFillMode**.| +| NODE_IMAGE_ANIMATOR_ITERATION | Sets the number of times that the frame-by-frame animation is played. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].i32: number of times that the animation is played.
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].i32: number of times that the animation is played.| +| NODE_BACKDROP_BLUR | Sets the background blur effect. This attribute can be set, reset, and obtained as required through APIs.
Format of the [ArkUI_AttributeItem](_ark_u_i___attribute_item.md) parameter for setting the attribute:
.value[0].f32: background blur radius. The value range is [0, +∞). The unit is px. The default value is **0.0**.
.value[1]?.f32: brightness of black in the grayscale blur. The value range is [0, 127].
.value[2]?.f32: degree of darkening the white color in the grayscale blur. The value range is [0, 127].
Format of the return value [ArkUI_AttributeItem](_ark_u_i___attribute_item.md):
.value[0].f32: background blur radius. The value range is [0, +∞). The unit is px.
.value[1].f32: brightness of black in the grayscale blur. The value range is [0, 127].
.value[2].f32: degree of darkening the white color in the grayscale blur. The value range is [0, 127].| + ### ArkUI_DatePickerMode @@ -3436,10 +3737,10 @@ Defines the NodeContent event type. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| NODE_CONTENT_EVENT_ON_ATTACH_TO_WINDOW | Attach event. | -| NODE_CONTENT_EVENT_ON_DETACH_FROM_WINDOW | Detach event. | +| NODE_CONTENT_EVENT_ON_ATTACH_TO_WINDOW | Attach event. | +| NODE_CONTENT_EVENT_ON_DETACH_FROM_WINDOW | Detach event. | ### ArkUI_NodeCustomEventType @@ -3453,13 +3754,13 @@ Enumerates the custom component event types. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_NODE_CUSTOM_EVENT_ON_MEASURE | Measure. | -| ARKUI_NODE_CUSTOM_EVENT_ON_LAYOUT | Layout. | -| ARKUI_NODE_CUSTOM_EVENT_ON_DRAW | Draw. | -| ARKUI_NODE_CUSTOM_EVENT_ON_FOREGROUND_DRAW | Foreground. | -| ARKUI_NODE_CUSTOM_EVENT_ON_OVERLAY_DRAW | Overlay. | +| ARKUI_NODE_CUSTOM_EVENT_ON_MEASURE | Measure. | +| ARKUI_NODE_CUSTOM_EVENT_ON_LAYOUT | Layout. | +| ARKUI_NODE_CUSTOM_EVENT_ON_DRAW | Draw. | +| ARKUI_NODE_CUSTOM_EVENT_ON_FOREGROUND_DRAW | Foreground. | +| ARKUI_NODE_CUSTOM_EVENT_ON_OVERLAY_DRAW | Overlay. | ### ArkUI_NodeDirtyFlag @@ -3472,11 +3773,11 @@ Enumerates the dirty area flags passed in the **::markDirty** API. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | | NODE_NEED_MEASURE | Remeasure.
When this type of flag is specified, re-layout is triggered by default.| -| NODE_NEED_LAYOUT | Re-layout. | -| NODE_NEED_RENDER | Re-rendering. | +| NODE_NEED_LAYOUT | Re-layout. | +| NODE_NEED_RENDER | Re-rendering. | ### ArkUI_NodeEventType @@ -3490,101 +3791,109 @@ Enumerates the event types supported by the NativeNode component. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| NODE_TOUCH_EVENT | Gesture event.
When the event callback occurs, the union type in the event parameter [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_UIInputEvent](_ark_u_i___event_module.md#arkui_uiinputevent).| -| NODE_EVENT_ON_APPEAR | Mount event.
This event is triggered when the component is mounted to the component tree and displayed.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) does not contain parameters.| -| NODE_EVENT_ON_DISAPPEAR | Unmount event.
This event is triggered when the component is unmounted from the component tree and disappears.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) does not contain parameters.| -| NODE_EVENT_ON_AREA_CHANGE | Component area change event.
This event is triggered when the component's size, position, or any other attribute that may affect its display area changes.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].f32: original width of the target element, in vp. The value is a number.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].f32: original height of the target element, in vp. The value is a number.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[2].f32: X coordinate of the upper left corner of the target element relative to the upper left corner of the parent element. The value type is number and the unit is vp.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[3].f32: Y-axis coordinate of the upper left corner of the target element relative to the upper left corner of the parent element. The value type is number, and the unit is vp.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[4].f32: X coordinate of the upper left corner of the target element relative to the upper left corner of the page. The value type is number, and the unit is vp.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[5].f32: Y coordinate of the upper left corner of the target element relative to the upper left corner of the page. The value type is number, and the unit is vp.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[6].f32: new width of the target element, in vp. The value is a number.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].f32: original height of the target element, in vp. The value is a number.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[8].f32: X coordinate of the upper left corner of the latest target element relative to the upper left corner of the parent element. The value type is number and the unit is vp.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[9].f32: Y coordinate of the upper left corner of the latest target element relative to the upper left corner of the parent element. The value type is number, and the unit is vp.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[10].f32: X coordinate of the upper left corner of the latest target element relative to the upper left corner of the page. The value type is number, and the unit is vp.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[11].f32: Y coordinate of the upper left corner of the latest target element relative to the upper left corner of the page. The value type is number, and the unit is vp.| -| NODE_ON_FOCUS | Event of obtaining the focus.
This event is triggered when the component obtains the focus.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) does not contain parameters.| -| NODE_ON_BLUR | Event of losing the focus.
This event is triggered when the component loses the focus.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) does not contain parameters.| +| NODE_TOUCH_EVENT | Gesture event.
When the event callback occurs, the union type in the event parameter [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_UIInputEvent](_ark_u_i___event_module.md#arkui_uiinputevent).| +| NODE_EVENT_ON_APPEAR | Mount event.
This event is triggered when the component is mounted to the component tree and displayed.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) does not contain parameters.| +| NODE_EVENT_ON_DISAPPEAR | Unmount event.
This event is triggered when the component is unmounted from the component tree and disappears.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) does not contain parameters.| +| NODE_EVENT_ON_AREA_CHANGE | Component area change event.
This event is triggered when the component's size, position, or any other attribute that may affect its display area changes.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].f32: original width of the target element, in vp. The value is a number.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].f32: original height of the target element, in vp. The value is a number.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[2].f32: X coordinate of the upper left corner of the target element relative to the upper left corner of the parent element. The value type is number and the unit is vp.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[3].f32: Y-axis coordinate of the upper left corner of the target element relative to the upper left corner of the parent element. The value type is number, and the unit is vp.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[4].f32: X coordinate of the upper left corner of the target element relative to the upper left corner of the page. The value type is number, and the unit is vp.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[5].f32: Y coordinate of the upper left corner of the target element relative to the upper left corner of the page. The value type is number, and the unit is vp.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[6].f32: new width of the target element, in vp. The value is a number.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].f32: original height of the target element, in vp. The value is a number.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[8].f32: X coordinate of the upper left corner of the latest target element relative to the upper left corner of the parent element. The value type is number and the unit is vp.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[9].f32: Y coordinate of the upper left corner of the latest target element relative to the upper left corner of the parent element. The value type is number, and the unit is vp.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[10].f32: X coordinate of the upper left corner of the latest target element relative to the upper left corner of the page. The value type is number, and the unit is vp.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[11].f32: Y coordinate of the upper left corner of the latest target element relative to the upper left corner of the page. The value type is number, and the unit is vp.| +| NODE_ON_FOCUS | Event of obtaining the focus.
This event is triggered when the component obtains the focus.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) does not contain parameters.| +| NODE_ON_BLUR | Event of losing the focus.
This event is triggered when the component loses the focus.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) does not contain parameters.| | NODE_ON_CLICK | Click event.
This event is triggered when the component is clicked.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
**[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].f32**: X coordinate of the click relative to the upper left corner of the clicked component's original area, in px.
**[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].f32**: Y coordinate of the click relative to the upper left corner of the clicked component's original area, in px.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[2].f32: event timestamp. It is the interval between the time when the event is triggered and the time when the system starts, in microseconds.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[3].i32: event input device. The value 1 indicates the mouse, 2 indicates the touchscreen, and 4 indicates the key.
**[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[4].f32**: X coordinate of the click relative to the upper left corner of the application window, in px.
**[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[5].f32**: Y coordinate of the click relative to the upper left corner of the application window, in px.
**[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[6].f32**: X coordinate of the click relative to the upper left corner of the application screen, in px.
**[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[7].f32**: Y coordinate of the click relative to the upper left corner of the application screen, in px.| -| NODE_ON_TOUCH_INTERCEPT | Custom component event interception.
This event is triggered when the component is clicked.
When the event callback occurs, the union type in the event parameter [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_UIInputEvent](_ark_u_i___event_module.md#arkui_uiinputevent).| -| NODE_EVENT_ON_VISIBLE_AREA_CHANGE | Visible area change event.
This event is triggered when the ratio of the component's visible area to its total area is greater than or less than the threshold. Before registering the event, you need to use **NODE_VISIBLE_AREA_CHANGE_RATIO** to configure the threshold.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: whether the component's visible area has increased or decreased relative to its total area since the last update. The value **1** indicates that the visible area has increased, and **0** indicates that the visible area has decreased.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].f32: ratio of the component's visible area to its total area at the time the callback is triggered.| -| NODE_ON_HOVER | Called when the mouse pointer is moved over or away from the component.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: indicates whether the mouse pointer is hovered over the component. The value 1 indicates that the mouse pointer is hovered over the component, and the value 0 indicates that the mouse pointer is hovered over the component.| -| NODE_ON_MOUSE | Mouse event.
This event is triggered when the component is clicked by a mouse device button or when the mouse pointer moves within the component.
When the event callback occurs, the union type in the event parameter [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_UIInputEvent](_ark_u_i___event_module.md#arkui_uiinputevent).| -| NODE_EVENT_ON_ATTACH | Attach event.
This event is triggered when the component is attached to the component tree.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) does not contain parameters.| -| NODE_EVENT_ON_DETACH | Detach event.
This event is triggered when the component is detached from the component tree.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) does not contain parameters.| -| NODE_ON_ACCESSIBILITY_ACTIONS | Accessibility action.
This event is triggered when an accessibility action is performed after the corresponding accessibility action type is set.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].u32:: operation type for triggering callback. The parameter type is [ArkUI_AccessibilityActionType](#arkui_accessibilityactiontype).| -| NODE_ON_PRE_DRAG | Notifies the listener of the interaction state prior to a drop and drop operation.
This event is triggered when a component is draggable and when a long press, lift, or drag initiation occurs.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: corresponds to [ArkUI_PreDragStatus](#arkui_predragstatus).| -| NODE_ON_DRAG_START | Called when the user starts to drag an item.
A drag operation is recognized only when the dragged item is moved far enough.
When the event callback occurs, you can obtain [ArkUI_DragEvent](#arkui_dragevent) from the [ArkUI_NodeEvent](#arkui_nodeevent-12) object.| -| NODE_ON_DRAG_ENTER | Called when a dragged item enters the boundaries of the current component.
The current component refers to the component that listens for this event.
When the event callback occurs, you can obtain [ArkUI_DragEvent](#arkui_dragevent) from the [ArkUI_NodeEvent](#arkui_nodeevent-12) object.| -| NODE_ON_DRAG_MOVE | Called when a dragged item moves in the current component.
The current component refers to the component that listens for this event.
When the event callback occurs, you can obtain [ArkUI_DragEvent](#arkui_dragevent) from the [ArkUI_NodeEvent](#arkui_nodeevent-12) object.| -| NODE_ON_DRAG_LEAVE | Called when a dragged item leaves the boundaries of the current component.
The current component refers to the component that listens for this event.
When the event callback occurs, you can obtain [ArkUI_DragEvent](#arkui_dragevent) from the [ArkUI_NodeEvent](#arkui_nodeevent-12) object.| -| NODE_ON_DROP | Called when a dragged item is dropped on the current component. The component can obtain the drag data for processing through the callback.
The current component refers to the component that listens for this event.
When the event callback occurs, you can obtain [ArkUI_DragEvent](#arkui_dragevent) from the [ArkUI_NodeEvent](#arkui_nodeevent-12) object.| -| NODE_ON_DRAG_END | Called when a drag operation ends. The drag source can obtain the drag result by registering this callback.
A drag operation ends when the dragged item is released. When the event callback occurs, the [ArkUI_DragEvent](#arkui_dragevent) object can be obtained from the [ArkUI_NodeEvent](#arkui_nodeevent-12) object.| +| NODE_ON_CLICK_EVENT | Click event.
This event is triggered when the component is clicked.
When the event callback occurs, the union type in the event parameter [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_UIInputEvent](_ark_u_i___event_module.md#arkui_uiinputevent).| +| NODE_ON_TOUCH_INTERCEPT | Custom component event interception.
This event is triggered when the component is clicked.
When the event callback occurs, the union type in the event parameter [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_UIInputEvent](_ark_u_i___event_module.md#arkui_uiinputevent).| +| NODE_EVENT_ON_VISIBLE_AREA_CHANGE | Visible area change event.
This event is triggered when the ratio of the component's visible area to its total area is greater than or less than the threshold. Before registering the event, you need to use **NODE_VISIBLE_AREA_CHANGE_RATIO** to configure the threshold.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: whether the component's visible area has increased or decreased relative to its total area since the last update. The value **1** indicates that the visible area has increased, and **0** indicates that the visible area has decreased.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].f32: ratio of the component's visible area to its total area at the time the callback is triggered.| +| NODE_ON_HOVER | Called when the mouse pointer is moved over or away from the component.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: indicates whether the mouse pointer is hovered over the component. The value 1 indicates that the mouse pointer is hovered over the component, and the value 0 indicates that the mouse pointer is hovered over the component.| +| NODE_ON_HOVER_EVENT | Called when the mouse pointer is moved over or away from the component.
When the event callback occurs, the union type in the event parameter [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_UIInputEvent](_ark_u_i___event_module.md#arkui_uiinputevent).| +| NODE_ON_MOUSE | Mouse event.
This event is triggered when the component is clicked by a mouse device button or when the mouse pointer moves within the component.
When the event callback occurs, the union type in the event parameter [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_UIInputEvent](_ark_u_i___event_module.md#arkui_uiinputevent).| +| NODE_EVENT_ON_ATTACH | Attach event.
This event is triggered when the component is attached to the component tree.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) does not contain parameters.| +| NODE_EVENT_ON_DETACH | Detach event.
This event is triggered when the component is detached from the component tree.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) does not contain parameters.| +| NODE_ON_ACCESSIBILITY_ACTIONS | Accessibility action.
This event is triggered when an accessibility action is performed after the corresponding accessibility action type is set.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].u32:: operation type for triggering callback. The parameter type is [ArkUI_AccessibilityActionType](#arkui_accessibilityactiontype).| +| NODE_ON_PRE_DRAG | Notifies the listener of the interaction state prior to a drop and drop operation.
This event is triggered when a component is draggable and when a long press, lift, or drag initiation occurs.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: corresponds to [ArkUI_PreDragStatus](#arkui_predragstatus).| +| NODE_ON_DRAG_START | Called when the user starts to drag an item.
A drag operation is recognized only when the dragged item is moved far enough.
When the event callback occurs, you can obtain [ArkUI_DragEvent](#arkui_dragevent) from the [ArkUI_NodeEvent](#arkui_nodeevent-12) object.| +| NODE_ON_DRAG_ENTER | Called when a dragged item enters the boundaries of the current component.
The current component refers to the component that listens for this event.
When the event callback occurs, you can obtain [ArkUI_DragEvent](#arkui_dragevent) from the [ArkUI_NodeEvent](#arkui_nodeevent-12) object.| +| NODE_ON_DRAG_MOVE | Called when a dragged item moves in the current component.
The current component refers to the component that listens for this event.
When the event callback occurs, you can obtain [ArkUI_DragEvent](#arkui_dragevent) from the [ArkUI_NodeEvent](#arkui_nodeevent-12) object.| +| NODE_ON_DRAG_LEAVE | Called when a dragged item leaves the boundaries of the current component.
The current component refers to the component that listens for this event.
When the event callback occurs, you can obtain [ArkUI_DragEvent](#arkui_dragevent) from the [ArkUI_NodeEvent](#arkui_nodeevent-12) object.| +| NODE_ON_DROP | Called when a dragged item is dropped on the current component. The component can obtain the drag data for processing through the callback.
The current component refers to the component that listens for this event.
When the event callback occurs, you can obtain [ArkUI_DragEvent](#arkui_dragevent) from the [ArkUI_NodeEvent](#arkui_nodeevent-12) object.| +| NODE_ON_DRAG_END | Called when a drag operation ends. The drag source can obtain the drag result by registering this callback.
A drag operation ends when the dragged item is released. When the event callback occurs, the [ArkUI_DragEvent](#arkui_dragevent) object can be obtained from the [ArkUI_NodeEvent](#arkui_nodeevent-12) object.| | NODE_ON_KEY_EVENT | Triggered when a key event occurs.
The callback can be triggered during interactions with a focused window using an external keyboard or other input device.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
**Since**
14 | | NODE_ON_KEY_PRE_IME | Defines the event triggered before the input method responds to the key action.
If the return value of this callback is **true**, the key event is considered consumed, and subsequent event callbacks (**keyboardShortcut**, input method events, **onKeyEvent**) will be intercepted and no longer triggered. The callback can be triggered during interactions with a focused window using an external keyboard or other input device.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
**Since**
14 | +| NODE_ON_AXIS | Defines the event triggered when the bound component receives an axis event.
Defines the event triggered when the bound component receives an axis event.
When an event occurs, the union type in the [ArkUI_NodeEvent] (#arkui_nodeevent-12) object is [ArkUI_UIInputEvent](_ark_u_i___event_module.md#arkui_uiinputevent).
**Since**
18| +| NODE_DISPATCH_KEY_EVENT | Defines the component key event re-dispatch event. When a component node receives a key event, this callback is triggered instead of dispatching the event to its child nodes.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
**Since**
15 | +| NODE_VISIBLE_AREA_APPROXIMATE_CHANGE_EVENT | Visible area change event.
This event is triggered when the ratio of the component's visible area to its total area is greater than or less than the threshold. Before registering the event, you need to use **NODE_VISIBLE_AREA_APPROXIMATE_CHANGE_RATIO** to configure the threshold.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: whether the component's visible area has increased or decreased relative to its total area since the last update. The value **1** indicates that the visible area has increased, and **0** indicates that the visible area has decreased.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].f32: ratio of the component's visible area to its total area at the time the callback is triggered.
**Since**
18 | | NODE_TEXT_ON_DETECT_RESULT_UPDATE | Called when text recognition with the configured **TextDataDetectorConfig** settings succeeds.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_StringAsyncEvent](_ark_u_i___string_async_event.md).
[ArkUI_StringAsyncEvent](_ark_u_i___string_async_event.md) contains the following parameters:
[ArkUI_StringAsyncEvent.pStr](_ark_u_i___string_async_event.md#pstr): text recognition result in JSON format.| -| NODE_IMAGE_ON_COMPLETE | Image loading success event.
This event is triggered when an image is successfully loaded or decoded.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: loading status. The value **0** indicates that the image is loaded successfully, and the value **1** indicates that the image is decoded successfully.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].f32: width of the image, in px.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[2].f32: height of the image, in px.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[3].f32: width of the component, in px.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[4].f32: height of the component, in px.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[5].f32: offset of the rendered content relative to the component on the x-axis, in px.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[6].f32: offset of the rendered content relative to the component on the y-axis, in px.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[7].f32: actual rendered width of the image, in px.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[8].f32:actual rendered height of the image, in px.| -| NODE_IMAGE_ON_ERROR | Image loading failure event.
This event is triggered when an error occurs during image loading.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32 error code information:
401: The image could not be obtained because the image path is invalid.
103101: The image format is not supported.| -| NODE_IMAGE_ON_SVG_PLAY_FINISH | Defines the SVG animation playback completion event.
This event is triggered when the animation playback in the loaded SVG image is complete.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) does not contain parameters.| -| NODE_IMAGE_ON_DOWNLOAD_PROGRESS | Called during image download.
Condition for triggering this event: This event is triggered when the page component downloads a web page image.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
Number of bytes that have been downloaded by the [ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].u32: so far.
Total number of bytes of images to be downloaded by the [ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].u32:.| -| NODE_TOGGLE_ON_CHANGE | Called when the toggle status changes.
This event is triggered when the switch status changes.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: current switch status. The value 1 indicates that the switch is turned on, and the value 0 indicates that the switch is turned off.| -| NODE_TEXT_INPUT_ON_CHANGE | Called when the text input content changes.
Condition for triggering the event: The input content changes.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_StringAsyncEvent](_ark_u_i___string_async_event.md).
[ArkUI_StringAsyncEvent](_ark_u_i___string_async_event.md) contains the following parameters:
[ArkUI_StringAsyncEvent.pStr](_ark_u_i___string_async_event.md#pstr): input text content.| -| NODE_TEXT_INPUT_ON_SUBMIT | Called when the Enter key of the text input method is pressed.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: type of the Enter key.| -| NODE_TEXT_INPUT_ON_CUT | Called when the cut button on the pasteboard, which displays when the text box is long pressed, is clicked.
Condition for triggering this event: Touch and hold the internal area of the text box to display the clipboard, and touch the clipboard cut button.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_StringAsyncEvent](_ark_u_i___string_async_event.md).
[ArkUI_StringAsyncEvent](_ark_u_i___string_async_event.md) contains the following parameters:
[ArkUI_StringAsyncEvent.pStr](_ark_u_i___string_async_event.md#pstr): cut text content.| -| NODE_TEXT_INPUT_ON_PASTE | Called when the paste button on the pasteboard, which displays when the text box is long pressed, is clicked.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_StringAsyncEvent](_ark_u_i___string_async_event.md).
[ArkUI_StringAsyncEvent](_ark_u_i___string_async_event.md) contains the following parameters:
[ArkUI_StringAsyncEvent.pStr](_ark_u_i___string_async_event.md#pstr): text pasted.| -| NODE_TEXT_INPUT_ON_TEXT_SELECTION_CHANGE | Called when the text selection position changes.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: indicates the start position of the selected text.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].i32: indicates the end position of the selected text.| -| NODE_TEXT_INPUT_ON_EDIT_CHANGE | Called when the input status changes.
Condition for triggering this event: The input status changes.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: **true** indicates that text input is in progress.| -| NODE_TEXT_INPUT_ON_INPUT_FILTER_ERROR | Called when matching with the regular expression specified by **NODE_TEXT_INPUT_INPUT_FILTER** fails.
Condition for triggering the event: The regular expression fails to be matched.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_StringAsyncEvent](_ark_u_i___string_async_event.md).
[ArkUI_StringAsyncEvent](_ark_u_i___string_async_event.md) contains the following parameters:
[ArkUI_StringAsyncEvent.pStr](_ark_u_i___string_async_event.md#pstr): content that is filtered out when regular expression matching fails.| -| NODE_TEXT_INPUT_ON_CONTENT_SCROLL | Called when the text content is scrolled.
Condition for triggering this event: The text content is scrolled.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: horizontal coordinate offset of the text in the content area.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].i32: offset in the Y coordinate of the text in the content area.| -| NODE_TEXT_INPUT_ON_CONTENT_SIZE_CHANGE | Called when the text input content changes.
Condition for triggering the event: The input content changes.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].f32: indicates the width of the text.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].f32: height of the text.| -| NODE_TEXT_INPUT_ON_WILL_INSERT | Called when text is about to be entered.
The event parameter is [ArkUI_NodeEvent](#arkui_nodeevent-12).
value.f32: position of the text, with the index of **0**; obtained using **OH_ArkUI_NodeEvent_GetNumberValue**.
buffer: string value of the text, with the index of **0**; obtained using **OH_ArkUI_NodeEvent_GetStringValue**.

It returns **true** if the text is inserted; returns **false** otherwise. You can set the return value using **OH_ArkUI_NodeEvent_SetReturnNumberValue**.| -| NODE_TEXT_INPUT_ON_DID_INSERT | Called when text is entered.
The event parameter is [ArkUI_NodeEvent](#arkui_nodeevent-12).
value.f32: position of the text, with the index of **0**; obtained using **OH_ArkUI_NodeEvent_GetNumberValue**.
buffer: string value of the text, with the index of **0**; obtained using **OH_ArkUI_NodeEvent_GetStringValue**.| -| NODE_TEXT_INPUT_ON_WILL_DELETE | Called when text is about to be deleted.
The event parameter is [ArkUI_NodeEvent](#arkui_nodeevent-12).
value.f32: position of the text deleted, with the index of **0**; obtained using **OH_ArkUI_NodeEvent_GetNumberValue**.
value.i32: direction for deleting the text, with the index of **1**; obtained using **OH_ArkUI_NodeEvent_GetNumberValue**. The value **0** indicates backward-delete, and **1** indicates forward-delete.
buffer: string value of the text, with the index of **0**; obtained using **OH_ArkUI_NodeEvent_GetStringValue**.

It returns **true** if the text is inserted; returns **false** otherwise.
You can set the return value using **OH_ArkUI_NodeEvent_SetReturnNumberValue**.| -| NODE_TEXT_INPUT_ON_DID_DELETE | Called when text is deleted.
The event parameter is [ArkUI_NodeEvent](#arkui_nodeevent-12).
value.f32: position of the text deleted, with the index of **0**; obtained using **OH_ArkUI_NodeEvent_GetNumberValue**.
value.i32: direction for deleting the text, with the index of **1**; obtained using **OH_ArkUI_NodeEvent_GetNumberValue**. The value **0** indicates backward-delete, and **1** indicates forward-delete.
buffer: string value of the text, with the index of **0**; obtained using **OH_ArkUI_NodeEvent_GetStringValue**.| -| NODE_TEXT_INPUT_ON_CHANGE_WITH_PREVIEW_TEXT | Called when content (including preview text) changes in the component.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_TextChangeEvent](_ark_u_i___text_change_event.md).
[ArkUI_TextChangeEvent](_ark_u_i___text_change_event.md) contains the following parameters:
**[ArkUI_TextChangeEvent.pStr](_ark_u_i___text_change_event.md#pstr)**: text content.
**[ArkUI_TextChangeEvent.pExtendStr](_ark_u_i___text_change_event.md#pextendstr)**: preview text content.
**[ArkUI_TextChangeEvent.number](_ark_u_i___text_change_event.md#number)**: position where the preview text is inserted.| -| NODE_TEXT_AREA_ON_CHANGE | Called when the input in the text box changes.

When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_StringAsyncEvent](_ark_u_i___string_async_event.md).
[ArkUI_StringAsyncEvent](_ark_u_i___string_async_event.md) contains the following parameters:
[ArkUI_StringAsyncEvent.pStr](_ark_u_i___string_async_event.md#pstr): text entered.| +| NODE_IMAGE_ON_COMPLETE | Image loading success event.
This event is triggered when an image is successfully loaded or decoded.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: loading status. The value **0** indicates that the image is loaded successfully, and the value **1** indicates that the image is decoded successfully.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].f32: width of the image, in px.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[2].f32: height of the image, in px.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[3].f32: width of the component, in px.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[4].f32: height of the component, in px.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[5].f32: offset of the rendered content relative to the component on the x-axis, in px.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[6].f32: offset of the rendered content relative to the component on the y-axis, in px.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[7].f32: actual rendered width of the image, in px.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[8].f32:actual rendered height of the image, in px.| +| NODE_IMAGE_ON_ERROR | Image loading failure event.
This event is triggered when an error occurs during image loading.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32 error code information:
401: The image could not be obtained because the image path is invalid.
103101: The image format is not supported.| +| NODE_IMAGE_ON_SVG_PLAY_FINISH | Defines the SVG animation playback completion event.
This event is triggered when the animation playback in the loaded SVG image is complete.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) does not contain parameters.| +| NODE_IMAGE_ON_DOWNLOAD_PROGRESS | Called during image download.
Condition for triggering this event: This event is triggered when the page component downloads a web page image.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
Number of bytes that have been downloaded by the [ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].u32: so far.
Total number of bytes of images to be downloaded by the [ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].u32:.| +| NODE_TOGGLE_ON_CHANGE | Called when the toggle status changes.
This event is triggered when the switch status changes.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: current switch status. The value 1 indicates that the switch is turned on, and the value 0 indicates that the switch is turned off.| +| NODE_TEXT_INPUT_ON_CHANGE | Called when the text input content changes.
Condition for triggering the event: The input content changes.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_StringAsyncEvent](_ark_u_i___string_async_event.md).
[ArkUI_StringAsyncEvent](_ark_u_i___string_async_event.md) contains the following parameters:
[ArkUI_StringAsyncEvent.pStr](_ark_u_i___string_async_event.md#pstr): input text content.| +| NODE_TEXT_INPUT_ON_SUBMIT | This event is triggered when the Enter key of the textInput input method is pressed.
This event is triggered when the Enter key of the input method is pressed.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: type of the Enter key.| +| NODE_TEXT_INPUT_ON_CUT | Called when the cut button on the pasteboard, which displays when the text box is long pressed, is clicked.
Condition for triggering this event: Touch and hold the internal area of the text box to display the clipboard, and touch the clipboard cut button.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_StringAsyncEvent](_ark_u_i___string_async_event.md).
[ArkUI_StringAsyncEvent](_ark_u_i___string_async_event.md) contains the following parameters:
[ArkUI_StringAsyncEvent.pStr](_ark_u_i___string_async_event.md#pstr): cut text content.| +| NODE_TEXT_INPUT_ON_PASTE | Called when the paste button on the pasteboard, which displays when the text box is long pressed, is clicked.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_StringAsyncEvent](_ark_u_i___string_async_event.md).
[ArkUI_StringAsyncEvent](_ark_u_i___string_async_event.md) contains the following parameters:
[ArkUI_StringAsyncEvent.pStr](_ark_u_i___string_async_event.md#pstr): text pasted.| +| NODE_TEXT_INPUT_ON_TEXT_SELECTION_CHANGE | Called when the text selection position changes.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: indicates the start position of the selected text.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].i32: indicates the end position of the selected text.| +| NODE_TEXT_INPUT_ON_EDIT_CHANGE | Called when the input status changes.
Condition for triggering this event: The input status changes.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: **true** indicates that text input is in progress.| +| NODE_TEXT_INPUT_ON_INPUT_FILTER_ERROR | Called when matching with the regular expression specified by **NODE_TEXT_INPUT_INPUT_FILTER** fails.
Condition for triggering the event: The regular expression fails to be matched.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_StringAsyncEvent](_ark_u_i___string_async_event.md).
[ArkUI_StringAsyncEvent](_ark_u_i___string_async_event.md) contains the following parameters:
[ArkUI_StringAsyncEvent.pStr](_ark_u_i___string_async_event.md#pstr): content that is filtered out when regular expression matching fails.| +| NODE_TEXT_INPUT_ON_CONTENT_SCROLL | Called when the text content is scrolled.
Condition for triggering this event: The text content is scrolled.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: horizontal coordinate offset of the text in the content area.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].i32: offset in the Y coordinate of the text in the content area.| +| NODE_TEXT_INPUT_ON_CONTENT_SIZE_CHANGE | Called when the text input content changes.
Condition for triggering the event: The input content changes.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].f32: indicates the width of the text.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].f32: height of the text.| +| NODE_TEXT_INPUT_ON_WILL_INSERT | Called when text is about to be entered.
The event parameter is [ArkUI_NodeEvent](#arkui_nodeevent-12).
value.f32: position of the text, with the index of **0**; obtained using **OH_ArkUI_NodeEvent_GetNumberValue**.
buffer: string value of the text, with the index of **0**; obtained using **OH_ArkUI_NodeEvent_GetStringValue**.

It returns **true** if the text is inserted; returns **false** otherwise. You can set the return value using **OH_ArkUI_NodeEvent_SetReturnNumberValue**.| +| NODE_TEXT_INPUT_ON_DID_INSERT | Called when text is entered.
The event parameter is [ArkUI_NodeEvent](#arkui_nodeevent-12).
value.f32: position of the text, with the index of **0**; obtained using **OH_ArkUI_NodeEvent_GetNumberValue**.
buffer: string value of the text, with the index of **0**; obtained using **OH_ArkUI_NodeEvent_GetStringValue**.| +| NODE_TEXT_INPUT_ON_WILL_DELETE | Called when text is about to be deleted.
The event parameter is [ArkUI_NodeEvent](#arkui_nodeevent-12).
value.f32: position of the text deleted, with the index of **0**; obtained using **OH_ArkUI_NodeEvent_GetNumberValue**.
value.i32: direction for deleting the text, with the index of **1**; obtained using **OH_ArkUI_NodeEvent_GetNumberValue**. The value **0** indicates backward-delete, and **1** indicates forward-delete.
buffer: string value of the text, with the index of **0**; obtained using **OH_ArkUI_NodeEvent_GetStringValue**.

It returns **true** if the text is inserted; returns **false** otherwise.
You can set the return value using **OH_ArkUI_NodeEvent_SetReturnNumberValue**.| +| NODE_TEXT_INPUT_ON_DID_DELETE | Called when text is deleted.
The event parameter is [ArkUI_NodeEvent](#arkui_nodeevent-12).
value.f32: position of the text deleted, with the index of **0**; obtained using **OH_ArkUI_NodeEvent_GetNumberValue**.
value.i32: direction for deleting the text, with the index of **1**; obtained using **OH_ArkUI_NodeEvent_GetNumberValue**. The value **0** indicates backward-delete, and **1** indicates forward-delete.
buffer: string value of the text, with the index of **0**; obtained using **OH_ArkUI_NodeEvent_GetStringValue**.| +| NODE_TEXT_INPUT_ON_CHANGE_WITH_PREVIEW_TEXT | Defines the event triggered when content (including preview text) changes in the component.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_TextChangeEvent](_ark_u_i___text_change_event.md).
[ArkUI_TextChangeEvent](_ark_u_i___text_change_event.md) contains the following parameters:
**[ArkUI_TextChangeEvent.pStr](_ark_u_i___text_change_event.md#pstr)**: text content.
**[ArkUI_TextChangeEvent.pExtendStr](_ark_u_i___text_change_event.md#pextendstr)**: preview text content.
**[ArkUI_TextChangeEvent.number](_ark_u_i___text_change_event.md#number)**: position where the preview text is inserted.| +| NODE_TEXT_AREA_ON_CHANGE | Called when the input in the text box changes.

When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_StringAsyncEvent](_ark_u_i___string_async_event.md).
[ArkUI_StringAsyncEvent](_ark_u_i___string_async_event.md) contains the following parameters:
[ArkUI_StringAsyncEvent.pStr](_ark_u_i___string_async_event.md#pstr): text entered.| | NODE_TEXT_AREA_ON_PASTE | Called when the paste button on the pasteboard, which displays when the text box is long pressed, is clicked.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_StringAsyncEvent](_ark_u_i___string_async_event.md).
[ArkUI_StringAsyncEvent](_ark_u_i___string_async_event.md) contains the following parameters:
[ArkUI_StringAsyncEvent.pStr](_ark_u_i___string_async_event.md#pstr): text pasted.| | NODE_TEXT_AREA_ON_TEXT_SELECTION_CHANGE | Called when the text selection position changes.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: indicates the start position of the selected text.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].i32: end position of the text selection area.| -| NODE_TEXT_AREA_ON_EDIT_CHANGE | Called when the input status changes.
Condition for triggering this event: The input status changes.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: **true** indicates that text input is in progress.| -| NODE_TEXT_AREA_ON_SUBMIT | Called when the Enter key on the keyboard is pressed for the multi-line text box.
This event is not triggered when **keyType** is **ARKUI_ENTER_KEY_TYPE_NEW_LINE**.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: type of the Enter key.| -| NODE_TEXT_AREA_ON_INPUT_FILTER_ERROR | Called when matching with the regular expression specified by **NODE_TEXT_AREA_INPUT_FILTER** fails.

When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_StringAsyncEvent](_ark_u_i___string_async_event.md).
[ArkUI_StringAsyncEvent](_ark_u_i___string_async_event.md) contains the following parameters:
[ArkUI_StringAsyncEvent.pStr](_ark_u_i___string_async_event.md#pstr): content that is filtered out when regular expression matching fails.| -| NODE_TEXT_AREA_ON_CONTENT_SCROLL | Called when the text content is scrolled.
Condition for triggering this event: The text content is scrolled.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: horizontal coordinate offset of the text in the content area.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].i32: offset in the Y coordinate of the text in the content area.| -| NODE_TEXT_AREA_ON_CONTENT_SIZE_CHANGE | Called when the text input content changes in the **TextArea**. component.

When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].f32: indicates the width of the text.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].f32: height of the text.| -| NODE_TEXT_AREA_ON_WILL_INSERT | Called when text is about to be entered.
The event parameter is [ArkUI_NodeEvent](#arkui_nodeevent-12).
value.f32: position of the text, with the index of **0**; obtained using **OH_ArkUI_NodeEvent_GetNumberValue**.
buffer: string value of the text, with the index of **0**; obtained using **OH_ArkUI_NodeEvent_GetStringValue**.

It returns **true** if the text is inserted; returns **false** otherwise. You can set the return value using **OH_ArkUI_NodeEvent_SetReturnNumberValue**.| -| NODE_TEXT_AREA_ON_DID_INSERT | Called when text is entered.
The event parameter is [ArkUI_NodeEvent](#arkui_nodeevent-12).
value.f32: position of the text, with the index of **0**; obtained using **OH_ArkUI_NodeEvent_GetNumberValue**.
buffer: string value of the text, with the index of **0**; obtained using **OH_ArkUI_NodeEvent_GetStringValue**.| -| NODE_TEXT_AREA_ON_WILL_DELETE | Called when text is about to be deleted.
The event parameter is [ArkUI_NodeEvent](#arkui_nodeevent-12).
value.f32: position of the text deleted, with the index of **0**; obtained using **OH_ArkUI_NodeEvent_GetNumberValue**.
value.i32: direction for deleting the text, with the index of **1**; obtained using **OH_ArkUI_NodeEvent_GetNumberValue**. The value **0** indicates backward-delete, and **1** indicates forward-delete.
buffer: string value of the text, with the index of **0**; obtained using **OH_ArkUI_NodeEvent_GetStringValue**.

It returns **true** if the text is inserted; returns **false** otherwise.
You can set the return value using **OH_ArkUI_NodeEvent_SetReturnNumberValue**.| -| NODE_TEXT_AREA_ON_DID_DELETE | Called when text is deleted.
The event parameter is [ArkUI_NodeEvent](#arkui_nodeevent-12).
value.f32: position of the text deleted, with the index of **0**; obtained using **OH_ArkUI_NodeEvent_GetNumberValue**.
value.i32: direction for deleting the text, with the index of **1**; obtained using **OH_ArkUI_NodeEvent_GetNumberValue**. The value **0** indicates backward-delete, and **1** indicates forward-delete.
buffer: string value of the text, with the index of **0**; obtained using **OH_ArkUI_NodeEvent_GetStringValue**.| -| NODE_TEXT_AREA_ON_CHANGE_WITH_PREVIEW_TEXT | Called when content (including preview text) changes in the component.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_TextChangeEvent](_ark_u_i___text_change_event.md).
[ArkUI_TextChangeEvent](_ark_u_i___text_change_event.md) contains the following parameters:
**[ArkUI_TextChangeEvent.pStr](_ark_u_i___text_change_event.md#pstr)**: text content.
**[ArkUI_TextChangeEvent.pExtendStr](_ark_u_i___text_change_event.md#pextendstr)**: preview text content.
**[ArkUI_TextChangeEvent.number](_ark_u_i___text_change_event.md#number)**: position where the preview text is inserted.| -| NODE_CHECKBOX_EVENT_ON_CHANGE | Called when the selected status of the **ARKUI_NODE_CHECKBOX** component changes.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: **1**: selected; **0**: not selected| -| NODE_DATE_PICKER_EVENT_ON_DATE_CHANGE | Called when a date is selected in the **ARKUI_NODE_DATE_PICKER** component.

When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: year of the selected date.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].i32: month of the selected date. Value range: 0–11.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[2].i32: day of the selected date.| -| NODE_TIME_PICKER_EVENT_ON_CHANGE | Called when a time is selected in the **ARKUI_NODE_TIME_PICKER** component.

When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: hour of the selected time. Value range: 0-23.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].i32: minute of the selected time. Value range: 0-59.| -| NODE_TEXT_PICKER_EVENT_ON_CHANGE | Called when an item is selected in the **ARKUI_NODE_TEXT_PICKER** component.

When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0...11].i32: value of the selected item.| -| NODE_CALENDAR_PICKER_EVENT_ON_CHANGE | Called when a date is selected in the **NODE_CALENDAR_PICKER**.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
**ArkUI_NodeComponent.data[0].u32**: year of the selected date.
**ArkUI_NodeComponent.data[1].u32**: month of the selected date.
**ArkUI_NodeComponent.data[2].u32**: day of the selected date.| -| NODE_SLIDER_EVENT_ON_CHANGE | Called when the **ARKUI_NODE_SLIDER** component is dragged or clicked.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].f32: current slider value.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].i32: state triggered by the event.| -| NODE_RADIO_EVENT_ON_CHANGE | Called when the **ARKUI_NODE_RADIO** component is dragged or clicked.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: status of the radio button.| -| NODE_CHECKBOX_GROUP_EVENT_ON_CHANGE | Called when the selection state of **ARKUI_NODE_CHECKBOX_GROUP** or any check box in the group changes.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_StringAsyncEvent](_ark_u_i___string_async_event.md).
[ArkUI_StringAsyncEvent](_ark_u_i___string_async_event.md) contains the following parameters:
**[ArkUI_StringAsyncEvent.pStr](_ark_u_i___string_async_event.md#pstr)**:
Name: name of the selected check box.
Status: **0**: All check boxes in the group are selected. **1**: Some check boxes in the group are selected. **2**: No check box in the group is selected.| -| NODE_IMAGE_ANIMATOR_EVENT_ON_START | Called when the frame-by-frame animation starts to play.


When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) does not contain parameters.| -| NODE_IMAGE_ANIMATOR_EVENT_ON_PAUSE | Called when the frame-by-frame animation playback is paused.


When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) does not contain parameters.| -| NODE_IMAGE_ANIMATOR_EVENT_ON_REPEAT | Called when the frame-by-frame animation playback is repeated.


When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) does not contain parameters.| -| NODE_IMAGE_ANIMATOR_EVENT_ON_CANCEL | Called when the frame-by-frame animation playback returns to the initial state.


When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) does not contain parameters.| -| NODE_IMAGE_ANIMATOR_EVENT_ON_FINISH | Called when the frame-by-frame animation playback is complete or stopped.


When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) does not contain parameters.| -| NODE_SWIPER_EVENT_ON_CHANGE | Called when the index of the currently displayed element of this **ARKUI_NODE_SWIPER** instance changes.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: index of the currently displayed element.| -| NODE_SWIPER_EVENT_ON_ANIMATION_START | Called when the switching animation of this **ARKUI_NODE_SWIPER** instance starts.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: index of the currently displayed element.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].i32: index of the target element to switch to.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[2].f32: offset of the currently displayed element relative to the start position of the swiper along the main axis.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[3].f32: offset of the target element relative to the start position of the swiper along the main axis.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[4].f32: hands-off velocity.| -| NODE_SWIPER_EVENT_ON_ANIMATION_END | Called when the switching animation of this **ARKUI_NODE_SWIPER** instance ends.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: index of the currently displayed element.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].f32: offset of the currently displayed element relative to the start position of the swiper along the main axis.| -| NODE_SWIPER_EVENT_ON_GESTURE_SWIPE | Triggered on a frame-by-frame basis when the page is turned by a swipe.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: index of the currently displayed element.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].f32: offset of the currently displayed element relative to the start position of the swiper along the main axis.| -| NODE_SWIPER_EVENT_ON_CONTENT_DID_SCROLL | Called when content in the **ARKUI_NODE_SWIPER** component scrolls. Instructions:
1. When [ArkUI_SwiperDisplayModeType](#arkui_swiperdisplaymodetype) is set to ARKUI_SWIPER_DISPLAY_MODE_AUTO_LINEAR, this API does not take effect.
2. This API does not work when **prevMargin** and **nextMargin** are set in such a way that the **Swiper** frontend and backend display the same page during loop playback.
3. During page scrolling, the **ContentDidScrollCallback** callback is invoked for all pages in the viewport on a frame-by-frame basis.
For example, when there are two pages whose subscripts are 0 and 1 in the viewport, two callbacks whose indexes are 0 and 1 are invoked in each frame.
4. When the swipeByGroup parameter of the displayCount attribute is set to true and at least one page in the same group is in the window:
Callback is triggered for all pages in the same group.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: index of the Swiper component, which is the same as the index value in the onChange event.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].i32: index of a page in the window.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[2].f32: moving ratio of the page relative to the start position of the Swiper major axis (the start position of the page corresponding to selectedIndex).
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[3].f32: page length in the principal axis direction.| +| NODE_TEXT_AREA_ON_EDIT_CHANGE | Called when the input status changes.
Condition for triggering this event: The input status changes.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: **true** indicates that text input is in progress.| +| NODE_TEXT_AREA_ON_SUBMIT | Called when the Enter key on the keyboard is pressed for the multi-line text box.
This event is not triggered when **keyType** is **ARKUI_ENTER_KEY_TYPE_NEW_LINE**.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: type of the Enter key.| +| NODE_TEXT_AREA_ON_INPUT_FILTER_ERROR | Called when matching with the regular expression specified by **NODE_TEXT_AREA_INPUT_FILTER** fails.

When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_StringAsyncEvent](_ark_u_i___string_async_event.md).
[ArkUI_StringAsyncEvent](_ark_u_i___string_async_event.md) contains the following parameters:
[ArkUI_StringAsyncEvent.pStr](_ark_u_i___string_async_event.md#pstr): content that is filtered out when regular expression matching fails.| +| NODE_TEXT_AREA_ON_CONTENT_SCROLL | Called when the text content is scrolled.
Condition for triggering this event: The text content is scrolled.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: horizontal coordinate offset of the text in the content area.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].i32: offset in the Y coordinate of the text in the content area.| +| NODE_TEXT_AREA_ON_CONTENT_SIZE_CHANGE | Called when the text input content changes in the **TextArea**. component.

When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].f32: indicates the width of the text.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].f32: height of the text.| +| NODE_TEXT_AREA_ON_WILL_INSERT | Called when text is about to be entered.
The event parameter is [ArkUI_NodeEvent](#arkui_nodeevent-12).
value.f32: position of the text, with the index of **0**; obtained using **OH_ArkUI_NodeEvent_GetNumberValue**.
buffer: string value of the text, with the index of **0**; obtained using **OH_ArkUI_NodeEvent_GetStringValue**.

It returns **true** if the text is inserted; returns **false** otherwise. You can set the return value using **OH_ArkUI_NodeEvent_SetReturnNumberValue**.| +| NODE_TEXT_AREA_ON_DID_INSERT | Called when text is entered.
The event parameter is [ArkUI_NodeEvent](#arkui_nodeevent-12).
value.f32: position of the text, with the index of **0**; obtained using **OH_ArkUI_NodeEvent_GetNumberValue**.
buffer: string value of the text, with the index of **0**; obtained using **OH_ArkUI_NodeEvent_GetStringValue**.| +| NODE_TEXT_AREA_ON_WILL_DELETE | Called when text is about to be deleted.
The event parameter is [ArkUI_NodeEvent](#arkui_nodeevent-12).
value.f32: position of the text deleted, with the index of **0**; obtained using **OH_ArkUI_NodeEvent_GetNumberValue**.
value.i32: direction for deleting the text, with the index of **1**; obtained using **OH_ArkUI_NodeEvent_GetNumberValue**. The value **0** indicates backward-delete, and **1** indicates forward-delete.
buffer: string value of the text, with the index of **0**; obtained using **OH_ArkUI_NodeEvent_GetStringValue**.

It returns **true** if the text is inserted; returns **false** otherwise.
You can set the return value using **OH_ArkUI_NodeEvent_SetReturnNumberValue**.| +| NODE_TEXT_AREA_ON_DID_DELETE | Called when text is deleted.
The event parameter is [ArkUI_NodeEvent](#arkui_nodeevent-12).
value.f32: position of the text deleted, with the index of **0**; obtained using **OH_ArkUI_NodeEvent_GetNumberValue**.
value.i32: direction for deleting the text, with the index of **1**; obtained using **OH_ArkUI_NodeEvent_GetNumberValue**. The value **0** indicates backward-delete, and **1** indicates forward-delete.
buffer: string value of the text, with the index of **0**; obtained using **OH_ArkUI_NodeEvent_GetStringValue**.| +| NODE_TEXT_AREA_ON_CHANGE_WITH_PREVIEW_TEXT | Defines the event triggered when content (including preview text) changes in the component.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_TextChangeEvent](_ark_u_i___text_change_event.md).
[ArkUI_TextChangeEvent](_ark_u_i___text_change_event.md) contains the following parameters:
**[ArkUI_TextChangeEvent.pStr](_ark_u_i___text_change_event.md#pstr)**: text content.
**[ArkUI_TextChangeEvent.pExtendStr](_ark_u_i___text_change_event.md#pextendstr)**: preview text content.
**[ArkUI_TextChangeEvent.number](_ark_u_i___text_change_event.md#number)**: position where the preview text is inserted.| +| NODE_CHECKBOX_EVENT_ON_CHANGE | Called when the selected status of the **ARKUI_NODE_CHECKBOX** component changes.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: **1**: selected; **0**: not selected| +| NODE_DATE_PICKER_EVENT_ON_DATE_CHANGE | Called when a date is selected in the **ARKUI_NODE_DATE_PICKER** component.

When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: year of the selected date.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].i32: month of the selected date. Value range: 0–11.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[2].i32: day of the selected date.| +| NODE_TIME_PICKER_EVENT_ON_CHANGE | Called when a time is selected in the **ARKUI_NODE_TIME_PICKER** component.

When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: hour of the selected time. Value range: 0-23.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].i32: minute of the selected time. Value range: 0-59.| +| NODE_TEXT_PICKER_EVENT_ON_CHANGE | Called when an item is selected in the **ARKUI_NODE_TEXT_PICKER** component.

When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0...11].i32: value of the selected item.| +| NODE_CALENDAR_PICKER_EVENT_ON_CHANGE | Called when a date is selected in the **NODE_CALENDAR_PICKER**.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
**ArkUI_NodeComponent.data[0].u32**: year of the selected date.
**ArkUI_NodeComponent.data[1].u32**: month of the selected date.
**ArkUI_NodeComponent.data[2].u32**: day of the selected date.| +| NODE_SLIDER_EVENT_ON_CHANGE | Called when the **ARKUI_NODE_SLIDER** component is dragged or clicked.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].f32: current slider value.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].i32: state triggered by the event.| +| NODE_RADIO_EVENT_ON_CHANGE | Called when the **ARKUI_NODE_RADIO** component is dragged or clicked.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: status of the radio button.| +| NODE_CHECKBOX_GROUP_EVENT_ON_CHANGE | Defines the event triggered when the selection state of **ARKUI_NODE_CHECKBOX_GROUP** or any check box in the group changes.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_StringAsyncEvent](_ark_u_i___string_async_event.md).
[ArkUI_StringAsyncEvent](_ark_u_i___string_async_event.md) contains the following parameters:
**[ArkUI_StringAsyncEvent.pStr](_ark_u_i___string_async_event.md#pstr)**:
Name: name of the selected check box.
Status: **0**: All check boxes in the group are selected. **1**: Some check boxes in the group are selected. **2**: No check box in the group is selected.| +| NODE_IMAGE_ANIMATOR_EVENT_ON_START | Called when the frame-by-frame animation starts to play.


When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) does not contain parameters.| +| NODE_IMAGE_ANIMATOR_EVENT_ON_PAUSE | Called when the frame-by-frame animation playback is paused.


When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) does not contain parameters.| +| NODE_IMAGE_ANIMATOR_EVENT_ON_REPEAT | Called when the frame-by-frame animation playback is repeated.


When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) does not contain parameters.| +| NODE_IMAGE_ANIMATOR_EVENT_ON_CANCEL | Called when the frame-by-frame animation playback returns to the initial state.


When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) does not contain parameters.| +| NODE_IMAGE_ANIMATOR_EVENT_ON_FINISH | Called when the frame-by-frame animation playback is complete or stopped.


When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) does not contain parameters.| +| NODE_SWIPER_EVENT_ON_CHANGE | Called when the index of the currently displayed element of this **ARKUI_NODE_SWIPER** instance changes.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: index of the currently displayed element.| +| NODE_SWIPER_EVENT_ON_ANIMATION_START | Called when the switching animation of this **ARKUI_NODE_SWIPER** instance starts.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: index of the currently displayed element.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].i32: index of the target element to switch to.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[2].f32: offset of the currently displayed element relative to the start position of the swiper along the main axis.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[3].f32: offset of the target element relative to the start position of the swiper along the main axis.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[4].f32: hands-off velocity.| +| NODE_SWIPER_EVENT_ON_ANIMATION_END | Called when the switching animation of this **ARKUI_NODE_SWIPER** instance ends.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: index of the currently displayed element.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].f32: offset of the currently displayed element relative to the start position of the swiper along the main axis.| +| NODE_SWIPER_EVENT_ON_GESTURE_SWIPE | Triggered on a frame-by-frame basis when the page is turned by a swipe.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: index of the currently displayed element.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].f32: offset of the currently displayed element relative to the start position of the swiper along the main axis.| +| NODE_SWIPER_EVENT_ON_CONTENT_DID_SCROLL | Called when content in the **ARKUI_NODE_SWIPER** component scrolls. Instructions:
1. When [ArkUI_SwiperDisplayModeType](#arkui_swiperdisplaymodetype) is set to ARKUI_SWIPER_DISPLAY_MODE_AUTO_LINEAR, this API does not take effect.
2. This API does not work when **prevMargin** and **nextMargin** are set in such a way that the **Swiper** frontend and backend display the same page during loop playback.
3. During page scrolling, the ContentDidScrollCallback callback is invoked for all pages in the viewport on a frame-by-frame basis.
For example, when there are two pages whose subscripts are 0 and 1 in the viewport, two callbacks whose indexes are 0 and 1 are invoked in each frame.
4. When the swipeByGroup parameter of the displayCount attribute is set to true and at least one page in the same group is in the window:
Callback is triggered for all pages in the same group.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: index of the Swiper component, which is the same as the index value in the onChange event.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].i32: index of a page in the window.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[2].f32: moving ratio of the page relative to the start position of the Swiper major axis (the start position of the page corresponding to selectedIndex).
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[3].f32: page length in the principal axis direction.| | NODE_SWIPER_EVENT_ON_SELECTED16+ | Defines the event triggered when the selection changes in the **ARKUI_NODE_SWIPER**.
**NOTE**
1. When the page switching animation starts after the user lifts their finger after swiping and the swipe meets the threshold for page turning.
2. When the page is changed programmatically using either **NODE_SWIPER_INDEX** or **NODE_SWIPER_SWIPE_TO_INDEX**.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
**[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32**: index of the currently selected element.| -| NODE_SCROLL_EVENT_ON_SCROLL | Defines the scrolling event enumeration values of the scrolling container component.
**NOTE**
1. This event is triggered when scrolling is started by the **Scroll** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called.
3. This event supports the out-of-bounds bounce effect.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].f32: horizontal scrolling offset.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].f32: vertical scrolling offset.| -| NODE_SCROLL_EVENT_ON_SCROLL_FRAME_BEGIN | Called when the container starts scrolling.
**NOTE**
1. This event is triggered when scrolling is started by the **Scroll** component or other input settings, such as keyboard and mouse operations.
2. This event is not triggered when the controller API is called.
3. This event does not support the out-of-bounds bounce effect.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].f32: indicates the upcoming scrolling amount.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].i32: current scroll state.
The [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) parameter contains the following return value:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].f32: The event handler can work out the amount by which the component needs to scroll based on the real-world situation and return the result in this parameter.| -| NODE_SCROLL_EVENT_ON_WILL_SCROLL | Called when the container is about to scroll.
**NOTE**
1. This event is triggered when scrolling is started by the **Scroll** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called.
3. This event supports the out-of-bounds bounce effect.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].f32:: scrolling offset of each frame. The offset is positive when the content scrolls leftwards and negative when the content scrolls rightwards. The unit is vp.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].f32: Scrolling offset of each frame. The offset is positive when the content scrolls up and negative when the content scrolls down. The unit is vp.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[2].i32: current scroll state. The parameter type is [ArkUI_ScrollState](#arkui_scrollstate).
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[3].i32: scroll source. The parameter type is [ArkUI_ScrollSource](#arkui_scrollsource).
**Returns**
Returns one or no number to indicate the actual amount by which the scroll component scrolls.| -| NODE_SCROLL_EVENT_ON_DID_SCROLL | Called when the container scrolls.
**NOTE**
1. This event is triggered when scrolling is started by the **Scroll** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called.
3. This event supports the out-of-bounds bounce effect.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].f32:: scrolling offset of each frame. The offset is positive when the content scrolls leftwards and negative when the content scrolls rightwards. The unit is vp.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].f32: Scrolling offset of each frame. The offset is positive when the content scrolls up and negative when the content scrolls down. The unit is vp.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[2].i32: current scroll state. The parameter type is [ArkUI_ScrollState](#arkui_scrollstate).| -| NODE_SCROLL_EVENT_ON_SCROLL_START | Called when the container starts scrolling.
**NOTE**
1. This event is triggered when scrolling is started by the **Scroll** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called, accompanied by a transition animation.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) does not contain parameters.| -| NODE_SCROLL_EVENT_ON_SCROLL_STOP | Called when the container stops scrolling.
**NOTE**
1. This event is triggered when scrolling is stopped by the **Scroll** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called, accompanied by a transition animation.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) does not contain parameters.| -| NODE_SCROLL_EVENT_ON_SCROLL_EDGE | Defines the scrolling edge event enumeration values of the scrolling container component.
**NOTE**
1. This event is triggered when scrolling reaches the edge after being started by the **Scroll** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called.
3. This event supports the out-of-bounds bounce effect.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32 indicates the top, bottom, left, and right edges that are touched.| -| NODE_SCROLL_EVENT_ON_REACH_START | Called when the container reaches the start edge.
**NOTE**
This event is triggered when scrolling hits the start edge.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) does not contain parameters.| -| NODE_SCROLL_EVENT_ON_REACH_END | Called when the container reaches the end edge.
**NOTE**
This event is triggered when scrolling hits the end edge.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) does not contain parameters.| -| NODE_LIST_ON_SCROLL_INDEX | Called when a child component enters or leaves the list display area.
**NOTE**
This event is triggered once when the list is initialized and when the index of the first child component or the next child component in the list display area changes.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: index of the first child component in the list display area.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].i32: index of the last child component in the list display area.
**[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[2].i32**: index of the center child component in the list display area.| -| NODE_LIST_ON_WILL_SCROLL | Called when the list is about to scroll.
**NOTE**
1. This event is triggered when scrolling is started by the **Scroll** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called.
3. This event supports the out-of-bounds bounce effect.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].f32: Scrolling offset of each frame. When the list content scrolls up, the offset is positive. When the list content scrolls down, the offset is negative.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].i32: current scroll state. The parameter type is [ArkUI_ScrollState](#arkui_scrollstate).
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[2].i32: scroll source. The parameter type is [ArkUI_ScrollSource](#arkui_scrollsource).
**Returns**
Returns one or no number to indicate the actual amount by which the scroll component scrolls.| -| NODE_LIST_ON_DID_SCROLL | Called when the list scrolls.
**NOTE**
1. This event is triggered when scrolling is started by the scrollable component or other input settings, such as keyboard and mouse operations.
2. Scrolling can be initiated by calling the controller API.
3. The out-of-bounds bounce effect is supported.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].f32: scroll offset of each frame. The offset is positive when the list is scrolled up and negative when the list is scrolled down.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].i32: current scroll state.| -| NODE_REFRESH_STATE_CHANGE | Called when the refresh state of the **ARKUI_NODE_REFRESH** object changes.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: refresh state.| -| NODE_REFRESH_ON_REFRESH | Called when the **ARKUI_NODE_REFRESH** object enters the refresh state.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) does not contain parameters.| -| NODE_REFRESH_ON_OFFSET_CHANGE | Called when the pull-down distance of the **ARKUI_NODE_REFRESH** object changes.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].f32: pull-down distance.| -| NODE_ON_WILL_SCROLL | Called when the water flow container is about to scroll.
**NOTE**
1. This event is triggered when scrolling is started by the scrollable component or other input settings, such as keyboard and mouse operations.
2. Scrolling can be initiated by calling the controller API.
3. The out-of-bounds bounce effect is supported.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].f32: scroll offset of each frame. The offset is positive when the component is scrolled up and negative when the component is scrolled down.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].i32: current scroll state. The parameter type is [ArkUI_ScrollState](#arkui_scrollstate).
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[2].i32: scroll source. The parameter type is [ArkUI_ScrollSource](#arkui_scrollsource).
**Returns**
Returns one or no number to indicate the actual amount by which the scroll component scrolls.| -| NODE_WATER_FLOW_ON_DID_SCROLL | Called when the water flow container scrolls.
**NOTE**
1. This event is triggered when scrolling is started by the scrollable component or other input settings, such as keyboard and mouse operations.
2. Scrolling can be initiated by calling the controller API.
3. The out-of-bounds bounce effect is supported.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].f32: Offset of scrolling each frame. The offset is positive when the content scrolls up and negative when the content scrolls down.
Current sliding status of the [ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].i32:.| -| NODE_WATER_FLOW_ON_SCROLL_INDEX | Called when the first or last item displayed in the water flow container changes.
**NOTE**
This event is triggered when either of the preceding indexes changes.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
Index of the start position of the water flow displayed on the [ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32:.
Index of the end position of the waterfall currently displayed on the [ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].i32:.| +| NODE_SWIPER_EVENT_ON_UNSELECTED16+ | Defines the event triggered when the selection changes in the **ARKUI_NODE_SWIPER**.
**NOTE**
1. When the page switching animation starts after the user lifts their finger after swiping and the swipe meets the threshold for page turning.
2. When the page is changed programmatically using either **NODE_SWIPER_INDEX** or **NODE_SWIPER_SWIPE_TO_INDEX**.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: index of the item that is about to be hidden.| +| NODE_SWIPER_EVENT_ON_CONTENT_WILL_SCROLL15+ | Defines the event for intercepting swipe behavior in the **Swiper** component. Instructions:
1. This event is only triggered by gesture operations, including finger swipes, scrolling the mouse wheel, and moving focus using keyboard arrow keys.
2. During finger swipes, the event is triggered for each frame. The system uses the return value of the event to determine whether to respond to the swipe for each frame.
3. For scrolling the mouse wheel and moving focus using keyboard arrow keys, the event is triggered once per page turning. The system uses the return value to decide whether to allow the page turning.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: index of the current page. During a finger swipe, this value remains constant as long as the finger is on the screen, even if the page has completely moved out of view.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].i32: index of the page that will be displayed in the direction of the swipe.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[2].f32: translation of the swipe, with a sign indicating the direction. A positive value indicates a swipe from index=1 to index=0, while a negative value indicates a swipe from index=0 to index=1.
This value represents the offset for each frame during a finger swipe and the distance for page turning when the mouse wheel or keyboard navigation is used.
The [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) parameter contains the following return value:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: whether to allow the swipe. The **Swiper** component will use this return value to decide whether to respond to the swipe.| +| NODE_SCROLL_EVENT_ON_SCROLL | Defines the scrolling event enumeration values of the scrolling container component.
**NOTE**
1. This event is triggered when scrolling is started by the **Scroll** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called.
3. This event supports the out-of-bounds bounce effect.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].f32: horizontal scrolling offset.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].f32: vertical scrolling offset.| +| NODE_SCROLL_EVENT_ON_SCROLL_FRAME_BEGIN | Called when the container starts scrolling.
**NOTE**
1. This event is triggered when scrolling is started by the **Scroll** component or other input settings, such as keyboard and mouse operations.
2. This event is not triggered when the controller API is called.
3. This event does not support the out-of-bounds bounce effect.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].f32: indicates the upcoming scrolling amount.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].i32: current scroll state.
The [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) parameter contains the following return value:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].f32: The event handler can work out the amount by which the component needs to scroll based on the real-world situation and return the result in this parameter.| +| NODE_SCROLL_EVENT_ON_WILL_SCROLL | Called when the container is about to scroll.
**NOTE**
1. This event is triggered when scrolling is started by the **Scroll** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called.
3. This event supports the out-of-bounds bounce effect.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].f32:: scrolling offset of each frame. The offset is positive when the content scrolls leftwards and negative when the content scrolls rightwards. The unit is vp.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].f32: Scrolling offset of each frame. The offset is positive when the content scrolls up and negative when the content scrolls down. The unit is vp.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[2].i32: current scroll state. The parameter type is [ArkUI_ScrollState](#arkui_scrollstate).
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[3].i32: scroll source. The parameter type is [ArkUI_ScrollSource](#arkui_scrollsource).
**Returns**
Returns one or no number to indicate the actual amount by which the scroll component scrolls.| +| NODE_SCROLL_EVENT_ON_DID_SCROLL | Called when the container scrolls.
**NOTE**
1. This event is triggered when scrolling is started by the **Scroll** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called.
3. This event supports the out-of-bounds bounce effect.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].f32:: scrolling offset of each frame. The offset is positive when the content scrolls leftwards and negative when the content scrolls rightwards. The unit is vp.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].f32: Scrolling offset of each frame. The offset is positive when the content scrolls up and negative when the content scrolls down. The unit is vp.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[2].i32: current scroll state. The parameter type is [ArkUI_ScrollState](#arkui_scrollstate).| +| NODE_SCROLL_EVENT_ON_SCROLL_START | Called when the container starts scrolling.
**NOTE**
1. This event is triggered when scrolling is started by the **Scroll** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called, accompanied by a transition animation.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) does not contain parameters.| +| NODE_SCROLL_EVENT_ON_SCROLL_STOP | Called when the container stops scrolling.
**NOTE**
1. This event is triggered when scrolling is stopped by the **Scroll** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called, accompanied by a transition animation.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) does not contain parameters.| +| NODE_SCROLL_EVENT_ON_SCROLL_EDGE | Defines the scrolling edge event enumeration values of the scrolling container component.
**NOTE**
1. This event is triggered when scrolling reaches the edge after being started by the **Scroll** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called.
3. This event supports the out-of-bounds bounce effect.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32 indicates the top, bottom, left, and right edges that are touched.| +| NODE_SCROLL_EVENT_ON_REACH_START | Called when the container reaches the start edge.
**NOTE**
This event is triggered when scrolling hits the start edge.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) does not contain parameters.| +| NODE_SCROLL_EVENT_ON_REACH_END | Called when the container reaches the end edge.
**NOTE**
This event is triggered when scrolling hits the end edge.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) does not contain parameters.| +| NODE_LIST_ON_SCROLL_INDEX | Called when a child component enters or leaves the list display area.
**NOTE**
This event is triggered once when the list is initialized and when the index of the first child component or the next child component in the list display area changes.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: index of the first child component in the list display area.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].i32: index of the last child component in the list display area.
**[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[2].i32**: index of the center child component in the list display area.| +| NODE_LIST_ON_WILL_SCROLL | Called when the list is about to scroll.
**NOTE**
1. This event is triggered when scrolling is started by the **Scroll** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called.
3. This event supports the out-of-bounds bounce effect.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].f32: Scrolling offset of each frame. When the list content scrolls up, the offset is positive. When the list content scrolls down, the offset is negative.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].i32: current scroll state. The parameter type is [ArkUI_ScrollState](#arkui_scrollstate).
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[2].i32: scroll source. The parameter type is [ArkUI_ScrollSource](#arkui_scrollsource).
**Returns**
Returns one or no number to indicate the actual amount by which the scroll component scrolls.| +| NODE_LIST_ON_DID_SCROLL | Called when the list scrolls.
**NOTE**
1. This event is triggered when scrolling is started by the **Scroll** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called.
3. This event supports the out-of-bounds bounce effect.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].f32: scroll offset of each frame. The offset is positive when the list is scrolled up and negative when the list is scrolled down.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].i32: current scroll state.| +| NODE_LIST_ON_SCROLL_VISIBLE_CONTENT_CHANGE | Called when a child component enters or leaves the list display area. During index calculation, the list item, header of the list item group, and footer of the list item group each are counted as a child component. When the list edge scrolling effect is the spring effect, the **NODE_LIST_ON_SCROLL_VISIBLE_CONTENT_CHANGE** event is not triggered when the user scrolls the list to the edge or releases the list to rebound.
**NOTE**
This event is triggered once when the list is initialized and when the index of the first child component or the next child component in the list display area changes.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: index of the first child component in the list display area.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].i32: area in the list item group where the list display area starts. The parameter type is [ArkUI_ListItemGroupArea](#arkui_listitemgrouparea).
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[2].i32: index of the list item at the start of the list display area in the list item group. If the start of the list display area is not on a list item, the value is **1**.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[3].i32: index of the last child component in the list display area.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[4].i32: area in the list item group where the list display area ends. The parameter type is [ArkUI_ListItemGroupArea](#arkui_listitemgrouparea).
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[5].i32: index of the list item at the end of the list display area in the list item group. If the end of the list display area is not on a list item, the value is **1**.| +| NODE_REFRESH_STATE_CHANGE | Called when the refresh state of the **ARKUI_NODE_REFRESH** object changes.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32: refresh state.| +| NODE_REFRESH_ON_REFRESH | Called when the **ARKUI_NODE_REFRESH** object enters the refresh state.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) does not contain parameters.| +| NODE_REFRESH_ON_OFFSET_CHANGE | Called when the pull-down distance of the **ARKUI_NODE_REFRESH** object changes.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].f32: pull-down distance.| +| NODE_ON_WILL_SCROLL | Called when the water flow container is about to scroll.
**NOTE**
1. This event is triggered when scrolling is started by the **Scroll** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called.
3. This event supports the out-of-bounds bounce effect.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].f32: scroll offset of each frame. The offset is positive when the component is scrolled up and negative when the component is scrolled down.
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].i32: current scroll state. The parameter type is [ArkUI_ScrollState](#arkui_scrollstate).
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[2].i32: scroll source. The parameter type is [ArkUI_ScrollSource](#arkui_scrollsource).
**Returns**
Returns one or no number to indicate the actual amount by which the scroll component scrolls.| +| NODE_WATER_FLOW_ON_DID_SCROLL | Called when the water flow container scrolls.
**NOTE**
1. This event is triggered when scrolling is started by the **Scroll** component or other input settings, such as keyboard and mouse operations.
2. This event is triggered when the controller API is called.
3. This event supports the out-of-bounds bounce effect.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
[ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].f32: Offset of scrolling each frame. The offset is positive when the content scrolls up and negative when the content scrolls down.
Current sliding status of the [ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].i32:.| +| NODE_WATER_FLOW_ON_SCROLL_INDEX | Called when the first or last item displayed in the water flow container changes.
**NOTE**
This event is triggered when either of the preceding indexes changes.
When the event callback occurs, the union type in the [ArkUI_NodeEvent](#arkui_nodeevent-12) object is [ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md).
[ArkUI_NodeComponentEvent](_ark_u_i___node_component_event.md) contains the following parameters:
Index of the start position of the water flow displayed on the [ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[0].i32:.
Index of the end position of the waterfall currently displayed on the [ArkUI_NodeComponentEvent.data](_ark_u_i___node_component_event.md#data)[1].i32:.| ### ArkUI_NodeType @@ -3598,46 +3907,46 @@ Enumerates ArkUI component types that can be created on the native side. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_NODE_CUSTOM | Custom node. | -| ARKUI_NODE_TEXT | Text to insert. | -| ARKUI_NODE_SPAN | Text span. | -| ARKUI_NODE_IMAGE_SPAN | Image span. | -| ARKUI_NODE_IMAGE | Image. | -| ARKUI_NODE_TOGGLE | Toggle. | -| ARKUI_NODE_LOADING_PROGRESS | Loading icon. | -| ARKUI_NODE_TEXT_INPUT | Single-line text input. | -| ARKUI_NODE_TEXT_AREA | Multi-line text input. | -| ARKUI_NODE_BUTTON | Icon. | -| ARKUI_NODE_PROGRESS | Progress indicator. | +| ARKUI_NODE_CUSTOM | *Custom nodes* | +| ARKUI_NODE_TEXT | Text to insert. | +| ARKUI_NODE_SPAN | Text span. | +| ARKUI_NODE_IMAGE_SPAN | Image span. | +| ARKUI_NODE_IMAGE | Image. | +| ARKUI_NODE_TOGGLE | Toggle. | +| ARKUI_NODE_LOADING_PROGRESS | Loading icon. | +| ARKUI_NODE_TEXT_INPUT | Single-line text input. | +| ARKUI_NODE_TEXT_AREA | Multi-line text input. | +| ARKUI_NODE_BUTTON | Icon | +| ARKUI_NODE_PROGRESS | Progress indicator. | | ARKUI_NODE_CHECKBOX | Check box. | | ARKUI_NODE_XCOMPONENT | XComponent of the SURFACE type. | -| ARKUI_NODE_DATE_PICKER | Date picker. | -| ARKUI_NODE_TIME_PICKER | Time picker. | -| ARKUI_NODE_TEXT_PICKER | Text picker. | -| ARKUI_NODE_CALENDAR_PICKER | Calendar picker. | -| ARKUI_NODE_SLIDER | Slider. | -| ARKUI_NODE_RADIO | Radio button. | +| ARKUI_NODE_DATE_PICKER | Date picker. | +| ARKUI_NODE_TIME_PICKER | Time picker. | +| ARKUI_NODE_TEXT_PICKER | Text picker. | +| ARKUI_NODE_CALENDAR_PICKER | Calendar picker. | +| ARKUI_NODE_SLIDER | Slider. | +| ARKUI_NODE_RADIO | Radio button. | | ARKUI_NODE_IMAGE_ANIMATOR | Frame animation component. | | ARKUI_NODE_XCOMPONENT_TEXTURE | XComponent of the TEXTURE type. | | ARKUI_NODE_CHECKBOX_GROUP | Check box group.| -| ARKUI_NODE_STACK | Stack container. | -| ARKUI_NODE_SWIPER | Swiper. | -| ARKUI_NODE_SCROLL | Scrolling container. | -| ARKUI_NODE_LIST | List. | -| ARKUI_NODE_LIST_ITEM | List item. | -| ARKUI_NODE_LIST_ITEM_GROUP | List item group. | -| ARKUI_NODE_COLUMN | Column container. | -| ARKUI_NODE_ROW | Row container. | -| ARKUI_NODE_FLEX | Flex container. | -| ARKUI_NODE_REFRESH | Refresh component. | -| ARKUI_NODE_WATER_FLOW | Water flow container. | -| ARKUI_NODE_FLOW_ITEM | Water flow item. | -| ARKUI_NODE_RELATIVE_CONTAINER | Relative layout component. | -| ARKUI_NODE_GRID | Grid. | -| ARKUI_NODE_GRID_ITEM | Grid item. | -| ARKUI_NODE_CUSTOM_SPAN | Custom span. | +| ARKUI_NODE_STACK | Stack container. | +| ARKUI_NODE_SWIPER | Swiper. | +| ARKUI_NODE_SCROLL | Scrolling container. | +| ARKUI_NODE_LIST | List. | +| ARKUI_NODE_LIST_ITEM | List item. | +| ARKUI_NODE_LIST_ITEM_GROUP | List item group. | +| ARKUI_NODE_COLUMN | Column container. | +| ARKUI_NODE_ROW | Row container. | +| ARKUI_NODE_FLEX | Flex container. | +| ARKUI_NODE_REFRESH | Refresh component. | +| ARKUI_NODE_WATER_FLOW | Water flow container. | +| ARKUI_NODE_FLOW_ITEM | Water flow item. | +| ARKUI_NODE_RELATIVE_CONTAINER | Relative layout component. | +| ARKUI_NODE_GRID | Grid. | +| ARKUI_NODE_GRID_ITEM | Grid item. | +| ARKUI_NODE_CUSTOM_SPAN | Custom span. | ### ArkUI_ObjectFit @@ -3651,23 +3960,25 @@ Enumerates the image filling effects. ImageSpanAlignment **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_OBJECT_FIT_CONTAIN | The image is scaled with its aspect ratio retained for the content to be completely displayed within the display boundaries. | -| ARKUI_OBJECT_FIT_COVER | The image is scaled with its aspect ratio retained for both sides to be greater than or equal to the display boundaries. | -| ARKUI_OBJECT_FIT_AUTO | The image is scaled automatically to fit the display area. | -| ARKUI_OBJECT_FIT_FILL | The image is scaled to fill the display area, and its aspect ratio is not retained. | -| ARKUI_OBJECT_FIT_SCALE_DOWN | The image is displayed with its aspect ratio retained, in a size smaller than or equal to the original size. | -| ARKUI_OBJECT_FIT_NONE | The original size is retained. | -| ARKUI_OBJECT_FIT_NONE_AND_ALIGN_TOP_START | Not resized, the image is aligned with the start edge of the top of the container. | -| ARKUI_OBJECT_FIT_NONE_AND_ALIGN_TOP | Not resized, the image is horizontally centered at the top of the container. | -| ARKUI_OBJECT_FIT_NONE_AND_ALIGN_TOP_END | Not resized, the image is aligned with the end edge at the top of the container. | -| ARKUI_OBJECT_FIT_NONE_AND_ALIGN_START | Not resized, the image is vertically centered on the start edge of the container. | -| ARKUI_OBJECT_FIT_NONE_AND_ALIGN_CENTER | Not resized, the image is horizontally and vertically centered in the container. | -| ARKUI_OBJECT_FIT_NONE_AND_ALIGN_END | Not resized, the image is vertically centered on the end edge of the container. | -| ARKUI_OBJECT_FIT_NONE_AND_ALIGN_BOTTOM_START | Not resized, the image is aligned with the start edge at the bottom of the container. | -| ARKUI_OBJECT_FIT_NONE_AND_ALIGN_BOTTOM | Not resized, the image is horizontally centered at the bottom of the container. | -| ARKUI_OBJECT_FIT_NONE_AND_ALIGN_BOTTOM_END | Not resized, the image is aligned with the end edge at the bottom of the container. | +| ARKUI_OBJECT_FIT_CONTAIN | The image is scaled with its aspect ratio retained for the content to be completely displayed within the display boundaries. | +| ARKUI_OBJECT_FIT_COVER | The image is scaled with its aspect ratio retained for both sides to be greater than or equal to the display boundaries. | +| ARKUI_OBJECT_FIT_AUTO | The image is scaled automatically to fit the display area. | +| ARKUI_OBJECT_FIT_FILL | The image is scaled to fill the display area, and its aspect ratio is not retained. | +| ARKUI_OBJECT_FIT_SCALE_DOWN | The image is displayed with its aspect ratio retained, in a size smaller than or equal to the original size. | +| ARKUI_OBJECT_FIT_NONE | The original size is retained. | +| ARKUI_OBJECT_FIT_NONE_AND_ALIGN_TOP_START | Not resized, the image is aligned with the start edge of the top of the container. | +| ARKUI_OBJECT_FIT_NONE_AND_ALIGN_TOP | Not resized, the image is horizontally centered at the top of the container. | +| ARKUI_OBJECT_FIT_NONE_AND_ALIGN_TOP_END | Not resized, the image is aligned with the end edge at the top of the container. | +| ARKUI_OBJECT_FIT_NONE_AND_ALIGN_START | Not resized, the image is vertically centered on the start edge of the container. | +| ARKUI_OBJECT_FIT_NONE_AND_ALIGN_CENTER | Not resized, the image is horizontally and vertically centered in the container. | +| ARKUI_OBJECT_FIT_NONE_AND_ALIGN_END | Not resized, the image is vertically centered on the end edge of the container. | +| ARKUI_OBJECT_FIT_NONE_AND_ALIGN_BOTTOM_START | Not resized, the image is aligned with the start edge at the bottom of the container. | +| ARKUI_OBJECT_FIT_NONE_AND_ALIGN_BOTTOM | Not resized, the image is horizontally centered at the bottom of the container. | +| ARKUI_OBJECT_FIT_NONE_AND_ALIGN_BOTTOM_END | Not resized, the image is aligned with the end edge at the bottom of the container. | + + ### ArkUI_PageFlipMode ``` @@ -3675,7 +3986,7 @@ enum ArkUI_PageFlipMode ``` **Description** -Enumerates the page flipping modes using the mouse wheel for the **Swiper** component. +Enumerates the page flipping modes using the mouse wheel for the Swiper component. **Since**: 14 @@ -3694,7 +4005,7 @@ enum ArkUI_SwiperAnimationMode Enumerates the animation modes for the **Swiper** component when jumping to the page with the specified index. -**Since**: 16 +**Since**: 15 | Enum| Description| | -------- | -------- | @@ -3714,16 +4025,16 @@ Defines an enum for interaction states prior to a drop and drop operation. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_PRE_DRAG_STATUS_UNKNOWN | Unknown. | -| ARKUI_PRE_DRAG_STATUS_ACTION_DETECTING | A drag gesture is being detected. | -| ARKUI_PRE_DRAG_STATUS_READY_TO_TRIGGER_DRAG | The component is ready to be dragged. | -| ARKUI_PRE_DRAG_STATUS_PREVIEW_LIFT_STARTED | A lift animation is started. | -| ARKUI_PRE_DRAG_STATUS_PREVIEW_LIFT_FINISHED | A lift animation is finished. | -| ARKUI_PRE_DRAG_STATUS_PREVIEW_LANDING_STARTED | A drop animation is started. | -| ARKUI_PRE_DRAG_STATUS_PREVIEW_LANDING_FINISHED | A drop animation is finished. | -| ARKUI_PRE_DRAG_STATUS_CANCELED_BEFORE_DRAG | A drop animation is terminated. | +| ARKUI_PRE_DRAG_STATUS_UNKNOWN | Unknown. | +| ARKUI_PRE_DRAG_STATUS_ACTION_DETECTING | A drag gesture is being detected. | +| ARKUI_PRE_DRAG_STATUS_READY_TO_TRIGGER_DRAG | The component is ready to be dragged. | +| ARKUI_PRE_DRAG_STATUS_PREVIEW_LIFT_STARTED | A lift animation is started. | +| ARKUI_PRE_DRAG_STATUS_PREVIEW_LIFT_FINISHED | A lift animation is finished. | +| ARKUI_PRE_DRAG_STATUS_PREVIEW_LANDING_STARTED | A drop animation is started. | +| ARKUI_PRE_DRAG_STATUS_PREVIEW_LANDING_FINISHED | A drop animation is finished. | +| ARKUI_PRE_DRAG_STATUS_CANCELED_BEFORE_DRAG | A drop animation is terminated. | ### ArkUI_ProgressType @@ -3737,13 +4048,13 @@ Enumerates the styles of the progress indicator. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_PROGRESS_TYPE_LINEAR | Linear type. | -| ARKUI_PROGRESS_TYPE_RING | Indeterminate ring style. | -| ARKUI_PROGRESS_TYPE_ECLIPSE | Eclipse style. | -| ARKUI_PROGRESS_TYPE_SCALE_RING | Determinate ring style. | -| ARKUI_PROGRESS_TYPE_CAPSULE | Capsule style. | +| ARKUI_PROGRESS_TYPE_LINEAR | Linear type. | +| ARKUI_PROGRESS_TYPE_RING | Indeterminate ring style. | +| ARKUI_PROGRESS_TYPE_ECLIPSE | Eclipse style. | +| ARKUI_PROGRESS_TYPE_SCALE_RING | Determinate ring style. | +| ARKUI_PROGRESS_TYPE_CAPSULE | Capsule style. | ### ArkUI_RelativeLayoutChainStyle @@ -3757,11 +4068,11 @@ Enumerates the chain styles. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_RELATIVE_LAYOUT_CHAIN_STYLE_SPREAD | Child components are evenly distributed among constraint anchors. | -| ARKUI_RELATIVE_LAYOUT_CHAIN_STYLE_SPREAD_INSIDE | All child components except the first and last ones are evenly distributed among constraint anchors. | -| ARKUI_RELATIVE_LAYOUT_CHAIN_STYLE_PACKED | There is no gap between child components in the chain. | +| ARKUI_RELATIVE_LAYOUT_CHAIN_STYLE_SPREAD | Child components are evenly distributed among constraint anchors. | +| ARKUI_RELATIVE_LAYOUT_CHAIN_STYLE_SPREAD_INSIDE | All child components except the first and last ones are evenly distributed among constraint anchors. | +| ARKUI_RELATIVE_LAYOUT_CHAIN_STYLE_PACKED | There is no gap between child components in the chain. | ### ArkUI_RenderFit @@ -3770,24 +4081,24 @@ Enumerates the chain styles. enum ArkUI_RenderFit ``` -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_RENDER_FIT_CENTER | The component's content stays at the final size and always aligned with the center of the component. | -| ARKUI_RENDER_FIT_TOP | The component's content stays at the final size and always aligned with the top center of the component. | -| ARKUI_RENDER_FIT_BOTTOM | The component's content stays at the final size and always aligned with the bottom center of the component. | -| ARKUI_RENDER_FIT_LEFT | The component's content stays at the final size and always aligned with the left of the component. | -| ARKUI_RENDER_FIT_RIGHT | The component's content stays at the final size and always aligned with the right of the component. | -| ARKUI_RENDER_FIT_TOP_LEFT | The component's content stays at the final size and always aligned with the upper left corner of the component. | -| ARKUI_RENDER_FIT_TOP_RIGHT | The component's content stays at the final size and always aligned with the upper right corner of the component. | -| ARKUI_RENDER_FIT_BOTTOM_LEFT | The component's content stays at the final size and always aligned with the lower left corner of the component. | -| ARKUI_RENDER_FIT_BOTTOM_RIGHT | The component's content stays at the final size and always aligned with the lower right corner of the component. | -| ARKUI_RENDER_FIT_RESIZE_FILL | The component's content is always resized to fill the component's content box, without considering its aspect ratio in the final state. | -| ARKUI_RENDER_FIT_RESIZE_CONTAIN | While maintaining its aspect ratio in the final state, the component's content is scaled to fit within the component's content box. It is always aligned with the center of the component. | -| ARKUI_RENDER_FIT_RESIZE_CONTAIN_TOP_LEFT | While maintaining its aspect ratio in the final state, the component's content is scaled to fit within the component's content box. When there is remaining space in the width direction of the component, the content is left-aligned with the component. When there is remaining space in the height direction of the component, the content is top-aligned with the component. | -| ARKUI_RENDER_FIT_RESIZE_CONTAIN_BOTTOM_RIGHT | While maintaining its aspect ratio in the final state, the component's content is scaled to fit within the component's content box. When there is remaining space in the width direction of the component, the content is right-aligned with the component. When there is remaining space in the height direction of the component, the content is bottom-aligned with the component. | -| ARKUI_RENDER_FIT_RESIZE_COVER | While maintaining its aspect ratio in the final state, the component's content is scaled to cover the component's entire content box. It is always aligned with the center of the component, so that its middle part is displayed. | -| ARKUI_RENDER_FIT_RESIZE_COVER_TOP_LEFT | While maintaining its aspect ratio in the final state, the component's content is scaled to cover the component's entire content box. When there is remaining space in the width direction, the content is left-aligned with the component, so that its left part is displayed. When there is remaining space in the height direction, the content is top-aligned with the component, so that its top part is displayed. | -| ARKUI_RENDER_FIT_RESIZE_COVER_BOTTOM_RIGHT | While maintaining its aspect ratio in the final state, the component's content is scaled to cover the component's entire content box. When there is remaining space in the width direction, the content is right-aligned with the component, so that its right part is displayed. When there is remaining space in the height direction, the content is bottom-aligned with the component, so that its bottom part is displayed. | +| ARKUI_RENDER_FIT_CENTER | The component's content stays at the final size and always aligned with the center of the component. | +| ARKUI_RENDER_FIT_TOP | The component's content stays at the final size and always aligned with the top center of the component. | +| ARKUI_RENDER_FIT_BOTTOM | The component's content stays at the final size and always aligned with the bottom center of the component. | +| ARKUI_RENDER_FIT_LEFT | The component's content stays at the final size and always aligned with the left of the component. | +| ARKUI_RENDER_FIT_RIGHT | The component's content stays at the final size and always aligned with the right of the component. | +| ARKUI_RENDER_FIT_TOP_LEFT | The component's content stays at the final size and always aligned with the upper left corner of the component. | +| ARKUI_RENDER_FIT_TOP_RIGHT | The component's content stays at the final size and always aligned with the upper right corner of the component. | +| ARKUI_RENDER_FIT_BOTTOM_LEFT | The component's content stays at the final size and always aligned with the lower left corner of the component. | +| ARKUI_RENDER_FIT_BOTTOM_RIGHT | The component's content stays at the final size and always aligned with the lower right corner of the component. | +| ARKUI_RENDER_FIT_RESIZE_FILL | The component's content is always resized to fill the component's content box, without considering its aspect ratio in the final state. | +| ARKUI_RENDER_FIT_RESIZE_CONTAIN | While maintaining its aspect ratio in the final state, the component's content is scaled to fit within the component's content box. It is always aligned with the center of the component. | +| ARKUI_RENDER_FIT_RESIZE_CONTAIN_TOP_LEFT | While maintaining its aspect ratio in the final state, the component's content is scaled to fit within the component's content box. When there is remaining space in the width direction of the component, the content is left-aligned with the component. When there is remaining space in the height direction of the component, the content is top-aligned with the component. | +| ARKUI_RENDER_FIT_RESIZE_CONTAIN_BOTTOM_RIGHT | While maintaining its aspect ratio in the final state, the component's content is scaled to fit within the component's content box. When there is remaining space in the width direction of the component, the content is right-aligned with the component. When there is remaining space in the height direction of the component, the content is bottom-aligned with the component. | +| ARKUI_RENDER_FIT_RESIZE_COVER | While maintaining its aspect ratio in the final state, the component's content is scaled to cover the component's entire content box. It is always aligned with the center of the component, so that its middle part is displayed. | +| ARKUI_RENDER_FIT_RESIZE_COVER_TOP_LEFT | While maintaining its aspect ratio in the final state, the component's content is scaled to cover the component's entire content box. When there is remaining space in the width direction, the content is left-aligned with the component, so that its left part is displayed. When there is remaining space in the height direction, the content is top-aligned with the component, so that its top part is displayed. | +| ARKUI_RENDER_FIT_RESIZE_COVER_BOTTOM_RIGHT | While maintaining its aspect ratio in the final state, the component's content is scaled to cover the component's entire content box. When there is remaining space in the width direction, the content is right-aligned with the component, so that its right part is displayed. When there is remaining space in the height direction, the content is bottom-aligned with the component, so that its bottom part is displayed. | ### ArkUI_RouterPageState @@ -3801,13 +4112,13 @@ Enumerates the states of a page during routing. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_ROUTER_PAGE_STATE_ON_WILL_APPEAR | The page is about to be displayed. | -| ARKUI_ROUTER_PAGE_STATE_ON_WILL_DISAPPEAR | The page is about to be destroyed. | -| ARKUI_ROUTER_PAGE_STATE_ON_SHOW | The page is displayed. | -| ARKUI_ROUTER_PAGE_STATE_ON_HIDE | The page is hidden. | -| ARKUI_ROUTER_PAGE_STATE_ON_BACK_PRESS | The back button is pressed for the page. | +| ARKUI_ROUTER_PAGE_STATE_ON_WILL_APPEAR | The page is about to be displayed. | +| ARKUI_ROUTER_PAGE_STATE_ON_WILL_DISAPPEAR | The page is about to be destroyed. | +| ARKUI_ROUTER_PAGE_STATE_ON_SHOW | The page is displayed. | +| ARKUI_ROUTER_PAGE_STATE_ON_HIDE | The page is hidden. | +| ARKUI_ROUTER_PAGE_STATE_ON_BACK_PRESS | The back button is pressed for the page. | ### ArkUI_SafeAreaEdge @@ -3821,12 +4132,12 @@ Enumerates the edges for expanding the safe area. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_SAFE_AREA_EDGE_TOP | Top edge. | -| ARKUI_SAFE_AREA_EDGE_BOTTOM | Bottom edge. | -| ARKUI_SAFE_AREA_EDGE_START | Start edge. | -| ARKUI_SAFE_AREA_EDGE_END | End edge. | +| ARKUI_SAFE_AREA_EDGE_TOP | Top edge. | +| ARKUI_SAFE_AREA_EDGE_BOTTOM | Bottom edge. | +| ARKUI_SAFE_AREA_EDGE_START | Start edge. | +| ARKUI_SAFE_AREA_EDGE_END | End edge. | ### ArkUI_SafeAreaType @@ -3840,12 +4151,52 @@ Enumerates the types of expanded safe areas. **Since**: 12 -| Enum| Description| +| Enum| Description| +| -------- | -------- | +| ARKUI_SAFE_AREA_TYPE_SYSTEM | Default non-safe area of the system, including the status bar and navigation bar. | +| ARKUI_SAFE_AREA_TYPE_CUTOUT | Non-safe area of the device, for example, the notch area. | +| ARKUI_SAFE_AREA_TYPE_KEYBOARD | Soft keyboard area. | + + +### ArkUI_ListItemGroupArea + +``` +enum ArkUI_ListItemGroupArea +``` +**Description** + +Enumerates the component areas. + +**Since**: 15 + +| Enum| Description| | -------- | -------- | -| ARKUI_SAFE_AREA_TYPE_SYSTEM | Default non-safe area of the system, including the status bar and navigation bar. | -| ARKUI_SAFE_AREA_TYPE_CUTOUT | Non-safe area of the device, for example, the notch area. | -| ARKUI_SAFE_AREA_TYPE_KEYBOARD | Soft keyboard area. | +| ARKUI_LIST_ITEM_GROUP_AREA_OUTSIDE | Outside the component area. | +| ARKUI_LIST_ITEM_SWIPE_AREA_NONE | Area when the component has no header, footer, or list items. | +| ARKUI_LIST_ITEM_SWIPE_AREA_ITEM | Area of the component's list items. | +| ARKUI_LIST_ITEM_SWIPE_AREA_HEADER | Header area of the component. | +| ARKUI_LIST_ITEM_SWIPE_AREA_FOOTER | Footer area of the component. | + + +### ArkUI_FocusMove + +``` +enum ArkUI_FocusMove +``` +**Description** + +Enumerates the focus movement directions. + +**Since**: 18 +| Enum| Description| +| -------- | -------- | +| ARKUI_FOCUS_MOVE_FORWARD | Tab key. | +| ARKUI_FOCUS_MOVE_BACKWARD | Shift+Tab key. | +| ARKUI_FOCUS_MOVE_UP | Up arrow key. | +| ARKUI_FOCUS_MOVE_DOWN | Down arrow key. | +| ARKUI_FOCUS_MOVE_LEFT | Left arrow key. | +| ARKUI_FOCUS_MOVE_RIGHT | Right arrow key. | ### ArkUI_ScrollAlignment @@ -3858,12 +4209,13 @@ Defines how the list item to scroll to is aligned with the container. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_SCROLL_ALIGNMENT_START | The start edge of the list item is flush with the start edge of the container. | -| ARKUI_SCROLL_ALIGNMENT_CENTER | The list item is centered along the main axis of the list. | -| ARKUI_SCROLL_ALIGNMENT_END | The end edge of the list item Aligns the tail of an item with that of a container. | -| ARKUI_SCROLL_ALIGNMENT_AUTO | The list item is automatically aligned. If the item is fully contained within the display area, no adjustment is performed. Otherwise, the item is aligned so that its start or end edge is flush with the start or end edge of the container, whichever requires a shorter scrolling distance. | +| ARKUI_SCROLL_ALIGNMENT_START | The start edge of the list item is flush with the start edge of the container. | +| ARKUI_SCROLL_ALIGNMENT_CENTER | The list item is centered along the main axis of the list. | +| ARKUI_SCROLL_ALIGNMENT_END | The end edge of the list item Aligns the tail of an item with that of a container. | +| ARKUI_SCROLL_ALIGNMENT_AUTO | The list item is automatically aligned. If the item is fully contained within the display area, no adjustment is performed. Otherwise, the item is aligned so that its start or end edge is flush with the start or end edge of the container, whichever requires a shorter scrolling distance. | + ### ArkUI_ScrollBarDisplayMode @@ -3876,11 +4228,11 @@ Enumerates the scrollbar display modes. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_SCROLL_BAR_DISPLAY_MODE_OFF | Not displayed. | -| ARKUI_SCROLL_BAR_DISPLAY_MODE_AUTO | Displayed when the screen is touched and hidden after 2s. | -| ARKUI_SCROLL_BAR_DISPLAY_MODE_ON | Always displayed. | +| ARKUI_SCROLL_BAR_DISPLAY_MODE_OFF | Not displayed. | +| ARKUI_SCROLL_BAR_DISPLAY_MODE_AUTO | Displayed when the screen is touched and hidden after 2s. | +| ARKUI_SCROLL_BAR_DISPLAY_MODE_ON | Always displayed. | ### ArkUI_ScrollDirection @@ -3894,11 +4246,11 @@ Enumerates the scroll directions of scrollable components. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_SCROLL_DIRECTION_VERTICAL | Only vertical scrolling is supported. | -| ARKUI_SCROLL_DIRECTION_HORIZONTAL | Only horizontal scrolling is supported. | -| ARKUI_SCROLL_DIRECTION_NONE | Scrolling is forbidden. | +| ARKUI_SCROLL_DIRECTION_VERTICAL | Only vertical scrolling is supported. | +| ARKUI_SCROLL_DIRECTION_HORIZONTAL | Only horizontal scrolling is supported. | +| ARKUI_SCROLL_DIRECTION_NONE | Scrolling is forbidden. | ### ArkUI_ScrollEdge @@ -3912,12 +4264,12 @@ Defines the edge to which the component scrolls. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_SCROLL_EDGE_TOP | Top edge in the vertical direction. | -| ARKUI_SCROLL_EDGE_BOTTOM | Bottom edge in the vertical direction. | -| ARKUI_SCROLL_EDGE_START | Start position in the horizontal direction. | -| ARKUI_SCROLL_EDGE_END | End position in the horizontal direction. | +| ARKUI_SCROLL_EDGE_TOP | Top edge in the vertical direction. | +| ARKUI_SCROLL_EDGE_BOTTOM | Bottom edge in the vertical direction. | +| ARKUI_SCROLL_EDGE_START | Start position in the horizontal direction. | +| ARKUI_SCROLL_EDGE_END | End position in the horizontal direction. | ### ArkUI_ScrollNestedMode @@ -3931,12 +4283,12 @@ Enumerates nested scrolling options. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_SCROLL_NESTED_MODE_SELF_ONLY | The scrolling is contained within the component, and no scroll chaining occurs, that is, the parent component does not scroll when the component scrolling reaches the boundary. | -| ARKUI_SCROLL_NESTED_MODE_SELF_FIRST | The component scrolls first, and when it hits the boundary, the parent component scrolls. When the parent component hits the boundary, its edge effect is displayed. If no edge effect is specified for the parent component, the edge effect of the child component is displayed instead. | -| ARKUI_SCROLL_NESTED_MODE_PARENT_FIRST | The parent component scrolls first, and when it hits the boundary, the component scrolls. When the component hits the boundary, its edge effect is displayed. If no edge effect is specified for the component, the edge effect of the parent component is displayed instead. | -| ARKUI_SCROLL_NESTED_MODE_PARALLEL | The component and its parent component scroll at the same time. When both the component and its parent component hit the boundary, the edge effect of the component is displayed. If no edge effect is specified for the component, the edge effect of the parent component is displayed instead. | +| ARKUI_SCROLL_NESTED_MODE_SELF_ONLY | The scrolling is contained within the component, and no scroll chaining occurs, that is, the parent component does not scroll when the component scrolling reaches the boundary. | +| ARKUI_SCROLL_NESTED_MODE_SELF_FIRST | The component scrolls first, and when it hits the boundary, the parent component scrolls. When the parent component hits the boundary, its edge effect is displayed. If no edge effect is specified for the parent component, the edge effect of the child component is displayed instead. | +| ARKUI_SCROLL_NESTED_MODE_PARENT_FIRST | The parent component scrolls first, and when it hits the boundary, the component scrolls. When the component hits the boundary, its edge effect is displayed. If no edge effect is specified for the component, the edge effect of the parent component is displayed instead. | +| ARKUI_SCROLL_NESTED_MODE_PARALLEL | The component and its parent component scroll at the same time. When both the component and its parent component hit the boundary, the edge effect of the component is displayed. If no edge effect is specified for the component, the edge effect of the parent component is displayed instead. | ### ArkUI_ScrollSnapAlign @@ -3950,12 +4302,12 @@ Enumerates the alignment modes of list items when scrolling ends. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_SCROLL_SNAP_ALIGN_NONE | No alignment. This is the default value. | -| ARKUI_SCROLL_SNAP_ALIGN_START | The first item in the view is aligned at the start of the list. | -| ARKUI_SCROLL_SNAP_ALIGN_CENTER | The middle items in the view are aligned in the center of the list. | -| ARKUI_SCROLL_SNAP_ALIGN_END | The last item in the view is aligned at the end of the list. | +| ARKUI_SCROLL_SNAP_ALIGN_NONE | No alignment. This is the default value. | +| ARKUI_SCROLL_SNAP_ALIGN_START | The first item in the view is aligned at the start of the list. | +| ARKUI_SCROLL_SNAP_ALIGN_CENTER | The middle items in the view are aligned in the center of the list. | +| ARKUI_SCROLL_SNAP_ALIGN_END | The last item in the view is aligned at the end of the list. | ### ArkUI_ScrollSource @@ -3969,16 +4321,16 @@ Enumerates the scrolling sources. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_SCROLL_SOURCE_DRAG | Drag your finger. | -| ARKUI_SCROLL_SOURCE_FLING | Inertia scrolling after finger dragging. | -| ARKUI_SCROLL_SOURCE_EDGE_EFFECT | Executes the EdgeEffect.Spring edge special effect when the boundary is crossed. | -| ARKUI_SCROLL_SOURCE_OTHER_USER_INPUT | User input other than dragging, such as mouse wheel and keyboard events. | -| ARKUI_SCROLL_SOURCE_SCROLL_BAR | Scrollbar dragging | -| ARKUI_SCROLL_SOURCE_SCROLL_BAR_FLING | Inertial scrolling after the scroll bar is dragged. | -| ARKUI_SCROLL_SOURCE_SCROLLER | Scrolling by the scroll controller (without animation). | -| ARKUI_SCROLL_SOURCE_ANIMATION | Scrolling by the scroll controller (with animation). | +| ARKUI_SCROLL_SOURCE_DRAG | Drag your finger. | +| ARKUI_SCROLL_SOURCE_FLING | Inertia scrolling after finger dragging. | +| ARKUI_SCROLL_SOURCE_EDGE_EFFECT | Executes the EdgeEffect.Spring edge special effect when the boundary is crossed. | +| ARKUI_SCROLL_SOURCE_OTHER_USER_INPUT | User input other than dragging, such as mouse wheel and keyboard events. | +| ARKUI_SCROLL_SOURCE_SCROLL_BAR | Scrollbar dragging | +| ARKUI_SCROLL_SOURCE_SCROLL_BAR_FLING | Inertial scrolling after the scroll bar is dragged. | +| ARKUI_SCROLL_SOURCE_SCROLLER | Scrolling by the scroll controller (without animation). | +| ARKUI_SCROLL_SOURCE_ANIMATION | Scrolling by the scroll controller (with animation). | ### ArkUI_ScrollState @@ -3992,11 +4344,11 @@ Enumerates the scrolling states. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_SCROLL_STATE_IDLE | Idle. The container enters this state when an API in the controller is used to scroll the container or when the scrollbar is dragged. | -| ARKUI_SCROLL_STATE_SCROLL | Scrolling. The container enters this state when the user drags the container to scroll. | -| ARKUI_SCROLL_STATE_FLING | Inertial scrolling. The container enters this state when inertial scrolling occurs or when the container bounces back after being released from a fling. | +| ARKUI_SCROLL_STATE_IDLE | Idle. The container enters this state when an API in the controller is used to scroll the container or when the scrollbar is dragged. | +| ARKUI_SCROLL_STATE_SCROLL | Scrolling. The container enters this state when the user drags the container to scroll. | +| ARKUI_SCROLL_STATE_FLING | Inertial scrolling. The container enters this state when inertial scrolling occurs or when the container bounces back after being released from a fling. | ### ArkUI_ShadowStyle @@ -4010,14 +4362,14 @@ Enumerated value of the shadow effect. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_SHADOW_STYLE_OUTER_DEFAULT_XS | Mini shadow. | -| ARKUI_SHADOW_STYLE_OUTER_DEFAULT_SM | Small shadow. | -| ARKUI_SHADOW_STYLE_OUTER_DEFAULT_MD | Medium shadow. | -| ARKUI_SHADOW_STYLE_OUTER_DEFAULT_LG | Large shadow. | -| ARKUI_SHADOW_STYLE_OUTER_FLOATING_SM | Floating small shadow. | -| ARKUI_SHADOW_STYLE_OUTER_FLOATING_MD | Floating medium shadow. | +| ARKUI_SHADOW_STYLE_OUTER_DEFAULT_XS | Mini shadow. | +| ARKUI_SHADOW_STYLE_OUTER_DEFAULT_SM | Small shadow. | +| ARKUI_SHADOW_STYLE_OUTER_DEFAULT_MD | Medium shadow. | +| ARKUI_SHADOW_STYLE_OUTER_DEFAULT_LG | Large shadow. | +| ARKUI_SHADOW_STYLE_OUTER_FLOATING_SM | Floating small shadow. | +| ARKUI_SHADOW_STYLE_OUTER_FLOATING_MD | Floating medium shadow. | ### ArkUI_ShadowType @@ -4031,10 +4383,10 @@ Defines the enumerated values of the shadow type. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_SHADOW_TYPE_COLOR | Color. | -| ARKUI_SHADOW_TYPE_BLUR | Blur. | +| ARKUI_SHADOW_TYPE_COLOR | Color. | +| ARKUI_SHADOW_TYPE_BLUR | Blur. | ### ArkUI_ShapeType @@ -4047,12 +4399,12 @@ Enumerates custom shape types. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_SHAPE_TYPE_RECTANGLE | Rectangle. | -| ARKUI_SHAPE_TYPE_CIRCLE | **(circle)** | -| ARKUI_SHAPE_TYPE_ELLIPSE | Ellipse. | -| ARKUI_SHAPE_TYPE_PATH | Path Type | +| ARKUI_SHAPE_TYPE_RECTANGLE | Rectangle. | +| ARKUI_SHAPE_TYPE_CIRCLE | **(circle)** | +| ARKUI_SHAPE_TYPE_ELLIPSE | Ellipse. | +| ARKUI_SHAPE_TYPE_PATH | Path Type | ### ArkUI_SliderBlockStyle @@ -4066,11 +4418,11 @@ Enumerates the styles of the slider in the block direction. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_SLIDER_BLOCK_STYLE_DEFAULT | Round slider. | -| ARKUI_SLIDER_BLOCK_STYLE_IMAGE | Slider with an image background. | -| ARKUI_SLIDER_BLOCK_STYLE_SHAPE | Slider in a custom shape. | +| ARKUI_SLIDER_BLOCK_STYLE_DEFAULT | Round slider. | +| ARKUI_SLIDER_BLOCK_STYLE_IMAGE | Slider with an image background. | +| ARKUI_SLIDER_BLOCK_STYLE_SHAPE | Slider in a custom shape. | ### ArkUI_SliderDirection @@ -4084,10 +4436,10 @@ Enumerates the scroll directions of the slider. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_SLIDER_DIRECTION_VERTICAL | Vertical direction. | -| ARKUI_SLIDER_DIRECTION_HORIZONTAL | Horizontal direction. | +| ARKUI_SLIDER_DIRECTION_VERTICAL | Vertical direction. | +| ARKUI_SLIDER_DIRECTION_HORIZONTAL | Horizontal direction. | ### ArkUI_SliderStyle @@ -4101,11 +4453,11 @@ Enumerates the slider styles. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_SLIDER_STYLE_OUT_SET | The slider is on the slider rail. | -| ARKUI_SLIDER_STYLE_IN_SET | The slider is in the slider rail. | -| ARKUI_SLIDER_STYLE_NONE | There is no thumb. | +| ARKUI_SLIDER_STYLE_OUT_SET | The slider is on the slider rail. | +| ARKUI_SLIDER_STYLE_IN_SET | The slider is in the slider rail. | +| ARKUI_SLIDER_STYLE_NONE | There is no thumb. | ### ArkUI_StickyStyle @@ -4119,12 +4471,12 @@ Enumerates the modes for pinning the header to the top or the footer to the bott **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_STICKY_STYLE_NONE | In the list item group, the header is not pinned to the top, and the footer is not pinned to the bottom. | -| ARKUI_STICKY_STYLE_HEADER | In the list item group, the header is pinned to the top, and the footer is not pinned to the bottom. | -| ARKUI_STICKY_STYLE_FOOTER | In the list item group, the footer is pinned to the bottom, and the header is not pinned to the top. | -| ARKUI_STICKY_STYLE_BOTH | In the list item group, the footer is pinned to the bottom, and the header is pinned to the top. | +| ARKUI_STICKY_STYLE_NONE | In the list item group, the header is not pinned to the top, and the footer is not pinned to the bottom. | +| ARKUI_STICKY_STYLE_HEADER | In the list item group, the header is pinned to the top, and the footer is not pinned to the bottom. | +| ARKUI_STICKY_STYLE_FOOTER | In the list item group, the footer is pinned to the bottom, and the header is not pinned to the top. | +| ARKUI_STICKY_STYLE_BOTH | In the list item group, the footer is pinned to the bottom, and the header is pinned to the top. | ### ArkUI_SwiperArrow @@ -4134,15 +4486,15 @@ enum ArkUI_SwiperArrow ``` **Description** -Enumerates arrow styles of the navigation point indicator. +Enumerates arrow styles of the navigation indicator. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_SWIPER_ARROW_HIDE | The arrow is not displayed for the navigation point indicator. | -| ARKUI_SWIPER_ARROW_SHOW | The arrow is displayed for the navigation point indicator. | -| ARKUI_SWIPER_ARROW_SHOW_ON_HOVER | The arrow is displayed only when the mouse pointer hovers over the navigation point indicator. | +| ARKUI_SWIPER_ARROW_HIDE | The arrow is not displayed for the navigation indicator. | +| ARKUI_SWIPER_ARROW_SHOW | The arrow is displayed for the navigation indicator. | +| ARKUI_SWIPER_ARROW_SHOW_ON_HOVER | The arrow is displayed only when the mouse pointer hovers over the navigation indicator. | ### ArkUI_SwiperDisplayModeType @@ -4156,10 +4508,10 @@ Enumerates the modes in which elements are displayed along the main axis of the **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_SWIPER_DISPLAY_MODE_STRETCH | The slide width of the **Swiper** component is equal to the width of the component. | -| ARKUI_SWIPER_DISPLAY_MODE_AUTO_LINEAR | The slide width of the **Swiper** component is equal to the width of the leftmost child component in the viewport. | +| ARKUI_SWIPER_DISPLAY_MODE_STRETCH | The slide width of the **Swiper** component is equal to the width of the component. | +| ARKUI_SWIPER_DISPLAY_MODE_AUTO_LINEAR | The slide width of the **Swiper** component is equal to the width of the leftmost child component in the viewport. | ### ArkUI_SwiperIndicatorType @@ -4169,14 +4521,14 @@ enum ArkUI_SwiperIndicatorType ``` **Description** -Enumerates the navigation point indicator types of the **Swiper** component. +Enumerates the navigation indicator types of the **Swiper** component. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_SWIPER_INDICATOR_TYPE_DOT | Dot type. | -| ARKUI_SWIPER_INDICATOR_TYPE_DIGIT | Digit type. | +| ARKUI_SWIPER_INDICATOR_TYPE_DOT | Dot type. | +| ARKUI_SWIPER_INDICATOR_TYPE_DIGIT | Digit type. | ### ArkUI_SwiperNestedScrollMode @@ -4190,10 +4542,10 @@ Enumerates the nested scrolling mode of the **Swiper** component and its parent **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_SWIPER_NESTED_SRCOLL_SELF_ONLY | The scrolling is contained within the **Swiper** component, and no scroll chaining occurs, that is, the parent container does not scroll when the component scrolling reaches the boundary. | -| ARKUI_SWIPER_NESTED_SRCOLL_SELF_FIRST | The **Swiper** component scrolls first, and when it hits the boundary, the parent container scrolls. When the parent container hits the boundary, its edge effect is displayed. If no edge effect is specified for the parent container, the edge effect of the child component is displayed instead. | +| ARKUI_SWIPER_NESTED_SRCOLL_SELF_ONLY | The scrolling is contained within the **Swiper** component, and no scroll chaining occurs, that is, the parent container does not scroll when the component scrolling reaches the boundary. | +| ARKUI_SWIPER_NESTED_SRCOLL_SELF_FIRST | The **Swiper** component scrolls first, and when it hits the boundary, the parent container scrolls. When the parent container hits the boundary, its edge effect is displayed. If no edge effect is specified for the parent container, the edge effect of the child component is displayed instead. | ### ArkUI_SystemColorMode @@ -4207,10 +4559,10 @@ Enumerates the system color modes. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_SYSTEM_COLOR_MODE_LIGHT | Light mode. | -| ARKUI_SYSTEM_COLOR_MODE_DARK | Dark mode. | +| ARKUI_SYSTEM_COLOR_MODE_LIGHT | Light mode. | +| ARKUI_SYSTEM_COLOR_MODE_DARK | Dark mode. | ### ArkUI_TextAlignment @@ -4224,12 +4576,12 @@ Enumerates the text alignment mode. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_TEXT_ALIGNMENT_START | Aligned with the start. | -| ARKUI_TEXT_ALIGNMENT_CENTER | Horizontally centered. | -| ARKUI_TEXT_ALIGNMENT_END | Aligned with the end. | -| ARKUI_TEXT_ALIGNMENT_JUSTIFY | Aligned with both margins. | +| ARKUI_TEXT_ALIGNMENT_START | Aligned with the start. | +| ARKUI_TEXT_ALIGNMENT_CENTER | Horizontally centered. | +| ARKUI_TEXT_ALIGNMENT_END | Aligned with the end. | +| ARKUI_TEXT_ALIGNMENT_JUSTIFY | Aligned with both margins. | ### ArkUI_TextAreaType @@ -4243,12 +4595,12 @@ Enumerates the text box types. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_TEXTAREA_TYPE_NORMAL | Normal input mode. | -| ARKUI_TEXTAREA_TYPE_NUMBER | Number input mode. | -| ARKUI_TEXTAREA_TYPE_PHONE_NUMBER | Phone number input mode. | -| ARKUI_TEXTAREA_TYPE_EMAIL | Email address input mode. | +| ARKUI_TEXTAREA_TYPE_NORMAL | Normal input mode. | +| ARKUI_TEXTAREA_TYPE_NUMBER | Number input mode. | +| ARKUI_TEXTAREA_TYPE_PHONE_NUMBER | Phone number input mode. | +| ARKUI_TEXTAREA_TYPE_EMAIL | Email address input mode. | ### ArkUI_TextCase @@ -4262,11 +4614,11 @@ Defines the enumerated values of text case. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_TEXT_CASE_NORMAL | The original case of the text is retained. | -| ARKUI_TEXT_CASE_LOWER | All letters in the text are in lowercase. | -| ARKUI_TEXT_CASE_UPPER | All letters in the text are in uppercase. | +| ARKUI_TEXT_CASE_NORMAL | The original case of the text is retained. | +| ARKUI_TEXT_CASE_LOWER | All letters in the text are in lowercase. | +| ARKUI_TEXT_CASE_UPPER | All letters in the text are in uppercase. | ### ArkUI_TextCopyOptions @@ -4280,12 +4632,12 @@ Enumerates copy options, which define whether copy and paste is allowed for text **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_TEXT_COPY_OPTIONS_NONE | Copy is not allowed. | -| ARKUI_TEXT_COPY_OPTIONS_IN_APP | Intra-application copy is allowed. | -| ARKUI_TEXT_COPY_OPTIONS_LOCAL_DEVICE | Intra-device copy is allowed. | -| ARKUI_TEXT_COPY_OPTIONS_CROSS_DEVICE | Cross-device copy is allowed. | +| ARKUI_TEXT_COPY_OPTIONS_NONE | Copy is not allowed. | +| ARKUI_TEXT_COPY_OPTIONS_IN_APP | Intra-application copy is allowed. | +| ARKUI_TEXT_COPY_OPTIONS_LOCAL_DEVICE | Intra-device copy is allowed. | +| ARKUI_TEXT_COPY_OPTIONS_CROSS_DEVICE | Cross-device copy is allowed. | ### ArkUI_TextDataDetectorType @@ -4299,12 +4651,12 @@ Enumerates the entity types of text recognition. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_TEXT_DATA_DETECTOR_TYPE_PHONE_NUMBER | Phone number. | -| ARKUI_TEXT_DATA_DETECTOR_TYPE_URL | Link. | -| ARKUI_TEXT_DATA_DETECTOR_TYPE_EMAIL | Email | -| ARKUI_TEXT_DATA_DETECTOR_TYPE_ADDRESS | Network address. | +| ARKUI_TEXT_DATA_DETECTOR_TYPE_PHONE_NUMBER | Phone number. | +| ARKUI_TEXT_DATA_DETECTOR_TYPE_URL | Link. | +| ARKUI_TEXT_DATA_DETECTOR_TYPE_EMAIL | Email | +| ARKUI_TEXT_DATA_DETECTOR_TYPE_ADDRESS | Network address. | ### ArkUI_TextDecorationStyle @@ -4318,13 +4670,13 @@ Enumerates the text decoration styles. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_TEXT_DECORATION_STYLE_SOLID | Single solid line. | -| ARKUI_TEXT_DECORATION_STYLE_DOUBLE | Double solid line. | -| ARKUI_TEXT_DECORATION_STYLE_DOTTED | Dotted line. | -| ARKUI_TEXT_DECORATION_STYLE_DASHED | Dashed style. | -| ARKUI_TEXT_DECORATION_STYLE_WAVY | Wavy line. | +| ARKUI_TEXT_DECORATION_STYLE_SOLID | Single solid line. | +| ARKUI_TEXT_DECORATION_STYLE_DOUBLE | Double solid line. | +| ARKUI_TEXT_DECORATION_STYLE_DOTTED | Dotted line. | +| ARKUI_TEXT_DECORATION_STYLE_DASHED | Dashed style. | +| ARKUI_TEXT_DECORATION_STYLE_WAVY | Wavy line. | ### ArkUI_TextDecorationType @@ -4338,12 +4690,12 @@ Enumerates the text decoration types. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_TEXT_DECORATION_TYPE_NONE | No text decoration. | -| ARKUI_TEXT_DECORATION_TYPE_UNDERLINE | Line under the text. | -| ARKUI_TEXT_DECORATION_TYPE_OVERLINE | Line over the text. | -| ARKUI_TEXT_DECORATION_TYPE_LINE_THROUGH | Line through the text. | +| ARKUI_TEXT_DECORATION_TYPE_NONE | No text decoration. | +| ARKUI_TEXT_DECORATION_TYPE_UNDERLINE | Line under the text. | +| ARKUI_TEXT_DECORATION_TYPE_OVERLINE | Line over the text. | +| ARKUI_TEXT_DECORATION_TYPE_LINE_THROUGH | Line through the text. | ### ArkUI_TextHeightAdaptivePolicy @@ -4357,11 +4709,11 @@ Defines how the adaptive height is determined for the text. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_TEXT_HEIGHT_ADAPTIVE_POLICY_MAX_LINES_FIRST | Prioritize the **maxLines** settings. | -| ARKUI_TEXT_HEIGHT_ADAPTIVE_POLICY_MIN_FONT_SIZE_FIRST | Prioritize the **minFontSize** settings. | -| ARKUI_TEXT_HEIGHT_ADAPTIVE_POLICY_LAYOUT_CONSTRAINT_FIRST | Prioritize the layout constraint settings in terms of height. | +| ARKUI_TEXT_HEIGHT_ADAPTIVE_POLICY_MAX_LINES_FIRST | Prioritize the **maxLines** settings. | +| ARKUI_TEXT_HEIGHT_ADAPTIVE_POLICY_MIN_FONT_SIZE_FIRST | Prioritize the **minFontSize** settings. | +| ARKUI_TEXT_HEIGHT_ADAPTIVE_POLICY_LAYOUT_CONSTRAINT_FIRST | Prioritize the layout constraint settings in terms of height. | ### ArkUI_TextInputContentType @@ -4375,29 +4727,41 @@ Enumerates the autofill types. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_TEXTINPUT_CONTENT_TYPE_USER_NAME | Username. Password Vault, when enabled, can automatically save and fill in usernames. | -| ARKUI_TEXTINPUT_CONTENT_TYPE_PASSWORD | Password. Password Vault, when enabled, can automatically save and fill in passwords. | -| ARKUI_TEXTINPUT_CONTENT_TYPE_NEW_PASSWORD | New password. Password Vault, when enabled, can automatically generate a new password. | -| ARKUI_TEXTINPUT_CONTENT_TYPE_FULL_STREET_ADDRESS | Full street address. The scenario-based autofill feature, when enabled, can automatically save and fill in full street addresses. | -| ARKUI_TEXTINPUT_CONTENT_TYPE_HOUSE_NUMBER | House number. The scenario-based autofill feature, when enabled, can automatically save and fill in house numbers. | -| ARKUI_TEXTINPUT_CONTENT_TYPE_DISTRICT_ADDRESS | District and county. The scenario-based autofill feature, when enabled, can automatically save and fill in districts and counties. | -| ARKUI_TEXTINPUT_CONTENT_TYPE_CITY_ADDRESS | City. The scenario-based autofill feature, when enabled, can automatically save and fill in cities. | -| ARKUI_TEXTINPUT_CONTENT_TYPE_PROVINCE_ADDRESS | Province. The scenario-based autofill feature, when enabled, can automatically save and fill in provinces. | -| ARKUI_TEXTINPUT_CONTENT_TYPE_COUNTRY_ADDRESS | Country. The scenario-based autofill feature, when enabled, can automatically save and fill in countries. | -| ARKUI_TEXTINPUT_CONTENT_TYPE_PERSON_FULL_NAME | Full name. The scenario-based autofill feature, when enabled, can automatically save and fill in full names. | -| ARKUI_TEXTINPUT_CONTENT_TYPE_PERSON_LAST_NAME | Last name. The scenario-based autofill feature, when enabled, can automatically save and fill in last names. | -| ARKUI_TEXTINPUT_CONTENT_TYPE_PERSON_FIRST_NAME | First name. The scenario-based autofill feature, when enabled, can automatically save and fill in first names. | -| ARKUI_TEXTINPUT_CONTENT_TYPE_PHONE_NUMBER | Phone number. The scenario-based autofill feature, when enabled, can automatically save and fill in phone numbers. | -| ARKUI_TEXTINPUT_CONTENT_TYPE_PHONE_COUNTRY_CODE | Country code. The scenario-based autofill feature, when enabled, can automatically save and fill in country codes. | -| ARKUI_TEXTINPUT_CONTENT_TYPE_FULL_PHONE_NUMBER | Phone number with country code. The scenario-based autofill feature, when enabled, can automatically save and fill in phone numbers with country codes. | -| ARKUI_TEXTINPUT_CONTENT_EMAIL_ADDRESS | Email address. The scenario-based autofill feature, when enabled, can automatically save and fill in email addresses. | -| ARKUI_TEXTINPUT_CONTENT_TYPE_BANK_CARD_NUMBER | Bank card number. The scenario-based autofill feature, when enabled, can automatically save and fill in bank card numbers. | -| ARKUI_TEXTINPUT_CONTENT_TYPE_ID_CARD_NUMBER | ID card number. The scenario-based autofill feature, when enabled, can automatically save and fill in ID card numbers. | -| ARKUI_TEXTINPUT_CONTENT_TYPE_NICKNAME | Nickname. The scenario-based autofill feature, when enabled, can automatically save and fill in nicknames. | -| ARKUI_TEXTINPUT_CONTENT_TYPE_DETAIL_INFO_WITHOUT_STREET | Address information without street address. The scenario-based autofill feature, when enabled, can automatically save and fill in address information without street addresses. | -| ARKUI_TEXTINPUT_CONTENT_TYPE_FORMAT_ADDRESS | Standard address. The scenario-based autofill feature, when enabled, can automatically save and fill in standard addresses. | +| ARKUI_TEXTINPUT_CONTENT_TYPE_USER_NAME | Username. Password Vault, when enabled, can automatically save and fill in usernames. | +| ARKUI_TEXTINPUT_CONTENT_TYPE_PASSWORD | Password. Password Vault, when enabled, can automatically save and fill in passwords. | +| ARKUI_TEXTINPUT_CONTENT_TYPE_NEW_PASSWORD | New password. Password Vault, when enabled, can automatically generate a new password. | +| ARKUI_TEXTINPUT_CONTENT_TYPE_FULL_STREET_ADDRESS | Full street address. The scenario-based autofill feature, when enabled, can automatically save and fill in full street addresses. | +| ARKUI_TEXTINPUT_CONTENT_TYPE_HOUSE_NUMBER | House number. The scenario-based autofill feature, when enabled, can automatically save and fill in house numbers. | +| ARKUI_TEXTINPUT_CONTENT_TYPE_DISTRICT_ADDRESS | District and county. The scenario-based autofill feature, when enabled, can automatically save and fill in districts and counties. | +| ARKUI_TEXTINPUT_CONTENT_TYPE_CITY_ADDRESS | City. The scenario-based autofill feature, when enabled, can automatically save and fill in cities. | +| ARKUI_TEXTINPUT_CONTENT_TYPE_PROVINCE_ADDRESS | Province. The scenario-based autofill feature, when enabled, can automatically save and fill in provinces. | +| ARKUI_TEXTINPUT_CONTENT_TYPE_COUNTRY_ADDRESS | Country. The scenario-based autofill feature, when enabled, can automatically save and fill in countries. | +| ARKUI_TEXTINPUT_CONTENT_TYPE_PERSON_FULL_NAME | Full name. The scenario-based autofill feature, when enabled, can automatically save and fill in full names. | +| ARKUI_TEXTINPUT_CONTENT_TYPE_PERSON_LAST_NAME | Last name. The scenario-based autofill feature, when enabled, can automatically save and fill in last names. | +| ARKUI_TEXTINPUT_CONTENT_TYPE_PERSON_FIRST_NAME | First name. The scenario-based autofill feature, when enabled, can automatically save and fill in first names. | +| ARKUI_TEXTINPUT_CONTENT_TYPE_PHONE_NUMBER | Phone number. The scenario-based autofill feature, when enabled, can automatically save and fill in phone numbers. | +| ARKUI_TEXTINPUT_CONTENT_TYPE_PHONE_COUNTRY_CODE | Country code. The scenario-based autofill feature, when enabled, can automatically save and fill in country codes. | +| ARKUI_TEXTINPUT_CONTENT_TYPE_FULL_PHONE_NUMBER | Phone number with country code. The scenario-based autofill feature, when enabled, can automatically save and fill in phone numbers with country codes. | +| ARKUI_TEXTINPUT_CONTENT_EMAIL_ADDRESS | Email address. The scenario-based autofill feature, when enabled, can automatically save and fill in email addresses. | +| ARKUI_TEXTINPUT_CONTENT_TYPE_BANK_CARD_NUMBER | Bank card number. The scenario-based autofill feature, when enabled, can automatically save and fill in bank card numbers. | +| ARKUI_TEXTINPUT_CONTENT_TYPE_ID_CARD_NUMBER | ID card number. The scenario-based autofill feature, when enabled, can automatically save and fill in ID card numbers. | +| ARKUI_TEXTINPUT_CONTENT_TYPE_NICKNAME | Nickname. The scenario-based autofill feature, when enabled, can automatically save and fill in nicknames. | +| ARKUI_TEXTINPUT_CONTENT_TYPE_DETAIL_INFO_WITHOUT_STREET | Address information without street address. The scenario-based autofill feature, when enabled, can automatically save and fill in address information without street addresses. | +| ARKUI_TEXTINPUT_CONTENT_TYPE_FORMAT_ADDRESS | Standard address. The scenario-based autofill feature, when enabled, can automatically save and fill in standard addresses. | +| ARKUI_TEXTINPUT_CONTENT_TYPE_PASSPORT_NUMBER | Passport number. The scenario-based autofill feature, when enabled, can automatically save and fill in passport numbers. | +| ARKUI_TEXTINPUT_CONTENT_TYPE_VALIDITY | Passport validity period. The scenario-based autofill feature, when enabled, can automatically save and fill in passport validity periods. | +| ARKUI_TEXTINPUT_CONTENT_TYPE_ISSUE_AT | Passport place of issue. The scenario-based autofill feature, when enabled, can automatically save and fill in the place of issue for passports. | +| ARKUI_TEXTINPUT_CONTENT_TYPE_ORGANIZATION | Invoice title. The scenario-based autofill feature, when enabled, can automatically save and fill in invoice titles. | +| ARKUI_TEXTINPUT_CONTENT_TYPE_TAX_ID | Tax ID. The scenario-based autofill feature, when enabled, can automatically save and fill in tax IDs. | +| ARKUI_TEXTINPUT_CONTENT_TYPE_ADDRESS_CITY_AND_STATE | Location. The scenario-based autofill feature, when enabled, can automatically save and fill in locations. | +| ARKUI_TEXTINPUT_CONTENT_TYPE_FLIGHT_NUMBER | Flight number. Currently not supported for automatic saving and auto-filling. | +| ARKUI_TEXTINPUT_CONTENT_TYPE_LICENSE_NUMBER | Driver's license number. Currently not supported for automatic saving and auto-filling. | +| ARKUI_TEXTINPUT_CONTENT_TYPE_LICENSE_FILE_NUMBER | Driver's license file number. Currently not supported for automatic saving and auto-filling.| +| ARKUI_TEXTINPUT_CONTENT_TYPE_LICENSE_PLATE | License plate number. The scenario-based autofill feature, when enabled, can automatically save and fill in license plate numbers. | +| ARKUI_TEXTINPUT_CONTENT_TYPE_ENGINE_NUMBER | Vehicle registration engine number. Currently not supported for automatic saving and auto-filling. | +| ARKUI_TEXTINPUT_CONTENT_TYPE_LICENSE_CHASSIS_NUMBER | Chassis number. Currently not supported for automatic saving and auto-filling. | ### ArkUI_TextInputStyle @@ -4411,10 +4775,10 @@ Enumerates the text input styles. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_TEXTINPUT_STYLE_DEFAULT | Default style. The caret width is fixed at 1.5 vp, and the caret height is subject to the background height and font size of the selected text. | -| ARKUI_TEXTINPUT_STYLE_INLINE | Inline input style. The background height of the selected text is the same as the height of the text box. | +| ARKUI_TEXTINPUT_STYLE_DEFAULT | Default style. The caret width is fixed at 1.5 vp, and the caret height is subject to the background height and font size of the selected text. | +| ARKUI_TEXTINPUT_STYLE_INLINE | Inline input style. The background height of the selected text is the same as the height of the text box. | ### ArkUI_TextInputType @@ -4428,18 +4792,18 @@ Enumerates the text input types. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_TEXTINPUT_TYPE_NORMAL | Normal input mode. | -| ARKUI_TEXTINPUT_TYPE_NUMBER | Number input mode. | -| ARKUI_TEXTINPUT_TYPE_PHONE_NUMBER | Phone number input mode. | -| ARKUI_TEXTINPUT_TYPE_EMAIL | Email address input mode. | -| ARKUI_TEXTINPUT_TYPE_PASSWORD | Password input mode. | -| ARKUI_TEXTINPUT_TYPE_NUMBER_PASSWORD | Numeric password input mode. | -| ARKUI_TEXTINPUT_TYPE_SCREEN_LOCK_PASSWORD | Lock screen password input mode. | -| ARKUI_TEXTINPUT_TYPE_USER_NAME | Username input mode. | -| ARKUI_TEXTINPUT_TYPE_NEW_PASSWORD | New password input mode. | -| ARKUI_TEXTINPUT_TYPE_NUMBER_DECIMAL | Number input mode with a decimal point. | +| ARKUI_TEXTINPUT_TYPE_NORMAL | Normal input mode. | +| ARKUI_TEXTINPUT_TYPE_NUMBER | Number input mode. | +| ARKUI_TEXTINPUT_TYPE_PHONE_NUMBER | Phone number input mode. | +| ARKUI_TEXTINPUT_TYPE_EMAIL | Email address input mode. | +| ARKUI_TEXTINPUT_TYPE_PASSWORD | Password input mode. | +| ARKUI_TEXTINPUT_TYPE_NUMBER_PASSWORD | Numeric password input mode. | +| ARKUI_TEXTINPUT_TYPE_SCREEN_LOCK_PASSWORD | Lock screen password input mode. | +| ARKUI_TEXTINPUT_TYPE_USER_NAME | Username input mode. | +| ARKUI_TEXTINPUT_TYPE_NEW_PASSWORD | New password input mode. | +| ARKUI_TEXTINPUT_TYPE_NUMBER_DECIMAL | Number input mode with a decimal point. | ### ArkUI_TextOverflow @@ -4453,12 +4817,12 @@ Enumerates the display modes when the text is too long. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_TEXT_OVERFLOW_NONE | Extra-long text is not clipped. | -| ARKUI_TEXT_OVERFLOW_CLIP | Extra-long text is clipped. | -| ARKUI_TEXT_OVERFLOW_ELLIPSIS | An ellipsis (...) is used to represent text overflow. | -| ARKUI_TEXT_OVERFLOW_MARQUEE | Text continuously scrolls when text overflow occurs. | +| ARKUI_TEXT_OVERFLOW_NONE | Extra-long text is not clipped. | +| ARKUI_TEXT_OVERFLOW_CLIP | Extra-long text is clipped. | +| ARKUI_TEXT_OVERFLOW_ELLIPSIS | An ellipsis (...) is used to represent text overflow. | +| ARKUI_TEXT_OVERFLOW_MARQUEE | Text continuously scrolls when text overflow occurs. | ### ArkUI_TextPickerRangeType @@ -4472,12 +4836,12 @@ Enumerates the types of the text picker. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_TEXTPICKER_RANGETYPE_SINGLE | Single-column text picker. | -| ARKUI_TEXTPICKER_RANGETYPE_MULTI | Multi-column text picker. | -| ARKUI_TEXTPICKER_RANGETYPE_RANGE_CONTENT | Single-column text picker with image resources. | -| ARKUI_TEXTPICKER_RANGETYPE_CASCADE_RANGE_CONTENT | Interconnected multi-column text picker. | +| ARKUI_TEXTPICKER_RANGETYPE_SINGLE | Single-column text picker. | +| ARKUI_TEXTPICKER_RANGETYPE_MULTI | Multi-column text picker. | +| ARKUI_TEXTPICKER_RANGETYPE_RANGE_CONTENT | Single-column text picker with image resources. | +| ARKUI_TEXTPICKER_RANGETYPE_CASCADE_RANGE_CONTENT | Interconnected multi-column text picker. | ### ArkUI_ThemeColorMode @@ -4486,11 +4850,11 @@ Enumerates the types of the text picker. enum ArkUI_ThemeColorMode ``` -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_THEME_COLOR_MODE_SYSTEM | Following the system color mode. | -| ARKUI_THEME_COLOR_MODE_LIGHT | Light color mode. | -| ARKUI_THEME_COLOR_MODE_DARK | Dark color mode. | +| ARKUI_THEME_COLOR_MODE_SYSTEM | Following the system color mode. | +| ARKUI_THEME_COLOR_MODE_LIGHT | Light color mode. | +| ARKUI_THEME_COLOR_MODE_DARK | Dark color mode. | ### ArkUI_TransitionEdge @@ -4504,12 +4868,12 @@ Enumerates the slide-in and slide-out positions of the component from the screen **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_TRANSITION_EDGE_TOP | Top edge of the window. | -| ARKUI_TRANSITION_EDGE_BOTTOM | Bottom edge of the window. | -| ARKUI_TRANSITION_EDGE_START | Left edge of the window. | -| ARKUI_TRANSITION_EDGE_END | Right edge of the window. | +| ARKUI_TRANSITION_EDGE_TOP | Top edge of the window. | +| ARKUI_TRANSITION_EDGE_BOTTOM | Bottom edge of the window. | +| ARKUI_TRANSITION_EDGE_START | Left edge of the window. | +| ARKUI_TRANSITION_EDGE_END | Right edge of the window. | ### ArkUI_VerticalAlignment @@ -4523,11 +4887,11 @@ Enumerates the vertical alignment modes. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_VERTICAL_ALIGNMENT_TOP | Top aligned. | -| ARKUI_VERTICAL_ALIGNMENT_CENTER | Aligned with the center. This is the default alignment mode. | -| ARKUI_VERTICAL_ALIGNMENT_BOTTOM | Bottom aligned. | +| ARKUI_VERTICAL_ALIGNMENT_TOP | Top aligned. | +| ARKUI_VERTICAL_ALIGNMENT_CENTER | Aligned with the center. This is the default alignment mode. | +| ARKUI_VERTICAL_ALIGNMENT_BOTTOM | Bottom aligned. | ### ArkUI_Visibility @@ -4541,11 +4905,11 @@ Enumerates the visibility values. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_VISIBILITY_VISIBLE | Display | -| ARKUI_VISIBILITY_HIDDEN | The component is hidden, and a placeholder is used for it in the layout. | -| ARKUI_VISIBILITY_NONE | The component is hidden. It is not involved in the layout, and no placeholder is used for it. | +| ARKUI_VISIBILITY_VISIBLE | Display | +| ARKUI_VISIBILITY_HIDDEN | The component is hidden, and a placeholder is used for it in the layout. | +| ARKUI_VISIBILITY_NONE | The component is hidden. It is not involved in the layout, and no placeholder is used for it. | ### ArkUI_WordBreak @@ -4559,11 +4923,12 @@ Enumerates the word break rules. **Since**: 12 -| Enum| Description| +| Enum| Description| | -------- | -------- | -| ARKUI_WORD_BREAK_NORMAL | Word breaks can occur between any two characters for Chinese, Japanese, and Korean (CJK) text, but can occur only at a space character for non-CJK text (such as English). | -| ARKUI_WORD_BREAK_BREAK_ALL | Word breaks can occur between any two characters for non-CJK text. CJK text behavior is the same as for **NORMAL**. | -| ARKUI_WORD_BREAK_BREAK_WORD | This option has the same effect as **BREAK_ALL** for non-CJK text, except that if it preferentially wraps lines at appropriate characters (for example, spaces) whenever possible. CJK text behavior is the same as for **NORMAL**. | +| ARKUI_WORD_BREAK_NORMAL | Word breaks can occur between any two characters for Chinese, Japanese, and Korean (CJK) text, but can occur only at a space character for non-CJK text (such as English). | +| ARKUI_WORD_BREAK_BREAK_ALL | Word breaks can occur between any two characters for non-CJK text. CJK text behavior is the same as for **NORMAL**. | +| ARKUI_WORD_BREAK_BREAK_WORD | This option has the same effect as **BREAK_ALL** for non-CJK text, except that if it preferentially wraps lines at appropriate characters (for example, spaces) whenever possible. CJK text behavior is the same as for **NORMAL**. | +| ARKUI_WORD_BREAK_HYPHENATION | **Since**: 16 Line breaks can occur between any two syllabic units for non-CJK text. CJK text behavior is the same as for **NORMAL**. | ### ArkUI_XComponentType @@ -4577,10 +4942,60 @@ Defines the enumerated values of the XComponent type. **Since**: 12 +| Enum| Description| +| -------- | -------- | +| ARKUI_XCOMPONENT_TYPE_SURFACE | The custom content of EGL/OpenGL ES and media data is displayed individually on the screen. | +| ARKUI_XCOMPONENT_TYPE_TEXTURE | The custom content of EGL/OpenGL ES and media data is grouped and displayed together with content of the component. | + +### ArkUI_KeyboardAppearance + +``` +enum ArkUI_KeyboardAppearance +``` +**Description** + +Enumerates the appearance modes of the keyboard when the text box is focused. + +**Since**: 15 + +| Enum| Description| +| -------- | -------- | +| ARKUI_KEYBOARD_APPEARANCE_NONE_IMMERSIVE | Default appearance mode, not using the immersive style. | +| ARKUI_KEYBOARD_APPEARANCE_IMMERSIVE | Immersive style, following the system color mode. | +| ARKUI_KEYBOARD_APPEARANCE_LIGHT_IMMERSIVE | Immersive style in light mode. | +| ARKUI_KEYBOARD_APPEARANCE_DARK_IMMERSIVE | Immersive style in dark mode. | + +### ArkUI_KeyboardAvoidMode + +``` +enum ArkUI_KeyboardAvoidMode +``` +**Description** + +Enumerates the keyboard avoidance modes of the dialog box. + +**Since**: 18 + +| Enum| Description| +| -------- | -------- | +| ARKUI_KEYBOARD_AVOID_MODE_DEFAULT | Automatically avoids the soft keyboard and compresses the height when reaching the maximum limit. | +| ARKUI_KEYBOARD_AVOID_MODE_NONE | Does not avoid the soft keyboard. | + +### ArkUI_HoverModeAreaType + +``` +enum ArkUI_HoverModeAreaType +``` +**Description** + +Enumerates the default display areas of a dialog box in hover mode. + +**Since**: 18 + | Enum| Description| | -------- | -------- | -| ARKUI_XCOMPONENT_TYPE_SURFACE | The custom content of EGL/OpenGL ES and media data is displayed individually on the screen. | -| ARKUI_XCOMPONENT_TYPE_TEXTURE | The custom content of EGL/OpenGL ES and media data is grouped and displayed together with content of the component. | +| ARKUI_HOVER_MODE_AREA_TYPE_TOP | Upper half screen. | +| ARKUI_HOVER_MODE_AREA_TYPE_BOTTOM | Lower half screen. | ## Function Description @@ -4615,9 +5030,9 @@ Disposes of the pointer to an accessibility state. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| state | Pointer to an accessibility state object. | +| state | Pointer to an accessibility state object. | ### OH_ArkUI_AccessibilityState_GetCheckedState() @@ -4633,9 +5048,9 @@ Obtains the check box state of an accessibility state. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| state | Pointer to an accessibility state object. | +| state | Pointer to an accessibility state object. | **Returns** @@ -4655,9 +5070,9 @@ Obtains whether an accessibility state is disabled. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| state | Pointer to an accessibility state object. | +| state | Pointer to an accessibility state object. | **Returns** @@ -4677,9 +5092,9 @@ Obtains whether an accessibility state is selected. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| state | Pointer to an accessibility state object. | +| state | Pointer to an accessibility state object. | **Returns** @@ -4699,10 +5114,10 @@ Sets the check box state of an accessibility state. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| state | Pointer to an accessibility state object. | -| checkedState | Check box status. The parameter type is [ArkUI_AccessibilityCheckedState](#arkui_accessibilitycheckedstate). The default value is **ARKUI_ACCESSIBILITY_UNCHECKED**. | +| state | Pointer to an accessibility state object. | +| checkedState | Check box status. The parameter type is [ArkUI_AccessibilityCheckedState](#arkui_accessibilitycheckedstate). The default value is **ARKUI_ACCESSIBILITY_UNCHECKED**. | ### OH_ArkUI_AccessibilityState_SetDisabled() @@ -4718,10 +5133,10 @@ Sets whether an accessibility state is disabled. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| state | Pointer to an accessibility state object. | -| isDisabled | Whether the accessibility state is disabled. The value **1** means that the accessibility state is disabled, and **0** means the opposite. The default value is **0**. | +| state | Pointer to an accessibility state object. | +| isDisabled | Whether the accessibility state is disabled. The value **1** means that the accessibility state is disabled, and **0** means the opposite. The default value is **0**. | ### OH_ArkUI_AccessibilityState_SetSelected() @@ -4737,10 +5152,10 @@ Sets whether an accessibility state is selected. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| state | Pointer to an accessibility state object. | -| isSelected | Whether the accessibility state is selected. The value **1** means that the accessibility state is selected, and **0** means the opposite. The default value is **0**. | +| state | Pointer to an accessibility state object. | +| isSelected | Whether the accessibility state is selected. The value **1** means that the accessibility state is selected, and **0** means the opposite. The default value is **0**. | ### OH_ArkUI_AccessibilityValue_Create() @@ -4772,9 +5187,9 @@ Disposes of the pointer to an **AccessibilityValue** instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| state | Pointer to an **AccessibilityValue** instance. | +| state | Pointer to an **AccessibilityValue** instance. | ### OH_ArkUI_AccessibilityValue_GetCurrent() @@ -4790,9 +5205,9 @@ Obtains the current accessibility value. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| value | Pointer to an **AccessibilityValue** instance. | +| value | Pointer to an **AccessibilityValue** instance. | **Returns** @@ -4812,9 +5227,9 @@ Obtains the maximum accessibility value. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| value | Pointer to an **AccessibilityValue** instance. | +| value | Pointer to an **AccessibilityValue** instance. | **Returns** @@ -4834,9 +5249,9 @@ Obtains the minimum accessibility value. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| value | Pointer to an **AccessibilityValue** instance. | +| value | Pointer to an **AccessibilityValue** instance. | **Returns** @@ -4856,9 +5271,9 @@ Obtains the text description of an **AccessibilityValue** instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| value | Pointer to an **AccessibilityValue** instance. | +| value | Pointer to an **AccessibilityValue** instance. | **Returns** @@ -4878,10 +5293,10 @@ Sets the current accessibility value. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| value | Pointer to an **AccessibilityValue** instance. | -| current | Current value based on the range component. The default value is **-1**. | +| value | Pointer to an **AccessibilityValue** instance. | +| current | Current value based on the range component. The default value is **-1**. | ### OH_ArkUI_AccessibilityValue_SetMax() @@ -4897,10 +5312,10 @@ Sets the maximum accessibility value. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| value | Pointer to an **AccessibilityValue** instance. | -| max | Maximum value based on the range component. The default value is **-1**. | +| value | Pointer to an **AccessibilityValue** instance. | +| max | Maximum value based on the range component. The default value is **-1**. | ### OH_ArkUI_AccessibilityValue_SetMin() @@ -4916,10 +5331,10 @@ Sets the minimum accessibility value. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| value | Pointer to an **AccessibilityValue** instance. | -| min | Minimum value based on the range component. The default value is **-1**. | +| value | Pointer to an **AccessibilityValue** instance. | +| min | Minimum value based on the range component. The default value is **-1**. | ### OH_ArkUI_AccessibilityValue_SetText() @@ -4935,10 +5350,10 @@ Sets the text description of an **AccessibilityValue** instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| value | Pointer to an **AccessibilityValue** instance. | -| text | Text description. The default value is an empty string. | +| value | Pointer to an **AccessibilityValue** instance. | +| text | Text description. The default value is an empty string. | ### OH_ArkUI_ActiveChildrenInfo_Destroy() @@ -5024,9 +5439,9 @@ Disposes of an alignment rule configuration of this **RelativeContainer** compon **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an alignment rule configuration. | +| option | Pointer to an alignment rule configuration. | ### OH_ArkUI_AlignmentRuleOption_GetBiasHorizontal() @@ -5042,9 +5457,9 @@ Obtains the bias value in the horizontal direction. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an alignment rule configuration. | +| option | Pointer to an alignment rule configuration. | **Returns** @@ -5064,9 +5479,9 @@ Obtains the bias value in the vertical direction. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an alignment rule configuration. | +| option | Pointer to an alignment rule configuration. | **Returns** @@ -5086,9 +5501,9 @@ Obtains the alignment mode in bottom alignment parameters. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an alignment rule configuration. | +| option | Pointer to an alignment rule configuration. | **Returns** @@ -5102,15 +5517,15 @@ const char* OH_ArkUI_AlignmentRuleOption_GetBottomId (ArkUI_AlignmentRuleOption ``` **Description** -Obtains the ID in bottom alignment parameters. +Obtains the alignment mode in bottom alignment parameters. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an alignment rule configuration. | +| option | Pointer to an alignment rule configuration. | **Returns** @@ -5130,14 +5545,15 @@ Obtains the alignment mode in horizontal center alignment parameters. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an alignment rule configuration. | +| option | Pointer to an alignment rule configuration. | **Returns** Returns the alignment mode in horizontal center alignment parameters. + ### OH_ArkUI_AlignmentRuleOption_GetCenterAlignmentVertical() ``` @@ -5145,19 +5561,19 @@ ArkUI_VerticalAlignment OH_ArkUI_AlignmentRuleOption_GetCenterAlignmentVertical ``` **Description** -Obtains the alignment mode in vertical center alignment parameters. +Obtains the ID in vertical center alignment parameters. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an alignment rule configuration. | +| option | Pointer to an alignment rule configuration. | **Returns** -Returns the alignment mode in vertical center alignment parameters. +Returns the vertical center alignment parameters. ### OH_ArkUI_AlignmentRuleOption_GetCenterIdHorizontal() @@ -5173,13 +5589,13 @@ Obtains the alignment mode in horizontal center alignment parameters. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an alignment rule configuration. | +| option | Pointer to an alignment rule configuration. | **Returns** -Returns the alignment mode in horizontal center alignment parameters. +Returns the ID in horizontal center alignment parameters. ### OH_ArkUI_AlignmentRuleOption_GetCenterIdVertical() @@ -5195,9 +5611,9 @@ Obtains the ID in vertical center alignment parameters. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an alignment rule configuration. | +| option | Pointer to an alignment rule configuration. | **Returns** @@ -5217,9 +5633,9 @@ Obtains the alignment mode in the right alignment parameters. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an alignment rule configuration. | +| option | Pointer to an alignment rule configuration. | **Returns** @@ -5233,15 +5649,15 @@ const char* OH_ArkUI_AlignmentRuleOption_GetEndId (ArkUI_AlignmentRuleOption * o ``` **Description** -Obtains the ID in the right alignment parameters. +Obtains the alignment mode in the right alignment parameters. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an alignment rule configuration. | +| option | Pointer to an alignment rule configuration. | **Returns** @@ -5261,9 +5677,9 @@ Obtains the alignment mode in left alignment parameters. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an alignment rule configuration. | +| option | Pointer to an alignment rule configuration. | **Returns** @@ -5283,9 +5699,9 @@ Obtains the ID in the left alignment parameters. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an alignment rule configuration. | +| option | Pointer to an alignment rule configuration. | **Returns** @@ -5305,9 +5721,9 @@ Obtains the alignment mode in top alignment parameters. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an alignment rule configuration. | +| option | Pointer to an alignment rule configuration. | **Returns** @@ -5321,15 +5737,15 @@ const char* OH_ArkUI_AlignmentRuleOption_GetTopId (ArkUI_AlignmentRuleOption * o ``` **Description** -Obtains the ID in top alignment parameters. +Obtains the alignment mode in top alignment parameters. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an alignment rule configuration. | +| option | Pointer to an alignment rule configuration. | **Returns** @@ -5349,10 +5765,10 @@ Sets the bias value of the component in the horizontal direction under the ancho **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an alignment rule configuration. | -| horizontal | Bias value in the horizontal direction. | +| option | Pointer to an alignment rule configuration. | +| horizontal | Bias value in the horizontal direction. | ### OH_ArkUI_AlignmentRuleOption_SetBiasVertical() @@ -5368,10 +5784,10 @@ Sets the bias value of the component in the vertical direction under the anchor **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an alignment rule configuration. | -| horizontal | Bias value in the vertical direction. | +| option | Pointer to an alignment rule configuration. | +| horizontal | Bias value in the vertical direction. | ### OH_ArkUI_AlignmentRuleOption_SetBottom() @@ -5387,11 +5803,11 @@ Sets the bottom alignment parameters. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an alignment rule configuration. | -| id | ID of the anchor component. | -| value | Alignment mode relative to the anchor component. | +| option | Pointer to an alignment rule configuration. | +| id | ID of the anchor component. | +| value | Alignment mode relative to the anchor component. | ### OH_ArkUI_AlignmentRuleOption_SetCenterHorizontal() @@ -5407,11 +5823,11 @@ Sets the horizontal center alignment parameters. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an alignment rule configuration. | -| id | ID of the anchor component. | -| value | Alignment mode relative to the anchor component. | +| option | Pointer to an alignment rule configuration. | +| id | ID of the anchor component. | +| value | Alignment mode relative to the anchor component. | ### OH_ArkUI_AlignmentRuleOption_SetCenterVertical() @@ -5427,11 +5843,11 @@ Sets the vertical center alignment parameters. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an alignment rule configuration. | -| id | ID of the anchor component. | -| value | Alignment mode relative to the anchor component. | +| option | Pointer to an alignment rule configuration. | +| id | ID of the anchor component. | +| value | Alignment mode relative to the anchor component. | ### OH_ArkUI_AlignmentRuleOption_SetEnd() @@ -5447,11 +5863,11 @@ Sets the right alignment parameters. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an alignment rule configuration. | -| id | ID of the anchor component. | -| value | Alignment mode relative to the anchor component. | +| option | Pointer to an alignment rule configuration. | +| id | ID of the anchor component. | +| value | Alignment mode relative to the anchor component. | ### OH_ArkUI_AlignmentRuleOption_SetStart() @@ -5467,11 +5883,11 @@ Sets the left alignment parameters. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an alignment rule configuration. | -| id | ID of the anchor component. | -| value | Alignment mode relative to the anchor component. | +| option | Pointer to an alignment rule configuration. | +| id | ID of the anchor component. | +| value | Alignment mode relative to the anchor component. | ### OH_ArkUI_AlignmentRuleOption_SetTop() @@ -5487,11 +5903,11 @@ Sets the top alignment parameters. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an alignment rule configuration. | -| id | ID of the anchor component. | -| value | Alignment mode relative to the anchor component. | +| option | Pointer to an alignment rule configuration. | +| id | ID of the anchor component. | +| value | Alignment mode relative to the anchor component. | ### OH_ArkUI_AllowNodeAllDropDataTypes() @@ -5507,9 +5923,9 @@ Configures the specified component to allow any data types. This API resets the **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | Pointer to a component node. | +| node | Pointer to a component node. | **Returns** @@ -5557,9 +5973,9 @@ Obtains an animation curve. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an animation configuration. | +| option | Pointer to an animation configuration. | **Returns** @@ -5579,9 +5995,9 @@ Obtains the animation delay, in milliseconds. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an animation configuration. | +| option | Pointer to an animation configuration. | **Returns** @@ -5601,9 +6017,9 @@ Obtains the animation duration, in milliseconds. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an animation configuration. | +| option | Pointer to an animation configuration. | **Returns** @@ -5623,9 +6039,9 @@ Obtains the expected frame rate range of an animation. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an animation configuration. | +| option | Pointer to an animation configuration. | **Returns** @@ -5645,9 +6061,9 @@ Obtains the animation curve of an animation. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an animation configuration. | +| option | Pointer to an animation configuration. | **Returns** @@ -5667,9 +6083,9 @@ Obtains the number of times that an animation is played. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an animation configuration. | +| option | Pointer to an animation configuration. | **Returns** @@ -5688,9 +6104,9 @@ Obtains the playback mode of an animation. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an animation configuration. | +| option | Pointer to an animation configuration. | **Returns** @@ -5710,9 +6126,9 @@ Obtains the playback speed of an animation. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an animation configuration. | +| option | Pointer to an animation configuration. | **Returns** @@ -5732,10 +6148,10 @@ Sets the animation curve. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an animation configuration. | -| value | Animation curve. Default value: **ARKUI_CURVE_LINEAR**. | +| option | Pointer to an animation configuration. | +| value | Returns the animation curve. Default value: **ARKUI_CURVE_LINEAR**. | ### OH_ArkUI_AnimateOption_SetDelay() @@ -5751,10 +6167,10 @@ Sets the animation delay. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an animation configuration. | -| value | Delay of animation playback. | +| option | Pointer to an animation configuration. | +| value | Delay of animation playback. | ### OH_ArkUI_AnimateOption_SetDuration() @@ -5770,10 +6186,10 @@ Sets the animation duration. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an animation configuration. | -| value | Duration, in milliseconds. | +| option | Pointer to an animation configuration. | +| value | Duration, in milliseconds. | ### OH_ArkUI_AnimateOption_SetExpectedFrameRateRange() @@ -5789,10 +6205,10 @@ Sets the expected frame rate range of the animation. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an animation configuration. | -| value | Expected frame rate range of the animation. | +| option | Pointer to an animation configuration. | +| value | Expected frame rate range of the animation. | ### OH_ArkUI_AnimateOption_SetICurve() @@ -5808,10 +6224,10 @@ Sets the animation curve for an animation. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an animation configuration. | -| value | Animation curve settings. | +| option | Pointer to an animation configuration. | +| value | Animation curve settings. | **NOTE** @@ -5831,10 +6247,10 @@ Sets the number of times that an animation is played. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an animation configuration. | -| value | Number of times that the animation is played. | +| option | Pointer to an animation configuration. | +| value | Number of times that the animation is played. | ### OH_ArkUI_AnimateOption_SetPlayMode() @@ -5850,10 +6266,10 @@ Sets the playback mode for an animation. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an animation configuration. | -| value | Animation playback mode. | +| option | Pointer to an animation configuration. | +| value | Animation playback mode. | ### OH_ArkUI_AnimateOption_SetTempo() @@ -5869,10 +6285,10 @@ Sets the playback speed of an animation. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an animation configuration. | -| value | Animation playback speed. | +| option | Pointer to an animation configuration. | +| value | Animation playback speed. | ### OH_ArkUI_Animator_Cancel() @@ -5886,9 +6302,9 @@ Cancels the animation of an animator. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| animator | Animator object. | +| animator | Animator object. | **Returns** @@ -5906,9 +6322,9 @@ Ends the animation of an animator. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| animator | Animator object. | +| animator | Animator object. | **Returns** @@ -5926,9 +6342,9 @@ Pauses the animation of an animator. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| animator | Animator object. | +| animator | Animator object. | **Returns** @@ -5946,9 +6362,9 @@ Starts the animation of an animator. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| animator | Animator object. | +| animator | Animator object. | **Returns** @@ -5966,10 +6382,10 @@ Resets an animator configuration. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| animator | Animator object. | -| option | Pointer to an animation configuration. | +| animator | Animator object. | +| option | Pointer to an animation configuration. | **Returns** @@ -5987,9 +6403,9 @@ Plays the animation of an animator in reverse order. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| animator | Animator object. | +| animator | Animator object. | **Returns** @@ -6009,9 +6425,9 @@ Obtains the custom object in an animation event object. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Animation event object. | +| event | Animation event object. | **Returns** @@ -6031,9 +6447,9 @@ Obtains the custom object in an animation event object. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Animation event object. | +| event | Animation event object. | **Returns** @@ -6053,9 +6469,9 @@ Obtains the current progress in an animation event object. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Animation event object. | +| event | Animation event object. | **Returns** @@ -6075,9 +6491,9 @@ Creates an animator parameter object. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| keyframeSize | Number of keyframes. | +| keyframeSize | Number of keyframes. | **NOTE** @@ -6113,9 +6529,9 @@ Obtains the interpolation start point of an animation. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an animation configuration. | +| option | Pointer to an animation configuration. | **Returns** @@ -6135,9 +6551,9 @@ Obtains the interpolation curve of the animation of an animator. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an animation configuration. | +| option | Pointer to an animation configuration. | **Returns** @@ -6157,9 +6573,9 @@ Obtains the delay for playing an animation. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an animation configuration. | +| option | Pointer to an animation configuration. | **Returns** @@ -6179,9 +6595,9 @@ Obtains the playback direction of an animation. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an animation configuration. | +| option | Pointer to an animation configuration. | **Returns** @@ -6201,9 +6617,9 @@ Obtains the duration for playing an animation. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an animation configuration. | +| option | Pointer to an animation configuration. | **Returns** @@ -6223,9 +6639,9 @@ Obtains the interpolation end point of an animation. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an animation configuration. | +| option | Pointer to an animation configuration. | **Returns** @@ -6245,9 +6661,9 @@ Obtains the expected frame rate range of an animation. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an animation configuration. | +| option | Pointer to an animation configuration. | **Returns** @@ -6267,9 +6683,9 @@ Obtains whether the animator animation is restored to the initial state after be **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an animation configuration. | +| option | Pointer to an animation configuration. | **Returns** @@ -6289,9 +6705,9 @@ Obtains the number of times that an animation is played. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an **AnimatorOption** object. | +| option | Pointer to an **AnimatorOption** object. | **Returns** @@ -6311,10 +6727,10 @@ Obtains the interpolation curve for a keyframe in the animation of an animator. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an **AnimatorOption** object. | -| index | Keyframe index. | +| option | Pointer to an **AnimatorOption** object. | +| index | Keyframe index. | **Returns** @@ -6334,10 +6750,10 @@ Obtains the keyframe time of an animation. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an **AnimatorOption** object. | -| index | Keyframe index. | +| option | Pointer to an **AnimatorOption** object. | +| index | Keyframe index. | **Returns** @@ -6357,10 +6773,10 @@ Obtains the keyframe value of an animation. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an **AnimatorOption** object. | -| index | Keyframe index. | +| option | Pointer to an **AnimatorOption** object. | +| index | Keyframe index. | **Returns** @@ -6378,11 +6794,11 @@ Sets the callback invoked when the animation playback is canceled. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an animation configuration. | -| userData | Custom parameter. | -| callback | Callback used to return the result. | +| option | Pointer to an animation configuration. | +| userData | Custom parameter. | +| callback | Callback used to return the result. | **Returns** @@ -6400,11 +6816,11 @@ Sets the callback invoked when the animation playback is complete. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an animation configuration. | -| userData | Custom parameter. | -| callback | Callback used to return the result. | +| option | Pointer to an animation configuration. | +| userData | Custom parameter. | +| callback | Callback used to return the result. | **Returns** @@ -6422,11 +6838,11 @@ Sets the callback invoked when the animator receives a frame. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an animation configuration. | -| userData | Custom parameter. | -| callback | Callback used to return the result. | +| option | Pointer to an animation configuration. | +| userData | Custom parameter. | +| callback | Callback used to return the result. | **Returns** @@ -6444,11 +6860,11 @@ Sets the callback invoked when the animation playback is repeated. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an animation configuration. | -| userData | Custom parameter. | -| callback | Callback used to return the result. | +| option | Pointer to an animation configuration. | +| userData | Custom parameter. | +| callback | Callback used to return the result. | **Returns** @@ -6466,10 +6882,10 @@ Sets the interpolation start point for the animation of an animator. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an **AnimatorOption** object. | -| value | Start point of the animation interpolation. | +| option | Pointer to an **AnimatorOption** object. | +| value | Start point of the animation interpolation. | **NOTE** @@ -6491,10 +6907,10 @@ Sets the interpolation curve for the animation of an animator. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an **AnimatorOption** object. | -| value | Interpolation curve of the animation. Default value: **ARKUI_CURVE_LINEAR**. | +| option | Pointer to an **AnimatorOption** object. | +| value | Returns the interpolation curve of the animation. Default value: **ARKUI_CURVE_LINEAR**. | **NOTE** @@ -6516,10 +6932,10 @@ Sets the delay of animation playback, in milliseconds. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an **AnimatorOption** object. | -| value | Animation delay, in milliseconds. | +| option | Pointer to an **AnimatorOption** object. | +| value | Animation delay, in milliseconds. | **Returns** @@ -6537,10 +6953,10 @@ Sets the playback direction. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an **AnimatorOption** object. | -| value | Animation playback direction. | +| option | Pointer to an **AnimatorOption** object. | +| value | Animation playback direction. | **Returns** @@ -6558,10 +6974,10 @@ Sets the duration of an animation, in milliseconds. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an **AnimatorOption** object. | -| value | Duration for playing the animation, in milliseconds. | +| option | Pointer to an **AnimatorOption** object. | +| value | Duration for playing the animation, in milliseconds. | **Returns** @@ -6579,10 +6995,10 @@ Sets the interpolation end point for the animation of an animator. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an **AnimatorOption** object. | -| value | End point of animation interpolation. | +| option | Pointer to an **AnimatorOption** object. | +| value | End point of animation interpolation. | **NOTE** @@ -6604,10 +7020,10 @@ Sets the expected frame rate range of an animation. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an **AnimatorOption** object. | -| value | Expected frame rate range. | +| option | Pointer to an **AnimatorOption** object. | +| value | Expected frame rate range. | **Returns** @@ -6625,10 +7041,10 @@ Sets whether the animator animation is restored to the initial state after being **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an **AnimatorOption** object. | -| value | Whether to restore the animation to the initial state after the animation is executed. | +| option | Pointer to an **AnimatorOption** object. | +| value | Whether to restore the animation to the initial state after the animation is executed. | **Returns** @@ -6646,10 +7062,10 @@ Sets the number of times that the frame animation is played. The value **0** mea **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an **AnimatorOption** object. | -| value | Number of times that the animation is played. | +| option | Pointer to an **AnimatorOption** object. | +| value | Number of times that the animation is played. | **NOTE** @@ -6671,12 +7087,12 @@ Sets the keyframe parameters of an animation. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an **AnimatorOption** object. | -| time | Keyframe time. Value range: [0, 1]. The value must be in ascending order. | -| value | Keyframe value. | -| index | Keyframe index. | +| option | Pointer to an **AnimatorOption** object. | +| time | Keyframe time. Value range: [0, 1]. The value must be in ascending order. | +| value | Keyframe value. | +| index | Keyframe index. | **Returns** @@ -6694,11 +7110,11 @@ Sets the keyframe curve type for the animation of an animator. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to an **AnimatorOption** object. | -| value | Animation interpolation curve. | -| index | Keyframe index. | +| option | Pointer to an **AnimatorOption** object. | +| value | Animation interpolation curve. | +| index | Keyframe index. | **NOTE** @@ -6722,9 +7138,9 @@ Creates a barrier configuration for this **RelativeContainer** component. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| size | Number of barriers. | +| size | Number of barriers. | **Returns** @@ -6744,9 +7160,9 @@ Disposes of a barrier configuration. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| barrierStyle | Pointer to a barrier configuration. | +| barrierStyle | Pointer to a barrier configuration. | ### OH_ArkUI_BarrierOption_GetDirection() @@ -6762,10 +7178,10 @@ Obtains the direction of a barrier. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| barrierStyle | Pointer to a barrier configuration. | -| index | Index of the barrier. | +| barrierStyle | Pointer to a barrier configuration. | +| index | Index of the barrier. | **Returns** @@ -6785,10 +7201,10 @@ Obtains the ID of a barrier. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| barrierStyle | Pointer to a barrier configuration. | -| index | Index of the barrier. | +| barrierStyle | Pointer to a barrier configuration. | +| index | Index of the barrier. | **Returns** @@ -6808,11 +7224,11 @@ Obtains the referenced components of a barrier. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| barrierStyle | Pointer to a barrier configuration. | -| index | Index of the barrier. | -| referencedIndex | Index of the referenced component ID. | +| barrierStyle | Pointer to a barrier configuration. | +| index | Index of the barrier. | +| referencedIndex | Index of the referenced component ID. | **Returns** @@ -6832,10 +7248,10 @@ Obtains the number of referenced components of a barrier. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| barrierStyle | Pointer to a barrier configuration. | -| index | Index of the barrier. | +| barrierStyle | Pointer to a barrier configuration. | +| index | Index of the barrier. | **Returns** @@ -6855,11 +7271,11 @@ Sets the direction of a barrier. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| barrierStyle | Pointer to a barrier configuration. | -| value | Direction. | -| index | Index of the barrier. | +| barrierStyle | Pointer to a barrier configuration. | +| value | Direction. | +| index | Index of the barrier. | ### OH_ArkUI_BarrierOption_SetId() @@ -6875,11 +7291,11 @@ Sets the ID of a barrier. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| barrierStyle | Pointer to a barrier configuration. | -| value | ID of the barrier, which must be unique and cannot be the same as the name of any component in the container. | -| index | Index of the barrier. | +| barrierStyle | Pointer to a barrier configuration. | +| value | ID of the barrier, which must be unique and cannot be the same as the name of any component in the container. | +| index | Index of the barrier. | ### OH_ArkUI_BarrierOption_SetReferencedId() @@ -6895,11 +7311,11 @@ Sets the referenced components of a barrier. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| barrierStyle | Pointer to a barrier configuration. | -| value | Referenced component IDs. | -| index | Index of the barrier. | +| barrierStyle | Pointer to a barrier configuration. | +| value | Referenced component IDs. | +| index | Index of the barrier. | ### OH_ArkUI_ConvertToHtml() @@ -6915,9 +7331,9 @@ Converts styled string information into HTML. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| descriptor | Pointer to an **ArkUI_StyledString_Descriptor** object. | +| descriptor | Pointer to an **ArkUI_StyledString_Descriptor** object. | **Returns** @@ -6937,10 +7353,10 @@ Creates an asymmetric transition effect. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| appear | Transition effect for appearance. | -| disappear | Transition effect for disappearance. | +| appear | Transition effect for appearance. | +| disappear | Transition effect for disappearance. | **NOTE** @@ -6964,9 +7380,9 @@ Creates a drag action object for the specified UI instance. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| uiContext | Pointer to the UI instance object. | +| uiContext | Pointer to the UI instance object. | **Returns** @@ -6986,9 +7402,9 @@ Creates a drag action object. The object needs to be associated with a UI instan **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | Pointer to a component node. | +| node | Pointer to a component node. | **Returns** @@ -7024,9 +7440,9 @@ Creates a movement object for component transition. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| move | Panning type. | +| move | Panning type. | **Returns** @@ -7046,9 +7462,9 @@ Creates an opacity object for component transition. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| opacity | Opacity. The value range is [0, 1]. | +| opacity | Opacity. The value range is [0, 1]. | **NOTE** @@ -7072,9 +7488,9 @@ Creates a rotation object for component transition. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| rotate | Rotation parameter object during component transition. | +| rotate | Rotation parameter object during component transition. | **Returns** @@ -7094,9 +7510,9 @@ Creates a scaling transition effect object. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| scale | Scaling settings for component transition. | +| scale | Scaling settings for component transition. | **Returns** @@ -7116,15 +7532,14 @@ Creates a translation transition effect object. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| translate | Translation settings for component transition. | +| translate | Translation settings for component transition. | **Returns** Returns the created translation transition effect object; returns **NULL** if a parameter error occurs. - ### OH_ArkUI_Curve_CreateCubicBezierCurve() ``` @@ -7136,12 +7551,12 @@ Creates a cubic Bezier curve. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| x1 | X coordinate of the first point on the Bezier curve. Value range: [0, 1]. A value less than 0 evaluates to the value **0**. A value greater than 1 evaluates to the value **1**. | -| y1 | Y coordinate of the first point on the Bezier curve. | -| x2 | X coordinate of the second point on the Bezier curve. Value range: [0, 1]. A value less than 0 evaluates to the value **0**. A value greater than 1 evaluates to the value **1**. | -| y2 | Y coordinate of the second point on the Bezier curve. | +| x1 | X coordinate of the first point on the Bezier curve. Value range: [0, 1]. A value less than 0 evaluates to the value **0**. A value greater than 1 evaluates to the value **1**. | +| y1 | Y coordinate of the first point on the Bezier curve. | +| x2 | X coordinate of the second point on the Bezier curve. Value range: [0, 1]. A value less than 0 evaluates to the value **0**. A value greater than 1 evaluates to the value **1**. | +| y2 | Y coordinate of the second point on the Bezier curve. | **Returns** @@ -7159,9 +7574,9 @@ Implements initialization for the interpolation curve, which is used to create a **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| curve | Curve type. | +| curve | Curve type. | **Returns** @@ -7179,10 +7594,10 @@ Creates a custom curve. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| userData | Custom data. | -| interpolate | Custom interpolation callback. **fraction** indicates the input x value for interpolation when the animation starts; value range: [0,1]. The return value is the **y** value of the curve; value range: [0,1]. If **fraction** is **0**, the return value **0** corresponds to the animation start point; any other return value means that the animation jumps at the start point. If **fraction** is **1**, the return value **1** corresponds to the animation end point; any other return value means that the end value of the animation is not the value of the state variable, which will result in an effect of transition from that end value to the value of the state variable. | +| userData | Custom data. | +| interpolate | Custom interpolation callback. **fraction** indicates the input x value for interpolation when the animation starts; value range: [0,1]. The return value is the **y** value of the curve; value range: [0,1]. If **fraction** is **0**, the return value **0** corresponds to the animation start point; any other return value means that the animation jumps at the start point. If **fraction** is **1**, the return value **1** corresponds to the animation end point; any other return value means that the end value of the animation is not the value of the state variable, which will result in an effect of transition from that end value to the value of the state variable. | **Returns** @@ -7200,12 +7615,12 @@ Creates an interpolating spring curve animated from 0 to 1. The actual animation **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| velocity | Initial velocity. It is applied by external factors to the spring animation, designed to help ensure the smooth transition from the previous motion state. The velocity is the normalized velocity, and its value is equal to the actual velocity at the beginning of the animation divided by the animation attribute change value. | -| mass | Mass, which influences the inertia in the spring system. The greater the mass, the greater the amplitude of the oscillation, and the slower the speed of restoring to the equilibrium position. | -| stiffness | Stiffness. It is the degree to which an object deforms by resisting the force applied. In an elastic system, the greater the stiffness, the stronger the ability to resist deformation, and the faster the speed of restoring to the equilibrium position. | -| damping | Damping. It is used to describe the oscillation and attenuation of the system after being disturbed. The larger the damping, the smaller the number of oscillations of elastic motion, and the smaller the oscillation amplitude. | +| velocity | Initial velocity. It is applied by external factors to the spring animation, designed to help ensure the smooth transition from the previous motion state. The velocity is the normalized velocity, and its value is equal to the actual velocity at the beginning of the animation divided by the animation attribute change value. | +| mass | Mass, which influences the inertia in the spring system. The greater the mass, the greater the amplitude of the oscillation, and the slower the speed of restoring to the equilibrium position. | +| stiffness | Stiffness. It is the degree to which an object deforms by resisting the force applied. In an elastic system, the greater the stiffness, the stronger the ability to resist deformation, and the faster the speed of restoring to the equilibrium position. | +| damping | Damping. It is used to describe the oscillation and attenuation of the system after being disturbed. The larger the damping, the smaller the number of oscillations of elastic motion, and the smaller the oscillation amplitude. | **NOTE** @@ -7227,11 +7642,11 @@ Creates a responsive spring animation curve. It is a special case of **springMot **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| response | Duration of one complete oscillation. | -| dampingFraction | Damping coefficient. If the value is greater than 0 and less than 1, the value is underdamped and exceeds the target value during motion. If the value is equal to 1, the value is critical damping. If the value is greater than 1, the value is overdamped and gradually approaches the target value during motion. | -| overlapDuration | Duration for animations to overlap, in seconds. When animations overlap, the **response** values of these animations will transit smoothly over this duration if they are different. | +| response | Duration of one complete oscillation. | +| dampingFraction | Damping coefficient. If the value is greater than 0 and less than 1, the value is underdamped and exceeds the target value during motion. If the value is equal to 1, the value is critical damping. If the value is greater than 1, the value is overdamped and gradually approaches the target value during motion. | +| overlapDuration | Duration for animations to overlap, in seconds. When animations overlap, the **response** values of these animations will transit smoothly over this duration if they are different. | **NOTE** @@ -7253,12 +7668,12 @@ Creates a spring curve. The curve shape is subject to the spring parameters, and **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| velocity | Initial velocity. It is applied by external factors to the spring animation, designed to help ensure the smooth transition from the previous motion state. The velocity is the normalized velocity, and its value is equal to the actual velocity at the beginning of the animation divided by the animation attribute change value. | -| mass | Mass, which influences the inertia in the spring system. The greater the mass, the greater the amplitude of the oscillation, and the slower the speed of restoring to the equilibrium position. | -| stiffness | Stiffness. It is the degree to which an object deforms by resisting the force applied. In an elastic system, the greater the stiffness, the stronger the ability to resist deformation, and the faster the speed of restoring to the equilibrium position. | -| damping | Damping. It is used to describe the oscillation and attenuation of the system after being disturbed. The larger the damping, the smaller the number of oscillations of elastic motion, and the smaller the oscillation amplitude. | +| velocity | Initial velocity. It is applied by external factors to the spring animation, designed to help ensure the smooth transition from the previous motion state. The velocity is the normalized velocity, and its value is equal to the actual velocity at the beginning of the animation divided by the animation attribute change value. | +| mass | Mass, which influences the inertia in the spring system. The greater the mass, the greater the amplitude of the oscillation, and the slower the speed of restoring to the equilibrium position. | +| stiffness | Stiffness. It is the degree to which an object deforms by resisting the force applied. In an elastic system, the greater the stiffness, the stronger the ability to resist deformation, and the faster the speed of restoring to the equilibrium position. | +| damping | Damping. It is used to describe the oscillation and attenuation of the system after being disturbed. The larger the damping, the smaller the number of oscillations of elastic motion, and the smaller the oscillation amplitude. | **Returns** @@ -7276,11 +7691,11 @@ Creates a spring animation curve. If multiple spring animations are applied to t **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| response | Duration of one complete oscillation. | -| dampingFraction | Damping coefficient. If the value is greater than 0 and less than 1, the value is underdamped and exceeds the target value during motion. If the value is equal to 1, the value is critical damping. If the value is greater than 1, the value is overdamped and gradually approaches the target value during motion. | -| overlapDuration | Duration for animations to overlap, in seconds. When animations overlap, the **response** values of these animations will transit smoothly over this duration if they are different. | +| response | Duration of one complete oscillation. | +| dampingFraction | Damping coefficient. If the value is greater than 0 and less than 1, the value is underdamped and exceeds the target value during motion. If the value is equal to 1, the value is critical damping. If the value is greater than 1, the value is overdamped and gradually approaches the target value during motion. | +| overlapDuration | Duration for animations to overlap, in seconds. When animations overlap, the **response** values of these animations will transit smoothly over this duration if they are different. | **NOTE** @@ -7302,10 +7717,10 @@ Creates a step curve. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| count | Number of tiers. The value must be a positive integer. Value range: [1, +∞). | -| end | Step change occurs at the start point or end point of each interval. true: Step change occurs at the end point. false: Step change occurs at the start point. | +| count | Number of tiers. The value must be a positive integer. Value range: [1, +∞). | +| end | Step change occurs at the start point or end point of each interval. true: Step change occurs at the end point. false: Step change occurs at the start point. | **Returns** @@ -7323,9 +7738,9 @@ Disposes of a custom curve. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| curve | Returns the pointer to the interpolation object of the curve; | +| curve | Returns the pointer to the interpolation object of the curve; | ### OH_ArkUI_CustomProperty_Destroy() @@ -7397,9 +7812,9 @@ Disposes of drawing information for this custom span. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| info | Pointer to the drawing information of a custom span. | +| info | Pointer to the drawing information of a custom span. | ### OH_ArkUI_CustomSpanDrawInfo_GetBaseline() @@ -7415,7553 +7830,10319 @@ Obtains the baseline offset of the custom span relative to the mounted component **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| info | Pointer to the drawing information of a custom span. | +| info | Pointer to the drawing information of a custom span. | **Returns** Returns the baseline offset. If a parameter error occurs, **0.0f** is returned. A possible cause is that mandatory parameters are left unspecified. - -### OH_ArkUI_CustomSpanDrawInfo_GetLineBottom() +### OH_ArkUI_NodeUtils_GetWindowInfo() ``` -float OH_ArkUI_CustomSpanDrawInfo_GetLineBottom (ArkUI_CustomSpanDrawInfo * info) +int32_t OH_ArkUI_NodeUtils_GetWindowInfo(ArkUI_NodeHandle node, ArkUI_HostWindowInfo** info) ``` **Description** -Obtains the bottom margin of the custom span relative to the mounted component. +Obtains the information about the window to which a node belongs. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| info | Pointer to the drawing information of a custom span. | +| node | Pointer to the target node.| +| info | Pointer to the window information object.| **Returns** -Returns the bottom margin. If a parameter error occurs, **0.0f** is returned. A possible cause is that mandatory parameters are left unspecified. - +Returns the result code. Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful; returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs; returns **ARKUI_ERROR_CODE_NODE_NOT_ON_MAIN_TREE** if the node is not mounted on the main component tree. -### OH_ArkUI_CustomSpanDrawInfo_GetLineTop() +### OH_ArkUI_HostWindowInfo_GetName() ``` -float OH_ArkUI_CustomSpanDrawInfo_GetLineTop (ArkUI_CustomSpanDrawInfo * info) +const char* OH_ArkUI_HostWindowInfo_GetName(ArkUI_HostWindowInfo* info) ``` **Description** -Obtains the top margin of the custom span relative to the mounted component. +Obtains the window name from a **HostWindowInfo** object. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| info | Pointer to the drawing information of a custom span. | +| info | **HostWindowInfo** object.| **Returns** -Returns the top margin. If a parameter error occurs, **0.0f** is returned. A possible cause is that mandatory parameters are left unspecified. - +Returns the window name obtained from the **HostWindowInfo** object. -### OH_ArkUI_CustomSpanDrawInfo_GetXOffset() +### OH_ArkUI_HostWindowInfo_Destroy() ``` -float OH_ArkUI_CustomSpanDrawInfo_GetXOffset (ArkUI_CustomSpanDrawInfo * info) +void OH_ArkUI_HostWindowInfo_Destroy(ArkUI_HostWindowInfo* info) ``` **Description** -Obtains the x-axis offset of the custom span relative to the mounted component. +Destroys n **HostWindowInfo** object. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| info | Pointer to the drawing information of a custom span. | - -**Returns** - -Returns the x-axis offset. If a parameter error occurs, **0.0f** is returned. A possible cause is that mandatory parameters are left unspecified. - +| info | **HostWindowInfo** object to be destroyed.| -### OH_ArkUI_CustomSpanMeasureInfo_Create() +### OH_ArkUI_NodeUtils_MoveTo() ``` -ArkUI_CustomSpanMeasureInfo* OH_ArkUI_CustomSpanMeasureInfo_Create (void ) +int32_t OH_ArkUI_NodeUtils_MoveTo(ArkUI_NodeHandle node, ArkUI_NodeHandle target_parent, int32_t index) ``` **Description** -Creates measurement information for this custom span. +Moves a node to a target parent node as a child. -**Since**: 12 +**Since**: 16 -**Returns** +**Parameters** -Returns a **CustomSpanMeasureInfo** instance. If a null pointer is returned, the memory may be insufficient. +| Name| Description| +| -------- | -------- | +| node | Node to be moved.| +| target_parent | Pointer to the target parent node.| +| index | Index of the node after the movement. If the index is invalid, the node will be added to the end of the target parent node.| +**Returns** -### OH_ArkUI_CustomSpanMeasureInfo_Dispose() +Returns the result code. Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful; returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + +### OH_ArkUI_NodeUtils_GetAttachedNodeHandleById() ``` -void OH_ArkUI_CustomSpanMeasureInfo_Dispose (ArkUI_CustomSpanMeasureInfo * info) +int32_t OH_ArkUI_NodeUtils_GetAttachedNodeHandleById(const char* id, ArkUI_NodeHandle* node) ``` **Description** -Disposes of measurement information of a custom span. +Obtains the target node based on the provided user ID. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| info | Pointer to the measurement information of a custom span. | +| id | ID of the target node.| +| node | Pointer to the target parent node.| +**Returns** -### OH_ArkUI_CustomSpanMeasureInfo_GetFontSize() +Returns the result code. Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful; returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + +### OH_ArkUI_NodeUtils_SetCrossLanguageOption() ``` -float OH_ArkUI_CustomSpanMeasureInfo_GetFontSize (ArkUI_CustomSpanMeasureInfo * info) +int32_t OH_ArkUI_NodeUtils_SetCrossLanguageOption(ArkUI_NodeHandle node, ArkUI_CrossLanguageOption* option) ``` **Description** -Obtains the font size of the parent text node of a custom span. +Sets the cross-language options for the target node. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| info | Pointer to the measurement information of a custom span. | +| node | Pointer to the target node.| +| option | Cross-language configuration class. For details, see **ArkUI_CrossLanguageOption**.| **Returns** -Returns the font size of the parent text node. If a parameter error occurs, **0.0f** is returned. A possible cause is that mandatory parameters are left unspecified. - +Returns the result code. Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful; returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_CustomSpanMetrics_Create() +### OH_ArkUI_NodeUtils_GetCrossLanguageOption() ``` -ArkUI_CustomSpanMetrics* OH_ArkUI_CustomSpanMetrics_Create (void ) +int32_t OH_ArkUI_NodeUtils_GetCrossLanguageOption(ArkUI_NodeHandle node, ArkUI_CrossLanguageOption* option) ``` **Description** -Creates measurement metrics for this custom span. +Obtains the cross-language options for the target node. -**Since**: 12 +**Since**: 15 -**Returns** +**Parameters** -Returns a **CustomSpanMetrics** instance. If a null pointer is returned, the memory may be insufficient. +| Name| Description| +| -------- | -------- | +| node | Pointer to the target node.| +| option | Cross-language configuration class. For details, see **ArkUI_CrossLanguageOption**.| + +**Returns** +Returns the result code. Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful; returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_CustomSpanMetrics_Dispose() +### OH_ArkUI_NodeUtils_GetFirstChildIndexWithoutExpand() ``` -void OH_ArkUI_CustomSpanMetrics_Dispose (ArkUI_CustomSpanMetrics * metrics) +int32_t OH_ArkUI_NodeUtils_GetFirstChildIndexWithoutExpand(ArkUI_NodeHandle node, uint32_t* index) ``` **Description** -Disposes of measurement metrics of this custom span. +Obtains the index of the first child node of the target node in the tree without expanding any nodes. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| metrics | Returns a **CustomSpanMetrics** instance. | +| node | Pointer to the target node.| +| index | Pointer to a variable where the index of the first child node is stored.| + +**Returns** +Returns the result code. Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful; returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_CustomSpanMetrics_SetHeight() +### OH_ArkUI_NodeUtils_GetLastChildIndexWithoutExpand() ``` -int32_t OH_ArkUI_CustomSpanMetrics_SetHeight (ArkUI_CustomSpanMetrics * metrics, float height ) +int32_t OH_ArkUI_NodeUtils_GetLastChildIndexWithoutExpand(ArkUI_NodeHandle node, uint32_t* index) ``` **Description** -Sets the height for a custom span. +Obtains the index of the last child node of the target node in the tree without expanding any nodes. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| metrics | Returns a **CustomSpanMetrics** instance. | -| height | Height, in vp. | +| node | Pointer to the target node.| +| index | Pointer to a variable where the index of the last child node is stored.| **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. A possible cause is that mandatory parameters are left unspecified. - +Returns the result code. Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful; returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_CustomSpanMetrics_SetWidth() +### OH_ArkUI_NodeUtils_GetChildWithExpandMode() ``` -int32_t OH_ArkUI_CustomSpanMetrics_SetWidth (ArkUI_CustomSpanMetrics * metrics, float width ) +int32_t OH_ArkUI_NodeUtils_GetChildWithExpandMode(ArkUI_NodeHandle node, int32_t position, + ArkUI_NodeHandle* subnode, uint32_t expandMode) ``` **Description** -Sets the width for a custom span. +Obtains a child node at the specified index using different expansion modes. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| metrics | Returns a **CustomSpanMetrics** instance. | -| width | Width, in vp. | +| node | Pointer to the target node.| +| position | Index of the child node to obtain.| +| subnode | Pointer to the obtained child node.| +| expandMode | Expansion mode for node traversal. For details, see **ArkUI_ExpandMode**.| **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. A possible cause is that mandatory parameters are left unspecified. - +Returns the result code. Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful; returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_DialogDismissEvent_GetDismissReason() +### OH_ArkUI_CustomSpanDrawInfo_GetLineBottom() ``` -int32_t OH_ArkUI_DialogDismissEvent_GetDismissReason (ArkUI_DialogDismissEvent * event) +float OH_ArkUI_CustomSpanDrawInfo_GetLineBottom (ArkUI_CustomSpanDrawInfo * info) ``` **Description** -Obtains the dismissal reason from a dialog box dismiss event object. +Obtains the bottom margin of the custom span relative to the mounted component. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to a dialog box dismiss event object.| +| info | Pointer to the drawing information of a custom span. | **Returns** -Returns the dismissal reason. Returns **-1** if an exception occurs.
**DIALOG_DISMISS_BACK_PRESS**: touching the Back button, swiping left or right on the screen, or pressing the Esc key.
**DIALOG_DISMISS_TOUCH_OUTSIDE**: touching the mask.
**DIALOG_DISMISS_CLOSE_BUTTON**: touching the Close button.
**DIALOG_DISMISS_SLIDE_DOWN**: sliding down. +Returns the bottom margin. If a parameter error occurs, **0.0f** is returned. A possible cause is that mandatory parameters are left unspecified. -### OH_ArkUI_DialogDismissEvent_GetUserData() + +### OH_ArkUI_CustomSpanDrawInfo_GetLineTop() ``` -void* OH_ArkUI_DialogDismissEvent_GetUserData (ArkUI_DialogDismissEvent * event) +float OH_ArkUI_CustomSpanDrawInfo_GetLineTop (ArkUI_CustomSpanDrawInfo * info) ``` **Description** -Obtains the pointer to user data in a dialog box dismiss event object. +Obtains the top margin of the custom span relative to the mounted component. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to a dialog box dismiss event object.| +| info | Pointer to the drawing information of a custom span. | **Returns** -Returns the pointer to user data. +Returns the top margin. If a parameter error occurs, **0.0f** is returned. A possible cause is that mandatory parameters are left unspecified. -### OH_ArkUI_DialogDismissEvent_SetShouldBlockDismiss() +### OH_ArkUI_CustomSpanDrawInfo_GetXOffset() ``` -void OH_ArkUI_DialogDismissEvent_SetShouldBlockDismiss (ArkUI_DialogDismissEvent * event, bool shouldBlockDismiss ) +float OH_ArkUI_CustomSpanDrawInfo_GetXOffset (ArkUI_CustomSpanDrawInfo * info) ``` **Description** -Sets whether to block the system behavior of dismissing a dialog box. +Obtains the x-axis offset of the custom span relative to the mounted component. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to a dialog box dismiss event object. | -| shouldBlockDismiss | Whether to block the system behavior of dismissing the dialog box. The value **true** means to block the system behavior, and **false** means the opposite. | +| info | Pointer to the drawing information of a custom span. | +**Returns** -### OH_ArkUI_DisallowNodeAnyDropDataTypes() +Returns the x-axis offset. If a parameter error occurs, **0.0f** is returned. A possible cause is that mandatory parameters are left unspecified. + + +### OH_ArkUI_CustomSpanMeasureInfo_Create() ``` -int32_t OH_ArkUI_DisallowNodeAnyDropDataTypes (ArkUI_NodeHandle node) +ArkUI_CustomSpanMeasureInfo* OH_ArkUI_CustomSpanMeasureInfo_Create (void ) ``` **Description** -The configuration component is not allowed to accept any data type. This interface resets the data type configured through [OH_ArkUI_SetNodeAllowedDropDataTypes](#oh_arkui_setnodealloweddropdatatypes). +Creates measurement information for this custom span. **Since**: 12 -**Parameters** - -| Name| Description| -| -------- | -------- | -| node | Pointer to a component node. | - **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +Returns a **CustomSpanMeasureInfo** instance. If a null pointer is returned, the memory may be insufficient. -### OH_ArkUI_DragAction_Dispose() +### OH_ArkUI_CustomSpanMeasureInfo_Dispose() ``` -void OH_ArkUI_DragAction_Dispose (ArkUI_DragAction * dragAction) +void OH_ArkUI_CustomSpanMeasureInfo_Dispose (ArkUI_CustomSpanMeasureInfo * info) ``` **Description** -Disposes of an **ArkUI_DragAction** object. +Disposes of measurement information of a custom span. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| dragAction | Pointer to the target drag action object. | +| info | Pointer to the measurement information of a custom span. | -### OH_ArkUI_DragAction_RegisterStatusListener() +### OH_ArkUI_CustomSpanMeasureInfo_GetFontSize() ``` -int32_t OH_ArkUI_DragAction_RegisterStatusListener (ArkUI_DragAction * dragAction, void * userData, void(*)(ArkUI_DragAndDropInfo *dragAndDropInfo, void *userData) listener ) +float OH_ArkUI_CustomSpanMeasureInfo_GetFontSize (ArkUI_CustomSpanMeasureInfo * info) ``` **Description** -Registers a drag status listener. This listener can be used to check whether the data is successfully received and processed. +Obtains the font size of the parent text node of a custom span. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| dragAction | Pointer to the target drag action object. | -| userData | Custom user data. | -| listener | Listener to register. When the callback is invoked, the system returns a pointer to the drag status object. The pointer is destroyed after the callback is complete and the application should not hold it anymore. | +| info | Pointer to the measurement information of a custom span. | **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +Returns the font size of the parent text node. If a parameter error occurs, **0.0f** is returned. A possible cause is that mandatory parameters are left unspecified. -### OH_ArkUI_DragAction_SetData() +### OH_ArkUI_CustomSpanMetrics_Create() ``` -int32_t OH_ArkUI_DragAction_SetData (ArkUI_DragAction * dragAction, OH_UdmfData * data ) +ArkUI_CustomSpanMetrics* OH_ArkUI_CustomSpanMetrics_Create (void ) ``` **Description** -Sets the drag data. +Creates measurement metrics for this custom span. **Since**: 12 -**Parameters** - -| Name| Description| -| -------- | -------- | -| dragAction | Pointer to the target drag action object. | -| data | Drag data. | - **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +Returns a **CustomSpanMetrics** instance. If a null pointer is returned, the memory may be insufficient. -### OH_ArkUI_DragAction_SetDragPreviewOption() +### OH_ArkUI_CustomSpanMetrics_Dispose() ``` -int32_t OH_ArkUI_DragAction_SetDragPreviewOption (ArkUI_DragAction * dragAction, ArkUI_DragPreviewOption * option ) +void OH_ArkUI_CustomSpanMetrics_Dispose (ArkUI_CustomSpanMetrics * metrics) ``` **Description** -Sets an **ArkUI_DragPreviewOption** object for the specified drag action object. +Disposes of measurement metrics of this custom span. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| dragAction | Pointer to the target drag action object. | -| option | Custom parameters. | - -**Returns** - -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +| metrics | Returns a **CustomSpanMetrics** instance. | -### OH_ArkUI_DragAction_SetPixelMaps() +### OH_ArkUI_CustomSpanMetrics_SetHeight() ``` -int32_t OH_ArkUI_DragAction_SetPixelMaps (ArkUI_DragAction * dragAction, OH_PixelmapNative * pixelmapArray[], int32_t size ) +int32_t OH_ArkUI_CustomSpanMetrics_SetHeight (ArkUI_CustomSpanMetrics * metrics, float height ) ``` **Description** -Sets the drag previews for a drag action. +Sets the height for a custom span. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| dragAction | Pointer to the target drag action object. | -| pixelmapArray | Drag the bitmap array of the follower map. | -| size | Number of drag-and-drop images. | +| metrics | Returns a **CustomSpanMetrics** instance. | +| height | Height, in vp. | **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. A possible cause is that mandatory parameters are left unspecified. -### OH_ArkUI_DragAction_SetPointerId() +### OH_ArkUI_CustomSpanMetrics_SetWidth() ``` -int32_t OH_ArkUI_DragAction_SetPointerId (ArkUI_DragAction * dragAction, int32_t pointer ) +int32_t OH_ArkUI_CustomSpanMetrics_SetWidth (ArkUI_CustomSpanMetrics * metrics, float width ) ``` **Description** -Sets the pointer ID. If only one finger is operating on the screen, the pointer ID is 0. In general cases, you can set the pointer ID to 0. +Sets the width for a custom span. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| dragAction | Pointer to the target drag action object. | -| pointer | Pointer ID. The value ranges from 0 to 9. | +| metrics | Returns a **CustomSpanMetrics** instance. | +| width | Width, in vp. | **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. A possible cause is that mandatory parameters are left unspecified. -### OH_ArkUI_DragAction_SetTouchPointX() +### OH_ArkUI_DialogDismissEvent_GetDismissReason() ``` -int32_t OH_ArkUI_DragAction_SetTouchPointX (ArkUI_DragAction * dragAction, float x ) +int32_t OH_ArkUI_DialogDismissEvent_GetDismissReason (ArkUI_DialogDismissEvent * event) ``` **Description** -Sets the touch point relative to the upper left corner of the first drag preview (pixel map). +Obtains the dismissal reason from a dialog box dismiss event object. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| dragAction | Pointer to the target drag action object. | -| x | X value of the hand point coordinate. | +| event | Pointer to a dialog box dismiss event object.| **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. - +Returns the dismissal reason. Returns **-1** if an exception occurs.
**DIALOG_DISMISS_BACK_PRESS**: touching the Back button, swiping left or right on the screen, or pressing the Esc key.
**DIALOG_DISMISS_TOUCH_OUTSIDE**: touching the mask.
**DIALOG_DISMISS_CLOSE_BUTTON**: touching the Close button.
**DIALOG_DISMISS_SLIDE_DOWN**: sliding down. -### OH_ArkUI_DragAction_SetTouchPointY() +### OH_ArkUI_CustomDialog_OpenDialog() ``` -int32_t OH_ArkUI_DragAction_SetTouchPointY (ArkUI_DragAction * dragAction, float y ) +int32_t OH_ArkUI_CustomDialog_OpenDialog(ArkUI_CustomDialogOptions* options, void (*callback)(int32_t dialogId)) ``` **Description** -Sets the touch point relative to the upper left corner of the first drag preview (pixel map). +Displays a custom dialog box. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| dragAction | Pointer to the target drag action object. | -| y | Y value of the hand point coordinate. | +| options | Dialog box parameters.| +| callback | Callback invoked when the dialog box is displayed. The parameter is the dialog box ID.| **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. - +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. -### OH_ArkUI_DragAction_UnregisterStatusListener() +### OH_ArkUI_CustomDialog_UpdateDialog() ``` -void OH_ArkUI_DragAction_UnregisterStatusListener (ArkUI_DragAction * dragAction) +int32_t OH_ArkUI_CustomDialog_UpdateDialog(ArkUI_CustomDialogOptions* options, void (*callback)(int32_t dialogId)) ``` **Description** -Unregisters a drag status listener. +Updates a custom dialog box. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| dragAction | Pointer to the target drag action object. | +| options | Dialog box parameters.| +| callback | Callback invoked when the dialog box is updated. The parameter is the dialog box ID.| + +**Returns** +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. -### OH_ArkUI_DragAndDropInfo_GetDragEvent() +### OH_ArkUI_CustomDialog_CloseDialog() ``` -ArkUI_DragEvent* OH_ArkUI_DragAndDropInfo_GetDragEvent (ArkUI_DragAndDropInfo * dragAndDropInfo) +int32_t OH_ArkUI_CustomDialog_CloseDialog(int32_t dialogId) ``` **Description** -Obtains a drag event based on the specified drag and drop information. The drag event can then be used to obtain the drag result. +Closes a custom dialog box. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| dragAndDropInfo | Drag-related information returned by the drag status listener. | +| dialogId | ID of the dialog box to close.| **Returns** -Returns an **ArkUI_DragEvent** object; returns null if an error occurs. - +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. -### OH_ArkUI_DragAndDropInfo_GetDragStatus() +### OH_ArkUI_CustomDialog_CreateOptions() ``` -ArkUI_DragStatus OH_ArkUI_DragAndDropInfo_GetDragStatus (ArkUI_DragAndDropInfo * dragAndDropInfo) +ArkUI_CustomDialogOptions* OH_ArkUI_CustomDialog_CreateOptions(ArkUI_NodeHandle content) ``` **Description** -Obtains the drag status of a drag action. +Creates options for a custom dialog. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| dragAndDropInfo | Drag-related information returned by the drag status listener. | +| content | Content of the custom dialog box.| **Returns** -Returns an **ArkUI_DragStatus** object; returns **ArkUI_DRAG_STATUS_UNKNOWN** if an error occurs. - +Returns the pointer to the custom dialog box options. -### OH_ArkUI_DragEvent_DisableDefaultDropAnimation() +### OH_ArkUI_CustomDialog_DisposeOptions() ``` -int32_t OH_ArkUI_DragEvent_DisableDefaultDropAnimation (ArkUI_DragEvent * event, bool disable ) +void OH_ArkUI_CustomDialog_DisposeOptions(ArkUI_CustomDialogOptions* options) ``` **Description** -Sets whether to disable the default drop animation, which is enabled by default. Use this API to apply a custom drop animation. +Destroys custom dialog box options. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to an **ArkUI_DragEvent** object. | -| disable | Whether to disable the default drop animation. The value **true** means to disable the default drop animation, and **false** means the opposite. | - -**Returns** - -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +| options | Pointer to the custom dialog box options.| -### OH_ArkUI_DragEvent_GetDataTypes() +### OH_ArkUI_CustomDialog_SetLevelMode() ``` -int32_t OH_ArkUI_DragEvent_GetDataTypes (ArkUI_DragEvent * event, char ** result[], int32_t length ) +int32_t OH_ArkUI_CustomDialog_SetLevelMode(ArkUI_CustomDialogOptions* options, ArkUI_LevelMode levelMode) ``` **Description** -Obtains the type list of drag data types from a drag event. +Sets the display level of a dialog box. -**Since**: 12 +**Since**: 16 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to an **ArkUI_DragEvent** object. | -| char | \*\*result[] Returns the type list of the dragged data. You need to create a string array first. | -| length | The total length of the array must be greater than or equal to the number obtained by using [OH_ArkUI_DragEvent_GetDataTypesCount](#oh_arkui_dragevent_getdatatypescount). | +| options | Pointer to the custom dialog box options.| +| levelMode | Display level to set, specified by an enumeration value of **ArkUI_LevelMode**.| -**Returns** +**NOTE** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +This method must be called before the **OH_ArkUI_CustomDialog_OpenDialog** method. +**Returns** + +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. -### OH_ArkUI_DragEvent_GetDataTypesCount() +### OH_ArkUI_CustomDialog_SetLevelUniqueId() ``` -int32_t OH_ArkUI_DragEvent_GetDataTypesCount (ArkUI_DragEvent * event, int32_t * count ) +int32_t OH_ArkUI_CustomDialog_SetLevelUniqueId(ArkUI_CustomDialogOptions* options, int32_t uniqueId) ``` **Description** -Obtains the number of drag data types from a drag event. +Sets the ID of the node under the dialog box's display level. -**Since**: 12 +**Since**: 16 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to an **ArkUI_DragEvent** object. | -| count | Output parameter, which returns the number of types of dragged data. | +| options | Pointer to the custom dialog box options.| +| uniqueId | ID of the node under the dialog box's display level. The dialog box will be displayed on the same page as this node.| -**Returns** +**NOTE** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +This method must be called before the **OH_ArkUI_CustomDialog_OpenDialog** method. +**Returns** -### OH_ArkUI_DragEvent_GetDragResult() +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. + +### OH_ArkUI_CustomDialog_SetImmersiveMode() ``` -int32_t OH_ArkUI_DragEvent_GetDragResult (ArkUI_DragEvent * event, ArkUI_DragResult * result ) +int32_t OH_ArkUI_CustomDialog_SetImmersiveMode(ArkUI_CustomDialogOptions* options, ArkUI_ImmersiveMode immersiveMode) ``` **Description** -Obtains the drag and drop result from the drag event. +Sets the display area of the embedded pop-up window mask. -**Since**: 12 +**Since**: 16 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to an **ArkUI_DragEvent** object. | -| result | Output parameter, which returns the drag result corresponding to the drag event. | +| options | Pointer to the custom dialog box options.| +| immersiveMode | Display area, specified by an enumeration value of **ArkUI_ImmersiveMode**.| -**Returns** +**NOTE** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +This method must be called before the **OH_ArkUI_CustomDialog_OpenDialog** method. +**Returns** -### OH_ArkUI_DragEvent_GetModifierKeyStates() +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. + +### OH_ArkUI_CustomDialog_SetBackgroundColor() ``` -int32_t OH_ArkUI_DragEvent_GetModifierKeyStates (ArkUI_DragEvent * event, int64_t * keys ) +int32_t OH_ArkUI_CustomDialog_SetBackgroundColor(ArkUI_CustomDialogOptions* options, uint32_t backgroundColor) ``` **Description** -Obtains the pressed status of modifier keys from a drag event. +Sets the background color of a dialog box. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to an **ArkUI_DragEvent** object. | -| keys | Returns the modifier key combination that is currently pressed. The application can determine the modifier key combination through bitwise operations. | +| options | Dialog box parameters.| +| backgroundColor | Background color of the dialog box.| **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. - +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. -### OH_ArkUI_DragEvent_GetPreviewRectHeight() +### OH_ArkUI_CustomDialog_SetCornerRadius() ``` -float OH_ArkUI_DragEvent_GetPreviewRectHeight (ArkUI_DragEvent * event) +int32_t OH_ArkUI_CustomDialog_SetCornerRadius( + ArkUI_CustomDialogOptions* options, float topLeft, float topRight, float bottomLeft, float bottomRight) ``` **Description** -Obtains the height of a drag preview from a drag event. +Sets the corner radius for a dialog box. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to an **ArkUI_DragEvent** object. | +| options | Dialog box parameters.| +| topLeft | Radius of the upper left corner of the dialog box.| +| topRight | Radius of the upper right corner of the dialog box.| +| bottomLeft |Radius of the lower left corner of the dialog box.| +| bottomRight | Radius of the lower right corner of the dialog box.| **Returns** -Returns the height of the drag preview, in px; returns the default value **0** if the input parameter is invalid. - +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. -### OH_ArkUI_DragEvent_GetPreviewRectWidth() +### OH_ArkUI_CustomDialog_SetBorderWidth() ``` -float OH_ArkUI_DragEvent_GetPreviewRectWidth (ArkUI_DragEvent * event) +int32_t OH_ArkUI_CustomDialog_SetBorderWidth( + ArkUI_CustomDialogOptions* options, float top, float right, float bottom, float left, ArkUI_LengthMetricUnit unit) ``` **Description** -Obtains the width of a drag preview from a drag event. +Sets the border width of a dialog box. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to an **ArkUI_DragEvent** object. | +| options | Dialog box parameters.| +| top | Width of the top border of the dialog box.| +| right | Width of the right border of the dialog box.| +| bottom |Width of the bottom border of the dialog box.| +| left | Width of the left border of the dialog box.| +| unit | Unit of the width. The default value is vp.| **Returns** -Returns the width of the drag preview, in px; returns the default value **0** if the input parameter is invalid. - +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. -### OH_ArkUI_DragEvent_GetPreviewTouchPointX() +### OH_ArkUI_CustomDialog_SetBorderColor() ``` -float OH_ArkUI_DragEvent_GetPreviewTouchPointX (ArkUI_DragEvent * event) +int32_t OH_ArkUI_CustomDialog_SetBorderColor( + ArkUI_CustomDialogOptions* options, uint32_t top, uint32_t right, uint32_t bottom, uint32_t left) ``` **Description** -Obtains the X coordinate of the touch point for a drag preview from a drag event. +Sets the border color of the dialog box. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to an **ArkUI_DragEvent** object. | +| options | Dialog box parameters.| +| top | Color of the top border of the dialog box.| +| right | Color of the right border of the dialog box.| +| bottom |Color of the bottom border of the dialog box.| +| left | Color of the left border of the dialog box.| **Returns** -Returns the X coordinate of the touch point, in px; returns the default value **0** if the input parameter is invalid. - +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. -### OH_ArkUI_DragEvent_GetPreviewTouchPointY() +### OH_ArkUI_CustomDialog_SetBorderStyle() ``` -float OH_ArkUI_DragEvent_GetPreviewTouchPointY (ArkUI_DragEvent * event) +int32_t OH_ArkUI_CustomDialog_SetBorderStyle( + ArkUI_CustomDialogOptions* options, int32_t top, int32_t right, int32_t bottom, int32_t left) ``` **Description** -Obtains the Y coordinate of the touch point for a drag preview from a drag event. +Sets the border style of a dialog box. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | ArkUI_DragEvent event pointer. The unit is PX. If the input parameter is invalid, the default value 0 is returned. | +| options | Dialog box parameters.| +| top | Style of the top border of the dialog box.| +| right | Style of the right border of the dialog box.| +| bottom | Style of the bottom border of the dialog box.| +| left | Style of the left border of the dialog box.| **Returns** -float returns the y-axis coordinate of the drag and hand point. - +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. -### OH_ArkUI_DragEvent_GetTouchPointXToDisplay() +### OH_ArkUI_CustomDialog_SetWidth() ``` -float OH_ArkUI_DragEvent_GetTouchPointXToDisplay (ArkUI_DragEvent * event) +int32_t OH_ArkUI_CustomDialog_SetWidth(ArkUI_CustomDialogOptions* options, float width, ArkUI_LengthMetricUnit unit) ``` **Description** -Obtains the X coordinate of the touch point relative to the display from a drag event. +Sets the width of the dialog box background. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to an **ArkUI_DragEvent** object. | +| options | Dialog box parameters.| +| width | Width of the dialog box background.| +| unit | Unit of the width. The default value is vp.| **Returns** -Returns the X coordinate of the touch point relative to the display, in px; returns the default value **0** if the input parameter is invalid. - +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. -### OH_ArkUI_DragEvent_GetTouchPointXToWindow() +### OH_ArkUI_CustomDialog_SetHeight() ``` -float OH_ArkUI_DragEvent_GetTouchPointXToWindow (ArkUI_DragEvent * event) +int32_t OH_ArkUI_CustomDialog_SetHeight(ArkUI_CustomDialogOptions* options, float height, ArkUI_LengthMetricUnit unit) ``` **Description** -Obtains the X coordinate of the touch point relative to the window from a drag event. +Sets the height of the dialog box background. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to an **ArkUI_DragEvent** object. | +| options | Dialog box parameters.| +| height | Height of the dialog box background.| +| unit | Unit of the height. The default value is vp.| **Returns** -Returns the X coordinate of the touch point relative to the window, in px; returns the default value **0** if the input parameter is invalid. - +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. -### OH_ArkUI_DragEvent_GetTouchPointYToDisplay() +### OH_ArkUI_CustomDialog_SetShadow() ``` -float OH_ArkUI_DragEvent_GetTouchPointYToDisplay (ArkUI_DragEvent * event) +int32_t OH_ArkUI_CustomDialog_SetShadow(ArkUI_CustomDialogOptions* options, ArkUI_ShadowStyle shadow) ``` **Description** -Obtains the Y coordinate of the touch point relative to the display from a drag event. +Sets the shadow of the dialog box background. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to an **ArkUI_DragEvent** object. | +| options | Dialog box parameters.| +| shadow | Shadow style of the background, specified by an enumerated value.| **Returns** -Returns the Y coordinate of the touch point relative to the display, in px; returns the default value **0** if the input parameter is invalid. - +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. -### OH_ArkUI_DragEvent_GetTouchPointYToWindow() +### OH_ArkUI_CustomDialog_SetCustomShadow() ``` -float OH_ArkUI_DragEvent_GetTouchPointYToWindow (ArkUI_DragEvent * event) +int32_t OH_ArkUI_CustomDialog_SetCustomShadow( + ArkUI_CustomDialogOptions* options, const ArkUI_AttributeItem* customShadow) ``` **Description** -Obtains the Y coordinate of the touch point relative to the window from a drag event. +Sets the custom shadow of the dialog box background. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to an **ArkUI_DragEvent** object. | +| options | Dialog box parameters.| +| customShadow | Custom shadow parameter. The format is the same as that of the **NODE_SHADOW** property.| **Returns** -Returns the Y coordinate of the touch point relative to the window, in px; returns the default value **0** if the input parameter is invalid. - +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. -### OH_ArkUI_DragEvent_GetUdmfData() +### OH_ArkUI_CustomDialog_SetBackgroundBlurStyle() ``` -int32_t OH_ArkUI_DragEvent_GetUdmfData (ArkUI_DragEvent * event, OH_UdmfData * data ) +int32_t OH_ArkUI_CustomDialog_SetBackgroundBlurStyle(ArkUI_CustomDialogOptions* options, ArkUI_BlurStyle blurStyle) ``` **Description** -Obtain the default drag-and-drop data from ArkUI_DragEvent. +Sets the background blur style of the dialog box. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to an **ArkUI_DragEvent** object. | -| data | Pointer to the dragged data of OH_UdmfData. When receiving data, the application needs to create a pointer for receiving data by using the OH_UdmfData_Create method. | +| options | Dialog box parameters.| +| blurStyle | Background blur style, specified by an enumerated value.| **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. - +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. -### OH_ArkUI_DragEvent_GetVelocity() +### OH_ArkUI_CustomDialog_SetAlignment() ``` -float OH_ArkUI_DragEvent_GetVelocity (ArkUI_DragEvent * event) +int32_t OH_ArkUI_CustomDialog_SetAlignment( + ArkUI_CustomDialogOptions* options, int32_t alignment, float offsetX, float offsetY) ``` **Description** -Obtains the dragging velocity along the main axis. +Sets the alignment mode of a dialog box. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to an **ArkUI_DragEvent** object. | +| options | Dialog box parameters.| +| alignment | Alignment mode of the dialog box. The parameter type is **ArkUI_Alignment**.| +| offsetX | Horizontal offset of the dialog box. The value is a floating point number.| +| offsetY | Vertical offset of the dialog box. The value is a floating point number.| **Returns** -Returns the dragging velocity along the main axis, in px; returns the default value **0** if the input parameter is invalid. - +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. -### OH_ArkUI_DragEvent_GetVelocityX() +### OH_ArkUI_CustomDialog_SetModalMode() ``` -float OH_ArkUI_DragEvent_GetVelocityX (ArkUI_DragEvent * event) +int32_t OH_ArkUI_CustomDialog_SetModalMode(ArkUI_CustomDialogOptions* options, bool isModal) ``` **Description** -Obtains the dragging velocity along the x-axis. +Sets the modal mode for a custom dialog box. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to an **ArkUI_DragEvent** object. | +| options | Dialog box parameters.| +| isModal | Whether the dialog box is a modal. A modal dialog box has a mask applied, while a non-modal dialog box does not. The value **true** means that the dialog box is a modal.| **Returns** -Returns the dragging velocity along the x-axis, in px; returns the default value **0** if the input parameter is invalid. - +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. -### OH_ArkUI_DragEvent_GetVelocityY() +### OH_ArkUI_CustomDialog_SetAutoCancel() ``` -float OH_ArkUI_DragEvent_GetVelocityY (ArkUI_DragEvent * event) +int32_t OH_ArkUI_CustomDialog_SetAutoCancel(ArkUI_CustomDialogOptions* options, bool autoCancel) ``` **Description** -Obtains the dragging velocity along the y-axis. +Specifies whether to allow users to touch the mask to dismiss the custom dialog box. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to an **ArkUI_DragEvent** object. | +| options | Dialog box parameters.| +| autoCancel | Whether to allow users to touch the mask to dismiss the dialog box. The value **true** means to allow users to do so, and **false** means the opposite.| **Returns** -Returns the dragging velocity along the y-axis, in px; returns the default value **0** if the input parameter is invalid. - +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. -### OH_ArkUI_DragEvent_SetData() +### OH_ArkUI_CustomDialog_SetSubwindowMode() ``` -int32_t OH_ArkUI_DragEvent_SetData (ArkUI_DragEvent * event, OH_UdmfData * data ) +int32_t OH_ArkUI_CustomDialog_SetSubwindowMode(ArkUI_CustomDialogOptions* options, bool isShowInSubwindow) ``` **Description** -Sets drag data for a drag event. +Sets whether to display the dialog box in a subwindow. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to an **ArkUI_DragEvent** object. | -| data | Drag data. | +| options | Dialog box parameters.| +| isShowInSubwindow | Whether to show the dialog box in a subwindow when the dialog box needs to be displayed outside the main window. The default value is **false**, meaning the dialog box is displayed within the application, not in a separate subwindow.| **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. - +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. -### OH_ArkUI_DragEvent_SetDragResult() +### OH_ArkUI_CustomDialog_SetMask() ``` -int32_t OH_ArkUI_DragEvent_SetDragResult (ArkUI_DragEvent * event, ArkUI_DragResult result ) +int32_t OH_ArkUI_CustomDialog_SetMask( + ArkUI_CustomDialogOptions* options, uint32_t maskColor, const ArkUI_Rect* maskRect) ``` **Description** -Sets the result for a drag event. +Sets the mask for a custom dialog box. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to an **ArkUI_DragEvent** object. | -| result | Drag the data processing result. | +| options | Dialog box parameters.| +| maskColor | Mask color, in 0xargb format.| +| maskRect | Pointer to the mask area. Events outside the mask area are transparently transmitted, and events within the mask area are not. The parameter type is **ArkUI_Rect**.| **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. - +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. -### OH_ArkUI_DragEvent_SetSuggestedDropOperation() +### OH_ArkUI_CustomDialog_SetKeyboardAvoidMode() ``` -int32_t OH_ArkUI_DragEvent_SetSuggestedDropOperation (ArkUI_DragEvent * event, ArkUI_DropProposal proposal ) +int32_t OH_ArkUI_CustomDialog_SetKeyboardAvoidMode( + ArkUI_CustomDialogOptions* options, ArkUI_KeyboardAvoidMode keyboardAvoidMode) ``` **Description** -Sets the data processing mode. +Sets the keyboard avoidance mode of a dialog box. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| proposal | Recommended data processing mode | -| proposal | Type of the badge display status. | +| options | Dialog box parameters.| +| keyboardAvoidMode | Keyboard avoidance mode, specified by an enumerated value.| **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. - +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. -### OH_ArkUI_DragPreviewOption_Dispose() +### OH_ArkUI_CustomDialog_SetHoverModeEnabled() ``` -void OH_ArkUI_DragPreviewOption_Dispose (ArkUI_DragPreviewOption * option) +int32_t OH_ArkUI_CustomDialog_SetHoverModeEnabled(ArkUI_CustomDialogOptions* options, bool enabled) ``` **Description** -Disposes of an **ArkUI_DragPreviewOption** object. +Sets whether to enable the hover mode for a dialog box. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Custom parameters. | +| options | Dialog box parameters.| +| enabled | Whether to enable the hover mode. The default value is **false**.| + +**Returns** +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. -### OH_ArkUI_DragPreviewOption_SetBadgeNumber() +### OH_ArkUI_CustomDialog_SetHoverModeArea() ``` -int32_t OH_ArkUI_DragPreviewOption_SetBadgeNumber (ArkUI_DragPreviewOption * option, uint32_t forcedNumber ) +int32_t OH_ArkUI_CustomDialog_SetHoverModeArea( + ArkUI_CustomDialogOptions* options, ArkUI_HoverModeAreaType hoverModeAreaType) ``` **Description** -Sets the count on the badge. The settings will overwrite the value in the **SetDragPreviewNumberBadgeEnabled** API. +Sets the default display area of a dialog box in hover mode. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Custom parameters. | -| forcedNumber | Number of corner marks. | +| options | Dialog box parameters.| +| hoverModeAreaType | Display area in hover mode, specified by an enumerated value.| **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. - +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. -### OH_ArkUI_DragPreviewOption_SetDefaultAnimationBeforeLiftingEnabled() +### OH_ArkUI_CustomDialog_RegisterOnWillDismissCallback() ``` -int32_t OH_ArkUI_DragPreviewOption_SetDefaultAnimationBeforeLiftingEnabled (ArkUI_DragPreviewOption * option, bool enabled ) +int32_t OH_ArkUI_CustomDialog_RegisterOnWillDismissCallback( + ArkUI_CustomDialogOptions* options, void* userData, void (*callback)(ArkUI_DialogDismissEvent* event)) ``` **Description** -Sets whether to enable the default animation on a click or touch. +Registers a callback for the dismissal event of a custom dialog box. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Custom parameters. | -| enabled | Whether to enable the default click effect. | +| options | Dialog box parameters.| +| userData | Returns the pointer to user data.| +| callback | Callback for the dismissal event of the custom dialog box.| **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. - +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. -### OH_ArkUI_DragPreviewOption_SetDefaultRadiusEnabled() +### OH_ArkUI_CustomDialog_RegisterOnWillAppearCallback() ``` -int32_t OH_ArkUI_DragPreviewOption_SetDefaultRadiusEnabled (ArkUI_DragPreviewOption * option, bool enabled ) +int32_t OH_ArkUI_CustomDialog_RegisterOnWillAppearCallback( + ArkUI_CustomDialogOptions* options, void* userData, void (*callback)(void* userData)) ``` **Description** -Sets whether to enable the default corner radius effect for an **ArkUI_DragPreviewOption** object. The effect is enabled by default. +Registers a callback to be invoked when the specified custom dialog box is about to appear. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Custom parameters. | -| enabled | Whether to enable the default corner radius effect. | +| options | Dialog box parameters.| +| userData | Returns the pointer to user data.| +| callback | Event callback when the dialog box is about to appear.| **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. - +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. -### OH_ArkUI_DragPreviewOption_SetDefaultShadowEnabled() +### OH_ArkUI_CustomDialog_RegisterOnDidAppearCallback() ``` -int32_t OH_ArkUI_DragPreviewOption_SetDefaultShadowEnabled (ArkUI_DragPreviewOption * option, bool enabled ) +int32_t OH_ArkUI_CustomDialog_RegisterOnDidAppearCallback( + ArkUI_CustomDialogOptions* options, void* userData, void (*callback)(void* userData)) ``` **Description** -Sets whether to enable the default shadow effect for an **ArkUI_DragPreviewOption** object. The effect is enabled by default. +Registers a callback to be invoked when the specifiedcustom dialog box appears. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Custom parameters. | -| enabled | Whether to enable the default shadow effect. | +| options | Dialog box parameters.| +| userData | Returns the pointer to user data.| +| callback | Event callback when the dialog box appears.| **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. - +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. -### OH_ArkUI_DragPreviewOption_SetNumberBadgeEnabled() +### OH_ArkUI_CustomDialog_RegisterOnWillDisappearCallback() ``` -int32_t OH_ArkUI_DragPreviewOption_SetNumberBadgeEnabled (ArkUI_DragPreviewOption * option, bool enabled ) +int32_t OH_ArkUI_CustomDialog_RegisterOnWillDisappearCallback( + ArkUI_CustomDialogOptions* options, void* userData, void (*callback)(void* userData)) ``` **Description** -Sets whether to enable the badge for an **ArkUI_DragPreviewOption** object. If this feature is enabled, a badge that contains the number of dragged items is displayed. +Registers a callback to be invoked when the specified custom dialog box is about to disappear. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Custom parameters. | -| enabled | Whether to enable the badge. | +| options | Dialog box parameters.| +| userData | Returns the pointer to user data.| +| callback | Event callback when the dialog box is about to disappear.| **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. - +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. -### OH_ArkUI_DragPreviewOption_SetScaleMode() +### OH_ArkUI_CustomDialog_RegisterOnDidDisappearCallback() ``` -int32_t OH_ArkUI_DragPreviewOption_SetScaleMode (ArkUI_DragPreviewOption * option, ArkUI_DragPreviewScaleMode scaleMode ) +int32_t OH_ArkUI_CustomDialog_RegisterOnDidDisappearCallback( + ArkUI_CustomDialogOptions* options, void* userData, void (*callback)(void* userData)) ``` **Description** -Sets the scale mode for an **ArkUI_DragPreviewOption** object. +* @brief Registers a callback to be invoked when the specified custom dialog box disappears. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Custom parameters. | -| scaleMode | Scale mode to set. | +| options | Dialog box parameters.| +| userData | Returns the pointer to user data.| +| callback | Event callback when the dialog box disappears.| **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. - +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. -### OH_ArkUI_DrawableDescriptor_CreateFromAnimatedPixelMap() +### OH_ArkUI_DialogDismissEvent_GetUserData() ``` -ArkUI_DrawableDescriptor* OH_ArkUI_DrawableDescriptor_CreateFromAnimatedPixelMap (OH_PixelmapNativeHandle * array, int32_t size ) +void* OH_ArkUI_DialogDismissEvent_GetUserData (ArkUI_DialogDismissEvent * event) ``` **Description** -Creates a **DrawableDescriptor** object from an array of **PixelMap** objects. +Obtains the pointer to user data in a dialog box dismiss event object. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| array | Pointer to the array of **PixelMap** objects. | -| size | Size of the **PixelMap** object array. | +| event | Pointer to a dialog box dismiss event object.| **Returns** -Returns the pointer to the created **DrawableDescriptor** object. +Returns the pointer to user data. -### OH_ArkUI_DrawableDescriptor_CreateFromPixelMap() +### OH_ArkUI_DialogDismissEvent_SetShouldBlockDismiss() ``` -ArkUI_DrawableDescriptor* OH_ArkUI_DrawableDescriptor_CreateFromPixelMap (OH_PixelmapNativeHandle pixelMap) +void OH_ArkUI_DialogDismissEvent_SetShouldBlockDismiss (ArkUI_DialogDismissEvent * event, bool shouldBlockDismiss ) ``` **Description** -Creates a **DrawableDescriptor** object from a **PixelMap** object. +Sets whether to block the system behavior of dismissing a dialog box. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| pixelMap | Pointer to the **PixelMap** object. | - -**Returns** - -Returns the pointer to the created **DrawableDescriptor** object. +| event | Pointer to a dialog box dismiss event object. | +| shouldBlockDismiss | Whether to block the system behavior of dismissing the dialog box. The value **true** means to block the system behavior, and **false** means the opposite. | -### OH_ArkUI_DrawableDescriptor_Dispose() +### OH_ArkUI_DisallowNodeAnyDropDataTypes() ``` -void OH_ArkUI_DrawableDescriptor_Dispose (ArkUI_DrawableDescriptor * drawableDescriptor) +int32_t OH_ArkUI_DisallowNodeAnyDropDataTypes (ArkUI_NodeHandle node) ``` **Description** -Disposes of the pointer to a **DrawableDescriptor** object. +The configuration component is not allowed to accept any data type. This interface resets the data type configured through [OH_ArkUI_SetNodeAllowedDropDataTypes](#oh_arkui_setnodealloweddropdatatypes). **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| drawableDescriptor | Pointer to a **DrawableDescriptor** object. | +| node | Pointer to a component node. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_DrawableDescriptor_GetAnimatedPixelMapArray() +### OH_ArkUI_DragAction_Dispose() ``` -OH_PixelmapNativeHandle* OH_ArkUI_DrawableDescriptor_GetAnimatedPixelMapArray (ArkUI_DrawableDescriptor * drawableDescriptor) +void OH_ArkUI_DragAction_Dispose (ArkUI_DragAction * dragAction) ``` **Description** -Obtains an array of **PixelMap** objects for playing an animation. +Disposes of an **ArkUI_DragAction** object. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| drawableDescriptor | Pointer to a **DrawableDescriptor** object. | - -**Returns** - -Pointer to the PixelMap image array. +| dragAction | Pointer to the target drag action object. | -### OH_ArkUI_DrawableDescriptor_GetAnimatedPixelMapArraySize() +### OH_ArkUI_DragAction_RegisterStatusListener() ``` -int32_t OH_ArkUI_DrawableDescriptor_GetAnimatedPixelMapArraySize (ArkUI_DrawableDescriptor * drawableDescriptor) +int32_t OH_ArkUI_DragAction_RegisterStatusListener (ArkUI_DragAction * dragAction, void * userData, void(*)(ArkUI_DragAndDropInfo *dragAndDropInfo, void *userData) listener ) ``` **Description** -Obtains an array of **PixelMap** objects for playing an animation. +Registers a drag status listener. This listener can be used to check whether the data is successfully received and processed. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| drawableDescriptor | Pointer to a **DrawableDescriptor** object. | +| dragAction | Pointer to the target drag action object. | +| userData | Custom user data. | +| listener | Listener to register. When the callback is invoked, the system returns a pointer to the drag status object. The pointer is destroyed after the callback is complete and the application should not hold it anymore. | **Returns** -Size of the PixelMap image array. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_DrawableDescriptor_GetAnimationDuration() +### OH_ArkUI_DragAction_SetData() ``` -int32_t OH_ArkUI_DrawableDescriptor_GetAnimationDuration (ArkUI_DrawableDescriptor * drawableDescriptor) +int32_t OH_ArkUI_DragAction_SetData (ArkUI_DragAction * dragAction, OH_UdmfData * data ) ``` **Description** -Obtains the total playback duration of a PixelMap image array. +Sets the drag data. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| drawableDescriptor | Pointer to a **DrawableDescriptor** object. | +| dragAction | Pointer to the target drag action object. | +| data | Drag data. | **Returns** -Total playback duration, in milliseconds. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_DrawableDescriptor_GetAnimationIteration() +### OH_ArkUI_DragAction_SetDragPreviewOption() ``` -int32_t OH_ArkUI_DrawableDescriptor_GetAnimationIteration (ArkUI_DrawableDescriptor * drawableDescriptor) +int32_t OH_ArkUI_DragAction_SetDragPreviewOption (ArkUI_DragAction * dragAction, ArkUI_DragPreviewOption * option ) ``` **Description** -Obtains the number of times that a **PixelMap** object array is played. +Sets an **ArkUI_DragPreviewOption** object for the specified drag action object. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| drawableDescriptor | Pointer to a **DrawableDescriptor** object. | +| dragAction | Pointer to the target drag action object. | +| option | Custom parameters. | **Returns** -Returns the number of playback times. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_DrawableDescriptor_GetStaticPixelMap() +### OH_ArkUI_DragAction_SetPixelMaps() ``` -OH_PixelmapNativeHandle OH_ArkUI_DrawableDescriptor_GetStaticPixelMap (ArkUI_DrawableDescriptor * drawableDescriptor) +int32_t OH_ArkUI_DragAction_SetPixelMaps (ArkUI_DragAction * dragAction, OH_PixelmapNative * pixelmapArray[], int32_t size ) ``` **Description** -Obtains the pointer to a **PixelMap** object. +Sets the drag previews for a drag action. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| drawableDescriptor | Pointer to a **DrawableDescriptor** object. | +| dragAction | Pointer to the target drag action object. | +| pixelmapArray | Drag the bitmap array of the follower map. | +| size | Number of drag-and-drop images. | **Returns** -Pointer to the PixelMap object. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_DrawableDescriptor_SetAnimationDuration() +### OH_ArkUI_DragAction_SetPointerId() ``` -void OH_ArkUI_DrawableDescriptor_SetAnimationDuration (ArkUI_DrawableDescriptor * drawableDescriptor, int32_t duration ) +int32_t OH_ArkUI_DragAction_SetPointerId (ArkUI_DragAction * dragAction, int32_t pointer ) ``` **Description** -Sets the total playback duration of a PixelMap image array. +Sets the pointer ID. If only one finger is operating on the screen, the pointer ID is 0. In general cases, you can set the pointer ID to 0. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| drawableDescriptor | Pointer to a **DrawableDescriptor** object. | -| duration | Total playback duration, in milliseconds. | +| dragAction | Pointer to the target drag action object. | +| pointer | Pointer ID. The value ranges from 0 to 9. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_DrawableDescriptor_SetAnimationIteration() +### OH_ArkUI_DragAction_SetTouchPointX() ``` -void OH_ArkUI_DrawableDescriptor_SetAnimationIteration (ArkUI_DrawableDescriptor * drawableDescriptor, int32_t iteration ) +int32_t OH_ArkUI_DragAction_SetTouchPointX (ArkUI_DragAction * dragAction, float x ) ``` **Description** -Sets the number of times that a pixel map image array is played. +Sets the touch point relative to the upper left corner of the first drag preview (pixel map). **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| drawableDescriptor | Pointer to a **DrawableDescriptor** object. | -| iterations | Number of playback times. | +| dragAction | Pointer to the target drag action object. | +| x | X value of the hand point coordinate. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_DrawContext_GetCanvas() +### OH_ArkUI_DragAction_SetTouchPointY() ``` -void* OH_ArkUI_DrawContext_GetCanvas (ArkUI_DrawContext * context) +int32_t OH_ArkUI_DragAction_SetTouchPointY (ArkUI_DragAction * dragAction, float y ) ``` **Description** -Obtains the drawing canvas pointer, which can be converted into the OH_Drawing_Canvas pointer of the graphics library for drawing. +Sets the touch point relative to the upper left corner of the first drag preview (pixel map). **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| context | Drawing context. | +| dragAction | Pointer to the target drag action object. | +| y | Y value of the hand point coordinate. | **Returns** -Returns the pointer to the canvas for drawing. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_DrawContext_GetSize() +### OH_ArkUI_DragAction_UnregisterStatusListener() ``` -ArkUI_IntSize OH_ArkUI_DrawContext_GetSize (ArkUI_DrawContext * context) +void OH_ArkUI_DragAction_UnregisterStatusListener (ArkUI_DragAction * dragAction) ``` **Description** -Obtains the size of a drawing area. +Unregisters a drag status listener. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| context | Drawing context. | +| dragAction | Pointer to the target drag action object. | -**Returns** -Returns the size of the drawing area. +### OH_ArkUI_DragAndDropInfo_GetDragEvent() -### OH_ArkUI_FocusActivate() ``` -void OH_ArkUI_FocusActivate(ArkUI_ContextHandle uiContext, bool isActive, bool isAutoInactive); +ArkUI_DragEvent* OH_ArkUI_DragAndDropInfo_GetDragEvent (ArkUI_DragAndDropInfo * dragAndDropInfo) ``` **Description** -Sets the focus activation state for the current page. When activated, the focused node displays a focus box. +Obtains a drag event based on the specified drag and drop information. The drag event can then be used to obtain the drag result. -**Since**: 16 +**Since**: 12 **Parameters** | Name| Description| | -------- | -------- | -| uiContext | Pointer to the UI instance object.| -| isActive | Whether to enter or exit the focus active state.| -| isAutoInactive | Whether to automatically exit the focus active state on touch or mouse down events.
**true**: Automatically exit the focus active state.
**false**: Maintain the current state until the corresponding setting API is called.| +| dragAndDropInfo | Drag-related information returned by the drag status listener. | -### OH_ArkUI_FocusClear() -``` -void OH_ArkUI_FocusClear(ArkUI_ContextHandle uiContext); -``` -**Description** - -Clears the focus to the root container node. +**Returns** -**Since**: 16 +Returns an **ArkUI_DragEvent** object; returns null if an error occurs. -**Parameters** -| Name| Description| -| -------- | -------- | -| uiContext | Pointer to the UI instance object.| +### OH_ArkUI_DragAndDropInfo_GetDragStatus() -### OH_ArkUI_FocusRequest() ``` -ArkUI_ErrorCode OH_ArkUI_FocusRequest(ArkUI_NodeHandle node); +ArkUI_DragStatus OH_ArkUI_DragAndDropInfo_GetDragStatus (ArkUI_DragAndDropInfo * dragAndDropInfo) ``` **Description** -Requests focus for a specific node. +Obtains the drag status of a drag action. -**Since**: 16 +**Since**: 12 **Parameters** | Name| Description| | -------- | -------- | -| node | Pointer to a component node. | +| dragAndDropInfo | Drag-related information returned by the drag status listener. | + +**Returns** + +Returns an **ArkUI_DragStatus** object; returns **ArkUI_DRAG_STATUS_UNKNOWN** if an error occurs. + + +### OH_ArkUI_DragEvent_DisableDefaultDropAnimation() -### OH_ArkUI_FocusSetAutoTransfer() ``` -void OH_ArkUI_FocusSetAutoTransfer(ArkUI_ContextHandle uiContext, bool autoTransfer); +int32_t OH_ArkUI_DragEvent_DisableDefaultDropAnimation (ArkUI_DragEvent * event, bool disable ) ``` **Description** - Configures the focus transfer behavior when pages are switched. +Sets whether to disable the default drop animation, which is enabled by default. Use this API to apply a custom drop animation. -**Since**: 16 +**Since**: 12 **Parameters** | Name| Description| | -------- | -------- | -| uiContext | Pointer to the UI instance object.| -| autoTransfer | Whether to automatically transfer focus when pages are switched.| +| event | Pointer to an **ArkUI_DragEvent** object. | +| disable | Whether to disable the default drop animation. The value **true** means to disable the default drop animation, and **false** means the opposite. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_GestureEvent_GetActionType() + +### OH_ArkUI_DragEvent_GetDataTypes() ``` -ArkUI_GestureEventActionType OH_ArkUI_GestureEvent_GetActionType (const ArkUI_GestureEvent * event) +int32_t OH_ArkUI_DragEvent_GetDataTypes (ArkUI_DragEvent * event, char * eventTypeArray[], int32_t length, int32_t maxStrLen) ``` **Description** -Obtains the gesture event type. +Obtains the type list of drag data types from a drag event. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Gesture event. | +| event | Pointer to an **ArkUI_DragEvent** object. | +| char | List of the drag data types. You need to create a string array first. | +| length | Total length of the array, which cannot be less than the number obtained using [OH_ArkUI_DragEvent_GetDataTypeCount](#oh_arkui_dragevent_getdatatypecount). | +| maxStrLen | Maximum length of each data type string. | **Returns** -Returns the gesture event type. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. Returns **ARKUI_ERROR_CODE_BUFFER_SIZE_ERROR** if the provided buffer size is insufficient. -### OH_ArkUI_GestureEvent_GetNode() +### OH_ArkUI_DragEvent_GetDataTypeCount() ``` -ArkUI_NodeHandle OH_ArkUI_GestureEvent_GetNode (const ArkUI_GestureEvent * event) +int32_t OH_ArkUI_DragEvent_GetDataTypeCount (ArkUI_DragEvent * event, int32_t * count ) ``` **Description** -Obtains the ArkUI component to which the gesture is bound. +Obtains the number of drag data types from a drag event. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Gesture event. | +| event | Pointer to an **ArkUI_DragEvent** object. | +| count | Number of drag data types returned. | **Returns** -Returns the ArkUI component. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_GestureEvent_GetRawInputEvent() +### OH_ArkUI_DragEvent_GetDragResult() ``` -const ArkUI_UIInputEvent* OH_ArkUI_GestureEvent_GetRawInputEvent (const ArkUI_GestureEvent * event) +int32_t OH_ArkUI_DragEvent_GetDragResult (ArkUI_DragEvent * event, ArkUI_DragResult * result ) ``` **Description** -Obtains gesture input. +Obtains the drag and drop result from the drag event. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Gesture event. | +| event | Pointer to an **ArkUI_DragEvent** object. | +| result | Drag result returned. | **Returns** -Returns the pointer to the input event of the gesture event. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_GestureEvent_GetResponseNode() +### OH_ArkUI_DragEvent_GetDropOperation() ``` -ArkUI_NodeHandle OH_ArkUI_GestureEvent_GetResponseNode (ArkUI_GestureEvent * event) +int32_t OH_ArkUI_DragEvent_GetDropOperation (ArkUI_DragEvent * event, ArkUI_DropOperation * operation) ``` **Description** -Obtains the node that responds to the gesture. +Obtains the data handling method from the drag event. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Gesture event. | +| event | Pointer to an **ArkUI_DragEvent** object. | +| operation | Data handling method returned. | **Returns** -Returns the pointer to the node if the node exists; returns **NULL** otherwise. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_GestureEventTargetInfo_IsScrollBegin() +### OH_ArkUI_DragEvent_GetModifierKeyStates() ``` -int32_t OH_ArkUI_GestureEventTargetInfo_IsScrollBegin (ArkUI_GestureEventTargetInfo * info, bool * ret ) +int32_t OH_ArkUI_DragEvent_GetModifierKeyStates (ArkUI_DragEvent * event, uint64_t * keys ) ``` **Description** -Obtains whether this scroll container is scrolled to the top. +Obtains the pressed status of modifier keys from a drag event. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| info | Gesture event target information. | -| ret | Obtains whether this scroll container is scrolled to the top. | +| event | Pointer to an **ArkUI_DragEvent** object. | +| keys | Returns the modifier key combination that is currently pressed. The application can determine the modifier key combination through bitwise operations. | **Returns** -Returns **0** if the operation is successful. Returns **401** if a parameter error occurs. Returns **180001** if the component is not a scroll container. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_GestureEventTargetInfo_IsScrollEnd() +### OH_ArkUI_DragEvent_GetPreviewRectHeight() ``` -int32_t OH_ArkUI_GestureEventTargetInfo_IsScrollEnd (ArkUI_GestureEventTargetInfo * info, bool * ret ) +float OH_ArkUI_DragEvent_GetPreviewRectHeight (ArkUI_DragEvent * event) ``` **Description** -Obtains whether this scroll container is scrolled to the bottom. +Obtains the height of a drag preview from a drag event. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| info | Gesture event target information. | -| ret | Obtains whether this scroll container is scrolled to the bottom. | +| event | Pointer to an **ArkUI_DragEvent** object. | **Returns** -Returns **0** if the operation is successful. Returns **401** if a parameter error occurs. Returns **180001** if the component is not a scroll container. +Returns the height of the drag preview, in px; returns the default value **0** if the input parameter is invalid. -### OH_ArkUI_GestureInterruptInfo_GetGestureEvent() +### OH_ArkUI_DragEvent_GetPreviewRectWidth() ``` -ArkUI_GestureEvent* OH_ArkUI_GestureInterruptInfo_GetGestureEvent (const ArkUI_GestureInterruptInfo * event) +float OH_ArkUI_DragEvent_GetPreviewRectWidth (ArkUI_DragEvent * event) ``` **Description** -Obtains the pointer to the interrupted gesture event. +Obtains the width of a drag preview from a drag event. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Interrupt callback event. | +| event | Pointer to an **ArkUI_DragEvent** object. | **Returns** -Returns the pointer to the interrupted gesture event. +Returns the width of the drag preview, in px; returns the default value **0** if the input parameter is invalid. -### OH_ArkUI_GestureInterruptInfo_GetRecognizer() +### OH_ArkUI_DragEvent_GetPreviewTouchPointX() ``` -ArkUI_GestureRecognizer* OH_ArkUI_GestureInterruptInfo_GetRecognizer (const ArkUI_GestureInterruptInfo * event) +float OH_ArkUI_DragEvent_GetPreviewTouchPointX (ArkUI_DragEvent * event) ``` **Description** -Returns the pointer to interrupted gesture recognizer. +Obtains the X coordinate of the touch point for a drag preview from a drag event. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Interrupt callback event. | +| event | Pointer to an **ArkUI_DragEvent** object. | **Returns** -Pointer to the interrupted gesture. +Returns the X coordinate of the touch point, in px; returns the default value **0** if the input parameter is invalid. -### OH_ArkUI_GestureInterruptInfo_GetSystemFlag() +### OH_ArkUI_DragEvent_GetPreviewTouchPointY() ``` -bool OH_ArkUI_GestureInterruptInfo_GetSystemFlag (const ArkUI_GestureInterruptInfo * event) +float OH_ArkUI_DragEvent_GetPreviewTouchPointY (ArkUI_DragEvent * event) ``` **Description** -Checks whether a gesture is a built-in gesture of the component. +Obtains the Y coordinate of the touch point for a drag preview from a drag event. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Gesture interrupt callback event. | +| event | Pointer to an **ArkUI_DragEvent** object. | **Returns** -true: built-in gestures; false: non-built-in gestures. +Returns the Y coordinate of the touch point, in px; returns the default value **0** if the input parameter is invalid. -### OH_ArkUI_GestureInterruptInfo_GetSystemRecognizerType() +### OH_ArkUI_DragEvent_GetTouchPointXToDisplay() ``` -int32_t OH_ArkUI_GestureInterruptInfo_GetSystemRecognizerType (const ArkUI_GestureInterruptInfo * event) +float OH_ArkUI_DragEvent_GetTouchPointXToDisplay (ArkUI_DragEvent * event) ``` **Description** -Obtains the type of the system gesture to trigger. +Obtains the X coordinate of the touch point relative to the display from a drag event. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Interrupt callback event. | +| event | Pointer to an **ArkUI_DragEvent** object. | **Returns** -Returns the type of the system gesture to trigger. If the gesture to trigger is not a system gesture, **-1** is returned. +Returns the X coordinate of the touch point relative to the display, in px; returns the default value **0** if the input parameter is invalid. -### OH_ArkUI_GetContextByNode() +### OH_ArkUI_DragEvent_GetTouchPointXToWindow() ``` -ArkUI_ContextHandle OH_ArkUI_GetContextByNode (ArkUI_NodeHandle node) +float OH_ArkUI_DragEvent_GetTouchPointXToWindow (ArkUI_DragEvent * event) ``` **Description** -Obtains the pointer to the UI context object of the specified node. +Obtains the X coordinate of the touch point relative to the window from a drag event. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | Specified node. | +| event | Pointer to an **ArkUI_DragEvent** object. | **Returns** -Returns the pointer to the UI context object. +Returns the X coordinate of the touch point relative to the window, in px; returns the default value **0** if the input parameter is invalid. -### OH_ArkUI_GetContextFromNapiValue() +### OH_ArkUI_DragEvent_GetTouchPointYToDisplay() ``` -int32_t OH_ArkUI_GetContextFromNapiValue (napi_env env, napi_value value, ArkUI_ContextHandle * context ) +float OH_ArkUI_DragEvent_GetTouchPointYToDisplay (ArkUI_DragEvent * event) ``` **Description** -Obtains a **UIContext** object on the ArkTS side and maps it to an **ArkUI_ContextHandle** object on the native side. +Obtains the Y coordinate of the touch point relative to the display from a drag event. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| env | Pointer to the NAPI environment. | -| value | Context object created on the ArkTS side. | -| context | ArkUI_ContextHandle pointer. | +| event | Pointer to an **ArkUI_DragEvent** object. | **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +Returns the Y coordinate of the touch point relative to the display, in px; returns the default value **0** if the input parameter is invalid. -### OH_ArkUI_GetDrawableDescriptorFromNapiValue() +### OH_ArkUI_DragEvent_GetTouchPointYToWindow() ``` -int32_t OH_ArkUI_GetDrawableDescriptorFromNapiValue (napi_env env, napi_value value, ArkUI_DrawableDescriptor ** drawableDescriptor ) +float OH_ArkUI_DragEvent_GetTouchPointYToWindow (ArkUI_DragEvent * event) ``` **Description** -Maps a **DrawableDescriptor** object on the ArkTS side to an **ArkUI_DrawableDescriptor** object on the native side. +Obtains the Y coordinate of the touch point relative to the window from a drag event. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| env | Pointer to the NAPI environment. | -| value | **DrawableDescriptor** object created on the ArkTS side. | -| drawableDescriptor | Object that receives the pointer to the **ArkUI_DrawableDescriptor** object. | +| event | Pointer to an **ArkUI_DragEvent** object. | **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +Returns the Y coordinate of the touch point relative to the window, in px; returns the default value **0** if the input parameter is invalid. -### OH_ArkUI_GetDrawableDescriptorFromResourceNapiValue() +### OH_ArkUI_DragEvent_GetUdmfData() ``` -int32_t OH_ArkUI_GetDrawableDescriptorFromResourceNapiValue (napi_env env, napi_value value, ArkUI_DrawableDescriptor ** drawableDescriptor ) +int32_t OH_ArkUI_DragEvent_GetUdmfData (ArkUI_DragEvent * event, OH_UdmfData * data ) ``` **Description** -Maps an $r resource object on the ArkTS side to an **ArkUI_DrawableDescriptor** object on the native side. +Obtain the default drag-and-drop data from ArkUI_DragEvent. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| env | Pointer to the NAPI environment. | -| value | $r resource object created on ArkTS. | -| drawableDescriptor | Object that receives the pointer to the **ArkUI_DrawableDescriptor** object. | +| event | Pointer to an **ArkUI_DragEvent** object. | +| data | Pointer to the dragged data of OH_UdmfData. When receiving data, the application needs to create a pointer for receiving data by using the OH_UdmfData_Create method. | **Returns** Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_GetGestureBindNodeId() +### OH_ArkUI_DragEvent_GetVelocity() ``` -int32_t OH_ArkUI_GetGestureBindNodeId (ArkUI_GestureRecognizer * recognizer, char * nodeId, int32_t size, int32_t * result ) +float OH_ArkUI_DragEvent_GetVelocity (ArkUI_DragEvent * event) ``` **Description** -Obtains the ID of the component linked to a gesture recognizer. +Obtains the dragging velocity along the main axis. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| recognizer | Pointer to the gesture recognizer. | -| nodeId | ID of a component. | -| size | Size of the storage area. | -| result | Length of the string to be copied. | +| event | Pointer to an **ArkUI_DragEvent** object. | **Returns** -Returns **0** if the operation is successful. Returns **401** if a parameter error occurs. Returns **180002** if the buffer is not large enough. +Returns the dragging velocity along the main axis, in px; returns the default value **0** if the input parameter is invalid. -### OH_ArkUI_GetGestureEventTargetInfo() +### OH_ArkUI_DragEvent_GetVelocityX() ``` -int32_t OH_ArkUI_GetGestureEventTargetInfo (ArkUI_GestureRecognizer * recognizer, ArkUI_GestureEventTargetInfo ** info ) +float OH_ArkUI_DragEvent_GetVelocityX (ArkUI_DragEvent * event) ``` **Description** -Obtains the information about a gesture event target. +Obtains the dragging velocity along the x-axis. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| recognizer | Pointer to the gesture recognizer. | -| info | Gesture event target information. | +| event | Pointer to an **ArkUI_DragEvent** object. | **Returns** -Returns **0** if the operation is successful. Returns **401** if a parameter error occurs. +Returns the dragging velocity along the x-axis, in px; returns the default value **0** if the input parameter is invalid. -### OH_ArkUI_GetGestureRecognizerEnabled() +### OH_ArkUI_DragEvent_GetVelocityY() ``` -bool OH_ArkUI_GetGestureRecognizerEnabled (ArkUI_GestureRecognizer * recognizer) +float OH_ArkUI_DragEvent_GetVelocityY (ArkUI_DragEvent * event) ``` **Description** -Obtains the enabled state of a gesture recognizer. +Obtains the dragging velocity along the y-axis. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| recognizer | Pointer to the gesture recognizer. | +| event | Pointer to an **ArkUI_DragEvent** object. | **Returns** -**true**: enabled false: disabled +Returns the dragging velocity along the y-axis, in px; returns the default value **0** if the input parameter is invalid. -### OH_ArkUI_GetGestureRecognizerState() +### OH_ArkUI_DragEvent_SetData() ``` -int32_t OH_ArkUI_GetGestureRecognizerState (ArkUI_GestureRecognizer * recognizer, ArkUI_GestureRecognizerState * state ) +int32_t OH_ArkUI_DragEvent_SetData (ArkUI_DragEvent * event, OH_UdmfData * data ) ``` **Description** -Obtains the state of a gesture recognizer. +Sets drag data for a drag event. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| recognizer | Pointer to the gesture recognizer. | -| state | Status of the gesture recognizer. | +| event | Pointer to an **ArkUI_DragEvent** object. | +| data | Drag data. | **Returns** -Returns **0** if the operation is successful. Returns **401** if a parameter error occurs. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_GetGestureTag() +### OH_ArkUI_DragEvent_SetDragResult() ``` -int32_t OH_ArkUI_GetGestureTag (ArkUI_GestureRecognizer * recognizer, char * buffer, int32_t bufferSize, int32_t * result ) +int32_t OH_ArkUI_DragEvent_SetDragResult (ArkUI_DragEvent * event, ArkUI_DragResult result ) ``` **Description** -Obtains the mark of the gesture recognizer. +Sets the result for a drag event. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| recognizer | Pointer to the gesture recognizer. | -| buffer | Storage zone | -| bufferSize | Size of the storage area. | -| result | Length of the string to be copied. | +| event | Pointer to an **ArkUI_DragEvent** object. | +| result | Drag the data processing result. | **Returns** -Returns **0** if the operation is successful. Returns **401** if a parameter error occurs. Returns **180002** if the buffer is not large enough. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_GetNavDestinationId() +### OH_ArkUI_DragEvent_SetSuggestedDropOperation() ``` -ArkUI_ErrorCode OH_ArkUI_GetNavDestinationId (ArkUI_NodeHandle node, char * buffer, int32_t bufferSize, int32_t * writeLength ) +int32_t OH_ArkUI_DragEvent_SetSuggestedDropOperation (ArkUI_DragEvent * event, ArkUI_DropOperation dropOperation) ``` **Description** -Obtains the ID of the **NavDestination** component where the specified node is located. +Sets the data processing mode. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | Specified node. | -| buffer | buffer. NavDestinationID is written to this memory area. | -| bufferSize | Pointer to the buffer size. | -| writeLength | When ARKUI_ERROR_CODE_NO_ERROR is returned, this parameter indicates the length of the string written to the buffer. When ARKUI_ERROR_CODE_BUFFER_SIZE_ERROR is returned, this parameter indicates the minimum buffer size that can hold the target. | +| proposal | Recommended data processing mode | +| proposal | Type of the badge display status. | **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. The ARKUI_ERROR_CODE_GET_INFO_FAILED fails to query information. The possible cause is that the current node is not in Navigation. The buffer size specified by ARKUI_ERROR_CODE_BUFFER_SIZE_ERROR is less than the minimum buffer size that can hold the target. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_GetNavDestinationIndex() +### OH_ArkUI_DragPreviewOption_Dispose() ``` -ArkUI_ErrorCode OH_ArkUI_GetNavDestinationIndex (ArkUI_NodeHandle node, int32_t * index ) +void OH_ArkUI_DragPreviewOption_Dispose (ArkUI_DragPreviewOption * option) ``` **Description** -Obtains the index of the **NavDestination** component where the specified node is located in the navigation stack. +Disposes of an **ArkUI_DragPreviewOption** object. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | Specified node. | -| index | Returns the index, starting from 0. | - -**Returns** - -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. The ARKUI_ERROR_CODE_GET_INFO_FAILED fails to query information. The possible cause is that the current node is not in Navigation. +| option | Custom parameters. | -### OH_ArkUI_GetNavDestinationName() +### OH_ArkUI_DragPreviewOption_SetBadgeNumber() ``` -ArkUI_ErrorCode OH_ArkUI_GetNavDestinationName (ArkUI_NodeHandle node, char * buffer, int32_t bufferSize, int32_t * writeLength ) +int32_t OH_ArkUI_DragPreviewOption_SetBadgeNumber (ArkUI_DragPreviewOption * option, uint32_t forcedNumber ) ``` **Description** -Obtains the name of the **NavDestination** component where the specified node is located. +Sets the count on the badge. The settings will overwrite the value in the **SetDragPreviewNumberBadgeEnabled** API. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | Specified node. | -| buffer | Buffer. The queried NavDestination name is written to this memory area. | -| bufferSize | Pointer to the buffer size. | -| writeLength | When ARKUI_ERROR_CODE_NO_ERROR is returned, this parameter indicates the length of the string written to the buffer. When ARKUI_ERROR_CODE_BUFFER_SIZE_ERROR is returned, this parameter indicates the minimum buffer size that can hold the target. | +| option | Custom parameters. | +| forcedNumber | Number of corner marks. | **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. The ARKUI_ERROR_CODE_GET_INFO_FAILED fails to query information. The possible cause is that the current node is not in Navigation. The buffer size specified by ARKUI_ERROR_CODE_BUFFER_SIZE_ERROR is less than the minimum buffer size that can hold the target. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_GetNavDestinationNameByIndex() +### OH_ArkUI_DragPreviewOption_SetDefaultAnimationBeforeLiftingEnabled() ``` -ArkUI_ErrorCode OH_ArkUI_GetNavDestinationNameByIndex (ArkUI_NodeHandle node, int32_t index, char * buffer, int32_t bufferSize, int32_t * writeLength ) +int32_t OH_ArkUI_DragPreviewOption_SetDefaultAnimationBeforeLiftingEnabled (ArkUI_DragPreviewOption * option, bool enabled ) ``` **Description** -Obtains the page name that matches the specified index in the navigation stack where the specified node is located. The index starts from 0, which indicates the bottom of the stack. +Sets whether to enable the default animation on a click or touch. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | Specified node. | -| index | Index of the queried NavDestination in the stack. | -| buffer | Buffer. The name of the queried page is written to this memory area. | -| bufferSize | Pointer to the buffer size. | -| writeLength | When ARKUI_ERROR_CODE_NO_ERROR is returned, this parameter indicates the length of the string written to the buffer. When ARKUI_ERROR_CODE_BUFFER_SIZE_ERROR is returned, this parameter indicates the minimum buffer size that can hold the target. | +| option | Custom parameters. | +| enabled | Whether to enable the default click effect. | **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. The value of ARKUI_ERROR_CODE_NODE_INDEX_INVALID index is invalid. The ARKUI_ERROR_CODE_GET_INFO_FAILED fails to query information. The possible cause is that the current node is not in Navigation. The buffer size specified by ARKUI_ERROR_CODE_BUFFER_SIZE_ERROR is less than the minimum buffer size that can hold the target. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_GetNavDestinationParam() +### OH_ArkUI_DragPreviewOption_SetDefaultRadiusEnabled() ``` -napi_value OH_ArkUI_GetNavDestinationParam (ArkUI_NodeHandle node) +int32_t OH_ArkUI_DragPreviewOption_SetDefaultRadiusEnabled (ArkUI_DragPreviewOption * option, bool enabled ) ``` **Description** -Obtains the parameters of the **NavDestination** component where the specified node is located. +Sets whether to enable the default corner radius effect for an **ArkUI_DragPreviewOption** object. The effect is disabled by default. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | Specified node. | +| option | Custom parameters. | +| enabled | Whether to enable the default corner radius effect. | **Returns** -Parameter object. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_GetNavDestinationState() +### OH_ArkUI_DragPreviewOption_SetDefaultShadowEnabled() ``` -ArkUI_ErrorCode OH_ArkUI_GetNavDestinationState (ArkUI_NodeHandle node, ArkUI_NavDestinationState * state ) +int32_t OH_ArkUI_DragPreviewOption_SetDefaultShadowEnabled (ArkUI_DragPreviewOption * option, bool enabled ) ``` **Description** -Obtains the state of the **NavDestination** component where the specified node is located. +Sets whether to enable the default shadow effect for an **ArkUI_DragPreviewOption** object. The effect is disabled by default. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | Specified node. | -| state | The status value of NavDestination is written back to this parameter. | +| option | Custom parameters. | +| enabled | Whether to enable the default shadow effect. | **Returns** -The error code ARKUI_ERROR_CODE_NO_ERROR is returned. The ARKUI_ERROR_CODE_GET_INFO_FAILED fails to query information. The possible cause is that the current node is not in Navigation. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_GetNavigationId() +### OH_ArkUI_DragPreviewOption_SetNumberBadgeEnabled() ``` -ArkUI_ErrorCode OH_ArkUI_GetNavigationId (ArkUI_NodeHandle node, char * buffer, int32_t bufferSize, int32_t * writeLength ) +int32_t OH_ArkUI_DragPreviewOption_SetNumberBadgeEnabled (ArkUI_DragPreviewOption * option, bool enabled ) ``` **Description** -Obtains the ID of the **Navigation** component where the specified node is located. +Sets whether to enable the badge for an **ArkUI_DragPreviewOption** object. If this feature is enabled, a badge that contains the number of dragged items is displayed. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | Specified node. | -| buffer | buffer. The NavigationID is written to this memory area. | -| bufferSize | Pointer to the buffer size. | -| writeLength | When ARKUI_ERROR_CODE_NO_ERROR is returned, this parameter indicates the length of the string written to the buffer. When ARKUI_ERROR_CODE_BUFFER_SIZE_ERROR is returned, this parameter indicates the minimum buffer size that can hold the target. | +| option | Custom parameters. | +| enabled | Whether to enable the badge. | **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. The ARKUI_ERROR_CODE_GET_INFO_FAILED fails to query information. The possible cause is that the current node is not in Navigation. The buffer size specified by ARKUI_ERROR_CODE_BUFFER_SIZE_ERROR is less than the minimum buffer size that can hold the target. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_GetNavStackLength() +### OH_ArkUI_DragPreviewOption_SetScaleMode() ``` -ArkUI_ErrorCode OH_ArkUI_GetNavStackLength (ArkUI_NodeHandle node, int32_t * length ) +int32_t OH_ArkUI_DragPreviewOption_SetScaleMode (ArkUI_DragPreviewOption * option, ArkUI_DragPreviewScaleMode scaleMode ) ``` **Description** -Obtains the length of the navigation stack where the specified node is located. +Sets the scale mode for an **ArkUI_DragPreviewOption** object. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | Specified node. | -| length | Length of the stack. The result, if obtained successfully, is written back to this parameter. | +| option | Custom parameters. | +| scaleMode | Scale mode to set. | **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. The ARKUI_ERROR_CODE_GET_INFO_FAILED fails to query information. The possible cause is that the current node is not in Navigation. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_GetNodeContentFromNapiValue() +### OH_ArkUI_DrawableDescriptor_CreateFromAnimatedPixelMap() ``` -int32_t OH_ArkUI_GetNodeContentFromNapiValue (napi_env env, napi_value value, ArkUI_NodeContentHandle * content ) +ArkUI_DrawableDescriptor* OH_ArkUI_DrawableDescriptor_CreateFromAnimatedPixelMap (OH_PixelmapNativeHandle * array, int32_t size ) ``` **Description** -Obtains a **NodeContent** object on the ArkTS side and maps it to an **ArkUI_NodeContentHandle** object on the native side. +Creates a **DrawableDescriptor** object from an array of **PixelMap** objects. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| env | Pointer to the NAPI environment. | -| value | NodeContent object created on ArkTS. | -| context | ArkUI_NodeContentHandle pointer. | +| array | Pointer to the array of **PixelMap** objects. | +| size | Size of the **PixelMap** object array. | **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +Returns the pointer to the created **DrawableDescriptor** object. -### OH_ArkUI_GetNodeHandleFromNapiValue() +### OH_ArkUI_DrawableDescriptor_CreateFromPixelMap() ``` -int32_t OH_ArkUI_GetNodeHandleFromNapiValue (napi_env env, napi_value frameNode, ArkUI_NodeHandle * handle ) +ArkUI_DrawableDescriptor* OH_ArkUI_DrawableDescriptor_CreateFromPixelMap (OH_PixelmapNativeHandle pixelMap) ``` **Description** -Obtains a **FrameNode** object on the ArkTS side and maps it to an **ArkUI_NodeHandle** object on the native side. +Creates a **DrawableDescriptor** object from a **PixelMap** object. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| env | Pointer to the NAPI environment. | -| frameNode | FrameNode object created on the ArkTS side. | -| handle | **ArkUI_NodeHandle** pointer. | +| pixelMap | Pointer to the **PixelMap** object. | **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +Returns the pointer to the created **DrawableDescriptor** object. -### OH_ArkUI_GetPanGestureDirectionMask() + +### OH_ArkUI_DrawableDescriptor_Dispose() ``` -int32_t OH_ArkUI_GetPanGestureDirectionMask (ArkUI_GestureRecognizer * recognizer, ArkUI_GestureDirectionMask * directionMask ) +void OH_ArkUI_DrawableDescriptor_Dispose (ArkUI_DrawableDescriptor * drawableDescriptor) ``` **Description** -Obtains the direction of a pan gesture. +Disposes of the pointer to a **DrawableDescriptor** object. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| recognizer | Pointer to the gesture recognizer. | -| directionMask | Sliding direction of the sliding gesture. | - -**Returns** - -Returns **0** if the operation is successful. Returns **401** if a parameter error occurs. +| drawableDescriptor | Pointer to a **DrawableDescriptor** object. | -### OH_ArkUI_GetResponseRecognizersFromInterruptInfo() +### OH_ArkUI_DrawableDescriptor_GetAnimatedPixelMapArray() ``` -int32_t OH_ArkUI_GetResponseRecognizersFromInterruptInfo (const ArkUI_GestureInterruptInfo * event, ArkUI_GestureRecognizerHandleArray * responseChain, int32_t * count ) +OH_PixelmapNativeHandle* OH_ArkUI_DrawableDescriptor_GetAnimatedPixelMapArray (ArkUI_DrawableDescriptor * drawableDescriptor) ``` **Description** -Obtains information about a gesture response chain. +Obtains an array of **PixelMap** objects for playing an animation. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Gesture interrupt callback event. | -| responseChain | Gesture recognizer on the response chain component. | -| count | Number of gesture recognizers on the response chain component. | +| drawableDescriptor | Pointer to a **DrawableDescriptor** object. | **Returns** -Returns **0** if the operation is successful. Returns **401** if a parameter error occurs. +Pointer to the PixelMap image array. -### OH_ArkUI_GetRouterPageId() +### OH_ArkUI_DrawableDescriptor_GetAnimatedPixelMapArraySize() ``` -ArkUI_ErrorCode OH_ArkUI_GetRouterPageId (ArkUI_NodeHandle node, char * buffer, int32_t bufferSize, int32_t * writeLength ) +int32_t OH_ArkUI_DrawableDescriptor_GetAnimatedPixelMapArraySize (ArkUI_DrawableDescriptor * drawableDescriptor) ``` **Description** -Obtains the ID of the page where the specified node is located. +Obtains an array of **PixelMap** objects for playing an animation. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | Specified node. | -| buffer | buffer. Page Id is written to this memory area. | -| bufferSize | Pointer to the buffer size. | -| writeLength | When ARKUI_ERROR_CODE_NO_ERROR is returned, this parameter indicates the length of the string written to the buffer. When ARKUI_ERROR_CODE_BUFFER_SIZE_ERROR is returned, this parameter indicates the minimum buffer size that can hold the target. | +| drawableDescriptor | Pointer to a **DrawableDescriptor** object. | **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. The ARKUI_ERROR_CODE_GET_INFO_FAILED fails to query information. The buffer size specified by ARKUI_ERROR_CODE_BUFFER_SIZE_ERROR is less than the minimum buffer size that can hold the target. +Size of the PixelMap image array. -### OH_ArkUI_GetRouterPageIndex() +### OH_ArkUI_DrawableDescriptor_GetAnimationDuration() ``` -ArkUI_ErrorCode OH_ArkUI_GetRouterPageIndex (ArkUI_NodeHandle node, int32_t * index ) +int32_t OH_ArkUI_DrawableDescriptor_GetAnimationDuration (ArkUI_DrawableDescriptor * drawableDescriptor) ``` **Description** -Obtains the index of the page where the specified node is located in the page stack for routing. +Obtains the total playback duration of a PixelMap image array. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | Specified node. | -| index | Returns the index, starting from 1. | +| drawableDescriptor | Pointer to a **DrawableDescriptor** object. | **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. The ARKUI_ERROR_CODE_GET_INFO_FAILED fails to query information. The possible cause is that the current node is not in Navigation. +Total playback duration, in milliseconds. -### OH_ArkUI_GetRouterPageName() +### OH_ArkUI_DrawableDescriptor_GetAnimationIteration() ``` -ArkUI_ErrorCode OH_ArkUI_GetRouterPageName (ArkUI_NodeHandle node, char * buffer, int32_t bufferSize, int32_t * writeLength ) +int32_t OH_ArkUI_DrawableDescriptor_GetAnimationIteration (ArkUI_DrawableDescriptor * drawableDescriptor) ``` **Description** -Obtains the name of the page where the specified node is located. +Obtains the number of times that a **PixelMap** object array is played. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | Specified node. | -| buffer | Buffer. The page name is written to this memory area. | -| bufferSize | Pointer to the buffer size. | -| writeLength | When ARKUI_ERROR_CODE_NO_ERROR is returned, this parameter indicates the length of the string written to the buffer. When ARKUI_ERROR_CODE_BUFFER_SIZE_ERROR is returned, this parameter indicates the minimum buffer size that can hold the target. | +| drawableDescriptor | Pointer to a **DrawableDescriptor** object. | **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. The ARKUI_ERROR_CODE_GET_INFO_FAILED fails to query information. The buffer size specified by ARKUI_ERROR_CODE_BUFFER_SIZE_ERROR is less than the minimum buffer size that can hold the target. +Returns the number of playback times. -### OH_ArkUI_GetRouterPagePath() +### OH_ArkUI_DrawableDescriptor_GetStaticPixelMap() ``` -ArkUI_ErrorCode OH_ArkUI_GetRouterPagePath (ArkUI_NodeHandle node, char * buffer, int32_t bufferSize, int32_t * writeLength ) +OH_PixelmapNativeHandle OH_ArkUI_DrawableDescriptor_GetStaticPixelMap (ArkUI_DrawableDescriptor * drawableDescriptor) ``` **Description** -Obtains the path to the page where the specified node is located. +Obtains the pointer to a **PixelMap** object. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | Specified node. | -| buffer | buffer. Page Path is written to this memory area. | -| bufferSize | Pointer to the buffer size. | -| writeLength | When ARKUI_ERROR_CODE_NO_ERROR is returned, this parameter indicates the length of the string written to the buffer. When ARKUI_ERROR_CODE_BUFFER_SIZE_ERROR is returned, this parameter indicates the minimum buffer size that can hold the target. | +| drawableDescriptor | Pointer to a **DrawableDescriptor** object. | **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. The ARKUI_ERROR_CODE_GET_INFO_FAILED fails to query information. The buffer size specified by ARKUI_ERROR_CODE_BUFFER_SIZE_ERROR is less than the minimum buffer size that can hold the target. +Pointer to the PixelMap object. -### OH_ArkUI_GetRouterPageState() +### OH_ArkUI_DrawableDescriptor_SetAnimationDuration() ``` -ArkUI_ErrorCode OH_ArkUI_GetRouterPageState (ArkUI_NodeHandle node, ArkUI_RouterPageState * state ) +void OH_ArkUI_DrawableDescriptor_SetAnimationDuration (ArkUI_DrawableDescriptor * drawableDescriptor, int32_t duration ) ``` **Description** -Obtains the state of the page where the specified node is located. +Sets the total playback duration of a PixelMap image array. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | Specified node. | -| state | The status value of Router Page is written back to this parameter. | - -**Returns** - -The error code ARKUI_ERROR_CODE_NO_ERROR is returned. The ARKUI_ERROR_CODE_GET_INFO_FAILED fails to query information. +| drawableDescriptor | Pointer to a **DrawableDescriptor** object. | +| duration | Total playback duration, in milliseconds. | -### OH_ArkUI_GuidelineOption_Create() +### OH_ArkUI_DrawableDescriptor_SetAnimationIteration() ``` -ArkUI_GuidelineOption* OH_ArkUI_GuidelineOption_Create (int32_t size) +void OH_ArkUI_DrawableDescriptor_SetAnimationIteration (ArkUI_DrawableDescriptor * drawableDescriptor, int32_t iteration ) ``` **Description** -Creates a guideline configuration for this **RelativeContainer**. +Sets the number of times that a pixel map image array is played. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| size | Number of guidelines. | - -**Returns** - -Returns the guideline configuration. +| drawableDescriptor | Pointer to a **DrawableDescriptor** object. | +| iterations | Number of playback times. | -### OH_ArkUI_GuidelineOption_Dispose() +### OH_ArkUI_DrawContext_GetCanvas() ``` -void OH_ArkUI_GuidelineOption_Dispose (ArkUI_GuidelineOption * guideline) +void* OH_ArkUI_DrawContext_GetCanvas (ArkUI_DrawContext * context) ``` **Description** -Destroys auxiliary line information. +Obtains the drawing canvas pointer, which can be converted into the OH_Drawing_Canvas pointer of the graphics library for drawing. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| guideline | Pointer to a guideline configuration. | +| context | Drawing context. | +**Returns** -### OH_ArkUI_GuidelineOption_GetDirection() +Returns the pointer to the canvas for drawing. + + +### OH_ArkUI_DrawContext_GetSize() ``` -ArkUI_Axis OH_ArkUI_GuidelineOption_GetDirection (ArkUI_GuidelineOption * guideline, int32_t index ) +ArkUI_IntSize OH_ArkUI_DrawContext_GetSize (ArkUI_DrawContext * context) ``` **Description** -Obtains the direction of a guideline. +Obtains the size of a drawing area. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| guideline | Pointer to a guideline configuration. | -| index | Index of the guideline. | +| context | Drawing context. | **Returns** -Returns the direction of the guideline. - - -### OH_ArkUI_GuidelineOption_GetId() +Returns the size of the drawing area. +### OH_ArkUI_FocusActivate() ``` -const char* OH_ArkUI_GuidelineOption_GetId (ArkUI_GuidelineOption * guideline, int32_t index ) +void OH_ArkUI_FocusActivate(ArkUI_ContextHandle uiContext, bool isActive, bool isAutoInactive); ``` **Description** -Obtains the ID of a guideline. +Sets the focus activation state for the current page. When activated, the focused node displays a focus box. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| guideline | Pointer to a guideline configuration. | -| index | Index of the guideline. | +| uiContext | Pointer to the UI instance object.| +| isActive | Whether to enter or exit the focus active state.| +| isAutoInactive | Whether to automatically exit the focus active state on touch or mouse down events.
**true**: Automatically exit the focus active state.
**false**: Maintain the current state until the corresponding setting API is called.| -**Returns** +### OH_ArkUI_FocusClear() +``` +void OH_ArkUI_FocusClear(ArkUI_ContextHandle uiContext); +``` +**Description** -Returns the ID of the guideline. +Clears the focus to the root container node. +**Since**: 15 -### OH_ArkUI_GuidelineOption_GetPositionEnd() +**Parameters** + +| Name| Description| +| -------- | -------- | +| uiContext | Pointer to the UI instance object.| +### OH_ArkUI_FocusRequest() ``` -float OH_ArkUI_GuidelineOption_GetPositionEnd (ArkUI_GuidelineOption * guideline, int32_t index ) +ArkUI_ErrorCode OH_ArkUI_FocusRequest(ArkUI_NodeHandle node); ``` **Description** -Obtains the distance between a guideline and the right or bottom of the container. +Requests focus for a specific node. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| guideline | Pointer to a guideline configuration. | -| index | Index of the guideline. | +| node | Pointer to a component node. | -**Returns** +### OH_ArkUI_FocusSetAutoTransfer() +``` +void OH_ArkUI_FocusSetAutoTransfer(ArkUI_ContextHandle uiContext, bool autoTransfer); +``` +**Description** -Distance between the guideline and the right or bottom of the container. + Configures the focus transfer behavior when pages are switched. +**Since**: 15 -### OH_ArkUI_GuidelineOption_GetPositionStart() +**Parameters** +| Name| Description| +| -------- | -------- | +| uiContext | Pointer to the UI instance object.| +| autoTransfer | Whether to automatically transfer focus when pages are switched.| + +### OH_ArkUI_FocusSetKeyProcessingMode() ``` -float OH_ArkUI_GuidelineOption_GetPositionStart (ArkUI_GuidelineOption * guideline, int32_t index ) +void OH_ArkUI_FocusSetKeyProcessingMode(ArkUI_ContextHandle uiContext, ArkUI_KeyProcessingMode mode) ``` **Description** -Obtains the distance between a guideline and the left or top of the container. +Sets the mode for processing key events. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| guideline | Pointer to a guideline configuration. | -| index | Index of the guideline. | - -**Returns** - -Distance between the guideline and the left or top of the container. - +| uiContext | Pointer to the UI instance object.| +| mode | Mode for processing key events.| -### OH_ArkUI_GuidelineOption_SetDirection() +### OH_ArkUI_GestureEvent_GetActionType() ``` -void OH_ArkUI_GuidelineOption_SetDirection (ArkUI_GuidelineOption * guideline, ArkUI_Axis value, int32_t index ) +ArkUI_GestureEventActionType OH_ArkUI_GestureEvent_GetActionType (const ArkUI_GestureEvent * event) ``` **Description** -Sets the direction of a guideline. +Obtains the gesture event type. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| guideline | Pointer to a guideline configuration. | -| value | Direction. | -| index | Index of the guideline. | +| event | Gesture event. | +**Returns** + +Returns the gesture event type. -### OH_ArkUI_GuidelineOption_SetId() + +### OH_ArkUI_GestureEvent_GetNode() ``` -void OH_ArkUI_GuidelineOption_SetId (ArkUI_GuidelineOption * guideline, const char * value, int32_t index ) +ArkUI_NodeHandle OH_ArkUI_GestureEvent_GetNode (const ArkUI_GestureEvent * event) ``` **Description** -Sets the ID of a guideline. +Obtains the ArkUI component to which the gesture is bound. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| guideline | Pointer to a guideline configuration. | -| value | ID of the guideline, which must be unique and cannot be the same as the name of any component in the container. | -| index | Index of the guideline. | +| event | Gesture event. | +**Returns** + +Returns the ArkUI component. -### OH_ArkUI_GuidelineOption_SetPositionEnd() + +### OH_ArkUI_GestureEvent_GetRawInputEvent() ``` -void OH_ArkUI_GuidelineOption_SetPositionEnd (ArkUI_GuidelineOption * guideline, float value, int32_t index ) +const ArkUI_UIInputEvent* OH_ArkUI_GestureEvent_GetRawInputEvent (const ArkUI_GestureEvent * event) ``` **Description** -Sets the distance between a guideline and the right or bottom of the container. +Obtains gesture input. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| guideline | Pointer to a guideline configuration. | -| value | Distance between the guideline and the right or bottom of the container. | -| index | Index of the guideline. | +| event | Gesture event. | +**Returns** + +Returns the pointer to the input event of the gesture event. -### OH_ArkUI_GuidelineOption_SetPositionStart() + +### OH_ArkUI_GestureEvent_GetResponseNode() ``` -void OH_ArkUI_GuidelineOption_SetPositionStart (ArkUI_GuidelineOption * guideline, float value, int32_t index ) +ArkUI_NodeHandle OH_ArkUI_GestureEvent_GetResponseNode (ArkUI_GestureEvent * event) ``` **Description** -Sets the distance between a guideline and the left or top of the container. +Obtains the node that responds to the gesture. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| guideline | Pointer to a guideline configuration. | -| value | Distance between the guideline and the left or top of the container. | -| index | Index of the guideline. | +| event | Gesture event. | +**Returns** + +Returns the pointer to the node if the node exists; returns **NULL** otherwise. -### OH_ArkUI_ImageAnimatorFrameInfo_CreateFromDrawableDescriptor() + +### OH_ArkUI_GestureEventTargetInfo_IsScrollBegin() ``` -ArkUI_ImageAnimatorFrameInfo* OH_ArkUI_ImageAnimatorFrameInfo_CreateFromDrawableDescriptor (ArkUI_DrawableDescriptor * drawable) +int32_t OH_ArkUI_GestureEventTargetInfo_IsScrollBegin (ArkUI_GestureEventTargetInfo * info, bool * ret ) ``` **Description** -Creates an image frame information object based on a **DrawableDescriptor** object, with the image format being Resource or PixelMap. +Obtains whether this scroll container is scrolled to the top. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| drawable | Pointer to an **ArkUI_DrawableDescriptor** object created using Resource or PixelMap. | +| info | Gesture event target information. | +| ret | Obtains whether this scroll container is scrolled to the top. | **Returns** -Returns the pointer to the created frame image object. +Returns **0** if the operation is successful. Returns **401** if a parameter error occurs. Returns **180001** if the component is not a scroll container. -### OH_ArkUI_ImageAnimatorFrameInfo_CreateFromString() +### OH_ArkUI_GestureEventTargetInfo_IsScrollEnd() ``` -ArkUI_ImageAnimatorFrameInfo* OH_ArkUI_ImageAnimatorFrameInfo_CreateFromString (char * src) +int32_t OH_ArkUI_GestureEventTargetInfo_IsScrollEnd (ArkUI_GestureEventTargetInfo * info, bool * ret ) ``` **Description** -Creates an image frame information object based on an image path, with the image format being SVG, PNG, or JPG. +Obtains whether this scroll container is scrolled to the bottom. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| src | Image path. | +| info | Gesture event target information. | +| ret | Obtains whether this scroll container is scrolled to the bottom. | **Returns** -Returns the pointer to the created frame image object. +Returns **0** if the operation is successful. Returns **401** if a parameter error occurs. Returns **180001** if the component is not a scroll container. -### OH_ArkUI_ImageAnimatorFrameInfo_Dispose() +### OH_ArkUI_GestureInterruptInfo_GetGestureEvent() ``` -void OH_ArkUI_ImageAnimatorFrameInfo_Dispose (ArkUI_ImageAnimatorFrameInfo * imageInfo) +ArkUI_GestureEvent* OH_ArkUI_GestureInterruptInfo_GetGestureEvent (const ArkUI_GestureInterruptInfo * event) ``` **Description** -Disposes of the pointer to an image frame information object. +Obtains the pointer to the interrupted gesture event. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| imageInfo | Pointer to the frame image object. | +| event | Interrupt callback event. | +**Returns** -### OH_ArkUI_ImageAnimatorFrameInfo_GetDuration() +Returns the pointer to the interrupted gesture event. + +### OH_ArkUI_GestureInterruptInfo_GetRecognizer() ``` -int32_t OH_ArkUI_ImageAnimatorFrameInfo_GetDuration (ArkUI_ImageAnimatorFrameInfo * imageInfo) +ArkUI_GestureRecognizer* OH_ArkUI_GestureInterruptInfo_GetRecognizer (const ArkUI_GestureInterruptInfo * event) ``` **Description** -Obtains the playback duration of an image. +Returns the pointer to interrupted gesture recognizer. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| imageInfo | Pointer to the frame image object. | +| event | Interrupt callback event. | **Returns** -Returns the playback duration of the image, in milliseconds. If **imageInfo** is a null pointer, **0** is returned. +Pointer to the interrupted gesture. -### OH_ArkUI_ImageAnimatorFrameInfo_GetHeight() +### OH_ArkUI_GestureInterruptInfo_GetSystemFlag() ``` -int32_t OH_ArkUI_ImageAnimatorFrameInfo_GetHeight (ArkUI_ImageAnimatorFrameInfo * imageInfo) +bool OH_ArkUI_GestureInterruptInfo_GetSystemFlag (const ArkUI_GestureInterruptInfo * event) ``` **Description** -Obtains the image height. +Checks whether a gesture is a built-in gesture of the component. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| imageInfo | Pointer to the frame image object. | +| event | Gesture interrupt callback event. | **Returns** -Returns the image height, in PX. If **imageInfo** is a null pointer, **0** is returned. +true: built-in gestures; false: non-built-in gestures. -### OH_ArkUI_ImageAnimatorFrameInfo_GetLeft() +### OH_ArkUI_GestureInterruptInfo_GetSystemRecognizerType() ``` -int32_t OH_ArkUI_ImageAnimatorFrameInfo_GetLeft (ArkUI_ImageAnimatorFrameInfo * imageInfo) +int32_t OH_ArkUI_GestureInterruptInfo_GetSystemRecognizerType (const ArkUI_GestureInterruptInfo * event) ``` **Description** -Obtains the horizontal coordinate of an image relative to the upper left corner of the component. +Obtains the type of the system gesture to trigger. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| imageInfo | Pointer to the frame image object. | +| event | Interrupt callback event. | **Returns** -Returns the horizontal coordinate of the image relative to the upper left corner of the component, in px. If **imageInfo** is a null pointer, **0** is returned. +Returns the type of the system gesture to trigger. If the gesture to trigger is not a system gesture, **-1** is returned. -### OH_ArkUI_ImageAnimatorFrameInfo_GetTop() +### OH_ArkUI_GestureInterruptInfo_GetTouchRecognizers() ``` -int32_t OH_ArkUI_ImageAnimatorFrameInfo_GetTop (ArkUI_ImageAnimatorFrameInfo * imageInfo) +int32_t OH_ArkUI_GestureInterruptInfo_GetTouchRecognizers(const ArkUI_GestureInterruptInfo* info, + ArkUI_TouchRecognizerHandleArray* recognizers, int32_t* size) ``` **Description** -Obtains the vertical coordinate of an image relative to the upper left corner of the component. +Obtains touch recognizers from gesture interruption information. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| imageInfo | Pointer to the frame image object. | +| info | Interrupt callback event. | +| recognizers | Pointer to the array of touch recognizers. | +| size | Pointer to the size of the touch recognizer array. | **Returns** -Returns the vertical coordinate of the image relative to the upper left corner of the component, in px. If **imageInfo** is a null pointer, **0** is returned. +Returns **0** if the operation is successful. Returns **401** if a parameter error occurs. -### OH_ArkUI_ImageAnimatorFrameInfo_GetWidth() +### OH_ArkUI_TouchRecognizer_GetNodeHandle() ``` -int32_t OH_ArkUI_ImageAnimatorFrameInfo_GetWidth (ArkUI_ImageAnimatorFrameInfo * imageInfo) +ArkUI_NodeHandle OH_ArkUI_TouchRecognizer_GetNodeHandle(const ArkUI_TouchRecognizerHandle recognizer) ``` **Description** -Obtains the image width. +Obtains the component handle corresponding to a touch recognizer. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| imageInfo | Pointer to the frame image object. | +| recognizer | Handle to the touch recognizer. | **Returns** -Returns the image width, in PX. If **imageInfo** is a null pointer, **0** is returned. +Returns the component handle corresponding to the touch recognizer. -### OH_ArkUI_ImageAnimatorFrameInfo_SetDuration() +### OH_ArkUI_TouchRecognizer_CancelTouch() ``` -void OH_ArkUI_ImageAnimatorFrameInfo_SetDuration (ArkUI_ImageAnimatorFrameInfo * imageInfo, int32_t duration ) +int32_t OH_ArkUI_TouchRecognizer_CancelTouch(ArkUI_TouchRecognizerHandle recognizer, ArkUI_GestureInterruptInfo* info) ``` **Description** -Sets the playback duration of an image. +Sends a cancel touch event to a touch recognizer in a gesture interruption callback. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| imageInfo | Pointer to the frame image object. | -| duration | Playback duration of an image, in milliseconds. | +| recognizer | Handle to the touch recognizer. | +| info | Interrupt callback event. | +**Returns** -### OH_ArkUI_ImageAnimatorFrameInfo_SetHeight() +Returns **0** if the operation is successful. Returns **401** if a parameter error occurs. + + +### OH_ArkUI_GetContextByNode() ``` -void OH_ArkUI_ImageAnimatorFrameInfo_SetHeight (ArkUI_ImageAnimatorFrameInfo * imageInfo, int32_t height ) +ArkUI_ContextHandle OH_ArkUI_GetContextByNode (ArkUI_NodeHandle node) ``` **Description** -Sets the image height. +Obtains the pointer to the UI context object of the specified node. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| imageInfo | Pointer to the frame image object. | -| height | Image height, in px. | +| node | Specified node. | + +**Returns** + +Returns the pointer to the UI context object. -### OH_ArkUI_ImageAnimatorFrameInfo_SetLeft() +### OH_ArkUI_GetContextFromNapiValue() ``` -void OH_ArkUI_ImageAnimatorFrameInfo_SetLeft (ArkUI_ImageAnimatorFrameInfo * imageInfo, int32_t left ) +int32_t OH_ArkUI_GetContextFromNapiValue (napi_env env, napi_value value, ArkUI_ContextHandle * context ) ``` **Description** -Sets the horizontal coordinate of an image relative to the upper left corner of the component. +Obtains a **UIContext** object on the ArkTS side and maps it to an **ArkUI_ContextHandle** object on the native side. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| imageInfo | Pointer to the frame image object. | -| left | Horizontal coordinate of the image relative to the upper left corner of the component, in px. | +| env | Pointer to the NAPI environment. | +| value | Context object created on the ArkTS side. | +| context | ArkUI_ContextHandle pointer. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_ImageAnimatorFrameInfo_SetTop() +### OH_ArkUI_GetDrawableDescriptorFromNapiValue() ``` -void OH_ArkUI_ImageAnimatorFrameInfo_SetTop (ArkUI_ImageAnimatorFrameInfo * imageInfo, int32_t top ) +int32_t OH_ArkUI_GetDrawableDescriptorFromNapiValue (napi_env env, napi_value value, ArkUI_DrawableDescriptor ** drawableDescriptor ) ``` **Description** -Sets the vertical coordinate of an image relative to the upper left corner of the component. +Maps a **DrawableDescriptor** object on the ArkTS side to an **ArkUI_DrawableDescriptor** object on the native side. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| imageInfo | Pointer to the frame image object. | -| top | Vertical coordinate of the image relative to the upper left corner of the component, in px. | +| env | Pointer to the NAPI environment. | +| value | **DrawableDescriptor** object created on the ArkTS side. | +| drawableDescriptor | Object that receives the pointer to the **ArkUI_DrawableDescriptor** object. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_ImageAnimatorFrameInfo_SetWidth() +### OH_ArkUI_GetDrawableDescriptorFromResourceNapiValue() ``` -void OH_ArkUI_ImageAnimatorFrameInfo_SetWidth (ArkUI_ImageAnimatorFrameInfo * imageInfo, int32_t width ) +int32_t OH_ArkUI_GetDrawableDescriptorFromResourceNapiValue (napi_env env, napi_value value, ArkUI_DrawableDescriptor ** drawableDescriptor ) ``` **Description** -Sets the image width. +Maps an $r resource object on the ArkTS side to an **ArkUI_DrawableDescriptor** object on the native side. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| imageInfo | Pointer to the frame image object. | -| width | Image width, in px. | +| env | Pointer to the NAPI environment. | +| value | $r resource object created on ArkTS. | +| drawableDescriptor | Object that receives the pointer to the **ArkUI_DrawableDescriptor** object. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_IsBuiltInGesture() +### OH_ArkUI_GetGestureBindNodeId() ``` -bool OH_ArkUI_IsBuiltInGesture (ArkUI_GestureRecognizer * recognizer) +int32_t OH_ArkUI_GetGestureBindNodeId (ArkUI_GestureRecognizer * recognizer, char * nodeId, int32_t size, int32_t * result ) ``` **Description** -Obtains whether a gesture is a built-in gesture. +Obtains the ID of the component linked to a gesture recognizer. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| recognizer | Pointer to the gesture recognizer. | +| recognizer | Pointer to the gesture recognizer. | +| nodeId | ID of a component. | +| size | Size of the storage area. | +| result | Length of the string to be copied. | **Returns** -true: built-in gestures. false: The gesture is not a built-in gesture. +Returns **0** if the operation is successful. Returns **401** if a parameter error occurs. Returns **180002** if the buffer is not large enough. -### OH_ArkUI_IsGestureRecognizerValid() +### OH_ArkUI_GetGestureEventTargetInfo() ``` -bool OH_ArkUI_IsGestureRecognizerValid (ArkUI_GestureRecognizer * recognizer) +int32_t OH_ArkUI_GetGestureEventTargetInfo (ArkUI_GestureRecognizer * recognizer, ArkUI_GestureEventTargetInfo ** info ) ``` **Description** -Obtains whether a gesture recognizer is valid. +Obtains the information about a gesture event target. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| recognizer | Pointer to the gesture recognizer. | +| recognizer | Pointer to the gesture recognizer. | +| info | Gesture event target information. | **Returns** -true: The gesture recognizer is valid. Returns **false** if the gesture recognizer is invalid. +Returns **0** if the operation is successful. Returns **401** if a parameter error occurs. -### OH_ArkUI_KeyEvent_GetKeyCode() +### OH_ArkUI_GetGestureRecognizerEnabled() ``` -int32_t OH_ArkUI_KeyEvent_GetKeyCode (const ArkUI_UIInputEvent * event) +bool OH_ArkUI_GetGestureRecognizerEnabled (ArkUI_GestureRecognizer * recognizer) ``` **Description** -Obtains the key code from a key event. +Obtains the enabled state of a gesture recognizer. -**Since**: 14 +**Since**: 12 **Parameters** | Name| Description| | -------- | -------- | -| event | Pointer to an **ArkUI_UIInputEvent** object. | +| recognizer | Pointer to the gesture recognizer. | **Returns** -Key code. +**true**: enabled false: disabled -### OH_ArkUI_KeyEvent_GetKeyIntensionCode() +### OH_ArkUI_GetGestureRecognizerState() ``` -ArkUI_KeyIntension OH_ArkUI_KeyEvent_GetKeyIntensionCode (const ArkUI_UIInputEvent * event) +int32_t OH_ArkUI_GetGestureRecognizerState (ArkUI_GestureRecognizer * recognizer, ArkUI_GestureRecognizerState * state ) ``` **Description** -Obtains the intention code associated with a key event. +Obtains the state of a gesture recognizer. -**Since**: 14 +**Since**: 12 **Parameters** | Name| Description| | -------- | -------- | -| event | Pointer to an **ArkUI_UIInputEvent** object. | +| recognizer | Pointer to the gesture recognizer. | +| state | Status of the gesture recognizer. | **Returns** -Returns the intention code associated with the key event. +Returns **0** if the operation is successful. Returns **401** if a parameter error occurs. -### OH_ArkUI_KeyEvent_GetKeySource() +### OH_ArkUI_GetGestureTag() ``` -ArkUI_KeySourceType OH_ArkUI_KeyEvent_GetKeySource (const ArkUI_UIInputEvent * event) +int32_t OH_ArkUI_GetGestureTag (ArkUI_GestureRecognizer * recognizer, char * buffer, int32_t bufferSize, int32_t * result ) ``` **Description** -Obtains the type of input device that triggers a key event. +Obtains the mark of the gesture recognizer. -**Since**: 14 +**Since**: 12 **Parameters** | Name| Description| | -------- | -------- | -| event | Pointer to an **ArkUI_UIInputEvent** object. | +| recognizer | Pointer to the gesture recognizer. | +| buffer | Storage zone | +| bufferSize | Size of the storage area. | +| result | Length of the string to be copied. | **Returns** -Returns the device type. +Returns **0** if the operation is successful. Returns **401** if a parameter error occurs. Returns **180002** if the buffer is not large enough. -### OH_ArkUI_KeyEvent_GetKeyText() +### OH_ArkUI_GetNavDestinationId() ``` -const char* OH_ArkUI_KeyEvent_GetKeyText (const ArkUI_UIInputEvent * event) +ArkUI_ErrorCode OH_ArkUI_GetNavDestinationId (ArkUI_NodeHandle node, char * buffer, int32_t bufferSize, int32_t * writeLength ) ``` **Description** -Obtains the key value from a key event. +Obtains the ID of the **NavDestination** component where the specified node is located. -**Since**: 14 +**Since**: 12 **Parameters** | Name| Description| | -------- | -------- | -| event | Pointer to an **ArkUI_UIInputEvent** object. | +| node | Specified node. | +| buffer | buffer. NavDestinationID is written to this memory area. | +| bufferSize | Pointer to the buffer size. | +| writeLength | When ARKUI_ERROR_CODE_NO_ERROR is returned, this parameter indicates the length of the string written to the buffer. When ARKUI_ERROR_CODE_BUFFER_SIZE_ERROR is returned, this parameter indicates the minimum buffer size that can hold the target. | **Returns** -Key value. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. The ARKUI_ERROR_CODE_GET_INFO_FAILED fails to query information. The possible cause is that the current node is not in Navigation. The buffer size specified by ARKUI_ERROR_CODE_BUFFER_SIZE_ERROR is less than the minimum buffer size that can hold the target. -### OH_ArkUI_KeyEvent_GetType() +### OH_ArkUI_GetNavDestinationIndex() ``` -ArkUI_KeyEventType OH_ArkUI_KeyEvent_GetType (const ArkUI_UIInputEvent * event) +ArkUI_ErrorCode OH_ArkUI_GetNavDestinationIndex (ArkUI_NodeHandle node, int32_t * index ) ``` **Description** -Obtains the type of a key event. +Obtains the index of the **NavDestination** component where the specified node is located in the navigation stack. -**Since**: 14 +**Since**: 12 **Parameters** | Name| Description| | -------- | -------- | -| event | Pointer to an **ArkUI_UIInputEvent** object. | +| node | Specified node. | +| index | Returns the index, starting from 0. | **Returns** -Returns the key event type. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. The ARKUI_ERROR_CODE_GET_INFO_FAILED fails to query information. The possible cause is that the current node is not in Navigation. -### OH_ArkUI_KeyEvent_GetUnicode() +### OH_ArkUI_GetNavDestinationName() ``` -uint32_t OH_ArkUI_KeyEvent_GetUnicode (const ArkUI_UIInputEvent * event) +ArkUI_ErrorCode OH_ArkUI_GetNavDestinationName (ArkUI_NodeHandle node, char * buffer, int32_t bufferSize, int32_t * writeLength ) ``` **Description** -Obtains the Unicode value of a key event. Non-space basic Latin characters in the 0x0021-0x007E range are supported. Characters with a value of 0 are not supported. In the case of key combination, this API returns the Unicode value of the key corresponding to the key event. +Obtains the name of the **NavDestination** component where the specified node is located. -**Since**: 14 +**Since**: 12 **Parameters** | Name| Description| | -------- | -------- | -| event | Pointer to an **ArkUI_UIInputEvent** object. | +| node | Specified node. | +| buffer | Buffer. The queried NavDestination name is written to this memory area. | +| bufferSize | Pointer to the buffer size. | +| writeLength | When ARKUI_ERROR_CODE_NO_ERROR is returned, this parameter indicates the length of the string written to the buffer. When ARKUI_ERROR_CODE_BUFFER_SIZE_ERROR is returned, this parameter indicates the minimum buffer size that can hold the target. | **Returns** -Returns the Unicode value. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. The ARKUI_ERROR_CODE_GET_INFO_FAILED fails to query information. The possible cause is that the current node is not in Navigation. The buffer size specified by ARKUI_ERROR_CODE_BUFFER_SIZE_ERROR is less than the minimum buffer size that can hold the target. -### OH_ArkUI_KeyEvent_SetConsumed() +### OH_ArkUI_GetNavDestinationNameByIndex() ``` -void OH_ArkUI_KeyEvent_SetConsumed (const ArkUI_UIInputEvent * event, bool isConsumed ) +ArkUI_ErrorCode OH_ArkUI_GetNavDestinationNameByIndex (ArkUI_NodeHandle node, int32_t index, char * buffer, int32_t bufferSize, int32_t * writeLength ) ``` **Description** -Sets whether a key event is consumed in the key event callback. +Obtains the page name that matches the specified index in the navigation stack where the specified node is located. The index starts from 0, which indicates the bottom of the stack. -**Since**: 14 +**Since**: 12 **Parameters** | Name| Description| | -------- | -------- | -| event | Pointer to an **ArkUI_UIInputEvent** object. | -| isConsumed | Whether the event is consumed. | +| node | Specified node. | +| index | Index of the queried NavDestination in the stack. | +| buffer | Buffer. The name of the queried page is written to this memory area. | +| bufferSize | Pointer to the buffer size. | +| writeLength | When ARKUI_ERROR_CODE_NO_ERROR is returned, this parameter indicates the length of the string written to the buffer. When ARKUI_ERROR_CODE_BUFFER_SIZE_ERROR is returned, this parameter indicates the minimum buffer size that can hold the target. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. The value of ARKUI_ERROR_CODE_NODE_INDEX_INVALID index is invalid. The ARKUI_ERROR_CODE_GET_INFO_FAILED fails to query information. The possible cause is that the current node is not in Navigation. The buffer size specified by ARKUI_ERROR_CODE_BUFFER_SIZE_ERROR is less than the minimum buffer size that can hold the target. -### OH_ArkUI_KeyEvent_StopPropagation() +### OH_ArkUI_GetNavDestinationParam() ``` -void OH_ArkUI_KeyEvent_StopPropagation (const ArkUI_UIInputEvent * event, bool stopPropagation ) +napi_value OH_ArkUI_GetNavDestinationParam (ArkUI_NodeHandle node) ``` **Description** -Stops the event from bubbling upwards or downwards. +Obtains the parameters of the **NavDestination** component where the specified node is located. -**Since**: 14 +**Since**: 12 **Parameters** | Name| Description| | -------- | -------- | -| event | Pointer to an **ArkUI_UIInputEvent** object. | -| stopPropagation | Whether to stop event propagation. | - - -### OH_ArkUI_KeyEvent_Dispatch() - -``` -void OH_ArkUI_KeyEvent_Dispatch(ArkUI_NodeHandle node, const ArkUI_UIInputEvent* event) -``` -**Description** - -Dispatches a key event to a specific node. +| node | Specified node. | -**Since**: 16 +**Returns** -**Parameters** +Parameter object. -| Name| Description| -| -------- | -------- | -| node | Target node. | -| event | Pointer to an **ArkUI_UIInputEvent** object. | -### OH_ArkUI_KeyframeAnimateOption_Create() +### OH_ArkUI_GetNavDestinationState() ``` -ArkUI_KeyframeAnimateOption* OH_ArkUI_KeyframeAnimateOption_Create (int32_t size) +ArkUI_ErrorCode OH_ArkUI_GetNavDestinationState (ArkUI_NodeHandle node, ArkUI_NavDestinationState * state ) ``` **Description** -Obtains the keyframe animation parameters. +Obtains the state of the **NavDestination** component where the specified node is located. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| size | Number of key frame animation states. | +| node | Specified node. | +| state | The status value of NavDestination is written back to this parameter. | **Returns** -Returns the keyframe animation parameter object; returns **NULL** if the value of **size** is less than 0. +The error code ARKUI_ERROR_CODE_NO_ERROR is returned. The ARKUI_ERROR_CODE_GET_INFO_FAILED fails to query information. The possible cause is that the current node is not in Navigation. -### OH_ArkUI_KeyframeAnimateOption_Dispose() +### OH_ArkUI_GetNavigationId() ``` -void OH_ArkUI_KeyframeAnimateOption_Dispose (ArkUI_KeyframeAnimateOption * option) +ArkUI_ErrorCode OH_ArkUI_GetNavigationId (ArkUI_NodeHandle node, char * buffer, int32_t bufferSize, int32_t * writeLength ) ``` **Description** -Destroys a keyframe animation parameter object. +Obtains the ID of the **Navigation** component where the specified node is located. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Returns the keyframe animation parameter object; | +| node | Specified node. | +| buffer | buffer. The NavigationID is written to this memory area. | +| bufferSize | Pointer to the buffer size. | +| writeLength | When ARKUI_ERROR_CODE_NO_ERROR is returned, this parameter indicates the length of the string written to the buffer. When ARKUI_ERROR_CODE_BUFFER_SIZE_ERROR is returned, this parameter indicates the minimum buffer size that can hold the target. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. The ARKUI_ERROR_CODE_GET_INFO_FAILED fails to query information. The possible cause is that the current node is not in Navigation. The buffer size specified by ARKUI_ERROR_CODE_BUFFER_SIZE_ERROR is less than the minimum buffer size that can hold the target. -### OH_ArkUI_KeyframeAnimateOption_GetCurve() +### OH_ArkUI_GetNavStackLength() ``` -ArkUI_CurveHandle OH_ArkUI_KeyframeAnimateOption_GetCurve (ArkUI_KeyframeAnimateOption * option, int32_t index ) +ArkUI_ErrorCode OH_ArkUI_GetNavStackLength (ArkUI_NodeHandle node, int32_t * length ) ``` **Description** -Obtains the animation curve of a specific state in a keyframe animation. +Obtains the length of the navigation stack where the specified node is located. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Keyframe animation parameters. | -| index | Status index. | +| node | Specified node. | +| length | Length of the stack. The result, if obtained successfully, is written back to this parameter. | **Returns** -Returns the animation curve. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. The ARKUI_ERROR_CODE_GET_INFO_FAILED fails to query information. The possible cause is that the current node is not in Navigation. -### OH_ArkUI_KeyframeAnimateOption_GetDelay() +### OH_ArkUI_GetNodeContentFromNapiValue() ``` -int32_t OH_ArkUI_KeyframeAnimateOption_GetDelay (ArkUI_KeyframeAnimateOption * option) +int32_t OH_ArkUI_GetNodeContentFromNapiValue (napi_env env, napi_value value, ArkUI_NodeContentHandle * content ) ``` **Description** -Obtains the overall delay of a keyframe animation +Obtains a **NodeContent** object on the ArkTS side and maps it to an **ArkUI_NodeContentHandle** object on the native side. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Keyframe animation parameters. | +| env | Pointer to the NAPI environment. | +| value | NodeContent object created on ArkTS. | +| context | ArkUI_NodeContentHandle pointer. | **Returns** -Returns the overall delay. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_KeyframeAnimateOption_GetDuration() +### OH_ArkUI_GetNodeHandleFromNapiValue() ``` -int32_t OH_ArkUI_KeyframeAnimateOption_GetDuration (ArkUI_KeyframeAnimateOption * option, int32_t index ) +int32_t OH_ArkUI_GetNodeHandleFromNapiValue (napi_env env, napi_value frameNode, ArkUI_NodeHandle * handle ) ``` **Description** -Obtains the duration of a specific state in a keyframe animation. +Obtains a **FrameNode** object on the ArkTS side and maps it to an **ArkUI_NodeHandle** object on the native side. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Keyframe animation parameters. | -| index | Status index. | +| env | Pointer to the NAPI environment. | +| frameNode | FrameNode object created on the ArkTS side. | +| handle | **ArkUI_NodeHandle** pointer. | **Returns** -Duration, in milliseconds. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_KeyframeAnimateOption_GetIterations() +### OH_ArkUI_GetPanGestureDirectionMask() ``` -int32_t OH_ArkUI_KeyframeAnimateOption_GetIterations (ArkUI_KeyframeAnimateOption * option) +int32_t OH_ArkUI_GetPanGestureDirectionMask (ArkUI_GestureRecognizer * recognizer, ArkUI_GestureDirectionMask * directionMask ) ``` **Description** -Obtains the number of times that a keyframe animation is played. +Obtains the direction of a pan gesture. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Keyframe animation parameters. | +| recognizer | Pointer to the gesture recognizer. | +| directionMask | Sliding direction of the sliding gesture. | **Returns** -Number of times that the animation is played. +Returns **0** if the operation is successful. Returns **401** if a parameter error occurs. -### OH_ArkUI_KeyframeAnimateOption_RegisterOnEventCallback() +### OH_ArkUI_GetResponseRecognizersFromInterruptInfo() ``` -int32_t OH_ArkUI_KeyframeAnimateOption_RegisterOnEventCallback (ArkUI_KeyframeAnimateOption * option, void * userData, void(*)(void *userData) event, int32_t index ) +int32_t OH_ArkUI_GetResponseRecognizersFromInterruptInfo (const ArkUI_GestureInterruptInfo * event, ArkUI_GestureRecognizerHandleArray * responseChain, int32_t * count ) ``` **Description** -Sets the closure function of the state at the time of the keyframe, that is, the state to be reached at the time of the keyframe. +Obtains information about a gesture response chain. + +**Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Keyframe animation parameters. | -| event | Closure function. | -| userData | Pointer to a custom object. | -| index | Status index. | +| event | Gesture interrupt callback event. | +| responseChain | Gesture recognizer on the response chain component. | +| count | Number of gesture recognizers on the response chain component. | **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +Returns **0** if the operation is successful. Returns **401** if a parameter error occurs. -### OH_ArkUI_KeyframeAnimateOption_RegisterOnFinishCallback() +### OH_ArkUI_GetRouterPageId() ``` -int32_t OH_ArkUI_KeyframeAnimateOption_RegisterOnFinishCallback (ArkUI_KeyframeAnimateOption * option, void * userData, void(*)(void *userData) onFinish ) +ArkUI_ErrorCode OH_ArkUI_GetRouterPageId (ArkUI_NodeHandle node, char * buffer, int32_t bufferSize, int32_t * writeLength ) ``` **Description** -Sets the callback invoked when the keyframe animation playback is complete. This API is called after the keyframe animation has played for the specified number of times. +Obtains the ID of the page where the specified node is located. + +**Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Keyframe animation parameters. | -| userData | Pointer to a custom object. | -| onFinish | Callback used to return the result. | +| node | Specified node. | +| buffer | buffer. Page Id is written to this memory area. | +| bufferSize | Pointer to the buffer size. | +| writeLength | When ARKUI_ERROR_CODE_NO_ERROR is returned, this parameter indicates the length of the string written to the buffer. When ARKUI_ERROR_CODE_BUFFER_SIZE_ERROR is returned, this parameter indicates the minimum buffer size that can hold the target. | **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. The ARKUI_ERROR_CODE_GET_INFO_FAILED fails to query information. The buffer size specified by ARKUI_ERROR_CODE_BUFFER_SIZE_ERROR is less than the minimum buffer size that can hold the target. -### OH_ArkUI_KeyframeAnimateOption_SetCurve() +### OH_ArkUI_GetRouterPageIndex() ``` -int32_t OH_ArkUI_KeyframeAnimateOption_SetCurve (ArkUI_KeyframeAnimateOption * option, ArkUI_CurveHandle value, int32_t index ) +ArkUI_ErrorCode OH_ArkUI_GetRouterPageIndex (ArkUI_NodeHandle node, int32_t * index ) ``` **Description** -Sets the animation curve for a specific keyframe in a keyframe animation. +Obtains the index of the page where the specified node is located in the page stack for routing. + +**Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Keyframe animation parameters. | -| value | Animation curve used by the key frame. Default value: **EASE_IN_OUT**. | -| index | Status index. | - -**NOTE** - -Because the **springMotion**, **responsiveSpringMotion**, and **interpolatingSpring** curves do not have effective duration settings, they are not supported. +| node | Specified node. | +| index | Returns the index, starting from 1. | **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. The ARKUI_ERROR_CODE_GET_INFO_FAILED fails to query information. The possible cause is that the current node is not in Navigation. -### OH_ArkUI_KeyframeAnimateOption_SetDelay() +### OH_ArkUI_GetRouterPageName() ``` -int32_t OH_ArkUI_KeyframeAnimateOption_SetDelay (ArkUI_KeyframeAnimateOption * option, int32_t value ) +ArkUI_ErrorCode OH_ArkUI_GetRouterPageName (ArkUI_NodeHandle node, char * buffer, int32_t bufferSize, int32_t * writeLength ) ``` **Description** -Sets the overall delay of a keyframe animation, in milliseconds. By default, the keyframe animation is played without delay. +Obtains the name of the page where the specified node is located. + +**Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Keyframe animation parameters. | -| value | Delay time, in milliseconds. | +| node | Specified node. | +| buffer | Buffer. The page name is written to this memory area. | +| bufferSize | Pointer to the buffer size. | +| writeLength | When ARKUI_ERROR_CODE_NO_ERROR is returned, this parameter indicates the length of the string written to the buffer. When ARKUI_ERROR_CODE_BUFFER_SIZE_ERROR is returned, this parameter indicates the minimum buffer size that can hold the target. | **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. The ARKUI_ERROR_CODE_GET_INFO_FAILED fails to query information. The buffer size specified by ARKUI_ERROR_CODE_BUFFER_SIZE_ERROR is less than the minimum buffer size that can hold the target. -### OH_ArkUI_KeyframeAnimateOption_SetDuration() +### OH_ArkUI_GetRouterPagePath() ``` -int32_t OH_ArkUI_KeyframeAnimateOption_SetDuration (ArkUI_KeyframeAnimateOption * option, int32_t value, int32_t index ) +ArkUI_ErrorCode OH_ArkUI_GetRouterPagePath (ArkUI_NodeHandle node, char * buffer, int32_t bufferSize, int32_t * writeLength ) ``` **Description** -Sets the duration of a keyframe animation, in milliseconds. +Obtains the path to the page where the specified node is located. + +**Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Keyframe animation parameters. | -| value | Duration, in milliseconds. | -| index | Status index. | +| node | Specified node. | +| buffer | buffer. Page Path is written to this memory area. | +| bufferSize | Pointer to the buffer size. | +| writeLength | When ARKUI_ERROR_CODE_NO_ERROR is returned, this parameter indicates the length of the string written to the buffer. When ARKUI_ERROR_CODE_BUFFER_SIZE_ERROR is returned, this parameter indicates the minimum buffer size that can hold the target. | **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. The ARKUI_ERROR_CODE_GET_INFO_FAILED fails to query information. The buffer size specified by ARKUI_ERROR_CODE_BUFFER_SIZE_ERROR is less than the minimum buffer size that can hold the target. -### OH_ArkUI_KeyframeAnimateOption_SetIterations() +### OH_ArkUI_GetRouterPageState() ``` -int32_t OH_ArkUI_KeyframeAnimateOption_SetIterations (ArkUI_KeyframeAnimateOption * option, int32_t value ) +ArkUI_ErrorCode OH_ArkUI_GetRouterPageState (ArkUI_NodeHandle node, ArkUI_RouterPageState * state ) ``` **Description** -Sets the number of times that the keyframe animation is played. By default, the animation is played once. The value **-1** indicates that the animation is played for an unlimited number of times. The value **0** indicates that there is no animation. +Obtains the state of the page where the specified node is located. + +**Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Keyframe animation parameters. | -| value | Number of times that the animation is played. | +| node | Specified node. | +| state | The status value of Router Page is written back to this parameter. | **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +The error code ARKUI_ERROR_CODE_NO_ERROR is returned. The ARKUI_ERROR_CODE_GET_INFO_FAILED fails to query information. -### OH_ArkUI_LayoutConstraint_Copy() +### OH_ArkUI_GuidelineOption_Create() ``` -ArkUI_LayoutConstraint* OH_ArkUI_LayoutConstraint_Copy (const ArkUI_LayoutConstraint * Constraint) +ArkUI_GuidelineOption* OH_ArkUI_GuidelineOption_Create (int32_t size) ``` **Description** -Constraint size deep copy. +Creates a guideline configuration for this **RelativeContainer**. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| Constraint | Size constraint. | +| size | Number of guidelines. | **Returns** -Pointer to the new constraint size. +Returns the guideline configuration. -### OH_ArkUI_LayoutConstraint_Create() +### OH_ArkUI_GuidelineOption_Dispose() ``` -ArkUI_LayoutConstraint* OH_ArkUI_LayoutConstraint_Create () +void OH_ArkUI_GuidelineOption_Dispose (ArkUI_GuidelineOption * guideline) ``` **Description** -Create a constraint size. +Destroys auxiliary line information. **Since**: 12 +**Parameters** -### OH_ArkUI_LayoutConstraint_Dispose() +| Name| Description| +| -------- | -------- | +| guideline | Pointer to a guideline configuration. | + + +### OH_ArkUI_GuidelineOption_GetDirection() ``` -void* OH_ArkUI_LayoutConstraint_Dispose (ArkUI_LayoutConstraint * Constraint) +ArkUI_Axis OH_ArkUI_GuidelineOption_GetDirection (ArkUI_GuidelineOption * guideline, int32_t index ) ``` **Description** -Pointer to the size of the destruction constraint. +Obtains the direction of a guideline. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| Constraint | Size constraint. | +| guideline | Pointer to a guideline configuration. | +| index | Index of the barrier. | +**Returns** -### OH_ArkUI_LayoutConstraint_GetMaxHeight() +Returns the direction of the guideline. + + +### OH_ArkUI_GuidelineOption_GetId() ``` -int32_t OH_ArkUI_LayoutConstraint_GetMaxHeight (const ArkUI_LayoutConstraint * Constraint) +const char* OH_ArkUI_GuidelineOption_GetId (ArkUI_GuidelineOption * guideline, int32_t index ) ``` **Description** -Obtains the maximum height for a size constraint, in px. +Obtains the ID of a guideline. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| Constraint | Size constraint. | +| guideline | Pointer to a guideline configuration. | +| index | Index of the barrier. | **Returns** -Maximum height. +Returns the ID of the guideline. -### OH_ArkUI_LayoutConstraint_GetMaxWidth() +### OH_ArkUI_GuidelineOption_GetPositionEnd() ``` -int32_t OH_ArkUI_LayoutConstraint_GetMaxWidth (const ArkUI_LayoutConstraint * Constraint) +float OH_ArkUI_GuidelineOption_GetPositionEnd (ArkUI_GuidelineOption * guideline, int32_t index ) ``` **Description** -Obtains the maximum width for a size constraint, in px. +Obtains the distance between a guideline and the right or bottom of the container. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| Constraint | Size constraint. | +| guideline | Pointer to a guideline configuration. | +| index | Index of the barrier. | **Returns** -Maximum width. +Distance between the guideline and the right or bottom of the container. -### OH_ArkUI_LayoutConstraint_GetMinHeight() +### OH_ArkUI_GuidelineOption_GetPositionStart() ``` -int32_t OH_ArkUI_LayoutConstraint_GetMinHeight (const ArkUI_LayoutConstraint * Constraint) +float OH_ArkUI_GuidelineOption_GetPositionStart (ArkUI_GuidelineOption * guideline, int32_t index ) ``` **Description** -Obtains the minimum height for a size constraint, in px. +Obtains the distance between a guideline and the left or top of the container. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| Constraint | Size constraint. | +| guideline | Pointer to a guideline configuration. | +| index | Index of the barrier. | **Returns** -Minimum Height +Distance between the guideline and the left or top of the container. -### OH_ArkUI_LayoutConstraint_GetMinWidth() +### OH_ArkUI_GuidelineOption_SetDirection() ``` -int32_t OH_ArkUI_LayoutConstraint_GetMinWidth (const ArkUI_LayoutConstraint * Constraint) +void OH_ArkUI_GuidelineOption_SetDirection (ArkUI_GuidelineOption * guideline, ArkUI_Axis value, int32_t index ) ``` **Description** -Obtains the minimum width for a size constraint, in px. +Sets the direction of a guideline. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| Constraint | Size constraint. | - -**Returns** - -Minimum Width +| guideline | Pointer to a guideline configuration. | +| value | Direction. | +| index | Index of the guideline. | -### OH_ArkUI_LayoutConstraint_GetPercentReferenceHeight() +### OH_ArkUI_GuidelineOption_SetId() ``` -int32_t OH_ArkUI_LayoutConstraint_GetPercentReferenceHeight (const ArkUI_LayoutConstraint * Constraint) +void OH_ArkUI_GuidelineOption_SetId (ArkUI_GuidelineOption * guideline, const char * value, int32_t index ) ``` **Description** -Obtains the height percentage reference for a size constraint, in px. +Sets the ID of a guideline. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| Constraint | Size constraint. | - -**Returns** - -Height percentage benchmark. +| guideline | Pointer to a guideline configuration. | +| value | ID of the barrier, which must be unique and cannot be the same as the name of any component in the container. | +| index | Index of the guideline. | -### OH_ArkUI_LayoutConstraint_GetPercentReferenceWidth() +### OH_ArkUI_GuidelineOption_SetPositionEnd() ``` -int32_t OH_ArkUI_LayoutConstraint_GetPercentReferenceWidth (const ArkUI_LayoutConstraint * Constraint) +void OH_ArkUI_GuidelineOption_SetPositionEnd (ArkUI_GuidelineOption * guideline, float value, int32_t index ) ``` **Description** -Obtains the width percentage reference for a size constraint, in px. +Sets the distance between a guideline and the right or bottom of the container. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| Constraint | Size constraint. | - -**Returns** - -Width percentage reference. +| guideline | Pointer to a guideline configuration. | +| value | Distance between the guideline and the right or bottom of the container. | +| index | Index of the guideline. | -### OH_ArkUI_LayoutConstraint_SetMaxHeight() +### OH_ArkUI_GuidelineOption_SetPositionStart() ``` -void OH_ArkUI_LayoutConstraint_SetMaxHeight (ArkUI_LayoutConstraint * Constraint, int32_t value ) +void OH_ArkUI_GuidelineOption_SetPositionStart (ArkUI_GuidelineOption * guideline, float value, int32_t index ) ``` **Description** -Sets the maximum height. +Sets the distance between a guideline and the left or top of the container. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| Constraint | Size constraint. | -| value | Maximum height, in pixels. | +| guideline | Pointer to a guideline configuration. | +| value | Distance between the guideline and the left or top of the container. | +| index | Index of the guideline. | -### OH_ArkUI_LayoutConstraint_SetMaxWidth() +### OH_ArkUI_ImageAnimatorFrameInfo_CreateFromDrawableDescriptor() ``` -void OH_ArkUI_LayoutConstraint_SetMaxWidth (ArkUI_LayoutConstraint * Constraint, int32_t value ) +ArkUI_ImageAnimatorFrameInfo* OH_ArkUI_ImageAnimatorFrameInfo_CreateFromDrawableDescriptor (ArkUI_DrawableDescriptor * drawable) ``` **Description** -Sets the maximum width. +Creates an image frame information object based on a **DrawableDescriptor** object, with the image format being Resource or PixelMap. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| Constraint | Size constraint. | -| value | Maximum width, in pixels. | +| drawable | Pointer to an **ArkUI_DrawableDescriptor** object created using Resource or PixelMap. | +**Returns** + +Returns the pointer to the created frame image object. -### OH_ArkUI_LayoutConstraint_SetMinHeight() + +### OH_ArkUI_ImageAnimatorFrameInfo_CreateFromString() ``` -void OH_ArkUI_LayoutConstraint_SetMinHeight (ArkUI_LayoutConstraint * Constraint, int32_t value ) +ArkUI_ImageAnimatorFrameInfo* OH_ArkUI_ImageAnimatorFrameInfo_CreateFromString (char * src) ``` **Description** -Sets the minimum height. +Creates an image frame information object based on an image path, with the image format being SVG, PNG, or JPG. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| Constraint | Size constraint. | -| value | Minimum height, in pixels. | +| src | Image path. | +**Returns** + +Returns the pointer to the created frame image object. -### OH_ArkUI_LayoutConstraint_SetMinWidth() + +### OH_ArkUI_ImageAnimatorFrameInfo_Dispose() ``` -void OH_ArkUI_LayoutConstraint_SetMinWidth (ArkUI_LayoutConstraint * Constraint, int32_t value ) +void OH_ArkUI_ImageAnimatorFrameInfo_Dispose (ArkUI_ImageAnimatorFrameInfo * imageInfo) ``` **Description** -Sets the minimum width. +Disposes of the pointer to an image frame information object. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| Constraint | Size constraint. | -| value | Minimum width, in pixels. | +| imageInfo | Pointer to the frame image object. | -### OH_ArkUI_LayoutConstraint_SetPercentReferenceHeight() +### OH_ArkUI_ImageAnimatorFrameInfo_GetDuration() ``` -void OH_ArkUI_LayoutConstraint_SetPercentReferenceHeight (ArkUI_LayoutConstraint * Constraint, int32_t value ) +int32_t OH_ArkUI_ImageAnimatorFrameInfo_GetDuration (ArkUI_ImageAnimatorFrameInfo * imageInfo) ``` **Description** -Sets the height percentage reference. +Obtains the playback duration of an image. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| Constraint | Size constraint. | -| value | Height percentage base, in px. | +| imageInfo | Pointer to the frame image object. | +**Returns** + +Returns the playback duration of the image, in milliseconds. If **imageInfo** is a null pointer, **0** is returned. -### OH_ArkUI_LayoutConstraint_SetPercentReferenceWidth() + +### OH_ArkUI_ImageAnimatorFrameInfo_GetHeight() ``` -void OH_ArkUI_LayoutConstraint_SetPercentReferenceWidth (ArkUI_LayoutConstraint * Constraint, int32_t value ) +int32_t OH_ArkUI_ImageAnimatorFrameInfo_GetHeight (ArkUI_ImageAnimatorFrameInfo * imageInfo) ``` **Description** -Sets the width percentage reference. +Obtains the image height. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| Constraint | Size constraint. | -| value | Width percentage benchmark, in px. | +| imageInfo | Pointer to the frame image object. | +**Returns** + +Returns the image height, in PX. If **imageInfo** is a null pointer, **0** is returned. -### OH_ArkUI_List_CloseAllSwipeActions() + +### OH_ArkUI_ImageAnimatorFrameInfo_GetLeft() ``` -int32_t OH_ArkUI_List_CloseAllSwipeActions (ArkUI_NodeHandle node, void * userData, void(*)(void *userData) onFinish ) +int32_t OH_ArkUI_ImageAnimatorFrameInfo_GetLeft (ArkUI_ImageAnimatorFrameInfo * imageInfo) ``` **Description** -Collapse the expanded ListItem. +Obtains the horizontal coordinate of an image relative to the upper left corner of the component. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | Node object for which an event needs to be registered. | -| userData | Custom event parameter, which is passed in the callback when the event is triggered. | -| onFinish | Callback triggered after the collapse animation is complete. | +| imageInfo | Pointer to the frame image object. | **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. Returns **ARKUI_ERROR_CODE_ATTRIBUTE_OR_EVENT_NOT_SUPPORTED** if the event is not supported. +Returns the horizontal coordinate of the image relative to the upper left corner of the component, in px. If **imageInfo** is a null pointer, **0** is returned. -### OH_ArkUI_ListChildrenMainSizeOption_Create() +### OH_ArkUI_ImageAnimatorFrameInfo_GetTop() ``` -ArkUI_ListChildrenMainSize* OH_ArkUI_ListChildrenMainSizeOption_Create () +int32_t OH_ArkUI_ImageAnimatorFrameInfo_GetTop (ArkUI_ImageAnimatorFrameInfo * imageInfo) ``` **Description** -Creates a **ListChildrenMainSize** instance. +Obtains the vertical coordinate of an image relative to the upper left corner of the component. **Since**: 12 +**Parameters** + +| Name| Description| +| -------- | -------- | +| imageInfo | Pointer to the frame image object. | + **Returns** -Returns the created **ListChildrenMainSize** instance. +Returns the vertical coordinate of the image relative to the upper left corner of the component, in px. If **imageInfo** is a null pointer, **0** is returned. -### OH_ArkUI_ListChildrenMainSizeOption_Dispose() +### OH_ArkUI_ImageAnimatorFrameInfo_GetWidth() ``` -void OH_ArkUI_ListChildrenMainSizeOption_Dispose (ArkUI_ListChildrenMainSize * option) +int32_t OH_ArkUI_ImageAnimatorFrameInfo_GetWidth (ArkUI_ImageAnimatorFrameInfo * imageInfo) ``` **Description** -Destroys a ListChildrenMainSize instance. +Obtains the image width. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | ListChildrenMainSize instance to be destroyed. | +| imageInfo | Pointer to the frame image object. | + +**Returns** + +Returns the image width, in PX. If **imageInfo** is a null pointer, **0** is returned. -### OH_ArkUI_ListChildrenMainSizeOption_GetDefaultMainSize() +### OH_ArkUI_ImageAnimatorFrameInfo_SetDuration() ``` -float OH_ArkUI_ListChildrenMainSizeOption_GetDefaultMainSize (ArkUI_ListChildrenMainSize * option) +void OH_ArkUI_ImageAnimatorFrameInfo_SetDuration (ArkUI_ImageAnimatorFrameInfo * imageInfo, int32_t duration ) ``` **Description** -Obtains the default size in a **ListChildrenMainSize** instance. +Sets the playback duration of an image. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | **ListChildrenMainSize** instance. | - -**Returns** - -Returns the default size, in vp. The default value is **0**. If **option** is a null pointer, **-1** is returned. +| imageInfo | Pointer to the frame image object. | +| duration | Playback duration of an image, in milliseconds. | -### OH_ArkUI_ListChildrenMainSizeOption_GetMainSize() +### OH_ArkUI_ImageAnimatorFrameInfo_SetHeight() ``` -float OH_ArkUI_ListChildrenMainSizeOption_GetMainSize (ArkUI_ListChildrenMainSize * option, int32_t index ) +void OH_ArkUI_ImageAnimatorFrameInfo_SetHeight (ArkUI_ImageAnimatorFrameInfo * imageInfo, int32_t height ) ``` **Description** -Obtains the value of the ChildrenMainSizeOption array of the List component. +Sets the image height. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | **ListChildrenMainSize** instance. | -| index | Subscript position of the value to be obtained. | - -**Returns** - -Value of the specific position of the array. If a parameter error occurs, **-1** is returned. +| imageInfo | Pointer to the frame image object. | +| height | Image height, in px. | -### OH_ArkUI_ListChildrenMainSizeOption_Resize() +### OH_ArkUI_ImageAnimatorFrameInfo_SetLeft() ``` -void OH_ArkUI_ListChildrenMainSizeOption_Resize (ArkUI_ListChildrenMainSize * option, int32_t totalSize ) +void OH_ArkUI_ImageAnimatorFrameInfo_SetLeft (ArkUI_ImageAnimatorFrameInfo * imageInfo, int32_t left ) ``` **Description** -Resets the array size of ChildrenMainSizeOption of the List component. +Sets the horizontal coordinate of an image relative to the upper left corner of the component. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | **ListChildrenMainSize** instance. | -| totalSize | Array size. | +| imageInfo | Pointer to the frame image object. | +| left | Horizontal coordinate of the image relative to the upper left corner of the component, in px. | -### OH_ArkUI_ListChildrenMainSizeOption_SetDefaultMainSize() +### OH_ArkUI_ImageAnimatorFrameInfo_SetTop() ``` -int32_t OH_ArkUI_ListChildrenMainSizeOption_SetDefaultMainSize (ArkUI_ListChildrenMainSize * option, float defaultMainSize ) +void OH_ArkUI_ImageAnimatorFrameInfo_SetTop (ArkUI_ImageAnimatorFrameInfo * imageInfo, int32_t top ) ``` **Description** -Sets the default size in a **ListChildrenMainSize** instance. +Sets the vertical coordinate of an image relative to the upper left corner of the component. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | **ListChildrenMainSize** instance. | -| defaultMainSize | Default size of a list item in a list. The unit is vp. | - -**Returns** - -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +| imageInfo | Pointer to the frame image object. | +| top | Vertical coordinate of the image relative to the upper left corner of the component, in px. | -### OH_ArkUI_ListChildrenMainSizeOption_Splice() +### OH_ArkUI_ImageAnimatorFrameInfo_SetWidth() ``` -int32_t OH_ArkUI_ListChildrenMainSizeOption_Splice (ArkUI_ListChildrenMainSize * option, int32_t index, int32_t deleteCount, int32_t addCount ) +void OH_ArkUI_ImageAnimatorFrameInfo_SetWidth (ArkUI_ImageAnimatorFrameInfo * imageInfo, int32_t width ) ``` **Description** -The size of the ChildrenMainSizeOption array of the List component is adjusted. +Sets the image width. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | **ListChildrenMainSize** instance. | -| index | Start position of the array whose MainSize is to be modified. | -| deleteCount | Number of MainSize arrays to be deleted starting from index. | -| addCount | Number of MainSize arrays to be added starting from index. | - -**Returns** - -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +| imageInfo | Pointer to the frame image object. | +| width | Image width, in px. | -### OH_ArkUI_ListChildrenMainSizeOption_UpdateSize() +### OH_ArkUI_IsBuiltInGesture() ``` -int32_t OH_ArkUI_ListChildrenMainSizeOption_UpdateSize (ArkUI_ListChildrenMainSize * option, int32_t index, float mainSize ) +bool OH_ArkUI_IsBuiltInGesture (ArkUI_GestureRecognizer * recognizer) ``` **Description** -Updates the values in a **ChildrenMainSizeOption** array of a List component. +Obtains whether a gesture is a built-in gesture. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | **ListChildrenMainSize** instance. | -| index | Index at which to start changing the values in the array. | -| mainSize | New size value to set at the specified index. | +| recognizer | Pointer to the gesture recognizer. | **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +true: built-in gestures. false: The gesture is not a built-in gesture. -### OH_ArkUI_ListItemSwipeActionItem_Create() +### OH_ArkUI_IsGestureRecognizerValid() ``` -ArkUI_ListItemSwipeActionItem* OH_ArkUI_ListItemSwipeActionItem_Create () +bool OH_ArkUI_IsGestureRecognizerValid (ArkUI_GestureRecognizer * recognizer) ``` **Description** -Creates a **ListItemSwipeActionItem** instance. +Obtains whether a gesture recognizer is valid. **Since**: 12 +**Parameters** + +| Name| Description| +| -------- | -------- | +| recognizer | Pointer to the gesture recognizer. | + **Returns** -Returns the created **ListItemSwipeActionItem** instance. +true: The gesture recognizer is valid. Returns **false** if the gesture recognizer is invalid. -### OH_ArkUI_ListItemSwipeActionItem_Dispose() +### OH_ArkUI_KeyEvent_GetKeyCode() ``` -void OH_ArkUI_ListItemSwipeActionItem_Dispose (ArkUI_ListItemSwipeActionItem * item) +int32_t OH_ArkUI_KeyEvent_GetKeyCode (const ArkUI_UIInputEvent * event) ``` **Description** -Disposes of a **ListItemSwipeActionItem** instance. +Obtains the key code from a key event. -**Since**: 12 +**Since**: 14 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| item | **ListItemSwipeActionItem** instance to dispose of. | +| event | Pointer to an **ArkUI_UIInputEvent** object. | + +**Returns** + +Key code. -### OH_ArkUI_ListItemSwipeActionItem_GetActionAreaDistance() +### OH_ArkUI_KeyEvent_GetKeyIntensionCode() ``` -float OH_ArkUI_ListItemSwipeActionItem_GetActionAreaDistance (ArkUI_ListItemSwipeActionItem * item) +ArkUI_KeyIntension OH_ArkUI_KeyEvent_GetKeyIntensionCode (const ArkUI_UIInputEvent * event) ``` **Description** -Obtains the swipe distance threshold for deleting the list item. +Obtains the intention code associated with a key event. -**Since**: 12 +**Since**: 14 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| item | Target **ListItemSwipeActionItem** instance. | +| event | Pointer to an **ArkUI_UIInputEvent** object. | **Returns** -Returns the swipe distance threshold for deleting the list item. Return **0** if an error occurs. +Returns the intention code associated with the key event. -### OH_ArkUI_ListItemSwipeActionItem_SetActionAreaDistance() +### OH_ArkUI_KeyEvent_GetKeySource() ``` -void OH_ArkUI_ListItemSwipeActionItem_SetActionAreaDistance (ArkUI_ListItemSwipeActionItem * item, float distance ) +ArkUI_KeySourceType OH_ArkUI_KeyEvent_GetKeySource (const ArkUI_UIInputEvent * event) ``` **Description** -Swipe distance threshold for deleting the list item. +Obtains the type of input device that triggers a key event. -**Since**: 12 +**Since**: 14 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| item | Target **ListItemSwipeActionItem** instance. | -| distance | Returns the swipe distance threshold for deleting the list item. | +| event | Pointer to an **ArkUI_UIInputEvent** object. | + +**Returns** + +Returns the device type. + + +### OH_ArkUI_KeyEvent_GetKeyText() + +``` +const char* OH_ArkUI_KeyEvent_GetKeyText (const ArkUI_UIInputEvent * event) +``` +**Description** + +Obtains the key value from a key event. + +**Since**: 14 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| event | Pointer to an **ArkUI_UIInputEvent** object. | + +**Returns** + +Key value. + + +### OH_ArkUI_KeyEvent_GetType() + +``` +ArkUI_KeyEventType OH_ArkUI_KeyEvent_GetType (const ArkUI_UIInputEvent * event) +``` +**Description** + +Obtains the type of a key event. + +**Since**: 14 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| event | Pointer to an **ArkUI_UIInputEvent** object. | + +**Returns** + +Returns the key event type. + + +### OH_ArkUI_KeyEvent_GetUnicode() + +``` +uint32_t OH_ArkUI_KeyEvent_GetUnicode (const ArkUI_UIInputEvent * event) +``` +**Description** + +Obtains the Unicode value of a key event. Non-space basic Latin characters in the 0x0021-0x007E range are supported. Characters with a value of 0 are not supported. In the case of key combination, this API returns the Unicode value of the key corresponding to the key event. + +**Since**: 14 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| event | Pointer to an **ArkUI_UIInputEvent** object. | + +**Returns** + +Returns the Unicode value. + + +### OH_ArkUI_KeyEvent_SetConsumed() + +``` +void OH_ArkUI_KeyEvent_SetConsumed (const ArkUI_UIInputEvent * event, bool isConsumed ) +``` +**Description** + +Sets whether a key event is consumed in the key event callback. + +**Since**: 14 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| event | Pointer to an **ArkUI_UIInputEvent** object. | +| isConsumed | Whether the event is consumed. | + + +### OH_ArkUI_KeyEvent_StopPropagation() + +``` +void OH_ArkUI_KeyEvent_StopPropagation (const ArkUI_UIInputEvent * event, bool stopPropagation ) +``` +**Description** + +Stops the event from bubbling upwards or downwards. + +**Since**: 14 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| event | Pointer to an **ArkUI_UIInputEvent** object. | +| stopPropagation | Whether to stop event propagation. | + + +### OH_ArkUI_KeyEvent_Dispatch() + +``` +void OH_ArkUI_KeyEvent_Dispatch(ArkUI_NodeHandle node, const ArkUI_UIInputEvent* event) +``` +**Description** + +Dispatches a key event to a specific node. + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| node | Node object for which an event needs to be registered. | +| event | Pointer to an **ArkUI_UIInputEvent** object. | + +### OH_ArkUI_KeyframeAnimateOption_Create() + +``` +ArkUI_KeyframeAnimateOption* OH_ArkUI_KeyframeAnimateOption_Create (int32_t size) +``` +**Description** + +Obtains the keyframe animation parameters. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| size | Number of key frame animation states. | + +**Returns** + +Returns the keyframe animation parameter object; returns **NULL** if the value of **size** is less than 0. + + +### OH_ArkUI_KeyframeAnimateOption_Dispose() + +``` +void OH_ArkUI_KeyframeAnimateOption_Dispose (ArkUI_KeyframeAnimateOption * option) +``` +**Description** + +Destroys a keyframe animation parameter object. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| option | Returns the keyframe animation parameter object; | + + +### OH_ArkUI_KeyframeAnimateOption_GetCurve() + +``` +ArkUI_CurveHandle OH_ArkUI_KeyframeAnimateOption_GetCurve (ArkUI_KeyframeAnimateOption * option, int32_t index ) +``` +**Description** + +Obtains the animation curve of a specific state in a keyframe animation. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| option | Keyframe animation parameters. | +| index | Status index. | + +**Returns** + +Returns the animation curve. + + +### OH_ArkUI_KeyframeAnimateOption_GetDelay() + +``` +int32_t OH_ArkUI_KeyframeAnimateOption_GetDelay (ArkUI_KeyframeAnimateOption * option) +``` +**Description** + +Obtains the overall delay of a keyframe animation + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| option | Keyframe animation parameters. | + +**Returns** + +Returns the overall delay. + + +### OH_ArkUI_KeyframeAnimateOption_GetDuration() + +``` +int32_t OH_ArkUI_KeyframeAnimateOption_GetDuration (ArkUI_KeyframeAnimateOption * option, int32_t index ) +``` +**Description** + +Obtains the duration of a specific state in a keyframe animation. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| option | Keyframe animation parameters. | +| index | Status index. | + +**Returns** + +Duration, in milliseconds. + + +### OH_ArkUI_KeyframeAnimateOption_GetIterations() + +``` +int32_t OH_ArkUI_KeyframeAnimateOption_GetIterations (ArkUI_KeyframeAnimateOption * option) +``` +**Description** + +Obtains the number of times that a keyframe animation is played. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| option | Keyframe animation parameters. | + +**Returns** + +Returns the number of times that the animation is played. + +### OH_ArkUI_KeyframeAnimateOption_GetExpectedFrameRate() + +``` +ArkUI_ExpectedFrameRateRange* OH_ArkUI_KeyframeAnimateOption_GetExpectedFrameRate(ArkUI_KeyframeAnimateOption* option) +``` +**Description** + +Obtains the expected frame rate from keyframe animation parameters. + +**Since**: 16 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| option | Keyframe animation parameters. | + +**Returns** + +Returns the expected frame rate obtained. + + +### OH_ArkUI_KeyframeAnimateOption_RegisterOnEventCallback() + +``` +int32_t OH_ArkUI_KeyframeAnimateOption_RegisterOnEventCallback (ArkUI_KeyframeAnimateOption * option, void * userData, void(*)(void *userData) event, int32_t index ) +``` +**Description** + +Sets the closure function of the state at the time of the keyframe, that is, the state to be reached at the time of the keyframe. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| option | Keyframe animation parameters. | +| event | Closure function. | +| userData | Pointer to a custom object. | +| index | Status index. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + + +### OH_ArkUI_KeyframeAnimateOption_RegisterOnFinishCallback() + +``` +int32_t OH_ArkUI_KeyframeAnimateOption_RegisterOnFinishCallback (ArkUI_KeyframeAnimateOption * option, void * userData, void(*)(void *userData) onFinish ) +``` +**Description** + +Sets the callback invoked when the keyframe animation playback is complete. This API is called after the keyframe animation has played for the specified number of times. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| option | Keyframe animation parameters. | +| userData | Pointer to a custom object. | +| onFinish | Callback used to return the result. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + + +### OH_ArkUI_KeyframeAnimateOption_SetCurve() + +``` +int32_t OH_ArkUI_KeyframeAnimateOption_SetCurve (ArkUI_KeyframeAnimateOption * option, ArkUI_CurveHandle value, int32_t index ) +``` +**Description** + +Sets the animation curve for a specific keyframe in a keyframe animation. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| option | Keyframe animation parameters. | +| value | Animation curve used by the key frame. Default value: **EASE_IN_OUT**. | +| index | Status index. | + +**NOTE** + +Because the **springMotion**, **responsiveSpringMotion**, and **interpolatingSpring** curves do not have effective duration settings, they are not supported. + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + + +### OH_ArkUI_KeyframeAnimateOption_SetDelay() + +``` +int32_t OH_ArkUI_KeyframeAnimateOption_SetDelay (ArkUI_KeyframeAnimateOption * option, int32_t value ) +``` +**Description** + +Sets the overall delay of a keyframe animation, in milliseconds. By default, the keyframe animation is played without delay. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| option | Keyframe animation parameters. | +| value | Delay time, in milliseconds. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + + +### OH_ArkUI_KeyframeAnimateOption_SetDuration() + +``` +int32_t OH_ArkUI_KeyframeAnimateOption_SetDuration (ArkUI_KeyframeAnimateOption * option, int32_t value, int32_t index ) +``` +**Description** + +Sets the duration of a keyframe animation, in milliseconds. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| option | Keyframe animation parameters. | +| value | Duration, in milliseconds. | +| index | Status index. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + + +### OH_ArkUI_KeyframeAnimateOption_SetIterations() + +``` +int32_t OH_ArkUI_KeyframeAnimateOption_SetIterations (ArkUI_KeyframeAnimateOption * option, int32_t value ) +``` +**Description** + +Sets the number of times that the keyframe animation is played. By default, the animation is played once. The value **-1** indicates that the animation is played for an unlimited number of times. The value **0** indicates that there is no animation. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| option | Keyframe animation parameters. | +| value | Number of times that the animation is played. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + +### OH_ArkUI_KeyframeAnimateOption_SetExpectedFrameRate() + +``` +int32_t OH_ArkUI_KeyframeAnimateOption_SetExpectedFrameRate( + ArkUI_KeyframeAnimateOption* option, ArkUI_ExpectedFrameRateRange* frameRate) +``` +**Description** + +Sets the expected frame rate for a keyframe animation. + +**Parameters** + +| Name| Description| +| -------- | -------- | +| option | Keyframe animation parameters. | +| frameRate | Expected frame rate to set. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. +Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + + +### OH_ArkUI_LayoutConstraint_Copy() + +``` +ArkUI_LayoutConstraint* OH_ArkUI_LayoutConstraint_Copy (const ArkUI_LayoutConstraint * Constraint) +``` +**Description** + +Constraint size deep copy. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| Constraint | Size constraint. | + +**Returns** + +Pointer to the new constraint size. + + +### OH_ArkUI_LayoutConstraint_Create() + +``` +ArkUI_LayoutConstraint* OH_ArkUI_LayoutConstraint_Create () +``` +**Description** + +Create a constraint size. + +**Since**: 12 + + +### OH_ArkUI_LayoutConstraint_Dispose() + +``` +void* OH_ArkUI_LayoutConstraint_Dispose (ArkUI_LayoutConstraint * Constraint) +``` +**Description** + +Pointer to the size of the destruction constraint. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| Constraint | Size constraint. | + + +### OH_ArkUI_LayoutConstraint_GetMaxHeight() + +``` +int32_t OH_ArkUI_LayoutConstraint_GetMaxHeight (const ArkUI_LayoutConstraint * Constraint) +``` +**Description** + +Obtains the maximum height for a size constraint, in px. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| Constraint | Size constraint. | + +**Returns** + +Maximum height. + + +### OH_ArkUI_LayoutConstraint_GetMaxWidth() + +``` +int32_t OH_ArkUI_LayoutConstraint_GetMaxWidth (const ArkUI_LayoutConstraint * Constraint) +``` +**Description** + +Obtains the maximum width for a size constraint, in px. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| Constraint | Size constraint. | + +**Returns** + +Maximum width. + + +### OH_ArkUI_LayoutConstraint_GetMinHeight() + +``` +int32_t OH_ArkUI_LayoutConstraint_GetMinHeight (const ArkUI_LayoutConstraint * Constraint) +``` +**Description** + +Obtains the minimum height for a size constraint, in px. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| Constraint | Size constraint. | + +**Returns** + +Minimum Height + + +### OH_ArkUI_LayoutConstraint_GetMinWidth() + +``` +int32_t OH_ArkUI_LayoutConstraint_GetMinWidth (const ArkUI_LayoutConstraint * Constraint) +``` +**Description** + +Obtains the minimum width for a size constraint, in px. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| Constraint | Size constraint. | + +**Returns** + +Minimum Width + + +### OH_ArkUI_LayoutConstraint_GetPercentReferenceHeight() + +``` +int32_t OH_ArkUI_LayoutConstraint_GetPercentReferenceHeight (const ArkUI_LayoutConstraint * Constraint) +``` +**Description** + +Obtains the height percentage reference for a size constraint, in px. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| Constraint | Size constraint. | + +**Returns** + +Height percentage benchmark. + + +### OH_ArkUI_LayoutConstraint_GetPercentReferenceWidth() + +``` +int32_t OH_ArkUI_LayoutConstraint_GetPercentReferenceWidth (const ArkUI_LayoutConstraint * Constraint) +``` +**Description** + +Obtains the width percentage reference for a size constraint, in px. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| Constraint | Size constraint. | + +**Returns** + +Width percentage reference. + + +### OH_ArkUI_LayoutConstraint_SetMaxHeight() + +``` +void OH_ArkUI_LayoutConstraint_SetMaxHeight (ArkUI_LayoutConstraint * Constraint, int32_t value ) +``` +**Description** + +Sets the maximum height. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| Constraint | Size constraint. | +| value | Maximum height, in pixels. | + + +### OH_ArkUI_LayoutConstraint_SetMaxWidth() + +``` +void OH_ArkUI_LayoutConstraint_SetMaxWidth (ArkUI_LayoutConstraint * Constraint, int32_t value ) +``` +**Description** + +Sets the maximum width. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| Constraint | Size constraint. | +| value | Maximum width, in pixels. | + + +### OH_ArkUI_LayoutConstraint_SetMinHeight() + +``` +void OH_ArkUI_LayoutConstraint_SetMinHeight (ArkUI_LayoutConstraint * Constraint, int32_t value ) +``` +**Description** + +Sets the minimum height. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| Constraint | Size constraint. | +| value | Minimum height, in pixels. | + + +### OH_ArkUI_LayoutConstraint_SetMinWidth() + +``` +void OH_ArkUI_LayoutConstraint_SetMinWidth (ArkUI_LayoutConstraint * Constraint, int32_t value ) +``` +**Description** + +Sets the minimum width. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| Constraint | Size constraint. | +| value | Minimum width, in pixels. | + + +### OH_ArkUI_LayoutConstraint_SetPercentReferenceHeight() + +``` +void OH_ArkUI_LayoutConstraint_SetPercentReferenceHeight (ArkUI_LayoutConstraint * Constraint, int32_t value ) +``` +**Description** + +Sets the height percentage reference. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| Constraint | Size constraint. | +| value | Height percentage base, in px. | + + +### OH_ArkUI_LayoutConstraint_SetPercentReferenceWidth() + +``` +void OH_ArkUI_LayoutConstraint_SetPercentReferenceWidth (ArkUI_LayoutConstraint * Constraint, int32_t value ) +``` +**Description** + +Sets the width percentage reference. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| Constraint | Size constraint. | +| value | Width percentage benchmark, in px. | + + +### OH_ArkUI_List_CloseAllSwipeActions() + +``` +int32_t OH_ArkUI_List_CloseAllSwipeActions (ArkUI_NodeHandle node, void * userData, void(*)(void *userData) onFinish ) +``` +**Description** + +Collapse the expanded ListItem. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| node | Node object for which an event needs to be registered. | +| userData | Custom event parameter, which is passed in the callback when the event is triggered. | +| onFinish | Callback triggered after the collapse animation is complete. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. Returns **ARKUI_ERROR_CODE_ATTRIBUTE_OR_EVENT_NOT_SUPPORTED** if the event is not supported. + + +### OH_ArkUI_ListChildrenMainSizeOption_Create() + +``` +ArkUI_ListChildrenMainSize* OH_ArkUI_ListChildrenMainSizeOption_Create () +``` +**Description** + +Creates a **ListChildrenMainSize** instance. + +**Since**: 12 + +**Returns** + +Returns the created **ListChildrenMainSize** instance. + +### OH_ArkUI_ListChildrenMainSizeOption_Dispose() + +``` +void OH_ArkUI_ListChildrenMainSizeOption_Dispose (ArkUI_ListChildrenMainSize * option) +``` +**Description** + +Destroys a ListChildrenMainSize instance. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| option | ListChildrenMainSize instance to be destroyed. | + + +### OH_ArkUI_ListChildrenMainSizeOption_GetDefaultMainSize() + +``` +float OH_ArkUI_ListChildrenMainSizeOption_GetDefaultMainSize (ArkUI_ListChildrenMainSize * option) +``` +**Description** + +Obtains the default size in a **ListChildrenMainSize** instance. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| option | **ListChildrenMainSize** instance. | + +**Returns** + +Returns the default size, in vp. The default value is **0**. If **option** is a null pointer, **-1** is returned. + + +### OH_ArkUI_ListChildrenMainSizeOption_GetMainSize() + +``` +float OH_ArkUI_ListChildrenMainSizeOption_GetMainSize (ArkUI_ListChildrenMainSize * option, int32_t index ) +``` +**Description** + +Obtains the value of the **ChildrenMainSizeOption** array of the **List** component. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| option | **ListChildrenMainSize** instance. | +| index | Subscript position of the value to be obtained. | + +**Returns** + +Value of the specific position of the array. If a parameter error occurs, **-1** is returned. + + +### OH_ArkUI_ListChildrenMainSizeOption_Resize() + +``` +void OH_ArkUI_ListChildrenMainSizeOption_Resize (ArkUI_ListChildrenMainSize * option, int32_t totalSize ) +``` +**Description** + +Resets the array size of ChildrenMainSizeOption of the List component. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| option | **ListChildrenMainSize** instance. | +| totalSize | Array size. | + + +### OH_ArkUI_ListChildrenMainSizeOption_SetDefaultMainSize() + +``` +int32_t OH_ArkUI_ListChildrenMainSizeOption_SetDefaultMainSize (ArkUI_ListChildrenMainSize * option, float defaultMainSize ) +``` +**Description** + +Sets the default size in a **ListChildrenMainSize** instance. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| option | **ListChildrenMainSize** instance. | +| defaultMainSize | Default size of a list item in a list. The unit is vp. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + + +### OH_ArkUI_ListChildrenMainSizeOption_Splice() + +``` +int32_t OH_ArkUI_ListChildrenMainSizeOption_Splice (ArkUI_ListChildrenMainSize * option, int32_t index, int32_t deleteCount, int32_t addCount ) +``` +**Description** + +The size of the ChildrenMainSizeOption array of the List component is adjusted. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| option | **ListChildrenMainSize** instance. | +| index | Start position of the array whose MainSize is to be modified. | +| deleteCount | Number of MainSize arrays to be deleted starting from index. | +| addCount | Number of MainSize arrays to be added starting from index. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + + +### OH_ArkUI_ListChildrenMainSizeOption_UpdateSize() + +``` +int32_t OH_ArkUI_ListChildrenMainSizeOption_UpdateSize (ArkUI_ListChildrenMainSize * option, int32_t index, float mainSize ) +``` +**Description** + +Updates the values in a **ChildrenMainSizeOption** array of a **List** component. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| option | **ListChildrenMainSize** instance. | +| index | Index at which to start changing the values in the array. | +| mainSize | New size value to set at the specified index. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + + +### OH_ArkUI_ListItemSwipeActionItem_Create() + +``` +ArkUI_ListItemSwipeActionItem* OH_ArkUI_ListItemSwipeActionItem_Create () +``` +**Description** + +Creates a **ListItemSwipeActionItem** instance. + +**Since**: 12 + +**Returns** + +Returns the created **ListItemSwipeActionItem** instance. + + +### OH_ArkUI_ListItemSwipeActionItem_Dispose() + +``` +void OH_ArkUI_ListItemSwipeActionItem_Dispose (ArkUI_ListItemSwipeActionItem * item) +``` +**Description** + +Disposes of a **ListItemSwipeActionItem** instance. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| item | **ListItemSwipeActionItem** instance to dispose of. | + + +### OH_ArkUI_ListItemSwipeActionItem_GetActionAreaDistance() + +``` +float OH_ArkUI_ListItemSwipeActionItem_GetActionAreaDistance (ArkUI_ListItemSwipeActionItem * item) +``` +**Description** + +Obtains the swipe distance threshold for deleting the list item. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| item | Target **ListItemSwipeActionItem** instance. | + +**Returns** + +Returns the swipe distance threshold for deleting the list item. Return **0** if an error occurs. + + +### OH_ArkUI_ListItemSwipeActionItem_SetActionAreaDistance() + +``` +void OH_ArkUI_ListItemSwipeActionItem_SetActionAreaDistance (ArkUI_ListItemSwipeActionItem * item, float distance ) +``` +**Description** + +Swipe distance threshold for deleting the list item. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| item | Target **ListItemSwipeActionItem** instance. | +| distance | Returns the swipe distance threshold for deleting the list item. | ### OH_ArkUI_ListItemSwipeActionItem_SetContent() ``` -void OH_ArkUI_ListItemSwipeActionItem_SetContent (ArkUI_ListItemSwipeActionItem * item, ArkUI_NodeHandle node ) +void OH_ArkUI_ListItemSwipeActionItem_SetContent (ArkUI_ListItemSwipeActionItem * item, ArkUI_NodeHandle node ) +``` +**Description** + +Sets the layout content of ListItemSwipeActionItem. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| item | Target **ListItemSwipeActionItem** instance. | +| node | Layout information | + + +### OH_ArkUI_ListItemSwipeActionItem_SetOnAction() + +``` +void OH_ArkUI_ListItemSwipeActionItem_SetOnAction (ArkUI_ListItemSwipeActionItem * item, void(*)() callback ) +``` +**Description** + +Sets the callback invoked when the list item is deleted while in the delete area. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| item | Target **ListItemSwipeActionItem** instance. | +| callback | Callback to invoke when an event of the specified type occurs. | + + +### OH_ArkUI_ListItemSwipeActionItem_SetOnActionWithUserData() + +``` +void OH_ArkUI_ListItemSwipeActionItem_SetOnActionWithUserData (ArkUI_ListItemSwipeActionItem * item, void * userData, void(*)(void *userData) callback ) +``` +**Description** + +Sets the callback invoked when the list item is deleted while in the delete area. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| item | Target **ListItemSwipeActionItem** instance. | +| userData | Custom data. | +| callback | Callback to invoke when an event of the specified type occurs. | + + +### OH_ArkUI_ListItemSwipeActionItem_SetOnEnterActionArea() + +``` +void OH_ArkUI_ListItemSwipeActionItem_SetOnEnterActionArea (ArkUI_ListItemSwipeActionItem * item, void(*)() callback ) +``` +**Description** + +Sets the callback invoked each time the list item enters the delete area. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| item | Target **ListItemSwipeActionItem** instance. | +| callback | Callback to invoke when an event of the specified type occurs. | + + +### OH_ArkUI_ListItemSwipeActionItem_SetOnEnterActionAreaWithUserData() + +``` +void OH_ArkUI_ListItemSwipeActionItem_SetOnEnterActionAreaWithUserData (ArkUI_ListItemSwipeActionItem * item, void * userData, void(*)(void *userData) callback ) +``` +**Description** + +Sets the callback invoked each time the list item enters the delete area. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| item | Target **ListItemSwipeActionItem** instance. | +| userData | Custom data. | +| callback | Callback to invoke when an event of the specified type occurs. | + + +### OH_ArkUI_ListItemSwipeActionItem_SetOnExitActionArea() + +``` +void OH_ArkUI_ListItemSwipeActionItem_SetOnExitActionArea (ArkUI_ListItemSwipeActionItem * item, void(*)() callback ) +``` +**Description** + +Sets the callback invoked each time the list item exits the delete area. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| item | Target **ListItemSwipeActionItem** instance. | +| callback | Callback to invoke when an event of the specified type occurs. | + + +### OH_ArkUI_ListItemSwipeActionItem_SetOnExitActionAreaWithUserData() + +``` +void OH_ArkUI_ListItemSwipeActionItem_SetOnExitActionAreaWithUserData (ArkUI_ListItemSwipeActionItem * item, void * userData, void(*)(void *userData) callback ) +``` +**Description** + +Sets the callback invoked each time the list item exits the delete area. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| item | Target **ListItemSwipeActionItem** instance. | +| userData | Custom data. | +| callback | Callback to invoke when an event of the specified type occurs. | + + +### OH_ArkUI_ListItemSwipeActionItem_SetOnStateChange() + +``` +void OH_ArkUI_ListItemSwipeActionItem_SetOnStateChange (ArkUI_ListItemSwipeActionItem * item, void(*)(ArkUI_ListItemSwipeActionState swipeActionState) callback ) +``` +**Description** + +Sets the callback invoked when the swipe state of the list item changes. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| item | Target **ListItemSwipeActionItem** instance. | +| callback | Status after the callback event swipeActionState changes. | + + +### OH_ArkUI_ListItemSwipeActionItem_SetOnStateChangeWithUserData() + +``` +void OH_ArkUI_ListItemSwipeActionItem_SetOnStateChangeWithUserData (ArkUI_ListItemSwipeActionItem * item, void * userData, void(*)(ArkUI_ListItemSwipeActionState swipeActionState, void *userData) callback ) +``` +**Description** + +Sets the callback invoked when the swipe state of the list item changes. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| item | Target **ListItemSwipeActionItem** instance. | +| userData | Custom data. | +| callback | Status after the callback event swipeActionState changes. | + + +### OH_ArkUI_ListItemSwipeActionOption_Create() + +``` +ArkUI_ListItemSwipeActionOption* OH_ArkUI_ListItemSwipeActionOption_Create () +``` +**Description** + +Creates a **ListItemSwipeActionOption** instance. + +**Since**: 12 + +**Returns** + +ListItemSwipeActionOption configuration item instance. + + +### OH_ArkUI_ListItemSwipeActionOption_Dispose() + +``` +void OH_ArkUI_ListItemSwipeActionOption_Dispose (ArkUI_ListItemSwipeActionOption * option) +``` +**Description** + +Destroys a ListItemSwipeActionOption instance. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| option | ListItemSwipeActionOption instance to destroy. | + + +### OH_ArkUI_ListItemSwipeActionOption_GetEdgeEffect() + +``` +int32_t OH_ArkUI_ListItemSwipeActionOption_GetEdgeEffect (ArkUI_ListItemSwipeActionOption * option) +``` +**Description** + +Obtains the sliding effect. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| option | Target **ListItemSwipeActionItem** instance. | + +**Returns** + +Scroll effect. The default return value is **ARKUI_LIST_ITEM_SWIPE_EDGE_EFFECT_SPRING**. + + +### OH_ArkUI_ListItemSwipeActionOption_SetEdgeEffect() + +``` +void OH_ArkUI_ListItemSwipeActionOption_SetEdgeEffect (ArkUI_ListItemSwipeActionOption * option, ArkUI_ListItemSwipeEdgeEffect edgeEffect ) +``` +**Description** + +Sets the sliding effect. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| option | Target **ListItemSwipeActionItem** instance. | +| edgeEffect | Scroll effect. | + + +### OH_ArkUI_ListItemSwipeActionOption_SetEnd() + +``` +void OH_ArkUI_ListItemSwipeActionOption_SetEnd (ArkUI_ListItemSwipeActionOption * option, ArkUI_ListItemSwipeActionItem * item ) +``` +**Description** + +Sets the layout content for the right edge (for a vertical layout) or bottom edge (for a horizontal layout) of a **ListItemSwipeActionItem** instance. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| option | Target **ListItemSwipeActionItem** instance. | +| builder | Layout information | + + +### OH_ArkUI_ListItemSwipeActionOption_SetOnOffsetChange() + +``` +void OH_ArkUI_ListItemSwipeActionOption_SetOnOffsetChange (ArkUI_ListItemSwipeActionOption * option, void(*)(float offset) callback ) +``` +**Description** + +Sets the callback invoked when the scroll offset changes. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| option | Target **ListItemSwipeActionItem** instance. | +| callback | Sliding offset of the callback event offset. | + + +### OH_ArkUI_ListItemSwipeActionOption_SetOnOffsetChangeWithUserData() + +``` +void OH_ArkUI_ListItemSwipeActionOption_SetOnOffsetChangeWithUserData (ArkUI_ListItemSwipeActionOption * option, void * userData, void(*)(float offset, void *userData) callback ) +``` +**Description** + +Sets the callback invoked when the scroll offset changes. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| option | Target **ListItemSwipeActionItem** instance. | +| userData | Custom data. | +| callback | Sliding offset of the callback event offset. | + + +### OH_ArkUI_ListItemSwipeActionOption_SetStart() + +``` +void OH_ArkUI_ListItemSwipeActionOption_SetStart (ArkUI_ListItemSwipeActionOption * option, ArkUI_ListItemSwipeActionItem * item ) +``` +**Description** + +Sets the layout content for the left edge (for a vertical layout) or top edge (for a horizontal layout) of a **ListItemSwipeActionItem** instance. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| option | Target **ListItemSwipeActionItem** instance. | +| builder | Layout information | + + +### OH_ArkUI_LongPress_GetRepeatCount() + +``` +int32_t OH_ArkUI_LongPress_GetRepeatCount (const ArkUI_GestureEvent * event) +``` +**Description** + +Obtains the number of times that a long press gesture is triggered periodically. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| event | Gesture event. | + +**Returns** + +Returns the number of times that the long press gesture is triggered periodically. + + +### OH_ArkUI_MarshallStyledStringDescriptor() + +``` +int32_t OH_ArkUI_MarshallStyledStringDescriptor (uint8_t * buffer, size_t bufferSize, ArkUI_StyledString_Descriptor * descriptor ) +``` +**Description** + +Serializes the styled string information into a byte array. + +**Since**: 14 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| buffer | Byte array where the serialized data will be stored. | +| bufferSize | Length of the byte array. | +| descriptor | Pointer to an **ArkUI_StyledString_Descriptor** object. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. Returns **ARKUI_ERROR_CODE_INVALID_STYLED_STRING** if the styled string is invalid. + + +### OH_ArkUI_NodeAdapter_Create() + +``` +ArkUI_NodeAdapterHandle OH_ArkUI_NodeAdapter_Create () +``` +**Description** + +Creates a component adapter. + +**Since**: 12 + + +### OH_ArkUI_NodeAdapter_Dispose() + +``` +void OH_ArkUI_NodeAdapter_Dispose (ArkUI_NodeAdapterHandle handle) +``` +**Description** + +Destroys a component adapter. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| handle | Component adapter object. | + + +### OH_ArkUI_NodeAdapter_GetAllItems() + +``` +int32_t OH_ArkUI_NodeAdapter_GetAllItems (ArkUI_NodeAdapterHandle handle, ArkUI_NodeHandle ** items, uint32_t * size ) +``` +**Description** + +Obtains all elements stored in the specified adapter. + +When the API is called, the array object pointer of the element is returned. The memory data pointed by the pointer needs to be manually released by developers. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| handle | Component adapter object. | +| items | Array of nodes in the adapter. | +| size | Number of elements. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + + +### OH_ArkUI_NodeAdapter_GetTotalNodeCount() + +``` +uint32_t OH_ArkUI_NodeAdapter_GetTotalNodeCount (ArkUI_NodeAdapterHandle handle) +``` +**Description** + +Obtains the total number of elements in the Adapter. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| handle | Component adapter object. | + +**Returns** + +Total number of elements in the Adapter. + + +### OH_ArkUI_NodeAdapter_InsertItem() + +``` +int32_t OH_ArkUI_NodeAdapter_InsertItem (ArkUI_NodeAdapterHandle handle, uint32_t startPosition, uint32_t itemCount ) +``` +**Description** + +Instructs the specified adapter to insert certain elements. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| handle | Component adapter object. | +| startPosition | Start position for inserting an element. | +| itemCount | Number of inserted elements. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + + +### OH_ArkUI_NodeAdapter_MoveItem() + +``` +int32_t OH_ArkUI_NodeAdapter_MoveItem (ArkUI_NodeAdapterHandle handle, uint32_t from, uint32_t to ) +``` +**Description** + +Instructs the specified adapter to move certain elements. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| handle | Component adapter object. | +| from | Start position of the element shift. | +| to | End position of the element shift. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + + +### OH_ArkUI_NodeAdapter_RegisterEventReceiver() + +``` +int32_t OH_ArkUI_NodeAdapter_RegisterEventReceiver (ArkUI_NodeAdapterHandle handle, void * userData, void(*)(ArkUI_NodeAdapterEvent *event) receiver ) +``` +**Description** + +Registers callback events related to the Adapter. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| handle | Component adapter object. | +| userData | Custom data. | +| receiver | Event receiving callback. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + + +### OH_ArkUI_NodeAdapter_ReloadAllItems() + +``` +int32_t OH_ArkUI_NodeAdapter_ReloadAllItems (ArkUI_NodeAdapterHandle handle) +``` +**Description** + +Instructs the specified adapter to reload all elements. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| handle | Component adapter object. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + + +### OH_ArkUI_NodeAdapter_ReloadItem() + +``` +int32_t OH_ArkUI_NodeAdapter_ReloadItem (ArkUI_NodeAdapterHandle handle, uint32_t startPosition, uint32_t itemCount ) +``` +**Description** + +Instructs the specified adapter to reload certain elements. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| handle | Component adapter object. | +| startPosition | Start position of an element change. | +| itemCount | Number of changed elements. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + + +### OH_ArkUI_NodeAdapter_RemoveItem() + +``` +int32_t OH_ArkUI_NodeAdapter_RemoveItem (ArkUI_NodeAdapterHandle handle, uint32_t startPosition, uint32_t itemCount ) +``` +**Description** + +Instructs the specified adapter to remove certain elements. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| handle | Component adapter object. | +| startPosition | Start position for deleting an element. | +| itemCount | Number of deleted elements. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + + +### OH_ArkUI_NodeAdapter_SetTotalNodeCount() + +``` +int32_t OH_ArkUI_NodeAdapter_SetTotalNodeCount (ArkUI_NodeAdapterHandle handle, uint32_t size ) +``` +**Description** + +Sets the total number of elements in the specified adapter. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| handle | Component adapter object. | +| size | Number of elements. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + + +### OH_ArkUI_NodeAdapter_UnregisterEventReceiver() + +``` +void OH_ArkUI_NodeAdapter_UnregisterEventReceiver (ArkUI_NodeAdapterHandle handle) +``` +**Description** + +Deregisters Adapter-related callback events. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| handle | Component adapter object. | + + +### OH_ArkUI_NodeAdapterEvent_GetHostNode() + +``` +ArkUI_NodeHandle OH_ArkUI_NodeAdapterEvent_GetHostNode (ArkUI_NodeAdapterEvent * event) +``` +**Description** + +Obtains the scrolling class container node that uses the adapter. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| event | Adapter event object. | + +**Returns** + +Returns the scrollable container node that uses the specified adapter. + + +### OH_ArkUI_NodeAdapterEvent_GetItemIndex() + +``` +uint32_t OH_ArkUI_NodeAdapterEvent_GetItemIndex (ArkUI_NodeAdapterEvent * event) +``` +**Description** + +Sequence number of the element to be operated when the adapter event is obtained. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| event | Adapter event object. | + +**Returns** + +Sequence number of an element. + + +### OH_ArkUI_NodeAdapterEvent_GetRemovedNode() + +``` +ArkUI_NodeHandle OH_ArkUI_NodeAdapterEvent_GetRemovedNode (ArkUI_NodeAdapterEvent * event) +``` +**Description** + +Obtains the element to be destroyed in the event to be destroyed. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| event | Adapter event object. | + +**Returns** + +Element to be destroyed. + + +### OH_ArkUI_NodeAdapterEvent_GetType() + +``` +ArkUI_NodeAdapterEventType OH_ArkUI_NodeAdapterEvent_GetType (ArkUI_NodeAdapterEvent * event) +``` +**Description** + +Obtains the event type. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| event | Adapter event object. | + +**Returns** + +Represents an event type. + + +### OH_ArkUI_NodeAdapterEvent_GetUserData() + +``` +void* OH_ArkUI_NodeAdapterEvent_GetUserData (ArkUI_NodeAdapterEvent * event) +``` +**Description** + +Obtains the custom data passed in during registration of the specified event. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| event | Adapter event object. | + + +### OH_ArkUI_NodeAdapterEvent_SetItem() + +``` +int32_t OH_ArkUI_NodeAdapterEvent_SetItem (ArkUI_NodeAdapterEvent * event, ArkUI_NodeHandle node ) +``` +**Description** + +Sets the component to be added to the specified adapter. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| event | Adapter event object. | +| node | Component to be added. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + + +### OH_ArkUI_NodeAdapterEvent_SetNodeId() + +``` +int32_t OH_ArkUI_NodeAdapterEvent_SetNodeId (ArkUI_NodeAdapterEvent * event, int32_t id ) +``` +**Description** + +Sets the generated component ID. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| event | Adapter event object. | +| id | Sets the returned component ID. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + + +### OH_ArkUI_NodeContent_AddNode() + +``` +int32_t OH_ArkUI_NodeContent_AddNode (ArkUI_NodeContentHandle content, ArkUI_NodeHandle node ) +``` +**Description** + +Adds an ArkUI component node to the specified NodeContent object. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| content | NodeContent object to which a node is to be added. | +| node | Node to be added. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + + +### OH_ArkUI_NodeContent_GetUserData() + +``` +void* OH_ArkUI_NodeContent_GetUserData (ArkUI_NodeContentHandle content) +``` +**Description** + +Obtains the user-defined data saved on the NodeContent object. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| content | NodeContent object whose user-defined data needs to be saved. | + +**Returns** + +Custom data. + + +### OH_ArkUI_NodeContent_InsertNode() + +``` +int32_t OH_ArkUI_NodeContent_InsertNode (ArkUI_NodeContentHandle content, ArkUI_NodeHandle node, int32_t position ) +``` +**Description** + +Inserts an ArkUI component node into a specific location of the corresponding NodeContent object. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| content | NodeContent object of the node to be inserted. | +| node | Node to be inserted. | +| position | Start time for an asset to be inserted, | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + + +### OH_ArkUI_NodeContent_RegisterCallback() + +``` +int32_t OH_ArkUI_NodeContent_RegisterCallback (ArkUI_NodeContentHandle content, ArkUI_NodeContentCallback callback ) +``` +**Description** + +Registers the NodeContent event function. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| content | NodeContent object for which an event needs to be registered. | +| callback | Callback to be executed when the event is triggered. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + + +### OH_ArkUI_NodeContent_RemoveNode() + +``` +int32_t OH_ArkUI_NodeContent_RemoveNode (ArkUI_NodeContentHandle content, ArkUI_NodeHandle node ) +``` +**Description** + +Removes an ArkUI component node from the specified NodeContent object. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| content | NodeContent object of the node to be deleted. | +| node | Node to be deleted. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + + +### OH_ArkUI_NodeContent_SetUserData() + +``` +int32_t OH_ArkUI_NodeContent_SetUserData (ArkUI_NodeContentHandle content, void * userData ) +``` +**Description** + +Saves user-defined data on the NodeContent object. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| content | NodeContent object whose user-defined data needs to be saved. | +| userData | User-defined data to be saved. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + + +### OH_ArkUI_NodeContentEvent_GetEventType() + +``` +ArkUI_NodeContentEventType OH_ArkUI_NodeContentEvent_GetEventType (ArkUI_NodeContentEvent * event) +``` +**Description** + +Obtains the type of the specified NodeContent event. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| event | Pointer to the NodeContent event. | + +**Returns** + +NodeContent event type. + + +### OH_ArkUI_NodeContentEvent_GetNodeContentHandle() + +``` +ArkUI_NodeContentHandle OH_ArkUI_NodeContentEvent_GetNodeContentHandle (ArkUI_NodeContentEvent * event) +``` +**Description** + +Obtains the object that triggers the specified NodeContent event. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| event | Pointer to the NodeContent event. | + +**Returns** + +Returns the NodeContent object that triggers the event. + + +### OH_ArkUI_NodeCustomEvent_GetCustomSpanDrawInfo() + +``` +int32_t OH_ArkUI_NodeCustomEvent_GetCustomSpanDrawInfo (ArkUI_NodeCustomEvent * event, ArkUI_CustomSpanDrawInfo * info ) +``` +**Description** + +Obtains the drawing information of a custom span through a custom component event. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| event | Pointer to the custom component event. | +| info | Drawing information to obtain. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. A possible cause is that mandatory parameters are left unspecified. + + +### OH_ArkUI_NodeCustomEvent_GetCustomSpanMeasureInfo() + +``` +int32_t OH_ArkUI_NodeCustomEvent_GetCustomSpanMeasureInfo (ArkUI_NodeCustomEvent * event, ArkUI_CustomSpanMeasureInfo * info ) +``` +**Description** + +Obtains the measurement information of a custom span through a custom component event. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| event | Pointer to the custom component event. | +| info | Measurement information to obtain. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. A possible cause is that mandatory parameters are left unspecified. + + +### OH_ArkUI_NodeCustomEvent_GetDrawContextInDraw() + +``` +ArkUI_DrawContext* OH_ArkUI_NodeCustomEvent_GetDrawContextInDraw (ArkUI_NodeCustomEvent * event) +``` +**Description** + +Obtains the drawing context through a custom component event. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| event | Pointer to the custom component event. | + +**Returns** + +Returns the drawing context. + + +### OH_ArkUI_NodeCustomEvent_GetEventTargetId() + +``` +int32_t OH_ArkUI_NodeCustomEvent_GetEventTargetId (ArkUI_NodeCustomEvent * event) +``` +**Description** + +Obtains the ID of a custom component event. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| event | Pointer to the custom component event. | + +**Returns** + +Returns the custom event ID. + + +### OH_ArkUI_NodeCustomEvent_GetEventType() + +``` +ArkUI_NodeCustomEventType OH_ArkUI_NodeCustomEvent_GetEventType (ArkUI_NodeCustomEvent * event) +``` +**Description** + +Obtains the event type through a custom component event. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| event | Pointer to the custom component event. | + +**Returns** + +Returns the type of the custom component event. + + +### OH_ArkUI_NodeCustomEvent_GetLayoutConstraintInMeasure() + +``` +ArkUI_LayoutConstraint* OH_ArkUI_NodeCustomEvent_GetLayoutConstraintInMeasure (ArkUI_NodeCustomEvent * event) +``` +**Description** + +Obtains the size constraint for measurement through a custom component event. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| event | Pointer to the custom component event. | + +**Returns** + +Pointer to the constraint size. + + +### OH_ArkUI_NodeCustomEvent_GetNodeHandle() + +``` +ArkUI_NodeHandle OH_ArkUI_NodeCustomEvent_GetNodeHandle (ArkUI_NodeCustomEvent * event) +``` +**Description** + +Obtains a component object through a custom component event. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| event | Pointer to the custom component event. | + +**Returns** + +Returns the obtained component object. + + +### OH_ArkUI_NodeCustomEvent_GetPositionInLayout() + +``` +ArkUI_IntOffset OH_ArkUI_NodeCustomEvent_GetPositionInLayout (ArkUI_NodeCustomEvent * event) +``` +**Description** + +Obtains the expected position of a component relative to its parent component in the layout phase through a custom component event. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| event | Pointer to the custom component event. | + +**Returns** + +Returns the expected position relative to the parent component. + + +### OH_ArkUI_NodeCustomEvent_GetUserData() + +``` +void* OH_ArkUI_NodeCustomEvent_GetUserData (ArkUI_NodeCustomEvent * event) +``` +**Description** + +Obtains custom event parameters through a custom component event. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| event | Pointer to the custom component event. | + +**Returns** + +Returns the custom event parameters. + + +### OH_ArkUI_NodeCustomEvent_SetCustomSpanMetrics() + +``` +int32_t OH_ArkUI_NodeCustomEvent_SetCustomSpanMetrics (ArkUI_NodeCustomEvent * event, ArkUI_CustomSpanMetrics * metrics ) +``` +**Description** + +Sets the measurement metrics of a custom span through a custom component event. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| event | Pointer to the custom component event. | +| metrics | Measurement metrics to set. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. A possible cause is that mandatory parameters are left unspecified. + + +### OH_ArkUI_NodeEvent_GetDragEvent() + +``` +ArkUI_DragEvent* OH_ArkUI_NodeEvent_GetDragEvent (ArkUI_NodeEvent * nodeEvent) +``` +**Description** + +Obtains an **ArkUI_DragEvent** object from the specified **ArkUI_DragEvent** object. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| node | Pointer to an **ArkUI_NodeEvent** object. | + +**Returns** + +Returns the pointer to an **ArkUI_DragEvent** object; returns null if the parameter passed in is invalid or is not a drag-related event. + + +### OH_ArkUI_NodeEvent_GetEventType() + +``` +ArkUI_NodeEventType OH_ArkUI_NodeEvent_GetEventType (ArkUI_NodeEvent * event) +``` +**Description** + +Obtains the type of a component event. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| event | Pointer to the component event. | + +**Returns** + +Returns the type of the component event. + + +### OH_ArkUI_NodeEvent_GetInputEvent() + +``` +ArkUI_UIInputEvent* OH_ArkUI_NodeEvent_GetInputEvent (ArkUI_NodeEvent * event) +``` +**Description** + +Obtains input event (for example, touch event) data for a component event. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| event | Pointer to the component event. | + +**Returns** + +Returns the pointer to the input event data. + + +### OH_ArkUI_NodeEvent_GetNodeComponentEvent() + +``` +ArkUI_NodeComponentEvent* OH_ArkUI_NodeEvent_GetNodeComponentEvent (ArkUI_NodeEvent * event) +``` +**Description** + +Obtains the numerical data in a component event. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| event | Pointer to the component event. | + +**Returns** + +Returns the pointer to the numerical data. + + +### OH_ArkUI_NodeEvent_GetNodeHandle() + +``` +ArkUI_NodeHandle OH_ArkUI_NodeEvent_GetNodeHandle (ArkUI_NodeEvent * event) +``` +**Description** + +Obtains the component object that triggers an event. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| event | Pointer to the component event. | + +**Returns** + +Component object that triggers the event. + + +### OH_ArkUI_NodeEvent_GetNumberValue() + +``` +int32_t OH_ArkUI_NodeEvent_GetNumberValue (ArkUI_NodeEvent * event, int32_t index, ArkUI_NumberValue * value ) +``` +**Description** + +Obtains the numeric-type parameter of a component event. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| event | Pointer to the component event. | +| index | Return value index. | +| value | Return value. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_NODE_EVENT_PARAM_INDEX_OUT_OF_RANGE** if the parameter length in the parameter event exceeds the limit. Returns **ARKUI_ERROR_CODE_NODE_EVENT_PARAM_INVALID** if the data does not exist in the component event. + + +### OH_ArkUI_NodeEvent_GetPreDragStatus() + +``` +ArkUI_PreDragStatus OH_ArkUI_NodeEvent_GetPreDragStatus (ArkUI_NodeEvent * nodeEvent) +``` +**Description** + +Obtains the state prior to a drop and drop operation. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| node | ArkUI_NodeEvent node object. | + +**Returns** + +Returns the state prior to the drop and drop operation. + + +### OH_ArkUI_NodeEvent_GetStringAsyncEvent() + +``` +ArkUI_StringAsyncEvent* OH_ArkUI_NodeEvent_GetStringAsyncEvent (ArkUI_NodeEvent * event) +``` +**Description** + +Obtains the string data in a component event. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| event | Pointer to the component event. | + +**Returns** + +ArkUI_StringAsyncEvent\Pointer to string data. + + +### OH_ArkUI_NodeEvent_GetStringValue() + +``` +int32_t OH_ArkUI_NodeEvent_GetStringValue (ArkUI_NodeEvent * event, int32_t index, char ** string, int32_t * stringSize ) +``` +**Description** + +Obtains the string-type parameter of the component callback event. The string data is valid only during event callback and needs to be used outside event callback. You are advised to copy the string data. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| event | Pointer to the component event. | +| index | Return value index. | +| string | Pointer to the string array. | +| stringSize | Length of the string array. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_NODE_EVENT_PARAM_INDEX_OUT_OF_RANGE** if the parameter length in the parameter event exceeds the limit. Returns **ARKUI_ERROR_CODE_NODE_EVENT_PARAM_INVALID** if the data does not exist in the component event. + + +### OH_ArkUI_NodeEvent_GetTargetId() + +``` +int32_t OH_ArkUI_NodeEvent_GetTargetId (ArkUI_NodeEvent * event) +``` +**Description** + +Obtains the custom ID of a component event. + +The event ID is transferred as a parameter when the registerNodeEvent function is called and can be used in the distribution logic of the same event entry function registerNodeEventReceiver. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| event | Pointer to the component event. | + +**Returns** + +Returns the custom ID of the component event. + + +### OH_ArkUI_NodeEvent_GetUserData() + +``` +void* OH_ArkUI_NodeEvent_GetUserData (ArkUI_NodeEvent * event) +``` +**Description** + +Obtains the custom data in a component event. + +This parameter is passed in **registerNodeEvent** and can be applied to the service logic when the event is triggered. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| event | Pointer to the component event. | + +**Returns** + +Returns the pointer to user data. + + +### OH_ArkUI_NodeEvent_SetReturnNumberValue() + +``` +int32_t OH_ArkUI_NodeEvent_SetReturnNumberValue (ArkUI_NodeEvent * event, ArkUI_NumberValue * value, int32_t size ) +``` +**Description** + +Sets the return value for a component event. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| event | Pointer to the component event. | +| value | Event numeric type array. | +| size | Size of the array. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. The component event does not support return values. Returns **ARKUI_ERROR_CODE_NODE_EVENT_PARAM_INVALID** if the data does not exist in the component event. + + +### OH_ArkUI_NodeUtils_AddCustomProperty() + +``` +void OH_ArkUI_NodeUtils_AddCustomProperty (ArkUI_NodeHandle node, const char * name, const char * value ) +``` +**Description** + +Sets a custom property for a component. This API takes effect only in the main thread. + +**Since**: 13 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| node | **ArkUI_NodeHandle** pointer. | +| name | Name of the custom property. A null pointer is not allowed. | +| value | Value of the custom property. A null pointer is not allowed. | + + +### OH_ArkUI_NodeUtils_GetActiveChildrenInfo() + +``` +int32_t OH_ArkUI_NodeUtils_GetActiveChildrenInfo (ArkUI_NodeHandle head, ArkUI_ActiveChildrenInfo ** handle ) +``` +**Description** + +Obtains all active child nodes of the specified node. Spans are not counted as child nodes. + +**Since**: 14 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| head | Node for which to obtain the child nodes. | +| handle | Pointer to the struct containing information about the child nodes of the head node. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + + +### OH_ArkUI_NodeUtils_GetCurrentPageRootNode() + +``` +ArkUI_NodeHandle OH_ArkUI_NodeUtils_GetCurrentPageRootNode (ArkUI_NodeHandle node) ``` **Description** -Sets the layout content of ListItemSwipeActionItem. +Obtains the root node of the current page. + +**Since**: 14 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| node | Target node. | + +**Returns** + +Returns the pointer to the root node if the node exists; returns **NULL** otherwise. + + +### OH_ArkUI_NodeUtils_GetCustomProperty() + +``` +int32_t OH_ArkUI_NodeUtils_GetCustomProperty (ArkUI_NodeHandle node, const char * name, ArkUI_CustomProperty ** handle ) +``` +**Description** + +Obtains the value of a custom property of the specified component. + +**Since**: 14 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| node | **ArkUI_NodeHandle** pointer. | +| name | Name of the custom property. | +| handle | Pointer to the struct that receives the custom property corresponding to the key parameter name. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + + +### OH_ArkUI_NodeUtils_GetLayoutPosition() + +``` +int32_t OH_ArkUI_NodeUtils_GetLayoutPosition (ArkUI_NodeHandle node, ArkUI_IntOffset * localOffset ) +``` +**Description** + +Obtains the position of the component's layout area relative to its parent component. The relative position does not count in transformation attributes, such as translate. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| item | Target **ListItemSwipeActionItem** instance. | -| node | Layout information | +| node | **ArkUI_NodeHandle** pointer. | +| localOffset | Offset of the component handle relative to the parent component, in pixels. | +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_ListItemSwipeActionItem_SetOnAction() + +### OH_ArkUI_NodeUtils_GetLayoutPositionInScreen() ``` -void OH_ArkUI_ListItemSwipeActionItem_SetOnAction (ArkUI_ListItemSwipeActionItem * item, void(*)() callback ) +int32_t OH_ArkUI_NodeUtils_GetLayoutPositionInScreen (ArkUI_NodeHandle node, ArkUI_IntOffset * screenOffset ) ``` **Description** -Sets the callback invoked when the list item is deleted while in the delete area. +Obtains the position of the component's layout area relative to the screen. The relative position does not count in transformation attributes, such as translate. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| item | Target **ListItemSwipeActionItem** instance. | -| callback | Callback to invoke when an event of the specified type occurs. | +| node | **ArkUI_NodeHandle** pointer. | +| screenOffset | Offset of the component handle relative to the screen, in pixels. | +**Returns** -### OH_ArkUI_ListItemSwipeActionItem_SetOnActionWithUserData() +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + + +### OH_ArkUI_NodeUtils_GetLayoutPositionInWindow() ``` -void OH_ArkUI_ListItemSwipeActionItem_SetOnActionWithUserData (ArkUI_ListItemSwipeActionItem * item, void * userData, void(*)(void *userData) callback ) +int32_t OH_ArkUI_NodeUtils_GetLayoutPositionInWindow (ArkUI_NodeHandle node, ArkUI_IntOffset * globalOffset ) ``` **Description** -Sets the callback invoked when the list item is deleted while in the delete area. +Obtains the position of the component's layout area relative to the window. The relative position does not count in transformation attributes, such as translate. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| item | Target **ListItemSwipeActionItem** instance. | -| userData | Custom data. | -| callback | Callback to invoke when an event of the specified type occurs. | +| node | **ArkUI_NodeHandle** pointer. | +| globalOffset | Offset of the component handle relative to the window, in pixels. | +**Returns** -### OH_ArkUI_ListItemSwipeActionItem_SetOnEnterActionArea() +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + + +### OH_ArkUI_NodeUtils_GetLayoutSize() ``` -void OH_ArkUI_ListItemSwipeActionItem_SetOnEnterActionArea (ArkUI_ListItemSwipeActionItem * item, void(*)() callback ) +int32_t OH_ArkUI_NodeUtils_GetLayoutSize (ArkUI_NodeHandle node, ArkUI_IntSize * size ) +``` +**Description** + +Obtains the layout area size of a component. The size does not count in transformation attributes, such as scale. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| node | **ArkUI_NodeHandle** pointer. | +| size | Size of the layout area, in px. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + + +### OH_ArkUI_NodeUtils_GetNodeType() + +``` +int32_t OH_ArkUI_NodeUtils_GetNodeType (ArkUI_NodeHandle node) +``` +**Description** + +Obtains the type of the specified node. + +**Since**: 14 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| node | Target node. | + +**Returns** + +Returns the type of the node. Returns **-1** if the type is not supported yet. For details about the available types, see [ArkUI_NodeType](#arkui_nodetype). + + +### OH_ArkUI_NodeUtils_GetParentInPageTree() + +``` +ArkUI_NodeHandle OH_ArkUI_NodeUtils_GetParentInPageTree (ArkUI_NodeHandle node) +``` +**Description** + +Obtains the parent node, which can be a component node created with ArkTS. + +**Since**: 14 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| node | Target node. | + +**Returns** + +Returns the pointer to the component if the component exists; returns **NULL** otherwise. + + +### OH_ArkUI_NodeUtils_GetPositionWithTranslateInScreen() + +``` +int32_t OH_ArkUI_NodeUtils_GetPositionWithTranslateInScreen (ArkUI_NodeHandle node, ArkUI_IntOffset * translateOffset ) +``` +**Description** + +Obtains the position of a component on the screen, including the translate attribute. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| node | **ArkUI_NodeHandle** pointer. | +| translateOffset | Accumulated offset of the component, its parent component, and its ancestor node, in px. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + + +### OH_ArkUI_NodeUtils_GetPositionWithTranslateInWindow() + +``` +int32_t OH_ArkUI_NodeUtils_GetPositionWithTranslateInWindow (ArkUI_NodeHandle node, ArkUI_IntOffset * translateOffset ) +``` +**Description** + +Obtains the position of a component in the window, including the translate attribute. + +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| node | **ArkUI_NodeHandle** pointer. | +| translateOffset | Accumulated offset of the component, its parent component, and its ancestor node, in px. | + +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + + +### OH_ArkUI_NodeUtils_IsCreatedByNDK() + +``` +bool OH_ArkUI_NodeUtils_IsCreatedByNDK (ArkUI_NodeHandle node) +``` +**Description** + +Checks whether the specified component is created with the C API. + +**Since**: 14 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| node | Target node. | + +**Returns** + +Returns whether the node is created with the C API. The value **true** means that the node is created with the C API, and **false** means the opposite. + + +### OH_ArkUI_NodeUtils_RemoveCustomProperty() + +``` +void OH_ArkUI_NodeUtils_RemoveCustomProperty (ArkUI_NodeHandle node, const char * name ) +``` +**Description** + +Removes a custom property that has been set for the specified component. + +**Since**: 13 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| node | **ArkUI_NodeHandle** pointer. | +| name | Name of the custom property. | + + +### OH_ArkUI_PanGesture_GetOffsetX() + +``` +float OH_ArkUI_PanGesture_GetOffsetX (const ArkUI_GestureEvent * event) ``` **Description** -Sets the callback invoked each time the list item enters the delete area. +Obtains the relative offset of a pan gesture along the x-axis. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| item | Target **ListItemSwipeActionItem** instance. | -| callback | Callback to invoke when an event of the specified type occurs. | +| event | Gesture event. | +**Returns** -### OH_ArkUI_ListItemSwipeActionItem_SetOnEnterActionAreaWithUserData() +Returns the relative offset of the gesture along the x-axis, in px. + + +### OH_ArkUI_PanGesture_GetOffsetY() ``` -void OH_ArkUI_ListItemSwipeActionItem_SetOnEnterActionAreaWithUserData (ArkUI_ListItemSwipeActionItem * item, void * userData, void(*)(void *userData) callback ) +float OH_ArkUI_PanGesture_GetOffsetY (const ArkUI_GestureEvent * event) ``` **Description** -Sets the callback invoked each time the list item enters the delete area. +Obtains the relative offset of a pan gesture along the y-axis. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| item | Target **ListItemSwipeActionItem** instance. | -| userData | Custom data. | -| callback | Callback to invoke when an event of the specified type occurs. | +| event | Gesture event. | +**Returns** -### OH_ArkUI_ListItemSwipeActionItem_SetOnExitActionArea() +Returns the relative offset of the gesture along the y-axis, in px. + + +### OH_ArkUI_PanGesture_GetVelocity() ``` -void OH_ArkUI_ListItemSwipeActionItem_SetOnExitActionArea (ArkUI_ListItemSwipeActionItem * item, void(*)() callback ) +float OH_ArkUI_PanGesture_GetVelocity (const ArkUI_GestureEvent * event) ``` **Description** -Sets the callback invoked each time the list item exits the delete area. +Obtains the velocity of a pan gesture along the main axis. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| item | Target **ListItemSwipeActionItem** instance. | -| callback | Callback to invoke when an event of the specified type occurs. | +| event | Gesture event. | +**Returns** -### OH_ArkUI_ListItemSwipeActionItem_SetOnExitActionAreaWithUserData() +Returns the velocity of the pan gesture along the main axis, in px/s. The value is the square root of the sum of the squares of the velocity on the x-axis and y-axis. + + +### OH_ArkUI_PanGesture_GetVelocityX() ``` -void OH_ArkUI_ListItemSwipeActionItem_SetOnExitActionAreaWithUserData (ArkUI_ListItemSwipeActionItem * item, void * userData, void(*)(void *userData) callback ) +float OH_ArkUI_PanGesture_GetVelocityX (const ArkUI_GestureEvent * event) ``` **Description** -Sets the callback invoked each time the list item exits the delete area. +Obtains the velocity of a pan gesture along the x-axis. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| item | Target **ListItemSwipeActionItem** instance. | -| userData | Custom data. | -| callback | Callback to invoke when an event of the specified type occurs. | +| event | Gesture event. | -### OH_ArkUI_ListItemSwipeActionItem_SetOnStateChange() +**Returns** + +Returns the velocity of the pan gesture along the x-axis, in px/s. + + +### OH_ArkUI_PanGesture_GetVelocityY() ``` -void OH_ArkUI_ListItemSwipeActionItem_SetOnStateChange (ArkUI_ListItemSwipeActionItem * item, void(*)(ArkUI_ListItemSwipeActionState swipeActionState) callback ) +float OH_ArkUI_PanGesture_GetVelocityY (const ArkUI_GestureEvent * event) ``` **Description** -Sets the callback invoked when the swipe state of the list item changes. +Obtains the velocity of a pan gesture along the y-axis. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| item | Target **ListItemSwipeActionItem** instance. | -| callback | Status after the callback event swipeActionState changes. | +| event | Gesture event. | +**Returns** -### OH_ArkUI_ListItemSwipeActionItem_SetOnStateChangeWithUserData() +Returns the velocity of the pan gesture along the y-axis, in px/s. + + +### OH_ArkUI_ParallelInnerGestureEvent_GetConflictRecognizers() ``` -void OH_ArkUI_ListItemSwipeActionItem_SetOnStateChangeWithUserData (ArkUI_ListItemSwipeActionItem * item, void * userData, void(*)(ArkUI_ListItemSwipeActionState swipeActionState, void *userData) callback ) +int32_t OH_ArkUI_ParallelInnerGestureEvent_GetConflictRecognizers (ArkUI_ParallelInnerGestureEvent * event, ArkUI_GestureRecognizerHandleArray * array, int32_t * size ) ``` **Description** -Sets the callback invoked when the swipe state of the list item changes. +Obtains the conflicting gesture recognizers in a parallel internal gesture event. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| item | Target **ListItemSwipeActionItem** instance. | -| userData | Custom data. | -| callback | Status after the callback event swipeActionState changes. | +| event | Parallel internal gesture event. | +| array | Array of conflicting gesture recognizers. | +| size | Size of the conflicting gesture recognizer array. | +**Returns** -### OH_ArkUI_ListItemSwipeActionOption_Create() +Returns **0** if the operation is successful. Returns **401** if a parameter error occurs. + + +### OH_ArkUI_ParallelInnerGestureEvent_GetCurrentRecognizer() ``` -ArkUI_ListItemSwipeActionOption* OH_ArkUI_ListItemSwipeActionOption_Create () +ArkUI_GestureRecognizer* OH_ArkUI_ParallelInnerGestureEvent_GetCurrentRecognizer (ArkUI_ParallelInnerGestureEvent * event) ``` **Description** -Creates a **ListItemSwipeActionOption** instance. +Obtains the current gesture recognizer in a parallel internal gesture event. **Since**: 12 -**Returns** +**Parameters** -ListItemSwipeActionOption configuration item instance. +| Name| Description| +| -------- | -------- | +| event | Parallel internal gesture event. | +**Returns** -### OH_ArkUI_ListItemSwipeActionOption_Dispose() +Returns the pointer to the current gesture recognizer. + +### OH_ArkUI_ParallelInnerGestureEvent_GetUserData() ``` -void OH_ArkUI_ListItemSwipeActionOption_Dispose (ArkUI_ListItemSwipeActionOption * option) +void* OH_ArkUI_ParallelInnerGestureEvent_GetUserData (ArkUI_ParallelInnerGestureEvent * event) ``` **Description** -Destroys a ListItemSwipeActionOption instance. +Obtains custom data in the parallel internal gesture event. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | ListItemSwipeActionOption instance to destroy. | +| event | Parallel internal gesture event. | +**Returns** -### OH_ArkUI_ListItemSwipeActionOption_GetEdgeEffect() +Returns the pointer to custom data. + +### OH_ArkUI_GestureInterrupter_GetUserData ``` -int32_t OH_ArkUI_ListItemSwipeActionOption_GetEdgeEffect (ArkUI_ListItemSwipeActionOption * option) +void* OH_ArkUI_GestureInterrupter_GetUserData(ArkUI_GestureInterruptInfo* event) ``` + **Description** -Obtains the sliding effect. +Obtains the custom data from a gesture interruption event. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| -| -------- | -------- | -| option | Target **ListItemSwipeActionItem** instance. | +| Name | Description | +| ----- | -------------------------- | +| event | Pointer to the gesture interruption information.| **Returns** -Scroll effect. The default return value is **ARKUI_LIST_ITEM_SWIPE_EDGE_EFFECT_SPRING**. +Returns the pointer to the custom data. -### OH_ArkUI_ListItemSwipeActionOption_SetEdgeEffect() +### OH_ArkUI_PinchGesture_GetCenterX() ``` -void OH_ArkUI_ListItemSwipeActionOption_SetEdgeEffect (ArkUI_ListItemSwipeActionOption * option, ArkUI_ListItemSwipeEdgeEffect edgeEffect ) +float OH_ArkUI_PinchGesture_GetCenterX (const ArkUI_GestureEvent * event) ``` **Description** -Sets the sliding effect. +Obtains the X coordinate of the center of the pinch gesture, in vp, relative to the upper left corner of the current component. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Target **ListItemSwipeActionItem** instance. | -| edgeEffect | Scroll effect. | +| event | Gesture event. | + +**Returns** + +Returns the X coordinate of the center of the pinch gesture, in vp, relative to the upper left corner of the current component. -### OH_ArkUI_ListItemSwipeActionOption_SetEnd() +### OH_ArkUI_PinchGesture_GetCenterY() ``` -void OH_ArkUI_ListItemSwipeActionOption_SetEnd (ArkUI_ListItemSwipeActionOption * option, ArkUI_ListItemSwipeActionItem * item ) +float OH_ArkUI_PinchGesture_GetCenterY (const ArkUI_GestureEvent * event) ``` **Description** -Sets the layout content for the right edge (for a vertical layout) or bottom edge (for a horizontal layout) of a **ListItemSwipeActionItem** instance. +Obtains the Y coordinate of the center of the pinch gesture, in vp, relative to the upper left corner of the current component. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Target **ListItemSwipeActionItem** instance. | -| builder | Layout information | +| event | Gesture event. | + +**Returns** + +Returns the Y coordinate of the center of the pinch gesture, in vp, relative to the upper left corner of the current component. -### OH_ArkUI_ListItemSwipeActionOption_SetOnOffsetChange() +### OH_ArkUI_PinchGesture_GetScale() ``` -void OH_ArkUI_ListItemSwipeActionOption_SetOnOffsetChange (ArkUI_ListItemSwipeActionOption * option, void(*)(float offset) callback ) +float OH_ArkUI_PinchGesture_GetScale (const ArkUI_GestureEvent * event) ``` **Description** -Sets the callback invoked when the scroll offset changes. +Obtains the scale ratio of a pinch gesture. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Target **ListItemSwipeActionItem** instance. | -| callback | Sliding offset of the callback event offset. | +| event | Gesture event. | + +**Returns** + +Scale. -### OH_ArkUI_ListItemSwipeActionOption_SetOnOffsetChangeWithUserData() +### OH_ArkUI_QueryModuleInterfaceByName() ``` -void OH_ArkUI_ListItemSwipeActionOption_SetOnOffsetChangeWithUserData (ArkUI_ListItemSwipeActionOption * option, void * userData, void(*)(float offset, void *userData) callback ) +void* OH_ArkUI_QueryModuleInterfaceByName (ArkUI_NativeAPIVariantKind type, const char * structName ) ``` **Description** -Sets the callback invoked when the scroll offset changes. +Obtains the native API set of a specified type. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Target **ListItemSwipeActionItem** instance. | -| userData | Custom data. | -| callback | Sliding offset of the callback event offset. | +| type | Type of the native API set provided by ArkUI, for example, **ARKUI_NATIVE_NODE** or **ARKUI_NATIVE_GESTURE**. | +| sturctName | Name of a native struct defined in the corresponding header file, for example, **ArkUI_NativeNodeAPI_1** in <arkui/native_node.h>. | + +**Returns** + +Returns the pointer to the abstract native API, which can be used after being converted into a specific type. \#include<arkui/native_interface.h> \#include<arkui/native_node.h> \#include<arkui/native_gesture.h> auto\* anyNativeAPI = [OH_ArkUI_QueryModuleInterfaceByName](#oh_arkui_querymoduleinterfacebyname)(ARKUI_NATIVE_NODE, "ArkUI_NativeNodeAPI_1"); if (anyNativeAPI) { auto nativeNodeApi = reinterpret_cast<[ArkUI_NativeNodeAPI_1](_ark_u_i___native_node_a_p_i__1.md)\*>(anyNativeAPI); } auto anyGestureAPI = OH_ArkUI_QueryModuleInterface(ARKUI_NATIVE_GESTURE, "ArkUI_NativeGestureAPI_1"); if (anyNativeAPI) { auto basicGestureApi = reinterpret_cast<[ArkUI_NativeGestureAPI_1](_ark_u_i___native_gesture_a_p_i__1.md)\*>(anyGestureAPI); } -### OH_ArkUI_ListItemSwipeActionOption_SetStart() +### OH_ArkUI_RegisterSystemColorModeChangeEvent() ``` -void OH_ArkUI_ListItemSwipeActionOption_SetStart (ArkUI_ListItemSwipeActionOption * option, ArkUI_ListItemSwipeActionItem * item ) +int32_t OH_ArkUI_RegisterSystemColorModeChangeEvent (ArkUI_NodeHandle node, void * userData, void(*)(ArkUI_SystemColorMode colorMode, void *userData) onColorModeChange ) ``` **Description** -Sets the layout content for the left edge (for a vertical layout) or top edge (for a horizontal layout) of a **ListItemSwipeActionItem** instance. +Registers an event listener for system color mode changes. A single component can only register one callback for system color mode changes. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Target **ListItemSwipeActionItem** instance. | -| builder | Layout information | +| node | Specified node. | +| userData | Custom event parameter, which is passed in the callback when the event is triggered. | +| onColorModeChange | Callback to be executed when the event is triggered. | +**Returns** -### OH_ArkUI_LongPress_GetRepeatCount() +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. Returns **ARKUI_ERROR_CODE_ATTRIBUTE_OR_EVENT_NOT_SUPPORTED** if the event is not supported. + + +### OH_ArkUI_RegisterSystemFontStyleChangeEvent() ``` -int32_t OH_ArkUI_LongPress_GetRepeatCount (const ArkUI_GestureEvent * event) +int32_t OH_ArkUI_RegisterSystemFontStyleChangeEvent (ArkUI_NodeHandle node, void * userData, void(*)(ArkUI_SystemFontStyleEvent *event, void *userData) onFontStyleChange ) ``` **Description** -Obtains the number of times that a long press gesture is triggered periodically. +Registers an event listener for system font style changes. A single component can only register one callback for system font style changes. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Gesture event. | +| node | Specified node. | +| userData | Custom event parameter, which is passed in the callback when the event is triggered. | +| onFontStyleChange | Callback to be executed when the event is triggered. | **Returns** -Returns the number of times that the long press gesture is triggered periodically. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. Returns **ARKUI_ERROR_CODE_ATTRIBUTE_OR_EVENT_NOT_SUPPORTED** if the event is not supported. -### OH_ArkUI_MarshallStyledStringDescriptor() +### OH_ArkUI_RotationGesture_GetAngle() ``` -int32_t OH_ArkUI_MarshallStyledStringDescriptor (uint8_t * buffer, size_t bufferSize, ArkUI_StyledString_Descriptor * descriptor ) +float OH_ArkUI_RotationGesture_GetAngle (const ArkUI_GestureEvent * event) ``` **Description** -Serializes the styled string information into a byte array. +Obtains the angle information of a rotation gesture. -**Since**: 14 +**Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| buffer | Byte array where the serialized data will be stored. | -| bufferSize | Length of the byte array. | -| descriptor | Pointer to an **ArkUI_StyledString_Descriptor** object. | +| event | Gesture event. | **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. Returns **ARKUI_ERROR_CODE_INVALID_STYLED_STRING** if the styled string is invalid. +Rotation angle. -### OH_ArkUI_NodeAdapter_Create() +### OH_ArkUI_SetArkUIGestureRecognizerDisposeNotify() ``` -ArkUI_NodeAdapterHandle OH_ArkUI_NodeAdapter_Create () +int32_t OH_ArkUI_SetArkUIGestureRecognizerDisposeNotify (ArkUI_GestureRecognizer * recognizer, ArkUI_GestureRecognizerDestructNotifyCallback callback, void * userData ) ``` **Description** -Creates a component adapter. +Sets a callback function for notifying gesture recognizer destruction. -**Since**: 12 +**Parameters** +| Name| Description| +| -------- | -------- | +| recognizer | Pointer to the gesture recognizer. | +| callback | Callback function for notifying gesture recognizer destruction. | +| userData | Custom data. | + +**Returns** + +Returns **0** if the operation is successful. Returns **401** if a parameter error occurs. -### OH_ArkUI_NodeAdapter_Dispose() + +### OH_ArkUI_SetDragEventStrictReportWithContext() ``` -void OH_ArkUI_NodeAdapter_Dispose (ArkUI_NodeAdapterHandle handle) +int32_t OH_ArkUI_SetDragEventStrictReportWithContext (ArkUI_ContextHandle uiContext, bool enabled ) ``` **Description** -Destroys a component adapter. +Sets whether to enable strict reporting on drag events. This feature is disabled by default, and you are advised to enable it. If this feature is disabled, the parent component is not notified when an item in it is dragged over its child component. If this feature is enabled, the component is notified of the dragged item's leaving, and the child component to which the dragged item is dropped is notified of the item's entering. This configuration is related to a specific UI instance. You can pass in a UI instance for association. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| handle | Component adapter object. | +| uiContext | Pointer to the UI instance. | +| enabled | Whether to enable strict reporting on drag events. | +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_NodeAdapter_GetAllItems() + +### OH_ArkUI_SetDragEventStrictReportWithNode() ``` -int32_t OH_ArkUI_NodeAdapter_GetAllItems (ArkUI_NodeAdapterHandle handle, ArkUI_NodeHandle ** items, uint32_t * size ) +int32_t OH_ArkUI_SetDragEventStrictReportWithNode (ArkUI_NodeHandle node, bool enabled ) ``` **Description** -Obtains all elements stored in the specified adapter. - -When the API is called, the array object pointer of the element is returned. The memory data pointed by the pointer needs to be manually released by developers. +Sets whether to enable strict reporting on drag events. This feature is disabled by default, and you are advised to enable it. If this feature is disabled, the parent component is not notified when an item in it is dragged over its child component. If this feature is enabled, the component is notified of the dragged item's leaving, and the child component to which the dragged item is dropped is notified of the item's entering. This configuration is related to a specific UI instance. You can pass in a specific component node on the current UI instance for association. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| handle | Component adapter object. | -| items | Array of nodes in the adapter. | -| size | Number of elements. | +| node | Pointer to a component node. | +| enabled | Whether to enable strict reporting on drag events. | **Returns** Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_NodeAdapter_GetTotalNodeCount() +### OH_ArkUI_SetGestureRecognizerEnabled() ``` -uint32_t OH_ArkUI_NodeAdapter_GetTotalNodeCount (ArkUI_NodeAdapterHandle handle) +int32_t OH_ArkUI_SetGestureRecognizerEnabled (ArkUI_GestureRecognizer * recognizer, bool enabled ) ``` **Description** -Obtains the total number of elements in the Adapter. +Sets the enabled state of a gesture recognizer. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| handle | Component adapter object. | +| recognizer | Pointer to the gesture recognizer. | +| enabled | Whether to enable notification. | **Returns** -Total number of elements in the Adapter. - +Returns **0** if the operation is successful. Returns **401** if a parameter error occurs. -### OH_ArkUI_NodeAdapter_InsertItem() +### OH_ArkUI_SetGestureRecognizerLimitFingerCount ``` -int32_t OH_ArkUI_NodeAdapter_InsertItem (ArkUI_NodeAdapterHandle handle, uint32_t startPosition, uint32_t itemCount ) +int32_t OH_ArkUI_SetGestureRecognizerLimitFingerCount (ArkUI_GestureRecognizer * recognizer, bool limitFingerCount ) ``` **Description** -Instructs the specified adapter to insert certain elements. - -**Since**: 12 +Sets whether to enforce the exact number of fingers touching the screen. **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| handle | Component adapter object. | -| startPosition | Start position for inserting an element. | -| itemCount | Number of inserted elements. | +| recognizer | Pointer to the gesture recognizer. | +| limitFingerCount | Whether to enforce the exact number of fingers touching the screen. | **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +Returns **0** if the operation is successful. Returns **401** if a parameter error occurs. -### OH_ArkUI_NodeAdapter_MoveItem() + + +### OH_ArkUI_SetNodeAllowedDropDataTypes() ``` -int32_t OH_ArkUI_NodeAdapter_MoveItem (ArkUI_NodeAdapterHandle handle, uint32_t from, uint32_t to ) +int32_t OH_ArkUI_SetNodeAllowedDropDataTypes (ArkUI_NodeHandle node, const char * typesArray[], int32_t count ) ``` **Description** -Instructs the specified adapter to move certain elements. +Sets the types of data that can be dropped to the specified component. This API resets the settings configured through [OH_ArkUI_DisallowNodeAnyDropDataTypes](#oh_arkui_disallownodeanydropdatatypes) or [OH_ArkUI_AllowNodeAllDropDataTypes](#oh_arkui_allownodealldropdatatypes). **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| handle | Component adapter object. | -| from | Start position of the element shift. | -| to | End position of the element shift. | +| node | Pointer to a component node. | +| typesArray | Array of data types that can fall into. | +| count | Length of an array. | **Returns** Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_NodeAdapter_RegisterEventReceiver() +### OH_ArkUI_SetNodeDraggable() ``` -int32_t OH_ArkUI_NodeAdapter_RegisterEventReceiver (ArkUI_NodeAdapterHandle handle, void * userData, void(*)(ArkUI_NodeAdapterEvent *event) receiver ) +int32_t OH_ArkUI_SetNodeDraggable (ArkUI_NodeHandle node, bool enabled ) ``` **Description** -Registers callback events related to the Adapter. +Sets whether the component is draggable. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| handle | Component adapter object. | -| userData | Custom data. | -| receiver | Event receiving callback. | +| node | Pointer to a component node. | +| bool | Whether the component is draggable. | **Returns** Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_NodeAdapter_ReloadAllItems() +### OH_ArkUI_SetNodeDragPreview() ``` -int32_t OH_ArkUI_NodeAdapter_ReloadAllItems (ArkUI_NodeAdapterHandle handle) +int32_t OH_ArkUI_SetNodeDragPreview (ArkUI_NodeHandle node, OH_PixelmapNative * preview ) ``` **Description** -Instructs the specified adapter to reload all elements. +Sets a custom drag preview for the specified component. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| handle | Component adapter object. | +| node | Pointer to the target component node. | +| preview | Custom drag preview, which is a pixel map. | **Returns** Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_NodeAdapter_ReloadItem() +### OH_ArkUI_SetNodeDragPreviewOption() ``` -int32_t OH_ArkUI_NodeAdapter_ReloadItem (ArkUI_NodeAdapterHandle handle, uint32_t startPosition, uint32_t itemCount ) +int32_t OH_ArkUI_SetNodeDragPreviewOption (ArkUI_NodeHandle node, ArkUI_DragPreviewOption * option ) ``` **Description** -Instructs the specified adapter to reload certain elements. +Sets an **ArkUI_DragPreviewOption** object for the specified component. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| handle | Component adapter object. | -| startPosition | Start position of an element change. | -| itemCount | Number of changed elements. | +| node | Pointer to a component node. | +| option | Custom parameters. | **Returns** Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_NodeAdapter_RemoveItem() +### OH_ArkUI_StartDrag() ``` -int32_t OH_ArkUI_NodeAdapter_RemoveItem (ArkUI_NodeAdapterHandle handle, uint32_t startPosition, uint32_t itemCount ) +int32_t OH_ArkUI_StartDrag (ArkUI_DragAction * dragAction) ``` **Description** -Instructs the specified adapter to remove certain elements. +Initiates a drag action through the specified drag action object. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| handle | Component adapter object. | -| startPosition | Start position for deleting an element. | -| itemCount | Number of deleted elements. | +| dragAction | Drag action object. | **Returns** Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_NodeAdapter_SetTotalNodeCount() +### OH_ArkUI_StyledString_AddPlaceholder() ``` -int32_t OH_ArkUI_NodeAdapter_SetTotalNodeCount (ArkUI_NodeAdapterHandle handle, uint32_t size ) +void OH_ArkUI_StyledString_AddPlaceholder (ArkUI_StyledString * handle, OH_Drawing_PlaceholderSpan * placeholder ) ``` **Description** -Sets the total number of elements in the specified adapter. +Adds a placeholder. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| handle | Component adapter object. | -| size | Number of elements. | - -**Returns** - -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +| handle | Pointer to an **ArkUI_StyledString** object. | +| placeholder | Pointer to an **OH_Drawing_PlaceholderSpan** object. | -### OH_ArkUI_NodeAdapter_UnregisterEventReceiver() +### OH_ArkUI_StyledString_AddText() ``` -void OH_ArkUI_NodeAdapter_UnregisterEventReceiver (ArkUI_NodeAdapterHandle handle) +void OH_ArkUI_StyledString_AddText (ArkUI_StyledString * handle, const char * content ) ``` **Description** -Deregisters Adapter-related callback events. +Sets the text content based on the current format string style. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| handle | Component adapter object. | +| handle | Pointer to an **ArkUI_StyledString** object. | +| content | Pointer to the text content. | -### OH_ArkUI_NodeAdapterEvent_GetHostNode() +### OH_ArkUI_StyledString_Create() ``` -ArkUI_NodeHandle OH_ArkUI_NodeAdapterEvent_GetHostNode (ArkUI_NodeAdapterEvent * event) +ArkUI_StyledString* OH_ArkUI_StyledString_Create (OH_Drawing_TypographyStyle * style, OH_Drawing_FontCollection * collection ) ``` **Description** -Obtains the scrolling class container node that uses the adapter. +Creates an **ArkUI_StyledString** object. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Adapter event object. | +| style | Pointer to an **OH_Drawing_TypographyStyle** object, which is obtained by calling **OH_Drawing_CreateTypographyStyle**. | +| collection | Pointer to an **OH_Drawing_FontCollection** object, which is obtained by calling **OH_Drawing_CreateFontCollection**. | **Returns** -Returns the scrollable container node that uses the specified adapter. +Returns the pointer to the **ArkUI_StyledString** object created. If a null pointer is returned, the creation fails. A possible cause is that the application address space is full, or a parameter error, for example, a null pointer for the **style** or **collection** parameter, occurs. -### OH_ArkUI_NodeAdapterEvent_GetItemIndex() +### OH_ArkUI_StyledString_CreateTypography() ``` -uint32_t OH_ArkUI_NodeAdapterEvent_GetItemIndex (ArkUI_NodeAdapterEvent * event) +OH_Drawing_Typography* OH_ArkUI_StyledString_CreateTypography (ArkUI_StyledString * handle) ``` **Description** -Sequence number of the element to be operated when the adapter event is obtained. +Creates an **OH_Drawing_Typography** object based on an **ArkUI_StyledString** object. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Adapter event object. | +| handle | Pointer to an **ArkUI_StyledString** object. | **Returns** -Sequence number of an element. +Returns the pointer to the **OH_Drawing_Typography** object created. If a null pointer is returned, the creation fails. A possible cause is that a parameter error, for example, a null pointer for the **handle** parameter, occurs. -### OH_ArkUI_NodeAdapterEvent_GetRemovedNode() +### OH_ArkUI_StyledString_Descriptor_Create() ``` -ArkUI_NodeHandle OH_ArkUI_NodeAdapterEvent_GetRemovedNode (ArkUI_NodeAdapterEvent * event) +ArkUI_StyledString_Descriptor* OH_ArkUI_StyledString_Descriptor_Create (void ) ``` **Description** -Obtains the element to be destroyed in the event to be destroyed. - -**Since**: 12 - -**Parameters** +Creates an **ArkUI_StyledString_Descriptor** object. -| Name| Description| -| -------- | -------- | -| event | Adapter event object. | +**Since**: 14 **Returns** -Element to be destroyed. +Pointer to an **ArkUI_StyledString_Descriptor** object. -### OH_ArkUI_NodeAdapterEvent_GetType() +### OH_ArkUI_StyledString_Descriptor_Destroy() ``` -ArkUI_NodeAdapterEventType OH_ArkUI_NodeAdapterEvent_GetType (ArkUI_NodeAdapterEvent * event) +void OH_ArkUI_StyledString_Descriptor_Destroy (ArkUI_StyledString_Descriptor * descriptor) ``` **Description** -Obtains the event type. +Destroys an **ArkUI_StyledString_Descriptor** object and reclaims the memory occupied by the object. -**Since**: 12 +**Since**: 14 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Adapter event object. | - -**Returns** - -Represents an event type. +| descriptor | Pointer to an **ArkUI_StyledString_Descriptor** object. | -### OH_ArkUI_NodeAdapterEvent_GetUserData() +### OH_ArkUI_StyledString_Destroy() ``` -void* OH_ArkUI_NodeAdapterEvent_GetUserData (ArkUI_NodeAdapterEvent * event) +void OH_ArkUI_StyledString_Destroy (ArkUI_StyledString * handle) ``` **Description** -Obtains the custom data passed in during registration of the specified event. +Destroys an **OH_Drawing_TextStyle** object and reclaims the memory occupied by the object. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Adapter event object. | +| handle | Pointer to an **ArkUI_StyledString** object. | -### OH_ArkUI_NodeAdapterEvent_SetItem() +### OH_ArkUI_StyledString_PopTextStyle() ``` -int32_t OH_ArkUI_NodeAdapterEvent_SetItem (ArkUI_NodeAdapterEvent * event, ArkUI_NodeHandle node ) +void OH_ArkUI_StyledString_PopTextStyle (ArkUI_StyledString * handle) ``` **Description** -Sets the component to be added to the specified adapter. +Removes the top style from the current formatted string object. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Adapter event object. | -| node | Component to be added. | +| handle | Pointer to an **ArkUI_StyledString** object. | -**Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +### OH_ArkUI_StyledString_PushTextStyle() + +``` +void OH_ArkUI_StyledString_PushTextStyle (ArkUI_StyledString * handle, OH_Drawing_TextStyle * style ) +``` +**Description** +Sets the new typesetting style to the top of the current format string style stack. -### OH_ArkUI_NodeAdapterEvent_SetNodeId() +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| handle | Pointer to an **ArkUI_StyledString** object. | +| style | Pointer to an **OH_Drawing_TextStyle** object. | + + +### OH_ArkUI_SwipeGesture_GetAngle() ``` -int32_t OH_ArkUI_NodeAdapterEvent_SetNodeId (ArkUI_NodeAdapterEvent * event, int32_t id ) +float OH_ArkUI_SwipeGesture_GetAngle (const ArkUI_GestureEvent * event) ``` **Description** -Sets the generated component ID. +Obtains the angle information of the swipe gesture. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Adapter event object. | -| id | Sets the returned component ID. | +| event | Gesture event. | **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +Returns the angle of the swipe gesture, which is the result obtained based on the aforementioned formula. -### OH_ArkUI_NodeContent_AddNode() +### OH_ArkUI_SwipeGesture_GetVelocity() ``` -int32_t OH_ArkUI_NodeContent_AddNode (ArkUI_NodeContentHandle content, ArkUI_NodeHandle node ) +float OH_ArkUI_SwipeGesture_GetVelocity (const ArkUI_GestureEvent * event) ``` **Description** -Adds an ArkUI component node to the specified NodeContent object. +Obtains the average velocity of all fingers used in the swipe gesture. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| content | NodeContent object to which a node is to be added. | -| node | Node to be added. | +| event | Gesture event. | **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +Returns the average velocity of all fingers used in the swipe gesture, in px/s. -### OH_ArkUI_NodeContent_GetUserData() +### OH_ArkUI_SwiperIndicator_Create() ``` -void* OH_ArkUI_NodeContent_GetUserData (ArkUI_NodeContentHandle content) +ArkUI_SwiperIndicator* OH_ArkUI_SwiperIndicator_Create (ArkUI_SwiperIndicatorType type) ``` **Description** -Obtains the user-defined data saved on the NodeContent object. +Creates a navigation indicator for the Swiper component. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| content | NodeContent object whose user-defined data needs to be saved. | +| type | Type of the navigation indicator. | **Returns** -Custom data. +Returns the pointer to the navigation indicator. -### OH_ArkUI_NodeContent_InsertNode() +### OH_ArkUI_SwiperIndicator_Dispose() ``` -int32_t OH_ArkUI_NodeContent_InsertNode (ArkUI_NodeContentHandle content, ArkUI_NodeHandle node, int32_t position ) +void OH_ArkUI_SwiperIndicator_Dispose (ArkUI_SwiperIndicator * indicator) ``` **Description** -Inserts an ArkUI component node into a specific location of the corresponding NodeContent object. +Disposes of the navigation indicator of this **Swiper** component. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| content | NodeContent object of the node to be inserted. | -| node | Node to be inserted. | -| position | Start time for an asset to be inserted, | - -**Returns** - -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +| indicator | Returns the pointer to the navigation indicator. | -### OH_ArkUI_NodeContent_RegisterCallback() +### OH_ArkUI_SwiperIndicator_GetBottomPosition() ``` -int32_t OH_ArkUI_NodeContent_RegisterCallback (ArkUI_NodeContentHandle content, ArkUI_NodeContentCallback callback ) +float OH_ArkUI_SwiperIndicator_GetBottomPosition (ArkUI_SwiperIndicator * indicator) ``` **Description** -Registers the NodeContent event function. +Obtains the distance between the navigation indicator and the bottom edge of the **Swiper** component. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| content | NodeContent object for which an event needs to be registered. | -| callback | Callback to be executed when the event is triggered. | +| indicator | Returns the pointer to the navigation indicator. | **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +Returns the distance between a navigation indicator and the bottom edge of the **Swiper** component. -### OH_ArkUI_NodeContent_RemoveNode() +### OH_ArkUI_SwiperIndicator_GetColor() ``` -int32_t OH_ArkUI_NodeContent_RemoveNode (ArkUI_NodeContentHandle content, ArkUI_NodeHandle node ) +uint32_t OH_ArkUI_SwiperIndicator_GetColor (ArkUI_SwiperIndicator * indicator) ``` **Description** -Removes an ArkUI component node from the specified NodeContent object. +Obtains the color of a dot-style navigation indicator of the **Swiper** component. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| content | NodeContent object of the node to be deleted. | -| node | Node to be deleted. | +| indicator | Returns the pointer to the navigation indicator. | **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +Returns the color, in 0xARGB format. For example, 0xFFFF0000 indicates red. -### OH_ArkUI_NodeContent_SetUserData() +### OH_ArkUI_SwiperIndicator_GetEndPosition() ``` -int32_t OH_ArkUI_NodeContent_SetUserData (ArkUI_NodeContentHandle content, void * userData ) +float OH_ArkUI_SwiperIndicator_GetEndPosition (ArkUI_SwiperIndicator * indicator) ``` **Description** -Saves user-defined data on the NodeContent object. +Obtains the distance between a navigation indicator and the right edge of the **Swiper** component. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| content | NodeContent object whose user-defined data needs to be saved. | -| userData | User-defined data to be saved. | +| indicator | Returns the pointer to the navigation indicator. | **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +Returns the distance between the navigation indicator and the right edge of the **Swiper** component. -### OH_ArkUI_NodeContentEvent_GetEventType() +### OH_ArkUI_SwiperIndicator_GetItemHeight() ``` -ArkUI_NodeContentEventType OH_ArkUI_NodeContentEvent_GetEventType (ArkUI_NodeContentEvent * event) +float OH_ArkUI_SwiperIndicator_GetItemHeight (ArkUI_SwiperIndicator * indicator) ``` **Description** -Obtains the type of the specified NodeContent event. +Obtains the height of a dot-style navigation indicator of the **Swiper** component. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to the NodeContent event. | +| indicator | Returns the pointer to the navigation indicator. | **Returns** -NodeContent event type. +Returns the height of the dot-style navigation indicator. -### OH_ArkUI_NodeContentEvent_GetNodeContentHandle() +### OH_ArkUI_SwiperIndicator_GetItemWidth() ``` -ArkUI_NodeContentHandle OH_ArkUI_NodeContentEvent_GetNodeContentHandle (ArkUI_NodeContentEvent * event) +float OH_ArkUI_SwiperIndicator_GetItemWidth (ArkUI_SwiperIndicator * indicator) ``` **Description** -Obtains the object that triggers the specified NodeContent event. +Obtains the width of a dot-style navigation indicator of the **Swiper** component. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to the NodeContent event. | +| indicator | Returns the pointer to the navigation indicator. | **Returns** -Returns the NodeContent object that triggers the event. +Returns the width of the dot-style navigation indicator. -### OH_ArkUI_NodeCustomEvent_GetCustomSpanDrawInfo() +### OH_ArkUI_SwiperIndicator_GetMask() ``` -int32_t OH_ArkUI_NodeCustomEvent_GetCustomSpanDrawInfo (ArkUI_NodeCustomEvent * event, ArkUI_CustomSpanDrawInfo * info ) +int32_t OH_ArkUI_SwiperIndicator_GetMask (ArkUI_SwiperIndicator * indicator) ``` **Description** -Obtains the drawing information of a custom span through a custom component event. +Obtains whether the mask is enabled for a dot-style navigation indicator of the **Swiper** component. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to the custom component event. | -| info | Drawing information to obtain. | +| indicator | Returns the pointer to the navigation indicator. | **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. A possible cause is that mandatory parameters are left unspecified. +Returns **1** if the mask is enabled; returns **0** otherwise. -### OH_ArkUI_NodeCustomEvent_GetCustomSpanMeasureInfo() +### OH_ArkUI_SwiperIndicator_GetMaxDisplayCount() ``` -int32_t OH_ArkUI_NodeCustomEvent_GetCustomSpanMeasureInfo (ArkUI_NodeCustomEvent * event, ArkUI_CustomSpanMeasureInfo * info ) +int32_t OH_ArkUI_SwiperIndicator_GetMaxDisplayCount (ArkUI_SwiperIndicator * indicator) ``` **Description** -Obtains the measurement information of a custom span through a custom component event. +Obtains the maximum number of dots for the dot-style navigation indicator. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to the custom component event. | -| info | Measurement information to obtain. | +| indicator | Returns the pointer to the navigation indicator. | **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. A possible cause is that mandatory parameters are left unspecified. +Returns the maximum number of dots. The value ranges from 6 to 9. -### OH_ArkUI_NodeCustomEvent_GetDrawContextInDraw() +### OH_ArkUI_SwiperDigitIndicator_Create() ``` -ArkUI_DrawContext* OH_ArkUI_NodeCustomEvent_GetDrawContextInDraw (ArkUI_NodeCustomEvent * event) +ArkUI_SwiperDigitIndicator *OH_ArkUI_SwiperDigitIndicator_Create() ``` **Description** -Obtains the drawing context through a custom component event. +Creates a digit-style navigation indicator for this **Swiper** component. -**Since**: 12 +**Since**: 15 -**Parameters** +**Returns** -| Name| Description| -| -------- | -------- | -| event | Pointer to the custom component event. | +Returns the pointer to the digit-style navigation indicator. -**Returns** +### OH_ArkUI_SwiperDigitIndicator_SetStartPosition() -Returns the drawing context. +``` +void OH_ArkUI_SwiperDigitIndicator_SetStartPosition(ArkUI_SwiperDigitIndicator* indicator, float value) +``` +**Description** + +Sets the start position of the digit-style navigation indicator for the **Swiper** component. This determines the distance from the left edge of the **Swiper** component. For right-to-left scripts, this determines the distance from the right edge. +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| indicator | Pointer to a digit-style navigation indicator. | +| value | Distance from the left edge of the **Swiper** component. For right-to-left scripts, this indicates the distance from the right edge. | -### OH_ArkUI_NodeCustomEvent_GetEventTargetId() +### OH_ArkUI_SwiperDigitIndicator_GetStartPosition() ``` -int32_t OH_ArkUI_NodeCustomEvent_GetEventTargetId (ArkUI_NodeCustomEvent * event) +float OH_ArkUI_SwiperDigitIndicator_GetStartPosition(ArkUI_SwiperDigitIndicator* indicator) ``` **Description** -Obtains the ID of a custom component event. +Obtains the start position of the digit-style navigation indicator for the **Swiper** component. This indicates the distance from the left edge of the **Swiper** component. For right-to-left scripts, this indicates the distance from the right edge. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to the custom component event. | +| indicator | Pointer to a digit-style navigation indicator.| **Returns** -Returns the custom event ID. - +Returns the distance from the left edge of the **Swiper** component. For right-to-left scripts, this indicates the distance from the right edge. -### OH_ArkUI_NodeCustomEvent_GetEventType() +### OH_ArkUI_SwiperDigitIndicator_SetTopPosition() ``` -ArkUI_NodeCustomEventType OH_ArkUI_NodeCustomEvent_GetEventType (ArkUI_NodeCustomEvent * event) +void OH_ArkUI_SwiperDigitIndicator_SetTopPosition(ArkUI_SwiperDigitIndicator* indicator, float value) ``` **Description** -Obtains the event type through a custom component event. +Sets the distance from the digit-style navigation indicator to the top of the **Swiper** component. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to the custom component event. | - -**Returns** - -Returns the type of the custom component event. - +| indicator | Pointer to a digit-style navigation indicator. | +| value | Distance from the digit-style navigation indicator to the top of the **Swiper** component. | -### OH_ArkUI_NodeCustomEvent_GetLayoutConstraintInMeasure() +### OH_ArkUI_SwiperDigitIndicator_GetTopPosition() ``` -ArkUI_LayoutConstraint* OH_ArkUI_NodeCustomEvent_GetLayoutConstraintInMeasure (ArkUI_NodeCustomEvent * event) +float OH_ArkUI_SwiperDigitIndicator_GetTopPosition(ArkUI_SwiperDigitIndicator* indicator) ``` **Description** -Obtains the size constraint for measurement through a custom component event. +Obtains the distance from the digit-style navigation indicator to the top of the **Swiper** component. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to the custom component event. | +| indicator | Pointer to a digit-style navigation indicator.| **Returns** -Pointer to the constraint size. - +Returns the distance from the digit-style navigation indicator to the top of the **Swiper** component. -### OH_ArkUI_NodeCustomEvent_GetNodeHandle() +### OH_ArkUI_SwiperDigitIndicator_SetEndPosition() ``` -ArkUI_NodeHandle OH_ArkUI_NodeCustomEvent_GetNodeHandle (ArkUI_NodeCustomEvent * event) +void OH_ArkUI_SwiperDigitIndicator_SetEndPosition(ArkUI_SwiperDigitIndicator* indicator, float value) ``` **Description** -Obtains a component object through a custom component event. +Sets the end position of the digit-style navigation indicator for the **Swiper** component. This determines the distance from the right edge of the **Swiper** component. For right-to-left scripts, this determines the distance from the left edge. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to the custom component event. | - -**Returns** +| indicator | Pointer to a digit-style navigation indicator. | +| value | Distance from the right edge of the **Swiper** component. For right-to-left scripts, this indicates the distance from the left edge. | -Returns the obtained component object. - - -### OH_ArkUI_NodeCustomEvent_GetPositionInLayout() +### OH_ArkUI_SwiperDigitIndicator_GetEndPosition() ``` -ArkUI_IntOffset OH_ArkUI_NodeCustomEvent_GetPositionInLayout (ArkUI_NodeCustomEvent * event) +float OH_ArkUI_SwiperDigitIndicator_GetEndPosition(ArkUI_SwiperDigitIndicator* indicator) ``` **Description** -Obtains the expected position of a component relative to its parent component in the layout phase through a custom component event. +Obtains the end position of the digit-style navigation indicator for the **Swiper** component. This indicates the distance from the right edge of the **Swiper** component. For right-to-left scripts, this indicates the distance from the left edge. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to the custom component event. | +| indicator | Pointer to a digit-style navigation indicator.| **Returns** -Returns the expected position relative to the parent component. - +Returns the distance from the right edge of the **Swiper** component. For right-to-left scripts, this indicates the distance from the left edge. -### OH_ArkUI_NodeCustomEvent_GetUserData() +### OH_ArkUI_SwiperDigitIndicator_SetBottomPosition() ``` -void* OH_ArkUI_NodeCustomEvent_GetUserData (ArkUI_NodeCustomEvent * event) +void OH_ArkUI_SwiperDigitIndicator_SetBottomPosition(ArkUI_SwiperDigitIndicator* indicator, float value) ``` **Description** -Obtains custom event parameters through a custom component event. +Sets the distance from the digit-style navigation indicator to the bottom of the **Swiper** component. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to the custom component event. | - -**Returns** - -Returns the custom event parameters. - +| indicator | Pointer to a digit-style navigation indicator. | +| value | Distance from the digit-style navigation indicator to the bottom of the **Swiper** component. | -### OH_ArkUI_NodeCustomEvent_SetCustomSpanMetrics() +### OH_ArkUI_SwiperDigitIndicator_GetBottomPosition() ``` -int32_t OH_ArkUI_NodeCustomEvent_SetCustomSpanMetrics (ArkUI_NodeCustomEvent * event, ArkUI_CustomSpanMetrics * metrics ) +float OH_ArkUI_SwiperDigitIndicator_GetBottomPosition(ArkUI_SwiperDigitIndicator* indicator) ``` **Description** -Sets the measurement metrics of a custom span through a custom component event. +Obtains the distance from the digit-style navigation indicator to the bottom of the **Swiper** component. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to the custom component event. | -| metrics | Measurement metrics to set. | +| indicator | Pointer to a digit-style navigation indicator.| **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. A possible cause is that mandatory parameters are left unspecified. - +Returns the distance from the digit-style navigation indicator to the bottom of the **Swiper** component. -### OH_ArkUI_NodeEvent_GetDragEvent() +### OH_ArkUI_SwiperDigitIndicator_SetFontColor() ``` -ArkUI_DragEvent* OH_ArkUI_NodeEvent_GetDragEvent (ArkUI_NodeEvent * nodeEvent) +void OH_ArkUI_SwiperDigitIndicator_SetFontColor(ArkUI_SwiperDigitIndicator* indicator, uint32_t color) ``` **Description** -Obtains an **ArkUI_DragEvent** object from the specified **ArkUI_DragEvent** object. +Sets the font color of the digit-style navigation indicator for the **Swiper** component. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | Pointer to an **ArkUI_NodeEvent** object. | - -**Returns** - -Returns the pointer to an **ArkUI_DragEvent** object; returns null if the parameter passed in is invalid or is not a drag-related event. - +| indicator | Pointer to a digit-style navigation indicator. | +| color | Color, in 0xARGB format. For example, 0xFFFF0000 indicates red. | -### OH_ArkUI_NodeEvent_GetEventType() +### OH_ArkUI_SwiperDigitIndicator_GetFontColor() ``` -ArkUI_NodeEventType OH_ArkUI_NodeEvent_GetEventType (ArkUI_NodeEvent * event) +uint32_t OH_ArkUI_SwiperDigitIndicator_GetFontColor(ArkUI_SwiperDigitIndicator* indicator) ``` **Description** -Obtains the type of a component event. +Obtains the font color of the digit-style navigation indicator for the **Swiper** component. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to the component event. | +| indicator | Pointer to a digit-style navigation indicator.| **Returns** -Returns the type of the component event. - +Returns the color, in 0xARGB format. For example, 0xFFFF0000 indicates red. -### OH_ArkUI_NodeEvent_GetInputEvent() +### OH_ArkUI_SwiperDigitIndicator_SetSelectedFontColor() ``` -ArkUI_UIInputEvent* OH_ArkUI_NodeEvent_GetInputEvent (ArkUI_NodeEvent * event) +void OH_ArkUI_SwiperDigitIndicator_SetSelectedFontColor(ArkUI_SwiperDigitIndicator* indicator, uint32_t selectedColor) ``` **Description** -Obtains input event (for example, touch event) data for a component event. +Sets the font color of the selected digit-style navigation indicator for the **Swiper** component. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to the component event. | - -**Returns** - -Returns the pointer to the input event data. - +| indicator | Pointer to a digit-style navigation indicator. | +| selectedColor | Color, in 0xARGB format. For example, 0xFFFF0000 indicates red. | -### OH_ArkUI_NodeEvent_GetNodeComponentEvent() +### OH_ArkUI_SwiperDigitIndicator_GetSelectedFontColor() ``` -ArkUI_NodeComponentEvent* OH_ArkUI_NodeEvent_GetNodeComponentEvent (ArkUI_NodeEvent * event) +uint32_t OH_ArkUI_SwiperDigitIndicator_GetSelectedFontColor(ArkUI_SwiperDigitIndicator* indicator) ``` **Description** -Obtains the numerical data in a component event. +Obtains the font color of the selected digit-style navigation indicator for the **Swiper** component. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to the component event. | +| indicator | Pointer to a digit-style navigation indicator.| **Returns** -Returns the pointer to the numerical data. - +Returns the color, in 0xARGB format. For example, 0xFFFF0000 indicates red. -### OH_ArkUI_NodeEvent_GetNodeHandle() +### OH_ArkUI_SwiperDigitIndicator_SetFontSize() ``` -ArkUI_NodeHandle OH_ArkUI_NodeEvent_GetNodeHandle (ArkUI_NodeEvent * event) +void OH_ArkUI_SwiperDigitIndicator_SetFontSize(ArkUI_SwiperDigitIndicator* indicator, float size) ``` **Description** -Obtains the component object that triggers an event. +Sets the font size of the digit-style navigation indicator for the **Swiper** component. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to the component event. | - -**Returns** - -Component object that triggers the event. - +| indicator | Pointer to a digit-style navigation indicator. | +| size | Font size, in fp. | -### OH_ArkUI_NodeEvent_GetNumberValue() +### OH_ArkUI_SwiperDigitIndicator_GetFontSize() ``` -int32_t OH_ArkUI_NodeEvent_GetNumberValue (ArkUI_NodeEvent * event, int32_t index, ArkUI_NumberValue * value ) +float OH_ArkUI_SwiperDigitIndicator_GetFontSize(ArkUI_SwiperDigitIndicator* indicator) ``` **Description** -Obtains the numeric-type parameter of a component event. +Obtains the font size of the digit-style navigation indicator for the **Swiper** component. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to the component event. | -| index | Return value index. | -| value | Return value. | +| indicator | Pointer to a digit-style navigation indicator.| **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_NODE_EVENT_PARAM_INDEX_OUT_OF_RANGE** if the parameter length in the parameter event exceeds the limit. Returns **ARKUI_ERROR_CODE_NODE_EVENT_PARAM_INVALID** if the data does not exist in the component event. - +Font size, in fp. -### OH_ArkUI_NodeEvent_GetPreDragStatus() +### OH_ArkUI_SwiperDigitIndicator_SetSelectedFontSize() ``` -ArkUI_PreDragStatus OH_ArkUI_NodeEvent_GetPreDragStatus (ArkUI_NodeEvent * nodeEvent) +void OH_ArkUI_SwiperDigitIndicator_SetSelectedFontSize(ArkUI_SwiperDigitIndicator* indicator, float size) ``` **Description** -Obtains the state prior to a drop and drop operation. +Sets the font size of the selected digit-style navigation indicator for the **Swiper** component. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | ArkUI_NodeEvent node object. | - -**Returns** - -Returns the state prior to the drop and drop operation. +| indicator | Pointer to a digit-style navigation indicator. | +| size | Font size, in fp. | - -### OH_ArkUI_NodeEvent_GetStringAsyncEvent() +### OH_ArkUI_SwiperDigitIndicator_GetSelectedFontSize() ``` -ArkUI_StringAsyncEvent* OH_ArkUI_NodeEvent_GetStringAsyncEvent (ArkUI_NodeEvent * event) +float OH_ArkUI_SwiperDigitIndicator_GetSelectedFontSize(ArkUI_SwiperDigitIndicator* indicator) ``` **Description** -Obtains the string data in a component event. +Obtains the font size of the selected digit-style navigation indicator for the **Swiper** component. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to the component event. | +| indicator | Pointer to a digit-style navigation indicator.| **Returns** -ArkUI_StringAsyncEvent\Pointer to string data. - +Returns the font size, in fp. -### OH_ArkUI_NodeEvent_GetStringValue() +### OH_ArkUI_SwiperDigitIndicator_SetFontWeight() ``` -int32_t OH_ArkUI_NodeEvent_GetStringValue (ArkUI_NodeEvent * event, int32_t index, char ** string, int32_t * stringSize ) +void OH_ArkUI_SwiperDigitIndicator_SetFontWeight(ArkUI_SwiperDigitIndicator* indicator, ArkUI_FontWeight fontWeight) ``` **Description** -Obtains the string-type parameter of the component callback event. The string data is valid only during event callback and needs to be used outside event callback. You are advised to copy the string data. +Sets the font weight of the digit-style navigation indicator for the **Swiper** component. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to the component event. | -| index | Return value index. | -| string | Pointer to the string array. | -| stringSize | Length of the string array. | - -**Returns** - -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_NODE_EVENT_PARAM_INDEX_OUT_OF_RANGE** if the parameter length in the parameter event exceeds the limit. Returns **ARKUI_ERROR_CODE_NODE_EVENT_PARAM_INVALID** if the data does not exist in the component event. - +| indicator | Pointer to a digit-style navigation indicator. | +| fontWeight | Font weight, specified by an enumeration value of [ArkUI_FontWeight](#arkui_fontweight). | -### OH_ArkUI_NodeEvent_GetTargetId() +### OH_ArkUI_SwiperDigitIndicator_GetFontWeight() ``` -int32_t OH_ArkUI_NodeEvent_GetTargetId (ArkUI_NodeEvent * event) +ArkUI_FontWeight OH_ArkUI_SwiperDigitIndicator_GetFontWeight(ArkUI_SwiperDigitIndicator* indicator) ``` **Description** -Obtains the custom ID of a component event. - -The event ID is transferred as a parameter when the registerNodeEvent function is called and can be used in the distribution logic of the same event entry function registerNodeEventReceiver. + Obtains the font weight of the digit-style navigation indicator for the **Swiper** component. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to the component event. | +| indicator | Pointer to a digit-style navigation indicator.| **Returns** -Returns the custom ID of the component event. - +Returns the font weight, specified by an enumeration value of [ArkUI_FontWeight](#arkui_fontweight). -### OH_ArkUI_NodeEvent_GetUserData() +### OH_ArkUI_SwiperDigitIndicator_SetSelectedFontWeight() ``` -void* OH_ArkUI_NodeEvent_GetUserData (ArkUI_NodeEvent * event) +void OH_ArkUI_SwiperDigitIndicator_SetSelectedFontWeight(ArkUI_SwiperDigitIndicator* indicator, ArkUI_FontWeight fontWeight) ``` **Description** -Obtains the custom data in a component event. - -This parameter is passed in **registerNodeEvent** and can be applied to the service logic when the event is triggered. +Sets the font weight of the selected digit-style navigation indicator for the **Swiper** component. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to the component event. | - -**Returns** +| indicator | Pointer to a digit-style navigation indicator. | +| fontWeight | Font weight, specified by an enumeration value of [ArkUI_FontWeight](#arkui_fontweight). | -Returns the pointer to user data. - - -### OH_ArkUI_NodeEvent_SetReturnNumberValue() +### OH_ArkUI_SwiperDigitIndicator_GetSelectedFontWeight() ``` -int32_t OH_ArkUI_NodeEvent_SetReturnNumberValue (ArkUI_NodeEvent * event, ArkUI_NumberValue * value, int32_t size ) +ArkUI_FontWeight OH_ArkUI_SwiperDigitIndicator_GetSelectedFontWeight(ArkUI_SwiperDigitIndicator* indicator) ``` **Description** -Sets the return value for a component event. + Obtains the font weight of the selected digit-style navigation indicator for the **Swiper** component. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to the component event. | -| value | Event numeric type array. | -| size | Size of the array. | +| indicator | Pointer to a digit-style navigation indicator.| **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. The component event does not support return values. Returns **ARKUI_ERROR_CODE_NODE_EVENT_PARAM_INVALID** if the data does not exist in the component event. - +Returns the font weight, specified by an enumeration value of [ArkUI_FontWeight](#arkui_fontweight). -### OH_ArkUI_NodeUtils_AddCustomProperty() +### OH_ArkUI_SwiperDigitIndicator_Dispose ``` -void OH_ArkUI_NodeUtils_AddCustomProperty (ArkUI_NodeHandle node, const char * name, const char * value ) +void OH_ArkUI_SwiperDigitIndicator_Dispose(ArkUI_SwiperDigitIndicator* indicator) ``` **Description** -Sets a custom property for a component. This API takes effect only in the main thread. +Disposes of the digit-style navigation indicator of this **Swiper** component. -**Since**: 13 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | **ArkUI_NodeHandle** pointer. | -| name | Name of the custom property. A null pointer is not allowed. | -| value | Value of the custom property. A null pointer is not allowed. | - +| indicator | Pointer to a digit-style navigation indicator. | -### OH_ArkUI_NodeUtils_GetActiveChildrenInfo() +### OH_ArkUI_SwiperArrowStyle_Create() ``` -int32_t OH_ArkUI_NodeUtils_GetActiveChildrenInfo (ArkUI_NodeHandle head, ArkUI_ActiveChildrenInfo ** handle ) +ArkUI_SwiperArrowStyle *OH_ArkUI_SwiperArrowStyle_Create() ``` **Description** -Obtains all active child nodes of the specified node. Spans are not counted as child nodes. - -**Since**: 14 - -**Parameters** +Creates an arrow style for the **Swiper** component. -| Name| Description| -| -------- | -------- | -| head | Node for which to obtain the child nodes. | -| handle | Pointer to the struct containing information about the child nodes of the head node. | +**Since**: 15 **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. - +Returns the pointer to the arrow object. -### OH_ArkUI_NodeUtils_GetCurrentPageRootNode() +### OH_ArkUI_SwiperArrowStyle_SetShowBackground() ``` -ArkUI_NodeHandle OH_ArkUI_NodeUtils_GetCurrentPageRootNode (ArkUI_NodeHandle node) +void OH_ArkUI_SwiperArrowStyle_SetShowBackground(ArkUI_SwiperArrowStyle *arrowStyle, int32_t showBackground) ``` **Description** -Obtains the root node of the current page. +Sets whether to display the background of the arrow for the **Swiper** component. -**Since**: 14 +**Since**: 15 **Parameters** | Name| Description| | -------- | -------- | -| node | Target node. | - -**Returns** - -Returns the pointer to the root node if the node exists; returns **NULL** otherwise. +| arrowStyle | Pointer to the arrow object. | +| showBackground | Whether to show the arrow background. The value **1** means to show the background, and **0** means the opposite. The default value is **0**. | - -### OH_ArkUI_NodeUtils_GetCustomProperty() +### OH_ArkUI_SwiperArrowStyle_GetShowBackground() ``` -int32_t OH_ArkUI_NodeUtils_GetCustomProperty (ArkUI_NodeHandle node, const char * name, ArkUI_CustomProperty ** handle ) +int32_t OH_ArkUI_SwiperArrowStyle_GetShowBackground(ArkUI_SwiperArrowStyle* arrowStyle) ``` **Description** -Obtains the value of a custom property of the specified component. + Checks whether the background of the arrow is displayed for the **Swiper** component. -**Since**: 14 +**Since**: 15 **Parameters** | Name| Description| | -------- | -------- | -| node | **ArkUI_NodeHandle** pointer. | -| name | Name of the custom property. | -| handle | Pointer to the struct that receives the custom property corresponding to the key parameter name. | +| arrowStyle | Pointer to the arrow object.| **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. - +Returns whether the arrow background is displayed. The value **1** means that the background is displayed, and **0** means the opposite. -### OH_ArkUI_NodeUtils_GetLayoutPosition() +### OH_ArkUI_SwiperArrowStyle_SetShowSidebarMiddle() ``` -int32_t OH_ArkUI_NodeUtils_GetLayoutPosition (ArkUI_NodeHandle node, ArkUI_IntOffset * localOffset ) +void OH_ArkUI_SwiperArrowStyle_SetShowSidebarMiddle(ArkUI_SwiperArrowStyle *arrowStyle, int32_t showSidebarMiddle) ``` **Description** -Obtains the position of the component's layout area relative to its parent component. The relative position does not count in transformation attributes, such as translate. +Sets the position of the arrow for the **Swiper** component. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | **ArkUI_NodeHandle** pointer. | -| localOffset | Offset of the component handle relative to the parent component, in pixels. | - -**Returns** - -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +| arrowStyle | Pointer to the arrow object. | +| showSidebarMiddle | Position of the arrow. **0**: The arrow is displayed on both sides of the navigation indicator. **1**: The arrow is displayed on both sides of the **Swiper** component. The default value is **0**. | - -### OH_ArkUI_NodeUtils_GetLayoutPositionInScreen() +### OH_ArkUI_SwiperArrowStyle_GetShowSidebarMiddle() ``` -int32_t OH_ArkUI_NodeUtils_GetLayoutPositionInScreen (ArkUI_NodeHandle node, ArkUI_IntOffset * screenOffset ) +int32_t OH_ArkUI_SwiperArrowStyle_GetShowSidebarMiddle(ArkUI_SwiperArrowStyle* arrowStyle) ``` **Description** -Obtains the position of the component's layout area relative to the screen. The relative position does not count in transformation attributes, such as translate. +Obtains the position of the arrow for the **Swiper** component. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | **ArkUI_NodeHandle** pointer. | -| screenOffset | Offset of the component handle relative to the screen, in pixels. | +| arrowStyle | Pointer to the arrow object.| **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. - +Returns the position of the arrow. **0**: The arrow is displayed on both sides of the navigation indicator. **1**: The arrow is displayed on both sides of the **Swiper** component. -### OH_ArkUI_NodeUtils_GetLayoutPositionInWindow() +### OH_ArkUI_SwiperArrowStyle_SetBackgroundSize() ``` -int32_t OH_ArkUI_NodeUtils_GetLayoutPositionInWindow (ArkUI_NodeHandle node, ArkUI_IntOffset * globalOffset ) +void OH_ArkUI_SwiperArrowStyle_SetBackgroundSize(ArkUI_SwiperArrowStyle* arrowStyle, float backgroundSize) ``` **Description** -Obtains the position of the component's layout area relative to the window. The relative position does not count in transformation attributes, such as translate. +Sets the background size for the arrow of the **Swiper** component. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| -| -------- | -------- | -| node | **ArkUI_NodeHandle** pointer. | -| globalOffset | Offset of the component handle relative to the window, in pixels. | - -**Returns** - -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. - +| Name| Description| +| -------- | -------- | +| arrowStyle | Pointer to the arrow object. | +| backgroundSize | Background size of the arrow, in vp. Default value: 24 vp when displayed on both sides of the navigation indicator and 32 vp when displayed on both sides of the **Swiper** component. | -### OH_ArkUI_NodeUtils_GetLayoutSize() +### OH_ArkUI_SwiperArrowStyle_GetBackgroundSize() ``` -int32_t OH_ArkUI_NodeUtils_GetLayoutSize (ArkUI_NodeHandle node, ArkUI_IntSize * size ) +float OH_ArkUI_SwiperArrowStyle_GetBackgroundSize(ArkUI_SwiperArrowStyle* arrowStyle) ``` **Description** -Obtains the layout area size of a component. The size does not count in transformation attributes, such as scale. +Obtains the background size of the arrow of the **Swiper** component. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | **ArkUI_NodeHandle** pointer. | -| size | Size of the layout area, in px. | +| arrowStyle | Pointer to the arrow object.| **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. - +Returns the background size of the arrow, in vp. -### OH_ArkUI_NodeUtils_GetNodeType() +### OH_ArkUI_SwiperArrowStyle_SetBackgroundColor() ``` -int32_t OH_ArkUI_NodeUtils_GetNodeType (ArkUI_NodeHandle node) +void OH_ArkUI_SwiperArrowStyle_SetBackgroundColor(ArkUI_SwiperArrowStyle* arrowStyle, uint32_t backgroundColor) ``` **Description** -Obtains the type of the specified node. +Sets the background color for the arrow of the **Swiper** component. -**Since**: 14 +**Since**: 15 **Parameters** | Name| Description| | -------- | -------- | -| node | Target node. | - -**Returns** - -Returns the type of the node. Returns **-1** if the type is not supported yet. For details about the available types, see [ArkUI_NodeType](#arkui_nodetype). - +| arrowStyle | Pointer to the arrow object. | +| backgroundColor | Background color of the arrow, in 0xARGB format. For example, 0xFFFF0000 indicates red. | -### OH_ArkUI_NodeUtils_GetParentInPageTree() +### OH_ArkUI_SwiperArrowStyle_GetBackgroundColor() ``` -ArkUI_NodeHandle OH_ArkUI_NodeUtils_GetParentInPageTree (ArkUI_NodeHandle node) +uint32_t OH_ArkUI_SwiperArrowStyle_GetBackgroundColor(ArkUI_SwiperArrowStyle* arrowStyle) ``` **Description** -Obtains the parent node, which can be a component node created with ArkTS. +Obtains the background color for the arrow of the **Swiper** component. -**Since**: 14 +**Since**: 15 **Parameters** | Name| Description| | -------- | -------- | -| node | Target node. | +| arrowStyle | Pointer to the arrow object.| **Returns** -Returns the pointer to the component if the component exists; returns **NULL** otherwise. - +Returns the background color of the arrow, in 0xARGB format. For example, 0xFFFF0000 indicates red. -### OH_ArkUI_NodeUtils_GetPositionWithTranslateInScreen() +### OH_ArkUI_SwiperArrowStyle_SetArrowSize() ``` -int32_t OH_ArkUI_NodeUtils_GetPositionWithTranslateInScreen (ArkUI_NodeHandle node, ArkUI_IntOffset * translateOffset ) +void OH_ArkUI_SwiperArrowStyle_SetArrowSize(ArkUI_SwiperArrowStyle* arrowStyle, float arrowSize) ``` **Description** -Obtains the position of a component on the screen, including the translate attribute. +Sets the size for the arrow of the **Swiper** component. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | **ArkUI_NodeHandle** pointer. | -| translateOffset | Accumulated offset of the component, its parent component, and its ancestor node, in px. | - -**Returns** - -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. - +| arrowStyle | Pointer to the arrow object. | +| arrowSize | Size of the arrow, in vp. Default value: 18 vp when displayed on both sides of the navigation indicator and 24 vp when displayed on both sides of the **Swiper** component. When the arrow background is displayed, the value of **arrowSize** is fixed at 3/4 of the value of **backgroundSize**.| -### OH_ArkUI_NodeUtils_GetPositionWithTranslateInWindow() +### OH_ArkUI_SwiperArrowStyle_GetArrowSize() ``` -int32_t OH_ArkUI_NodeUtils_GetPositionWithTranslateInWindow (ArkUI_NodeHandle node, ArkUI_IntOffset * translateOffset ) +float OH_ArkUI_SwiperArrowStyle_GetArrowSize(ArkUI_SwiperArrowStyle* arrowStyle) ``` **Description** -Obtains the position of a component in the window, including the translate attribute. +Obtains the size of the arrow of the **Swiper** component. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | **ArkUI_NodeHandle** pointer. | -| translateOffset | Accumulated offset of the component, its parent component, and its ancestor node, in px. | +| arrowStyle | Pointer to the arrow object.| **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. - +Returns the size of the arrow, in vp. -### OH_ArkUI_NodeUtils_IsCreatedByNDK() +### OH_ArkUI_SwiperArrowStyle_SetArrowColor() ``` -bool OH_ArkUI_NodeUtils_IsCreatedByNDK (ArkUI_NodeHandle node) +void OH_ArkUI_SwiperArrowStyle_SetArrowColor(ArkUI_SwiperArrowStyle* arrowStyle, uint32_t arrowColor) ``` **Description** -Checks whether the specified component is created with the C API. +Sets the color for the arrow of the **Swiper** component. -**Since**: 14 +**Since**: 15 **Parameters** | Name| Description| | -------- | -------- | -| node | Target node. | - -**Returns** - -Returns whether the node is created with the C API. The value **true** means that the node is created with the C API, and **false** means the opposite. - +| arrowStyle | Pointer to the arrow object. | +| arrowColor | Color of the arrow, in 0xARGB format. For example, 0xFFFF0000 indicates red.| -### OH_ArkUI_NodeUtils_RemoveCustomProperty() +### OH_ArkUI_SwiperArrowStyle_GetArrowColor() ``` -void OH_ArkUI_NodeUtils_RemoveCustomProperty (ArkUI_NodeHandle node, const char * name ) +uint32_t OH_ArkUI_SwiperArrowStyle_GetArrowColor(ArkUI_SwiperArrowStyle* arrowStyle) ``` **Description** -Removes a custom property that has been set for the specified component. +Obtains the color of the arrow of the **Swiper** component. -**Since**: 13 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | **ArkUI_NodeHandle** pointer. | -| name | Name of the custom property. | +| arrowStyle | Pointer to the arrow object.| +**Returns** -### OH_ArkUI_PanGesture_GetOffsetX() +Returns the color of the arrow, in 0xARGB format. For example, 0xFFFF0000 indicates red. + +### OH_ArkUI_SwiperArrowStyle_Dispose ``` -float OH_ArkUI_PanGesture_GetOffsetX (const ArkUI_GestureEvent * event) +void OH_ArkUI_SwiperArrowStyle_Dispose(ArkUI_SwiperArrowStyle* arrowStyle) ``` **Description** -Obtains the relative offset of a pan gesture along the x-axis. +Disposes of the arrow of the **Swiper** component. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Gesture event. | - -**Returns** +| arrowStyle | Pointer to the arrow object. | -Returns the relative offset of the gesture along the x-axis, in px. - - -### OH_ArkUI_PanGesture_GetOffsetY() +### OH_ArkUI_SwiperIndicator_GetSelectedColor() ``` -float OH_ArkUI_PanGesture_GetOffsetY (const ArkUI_GestureEvent * event) +uint32_t OH_ArkUI_SwiperIndicator_GetSelectedColor (ArkUI_SwiperIndicator * indicator) ``` **Description** -Obtains the relative offset of a pan gesture along the y-axis. +Obtains the color of the selected dot-style navigation indicator of the **Swiper** component. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Gesture event. | +| indicator | Returns the pointer to the navigation indicator. | **Returns** -Returns the relative offset of the gesture along the y-axis, in px. +Returns the color, in 0xARGB format. For example, 0xFFFF0000 indicates red. -### OH_ArkUI_PanGesture_GetVelocity() +### OH_ArkUI_SwiperIndicator_GetSelectedItemHeight() ``` -float OH_ArkUI_PanGesture_GetVelocity (const ArkUI_GestureEvent * event) +float OH_ArkUI_SwiperIndicator_GetSelectedItemHeight (ArkUI_SwiperIndicator * indicator) ``` **Description** -Obtains the velocity of a pan gesture along the main axis. +Obtains the height of the selected dot-style navigation indicator of the **Swiper** component. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Gesture event. | +| indicator | Returns the pointer to the navigation indicator. | **Returns** -Returns the velocity of the pan gesture along the main axis, in px/s. The value is the square root of the sum of the squares of the velocity on the x-axis and y-axis. +Returns the height of the dot-style navigation indicator. -### OH_ArkUI_PanGesture_GetVelocityX() +### OH_ArkUI_SwiperIndicator_GetSelectedItemWidth() ``` -float OH_ArkUI_PanGesture_GetVelocityX (const ArkUI_GestureEvent * event) +float OH_ArkUI_SwiperIndicator_GetSelectedItemWidth (ArkUI_SwiperIndicator * indicator) ``` **Description** -Obtains the velocity of a pan gesture along the x-axis. +Obtains the width of the selected dot-style navigation indicator of the **Swiper** component. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Gesture event. | +| indicator | Returns the pointer to the navigation indicator. | **Returns** -Returns the velocity of the pan gesture along the x-axis, in px/s. +Returns the width of the dot-style navigation indicator. -### OH_ArkUI_PanGesture_GetVelocityY() +### OH_ArkUI_SwiperIndicator_GetStartPosition() ``` -float OH_ArkUI_PanGesture_GetVelocityY (const ArkUI_GestureEvent * event) +float OH_ArkUI_SwiperIndicator_GetStartPosition (ArkUI_SwiperIndicator * indicator) ``` **Description** -Obtains the velocity of a pan gesture along the y-axis. +Obtains the distance between a navigation indicator and the left edge of the **Swiper** component. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Gesture event. | +| indicator | Returns the pointer to the navigation indicator. | **Returns** -Returns the velocity of the pan gesture along the y-axis, in px/s. +Returns the distance between the navigation indicator and the left edge of the **Swiper** component. -### OH_ArkUI_ParallelInnerGestureEvent_GetConflictRecognizers() +### OH_ArkUI_SwiperIndicator_GetTopPosition() ``` -int32_t OH_ArkUI_ParallelInnerGestureEvent_GetConflictRecognizers (ArkUI_ParallelInnerGestureEvent * event, ArkUI_GestureRecognizerHandleArray * array, int32_t * size ) +float OH_ArkUI_SwiperIndicator_GetTopPosition (ArkUI_SwiperIndicator * indicator) ``` **Description** -Obtains the conflicting gesture recognizers in a parallel internal gesture event. +Obtains the distance between the navigation indicator and the top edge of the **Swiper** component. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Parallel internal gesture event. | -| array | Array of conflicting gesture recognizers. | -| size | Size of the conflicting gesture recognizer array. | +| indicator | Returns the pointer to the navigation indicator. | **Returns** -Returns **0** if the operation is successful. Returns **401** if a parameter error occurs. +Returns the distance between a navigation indicator and the top edge of the **Swiper** component. -### OH_ArkUI_ParallelInnerGestureEvent_GetCurrentRecognizer() +### OH_ArkUI_SwiperIndicator_SetBottomPosition() ``` -ArkUI_GestureRecognizer* OH_ArkUI_ParallelInnerGestureEvent_GetCurrentRecognizer (ArkUI_ParallelInnerGestureEvent * event) +void OH_ArkUI_SwiperIndicator_SetBottomPosition (ArkUI_SwiperIndicator * indicator, float value ) ``` **Description** -Obtains the current gesture recognizer in a parallel internal gesture event. +Sets the distance between the navigation indicator and the bottom edge of the **Swiper** component. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Parallel internal gesture event. | - -**Returns** - -Returns the pointer to the current gesture recognizer. +| indicator | Pointer to a navigation indicator. | +| value | Distance between a navigation indicator and the bottom edge of the **Swiper** component. | -### OH_ArkUI_ParallelInnerGestureEvent_GetUserData() +### OH_ArkUI_SwiperIndicator_SetColor() ``` -void* OH_ArkUI_ParallelInnerGestureEvent_GetUserData (ArkUI_ParallelInnerGestureEvent * event) +void OH_ArkUI_SwiperIndicator_SetColor (ArkUI_SwiperIndicator * indicator, uint32_t color ) ``` **Description** -Obtains custom data in the parallel internal gesture event. +Sets the color of a dot-style navigation indicator for the **Swiper** component. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Parallel internal gesture event. | - -**Returns** - -Returns the pointer to custom data. +| indicator | Returns the pointer to the navigation indicator. | +| color | Color, in 0xARGB format. For example, 0xFFFF0000 indicates red. | -### OH_ArkUI_PinchGesture_GetCenterX() +### OH_ArkUI_SwiperIndicator_SetEndPosition() ``` -float OH_ArkUI_PinchGesture_GetCenterX (const ArkUI_GestureEvent * event) +void OH_ArkUI_SwiperIndicator_SetEndPosition (ArkUI_SwiperIndicator * indicator, float value ) ``` **Description** -Obtains the X coordinate of the center of the pinch gesture, in vp, relative to the upper left corner of the current component. +Distance between the navigation indicator and the left edge of the **Swiper** component. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Gesture event. | - -**Returns** -Returns the X coordinate of the center of the pinch gesture, in vp, relative to the upper left corner of the current component. +| indicator | Pointer to a navigation indicator. | +| value | Returns the distance between the navigation indicator and the right edge of the **Swiper** component. | -### OH_ArkUI_PinchGesture_GetCenterY() +### OH_ArkUI_SwiperIndicator_SetItemHeight() ``` -float OH_ArkUI_PinchGesture_GetCenterY (const ArkUI_GestureEvent * event) +void OH_ArkUI_SwiperIndicator_SetItemHeight (ArkUI_SwiperIndicator * indicator, float value ) ``` **Description** -Obtains the Y coordinate of the center of the pinch gesture, in vp, relative to the upper left corner of the current component. +Sets the height of a dot-style navigation indicator for the **Swiper** component. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Gesture event. | - -**Returns** - -Returns the Y coordinate of the center of the pinch gesture, in vp, relative to the upper left corner of the current component. +| indicator | Pointer to a navigation indicator. | +| value | Returns the height of the dot-style navigation indicator. | -### OH_ArkUI_PinchGesture_GetScale() +### OH_ArkUI_SwiperIndicator_SetItemWidth() ``` -float OH_ArkUI_PinchGesture_GetScale (const ArkUI_GestureEvent * event) +void OH_ArkUI_SwiperIndicator_SetItemWidth (ArkUI_SwiperIndicator * indicator, float value ) ``` **Description** -Obtains the scale ratio of a pinch gesture. +Sets the width of a dot-style navigation indicator for the **Swiper** component. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Gesture event. | - -**Returns** - -Scale. +| indicator | Pointer to a navigation indicator. | +| value | Returns the width of the dot-style navigation indicator. | -### OH_ArkUI_QueryModuleInterfaceByName() +### OH_ArkUI_SwiperIndicator_SetMask() ``` -void* OH_ArkUI_QueryModuleInterfaceByName (ArkUI_NativeAPIVariantKind type, const char * structName ) +void OH_ArkUI_SwiperIndicator_SetMask (ArkUI_SwiperIndicator * indicator, int32_t mask ) ``` **Description** -Obtains the native API set of a specified type. +Sets whether to enable the mask for a dot-style navigation indicator for the **Swiper** component. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| type | Type of the native API set provided by ArkUI, for example, **ARKUI_NATIVE_NODE** or **ARKUI_NATIVE_GESTURE**. | -| sturctName | Name of a native struct defined in the corresponding header file, for example, **ArkUI_NativeNodeAPI_1** in <arkui/native_node.h>. | - -**Returns** - -Returns the pointer to the abstract native API, which can be used after being converted into a specific type. \#include<arkui/native_interface.h> \#include<arkui/native_node.h> \#include<arkui/native_gesture.h> auto\* anyNativeAPI = [OH_ArkUI_QueryModuleInterfaceByName](#oh_arkui_querymoduleinterfacebyname)(ARKUI_NATIVE_NODE, "ArkUI_NativeNodeAPI_1"); if (anyNativeAPI) { auto nativeNodeApi = reinterpret_cast<[ArkUI_NativeNodeAPI_1](_ark_u_i___native_node_a_p_i__1.md)\*>(anyNativeAPI); } auto anyGestureAPI = OH_ArkUI_QueryModuleInterface(ARKUI_NATIVE_GESTURE, "ArkUI_NativeGestureAPI_1"); if (anyNativeAPI) { auto basicGestureApi = reinterpret_cast<[ArkUI_NativeGestureAPI_1](_ark_u_i___native_gesture_a_p_i__1.md)\*>(anyGestureAPI); } +| indicator | Pointer to a navigation indicator. | +| mask | Whether to enable the mask. The value **1** means to enable the mask, and **0** means the opposite. | -### OH_ArkUI_RegisterSystemColorModeChangeEvent() +### OH_ArkUI_SwiperIndicator_SetMaxDisplayCount() ``` -int32_t OH_ArkUI_RegisterSystemColorModeChangeEvent (ArkUI_NodeHandle node, void * userData, void(*)(ArkUI_SystemColorMode colorMode, void *userData) onColorModeChange ) +int32_t OH_ArkUI_SwiperIndicator_SetMaxDisplayCount (ArkUI_SwiperIndicator * indicator, int32_t maxDisplayCount ) ``` **Description** -Registers an event listener for system color mode changes. A single component can only register one callback for system color mode changes. +Sets the maximum number of dots for the dot-style navigation indicator. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | Specified node. | -| userData | Custom event parameter, which is passed in the callback when the event is triggered. | -| onColorModeChange | Callback to be executed when the event is triggered. | +| indicator | Pointer to a navigation indicator. | +| maxDisplayCount | Maximum number of navigation points. The value ranges from 6 to 9. | **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. Returns **ARKUI_ERROR_CODE_ATTRIBUTE_OR_EVENT_NOT_SUPPORTED** if the event is not supported. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if **maxDisplayCount** is set to an invalid value. -### OH_ArkUI_RegisterSystemFontStyleChangeEvent() +### OH_ArkUI_SwiperIndicator_SetSelectedColor() ``` -int32_t OH_ArkUI_RegisterSystemFontStyleChangeEvent (ArkUI_NodeHandle node, void * userData, void(*)(ArkUI_SystemFontStyleEvent *event, void *userData) onFontStyleChange ) +void OH_ArkUI_SwiperIndicator_SetSelectedColor (ArkUI_SwiperIndicator * indicator, uint32_t selectedColor ) ``` **Description** -Registers an event listener for system font style changes. A single component can only register one callback for system font style changes. +Sets the color of the selected dot-style navigation indicator for the **Swiper** component. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | Specified node. | -| userData | Custom event parameter, which is passed in the callback when the event is triggered. | -| onFontStyleChange | Callback to be executed when the event is triggered. | - -**Returns** - -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. Returns **ARKUI_ERROR_CODE_ATTRIBUTE_OR_EVENT_NOT_SUPPORTED** if the event is not supported. +| indicator | Pointer to a navigation indicator. | +| selectedColor | Color, in 0xARGB format. For example, 0xFFFF0000 indicates red. | -### OH_ArkUI_RotationGesture_GetAngle() +### OH_ArkUI_SwiperIndicator_SetSelectedItemHeight() ``` -float OH_ArkUI_RotationGesture_GetAngle (const ArkUI_GestureEvent * event) +void OH_ArkUI_SwiperIndicator_SetSelectedItemHeight (ArkUI_SwiperIndicator * indicator, float value ) ``` **Description** -Obtains the angle information of a rotation gesture. +Sets the height of the selected dot-style navigation indicator for the **Swiper** component. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Gesture event. | - -**Returns** - -Rotation angle. +| indicator | Pointer to a navigation indicator. | +| value | Height of the dot-style navigation indicator. | -### OH_ArkUI_SetArkUIGestureRecognizerDisposeNotify() +### OH_ArkUI_SwiperIndicator_SetSelectedItemWidth() ``` -int32_t OH_ArkUI_SetArkUIGestureRecognizerDisposeNotify (ArkUI_GestureRecognizer * recognizer, ArkUI_GestureRecognizerDestructNotifyCallback callback, void * userData ) +void OH_ArkUI_SwiperIndicator_SetSelectedItemWidth (ArkUI_SwiperIndicator * indicator, float value ) ``` **Description** -Sets a callback function for notifying gesture recognizer destruction. +Sets the width of the selected dot-style navigation indicator for the **Swiper** component. + +**Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| recognizer | Pointer to the gesture recognizer. | -| callback | Callback function for notifying gesture recognizer destruction. | -| userData | Custom data. | - -**Returns** - -Returns **0** if the operation is successful. Returns **401** if a parameter error occurs. +| indicator | Pointer to a navigation indicator. | +| value | Width of the dot-style navigation indicator. | -### OH_ArkUI_SetDragEventStrictReportWithContext() +### OH_ArkUI_SwiperIndicator_SetStartPosition() ``` -int32_t OH_ArkUI_SetDragEventStrictReportWithContext (ArkUI_ContextHandle uiContext, bool enabled ) +void OH_ArkUI_SwiperIndicator_SetStartPosition (ArkUI_SwiperIndicator * indicator, float value ) ``` **Description** -Sets whether to enable strict reporting on drag events. This feature is disabled by default, and you are advised to enable it. If this feature is disabled, the parent component is not notified when an item in it is dragged over its child component. If this feature is enabled, the component is notified of the dragged item's leaving, and the child component to which the dragged item is dropped is notified of the item's entering. This configuration is related to a specific UI instance. You can pass in a UI instance for association. +Sets the distance between the navigation indicator and the left edge of the **Swiper** component. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| uiContext | Pointer to the UI instance. | -| enabled | Whether to enable strict reporting on drag events. | - -**Returns** - -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +| indicator | Pointer to a navigation indicator. | +| value | Distance between the navigation indicator and the left edge of the **Swiper** component. | -### OH_ArkUI_SetDragEventStrictReportWithNode() +### OH_ArkUI_SwiperIndicator_SetTopPosition() ``` -int32_t OH_ArkUI_SetDragEventStrictReportWithNode (ArkUI_NodeHandle node, bool enabled ) +void OH_ArkUI_SwiperIndicator_SetTopPosition (ArkUI_SwiperIndicator * indicator, float value ) ``` **Description** -Sets whether to enable strict reporting on drag events. This feature is disabled by default, and you are advised to enable it. If this feature is disabled, the parent component is not notified when an item in it is dragged over its child component. If this feature is enabled, the component is notified of the dragged item's leaving, and the child component to which the dragged item is dropped is notified of the item's entering. This configuration is related to a specific UI instance. You can pass in a specific component node on the current UI instance for association. +Sets the distance between the navigation indicator and the top edge of the **Swiper** component. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | Pointer to a component node. | -| enabled | Whether to enable strict reporting on drag events. | - -**Returns** - -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +| indicator | Pointer to a navigation indicator. | +| value | Distance between a navigation indicator and the top edge of the **Swiper** component. | -### OH_ArkUI_SetGestureRecognizerEnabled() +### OH_ArkUI_SystemFontStyleEvent_GetFontSizeScale() ``` -int32_t OH_ArkUI_SetGestureRecognizerEnabled (ArkUI_GestureRecognizer * recognizer, bool enabled ) +float OH_ArkUI_SystemFontStyleEvent_GetFontSizeScale (const ArkUI_SystemFontStyleEvent * event) ``` **Description** -Sets the enabled state of a gesture recognizer. +Obtains the font size scale from the system font style change event. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| recognizer | Pointer to the gesture recognizer. | -| enabled | Whether to enable notification. | +| event | Pointer to the current system font style change event. | **Returns** -Returns **0** if the operation is successful. Returns **401** if a parameter error occurs. +Returns the font size scale after the change. Default value: **1.0**. -### OH_ArkUI_SetNodeAllowedDropDataTypes() +### OH_ArkUI_SystemFontStyleEvent_GetFontWeightScale() ``` -int32_t OH_ArkUI_SetNodeAllowedDropDataTypes (ArkUI_NodeHandle node, const char * typesArray[], int32_t count ) +float OH_ArkUI_SystemFontStyleEvent_GetFontWeightScale (const ArkUI_SystemFontStyleEvent * event) ``` **Description** -Sets the types of data that can be dropped to the specified component. This API resets the settings configured through [OH_ArkUI_DisallowNodeAnyDropDataTypes](#oh_arkui_disallownodeanydropdatatypes) or [OH_ArkUI_AllowNodeAllDropDataTypes](#oh_arkui_allownodealldropdatatypes). +Obtains the font weight scale from the system font style change event. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | Pointer to a component node. | -| typesArray | Array of data types that can fall into. | -| count | Length of an array. | +| event | Pointer to the current system font style change event. | **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +Returns the font weight scale after the change. Default value: **1.0**. -### OH_ArkUI_SetNodeDraggable() +### OH_ArkUI_TransitionEffect_Combine() ``` -int32_t OH_ArkUI_SetNodeDraggable (ArkUI_NodeHandle node, bool enabled ) +int32_t OH_ArkUI_TransitionEffect_Combine (ArkUI_TransitionEffect * option, ArkUI_TransitionEffect * combine ) ``` **Description** -Sets whether the component is draggable. +Sets a combination of transition effects. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | Pointer to a component node. | -| bool | Whether the component is draggable. | +| option | Transition effect options. | +| combine | Combination of transition effects. | **Returns** Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_SetNodeDragPreview() +### OH_ArkUI_TransitionEffect_Dispose() ``` -int32_t OH_ArkUI_SetNodeDragPreview (ArkUI_NodeHandle node, OH_PixelmapNative * preview ) +void OH_ArkUI_TransitionEffect_Dispose (ArkUI_TransitionEffect * option) ``` **Description** -Sets a custom drag preview for the specified component. +Destroys a transition effect object. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | Pointer to the target component node. | -| preview | Custom drag preview, which is a pixel map. | - -**Returns** - -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +| option | Transition effect object. | -### OH_ArkUI_SetNodeDragPreviewOption() +### OH_ArkUI_TransitionEffect_SetAnimation() ``` -int32_t OH_ArkUI_SetNodeDragPreviewOption (ArkUI_NodeHandle node, ArkUI_DragPreviewOption * option ) +int32_t OH_ArkUI_TransitionEffect_SetAnimation (ArkUI_TransitionEffect * option, ArkUI_AnimateOption * animation ) ``` **Description** -Sets an **ArkUI_DragPreviewOption** object for the specified component. +Sets transition effect animation settings. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | Pointer to a component node. | -| option | Custom parameters. | +| option | Transition effect options. | +| animation | Animation settings. | + +**NOTE** + +If **combine** is used for combining transition effects, the animation settings of a transition effect are applicable to the one following it. **Returns** Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_StartDrag() +### OH_ArkUI_UnmarshallStyledStringDescriptor() ``` -int32_t OH_ArkUI_StartDrag (ArkUI_DragAction * dragAction) +int32_t OH_ArkUI_UnmarshallStyledStringDescriptor (uint8_t * buffer, size_t bufferSize, ArkUI_StyledString_Descriptor * descriptor, size_t * resultSize ) ``` **Description** -Initiates a drag action through the specified drag action object. +Deserializes a byte array containing styled string information into a styled string. -**Since**: 12 +**Since**: 14 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| dragAction | Drag action object. | +| buffer | Byte array to be deserialized. | +| bufferSize | Length of the byte array. | +| descriptor | Pointer to an **ArkUI_StyledString_Descriptor** object. | +| resultSize | Actual length of the resulting byte array after deserialization. | **Returns** Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_StyledString_AddPlaceholder() +### OH_ArkUI_UnregisterSystemColorModeChangeEvent() ``` -void OH_ArkUI_StyledString_AddPlaceholder (ArkUI_StyledString * handle, OH_Drawing_PlaceholderSpan * placeholder ) +void OH_ArkUI_UnregisterSystemColorModeChangeEvent (ArkUI_NodeHandle node) ``` **Description** -Adds a placeholder. +Unregisters the event listener for system color mode changes. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| handle | Pointer to an **ArkUI_StyledString** object. | -| placeholder | Pointer to an **OH_Drawing_PlaceholderSpan** object. | +| node | Specified node. | -### OH_ArkUI_StyledString_AddText() +### OH_ArkUI_UnregisterSystemFontStyleChangeEvent() ``` -void OH_ArkUI_StyledString_AddText (ArkUI_StyledString * handle, const char * content ) +void OH_ArkUI_UnregisterSystemFontStyleChangeEvent (ArkUI_NodeHandle node) ``` **Description** -Sets the text content based on the current format string style. +Unregisters the event listener for system font style changes. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| handle | Pointer to an **ArkUI_StyledString** object. | -| content | Pointer to the text content. | +| node | Specified node. | -### OH_ArkUI_StyledString_Create() +### OH_ArkUI_WaterFlowSectionOption_Create() ``` -ArkUI_StyledString* OH_ArkUI_StyledString_Create (OH_Drawing_TypographyStyle * style, OH_Drawing_FontCollection * collection ) +ArkUI_WaterFlowSectionOption* OH_ArkUI_WaterFlowSectionOption_Create () ``` **Description** -Creates an **ArkUI_StyledString** object. +Creates a water flow section configuration. **Since**: 12 -**Parameters** - -| Name| Description| -| -------- | -------- | -| style | Pointer to an **OH_Drawing_TypographyStyle** object, which is obtained by calling **OH_Drawing_CreateTypographyStyle**. | -| collection | Pointer to an **OH_Drawing_FontCollection** object, which is obtained by calling **OH_Drawing_CreateFontCollection**. | - **Returns** -Returns the pointer to the **ArkUI_StyledString** object created. If a null pointer is returned, the creation fails. A possible cause is that the application address space is full, or a parameter error, for example, a null pointer for the **style** or **collection** parameter, occurs. +Return the pointer to the created water flow section configuration. -### OH_ArkUI_StyledString_CreateTypography() +### OH_ArkUI_WaterFlowSectionOption_Dispose() ``` -OH_Drawing_Typography* OH_ArkUI_StyledString_CreateTypography (ArkUI_StyledString * handle) +void OH_ArkUI_WaterFlowSectionOption_Dispose (ArkUI_WaterFlowSectionOption * option) ``` **Description** -Creates an **OH_Drawing_Typography** object based on an **ArkUI_StyledString** object. +Disposes of the pointer to a water flow section configuration. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| handle | Pointer to an **ArkUI_StyledString** object. | - -**Returns** - -Returns the pointer to the **OH_Drawing_Typography** object created. If a null pointer is returned, the creation fails. A possible cause is that a parameter error, for example, a null pointer for the **handle** parameter, occurs. +| option | Pointer to a water flow section configuration. | -### OH_ArkUI_StyledString_Descriptor_Create() +### OH_ArkUI_WaterFlowSectionOption_GetColumnGap() ``` -ArkUI_StyledString_Descriptor* OH_ArkUI_StyledString_Descriptor_Create (void ) +float OH_ArkUI_WaterFlowSectionOption_GetColumnGap (ArkUI_WaterFlowSectionOption * option, int32_t index ) ``` **Description** -Creates an **ArkUI_StyledString_Descriptor** object. +Obtains the gap between columns in the water flow section that matches the specified index. -**Since**: 14 +**Since**: 12 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| option | Pointer to a water flow section configuration. | +| index | Index of the target water flow section. | **Returns** -Pointer to an **ArkUI_StyledString_Descriptor** object. +Returns the gap between columns. -### OH_ArkUI_StyledString_Descriptor_Destroy() +### OH_ArkUI_WaterFlowSectionOption_GetCrossCount() ``` -void OH_ArkUI_StyledString_Descriptor_Destroy (ArkUI_StyledString_Descriptor * descriptor) +int32_t OH_ArkUI_WaterFlowSectionOption_GetCrossCount (ArkUI_WaterFlowSectionOption * option, int32_t index ) ``` **Description** -Destroys an **ArkUI_StyledString_Descriptor** object and reclaims the memory occupied by the object. +Obtains the number of columns (in a vertical layout) or rows (in a horizontal layout) of a water flow. -**Since**: 14 +**Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| descriptor | Pointer to an **ArkUI_StyledString_Descriptor** object. | +| option | Pointer to a water flow section configuration. | +| index | Index of the target water flow section. | +**Returns** -### OH_ArkUI_StyledString_Destroy() +Returns the number of columns (in a vertical layout) or rows (in a horizontal layout) of a water flow. + + +### OH_ArkUI_WaterFlowSectionOption_GetItemCount() ``` -void OH_ArkUI_StyledString_Destroy (ArkUI_StyledString * handle) +int32_t OH_ArkUI_WaterFlowSectionOption_GetItemCount (ArkUI_WaterFlowSectionOption * option, int32_t index ) ``` **Description** -Destroys an **OH_Drawing_TextStyle** object and reclaims the memory occupied by the object. +Obtains the number of items in the water flow section that matches the specified index. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| handle | Pointer to an **ArkUI_StyledString** object. | +| option | Pointer to a water flow section configuration. | +| index | Index of the target water flow section. | + +**Returns** + +Returns the number of items in the water flow section. -### OH_ArkUI_StyledString_PopTextStyle() +### OH_ArkUI_WaterFlowSectionOption_GetMargin() ``` -void OH_ArkUI_StyledString_PopTextStyle (ArkUI_StyledString * handle) +ArkUI_Margin OH_ArkUI_WaterFlowSectionOption_GetMargin (ArkUI_WaterFlowSectionOption * option, int32_t index ) ``` **Description** -Removes the top style from the current formatted string object. +Obtains the margins of the water flow section that matches the specified index. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| handle | Pointer to an **ArkUI_StyledString** object. | +| option | Pointer to a water flow section configuration. | +| index | Index of the target water flow section. | +**Returns** + +Returns the margins. -### OH_ArkUI_StyledString_PushTextStyle() + +### OH_ArkUI_WaterFlowSectionOption_GetRowGap() ``` -void OH_ArkUI_StyledString_PushTextStyle (ArkUI_StyledString * handle, OH_Drawing_TextStyle * style ) +float OH_ArkUI_WaterFlowSectionOption_GetRowGap (ArkUI_WaterFlowSectionOption * option, int32_t index ) ``` **Description** -Sets the new typesetting style to the top of the current format string style stack. +Obtains the gap between rows in the water flow section that matches the specified index. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| handle | Pointer to an **ArkUI_StyledString** object. | -| style | Pointer to an **OH_Drawing_TextStyle** object. | +| option | Pointer to a water flow section configuration. | +| index | Index of the target water flow section. | +**Returns** -### OH_ArkUI_SwipeGesture_GetAngle() +Returns the gap between rows. + + +### OH_ArkUI_WaterFlowSectionOption_GetSize() ``` -float OH_ArkUI_SwipeGesture_GetAngle (const ArkUI_GestureEvent * event) +int32_t OH_ArkUI_WaterFlowSectionOption_GetSize (ArkUI_WaterFlowSectionOption * option) ``` **Description** -Obtains the angle information of the swipe gesture. +Sets the array length for a water flow section configuration. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Gesture event. | +| option | Pointer to a water flow section configuration. | **Returns** -Returns the angle of the swipe gesture, which is the result obtained based on the aforementioned formula. +Returns the array length. If **-1** is returned, an error code indicating failure is returned. The possible cause is that the **option** parameter is abnormal, for example, a null pointer. -### OH_ArkUI_SwipeGesture_GetVelocity() +### OH_ArkUI_WaterFlowSectionOption_RegisterGetItemMainSizeCallbackByIndex() ``` -float OH_ArkUI_SwipeGesture_GetVelocity (const ArkUI_GestureEvent * event) +void OH_ArkUI_WaterFlowSectionOption_RegisterGetItemMainSizeCallbackByIndex (ArkUI_WaterFlowSectionOption * option, int32_t index, float(*)(int32_t itemIndex) callback ) ``` **Description** -Obtains the average velocity of all fingers used in the swipe gesture. +Obtains the main axis size of a specified item based on **flowItemIndex** through a water flow section configuration. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Gesture event. | - -**Returns** - -Returns the average velocity of all fingers used in the swipe gesture, in px/s. +| option | Pointer to a water flow section configuration. | +| index | Index of the target water flow section. | +| callback | Callback used to return the result. | -### OH_ArkUI_SwiperIndicator_Create() +### OH_ArkUI_WaterFlowSectionOption_RegisterGetItemMainSizeCallbackByIndexWithUserData() ``` -ArkUI_SwiperIndicator* OH_ArkUI_SwiperIndicator_Create (ArkUI_SwiperIndicatorType type) +void OH_ArkUI_WaterFlowSectionOption_RegisterGetItemMainSizeCallbackByIndexWithUserData (ArkUI_WaterFlowSectionOption * option, int32_t index, void * userData, float(*)(int32_t itemIndex, void *userData) callback ) ``` **Description** -Creates a navigation indicator for the Swiper component. +Obtains the main axis size of a specified item based on **flowItemIndex** through a water flow section configuration. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| type | Type of the navigation indicator. | - -**Returns** - -Returns the pointer to the navigation point indicator. +| option | Pointer to a water flow section configuration. | +| index | Index of the target water flow section. | +| userData | Custom data of the water flow item. | +| callback | Callback used to return the result. | -### OH_ArkUI_SwiperIndicator_Dispose() +### OH_ArkUI_WaterFlowSectionOption_SetColumnGap() ``` -void OH_ArkUI_SwiperIndicator_Dispose (ArkUI_SwiperIndicator * indicator) +void OH_ArkUI_WaterFlowSectionOption_SetColumnGap (ArkUI_WaterFlowSectionOption * , int32_t index, float columnGap ) ``` **Description** -Disposes of the navigation point indicator of this **Swiper** component. +Sets the gap between columns in the specified water flow section. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| indicator | Returns the pointer to the navigation point indicator. | +| option | Pointer to a water flow section configuration. | +| index | Index of the target water flow section. | +| columnGap | Gap between columns. | -### OH_ArkUI_SwiperIndicator_GetBottomPosition() +### OH_ArkUI_WaterFlowSectionOption_SetCrossCount() ``` -float OH_ArkUI_SwiperIndicator_GetBottomPosition (ArkUI_SwiperIndicator * indicator) +void OH_ArkUI_WaterFlowSectionOption_SetCrossCount (ArkUI_WaterFlowSectionOption * option, int32_t index, int32_t crossCount ) ``` **Description** -Obtains the distance between the navigation point indicator and the bottom edge of the **Swiper** component. +Sets the number of columns (in a vertical layout) or rows (in a horizontal layout) of a water flow. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| indicator | Returns the pointer to the navigation point indicator. | - -**Returns** - -Returns the distance between a navigation point indicator and the bottom edge of the **Swiper** component. +| option | Pointer to a water flow section configuration. | +| index | Index of the target water flow section. | +| crossCount | Number of columns or rows, depending on the layout direction. | -### OH_ArkUI_SwiperIndicator_GetColor() +### OH_ArkUI_WaterFlowSectionOption_SetItemCount() ``` -uint32_t OH_ArkUI_SwiperIndicator_GetColor (ArkUI_SwiperIndicator * indicator) +void OH_ArkUI_WaterFlowSectionOption_SetItemCount (ArkUI_WaterFlowSectionOption * option, int32_t index, int32_t itemCount ) ``` **Description** -Obtains the color of a navigation point indicator of the dot style of the **Swiper** component. +Sets the number of items in a water flow section. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| indicator | Returns the pointer to the navigation point indicator. | - -**Returns** - -Returns the color, in 0xARGB format. For example, 0xFFFF0000 indicates red. +| option | Pointer to a water flow section configuration. | +| index | Index of the target water flow section. | +| itemCount | Number of items in the water flow section. | -### OH_ArkUI_SwiperIndicator_GetEndPosition() +### OH_ArkUI_WaterFlowSectionOption_SetMargin() ``` -float OH_ArkUI_SwiperIndicator_GetEndPosition (ArkUI_SwiperIndicator * indicator) +void OH_ArkUI_WaterFlowSectionOption_SetMargin (ArkUI_WaterFlowSectionOption * option, int32_t index, float marginTop, float marginRight, float marginBottom, float marginLeft ) ``` **Description** -Obtains the distance between a navigation point indicator and the right edge of the **Swiper** component. +Sets the margins for the specified water flow section. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| indicator | Returns the pointer to the navigation point indicator. | +| option | Pointer to a water flow section configuration. | +| index | Index of the target water flow section. | +| marginTop | Top margin of the water flow section. | +| marginRight | Right margin of the water flow section. | +| marginBottom | Bottom margin of the water flow section. | +| marginLeft | Left margin of the water flow section. | + + +### OH_ArkUI_WaterFlowSectionOption_SetRowGap() + +``` +void OH_ArkUI_WaterFlowSectionOption_SetRowGap (ArkUI_WaterFlowSectionOption * option, int32_t index, float rowGap ) +``` +**Description** + +Sets the gap between rows in the specified water flow section. + +**Since**: 12 -**Returns** +**Parameters** -Returns the distance between the navigation point indicator and the right edge of the **Swiper** component. +| Name| Description| +| -------- | -------- | +| option | Pointer to a water flow section configuration. | +| index | Index of the target water flow section. | +| rowGap | Gap between rows to set. | -### OH_ArkUI_SwiperIndicator_GetItemHeight() +### OH_ArkUI_WaterFlowSectionOption_SetSize() ``` -float OH_ArkUI_SwiperIndicator_GetItemHeight (ArkUI_SwiperIndicator * indicator) +void OH_ArkUI_WaterFlowSectionOption_SetSize (ArkUI_WaterFlowSectionOption * option, int32_t size ) ``` **Description** -Obtains the height of a navigation point indicator of the dot style of the **Swiper** component. +Sets the array length for a water flow section configuration. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| indicator | Returns the pointer to the navigation point indicator. | - -**Returns** - -Returns the height of the navigation point indicator of the dot style. +| option | Pointer to a water flow section configuration. | +| size | Size of the array. | -### OH_ArkUI_SwiperIndicator_GetItemWidth() +### OH_ArkUI_PostFrameCallback() ``` -float OH_ArkUI_SwiperIndicator_GetItemWidth (ArkUI_SwiperIndicator * indicator) +int32_t OH_ArkUI_PostFrameCallback(ArkUI_ContextHandle uiContext, void* userData, void (*callback)(uint64_t nanoTimestamp, uint32_t frameCount, void* userData)) ``` **Description** -Obtains the width of a navigation point indicator of the dot style of the **Swiper** component. +Registers a callback to be executed after the next frame is rendered. This callback must not be called from a non-UI thread. The application will abort if a non-UI thread call is detected. -**Since**: 12 +**Since**: 16 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| indicator | Returns the pointer to the navigation point indicator. | +| uiContext | UI context object used to bind the instance.| +| userData | Custom event parameter, which is passed in the callback when the event is triggered.| +| callback | Custom callback to be invoked after the next frame event completes.| +| nanoTimestamp | Timestamp of the frame signal.| +| frameCount | Frame number.| **Returns** -Returns the width of the navigation point indicator of the dot style. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. +Returns **ARKUI_ERROR_CODE_CAPI_INIT_ERROR** if there is an API initialization error. +Returns **ARKUI_ERROR_CODE_UI_CONTEXT_INVALID** if the UIContext object is invalid. +Returns **ARKUI_ERROR_CODE_CALLBACK_INVALID** if the callback is invalid. -### OH_ArkUI_SwiperIndicator_GetMask() +### OH_ArkUI_RegisterLayoutCallbackOnNodeHandle() ``` -int32_t OH_ArkUI_SwiperIndicator_GetMask (ArkUI_SwiperIndicator * indicator) +int32_t OH_ArkUI_RegisterLayoutCallbackOnNodeHandle (ArkUI_NodeHandle node, void* userData, void (*onLayoutCompleted)(void* userData)) ``` **Description** -Obtains whether the mask is enabled for a navigation point indicator of the dot style of the **Swiper** component. +Registers a layout completion callback function for a specific component. Only one layout completion callback can be registered per component. -**Since**: 12 +**Since**: 16 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| indicator | Returns the pointer to the navigation point indicator. | +| node | Specified node. | +| userData | Custom event parameter, which is passed in the callback when the event is triggered. | +| onLayoutCompleted | Callback to be executed when the event is triggered. | **Returns** -Returns **1** if the mask is enabled; returns **0** otherwise. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. +Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_SwiperIndicator_GetMaxDisplayCount() +### OH_ArkUI_RegisterDrawCallbackOnNodeHandle() ``` -int32_t OH_ArkUI_SwiperIndicator_GetMaxDisplayCount (ArkUI_SwiperIndicator * indicator) +int32_t OH_ArkUI_RegisterDrawCallbackOnNodeHandle (ArkUI_NodeHandle node, void* userData, void (*onDrawCompleted)(void* userData)) ``` **Description** -Obtains the maximum number of dots for the navigation point indicator of the dot style. +Registers a drawing completion callback function for a specific component. Only one drawing completion callback can be registered per component. -**Since**: 12 +**Since**: 16 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| indicator | Pointer to the navigation point indicator. | +| node | Specified node. | +| userData | Custom event parameter, which is passed in the callback when the event is triggered. | +| onDrawCompleted | Callback to be executed when the event is triggered. | **Returns** -Returns the maximum number of dots. The value ranges from 6 to 9. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. +Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_SwiperIndicator_GetSelectedColor() +### OH_ArkUI_UnregisterLayoutCallbackOnNodeHandle() ``` -uint32_t OH_ArkUI_SwiperIndicator_GetSelectedColor (ArkUI_SwiperIndicator * indicator) +int32_t OH_ArkUI_UnregisterLayoutCallbackOnNodeHandle (ArkUI_NodeHandle node) ``` **Description** -Obtains the color of the selected navigation point indicator of the dot style of the **Swiper** component. +Unregisters the layout completion callback function for a specific component. -**Since**: 12 +**Since**: 16 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| indicator | Returns the pointer to the navigation point indicator. | +| node | Specified node. | **Returns** -Returns the color, in 0xARGB format. For example, 0xFFFF0000 indicates red. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. +Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_SwiperIndicator_GetSelectedItemHeight() +### OH_ArkUI_UnregisterDrawCallbackOnNodeHandle() ``` -float OH_ArkUI_SwiperIndicator_GetSelectedItemHeight (ArkUI_SwiperIndicator * indicator) +int32_t OH_ArkUI_UnregisterDrawCallbackOnNodeHandle (ArkUI_NodeHandle node) ``` **Description** -Obtains the height of the selected navigation point indicator of the dot style of the **Swiper** component. +Unregisters the drawing completion callback function for a specific component. -**Since**: 12 +**Since**: 16 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| indicator | Returns the pointer to the navigation point indicator. | +| node | Specified node. | **Returns** -Returns the height of the navigation point indicator of the dot style. +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. +Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_SwiperIndicator_GetSelectedItemWidth() +### OH_ArkUI_ProgressLinearStyleOption_Create ``` -float OH_ArkUI_SwiperIndicator_GetSelectedItemWidth (ArkUI_SwiperIndicator * indicator) +ArkUI_ProgressLinearStyleOption* OH_ArkUI_ProgressLinearStyleOption_Create(void) ``` **Description** -Obtains the width of the selected navigation point indicator of the dot style of the **Swiper** component. - -**Since**: 12 - -**Parameters** +Creates a **ProgressLinearStyleOption** instance. -| Name| Description| -| -------- | -------- | -| indicator | Returns the pointer to the navigation point indicator. | +**Since**: 15 **Returns** -Returns the width of the navigation point indicator of the dot style. +Returns the **ProgressLinearStyleOption** instance created. -### OH_ArkUI_SwiperIndicator_GetStartPosition() +### OH_ArkUI_ProgressLinearStyleOption_Destroy ``` -float OH_ArkUI_SwiperIndicator_GetStartPosition (ArkUI_SwiperIndicator * indicator) +void OH_ArkUI_ProgressLinearStyleOption_Destroy(ArkUI_ProgressLinearStyleOption* option) ``` **Description** -Obtains the distance between a navigation point indicator and the left edge of the **Swiper** component. +Destroys a **ProgressLinearStyleOption** instance. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| indicator | Returns the pointer to the navigation point indicator. | - -**Returns** - -Returns the distance between the navigation point indicator and the left edge of the **Swiper** component. +| option | **ProgressLinearStyleOption** instance to destroy. | -### OH_ArkUI_SwiperIndicator_GetTopPosition() +### OH_ArkUI_ProgressLinearStyleOption_SetScanEffectEnabled ``` -float OH_ArkUI_SwiperIndicator_GetTopPosition (ArkUI_SwiperIndicator * indicator) +void OH_ArkUI_ProgressLinearStyleOption_SetSmoothEffectEnabled(ArkUI_ProgressLinearStyleOption* option, bool enabled) ``` **Description** -Obtains the distance between the navigation point indicator and the top edge of the **Swiper** component. +Sets whether to enable the scan effect. + +**Since**: 15 -**Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| indicator | Returns the pointer to the navigation point indicator. | +| option | Pointer to the **ProgressLinearStyleOption** instance. | +| enabled | Whether to enable the scan effect. The default value is **false**.| -**Returns** - -Returns the distance between a navigation point indicator and the top edge of the **Swiper** component. - -### OH_ArkUI_SwiperIndicator_SetBottomPosition() +### OH_ArkUI_ProgressLinearStyleOption_SetSmoothEffectEnabled ``` -void OH_ArkUI_SwiperIndicator_SetBottomPosition (ArkUI_SwiperIndicator * indicator, float value ) +void OH_ArkUI_ProgressLinearStyleOption_SetSmoothEffectEnabled(ArkUI_ProgressLinearStyleOption* option, bool enabled) ``` **Description** -Sets the distance between the navigation point indicator and the bottom edge of the **Swiper** component. +Sets whether to enable the smooth progress effect. + +**Since**: 15 -**Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| indicator | Pointer to a navigation point indicator. | -| value | Distance between a navigation point indicator and the bottom edge of the **Swiper** component. | +| option | Pointer to the **ProgressLinearStyleOption** instance. | +| enabled | Whether to enable the smooth effect. When this effect is enabled, the progress changes smoothly from the current value to the target value. When this effect is disabled, the progress changes abruptly to the target value. The default value is **true**.| -### OH_ArkUI_SwiperIndicator_SetColor() +### OH_ArkUI_ProgressLinearStyleOption_SetStrokeWidth ``` -void OH_ArkUI_SwiperIndicator_SetColor (ArkUI_SwiperIndicator * indicator, uint32_t color ) +void OH_ArkUI_ProgressLinearStyleOption_SetStrokeWidth(ArkUI_ProgressLinearStyleOption* option, float strokeWidth) ``` **Description** -Sets the color of a navigation point indicator of the dot style for the **Swiper** component. +Sets the stroke width of the linear progress indicator. + +**Since**: 15 -**Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| indicator | Returns the pointer to the navigation point indicator. | -| color | Color, in 0xARGB format. For example, 0xFFFF0000 indicates red. | +| option | Pointer to the **ProgressLinearStyleOption** instance. | +| strokeWidth | Stroke width of the progress indicator. The value cannot be set in percentage. The default value is **4.0vp**.| -### OH_ArkUI_SwiperIndicator_SetEndPosition() +### OH_ArkUI_ProgressLinearStyleOption_SetStrokeRadius ``` -void OH_ArkUI_SwiperIndicator_SetEndPosition (ArkUI_SwiperIndicator * indicator, float value ) +void OH_ArkUI_ProgressLinearStyleOption_SetStrokeRadius(ArkUI_ProgressLinearStyleOption* option, float strokeRadius) ``` **Description** -Distance between the navigation point indicator and the left edge of the **Swiper** component. +Sets the corner radius of the linear progress indicator. + +**Since**: 15 -**Since**: 12 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| indicator | Returns the pointer to the navigation point indicator. | -| value | Returns the distance between the navigation point indicator and the right edge of the **Swiper** component. | +| option | Pointer to the **ProgressLinearStyleOption** instance. | +| strokeRadius | Corner radius of the progress indicator. The value range is [0, strokeWidth/2]. Default value: **strokeWidth/2**.| -### OH_ArkUI_SwiperIndicator_SetItemHeight() +### OH_ArkUI_ProgressLinearStyleOption_GetScanEffectEnabled ``` -void OH_ArkUI_SwiperIndicator_SetItemHeight (ArkUI_SwiperIndicator * indicator, float value ) +bool OH_ArkUI_ProgressLinearStyleOption_GetScanEffectEnabled(ArkUI_ProgressLinearStyleOption* option) ``` **Description** -Sets the height of a navigation point indicator of the dot style for the **Swiper** component. +Obtains the enabled status of the scan effect for the linear progress indicator. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| indicator | Returns the pointer to the navigation point indicator. | -| value | Returns the height of the navigation point indicator of the dot style. | +| option | Pointer to the **ProgressLinearStyleOption** instance. | + +**Returns** +Returns the enabled status of the scan effect. -### OH_ArkUI_SwiperIndicator_SetItemWidth() + +### OH_ArkUI_ProgressLinearStyleOption_GetSmoothEffectEnabled ``` -void OH_ArkUI_SwiperIndicator_SetItemWidth (ArkUI_SwiperIndicator * indicator, float value ) +bool OH_ArkUI_ProgressLinearStyleOption_GetSmoothEffectEnabled(ArkUI_ProgressLinearStyleOption* option) ``` **Description** -Sets the width of a navigation point indicator of the dot style for the **Swiper** component. +Obtains the enabled status of the smooth progress effect for the linear progress indicator. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| indicator | Returns the pointer to the navigation point indicator. | -| value | Returns the width of the navigation point indicator of the dot style. | +| option | Pointer to the **ProgressLinearStyleOption** instance. | + +**Returns** +Returns the enabled status of the smooth progress effect. -### OH_ArkUI_SwiperIndicator_SetMask() + +### OH_ArkUI_ProgressLinearStyleOption_GetStrokeWidth ``` -void OH_ArkUI_SwiperIndicator_SetMask (ArkUI_SwiperIndicator * indicator, int32_t mask ) +float OH_ArkUI_ProgressLinearStyleOption_GetStrokeWidth(ArkUI_ProgressLinearStyleOption* option) ``` **Description** -Sets whether to enable the mask for a navigation point indicator of the dot style for the **Swiper** component. +Obtains the stroke width of the linear progress indicator. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| indicator | Pointer to a navigation point indicator. | -| mask | Whether to enable the mask. The value **1** means to enable the mask, and **0** means the opposite. | +| option | Pointer to the **ProgressLinearStyleOption** instance. | + +**Returns** +Returns the stroke width of the progress indicator. -### OH_ArkUI_SwiperIndicator_SetMaxDisplayCount() + +### OH_ArkUI_ProgressLinearStyleOption_GetStrokeRadius ``` -int32_t OH_ArkUI_SwiperIndicator_SetMaxDisplayCount (ArkUI_SwiperIndicator * indicator, int32_t maxDisplayCount ) +float OH_ArkUI_ProgressLinearStyleOption_GetStrokeRadius(ArkUI_ProgressLinearStyleOption* option) ``` **Description** -Sets the maximum number of dots for the navigation point indicator of the dot style. +Obtains the corner radius of the linear progress indicator. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| indicator | Pointer to a navigation point indicator. | -| maxDisplayCount | Maximum number of navigation points. The value ranges from 6 to 9. | +| option | Pointer to the **ProgressLinearStyleOption** instance. | **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if **maxDisplayCount** is set to an invalid value. +Returns the corner radius of the progress indicator. -### OH_ArkUI_SwiperIndicator_SetSelectedColor() +### OH_ArkUI_DragEvent_StartDataLoading() ``` -void OH_ArkUI_SwiperIndicator_SetSelectedColor (ArkUI_SwiperIndicator * indicator, uint32_t selectedColor ) +int32_t OH_ArkUI_DragEvent_StartDataLoading (ArkUI_DragEvent* event, OH_UdmfGetDataParams* options, char* key, unsigned int keyLen) ``` **Description** -Sets the color of the selected navigation point indicator of the dot style for the **Swiper** component. +Asynchronously obtains drag data. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| indicator | Pointer to a navigation point indicator. | -| selectedColor | Color, in 0xARGB format. For example, 0xFFFF0000 indicates red. | +| event | Pointer to an **ArkUI_DragEvent** object. | +| options | Parameters for obtaining data from UDMF. | +| key | Unique ID of data, which is returned in the callback parameters when the event is triggered. | +| keyLen | Length of **key**, which must be greater than or equal to the value of **UDMF_KEY_BUFFER_LEN**. | +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. +Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_SwiperIndicator_SetSelectedItemHeight() + +### OH_ArkUI_CancelDataLoading() ``` -void OH_ArkUI_SwiperIndicator_SetSelectedItemHeight (ArkUI_SwiperIndicator * indicator, float value ) +int32_t OH_ArkUI_CancelDataLoading (ArkUI_ContextHandle uiContext, const char* key) ``` **Description** -Sets the height of the selected navigation point indicator of the dot style for the **Swiper** component. +Cancels the asynchronous obtaining of drag data. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| indicator | Pointer to a navigation point indicator. | -| value | Height of the navigation point indicator of the dot style. | +| uiContext | UI context object used to bind the instance.| +| key | Unique ID of data.| +**Returns** -### OH_ArkUI_SwiperIndicator_SetSelectedItemWidth() +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. +Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + + +### OH_ArkUI_DisableDropDataPrefetchOnNode() ``` -void OH_ArkUI_SwiperIndicator_SetSelectedItemWidth (ArkUI_SwiperIndicator * indicator, float value ) +int32_t OH_ArkUI_DisableDropDataPrefetchOnNode (ArkUI_NodeHandle node, bool disable) ``` **Description** -Sets the width of the selected navigation point indicator of the dot style for the **Swiper** component. +Sets whether to enable data prefetching for drag and drop operations on a specified node. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| indicator | Pointer to a navigation point indicator. | -| value | Width of the navigation point indicator of the dot style. | +| node | Specified node. | +| disable | Whether to enable data prefetching for the drop and drop operation. The value **true** means to disable data prefetching, and **false** means to enable data prefetching. The default value is **false**. To use **OH_ArkUI_DragEvent_StartDataLoading** to obtain data, set this parameter to **true**.| -### OH_ArkUI_SwiperIndicator_SetStartPosition() +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. +Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + +### OH_ArkUI_CrossLanguageOption_Create() ``` -void OH_ArkUI_SwiperIndicator_SetStartPosition (ArkUI_SwiperIndicator * indicator, float value ) +ArkUI_CrossLanguageOption* OH_ArkUI_CrossLanguageOption_Create(void) ``` **Description** -Sets the distance between the navigation point indicator and the left edge of the **Swiper** component. +Creates an instance of the cross-language configuration option. -**Since**: 12 +**Since**: 15 -**Parameters** +**Returns** -| Name| Description| -| -------- | -------- | -| indicator | Pointer to a navigation point indicator. | -| value | Distance between the navigation point indicator and the left edge of the **Swiper** component. | +Returns the pointer to the **ArkUI_CrossLanguageOption** instance created. If a null pointer is returned, creation failed, possibly due to insufficient memory. -### OH_ArkUI_SwiperIndicator_SetTopPosition() +### OH_ArkUI_CrossLanguageOption_Destroy() ``` -void OH_ArkUI_SwiperIndicator_SetTopPosition (ArkUI_SwiperIndicator * indicator, float value ) +void OH_ArkUI_CrossLanguageOption_Destroy(ArkUI_CrossLanguageOption* option) ``` **Description** -Sets the distance between the navigation point indicator and the top edge of the **Swiper** component. +Destroys an instance of the cross-language configuration option. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| indicator | Pointer to a navigation point indicator. | -| value | Distance between a navigation point indicator and the top edge of the **Swiper** component. | +| option | Cross-language configuration option instance to be destroyed. | - -### OH_ArkUI_SystemFontStyleEvent_GetFontSizeScale() +### OH_ArkUI_CrossLanguageOption_SetAttributeSettingStatus() ``` -float OH_ArkUI_SystemFontStyleEvent_GetFontSizeScale (const ArkUI_SystemFontStyleEvent * event) +void OH_ArkUI_CrossLanguageOption_SetAttributeSettingStatus(ArkUI_CrossLanguageOption* option, bool enable) ``` **Description** -Obtains the font size scale from the system font style change event. +Sets whether cross-language attribute setting is allowed in the configuration option. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to the current system font style change event. | - -**Returns** - -Returns the font size scale after the change. Default value: **1.0**. - +| option | Pointer to the cross-language configuration option instance. | +| enable | Whether cross-language attribute setting is allowed. The default value is **false**. | -### OH_ArkUI_SystemFontStyleEvent_GetFontWeightScale() +### OH_ArkUI_CrossLanguageOption_GetAttributeSettingStatus() ``` -float OH_ArkUI_SystemFontStyleEvent_GetFontWeightScale (const ArkUI_SystemFontStyleEvent * event) +bool OH_ArkUI_CrossLanguageOption_GetAttributeSettingStatus(ArkUI_CrossLanguageOption* option) ``` **Description** -Obtains the font weight scale from the system font style change event. +Checks whether cross-language attribute setting is allowed in the configuration option. -**Since**: 12 +**Since**: 15 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| event | Pointer to the current system font style change event. | +| option | Pointer to the cross-language configuration option instance. | **Returns** -Returns the font weight scale after the change. Default value: **1.0**. - +Whether cross-language attribute setting is allowed. -### OH_ArkUI_TransitionEffect_Combine() +### OH_ArkUI_VisibleAreaEventOptions_Create() ``` -int32_t OH_ArkUI_TransitionEffect_Combine (ArkUI_TransitionEffect * option, ArkUI_TransitionEffect * combine ) +ArkUI_VisibleAreaEventOptions* OH_ArkUI_VisibleAreaEventOptions_Create() ``` **Description** -Sets a combination of transition effects. - -**Since**: 12 - -**Parameters** +Creates an instance of visible area change event parameters. -| Name| Description| -| -------- | -------- | -| option | Transition effect options. | -| combine | Combination of transition effects. | +**Since**: 18 **Returns** +Returns the created instance of visible area change event parameters. -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. - - -### OH_ArkUI_TransitionEffect_Dispose() +### OH_ArkUI_VisibleAreaEventOptions_Dispose() ``` -void OH_ArkUI_TransitionEffect_Dispose (ArkUI_TransitionEffect * option) +void OH_ArkUI_VisibleAreaEventOptions_Dispose(ArkUI_VisibleAreaEventOptions* option) ``` **Description** -Destroys a transition effect object. +Disposes of an instance of visible area change event parameters. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Transition effect object. | +| option | Instance of visible area change event parameters to be destroyed. | - -### OH_ArkUI_TransitionEffect_SetAnimation() +### OH_ArkUI_VisibleAreaEventOptions_SetRatios() ``` -int32_t OH_ArkUI_TransitionEffect_SetAnimation (ArkUI_TransitionEffect * option, ArkUI_AnimateOption * animation ) +int32_t OH_ArkUI_VisibleAreaEventOptions_SetRatios(ArkUI_VisibleAreaEventOptions* option, float* value, int32_t size) ``` **Description** -Sets transition effect animation settings. - -**Since**: 12 - -**Parameters** +Sets the threshold ratios for visible area changes. -| Name| Description| -| -------- | -------- | -| option | Transition effect options. | -| animation | Animation settings. | +**Since**: 18 -**NOTE** +**Parameters** -If **combine** is used for combining transition effects, the animation settings of a transition effect are applicable to the one following it. +| Name| Description| +| -------- | -------- | +| option | Pointer to the instance of visible area change event parameters.| +| value | Array of threshold ratios.| +| size | Size of the array of threshold ratios.| **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. - +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. +Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_UnmarshallStyledStringDescriptor() +### OH_ArkUI_VisibleAreaEventOptions_SetExpectedUpdateInterval() ``` -int32_t OH_ArkUI_UnmarshallStyledStringDescriptor (uint8_t * buffer, size_t bufferSize, ArkUI_StyledString_Descriptor * descriptor, size_t * resultSize ) +int32_t OH_ArkUI_VisibleAreaEventOptions_SetExpectedUpdateInterval( + ArkUI_VisibleAreaEventOptions *option, int32_t value) ``` **Description** -Deserializes a byte array containing styled string information into a styled string. +Sets the expected update interval for visible area changes. -**Since**: 14 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| buffer | Byte array to be deserialized. | -| bufferSize | Length of the byte array. | -| descriptor | Pointer to an **ArkUI_StyledString_Descriptor** object. | -| resultSize | Actual length of the resulting byte array after deserialization. | +| option | Pointer to the instance of visible area change event parameters.| +| value | Expected update interval, in ms. The default value is **1000**.| **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. - +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. +Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_UnregisterSystemColorModeChangeEvent() +### OH_ArkUI_VisibleAreaEventOptions_GetRatios() ``` -void OH_ArkUI_UnregisterSystemColorModeChangeEvent (ArkUI_NodeHandle node) +int32_t OH_ArkUI_VisibleAreaEventOptions_GetRatios(ArkUI_VisibleAreaEventOptions* option, float* value, int32_t* size) ``` **Description** -Unregisters the event listener for system color mode changes. + Obtains the threshold ratios for visible area changes. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | Specified node. | +| option | Pointer to the instance of visible area change event parameters.| +| value | Array of threshold ratios.| +| size | Size of the array of threshold ratios.| +**Returns** -### OH_ArkUI_UnregisterSystemFontStyleChangeEvent() +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. +Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +Returns **ARKUI_ERROR_CODE_BUFFER_SIZE_ERROR** if the provided buffer size is insufficient. + +### OH_ArkUI_VisibleAreaEventOptions_GetExpectedUpdateInterval() ``` -void OH_ArkUI_UnregisterSystemFontStyleChangeEvent (ArkUI_NodeHandle node) +int32_t OH_ArkUI_VisibleAreaEventOptions_GetExpectedUpdateInterval(ArkUI_VisibleAreaEventOptions* option) ``` **Description** -Unregisters the event listener for system font style changes. + Obtains the expected update interval for visible area changes. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | Specified node. | +| option | Pointer to the instance of visible area change event parameters.| +**Returns** +Returns the expected update interval, in ms. -### OH_ArkUI_WaterFlowSectionOption_Create() +### OH_ArkUI_NodeUtils_GetPositionToParent() ``` -ArkUI_WaterFlowSectionOption* OH_ArkUI_WaterFlowSectionOption_Create () +int32_t OH_ArkUI_NodeUtils_GetPositionToParent (ArkUI_NodeHandle node, ArkUI_IntOffset* globalOffset ) ``` **Description** -Creates a water flow section configuration. +Obtains the offset of a specific node relative to its parent node. -**Since**: 12 +**Since**: 15 -**Returns** +**Parameters** -Return the pointer to the created water flow section configuration. +| Name| Description| +| -------- | -------- | +| node | **ArkUI_NodeHandle** pointer. | +| globalOffset | Offset of the target node relative to its parent node, in px. | + +**Returns** +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. +Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_WaterFlowSectionOption_Dispose() +### OH_ArkUI_GetGestureParam_DirectMask() ``` -void OH_ArkUI_WaterFlowSectionOption_Dispose (ArkUI_WaterFlowSectionOption * option) +int32_t OH_ArkUI_GetGestureParam_DirectMask(ArkUI_GestureRecognizer* recognizer, ArkUI_GestureDirectionMask* directMask) ``` **Description** -Disposes of the pointer to a water flow section configuration. +Obtains the swipe direction of a gesture recognizer. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to a water flow section configuration. | +| recognizer | Pointer to the gesture recognizer. | +| directMask | Swipe direction of the gesture recognizer. | +**Returns** -### OH_ArkUI_WaterFlowSectionOption_GetColumnGap() +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. +Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. + +### OH_ArkUI_GetGestureParam_FingerCount() ``` -float OH_ArkUI_WaterFlowSectionOption_GetColumnGap (ArkUI_WaterFlowSectionOption * option, int32_t index ) +int32_t OH_ArkUI_GetGestureParam_FingerCount(ArkUI_GestureRecognizer* recognizer, int* finger) ``` **Description** -Obtains the gap between columns in the water flow section that matches the specified index. +Obtains the number of fingers used by a gesture recognizer. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to a water flow section configuration. | -| index | Index of the target water flow section. | +| recognizer | Pointer to the gesture recognizer. | +| finger | Number of fingers used by the gesture recognizer. | **Returns** -Returns the gap between columns. - +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. +Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_WaterFlowSectionOption_GetCrossCount() +### OH_ArkUI_GetGestureParam_limitFingerCount() ``` -int32_t OH_ArkUI_WaterFlowSectionOption_GetCrossCount (ArkUI_WaterFlowSectionOption * option, int32_t index ) +int32_t OH_ArkUI_GetGestureParam_limitFingerCount(ArkUI_GestureRecognizer* recognizer, bool* isLimited) ``` **Description** -Obtains the number of columns (in a vertical layout) or rows (in a horizontal layout) of a water flow. +Checks whether a gesture recognizer has a finger count limit. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to a water flow section configuration. | -| index | Index of the target water flow section. | +| recognizer | Pointer to the gesture recognizer. | +| isLimited | Whether the gesture recognizer has a finger count limit. | **Returns** -Returns the number of columns (in a vertical layout) or rows (in a horizontal layout) of a water flow. - +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. +Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. -### OH_ArkUI_WaterFlowSectionOption_GetItemCount() +### OH_ArkUI_GetGestureParam_repeat() ``` -int32_t OH_ArkUI_WaterFlowSectionOption_GetItemCount (ArkUI_WaterFlowSectionOption * option, int32_t index ) +int32_t OH_ArkUI_GetGestureParam_repeat(ArkUI_GestureRecognizer* recognizer, bool* isRepeat) ``` **Description** -Obtains the number of items in the water flow section that matches the specified index. +Checks whether a gesture recognizer supports repeated event callbacks. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to a water flow section configuration. | -| index | Index of the target water flow section. | +| recognizer | Pointer to the gesture recognizer. | +| isRepeat | Whether the gesture recognizer supports repeated event callbacks. | **Returns** -Returns the number of items in the water flow section. - +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. +Returns **ARKUI_ERROR_CODE_RECOGNIZER_TYPE_NOT_SUPPORTED** if the gesture recognizer type is not supported. -### OH_ArkUI_WaterFlowSectionOption_GetMargin() +### OH_ArkUI_GetGestureParam_distance() ``` -ArkUI_Margin OH_ArkUI_WaterFlowSectionOption_GetMargin (ArkUI_WaterFlowSectionOption * option, int32_t index ) +int32_t OH_ArkUI_GetGestureParam_distance(ArkUI_GestureRecognizer* recognizer, double* distance) ``` **Description** -Obtains the margins of the water flow section that matches the specified index. +Obtains the allowed movement distance range for a gesture recognizer. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to a water flow section configuration. | -| index | Index of the target water flow section. | +| recognizer | Pointer to the gesture recognizer. | +| distance | Allowed movement distance range of the gesture recognizer. | **Returns** -Returns the margins. - +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. +Returns **ARKUI_ERROR_CODE_RECOGNIZER_TYPE_NOT_SUPPORTED** if the gesture recognizer type is not supported. -### OH_ArkUI_WaterFlowSectionOption_GetRowGap() +### OH_ArkUI_GetGestureParam_speed() ``` -float OH_ArkUI_WaterFlowSectionOption_GetRowGap (ArkUI_WaterFlowSectionOption * option, int32_t index ) +int32_t OH_ArkUI_GetGestureParam_speed(ArkUI_GestureRecognizer* recognizer, double* speed) ``` **Description** -Obtains the gap between rows in the water flow section that matches the specified index. +Obtains the minimum swipe speed recognized by a gesture recognizer. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to a water flow section configuration. | -| index | Index of the target water flow section. | +| recognizer | Pointer to the gesture recognizer. | +| speed | Minimum swipe speed recognized by the gesture recognizer. | **Returns** -Returns the gap between rows. - +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. +Returns **ARKUI_ERROR_CODE_RECOGNIZER_TYPE_NOT_SUPPORTED** if the gesture recognizer type is not supported. -### OH_ArkUI_WaterFlowSectionOption_GetSize() +### OH_ArkUI_GetGestureParam_duration() ``` -int32_t OH_ArkUI_WaterFlowSectionOption_GetSize (ArkUI_WaterFlowSectionOption * option) +int32_t OH_ArkUI_GetGestureParam_duration(ArkUI_GestureRecognizer* recognizer, int* duration) ``` **Description** -Sets the array length for a water flow section configuration. +Obtains the minimum duration required to trigger a long press by a gesture recognizer. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to a water flow section configuration. | +| recognizer | Pointer to the gesture recognizer. | +| duration | Minimum duration for a long press. | **Returns** -Returns the array length. If **-1** is returned, an error code indicating failure is returned. The possible cause is that the **option** parameter is abnormal, for example, a null pointer. - +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. +Returns **ARKUI_ERROR_CODE_RECOGNIZER_TYPE_NOT_SUPPORTED** if the gesture recognizer type is not supported. -### OH_ArkUI_WaterFlowSectionOption_RegisterGetItemMainSizeCallbackByIndex() +### OH_ArkUI_GetGestureParam_angle() ``` -void OH_ArkUI_WaterFlowSectionOption_RegisterGetItemMainSizeCallbackByIndex (ArkUI_WaterFlowSectionOption * option, int32_t index, float(*)(int32_t itemIndex) callback ) +int32_t OH_ArkUI_GetGestureParam_angle(ArkUI_GestureRecognizer* recognizer, double* angle) ``` **Description** -Obtains the main axis size of a specified item based on **flowItemIndex** through a water flow section configuration. +Obtains the minimum angle change required for a rotation gesture to be recognized by a gesture recognizer. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to a water flow section configuration. | -| index | Index of the target water flow section. | -| callback | Callback used to return the result. | +| recognizer | Pointer to the gesture recognizer. | +| angle | Minimum angle change. | + +**Returns** +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. +Returns **ARKUI_ERROR_CODE_RECOGNIZER_TYPE_NOT_SUPPORTED** if the gesture recognizer type is not supported. -### OH_ArkUI_WaterFlowSectionOption_RegisterGetItemMainSizeCallbackByIndexWithUserData() +### OH_ArkUI_GetGestureParam_distanceThreshold() ``` -void OH_ArkUI_WaterFlowSectionOption_RegisterGetItemMainSizeCallbackByIndexWithUserData (ArkUI_WaterFlowSectionOption * option, int32_t index, void * userData, float(*)(int32_t itemIndex, void *userData) callback ) +int32_t OH_ArkUI_GetGestureParam_distanceThreshold(ArkUI_GestureRecognizer* recognizer, double* distanceThreshold) ``` **Description** -Obtains the main axis size of a specified item based on **flowItemIndex** through a water flow section configuration. +Obtains the movement threshold for gestures to be recognized by a gesture recognizer. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to a water flow section configuration. | -| index | Index of the target water flow section. | -| userData | Custom data of the water flow item. | -| callback | Callback used to return the result. | +| recognizer | Pointer to the gesture recognizer. | +| distanceThreshold | Gesture movement threshold of the gesture recognizer. | +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. +Returns **ARKUI_ERROR_CODE_RECOGNIZER_TYPE_NOT_SUPPORTED** if the gesture recognizer type is not supported. -### OH_ArkUI_WaterFlowSectionOption_SetColumnGap() + +### OH_ArkUI_DragEvent_RequestDragEndPending() ``` -void OH_ArkUI_WaterFlowSectionOption_SetColumnGap (ArkUI_WaterFlowSectionOption * , int32_t index, float columnGap ) +int32_t OH_ArkUI_DragEvent_RequestDragEndPending(ArkUI_DragEvent* event, int32_t* requestIdentify) ``` **Description** -Sets the gap between columns in the specified water flow section. +Requests a delayed execution of the end of the drag and drop operation. When the system notifies the application of a drop event, this API can be called to explicitly inform the system that a delay is needed before the drag result can be processed. The system will defer the end of the drag and drop operation and wait for the application to return the drag result through the **OH_ArkUI_NotifyDragResult** API. This is typically used when the drag data is processed in a background thread to avoid blocking the main thread for an extended period, ensuring that the drag source receives an accurate result at the end of the drag operation. However, the system will not wait indefinitely; the maximum timeout is 2 seconds. If the **OH_ArkUI_NotifyDragResult** notification is not received within this time, the drag and drop operation will be forcibly terminated, and the drag source will be notified of the failure. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to a water flow section configuration. | -| index | Index of the target water flow section. | -| columnGap | Gap between columns. | +| event | Pointer to an **ArkUI_DragEvent** object. | +| requestIdentify | Unique identifier for this delayed drop operation.| -### OH_ArkUI_WaterFlowSectionOption_SetCrossCount() +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. +Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +Returns **ARKUI_ERROR_CODE_DRAG_DROP_OPERATION_NOT_ALLOWED** if the API is not called during the drop phase. + + + +### OH_ArkUI_NotifyDragResult() ``` -void OH_ArkUI_WaterFlowSectionOption_SetCrossCount (ArkUI_WaterFlowSectionOption * option, int32_t index, int32_t crossCount ) +int32_t OH_ArkUI_NotifyDragResult(int32_t requestIdentify, ArkUI_DragResult result) ``` **Description** -Sets the number of columns (in a vertical layout) or rows (in a horizontal layout) of a water flow. +Notifies the system of the drag result. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to a water flow section configuration. | -| index | Index of the target water flow section. | -| crossCount | Number of columns or rows, depending on the layout direction. | +| requestIdentify | Unique identifier for this delayed drop operation.| +| result | Drag result.| -### OH_ArkUI_WaterFlowSectionOption_SetItemCount() +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. +Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +Returns **ARKUI_ERROR_CODE_DRAG_DROP_OPERATION_NOT_ALLOWED** if the API is not called during the drop phase. + + +### OH_ArkUI_NotifyDragEndPendingDone() ``` -void OH_ArkUI_WaterFlowSectionOption_SetItemCount (ArkUI_WaterFlowSectionOption * option, int32_t index, int32_t itemCount ) +int32_t OH_ArkUI_NotifyDragEndPendingDone(int32_t requestIdentify) ``` **Description** -Sets the number of items in a water flow section. +Notifies the system that the delayed drag and drop operation has been completed. -**Since**: 12 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| option | Pointer to a water flow section configuration. | -| index | Index of the target water flow section. | -| itemCount | Number of items in the water flow section. | +| requestIdentify | Unique identifier for this delayed drop operation.| -### OH_ArkUI_WaterFlowSectionOption_SetMargin() +**Returns** + +Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. +Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +Returns **ARKUI_ERROR_CODE_DRAG_DROP_OPERATION_NOT_ALLOWED** if the API is not called during the drop phase. + +### OH_ArkUI_TextPickerRangeContentArray_Create() ``` -void OH_ArkUI_WaterFlowSectionOption_SetMargin (ArkUI_WaterFlowSectionOption * option, int32_t index, float marginTop, float marginRight, float marginBottom, float marginLeft ) +ArkUI_TextPickerRangeContentArray* OH_ArkUI_TextPickerRangeContentArray_Create(int32_t length) ``` **Description** -Sets the margins for the specified water flow section. +Creates a **TextPickerRangeContent** array object. -**Since**: 12 +**Since**: 18 **Parameters** | Name| Description| | -------- | -------- | -| option | Pointer to a water flow section configuration. | -| index | Index of the target water flow section. | -| marginTop | Top margin of the water flow section. | -| marginRight | Right margin of the water flow section. | -| marginBottom | Bottom margin of the water flow section. | -| marginLeft | Left margin of the water flow section. | +| length | Length of the **TextPickerRangeContent** array. | +**Returns** -### OH_ArkUI_WaterFlowSectionOption_SetRowGap() +Returns a pointer to an empty **TextPickerRangeContent** array. + +### OH_ArkUI_TextPickerRangeArray_SetIconAtIndex() ``` -void OH_ArkUI_WaterFlowSectionOption_SetRowGap (ArkUI_WaterFlowSectionOption * option, int32_t index, float rowGap ) +void OH_ArkUI_TextPickerRangeArray_SetIconAtIndex(ArkUI_TextPickerRangeContentArray* handle,char* icon,int32_t index); ``` **Description** -Sets the gap between rows in the specified water flow section. + Sets the icon data at the specified position in the **TextPickerRangeContent** array. -**Since**: 12 +**Since**: 18 **Parameters** | Name| Description| | -------- | -------- | -| option | Pointer to a water flow section configuration. | -| index | Index of the target water flow section. | -| rowGap | Gap between rows to set. | +| handle | Pointer to the **TextPickerRangeContent** array.| +| icon | Pointer to the icon image address.| +| index | Position in the array, starting from 0.| -### OH_ArkUI_WaterFlowSectionOption_SetSize() +### OH_ArkUI_TextPickerRangeContentArray_SetTextAtIndex() ``` -void OH_ArkUI_WaterFlowSectionOption_SetSize (ArkUI_WaterFlowSectionOption * option, int32_t size ) +void OH_ArkUI_TextPickerRangeContentArray_SetTextAtIndex(ArkUI_TextPickerRangeContentArray* handle,char* text,int32_t index); ``` **Description** -Sets the array length for a water flow section configuration. + Sets the text data at the specified position in the **TextPickerRangeContent** array. -**Since**: 12 +**Since**: 18 **Parameters** | Name| Description| | -------- | -------- | -| option | Pointer to a water flow section configuration. | -| size | Size of the array. | +| handle | Pointer to the **TextPickerRangeContent** array.| +| text | Pointer to the text content.| +| index | Position in the array, starting from 0.| -### OH_ArkUI_PostFrameCallback() +### OH_ArkUI_TextPickerRangeContentArray_Destroy() ``` -int32_t OH_ArkUI_PostFrameCallback(ArkUI_ContextHandle uiContext, void* userData, void (*callback)(uint64_t nanoTimestamp, uint32_t frameCount, void* userData)) +void OH_ArkUI_TextPickerRangeContentArray_Destroy(ArkUI_TextPickerRangeContentArray* handle); ``` **Description** -Registers a callback to be executed after the next frame is rendered. This callback must not be called from a non-UI thread. The application will abort if a non-UI thread call is detected. + Destroys a **TextPickerRangeContent** array object. -**Since**: 16 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| uiContext | UI context object used to bind the instance.| -| userData | Custom event parameter, which is passed in the callback when the event is triggered.| -| callback | Custom callback to be invoked after the next frame event completes.| -| nanoTimestamp | Timestamp of the frame signal.| -| frameCount | Frame number.| - -**Returns** - -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. -Returns **ARKUI_ERROR_CODE_CAPI_INIT_ERROR** if there is an API initialization error. -Returns **ARKUI_ERROR_CODE_UI_CONTEXT_INVALID** if the UIContext object is invalid. -Returns **ARKUI_ERROR_CODE_CALLBACK_INVALID** if the callback is invalid. +| handle | Pointer to the **TextPickerRangeContent** array.| -### OH_ArkUI_RegisterLayoutCallbackOnNodeHandle() +### OH_ArkUI_TextCascadePickerRangeContentArray_Create() ``` -int32_t OH_ArkUI_RegisterLayoutCallbackOnNodeHandle (ArkUI_NodeHandle node, void* userData, void (*onLayoutCompleted)(void* userData)) +ArkUI_TextCascadePickerRangeContentArray* OH_ArkUI_TextCascadePickerRangeContentArray_Create(int32_t length); ``` **Description** -Registers a layout completion callback function for a specific component. Only one layout completion callback can be registered per component. +Creates a **TextCascadePickerRangeContent** array object. -**Since**: 16 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | Specified node. | -| userData | Custom event parameter, which is passed in the callback when the event is triggered. | -| onLayoutCompleted | Callback to be executed when the event is triggered. | +| length | Length of the **TextPickerRangeContent** array.| **Returns** -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. -Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. - +Returns a pointer to an empty **TextCascadePickerRangeContent** array. -### OH_ArkUI_RegisterDrawCallbackOnNodeHandle() +### OH_ArkUI_TextCascadePickerRangeContentArray_SetTextAtIndex() ``` -int32_t OH_ArkUI_RegisterDrawCallbackOnNodeHandle (ArkUI_NodeHandle node, void* userData, void (*onDrawCompleted)(void* userData)) +void OH_ArkUI_TextCascadePickerRangeContentArray_SetTextAtIndex(ArkUI_TextCascadePickerRangeContentArray* handle,char* text,int32_t index); ``` **Description** -Registers a drawing completion callback function for a specific component. Only one drawing completion callback can be registered per component. + Sets the text data at the specified position in the **TextCascadePickerRangeContent** array. -**Since**: 16 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | Specified node. | -| userData | Custom event parameter, which is passed in the callback when the event is triggered. | -| onDrawCompleted | Callback to be executed when the event is triggered. | - -**Returns** - -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. -Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +| handle | Pointer to the **TextCascadePickerRangeContent** array.| +| text | Pointer to the text content.| +| index | Position in the array, starting from 0.| -### OH_ArkUI_UnregisterLayoutCallbackOnNodeHandle() +### OH_ArkUI_TextCascadePickerRangeContentArray_setChildAtIndex() ``` -int32_t OH_ArkUI_UnregisterLayoutCallbackOnNodeHandle (ArkUI_NodeHandle node) +void OH_ArkUI_TextCascadePickerRangeContentArray_setChildAtIndex(ArkUI_TextCascadePickerRangeContentArray* handle,ArkUI_TextCascadePickerRangeContentArray* child,int32_t index); ``` **Description** -Unregisters the layout completion callback function for a specific component. + Sets the child data at the specified position in the **TextCascadePickerRangeContent** array. -**Since**: 16 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | Specified node. | - -**Returns** - -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. -Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +| handle | Pointer to the **TextCascadePickerRangeContent** array.| +| child | Pointer to the child node array.| +| index | Position in the array, starting from 0.| -### OH_ArkUI_UnregisterDrawCallbackOnNodeHandle() +### OH_ArkUI_TextCascadePickerRangeContentArray_Destroy() ``` -int32_t OH_ArkUI_UnregisterDrawCallbackOnNodeHandle (ArkUI_NodeHandle node) +void OH_ArkUI_TextCascadePickerRangeContentArray_Destroy(ArkUI_TextCascadePickerRangeContentArray* handle); ``` **Description** -Unregisters the drawing completion callback function for a specific component. + Destroys a **TextCascadePickerRangeContent** array object. -**Since**: 16 +**Since**: 18 **Parameters** -| Name| Description| +| Name| Description| | -------- | -------- | -| node | Specified node. | - -**Returns** - -Returns **ARKUI_ERROR_CODE_NO_ERROR** if the operation is successful. -Returns **ARKUI_ERROR_CODE_PARAM_INVALID** if a parameter error occurs. +| handle | Pointer to the **TextCascadePickerRangeContent** array.| diff --git a/en/application-dev/reference/apis-arkui/_ark_u_i___native_node_a_p_i__1.md b/en/application-dev/reference/apis-arkui/_ark_u_i___native_node_a_p_i__1.md index 743c25dda454613c54b275b2d0d62b521732897d..92f7dd1ea0d141e1509bb995df8d5deff65b7a52 100644 --- a/en/application-dev/reference/apis-arkui/_ark_u_i___native_node_a_p_i__1.md +++ b/en/application-dev/reference/apis-arkui/_ark_u_i___native_node_a_p_i__1.md @@ -17,7 +17,7 @@ The APIs related to the native node must be called in the main thread. ### Member Variables -| Name | Description | +| Name| Description| | -------- | -------- | | int32_t [version](#version) | Specifies the struct version. | | [ArkUI_NodeHandle](_ark_u_i___native_module.md#arkui_nodehandle)(\* [createNode](#createnode) )([ArkUI_NodeType](_ark_u_i___native_module.md#arkui_nodetype) type) | Creates a component based on [ArkUI_NodeType](_ark_u_i___native_module.md#arkui_nodetype) and returns the pointer to the component object. | @@ -76,14 +76,14 @@ Adds a component to a parent node. **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | parent | Pointer to the parent node. | | child | Pointer to the child node. | **Returns** - Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs; returns [ARKUI_ERROR_CODE_NOT_SUPPROTED_FOR_ARKTS_NODE](_ark_u_i___native_module.md) if the following operations are not allowed on BuilderNode generated nodes: setting or resetting attributes, setting events, or adding or editing child nodes. +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md#arkui_errorcode) if the operation is successful. Returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md#arkui_errorcode) if a parameter error occurs. Returns [ARKUI_ERROR_CODE_NOT_SUPPROTED_FOR_ARKTS_NODE](_ark_u_i___native_module.md#arkui_errorcode) if the following operations are not allowed on BuilderNode generated nodes: setting or resetting attributes, setting events, or adding or editing child nodes. ### addNodeCustomEventReceiver @@ -103,14 +103,14 @@ Do not directly save the **ArkUI_NodeCustomEvent** object pointer. The data will **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | node | Component for which you want to add the custom event callback function. | | eventReceiver | Custom event callback for the component. | **Returns** - Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md#arkui_errorcode) if the operation is successful. Returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md#arkui_errorcode) if a parameter error occurs. ### addNodeEventReceiver @@ -130,14 +130,14 @@ Avoid directly saving pointers to **ArkUI_NodeEvent** objects, as the data will **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | node | Component for which you want to add the event callback function. | | eventReceiver | Event callback for the component. | **Returns** - Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md#arkui_errorcode) if the operation is successful. Returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md#arkui_errorcode) if a parameter error occurs. ### createNode @@ -151,7 +151,7 @@ Creates a component based on [ArkUI_NodeType](_ark_u_i___native_module.md#arkui_ **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | type | Type of the component to create. | @@ -171,7 +171,7 @@ Disposes of the component to which the specified pointer points. **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | node | Pointer to a component object. | @@ -189,7 +189,7 @@ The pointer returned by this API is an internal buffer pointer of the ArkUI fram **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | node | Node whose attribute needs to be obtained. | | attribute | Type of the attribute to obtain. | @@ -210,7 +210,7 @@ Obtains a child node. **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | node | Target node. | | position | Position of the child node. | @@ -231,7 +231,7 @@ Obtains the first child node. **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | node | Target node. | @@ -251,7 +251,7 @@ Obtains the last child node. **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | node | Target node. | @@ -271,7 +271,7 @@ Obtains the position of a component after the layout is complete. **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | node | Target node. | @@ -291,7 +291,7 @@ Obtains the width and height of a component after measurement. **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | node | Target node. | @@ -311,7 +311,7 @@ Obtains the next sibling node. **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | node | Target node. | @@ -331,7 +331,7 @@ Obtains the parent node. **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | node | Target node. | @@ -351,7 +351,7 @@ Obtains the previous sibling node. **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | node | Target node. | @@ -371,7 +371,7 @@ Obtains the number of child nodes. **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | node | Target node. | @@ -391,7 +391,7 @@ Obtains the custom data saved on the specified component. **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | node | Target component. | @@ -411,7 +411,7 @@ Mounts this component to a parent node, with the mount position after the specif **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | parent | Pointer to the parent node. | | child | Pointer to the child node. | @@ -419,7 +419,7 @@ Mounts this component to a parent node, with the mount position after the specif **Returns** - Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs; returns [ARKUI_ERROR_CODE_NOT_SUPPROTED_FOR_ARKTS_NODE](_ark_u_i___native_module.md) if the following operations are not allowed on BuilderNode generated nodes: setting or resetting attributes, setting events, or adding or editing child nodes. +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md#arkui_errorcode) if the operation is successful. Returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md#arkui_errorcode) if a parameter error occurs. Returns [ARKUI_ERROR_CODE_NOT_SUPPROTED_FOR_ARKTS_NODE](_ark_u_i___native_module.md#arkui_errorcode) if the following operations are not allowed on BuilderNode generated nodes: setting or resetting attributes, setting events, or adding or editing child nodes. ### insertChildAt @@ -433,15 +433,15 @@ Mounts this component to a parent node, with the mount position specified by **p **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | parent | Pointer to the parent node. | | child | Pointer to the child node. | -| postion | Position to which the target child node is to be inserted. If the value is a negative number or invalid, the node is inserted at the end of the parent node. | +| position| Position to which the target child node is to be inserted. If the value is a negative number or invalid, the node is inserted at the end of the parent node. | **Returns** - Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs; returns [ARKUI_ERROR_CODE_NOT_SUPPROTED_FOR_ARKTS_NODE](_ark_u_i___native_module.md) if the following operations are not allowed on BuilderNode generated nodes: setting or resetting attributes, setting events, or adding or editing child nodes. +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md#arkui_errorcode) if the operation is successful. Returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md#arkui_errorcode) if a parameter error occurs. Returns [ARKUI_ERROR_CODE_NOT_SUPPROTED_FOR_ARKTS_NODE](_ark_u_i___native_module.md#arkui_errorcode) if the following operations are not allowed on BuilderNode generated nodes: setting or resetting attributes, setting events, or adding or editing child nodes. ### insertChildBefore @@ -455,7 +455,7 @@ Mounts this component to a parent node, with the mount position before the speci **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | parent | Pointer to the parent node. | | child | Pointer to the child node. | @@ -463,7 +463,7 @@ Mounts this component to a parent node, with the mount position before the speci **Returns** - Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs; returns [ARKUI_ERROR_CODE_NOT_SUPPROTED_FOR_ARKTS_NODE](_ark_u_i___native_module.md) if the following operations are not allowed on BuilderNode generated nodes: setting or resetting attributes, setting events, or adding or editing child nodes. +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md#arkui_errorcode) if the operation is successful. Returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md#arkui_errorcode) if a parameter error occurs. Returns [ARKUI_ERROR_CODE_NOT_SUPPROTED_FOR_ARKTS_NODE](_ark_u_i___native_module.md#arkui_errorcode) if the following operations are not allowed on BuilderNode generated nodes: setting or resetting attributes, setting events, or adding or editing child nodes. ### layoutNode @@ -477,7 +477,7 @@ Lays outs a component and passes the expected position of the component relative **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | node | Target node. | | positionX | X-coordinate. | @@ -485,7 +485,7 @@ Lays outs a component and passes the expected position of the component relative **Returns** - Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md#arkui_errorcode) if the operation is successful. Returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md#arkui_errorcode) if a parameter error occurs. ### markDirty @@ -501,7 +501,7 @@ Regarding updates to system attributes, the ArkUI framework automatically marks **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | node | Node for which you want to mark as dirty area. | | dirtyFlag | Dirty area type. | @@ -518,14 +518,14 @@ Measures a node. You can use the **getMeasuredSize** API to obtain the size afte **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | node | Target node. | | Constraint | Size constraint. | **Returns** - Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md#arkui_errorcode) if the operation is successful. Returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md#arkui_errorcode) if a parameter error occurs. ### registerNodeCustomEvent @@ -539,7 +539,7 @@ Registers a custom event for a node. When the event is triggered, the value is r **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | node | Target node. | | eventType | Type of the event to register. | @@ -548,7 +548,7 @@ Registers a custom event for a node. When the event is triggered, the value is r **Returns** - Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs; returns [ARKUI_ERROR_CODE_ATTRIBUTE_OR_EVENT_NOT_SUPPORTED](_ark_u_i___native_module.md) if the dynamic implementation library of the native API was not found. +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md#arkui_errorcode) if the operation is successful. Returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md#arkui_errorcode) if a parameter error occurs. Returns [ARKUI_ERROR_CODE_ATTRIBUTE_OR_EVENT_NOT_SUPPORTED](_ark_u_i___native_module.md#arkui_errorcode) if the dynamic implementation library of the native API was not found. ### registerNodeCustomEventReceiver @@ -560,7 +560,7 @@ void(* ArkUI_NativeNodeAPI_1::registerNodeCustomEventReceiver) (void(*eventRecei Registers a unified entry point function for custom node event callbacks. -The ArkUI framework collects custom component events generated during the process and calls back the events through the registered **registerNodeCustomEventReceiver**. +The ArkUI framework collects custom component events generated during the process and calls back the events through the registered registerNodeCustomEventReceiver. A new call to this API will overwrite the previously registered event receiver. @@ -570,7 +570,7 @@ To bind with a component instance, you can use the **addNodeCustomEventReceiver* **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | eventReceiver | Event receiver to register. | @@ -586,16 +586,16 @@ Registers an event for the specified node. **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | node | Target node. | | eventType | Type of the event to register. | | targetId | Custom event ID, which is passed in the callback of [ArkUI_NodeEvent](_ark_u_i___native_module.md#arkui_nodeevent-12) when the event is triggered. | -| userData | Custom event parameter, which is passed in the callback of [ArkUI_NodeEvent](_ark_u_i___native_module.md#arkui_nodeevent-12) when the event is triggered. | +| userData | Custom event parameter, which is passed in the callback of [ArkUI_NodeEvent](_ark_u_i___native_module.md#arkui_nodeevent-12) when the event is triggered. | **Returns** - Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs; returns [ARKUI_ERROR_CODE_ATTRIBUTE_OR_EVENT_NOT_SUPPORTED](_ark_u_i___native_module.md) if the dynamic implementation library of the native API was not found; returns [ARKUI_ERROR_CODE_NOT_SUPPROTED_FOR_ARKTS_NODE](_ark_u_i___native_module.md) if the following operations are not allowed on BuilderNode generated nodes: setting or resetting attributes, setting events, or adding or editing child nodes. +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md#arkui_errorcode) if the operation is successful. Returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md#arkui_errorcode) if a parameter error occurs. Returns [ARKUI_ERROR_CODE_ATTRIBUTE_OR_EVENT_NOT_SUPPORTED](_ark_u_i___native_module.md#arkui_errorcode) if the dynamic implementation library of the native API was not found. Returns [ARKUI_ERROR_CODE_NOT_SUPPROTED_FOR_ARKTS_NODE](_ark_u_i___native_module.md#arkui_errorcode) if the following operations are not allowed on BuilderNode generated nodes: setting or resetting attributes, setting events, or adding or editing child nodes. ### registerNodeEventReceiver @@ -617,7 +617,7 @@ To bind with a component instance, you can use the **addNodeEventReceiver** func **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | eventReceiver | Event receiver to register. | @@ -633,7 +633,7 @@ Removes all child nodes from the parent component. **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | parent | Target node. | @@ -660,6 +660,7 @@ void(* ArkUI_NativeNodeAPI_1::unregisterNodeEventReceiver) () Unregisters this event receiver. + ### removeChild ``` @@ -671,14 +672,14 @@ Removes a component from its parent node. **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | parent | Pointer to the parent node. | | child | Pointer to the child node. | **Returns** - Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs; returns [ARKUI_ERROR_CODE_NOT_SUPPROTED_FOR_ARKTS_NODE](_ark_u_i___native_module.md) if the following operations are not allowed on BuilderNode generated nodes: setting or resetting attributes, setting events, or adding or editing child nodes. +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md#arkui_errorcode) if the operation is successful. Returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md#arkui_errorcode) if a parameter error occurs. Returns [ARKUI_ERROR_CODE_NOT_SUPPROTED_FOR_ARKTS_NODE](_ark_u_i___native_module.md#arkui_errorcode) if the following operations are not allowed on BuilderNode generated nodes: setting or resetting attributes, setting events, or adding or editing child nodes. ### removeNodeCustomEventReceiver @@ -692,14 +693,14 @@ Removes a registered custom event callback function from a component. **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | node | Component for which you want to remove the custom event callback function. | | eventReceiver | Custom event callback function to remove. | **Returns** - Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md#arkui_errorcode) if the operation is successful. Returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md#arkui_errorcode) if a parameter error occurs. ### removeNodeEventReceiver @@ -713,14 +714,14 @@ Removes the registered component event callback function from a component. **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | node | Component for which you want to add the event callback function. | | eventReceiver | Event callback function to remove. | **Returns** - Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md#arkui_errorcode) if the operation is successful. Returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md#arkui_errorcode) if a parameter error occurs. ### resetAttribute @@ -734,14 +735,14 @@ Resets an attribute. **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | node | Node whose attribute needs to be reset. | | attribute | Type of the attribute to reset. | **Returns** - Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs; returns [ARKUI_ERROR_CODE_ATTRIBUTE_OR_EVENT_NOT_SUPPORTED](_ark_u_i___native_module.md) if the dynamic implementation library of the native API was not found; returns [ARKUI_ERROR_CODE_NOT_SUPPROTED_FOR_ARKTS_NODE](_ark_u_i___native_module.md) if the following operations are not allowed on BuilderNode generated nodes: setting or resetting attributes, setting events, or adding or editing child nodes. +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md#arkui_errorcode) if the operation is successful. Returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md#arkui_errorcode) if a parameter error occurs. Returns [ARKUI_ERROR_CODE_ATTRIBUTE_OR_EVENT_NOT_SUPPORTED](_ark_u_i___native_module.md#arkui_errorcode) if the dynamic implementation library of the native API was not found. Returns [ARKUI_ERROR_CODE_NOT_SUPPROTED_FOR_ARKTS_NODE](_ark_u_i___native_module.md#arkui_errorcode) if the following operations are not allowed on BuilderNode generated nodes: setting or resetting attributes, setting events, or adding or editing child nodes. ### setAttribute @@ -755,7 +756,7 @@ Sets an attribute. **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | node | Node whose attribute needs to be set. | | attribute | Type of the attribute to set. | @@ -763,7 +764,7 @@ Sets an attribute. **Returns** - Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs; returns [ARKUI_ERROR_CODE_ATTRIBUTE_OR_EVENT_NOT_SUPPORTED](_ark_u_i___native_module.md) if the dynamic implementation library of the native API was not found; returns [ARKUI_ERROR_CODE_NOT_SUPPROTED_FOR_ARKTS_NODE](_ark_u_i___native_module.md) if the following operations are not allowed on BuilderNode generated nodes: setting or resetting attributes, setting events, or adding or editing child nodes. +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md#arkui_errorcode) if the operation is successful. Returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md#arkui_errorcode) if a parameter error occurs. Returns [ARKUI_ERROR_CODE_ATTRIBUTE_OR_EVENT_NOT_SUPPORTED](_ark_u_i___native_module.md#arkui_errorcode) if the dynamic implementation library of the native API was not found. Returns [ARKUI_ERROR_CODE_NOT_SUPPROTED_FOR_ARKTS_NODE](_ark_u_i___native_module.md#arkui_errorcode) if the following operations are not allowed on BuilderNode generated nodes: setting or resetting attributes, setting events, or adding or editing child nodes. ### setLayoutPosition @@ -777,7 +778,7 @@ Sets the position for a component. **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | node | Target node. | | positionX | X-coordinate. | @@ -785,7 +786,7 @@ Sets the position for a component. **Returns** - Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md#arkui_errorcode) if the operation is successful. Returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md#arkui_errorcode) if a parameter error occurs. ### setLengthMetricUnit @@ -799,14 +800,14 @@ Sets the unit for a component. **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | node | Component for which you want to set the unit. | | unit | Unit, which is an enumerated value of [ArkUI_LengthMetricUnit](_ark_u_i___native_module.md#arkui_lengthmetricunit). The default value is **ARKUI_LENGTH_METRIC_UNIT_DEFAULT**. | **Returns** - Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md#arkui_errorcode) if the operation is successful. Returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md#arkui_errorcode) if a parameter error occurs. ### setMeasuredSize @@ -820,7 +821,7 @@ Sets the width and height for a component after the measurement. **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | node | Target node. | | width | Width to set. | @@ -828,7 +829,7 @@ Sets the width and height for a component after the measurement. **Returns** - Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md#arkui_errorcode) if the operation is successful. Returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md#arkui_errorcode) if a parameter error occurs. ### setUserData @@ -842,14 +843,14 @@ Saves custom data on the specified component. **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | node | Component on which the custom data will be saved. | | userData | Custom data to be saved. | **Returns** - Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md) if the operation is successful; returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md) if a parameter error occurs. +Returns [ARKUI_ERROR_CODE_NO_ERROR](_ark_u_i___native_module.md#arkui_errorcode) if the operation is successful. Returns [ARKUI_ERROR_CODE_PARAM_INVALID](_ark_u_i___native_module.md#arkui_errorcode) if a parameter error occurs. ### unregisterNodeCustomEvent @@ -863,7 +864,7 @@ Unregisters a custom event for a node. **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | node | Target node. | | eventType | Type of the event to unregister. | @@ -880,7 +881,7 @@ Unregisters an event for the specified node. **Parameters** -| Name | Description | +| Name| Description| | -------- | -------- | | node | Target node. | | eventType | Type of the event to unregister. | diff --git a/en/application-dev/reference/apis-arkui/_ark_u_i___node_component_snapshot.md b/en/application-dev/reference/apis-arkui/_ark_u_i___node_component_snapshot.md new file mode 100644 index 0000000000000000000000000000000000000000..8e631040b483af065f202066e9423c5f0318073c --- /dev/null +++ b/en/application-dev/reference/apis-arkui/_ark_u_i___node_component_snapshot.md @@ -0,0 +1,137 @@ +# OH_ComponentSnapshot + + +## Overview + +Provides APIs for obtaining component snapshots. + +**Since**: 15 + +## Summary + +### Structs + +| Name| Description| +| -------- | -------- | +| struct [ArkUI_SnapshotOptions](native__type_8h.md#ArkUI_SnapshotOptions) | Defines a struct for snapshot options.| + +### Functions + +| Name| Description| +| -------- | -------- | +| int32_t [OH_ArkUI_GetNodeSnapshot](native__node_8h.md#OH_ArkUI_GetNodeSnapshot) () | Obtains a snapshot of a given component. If the node is not in the component tree or has not been rendered, the snapshot operation will fail. When the **Pixelmap** object created is no longer in use, it should be released by calling **OH_PixelmapNative_Release**.| +| ArkUI_SnapshotOptions [OH_ArkUI_CreateSnapshotOptions](native__type_8h.md#OH_ArkUI_CreateSnapshotOptions) () | Creates a snapshot options object, which must be released using **OH_ArkUI_SnapshotOptions_Dispose** when no longer in use.| +| void [OH_ArkUI_DestroySnapshotOptions](native__type_8h.md#OH_ArkUI_DestroySnapshotOptions) () | Destroys a snapshot options object.| +| int32_t [OH_ArkUI_SnapshotOptions_SetScale](native__type_8h.md#OH_ArkUI_SnapshotOptions_SetScale) () | Sets the scale property in the snapshot options.| + +### Creates a snapshot options object. + +## Type Description + +### ArkUI_SnapshotOptions + +``` +typedef struct ArkUI_SnapshotOptions ArkUI_SnapshotOptions; +``` + +**Description** + +Defines a struct for snapshot options. + +**Since**: 15 + +## Function Description + +### OH_ArkUI_GetNodeSnapshot() + +``` +int32_t OH_ArkUI_GetNodeSnapshot(ArkUI_NodeHandle node, ArkUI_SnapshotOptions* snapshotOptions, + OH_PixelmapNative** pixelMap) +``` + +**Description** + +Obtains a snapshot of the specified node. + +**Since**: 15 + +**Parameters** + +| Name | Description | +| --------------- | ------------------------------------------------------------ | +| node | Target node to capture a snapshot. | +| snapshotOptions | Snapshot settings. If the value is null, the default settings are used. | +| pixelmap | Pointer to the Pixelmap created by the system.| + +**Returns** + +| Return Value | Description | +| --------------------------------------------- | -------------- | +| `ARKUI_ERROR_CODE_NO_ERROR` | Success. | +| `ARKUI_ERROR_CODE_PARAM_INVALID` | Parameter error. | +| `ARKUI_ERROR_CODE_INTERNAL_ERROR` | Snapshot failed. A null pointer is returned. | +| `ARKUI_ERROR_CODE_COMPONENT_SNAPSHOT_TIMEOUT` | Snapshot timed out.| + + +### OH_ArkUI_CreateSnapshotOptions() + +``` +ArkUI_SnapshotOptions* OH_ArkUI_CreateSnapshotOptions() +``` + +**Description** + +Creates a snapshot options object, which must be released using **OH_ArkUI_SnapshotOptions_Dispose** when no longer in use. + +**Since**: 15 + +**Returns** + +| Return Value | Description | +| ------------------------ | ------------------------------------------------------------ | +| `ArkUI_SnapshotOptions*` | Pointer to the created snapshot options object. If a null pointer is returned, creation failed, possibly due to insufficient memory.| + + +### OH_ArkUI_DestroySnapshotOptions() + +``` +void OH_ArkUI_DestroySnapshotOptions(ArkUI_SnapshotOptions* snapshotOptions) +``` + +**Description** + +Destroys a snapshot options object. + +**Since**: 15 + +**Parameters** + +| Name | Description | +| --------------- | ---- | +| snapshotOptions | Screenshot options.| + +### OH_ArkUI_SnapshotOptions_SetScale() + +``` +int32_t OH_ArkUI_SnapshotOptions_SetScale(ArkUI_SnapshotOptions* snapshotOptions, float scale) +``` + +**Description** + +Sets the scale property in the snapshot options. + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| snapshotOptions | Screenshot options.| +| scale | Scale factor.| + +**Returns** + +| Return Value | Description | +| -------------------------------- | ---------- | +| `ARKUI_ERROR_CODE_NO_ERROR` | Success.| +| `ARKUI_ERROR_CODE_PARAM_INVALID` | Parameter error.
A possible cause is that mandatory parameters are left unspecified.| diff --git a/en/application-dev/reference/apis-arkui/_ark_u_i___text_change_event.md b/en/application-dev/reference/apis-arkui/_ark_u_i___text_change_event.md index caf58e299da064a7c1ea488c258bdb1c5fd9a816..4216ab646ef408a6f154ccd1af98e2f5a543001c 100644 --- a/en/application-dev/reference/apis-arkui/_ark_u_i___text_change_event.md +++ b/en/application-dev/reference/apis-arkui/_ark_u_i___text_change_event.md @@ -5,7 +5,7 @@ Defines the return types for the callback events triggered when the content of an input box changes, including the preview content. -**Since**: 16 +**Since**: 15 **Related module**: [ArkUI_NativeModule](_ark_u_i___native_module.md) diff --git a/en/application-dev/reference/apis-arkui/_window_manager___avoid_area.md b/en/application-dev/reference/apis-arkui/_window_manager___avoid_area.md new file mode 100644 index 0000000000000000000000000000000000000000..74cb90c3dd93d54b8b0729a7a1af50f3b261d446 --- /dev/null +++ b/en/application-dev/reference/apis-arkui/_window_manager___avoid_area.md @@ -0,0 +1,70 @@ +# WindowManager_AvoidArea + + +## Overview + +The WindowManager_AvoidArea struct describes the avoid area. + +**Since**: 15 + +**Related module**: [WindowManager_NativeModule](_window_manager___native_module.md) + + +## Summary + + +### Member Variables + +| Name| Description| +| -------- | -------- | +| [WindowManager_Rect](_window_manager___rect.md) [topRect](#toprect) | Top rectangle of the avoid area.| +| [WindowManager_Rect](_window_manager___rect.md) [leftRect](#leftrect) | Left rectangle of the avoid area.| +| [WindowManager_Rect](_window_manager___rect.md) [rightRect](#rightrect) | Right rectangle of the avoid area.| +| [WindowManager_Rect](_window_manager___rect.md) [bottomRect](#bottomrect) | Bottom rectangle of the avoid area.| + + +## Member Variable Description + + +### bottomRect + +``` +WindowManager_Rect WindowManager_AvoidArea::bottomRect +``` + +**Description** + +Bottom rectangle of the avoid area. + + +### leftRect + +``` +WindowManager_Rect WindowManager_AvoidArea::leftRect +``` + +**Description** + +Left rectangle of the avoid area. + + +### rightRect + +``` +WindowManager_Rect WindowManager_AvoidArea::rightRect +``` + +**Description** + +Right rectangle of the avoid area. + + +### topRect + +``` +WindowManager_Rect WindowManager_AvoidArea::topRect +``` + +**Description** + +Top rectangle of the avoid area. diff --git a/en/application-dev/reference/apis-arkui/_window_manager___native_module.md b/en/application-dev/reference/apis-arkui/_window_manager___native_module.md index a1838c3b64fbd624bfeb9296ee4248a3f80efb3c..405a85ccde4910d159838f1c5572cfc2cd5ebd49 100644 --- a/en/application-dev/reference/apis-arkui/_window_manager___native_module.md +++ b/en/application-dev/reference/apis-arkui/_window_manager___native_module.md @@ -13,33 +13,65 @@ The WindowManager_NativeModule module provides the capabilities of managing appl ### Files -| Name| Description| +| Name| Description| | -------- | -------- | -| [oh_window_comm.h](oh__window__comm_8h.md) | Declares the common enums and definitions of the window manager.| -| [oh_window_event_filter.h](oh__window__event__filter_8h.md) | Declares the APIs for a window to filter multimodal key events. When a multimodal input event passes through the window, the window can interrupt the event to prevent it from being further distributed.| +| [oh_window.h](oh__window_8h.md) | Declares the window management APIs. You can use the APIs to set and obtain the properties of a window, and set its status bar style and navigation bar style.| +| [oh_window_comm.h](oh__window__comm_8h.md) | Declares the common enums and definitions of the window manager.| +| [oh_window_event_filter.h](oh__window__event__filter_8h.md) | Declares the APIs for a window to filter multimodal key events. When a multimodal input event passes through the window, the window can interrupt the event to prevent it from being further distributed.| + + +### Structs + +| Name| Description| +| -------- | -------- | +| struct [WindowManager_Rect](_window_manager___rect.md) | Defines a struct for the window rectangle, including the window position, width, and height.| +| struct [WindowManager_WindowProperties](_window_manager___window_properties.md) | Defines a struct for the window properties.| +| struct [WindowManager_AvoidArea](_window_manager___avoid_area.md) | Defines a struct for the avoid area.| ### Types -| Name| Description| +| Name| Description| | -------- | -------- | -| typedef enum [WindowManager_ErrorCode](#windowmanager_errorcode) [WindowManager_ErrorCode](#windowmanager_errorcode) | Defines an enum for the status codes returned by the window manager interface.| -| typedef bool(\*[OH_NativeWindowManager_KeyEventFilter](#oh_nativewindowmanager_keyeventfilter)) (Input_KeyEvent \*keyEvent) | Defines a function for filtering a multimodal key event.| +| typedef enum [WindowManager_ErrorCode](#windowmanager_errorcode) [WindowManager_ErrorCode](#windowmanager_errorcode) | Defines an enum for the status codes returned by the window manager interface.| +| typedef bool(\* [OH_NativeWindowManager_KeyEventFilter](#oh_nativewindowmanager_keyeventfilter)) (Input_KeyEvent \*keyEvent) | Defines a function for filtering multimodal key events.| +| typedef bool(\* [OH_NativeWindowManager_MouseEventFilter](#oh_nativewindowmanager_mouseeventfilter)) (Input_MouseEvent \*mouseEvent) | Defines a function for filtering multimodal mouse events.| +| typedef bool(\* [OH_NativeWindowManager_TouchEventFilter](#oh_nativewindowmanager_toucheventfilter)) (Input_TouchEvent \*touchEvent) | Defines a function for filtering multimodal touch events.| ### Enums -| Name| Description| +| Name| Description| | -------- | -------- | -| [WindowManager_ErrorCode](#windowmanager_errorcode) { OK = 0, INVAILD_WINDOW_ID = 1000, SERVICE_ERROR = 2000 } | Enumerates the status codes returned by the window manager interface.| +| [WindowManager_ErrorCode](#windowmanager_errorcode-1) {
OK = 0, WINDOW_MANAGER_ERRORCODE_NO_PERMISSION = 201, WINDOW_MANAGER_ERRORCODE_INVALID_PARAM = 401, WINDOW_MANAGER_ERRORCODE_DEVICE_NOT_SUPPORTED = 801,
INVAILD_WINDOW_ID = 1000, SERVICE_ERROR = 2000, WINDOW_MANAGER_ERRORCODE_STATE_ABNORMAL = 1300002, WINDOW_MANAGER_ERRORCODE_SYSTEM_ABNORMAL = 1300003
} | Enumerates the status codes returned by the window manager interface.| +| [WindowManager_AvoidAreaType](#windowmanager_avoidareatype) {
WINDOW_MANAGER_AVOID_AREA_TYPE_SYSTEM = 0, WINDOW_MANAGER_AVOID_AREA_TYPE_CUTOUT = 1, WINDOW_MANAGER_AVOID_AREA_TYPE_SYSTEM_GESTURE = 2, WINDOW_MANAGER_AVOID_AREA_TYPE_KEYBOARD = 3,
WINDOW_MANAGER_AVOID_AREA_TYPE_NAVIGATION_INDICATOR = 4
} | Enumerates the avoid area types.| +| [WindowManager_WindowType](#windowmanager_windowtype) { WINDOW_MANAGER_WINDOW_TYPE_APP = 0, WINDOW_MANAGER_WINDOW_TYPE_MAIN = 1, WINDOW_MANAGER_WINDOW_TYPE_FLOAT = 8, WINDOW_MANAGER_WINDOW_TYPE_DIALOG = 16 } | Enumerates the window types.| ### Functions -| Name| Description| +| Name| Description| | -------- | -------- | -| [WindowManager_ErrorCode](#windowmanager_errorcode) [OH_NativeWindowManager_RegisterKeyEventFilter](#oh_nativewindowmanager_registerkeyeventfilter) (int32_t windowId, [OH_NativeWindowManager_KeyEventFilter](#oh_nativewindowmanager_keyeventfilter) keyEventFilter) | Registers the function for filtering a multimodal key event.| -| [WindowManager_ErrorCode](#windowmanager_errorcode) [OH_NativeWindowManager_UnregisterKeyEventFilter](#oh_nativewindowmanager_unregisterkeyeventfilter) (int32_t windowId) | Unregisters the function for filtering a multimodal key event.| +| int32_t [OH_WindowManager_SetWindowStatusBarEnabled](#oh_windowmanager_setwindowstatusbarenabled) (int32_t windowId, bool enabled, bool enableAnimation) | Sets whether to display the status bar in a window.| +| int32_t [OH_WindowManager_SetWindowStatusBarColor](#oh_windowmanager_setwindowstatusbarcolor) (int32_t windowId, int32_t color) | Sets the color of the status bar in a window.| +| int32_t [OH_WindowManager_SetWindowNavigationBarEnabled](#oh_windowmanager_setwindownavigationbarenabled) (int32_t windowId, bool enabled, bool enableAnimation) | Sets whether to display the navigation bar in a window.| +| int32_t [OH_WindowManager_GetWindowAvoidArea](#oh_windowmanager_getwindowavoidarea) (int32_t windowId, [WindowManager_AvoidAreaType](#windowmanager_avoidareatype) type, [WindowManager_AvoidArea](_window_manager___avoid_area.md) \*avoidArea) | Obtains the avoid area of a window.| +| [WindowManager_ErrorCode](#windowmanager_errorcode-1) [OH_WindowManager_IsWindowShown](#oh_windowmanager_iswindowshown) (int32_t windowId, bool \*isShow) | Checks whether a window is displayed.| +| [WindowManager_ErrorCode](#windowmanager_errorcode-1) [OH_WindowManager_ShowWindow](#oh_windowmanager_showwindow) (int32_t windowId) | Displays a window.| +| int32_t [OH_WindowManager_SetWindowTouchable](#oh_windowmanager_setwindowtouchable) (int32_t windowId, bool isTouchable) | Sets whether a window is touchable.| +| int32_t [OH_WindowManager_SetWindowFocusable](#oh_windowmanager_setwindowfocusable) (int32_t windowId, bool isFocusable) | Sets whether a window is focusable.| +| int32_t [OH_WindowManager_SetWindowBackgroundColor](#oh_windowmanager_setwindowbackgroundcolor) (int32_t windowId, const char \*color) | Sets the background color of a window.| +| int32_t [OH_WindowManager_SetWindowBrightness](#oh_windowmanager_setwindowbrightness) (int32_t windowId, float brightness) | Sets the screen brightness of a window.| +| int32_t [OH_WindowManager_SetWindowKeepScreenOn](#oh_windowmanager_setwindowkeepscreenon) (int32_t windowId, bool isKeepScreenOn) | Sets whether to always keep the screen on for a window.| +| int32_t [OH_WindowManager_SetWindowPrivacyMode](#oh_windowmanager_setwindowprivacymode) (int32_t windowId, bool isPrivacy) | Sets whether to enable privacy mode for a window.| +| int32_t [OH_WindowManager_GetWindowProperties](#oh_windowmanager_getwindowproperties) (int32_t windowId, [WindowManager_WindowProperties](_window_manager___window_properties.md) \*windowProperties) | Obtains the properties of a window.| +| int32_t [OH_WindowManager_Snapshot](#oh_windowmanager_snapshot) (int32_t windowId, OH_PixelmapNative \*pixelMap) | Obtains the snapshot of a window.| +| [WindowManager_ErrorCode](#windowmanager_errorcode-1) [OH_NativeWindowManager_RegisterKeyEventFilter](#oh_nativewindowmanager_registerkeyeventfilter) (int32_t windowId, [OH_NativeWindowManager_KeyEventFilter](#oh_nativewindowmanager_keyeventfilter) keyEventFilter) | Registers the function for filtering multimodal key events.| +| [WindowManager_ErrorCode](#windowmanager_errorcode-1) [OH_NativeWindowManager_UnregisterKeyEventFilter](#oh_nativewindowmanager_unregisterkeyeventfilter) (int32_t windowId) | Unregisters the function for filtering multimodal key events.| +| [WindowManager_ErrorCode](#windowmanager_errorcode-1) [OH_NativeWindowManager_RegisterMouseEventFilter](#oh_nativewindowmanager_registermouseeventfilter) (int32_t windowId, [OH_NativeWindowManager_MouseEventFilter](#oh_nativewindowmanager_mouseeventfilter) mouseEventFilter) | Registers the function for filtering multimodal mouse events.| +| [WindowManager_ErrorCode](#windowmanager_errorcode-1) [OH_NativeWindowManager_UnregisterMouseEventFilter](#oh_nativewindowmanager_unregistermouseeventfilter) (int32_t windowId) | Unregisters the function for filtering multimodal mouse events.| +| [WindowManager_ErrorCode](#windowmanager_errorcode-1) [OH_NativeWindowManager_RegisterTouchEventFilter](#oh_nativewindowmanager_registertoucheventfilter) (int32_t windowId, [OH_NativeWindowManager_TouchEventFilter](#oh_nativewindowmanager_toucheventfilter) touchEventFilter) | Registers the function for filtering multimodal touch events.| +| [WindowManager_ErrorCode](#windowmanager_errorcode-1) [OH_NativeWindowManager_UnregisterTouchEventFilter](#oh_nativewindowmanager_unregistertoucheventfilter) (int32_t windowId) | Unregisters the function for filtering multimodal touch events.| ## Type Description @@ -53,15 +85,61 @@ typedef bool(* OH_NativeWindowManager_KeyEventFilter) (Input_KeyEvent *keyEvent) **Description** -Defines a function for filtering a multimodal key event. +Defines a function for filtering multimodal key events. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| +| -------- | -------- | +| keyEvent | Pointer to the multimodal key event. For details, see **Input_KeyEvent**. The event is defined in **oh_input_manager**.| + +**Returns** + +Returns **true** if the event will be intercepted; returns **false** otherwise. + + +### OH_NativeWindowManager_MouseEventFilter + +``` +typedef bool(* OH_NativeWindowManager_MouseEventFilter) (Input_MouseEvent *mouseEvent) +``` + +**Description** + +Defines a function for filtering multimodal mouse events. + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| mouseEvent | Pointer to the multimodal mouse event. For details, see **Input_MouseEvent**. The event is defined in **oh_input_manager**.| + +**Returns** + +Returns **true** if the event will be intercepted; returns **false** otherwise. + + +### OH_NativeWindowManager_TouchEventFilter + +``` +typedef bool(* OH_NativeWindowManager_TouchEventFilter) (Input_TouchEvent *touchEvent) +``` + +**Description** + +Defines a function for filtering multimodal touch events. + +**Since**: 15 + +**Parameters** + +| Name| Description| | -------- | -------- | -| keyEvent | Multimodal key event. For details, see **Input_KeyEvent**. The event is defined in **oh_input_manager**.| +| touchEvent | Pointer to the multimodal touch event. For details, see **Input_TouchEvent**. The event is defined in **oh_input_manager**.| **Returns** @@ -84,6 +162,27 @@ Defines an enum for the status codes returned by the window manager interface. ## Enum Description +### WindowManager_AvoidAreaType + +``` +enum WindowManager_AvoidAreaType +``` + +**Description** + +Enumerates the avoid area types. + +**Since**: 15 + +| Value| Description| +| -------- | -------- | +| WINDOW_MANAGER_AVOID_AREA_TYPE_SYSTEM | System avoid area.| +| WINDOW_MANAGER_AVOID_AREA_TYPE_CUTOUT | Cutout.| +| WINDOW_MANAGER_AVOID_AREA_TYPE_SYSTEM_GESTURE | System gesture area.| +| WINDOW_MANAGER_AVOID_AREA_TYPE_KEYBOARD | Keyboard area.| +| WINDOW_MANAGER_AVOID_AREA_TYPE_NAVIGATION_INDICATOR | Navigation bar area.| + + ### WindowManager_ErrorCode ``` @@ -96,11 +195,36 @@ Enumerates the status codes returned by the window manager interface. **Since**: 12 -| Value| Description| +| Value| Description| | -------- | -------- | -| OK | Operation successful.| -| INVAILD_WINDOW_ID | Invalid window ID.| -| SERVICE_ERROR | Service error.| +| OK | Operation successful.| +| WINDOW_MANAGER_ERRORCODE_NO_PERMISSION15+ | No permission.| +| WINDOW_MANAGER_ERRORCODE_INVALID_PARAM15+ | Invalid parameter.| +| WINDOW_MANAGER_ERRORCODE_DEVICE_NOT_SUPPORTED15+ | Not supported by the device.| +| INVAILD_WINDOW_ID | Invalid window ID.| +| SERVICE_ERROR | Service error.| +| WINDOW_MANAGER_ERRORCODE_STATE_ABNORMAL15+ | Abnormal window status.| +| WINDOW_MANAGER_ERRORCODE_SYSTEM_ABNORMAL15+ | Abnormal window manager service.| + + +### WindowManager_WindowType + +``` +enum WindowManager_WindowType +``` + +**Description** + +Enumerates the window types. + +**Since**: 15 + +| Value| Description| +| -------- | -------- | +| WINDOW_MANAGER_WINDOW_TYPE_APP | Child window.| +| WINDOW_MANAGER_WINDOW_TYPE_MAIN | Main window.| +| WINDOW_MANAGER_WINDOW_TYPE_FLOAT | Floating window.| +| WINDOW_MANAGER_WINDOW_TYPE_DIALOG | Modal window.| ## Function Description @@ -114,16 +238,64 @@ WindowManager_ErrorCode OH_NativeWindowManager_RegisterKeyEventFilter (int32_t w **Description** -Registers the function for filtering a multimodal key event. +Registers the function for filtering multimodal key events. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| +| -------- | -------- | +| windowId | ID of the window for which the function is registered.| +| keyEventFilter | Function to register.| + +**Returns** + +Returns a status code defined in [WindowManager_ErrorCode](#windowmanager_errorcode). + + +### OH_NativeWindowManager_RegisterMouseEventFilter() + +``` +WindowManager_ErrorCode OH_NativeWindowManager_RegisterMouseEventFilter (int32_t windowId, OH_NativeWindowManager_MouseEventFilter mouseEventFilter ) +``` + +**Description** + +Registers the function for filtering multimodal mouse events. + +**Since**: 15 + +**Parameters** + +| Name| Description| | -------- | -------- | -| windowId | ID of the window for which the function is registered.| -| keyEventFilter | Function for filtering a multimodal key event.| +| windowId | ID of the window for which the function is registered.| +| mouseEventFilter | Function to register.| + +**Returns** + +Returns a status code defined in [WindowManager_ErrorCode](#windowmanager_errorcode). + + +### OH_NativeWindowManager_RegisterTouchEventFilter() + +``` +WindowManager_ErrorCode OH_NativeWindowManager_RegisterTouchEventFilter (int32_t windowId, OH_NativeWindowManager_TouchEventFilter touchEventFilter ) +``` + +**Description** + +Registers the function for filtering multimodal touch events. + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| windowId | ID of the window for which the function is registered.| +| touchEventFilter | Function to register.| **Returns** @@ -138,16 +310,518 @@ WindowManager_ErrorCode OH_NativeWindowManager_UnregisterKeyEventFilter (int32_t **Description** -Unregisters the function for filtering a multimodal key event. +Unregisters the function for filtering multimodal key events. **Since**: 12 **Parameters** -| Name| Description| +| Name| Description| +| -------- | -------- | +| windowId | ID of the window for which the function is unregistered.| + +**Returns** + +Returns a status code defined in [WindowManager_ErrorCode](#windowmanager_errorcode). + + +### OH_NativeWindowManager_UnregisterMouseEventFilter() + +``` +WindowManager_ErrorCode OH_NativeWindowManager_UnregisterMouseEventFilter (int32_t windowId) +``` + +**Description** + +Unregisters the function for filtering multimodal mouse events. + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| windowId | ID of the window for which the function is unregistered.| + +**Returns** + +Returns a status code defined in [WindowManager_ErrorCode](#windowmanager_errorcode). + + +### OH_NativeWindowManager_UnregisterTouchEventFilter() + +``` +WindowManager_ErrorCode OH_NativeWindowManager_UnregisterTouchEventFilter (int32_t windowId) +``` + +**Description** + +Unregisters the function for filtering multimodal touch events. + +**Since**: 15 + +**Parameters** + +| Name| Description| | -------- | -------- | -| windowId | ID of the window for which the function is unregistered.| +| windowId | ID of the window for which the function is unregistered.| **Returns** Returns a status code defined in [WindowManager_ErrorCode](#windowmanager_errorcode). + + +### OH_WindowManager_GetWindowAvoidArea() + +``` +int32_t OH_WindowManager_GetWindowAvoidArea (int32_t windowId, WindowManager_AvoidAreaType type, WindowManager_AvoidArea * avoidArea ) +``` + +**Description** + +Obtains the avoid area of a window. + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| windowId | Window ID. The default value is **0**. The value is an integer.| +| type | Type of the avoid area.| +| avoidArea | Pointer to the avoid area.| + +**Returns** + +Returns one of the following result codes: + +**OK**: This code is returned if the function is successfully called, and the pointer to the avoid area is returned. + +**WINDOW_MANAGER_ERRORCODE_INVALID_PARAM**: This code is returned if a parameter is incorrect. + +**WINDOW_MANAGER_ERRORCODE_STATE_ABNORMAL**: This code is returned if the window status is abnormal. + +**WINDOW_MANAGER_ERRORCODE_SYSTEM_ABNORMAL**: This code is returned if the window manager service is abnormal. + + +### OH_WindowManager_GetWindowProperties() + +``` +int32_t OH_WindowManager_GetWindowProperties (int32_t windowId, WindowManager_WindowProperties * windowProperties ) +``` + +**Description** + +Obtains the properties of a window. + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| windowId | Window ID. The default value is **0**. The value is an integer.| +| windowProperties | Pointer to the properties.| + +**Returns** + +Returns one of the following result codes: + +**OK**: This code is returned if the function is successfully called, and the pointer to the window properties is returned. + +**WINDOW_MANAGER_ERRORCODE_INVALID_PARAM**: This code is returned if a parameter is incorrect. + +**WINDOW_MANAGER_ERRORCODE_STATE_ABNORMAL**: This code is returned if the window status is abnormal. + +**WINDOW_MANAGER_ERRORCODE_SYSTEM_ABNORMAL**: This code is returned if the window manager service is abnormal. + + +### OH_WindowManager_IsWindowShown() + +``` +WindowManager_ErrorCode OH_WindowManager_IsWindowShown (int32_t windowId, bool * isShow ) +``` + +**Description** + +Checks whether a window is displayed. + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| windowId | Window ID. The default value is **0**. The value is an integer.| +| isShow | Pointer to the check result. The value **true** means that the window is displayed, and **false** means the opposite.| + +**Returns** + +Returns one of the following result codes: + +**OK**: This code is returned if the function is successfully called. + +**WINDOW_MANAGER_ERRORCODE_INVALID_PARAM**: This code is returned if a parameter is incorrect. + +**WINDOW_MANAGER_ERRORCODE_STATE_ABNORMAL**: This code is returned if the window status is abnormal. + + +### OH_WindowManager_SetWindowBackgroundColor() + +``` +int32_t OH_WindowManager_SetWindowBackgroundColor (int32_t windowId, const char * color ) +``` + +**Description** + +Sets the background color of a window. + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| windowId | Window ID. The default value is **0**. The value is an integer.| +| color | Pointer to the background color. The value is a string in hexadecimal RGB or ARGB color format.| + +**Returns** + +Returns one of the following result codes: + +**OK**: This code is returned if the function is successfully called. + +**WINDOW_MANAGER_ERRORCODE_INVALID_PARAM**: This code is returned if a parameter is incorrect. + +**WINDOW_MANAGER_ERRORCODE_STATE_ABNORMAL**: This code is returned if the window status is abnormal. + + +### OH_WindowManager_SetWindowBrightness() + +``` +int32_t OH_WindowManager_SetWindowBrightness (int32_t windowId, float brightness ) +``` + +**Description** + +Sets the screen brightness of a window. + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| windowId | Window ID. The default value is **0**. The value is an integer.| +| brightness | Screen brightness. The value is a floating point number in the range [0.0, 1.0] or set to **-1.0**, where **1.0** indicates the brightest, and **-1.0** is the default brightness.| + +**Returns** + +Returns one of the following result codes: + +**OK**: This code is returned if the function is successfully called. + +**WINDOW_MANAGER_ERRORCODE_INVALID_PARAM**: This code is returned if a parameter is incorrect. + +**WINDOW_MANAGER_ERRORCODE_STATE_ABNORMAL**: This code is returned if the window status is abnormal. + +**WINDOW_MANAGER_ERRORCODE_SYSTEM_ABNORMAL**: This code is returned if the window manager service is abnormal. + + +### OH_WindowManager_SetWindowFocusable() + +``` +int32_t OH_WindowManager_SetWindowFocusable (int32_t windowId, bool isFocusable ) +``` + +**Description** + +Sets whether a window is focusable. + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| windowId | Window ID. The default value is **0**. The value is an integer.| +| isFocusable | Whether the window is focusable. The value **true** means that the window is focusable, and **false** means the opposite.| + +**Returns** + +Returns one of the following result codes: + +**OK**: This code is returned if the function is successfully called. + +**WINDOW_MANAGER_ERRORCODE_INVALID_PARAM**: This code is returned if a parameter is incorrect. + +**WINDOW_MANAGER_ERRORCODE_STATE_ABNORMAL**: This code is returned if the window status is abnormal. + +**WINDOW_MANAGER_ERRORCODE_SYSTEM_ABNORMAL**: This code is returned if the window manager service is abnormal. + + +### OH_WindowManager_SetWindowKeepScreenOn() + +``` +int32_t OH_WindowManager_SetWindowKeepScreenOn (int32_t windowId, bool isKeepScreenOn ) +``` + +**Description** + +Sets whether to always keep the screen on for a window. + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| windowId | Window ID. The default value is **0**. The value is an integer.| +| isKeepScreenOn | Whether to always keep the screen on. The value **true** means to always keep the screen on, and the value **false** indicates the opposite.| + +**Returns** + +Returns one of the following result codes: + +**OK**: This code is returned if the function is successfully called. + +**WINDOW_MANAGER_ERRORCODE_INVALID_PARAM**: This code is returned if a parameter is incorrect. + +**WINDOW_MANAGER_ERRORCODE_STATE_ABNORMAL**: This code is returned if the window status is abnormal. + +**WINDOW_MANAGER_ERRORCODE_SYSTEM_ABNORMAL**: This code is returned if the window manager service is abnormal. + + +### OH_WindowManager_SetWindowNavigationBarEnabled() + +``` +int32_t OH_WindowManager_SetWindowNavigationBarEnabled (int32_t windowId, bool enabled, bool enableAnimation ) +``` + +**Description** + +Sets whether to display the navigation bar in a window. + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| windowId | Window ID. The default value is **0**. The value is an integer.| +| enabled | Whether to display the navigation bar. The value **true** means to display the navigation bar, and **false** means the opposite.| +| enableAnimation | Whether to enable the show/hide animation of the navigation bar. The value **true** means to enable the show/hide animation of the navigation bar, and **false** means the opposite.| + +**Returns** + +Returns one of the following result codes: + +**OK**: This code is returned if the function is successfully called. + +**WINDOW_MANAGER_ERRORCODE_INVALID_PARAM**: This code is returned if a parameter is incorrect. + +**WINDOW_MANAGER_ERRORCODE_DEVICE_NOT_SUPPORTED**: This code is returned if the feature is not supported by the device. + +**WINDOW_MANAGER_ERRORCODE_STATE_ABNORMAL**: This code is returned if the window status is abnormal. + +**WINDOW_MANAGER_ERRORCODE_SYSTEM_ABNORMAL**: This code is returned if the window manager service is abnormal. + + +### OH_WindowManager_SetWindowPrivacyMode() + +``` +int32_t OH_WindowManager_SetWindowPrivacyMode (int32_t windowId, bool isPrivacy ) +``` + +**Description** + +Sets whether to enable privacy mode for a window. + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| windowId | Window ID. The default value is **0**. The value is an integer.| +| isPrivacy | Whether to enable privacy mode. The value **true** means to enable privacy mode, and **false** means the opposite.| + +**Required permissions**: ohos.permission.PRIVACY_WINDOW + +**Returns** + +Returns one of the following result codes: + +**OK**: This code is returned if the function is successfully called. + +**WINDOW_MANAGER_ERRORCODE_INVALID_PARAM**: This code is returned if a parameter is incorrect. + +**WINDOW_MANAGER_ERRORCODE_INVALID_PARAM**: This code is returned if a parameter is incorrect. + +**WINDOW_MANAGER_ERRORCODE_STATE_ABNORMAL**: This code is returned if the window status is abnormal. + +**WINDOW_MANAGER_ERRORCODE_SYSTEM_ABNORMAL**: This code is returned if the window manager service is abnormal. + +**WINDOW_MANAGER_ERRORCODE_NO_PERMISSION**: This code is returned if the permission verification fails. + + +### OH_WindowManager_SetWindowStatusBarColor() + +``` +int32_t OH_WindowManager_SetWindowStatusBarColor (int32_t windowId, int32_t color ) +``` + +**Description** + +Sets the color of the status bar in a window. + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| windowId | Window ID. The default value is **0**. The value is an integer.| +| color | Color to set, in the ARGB format.| + +**Returns** + +Returns one of the following result codes: + +**OK**: This code is returned if the function is successfully called. + +**WINDOW_MANAGER_ERRORCODE_INVALID_PARAM**: This code is returned if a parameter is incorrect. + +**WINDOW_MANAGER_ERRORCODE_DEVICE_NOT_SUPPORTED**: This code is returned if the feature is not supported by the device. + +**WINDOW_MANAGER_ERRORCODE_STATE_ABNORMAL**: This code is returned if the window status is abnormal. + +**WINDOW_MANAGER_ERRORCODE_SYSTEM_ABNORMAL**: This code is returned if the window manager service is abnormal. + + +### OH_WindowManager_SetWindowStatusBarEnabled() + +``` +int32_t OH_WindowManager_SetWindowStatusBarEnabled (int32_t windowId, bool enabled, bool enableAnimation ) +``` + +**Description** + +Sets whether to display the status bar in a window. + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| windowId | Window ID. The default value is **0**. The value is an integer.| +| enabled | Whether to display the status bar. The value **true** means to display the status bar, and **false** means the opposite.| +| enableAnimation | Whether to enable the show/hide animation of the status bar. The value **true** means to enable the show/hide animation of the status bar, and **false** means the opposite.| + +**Returns** + +Returns one of the following result codes: + +**OK**: This code is returned if the function is successfully called. + +**WINDOW_MANAGER_ERRORCODE_INVALID_PARAM**: This code is returned if a parameter is incorrect. + +**WINDOW_MANAGER_ERRORCODE_DEVICE_NOT_SUPPORTED**: This code is returned if the feature is not supported by the device. + +**WINDOW_MANAGER_ERRORCODE_STATE_ABNORMAL**: This code is returned if the window status is abnormal. + +**WINDOW_MANAGER_ERRORCODE_SYSTEM_ABNORMAL**: This code is returned if the window manager service is abnormal. + + +### OH_WindowManager_SetWindowTouchable() + +``` +int32_t OH_WindowManager_SetWindowTouchable (int32_t windowId, bool isTouchable ) +``` + +**Description** + +Sets whether a window is touchable. + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| windowId | Window ID. The default value is **0**. The value is an integer.| +| isTouchable | Whether the window is touchable. The value **true** means that the window is touchable, and **false** means the opposite.| + +**Returns** + +Returns one of the following result codes: + +**OK**: This code is returned if the function is successfully called. + +**WINDOW_MANAGER_ERRORCODE_INVALID_PARAM**: This code is returned if a parameter is incorrect. + +**WINDOW_MANAGER_ERRORCODE_STATE_ABNORMAL**: This code is returned if the window status is abnormal. + +**WINDOW_MANAGER_ERRORCODE_SYSTEM_ABNORMAL**: This code is returned if the window manager service is abnormal. + + +### OH_WindowManager_ShowWindow() + +``` +WindowManager_ErrorCode OH_WindowManager_ShowWindow (int32_t windowId) +``` + +**Description** + +Displays a window. + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| windowId | Window ID. The default value is **0**. The value is an integer.| + +**Returns** + +Returns one of the following result codes: + +**OK**: This code is returned if the function is successfully called. + +**WINDOW_MANAGER_ERRORCODE_INVALID_PARAM**: This code is returned if a parameter is incorrect. + +**WINDOW_MANAGER_ERRORCODE_STATE_ABNORMAL**: This code is returned if the window status is abnormal. + +**WINDOW_MANAGER_ERRORCODE_SYSTEM_ABNORMAL**: This code is returned if the window manager service is abnormal. + + +### OH_WindowManager_Snapshot() + +``` +int32_t OH_WindowManager_Snapshot (int32_t windowId, OH_PixelmapNative * pixelMap ) +``` + +**Description** + +Obtains the snapshot of a window. + +**Since**: 15 + +**Parameters** + +| Name| Description| +| -------- | -------- | +| windowId | Window ID. The default value is **0**. The value is an integer. If the window ID is invalid or the window has been destroyed, you cannot obtain the window screenshot. To successfully obtain a screenshot, a valid window ID is required. You can obtain a valid window ID by calling the ArkTS API **getWindowProperties** on the window object.| +| pixelMap | Pointer to the snapshot.| + +**Returns** + +Returns one of the following result codes: + +**OK**: This code is returned if the function is successfully called, and the pointer to the pixelMap is returned. + +**WINDOW_MANAGER_ERRORCODE_INVALID_PARAM**: This code is returned if a parameter is incorrect. + +**WINDOW_MANAGER_ERRORCODE_STATE_ABNORMAL**: This code is returned if the window status is abnormal. diff --git a/en/application-dev/reference/apis-arkui/_window_manager___rect.md b/en/application-dev/reference/apis-arkui/_window_manager___rect.md new file mode 100644 index 0000000000000000000000000000000000000000..199bc950741c37a41682452a7445344939d3933d --- /dev/null +++ b/en/application-dev/reference/apis-arkui/_window_manager___rect.md @@ -0,0 +1,70 @@ +# WindowManager_Rect + + +## Overview + +The WindowManager_Rect struct describes the window rectangle, including the window position, width, and height. + +**Since**: 15 + +**Related module**: [WindowManager_NativeModule](_window_manager___native_module.md) + + +## Summary + + +### Member Variables + +| Name| Description| +| -------- | -------- | +| int32_t [posX](#posx) | X coordinate of the window, in px. The value is an integer.| +| int32_t [posY](#posy) | Y coordinate of the window, in px. The value is an integer.| +| uint32_t [width](#width) | Window width, in px. The value is an integer.| +| uint32_t [height](#height) | Window height, in px. The value is an integer.| + + +## Member Variable Description + + +### height + +``` +uint32_t WindowManager_Rect::height +``` + +**Description** + +Window height, in px. The value is an integer. + + +### posX + +``` +int32_t WindowManager_Rect::posX +``` + +**Description** + +X coordinate of the window, in px. The value is an integer. + + +### posY + +``` +int32_t WindowManager_Rect::posY +``` + +**Description** + +Y coordinate of the window, in px. The value is an integer. + + +### width + +``` +uint32_t WindowManager_Rect::width +``` + +**Description** + +Window width, in px. The value is an integer. diff --git a/en/application-dev/reference/apis-arkui/_window_manager___window_properties.md b/en/application-dev/reference/apis-arkui/_window_manager___window_properties.md new file mode 100644 index 0000000000000000000000000000000000000000..6d7db0f63c6bf8b631bfb759a8805abee850b514 --- /dev/null +++ b/en/application-dev/reference/apis-arkui/_window_manager___window_properties.md @@ -0,0 +1,178 @@ +# WindowManager_WindowProperties + + +## Overview + +The WindowManager_WindowProperties struct describes the window properties. + +**Since**: 15 + +**Related module**: [WindowManager_NativeModule](_window_manager___native_module.md) + + +## Summary + + +### Member Variables + +| Name| Description| +| -------- | -------- | +| [WindowManager_Rect](_window_manager___rect.md) [windowRect](#windowrect) | Position and size of the window.| +| [WindowManager_Rect](_window_manager___rect.md) [drawableRect](#drawablerect) | Size of the drawable area within the window.| +| [WindowManager_WindowType](_window_manager___native_module.md#windowmanager_windowtype) [type](#type) | Window type.| +| bool [isFullScreen](#isfullscreen) | Whether the window is in full-screen mode. The default value is **false**. The value **true** means that the window is in full-screen mode, and **false** means the opposite.| +| bool [isLayoutFullScreen](#islayoutfullscreen) | Whether the window layout is immersive. The default value is **false**. The value **true** means that the window layout is immersive, and **false** means the opposite.| +| bool [focusable](#focusable) | Whether the window is focusable. The default value is **true**. The value **true** means that the window is focusable, and **false** means the opposite.| +| bool [touchable](#touchable) | Whether the window is touchable. The default value is **true**. The value **true** means that the window is touchable, and **false** means the opposite.| +| float [brightness](#brightness) | Screen brightness of the window. The value is a floating point number in the range [0.0, 1.0] or set to **-1.0**, where **1.0** indicates the brightest, and **-1.0** is the default brightness.| +| bool [isKeepScreenOn](#iskeepscreenon) | Whether the screen is steady on. The default value is **false**. The value **true** means that the screen is steady on, and **false** means the opposite.| +| bool [isPrivacyMode](#isprivacymode) | Whether privacy mode is enabled for the window. The default value is **false**. The value **true** means that privacy mode is enabled, and **false** means the opposite.| +| bool [isTransparent](#istransparent) | Whether the window is transparent. The default value is **false**. The value **true** means that the window is transparent, and **false** means the opposite.| +| uint32_t [id](#id) | Window ID. The default value is **0**, and the value is an integer.| +| uint32_t [displayId](#displayid) | ID of the screen where the window is located. By default, the ID of the primary screen is returned. The value is an integer.| + + +## Member Variable Description + + +### brightness + +``` +float WindowManager_WindowProperties::brightness +``` + +**Description** + +Screen brightness of the window. The value is a floating point number in the range [0.0, 1.0] or set to **-1.0**, where **1.0** indicates the brightest, and **-1.0** is the default brightness. + + +### displayId + +``` +uint32_t WindowManager_WindowProperties::displayId +``` + +**Description** + +ID of the screen where the window is located. By default, the ID of the primary screen is returned. The value is an integer. + + +### drawableRect + +``` +WindowManager_Rect WindowManager_WindowProperties::drawableRect +``` + +**Description** + +Size of the drawable area within the window. + + +### focusable + +``` +bool WindowManager_WindowProperties::focusable +``` + +**Description** + +Whether the window is focusable. The default value is **true**. The value **true** means that the window is focusable, and **false** means the opposite. + + +### id + +``` +uint32_t WindowManager_WindowProperties::id +``` + +**Description** + +Window ID. The default value is **0**, and the value is an integer. + + +### isFullScreen + +``` +bool WindowManager_WindowProperties::isFullScreen +``` + +**Description** + +Whether the window is in full-screen mode. The default value is **false**. The value **true** means that the window is in full-screen mode, and **false** means the opposite. + + +### isKeepScreenOn + +``` +bool WindowManager_WindowProperties::isKeepScreenOn +``` + +**Description** + +Whether the screen is steady on. The default value is **false**. The value **true** means that the screen is steady on, and **false** means the opposite. + + +### isLayoutFullScreen + +``` +bool WindowManager_WindowProperties::isLayoutFullScreen +``` + +**Description** + +Whether the window layout is immersive. The default value is **false**. The value **true** means that the window layout is immersive, and **false** means the opposite. + + +### isPrivacyMode + +``` +bool WindowManager_WindowProperties::isPrivacyMode +``` + +**Description** + +Whether privacy mode is enabled for the window. The default value is **false**. The value **true** means that privacy mode is enabled, and **false** means the opposite. + + +### isTransparent + +``` +bool WindowManager_WindowProperties::isTransparent +``` + +**Description** + +Whether the window is transparent. The default value is **false**. The value **true** means that the window is transparent, and **false** means the opposite. + + +### touchable + +``` +bool WindowManager_WindowProperties::touchable +``` + +**Description** + +Whether the window is touchable. The default value is **true**. The value **true** means that the window is touchable, and **false** means the opposite. + + +### type + +``` +WindowManager_WindowType WindowManager_WindowProperties::type +``` + +**Description** + +Window type. + + +### windowRect + +``` +WindowManager_Rect WindowManager_WindowProperties::windowRect +``` + +**Description** + +Position and size of the window. diff --git a/en/application-dev/reference/apis-arkui/arkui-js-lite/Readme-EN.md b/en/application-dev/reference/apis-arkui/arkui-js-lite/Readme-EN.md index 19081eafef92518a7b4eb87c37a2f000d0ddaefe..988931ee05bf3257ba3a4b5a6f964b9d52ad75f7 100644 --- a/en/application-dev/reference/apis-arkui/arkui-js-lite/Readme-EN.md +++ b/en/application-dev/reference/apis-arkui/arkui-js-lite/Readme-EN.md @@ -1,28 +1,28 @@ # JavaScript-compatible Web-like Development Paradigm (ArkUI.Lite) -- Framework Overview +- Framework Overview - [File Organization](js-lite-framework-file.md) - ["js" Tag](js-lite-framework-js-tag.md) - [app.js](js-lite-framework-js-file.md) - [Lifecycle](js-lite-framework-lifecycle.md) - [Multi-Language Capability](js-lite-framework-localization.md) - - Syntax + - Syntax - [HML](js-lite-framework-syntax-hml.md) - [CSS](js-lite-framework-syntax-css.md) - [JavaScript](js-lite-framework-syntax-js.md) -- Universal Component Information +- Universal Component Information - [Universal Events](js-lite-common-events.md) - [Universal Attributes](js-lite-common-attributes.md) - [Universal Styles](js-lite-common-styles.md) - [Animation Styles](js-lite-components-common-animation.md) - [Media Query](js-lite-components-common-mediaquery.md) -- Container Components +- Container Components - [div](js-lite-components-container-div.md) - [list](js-lite-components-container-list.md) - [list-item](js-lite-components-container-list-item.md) - [stack](js-lite-components-container-stack.md) - [swiper](js-lite-components-container-swiper.md) -- Basic Components +- Basic Components - [chart](js-lite-components-basic-chart.md) - [image](js-lite-components-basic-image.md) - [image-animator](js-lite-components-basic-image-animator.md) @@ -34,6 +34,6 @@ - [slider](js-lite-components-basic-slider.md) - [switch](js-lite-components-basic-switch.md) - [text](js-lite-components-basic-text.md) -- Canvas Components +- Canvas Components - [canvas](js-lite-components-canvas-canvas.md) - [CanvasRenderingContext2D](js-lite-components-canvas-canvasrenderingcontext2d.md) \ No newline at end of file diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceNavigationDemo02.jpg b/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceNavigationDemo02.jpg new file mode 100644 index 0000000000000000000000000000000000000000..2dae9b092d475ffa8c554e6e8612bf7a4599f241 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceNavigationDemo02.jpg differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceNavigationDemo03.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceNavigationDemo03.png new file mode 100644 index 0000000000000000000000000000000000000000..299c749857dee744e61f00132e18864f7177ac88 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceNavigationDemo03.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceNavigationDemo04.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceNavigationDemo04.png new file mode 100644 index 0000000000000000000000000000000000000000..a263d43b58377a03df2e3ca3038ec2d57151b106 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceNavigationDemo04.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceSearchDemo01.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceSearchDemo01.gif new file mode 100644 index 0000000000000000000000000000000000000000..aae8f25227a14b93a77f2a65fb166acb9036ec66 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceSearchDemo01.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceSearchDemo02.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceSearchDemo02.gif new file mode 100644 index 0000000000000000000000000000000000000000..e0ac42b8ccc97c124ac3dbc0ed83f508521e1180 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceSearchDemo02.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceSearchDemo03.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceSearchDemo03.gif new file mode 100644 index 0000000000000000000000000000000000000000..c1b18844e490d55fe2ce628d7ea0edd3054c9179 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceSearchDemo03.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceSearchDemo04.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceSearchDemo04.gif new file mode 100644 index 0000000000000000000000000000000000000000..5f811cc7742ed76908f9a405ec807b42238d5bad Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceSearchDemo04.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceSearchDemo05.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceSearchDemo05.gif new file mode 100644 index 0000000000000000000000000000000000000000..1eca804ae8f52f21aa2ba04cf3940398b568ddbe Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceSearchDemo05.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceSearchDemo06.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceSearchDemo06.gif new file mode 100644 index 0000000000000000000000000000000000000000..4221015b8a005fb30b255a730b6f503de6747c38 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceSearchDemo06.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceSearchDemo07.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceSearchDemo07.gif new file mode 100644 index 0000000000000000000000000000000000000000..6b1762fe6d9f8c1697d0aeb19b8a930c65569a90 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceSearchDemo07.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceSearchDemo08.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceSearchDemo08.png new file mode 100644 index 0000000000000000000000000000000000000000..917f740d4f876da7261220eb9ba35d67112a1d2f Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceSearchDemo08.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceSearchDemo09.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceSearchDemo09.png new file mode 100644 index 0000000000000000000000000000000000000000..2c0d76ae5f42689322186955782f02b40018e0e4 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceSearchDemo09.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceSearchDemo10.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceSearchDemo10.gif new file mode 100644 index 0000000000000000000000000000000000000000..85a3e1a57b6377bb6b996c3f2c4535c4b08f5fd9 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceSearchDemo10.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceSearchDemo11.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceSearchDemo11.gif new file mode 100644 index 0000000000000000000000000000000000000000..dfe704e2063102658db89d91b5aa715ca70243df Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceSearchDemo11.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceSearchDemo12.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceSearchDemo12.gif new file mode 100644 index 0000000000000000000000000000000000000000..5904b54ba91dd2d6ea947b12e6b9c3aa299d85e3 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/AtomicServiceSearchDemo12.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/CapsuleSegmentButtonV2.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/CapsuleSegmentButtonV2.gif new file mode 100644 index 0000000000000000000000000000000000000000..2a8437413ddca52807df1a3c68bce00701f49040 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/CapsuleSegmentButtonV2.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/DatePickerDemo2.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/DatePickerDemo2.png new file mode 100644 index 0000000000000000000000000000000000000000..7dd6603d6391fc7abd0949d46ba0e9f373d0e06f Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/DatePickerDemo2.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/DatePickerDemo3.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/DatePickerDemo3.gif new file mode 100644 index 0000000000000000000000000000000000000000..0cdf3ae85c7dd13d96f4af0443c0a8b687f581e6 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/DatePickerDemo3.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/ExceptionPrompt3.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/ExceptionPrompt3.png new file mode 100644 index 0000000000000000000000000000000000000000..a3c6fd47bf8f818c5294903735c37d3518a48465 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/ExceptionPrompt3.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/LoadingDialog.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/LoadingDialog.gif new file mode 100644 index 0000000000000000000000000000000000000000..c227aca5dda48801607e19fc817f152c01b2c579 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/LoadingDialog.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/MultiCapsuleSegmentButtonV2.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/MultiCapsuleSegmentButtonV2.gif new file mode 100644 index 0000000000000000000000000000000000000000..c5e5c91eef0ad8ea39b090ea42595c02c914b02f Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/MultiCapsuleSegmentButtonV2.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/SubHeaderDefaultFocus.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/SubHeaderDefaultFocus.png new file mode 100644 index 0000000000000000000000000000000000000000..7bc23706a969b7f1f6a8cf3c50426961a1209fc5 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/SubHeaderDefaultFocus.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/TabSegmentButtonV2.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/TabSegmentButtonV2.gif new file mode 100644 index 0000000000000000000000000000000000000000..05671f711f2570bb181ec71faf57ecc4100278b9 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/TabSegmentButtonV2.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/TextInput.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/TextInput.gif new file mode 100644 index 0000000000000000000000000000000000000000..8f339c8d36bfe6fb2ea6b168a6afddbd2cec9ff1 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/TextInput.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/TextInputEditChange.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/TextInputEditChange.png new file mode 100644 index 0000000000000000000000000000000000000000..04ff9724c28eb103dd495bb1a2b11818950558ad Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/TextInputEditChange.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/TextInputWordBreak.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/TextInputWordBreak.png new file mode 100644 index 0000000000000000000000000000000000000000..cd252f4c2d9c4f2970c4a24fe1b3155c9610ec48 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/TextInputWordBreak.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDemo1.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDemo1.png new file mode 100644 index 0000000000000000000000000000000000000000..7680b85867f68c80f8de928e30bda4d67e0e51ec Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDemo1.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDemo2.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDemo2.gif new file mode 100644 index 0000000000000000000000000000000000000000..082c9c4f268f3ba4807cf3942069f422c599cf24 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDemo2.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDemo3.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDemo3.gif new file mode 100644 index 0000000000000000000000000000000000000000..95226849eaa2e203c26bce29d47041a30da5656b Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDemo3.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDemo4.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDemo4.gif new file mode 100644 index 0000000000000000000000000000000000000000..38baf4f1f81ff138a3153e5338fa9b7999452519 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDemo4.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDemo5.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDemo5.png new file mode 100644 index 0000000000000000000000000000000000000000..f4ea0f9742629b01b459271abd6851c2f2c26125 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDemo5.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDemo6.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDemo6.png new file mode 100644 index 0000000000000000000000000000000000000000..8068704341e7888c94a452b80421fb6e4b42ade2 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDemo6.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDemo7.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDemo7.gif new file mode 100644 index 0000000000000000000000000000000000000000..a08e1ab3ce93262f3ab4055904939f2f1e0a59ed Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDemo7.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDialogDemo3.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDialogDemo3.gif new file mode 100644 index 0000000000000000000000000000000000000000..3b384db53ac86a3a31a3006ed5c07eaa76a2f8d1 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDialogDemo3.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDialogDemo4.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDialogDemo4.png new file mode 100644 index 0000000000000000000000000000000000000000..474e45650d0163337a7a7b1d9486b5941f5b38a7 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDialogDemo4.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDialogDemo5.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDialogDemo5.png new file mode 100644 index 0000000000000000000000000000000000000000..adcd77c3207b670558485e2ead6e1a080a76219c Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDialogDemo5.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDialogDemo6.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDialogDemo6.png new file mode 100644 index 0000000000000000000000000000000000000000..6fa41fd7c807ce08f2c7ad498ac9631c42c8f08a Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDialogDemo6.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDialogDemo7.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDialogDemo7.png new file mode 100644 index 0000000000000000000000000000000000000000..e96c5a370b23352bcb8eb906d8d073c60da80cf4 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDialogDemo7.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDialogDemo8.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDialogDemo8.png new file mode 100644 index 0000000000000000000000000000000000000000..dcb5c280a3d34f26b8b80b90210387ca2938e205 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDialogDemo8.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDialogDemo9.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDialogDemo9.gif new file mode 100644 index 0000000000000000000000000000000000000000..5d2f84538060de2779366edb1a3f166812a814e1 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/TimePickerDialogDemo9.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/arcSwiper.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/arcSwiper.gif new file mode 100644 index 0000000000000000000000000000000000000000..4a52d422513862b30d5794cf9250c524a9017478 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/arcSwiper.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/arcslider.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/arcslider.gif new file mode 100644 index 0000000000000000000000000000000000000000..84fd04742b7bb3813d00fefb99249e2fb48e06f7 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/arcslider.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/atomicserviceTabs_icon.PNG b/en/application-dev/reference/apis-arkui/arkui-ts/figures/atomicserviceTabs_icon.PNG new file mode 100644 index 0000000000000000000000000000000000000000..672ee1d726966a80407518012030370102d99eaf Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/atomicserviceTabs_icon.PNG differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/atomicserviceTabs_text.PNG b/en/application-dev/reference/apis-arkui/arkui-ts/figures/atomicserviceTabs_text.PNG new file mode 100644 index 0000000000000000000000000000000000000000..08bcd557a4d41af0263fbcd1d79c794c828590f4 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/atomicserviceTabs_text.PNG differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/atomicservicetabs.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/atomicservicetabs.gif index 5944cdf6d6ed4f79c7d81d27e885f82e312c3292..bc3334ee92c7e0ae64bacf1e8bc0be41c0e91451 100644 Binary files a/en/application-dev/reference/apis-arkui/arkui-ts/figures/atomicservicetabs.gif and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/atomicservicetabs.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/atomicservicetabs_layoutMode.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/atomicservicetabs_layoutMode.gif new file mode 100644 index 0000000000000000000000000000000000000000..666d1436e78c8c288c4d591c95a53a9ff5d76ce3 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/atomicservicetabs_layoutMode.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/bindIndicatorDigitStyle.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/bindIndicatorDigitStyle.gif new file mode 100644 index 0000000000000000000000000000000000000000..d89e17c6e3ddb755125da733d5b23c10afb2c398 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/bindIndicatorDigitStyle.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/bindIndicatorDotStyle.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/bindIndicatorDotStyle.gif new file mode 100644 index 0000000000000000000000000000000000000000..c7d885dc5f6cf2316c86719f34f2b56f5f7ae4c7 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/bindIndicatorDotStyle.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/click.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/click.gif new file mode 100644 index 0000000000000000000000000000000000000000..6edb214c380ec3f571a1edc50cf20acab9b84d09 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/click.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/column.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/column.png index 3141c7c0bcecfdbb787bf5c84c829a6067f1aa62..481c9aa465999d1d0cad3ff00b409c28f6bf662d 100644 Binary files a/en/application-dev/reference/apis-arkui/arkui-ts/figures/column.png and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/column.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/container_attributeModifier.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/container_attributeModifier.png new file mode 100644 index 0000000000000000000000000000000000000000..f16cd3f0fc3dfe0869d960786e20e1ed4d142e40 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/container_attributeModifier.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/custom_layout_demo3.jpg b/en/application-dev/reference/apis-arkui/arkui-ts/figures/custom_layout_demo3.jpg new file mode 100644 index 0000000000000000000000000000000000000000..55234ba67a80b254385d0d2be02ef3ced12934f2 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/custom_layout_demo3.jpg differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/deleteListItem_example04.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/deleteListItem_example04.gif new file mode 100644 index 0000000000000000000000000000000000000000..3d28060f34dd4afd420afce4e7b21c4e6ad7c809 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/deleteListItem_example04.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/dragPreviewMode.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/dragPreviewMode.gif new file mode 100644 index 0000000000000000000000000000000000000000..07fe444234d62e84445e68878c649be07e132bbf Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/dragPreviewMode.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/edgeEffect_grid.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/edgeEffect_grid.gif new file mode 100644 index 0000000000000000000000000000000000000000..5b2d90ace9708d35eb3b466f5111006d6ef47a2c Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/edgeEffect_grid.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/edgeEffect_list.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/edgeEffect_list.gif new file mode 100644 index 0000000000000000000000000000000000000000..4e24c61aec6af2469e96414a51395a83c2aa8379 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/edgeEffect_list.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/editabletitlebarDefaultFocus01.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/editabletitlebarDefaultFocus01.png new file mode 100644 index 0000000000000000000000000000000000000000..3697171cd8a5183d5c80cb4266df9b3307e22ce7 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/editabletitlebarDefaultFocus01.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/editabletitlebarDefaultFocus02.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/editabletitlebarDefaultFocus02.png new file mode 100644 index 0000000000000000000000000000000000000000..9f3a9b7b603063b51a7e146c0829865f41d1502b Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/editabletitlebarDefaultFocus02.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001193872494.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001193872494.png new file mode 100644 index 0000000000000000000000000000000000000000..563ce2878d24a7fa46044f201433d759c3fa9001 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001193872494.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001194032460.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001194032460.png new file mode 100644 index 0000000000000000000000000000000000000000..d0e446b213816e4db8d67a9898da1afa7b8226ad Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001194032460.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001194192438.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001194192438.png new file mode 100644 index 0000000000000000000000000000000000000000..1f4208ebcf5ffeeda0d1f5c452327c8fd8dcf7ac Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001194192438.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001194192446.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001194192446.png new file mode 100644 index 0000000000000000000000000000000000000000..defc3c9eb037c06b894ee2e30563facb8c8375ab Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001194192446.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001194352438.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001194352438.png new file mode 100644 index 0000000000000000000000000000000000000000..1f4208ebcf5ffeeda0d1f5c452327c8fd8dcf7ac Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001194352438.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001194352440.jpeg b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001194352440.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..dfa631cc7809502778161bd6f640e32d2a367414 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001194352440.jpeg differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001194352441.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001194352441.png new file mode 100644 index 0000000000000000000000000000000000000000..c97ac10ac8ed9266f73eaecfdb6473f9ec1a1267 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001194352441.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001210353788.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001210353788.gif deleted file mode 100644 index f55a5e26c8b0dc0c11405b0b342399324afc3dbc..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001210353788.gif and /dev/null differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001238712417.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001238712417.png new file mode 100644 index 0000000000000000000000000000000000000000..294b32cf04462b04243afb828199be9b95e6dd17 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001238712417.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001238712421.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001238712421.png new file mode 100644 index 0000000000000000000000000000000000000000..3e7218eb57566d86457a9fbd4a8ed0f0dd490c3f Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001238712421.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001238832391.jpeg b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001238832391.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..54d37bb92f714dc3c2d2770e6fc954a30dc7142a Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001238832391.jpeg differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001238952379.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001238952379.png new file mode 100644 index 0000000000000000000000000000000000000000..72a515c8b425037a4307ef1b16def3e528aab4a0 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001238952379.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001238952381.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001238952381.png new file mode 100644 index 0000000000000000000000000000000000000000..fb7fc25c17990998ba263a8525e6a110794c0d87 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001238952381.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001239032415.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001239032415.png new file mode 100644 index 0000000000000000000000000000000000000000..22e84d1b8951b163748a079b6d1d302148d3b6bb Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001239032415.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001239032417.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001239032417.png new file mode 100644 index 0000000000000000000000000000000000000000..088d5a479cc188332bb7295b31aea277897faca8 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001239032417.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_000000127777782.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_000000127777782.png new file mode 100644 index 0000000000000000000000000000000000000000..21e6075ef044ce89c6f1789226a141eda8ef97c0 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_000000127777782.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001616916278.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001616916278.png deleted file mode 100644 index f3f46cbe96b982b615355ef0291e671a3ee15ca2..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001616916278.png and /dev/null differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001616959836.jpg b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001616959836.jpg deleted file mode 100644 index f98c28b2a9f55a8cfb3c65fbd6c728df91fa7e27..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_0000001616959836.jpg and /dev/null differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_backgroundBlurStyleOptions.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_backgroundBlurStyleOptions.png new file mode 100644 index 0000000000000000000000000000000000000000..b58d5a1ed0a2df6fa5c83a66c98fb1e8525b6203 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_backgroundBlurStyleOptions.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_backgroundEffect.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_backgroundEffect.png new file mode 100644 index 0000000000000000000000000000000000000000..48990a1929cca6f730c7501b98a1cdd245e7cacb Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_backgroundEffect.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_canvas.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_canvas.png new file mode 100644 index 0000000000000000000000000000000000000000..64e066cd91b270472fe09a33947b1849a5cc5338 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_canvas.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_composelistitem_demo_02.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_composelistitem_demo_02.png new file mode 100644 index 0000000000000000000000000000000000000000..80315adf40d51c05b0f68205c803ad11080d087c Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_composelistitem_demo_02.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_composelistitem_demo_03.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_composelistitem_demo_03.png new file mode 100644 index 0000000000000000000000000000000000000000..f0b016ec540f072d65645cd9c14292905fd4bb82 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_composelistitem_demo_03.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_composetitlebar_demo_03.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_composetitlebar_demo_03.png new file mode 100644 index 0000000000000000000000000000000000000000..2ab6c81e508caaecec27e4e75fedba69835dcf94 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_composetitlebar_demo_03.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_composetitlebar_example01.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_composetitlebar_example01.png new file mode 100644 index 0000000000000000000000000000000000000000..32be94d34e8963e0d315802cd957b44cacca0f2d Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_composetitlebar_example01.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_composetitlebar_example02.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_composetitlebar_example02.png new file mode 100644 index 0000000000000000000000000000000000000000..154e463caecdc2e6945bb8cda66a1fb11dbbee9e Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_composetitlebar_example02.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_editabletitlebar_demo_06.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_editabletitlebar_demo_06.png new file mode 100644 index 0000000000000000000000000000000000000000..95c2500cd406a00cd949a9898b8beeb3d15a65ee Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_editabletitlebar_demo_06.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_editabletitlebar_example01.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_editabletitlebar_example01.png new file mode 100644 index 0000000000000000000000000000000000000000..79f2f23236ee2e3068955a9dc0134181a3bd3389 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_editabletitlebar_example01.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_editabletitlebar_example02.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_editabletitlebar_example02.png new file mode 100644 index 0000000000000000000000000000000000000000..604476f76301bbd5efac0a204818187468b1adb3 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_editabletitlebar_example02.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_editabletitlebar_example03.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_editabletitlebar_example03.png new file mode 100644 index 0000000000000000000000000000000000000000..60e696ea3e1f3ad2aaddba63b3c3e7de197a90be Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_editabletitlebar_example03.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_refresh_builder.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_refresh_builder.gif new file mode 100644 index 0000000000000000000000000000000000000000..b6d49aeedc6ef99ff09a29dfe6abddcd37462b02 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_refresh_builder.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_refresh_default.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_refresh_default.gif new file mode 100644 index 0000000000000000000000000000000000000000..e9b2a759b29c193810b246aac70dff3090594129 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_refresh_default.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_refresh_maxrefreshingheight.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_refresh_maxrefreshingheight.gif new file mode 100644 index 0000000000000000000000000000000000000000..6fee708d6cb7bf21cd716d2b1cc19399e50d93aa Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_refresh_maxrefreshingheight.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_refresh_prompttext.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_refresh_prompttext.gif new file mode 100644 index 0000000000000000000000000000000000000000..81b2d7c69cc32bc7ed085e2037dead2e815c02d1 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_refresh_prompttext.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_refresh_refreshingcontent.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_refresh_refreshingcontent.gif new file mode 100644 index 0000000000000000000000000000000000000000..c9bd7613da2469300977e9c420c2112597bf14e9 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_refresh_refreshingcontent.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_selecttitlebar_example01.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_selecttitlebar_example01.png new file mode 100644 index 0000000000000000000000000000000000000000..387541f150f487dfa76c66f12fb892337a216301 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_selecttitlebar_example01.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_selecttitlebar_example02.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_selecttitlebar_example02.png new file mode 100644 index 0000000000000000000000000000000000000000..e10ad288b99ab16efde27b49bc457de2f6c64fed Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_selecttitlebar_example02.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_selecttitlebar_example03.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_selecttitlebar_example03.png new file mode 100644 index 0000000000000000000000000000000000000000..e8d699651f0f0aabbb20ebb7a39dd10ef4e2b0b7 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_selecttitlebar_example03.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_subheaderv2_example07.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_subheaderv2_example07.png new file mode 100644 index 0000000000000000000000000000000000000000..b6c3bba8dd872c8012d025af3c9edfe2d95686f8 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_subheaderv2_example07.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_tabtitlebar_example01.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_tabtitlebar_example01.png new file mode 100644 index 0000000000000000000000000000000000000000..8555c07babeaf1660331faa99d47c02eb1827fc9 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_tabtitlebar_example01.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_tabtitlebar_example02.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_tabtitlebar_example02.png new file mode 100644 index 0000000000000000000000000000000000000000..8555c07babeaf1660331faa99d47c02eb1827fc9 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_tabtitlebar_example02.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_treeview_demo_02.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_treeview_demo_02.png new file mode 100644 index 0000000000000000000000000000000000000000..ab0b1c4091c4ded344e245a04c5285faab18177d Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_image_treeview_demo_02.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_sheet6.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_sheet6.gif new file mode 100644 index 0000000000000000000000000000000000000000..7b38b09c39f2a1a9732f79b81bc52ce71f342eab Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/en-us_sheet6.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/expandSafeArea3.jpg b/en/application-dev/reference/apis-arkui/arkui-ts/figures/expandSafeArea3.jpg deleted file mode 100644 index 7ec3d6e8fb4327b65456733d798d515e3592bc1d..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/apis-arkui/arkui-ts/figures/expandSafeArea3.jpg and /dev/null differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/expandSafeArea3.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/expandSafeArea3.png new file mode 100644 index 0000000000000000000000000000000000000000..b50ca9ddec472e7b40ec034b94fd3c50e54a8b58 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/expandSafeArea3.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/expandSafeArea4.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/expandSafeArea4.png new file mode 100644 index 0000000000000000000000000000000000000000..7f3b6eb1bc9da055000c2c440af7c76ae10ced79 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/expandSafeArea4.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/fillColorExample.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/fillColorExample.png new file mode 100644 index 0000000000000000000000000000000000000000..8636f94b4902911678e6dc975c3bbfef93fa7476 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/fillColorExample.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/gauge-image8.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/gauge-image8.png new file mode 100644 index 0000000000000000000000000000000000000000..9678d50287f0be5337f7dc471fbc3e3da5c5215e Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/gauge-image8.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/gesture_recognizer_obtain_attributes.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/gesture_recognizer_obtain_attributes.gif new file mode 100644 index 0000000000000000000000000000000000000000..21447af00efa8463858edf584a4823f3103ab6da Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/gesture_recognizer_obtain_attributes.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/imageMatrix.jpeg b/en/application-dev/reference/apis-arkui/arkui-ts/figures/imageMatrix.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..eebf97ba47c9164d3d2f6918af3523ba826b622b Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/imageMatrix.jpeg differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/image_span_colorfilter.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/image_span_colorfilter.png new file mode 100644 index 0000000000000000000000000000000000000000..590c0dea63ad8c05766429e7b8c39f0d242f9e86 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/image_span_colorfilter.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/indicator_space.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/indicator_space.gif new file mode 100644 index 0000000000000000000000000000000000000000..ec3ccf12ccc3d10aacd1e22f5f5f06bdd2594132 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/indicator_space.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/isLiftingDisabled.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/isLiftingDisabled.gif new file mode 100644 index 0000000000000000000000000000000000000000..00a19ba9d6a721435e121a3d9210980bc057d6c8 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/isLiftingDisabled.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/letterSpacingDemo.jpeg b/en/application-dev/reference/apis-arkui/arkui-ts/figures/letterSpacingDemo.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..f0f4d19c08301f98074fcaf9aad090e0743a374d Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/letterSpacingDemo.jpeg differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/matrix-identity.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/matrix-identity.png new file mode 100644 index 0000000000000000000000000000000000000000..2d12ff8176d49749442a6b9800eb501a73728b8c Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/matrix-identity.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/matrix-invert.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/matrix-invert.png new file mode 100644 index 0000000000000000000000000000000000000000..4e72eab1cb4f7dec49024ad05c4e0c650d78d3c8 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/matrix-invert.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/matrix-multiply.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/matrix-multiply.png new file mode 100644 index 0000000000000000000000000000000000000000..8c2f368dd4be3059761e914820fe704761a41089 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/matrix-multiply.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/matrix-parameters.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/matrix-parameters.png new file mode 100644 index 0000000000000000000000000000000000000000..190e7a1f52bbea3cb056a7a3dfb3ed02a2f72923 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/matrix-parameters.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/matrix-rotate.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/matrix-rotate.png new file mode 100644 index 0000000000000000000000000000000000000000..34d62e15fcb9249edd65dec350c66554a31a9e3c Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/matrix-rotate.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/matrix-rotate10+.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/matrix-rotate10+.png new file mode 100644 index 0000000000000000000000000000000000000000..64136387abc2677ecd6a587459860a8ac242bdb7 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/matrix-rotate10+.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/matrix-scale.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/matrix-scale.png new file mode 100644 index 0000000000000000000000000000000000000000..59f0c98d326f08e6f91f0bba9a5ffb865f49ac7e Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/matrix-scale.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/matrix-translate.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/matrix-translate.png new file mode 100644 index 0000000000000000000000000000000000000000..3e91db06008e5def041fc81ccb777bc4a5781a77 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/matrix-translate.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/measureText.jpg b/en/application-dev/reference/apis-arkui/arkui-ts/figures/measureText.jpg new file mode 100644 index 0000000000000000000000000000000000000000..b14672ecff23b3d56735b9071e59a35df52724b1 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/measureText.jpg differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/mouse.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/mouse.gif new file mode 100644 index 0000000000000000000000000000000000000000..7813fe65ef6f5be3223afabc0a1887b617c1e97a Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/mouse.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/mouse1.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/mouse1.png deleted file mode 100644 index aa6709fa32eb5c6a29eff6ea54588fc86e8240c6..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/apis-arkui/arkui-ts/figures/mouse1.png and /dev/null differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/navdestination_custom_transition.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/navdestination_custom_transition.gif new file mode 100644 index 0000000000000000000000000000000000000000..ebc0663aba5ca109993346958e700b58d71406c1 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/navdestination_custom_transition.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/navdestination_explode_transition.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/navdestination_explode_transition.gif new file mode 100644 index 0000000000000000000000000000000000000000..f0ffcb754e1865913a30cd2f20c38257d0f39839 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/navdestination_explode_transition.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/navdestination_fade_transition.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/navdestination_fade_transition.gif new file mode 100644 index 0000000000000000000000000000000000000000..700e47951d2b3bc82bd3a8b76df57fd63c54dcbf Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/navdestination_fade_transition.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/navdestination_orientation.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/navdestination_orientation.gif new file mode 100644 index 0000000000000000000000000000000000000000..a2c3fe5a5d38df4e1558b1264061d824526bdc45 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/navdestination_orientation.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/navdestination_slide_bottom_transition.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/navdestination_slide_bottom_transition.gif new file mode 100644 index 0000000000000000000000000000000000000000..fbe62abd540d09a77a8438814b07171958f20051 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/navdestination_slide_bottom_transition.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/navdestination_slide_right_transition.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/navdestination_slide_right_transition.gif new file mode 100644 index 0000000000000000000000000000000000000000..62e7fafcf1e4c1e7792ac824581e465cdb78162b Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/navdestination_slide_right_transition.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/navigationColorBlur.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/navigationColorBlur.gif index 4f6eef79c3ca7d3c30df704138acc9f88be67e53..a79ad9bd2a9d56899c05d1f85337419744abd686 100644 Binary files a/en/application-dev/reference/apis-arkui/arkui-ts/figures/navigationColorBlur.gif and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/navigationColorBlur.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/normal-symbol.jpg b/en/application-dev/reference/apis-arkui/arkui-ts/figures/normal-symbol.jpg deleted file mode 100644 index 07f5486f45b8a5055728f4b6b053e3fd704f46e5..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/apis-arkui/arkui-ts/figures/normal-symbol.jpg and /dev/null differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/normal-symbol.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/normal-symbol.png new file mode 100644 index 0000000000000000000000000000000000000000..43b97244d7651bf193f97aa36ed694cc4a28c1a7 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/normal-symbol.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/objectRepeatExample.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/objectRepeatExample.png new file mode 100644 index 0000000000000000000000000000000000000000..db6a10b498def303c40102070ab28f7ccccf2fb3 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/objectRepeatExample.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/onAxisEvent.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/onAxisEvent.png new file mode 100644 index 0000000000000000000000000000000000000000..dbaae38e351849c3659d2eaf5f7c1922b785ec5e Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/onAxisEvent.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/onHoverMove.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/onHoverMove.png new file mode 100644 index 0000000000000000000000000000000000000000..7d8a0fd75bf845073ea6d6d78700211ec533665d Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/onHoverMove.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/onWillApplyTheme_V2.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/onWillApplyTheme_V2.png new file mode 100644 index 0000000000000000000000000000000000000000..3b6218e3ff976b5694c10ca52f2d3601075ef117 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/onWillApplyTheme_V2.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/on_off_cut.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/on_off_cut.gif new file mode 100644 index 0000000000000000000000000000000000000000..498e346a03dcbc2d9ff054b09af31713b248a865 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/on_off_cut.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/onlyForLifting.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/onlyForLifting.gif new file mode 100644 index 0000000000000000000000000000000000000000..373685629efbbeb09f15cac6718da86d176b7971 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/onlyForLifting.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/popup_9.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/popup_9.png new file mode 100644 index 0000000000000000000000000000000000000000..2a1849098712d6e2b416eb64a07f865a1c6f6c16 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/popup_9.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/renderModeExample.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/renderModeExample.png new file mode 100644 index 0000000000000000000000000000000000000000..8f45da8598e104d8470fe4db12fa45a3cf57b3aa Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/renderModeExample.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/row.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/row.png index d7fced9fe4a9fc618dee88ae95cc2f04a34bb3c3..4fb3e42680891ecc18a53c7d5c520644ec001d07 100644 Binary files a/en/application-dev/reference/apis-arkui/arkui-ts/figures/row.png and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/row.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/searchCopyOption.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/searchCopyOption.gif new file mode 100644 index 0000000000000000000000000000000000000000..df90daad3182edbee9c0cad87104a85bf41f068d Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/searchCopyOption.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/searchEnableKeyboardOnFocus.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/searchEnableKeyboardOnFocus.gif new file mode 100644 index 0000000000000000000000000000000000000000..df0a764b20826beddc357c99f79dd85a0ad1e79a Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/searchEnableKeyboardOnFocus.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/searchInputFilter.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/searchInputFilter.gif new file mode 100644 index 0000000000000000000000000000000000000000..86a2c0fb3afae233e8d6002464cbb08b60d9bf11 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/searchInputFilter.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/searchOnContentScroll.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/searchOnContentScroll.gif new file mode 100644 index 0000000000000000000000000000000000000000..f007bee803afac5b3a55b67a316ac6c491ae3aa8 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/searchOnContentScroll.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/searchSelectionMenuHidden.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/searchSelectionMenuHidden.gif new file mode 100644 index 0000000000000000000000000000000000000000..70f3712097aed51a0caa2889a56816dbea206ac7 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/searchSelectionMenuHidden.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/searchSetTextSelection.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/searchSetTextSelection.gif new file mode 100644 index 0000000000000000000000000000000000000000..0bcda67be585de584e169594e90acea380157ed9 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/searchSetTextSelection.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/searchTextAlign.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/searchTextAlign.gif new file mode 100644 index 0000000000000000000000000000000000000000..476e491dc352fbfca0a0e953168ecfcf005ca0a4 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/searchTextAlign.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/selectionmenu.jpeg b/en/application-dev/reference/apis-arkui/arkui-ts/figures/selectionmenu.jpeg deleted file mode 100644 index c527299222b338f0a5d679d3e6b252bf3ab2e325..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/apis-arkui/arkui-ts/figures/selectionmenu.jpeg and /dev/null differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/selectionmenu02.jpg b/en/application-dev/reference/apis-arkui/arkui-ts/figures/selectionmenu02.jpg new file mode 100644 index 0000000000000000000000000000000000000000..f02442d00e606d8d3ddfef61c84c3fbbe51bda4d Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/selectionmenu02.jpg differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/sourceSizeExample.png b/en/application-dev/reference/apis-arkui/arkui-ts/figures/sourceSizeExample.png new file mode 100644 index 0000000000000000000000000000000000000000..948c05cc9857c3f85f43b3696c25f5b765f5a898 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/sourceSizeExample.png differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/strokeText.jpg b/en/application-dev/reference/apis-arkui/arkui-ts/figures/strokeText.jpg new file mode 100644 index 0000000000000000000000000000000000000000..c2ca9f9df368fc5d9c24c294b40336a75cc7ad40 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/strokeText.jpg differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/styledString_10.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/styledString_10.gif new file mode 100644 index 0000000000000000000000000000000000000000..151bafdbaf290eac7a43903be2d16860cc0fd4fb Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/styledString_10.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/styledString_11.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/styledString_11.gif new file mode 100644 index 0000000000000000000000000000000000000000..3fc41878974e4ae55785dd34520535f0f42e5dbc Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/styledString_11.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/styledString_9.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/styledString_9.gif new file mode 100644 index 0000000000000000000000000000000000000000..58dec5fa93546f398034410c755d01f69ce4cb12 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/styledString_9.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/swiper-swipe-by-group.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/swiper-swipe-by-group.gif index d5e3d10a47de339f918840b0180b1b5f8aedd00d..c02b1b5f37dd26e34d5b02619b13c25b6b123684 100644 Binary files a/en/application-dev/reference/apis-arkui/arkui-ts/figures/swiper-swipe-by-group.gif and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/swiper-swipe-by-group.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/tabContent10.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/tabContent10.gif new file mode 100644 index 0000000000000000000000000000000000000000..a0dcf865aadfea2dacab377e921b1217c8d8c862 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/tabContent10.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/tabContent9.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/tabContent9.gif new file mode 100644 index 0000000000000000000000000000000000000000..ae4c44236dbcca19c4091ce1ad2ae0fbfafc6473 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/tabContent9.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/tabs13.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/tabs13.gif new file mode 100644 index 0000000000000000000000000000000000000000..5aeaf05ef75de0a7bbe990df7f6f2cf9444d3825 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/tabs13.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/tabs14.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/tabs14.gif new file mode 100644 index 0000000000000000000000000000000000000000..ef92cadcc900a6d8c1a465a963d1dea2a64b9c3c Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/tabs14.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/tabs15.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/tabs15.gif new file mode 100644 index 0000000000000000000000000000000000000000..4ab454582c55c9b3bb58d97d98908d8c15b8aef3 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/tabs15.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/tabs_swiper.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/tabs_swiper.gif new file mode 100644 index 0000000000000000000000000000000000000000..a509ba1e2bb009814504969591915494d548af79 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/tabs_swiper.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/tabs_tarbar.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/tabs_tarbar.gif new file mode 100644 index 0000000000000000000000000000000000000000..12dad343dabe37a5368677918ed76d9caef44e92 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/tabs_tarbar.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/textExp2.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/textExp2.gif index ce2c41462a5d0dcc425478170854bfe07c00c40c..e6bc285fbaa99837a29417514782ca76a4291a24 100644 Binary files a/en/application-dev/reference/apis-arkui/arkui-ts/figures/textExp2.gif and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/textExp2.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/textarea_custom_paste.PNG b/en/application-dev/reference/apis-arkui/arkui-ts/figures/textarea_custom_paste.PNG new file mode 100644 index 0000000000000000000000000000000000000000..7de79cf89786e02f84b101454678b0bbf0fcd189 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/textarea_custom_paste.PNG differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/tips01.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/tips01.gif new file mode 100644 index 0000000000000000000000000000000000000000..10dd937b230152e86a58ecd4c1606051b195725f Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/tips01.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/tips02.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/tips02.gif new file mode 100644 index 0000000000000000000000000000000000000000..168b310a3dd2b4532ea05e261c903b13b9cf9e72 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/tips02.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/touch.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/touch.gif new file mode 100644 index 0000000000000000000000000000000000000000..8fcd90f800c4242537e3809904614407296e9a35 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/touch.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/transferFromImageBitmap.jpg b/en/application-dev/reference/apis-arkui/arkui-ts/figures/transferFromImageBitmap.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d2fcace5ad1e973acc4da5109c0939d1bd60e0b6 Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/transferFromImageBitmap.jpg differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/waterFlow_footerContent.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/waterFlow_footerContent.gif new file mode 100644 index 0000000000000000000000000000000000000000..66a8f5f76bb39b7c60a6ae6c9b01f9c1c46405cd Binary files /dev/null and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/waterFlow_footerContent.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/figures/waterflow-pinch.gif b/en/application-dev/reference/apis-arkui/arkui-ts/figures/waterflow-pinch.gif index 262791086211f58a3646b5b6a1338003e0f244ce..bb521159853452ae9e376024b089d7f473ce76fb 100644 Binary files a/en/application-dev/reference/apis-arkui/arkui-ts/figures/waterflow-pinch.gif and b/en/application-dev/reference/apis-arkui/arkui-ts/figures/waterflow-pinch.gif differ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ArcButton.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ArcButton.md index 58c08b1d557bcaddcccc5c71b2088426a5468498..733aca48b49b8e5c4b1d111ae7a5de39238c431c 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ArcButton.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ArcButton.md @@ -1,10 +1,10 @@ # ArcButton -The **ArcButton** component represents an arc button specifically designed for circular screens on wearable devices. It offers various button styles, such as emphasized, normal, and warning, tailored for watch UIs. +The **ArcButton** component represents an arc button specifically designed for circular screens. It offers various button styles, such as emphasized, normal, and warning, tailored for watch UIs. > **NOTE** > -> This component is supported since API version 16. Updates will be marked with a superscript to indicate their earliest API version. +> This component is supported since API version 18. Updates will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -23,66 +23,110 @@ import { Not supported ## Attributes -The [universal attributes](ts-universal-attributes-size.md) are not supported. +The [universal attributes](ts-component-general-attributes.md) are not supported. ## Events Among the universal events, the [click event](ts-universal-events-click.md) and [touch event](ts-universal-events-touch.md) are supported. ## ArcButton -ArcButton({options:ArcButtonOptions}) +ArcButton({ options: ArcButtonOptions }) Creates an instance of **ArcButton** with configuration parameters. -**Decorator**: @ComponentV2 +**Decorator**: @Component -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. -**System capability**: SystemCapability.ArkUI.ArkUI.Full +**System capability**: SystemCapability.ArkUI.ArkUI.Circle **Parameters** | Name | Type | Mandatory| Decorator | Description | | ------- | ---------------- | ---- | ----------- | ------------------------- | -| options | [ArcButtonOptions](#arcbuttonoptions) | Yes | @ObservedV2 | Text, background color, shadow, and other parameters of the **ArcButton** component.| - - +| options | [ArcButtonOptions](#arcbuttonoptions) | Yes | @Require | Text, background color, shadow, and other parameters of the **ArcButton** component.| ## ArcButtonOptions Defines the default or custom style parameters for the **ArcButton** component. +**Atomic service API**: This API can be used in atomic services since API version 18. + **System capability**: SystemCapability.ArkUI.ArkUI.Circle +### Properties + | Name | Type | Mandatory| Description | | ---------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| position | [ArcButtonPosition](#arcbuttonposition) | No | Type of the arc button.
Default value: lower arc button | -| styleMode | [ArcButtonStyleMode](#arcbuttonstylemode) | No | Style mode for the arc button.
Default value: **ArcButtonStyleMode.EMPHASIZED_LIGHT**| -| status | [ArcButtonStatus](#arcbuttonstatus) | No | Status of the arc button.
Default value: **ArcButtonStatus.NORMAL** | -| label | [ResourceStr](ts-types.md#resourcestr) | No | Text displayed on the arc button. | -| backgroundBlurStyle | [BlurStyle](ts-universal-attributes-background.md#blurstyle9) | No | Background blur style of the arc button.
Default value: **BlurStyle.NONE**| -| backgroundColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | No | Background color of the arc button.
Default value: **Color.Black** | -| shadowColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | No | Shadow color of the arc button.
Default value: **Color.Black** | -| shadowEnabled | boolean | No | Whether to enable the shadow for the arc button.
Default value: **false** | -| fontSize | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | No | Font size of the arc button.
Default value: **19fp** | -| fontColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | No | Font color of the arc button.
Default value: **Color.White** | -| pressedFontColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | No | Font color of the arc button when pressed.
Default value: **Color.White** | -| fontStyle | [FontStyle](ts-appendix-enums.md#fontstyle) | No | Font style of the arc button.
Default value: **FontStyle.Normal** | -| fontFamily | string \| [Resource](ts-types.md#resource) | No | Font family of the arc button text. | -| fontMargin | [LocalizedMargin](ts-types.md#localizedmargin12) | No | Margin of the arc button text.
Default value: **{ start: 24vp, top: 10vp,end: 24vp, bottom:16vp }**| -|onTouch | (event: [TouchEvent](ts-universal-events-touch.md#touchevent)) => void | No | Callback triggered by touch actions on the arc button.| -|onClick | (event: [ClickEvent](ts-universal-events-click.md#clickevent)) => void | No | Callback triggered by click actions on the arc button.| +| position | [ArcButtonPosition](#arcbuttonposition) | Yes | Type of the arc button.
Default value: **ArcButtonPosition.BOTTOM_EDGE**| +| styleMode | [ArcButtonStyleMode](#arcbuttonstylemode) | Yes | Style mode for the arc button.
Default value: **ArcButtonStyleMode.EMPHASIZED_LIGHT**| +| status | [ArcButtonStatus](#arcbuttonstatus) | Yes | Status of the arc button.
Default value: **ArcButtonStatus.NORMAL** | +| label | [ResourceStr](ts-types.md#resourcestr) | Yes | Text displayed on the arc button. | +| backgroundBlurStyle | [BlurStyle](ts-universal-attributes-background.md#blurstyle9) | Yes | Background blur style of the arc button.
Default value: **BlurStyle.NONE**| +| backgroundColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | Yes | Background color of the arc button.
Default value: **Color.Black** | +| shadowColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | Yes | Shadow color of the arc button.
Default value: **Color.Black** | +| shadowEnabled | boolean | Yes | Whether to enable the shadow for the arc button.
Default value: **false**
The value **true** means to enable the shadow, and **false** means the opposite.| +| fontSize | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes | Font size of the arc button.
Default value: **19fp** | +| fontColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | Yes | Font color of the arc button.
Default value: **Color.White** | +| pressedFontColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | Yes | Font color of the arc button when pressed.
Default value: **Color.White** | +| fontStyle | [FontStyle](ts-appendix-enums.md#fontstyle) | Yes | Font style of the arc button.
Default value: **FontStyle.Normal** | +| fontFamily | string \| [Resource](ts-types.md#resource) | Yes | Font family of the arc button. | +| fontMargin | [LocalizedMargin](ts-types.md#localizedmargin12) | Yes | Margin of the arc button text.
Default value: **{ start: 24vp, top: 10vp,end: 24vp, bottom: 16vp }**| +|onTouch | [Callback](ts-types.md#voidcallback12)< [TouchEvent](ts-universal-events-touch.md#touchevent)> | No | Callback triggered by touch actions on the arc button.| +|onClick | [Callback](ts-types.md#voidcallback12)<[ClickEvent](ts-universal-events-click.md#clickevent)) > | No | Callback triggered by click actions on the arc button.| + +### constructor + +constructor(options: CommonArcButtonOptions) + +A constructor used to create an **ArcButton** component. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +**Parameters** +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------- | ---- | --------------------------------------------- | +| options | [CommonArcButtonOptions](#commonarcbuttonoptions) | Yes | Text, background color, shadow, and other parameters of the **ArcButton** component.| + +## CommonArcButtonOptions + +Defines the default or custom style parameters for the **ArcButton** component. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +| Name | Type | Mandatory| Description | +| ------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| position | [ArcButtonPosition](#arcbuttonposition) | Yes | Type of the arc button.
Default value: **ArcButtonPosition.BOTTOM_EDGE**| +| styleMode | [ArcButtonStyleMode](#arcbuttonstylemode) | Yes | Style mode for the arc button.
Default value: **ArcButtonStyleMode.EMPHASIZED_LIGHT**| +| status | [ArcButtonStatus](#arcbuttonstatus) | Yes | Status of the arc button.
Default value: **ArcButtonStatus.NORMAL** | +| label | [ResourceStr](ts-types.md#resourcestr) | Yes | Text displayed on the arc button. | +| backgroundBlurStyle | [BlurStyle](ts-universal-attributes-background.md#blurstyle9) | Yes | Background blur style of the arc button.
Default value: **BlurStyle.NONE** | +| backgroundColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | Yes | Background color of the arc button.
Default value: **Color.Black** | +| shadowColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | Yes | Shadow color of the arc button.
Default value: **Color.Black** | +| shadowEnabled | boolean | Yes | Whether to enable the shadow for the arc button.
Default value: **false**
The value **true** means to enable the shadow, and **false** means the opposite.| +| fontSize | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes | Font size of the arc button.
Default value: **19fp** | +| fontColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | Yes | Font color of the arc button.
Default value: **Color.White** | +| pressedFontColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | Yes | Font color of the arc button when pressed.
Default value: **Color.White** | +| fontStyle | [FontStyle](ts-appendix-enums.md#fontstyle) | Yes | Font style of the arc button.
Default value: **FontStyle.Normal** | +| fontFamily | string \| [Resource](ts-types.md#resource) | Yes | Font family of the arc button. | +| fontMargin | [LocalizedMargin](ts-types.md#localizedmargin12) | Yes | Margin of the arc button text.
Default value: **{ start: 24vp, top: 10vp,end: 24vp, bottom: 16vp }**| +| onTouch | [Callback](ts-types.md#voidcallback12)< [TouchEvent](ts-universal-events-touch.md#touchevent)> | No | Callback triggered by touch actions on the arc button. | +| onClick | [Callback](ts-types.md#voidcallback12)<[ClickEvent](ts-universal-events-click.md#clickevent)) > | No | Callback triggered by click actions on the arc button. | ## ArcButtonPosition Enumerates the types of arc buttons that can be set for **ArcButton**. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Circle -| Name | Value | Description | +| Name | Value | Description | | ----------- | ---- | -------------------------------- | | TOP_EDGE | 0 | Upper arc button located at the top of the circular screen. | | BOTTOM_EDGE | 1 | Lower arc button located at the bottom of the circular screen.| @@ -92,7 +136,7 @@ Enumerates the types of arc buttons that can be set for **ArcButton**. Enumerates the style modes that can be set for **ArcButton**. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Circle @@ -102,13 +146,14 @@ Enumerates the style modes that can be set for **ArcButton**. | EMPHASIZED_DARK | 1 | Emphasized, dark color.| | NORMAL_LIGHT | 2 | Normal, light color.| | NORMAL_DARK | 3 | Normal, dark color.| +| CUSTOM | 4 | Custom style.| ## ArcButtonStatus Enumerates the states that can be set for **ArcButton**. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Circle @@ -119,7 +164,6 @@ Enumerates the states that can be set for **ArcButton**. | DISABLED | 2 | Disabled state.| - ## Example This example shows the usage of **ArcButton**. diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ArcSlider.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ArcSlider.md new file mode 100644 index 0000000000000000000000000000000000000000..babe26f0a2438119395e1a4d952406e133592176 --- /dev/null +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ArcSlider.md @@ -0,0 +1,373 @@ +# ArcSlider + +The **ArcSlider** component is designed for circular screens to quickly adjust settings, such as the volume and brightness. + +> **NOTE** +> +> This component is supported since API version 18. Updates will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```ts +import { + ArcSlider, + ArcSliderPosition, + ArcSliderOptions, + ArcSliderValueOptions, + ArcSliderLayoutOptions, + ArcSliderStyleOptions, + ArcSliderValueOptionsConstructorOptions, + ArcSliderLayoutOptionsConstructorOptions, + ArcSliderStyleOptionsConstructorOptions, + ArcSliderOptionsConstructorOptions +} from '@kit.ArkUI' +``` + +## Child Components + +Not supported + +## Attributes + +The [universal attributes](ts-component-general-attributes.md) are not supported. + +## Events + +The [universal events](ts-component-general-events.md) are not supported. + +## ArcSlider + +ArcSlider({ options: ArcSliderOptions }) + +Creates an **ArcSlider** instance. The input parameter is the configuration for the arc slider. + +**Decorator**: @Component + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | ------------------------------------------------------------ | +| options | [ArcSliderOptions](#arcslideroptions) | Yes | Parameters of the arc slider.
Default value: default values of all properties of [ArcSliderOptions](#arcslideroptions)| + +## ArcSliderOptions + +Defines the properties of the arc slider. + +**Decorator type**: @ObservedV2 + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +| Name| Type| Mandatory| Decorator| Description| +| -------- | -------- | -------- | -------- | -------- | +| valueOptions | [ArcSliderValueOptions](#arcslidervalueoptions) | No| @Trace | Value of the arc slider.
Default value: default values of all properties of [ArcSliderValueOptions](#arcslidervalueoptions)| +| layoutOptions | [ArcSliderLayoutOptions](#arcsliderlayoutoptions) | No| @Trace | Layout of the arc slider.
Default value: default values of all properties of [ArcSliderLayoutOptions](#arcsliderlayoutoptions)| +| styleOptions | [ArcSliderStyleOptions](#arcsliderstyleoptions) | No| @Trace | Style of the arc slider.
Default value: default values of all properties of [ArcSliderStyleOptions](#arcsliderstyleoptions)| +| digitalCrownSensitivity | [CrownSensitivity](ts-appendix-enums.md#crownsensitivity18) | No| @Trace | Sensitivity to the digital crown rotation.
Default value: **CrownSensitivity.MEDIUM**| +| onTouch | [ArcSliderTouchHandler](#arcslidertouchhandler) | No| @Trace | Callback invoked to notify the application when the arc slider is touched.
If no value is provided, no callback is performed.| +| onChange | [ArcSliderChangeHandler](#arcsliderchangehandler) | No| @Trace | Callback invoked to notify the application when the progress value of the arc slider changes.
If no value is provided, no callback is performed.| +| onEnlarge | [ArcSliderEnlargeHandler](#arcsliderenlargehandler) | No| @Trace | Callback invoked to notify the application when the arc slider is zoomed in or out.
If no value is provided, no callback is performed.| + +### constructor + +constructor(options?: ArcSliderOptionsConstructorOptions) + +A constructor used to create an **ArcSliderOptions** instance. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------------ | ---- | ---------------------------- | +| options | [ArcSliderOptionsConstructorOptions](#arcslideroptionsconstructoroptions) | No | Construction information for **ArcSliderOptions**.| + +## ArcSliderValueOptions + +Defines the value of the arc slider. + +**Decorator type**: @ObservedV2 + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +| Name | Type | Mandatory| Decorator| Description | +| ----- | ------ | ---- | ---------- | ------------------------------------------------------------ | +| progress | number | No | @Trace | Current progress.
Default value: same as the value of **min** | +| min | number | No | @Trace | Minimum value.
Default value: **0** | +| max | number | No | @Trace | Maximum value.
Default value: **100**
**NOTE**
If the value of **min** is greater than or equal to that of **max**, **min** is set to **0** and **max** **100**.
If the value is not within the [min, max] range, the value of **min** or **max** is used, whichever is closer.| + +### constructor + +constructor(options?: ArcSliderValueOptionsConstructorOptions) + +A constructor used to create an **ArcSliderValueOptions** instance. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------------ | ---- | --------------------------------- | +| options | [ArcSliderValueOptionsConstructorOptions](#arcslidervalueoptionsconstructoroptions) | No | Construction information for **ArcSliderValueOptions**.| + +## ArcSliderLayoutOptions + +Defines the layout of the arc slider. + +**Decorator type**: @ObservedV2 + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +| Name | Type | Mandatory| Decorator| Description | +| -------- | --------------------------------------- | ---- | ---------- | ------------------------------------------------------------ | +| reverse | boolean | No | @Trace | Whether the value range of the arc slider is reversed.
Default value: **true** (swipe from bottom to top)| +| position | [ArcSliderPosition](#arcsliderposition) | No | @Trace | Position of the arc slider on the screen.
Default value: **ArcSliderPosition.RIGHT**| + +### constructor + +constructor(options?: ArcSliderLayoutOptionsConstructorOptions) + +A constructor used to create an **ArcSliderLayoutOptions** instance. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------------ | ---- | ---------------------------------- | +| options | [ArcSliderLayoutOptionsConstructorOptions](#arcsliderlayoutoptionsconstructoroptions) | No | Construction information for **ArcSliderLayoutOptions**.| + +## ArcSliderStyleOptions + +Defines the style of the arc slider. + +**Decorator type**: @ObservedV2 + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +| Name | Type | Mandatory| Decorator| Description | +| -------------------- | ------ | ---- | ---------- | ------------------------------------------------------------ | +| trackThickness | number | No | @Trace | Stroke width of the arc slider in the normal state, in vp.
Default value: **5**
The value ranges from 5 to 16. If an invalid value is set, the default value is used.| +| activeTrackThickness | number | No | @Trace | Stroke width of the arc slider when it is zoomed in, in vp.
Default value: **24**
The value ranges from 24 to 36. If an invalid value is set, the default value is used.| +| trackColor | string | No | @Trace | Background color of the stroke.
Default value: **#33FFFFFF** | +| selectedColor | string | No | @Trace | Highlight color of the stroke.
Default value: **#FF5EA1FF** | +| trackBlur | number | No | @Trace | Blur effect applied to the stroke background, in vp.
Default value: **20**
If a value less than 0 is set, the default value is used.| + +### constructor + +constructor(options?: ArcSliderStyleOptionsConstructorOptions) + +A constructor used to create an **ArcSliderStyleOptions** instance. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------------ | ---- | --------------------------------- | +| options | [ArcSliderStyleOptionsConstructorOptions](#arcsliderstyleoptionsconstructoroptions) | No | Construction information for **ArcSliderStyleOptions**.| + +## ArcSliderPosition + +Defines the position of the arc slider on the screen. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +| Name | Value | Description | +| ----- | ---- | -------------------------------- | +| LEFT | 0 | The arc slider is displayed on the left.| +| RIGHT | 1 | The arc slider is displayed on the right.| + +## ArcSliderTouchHandler + +type ArcSliderTouchHandler = (event: TouchEvent) => void + +Defines the callback invoked to notify the application when the arc slider is touched. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | -------------------- | +| event | [TouchEvent](ts-universal-events-touch.md#touchevent) | Yes | **TouchEvent** object.| + +## ArcSliderChangeHandler + +type ArcSliderChangeHandler = (progress: number) => void + +Defines the callback invoked to notify the application when the progress value of the arc slider changes. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | -------------------- | +| progress | number | Yes | Current progress of the slider.| + +## ArcSliderEnlargeHandler + +type ArcSliderEnlargeHandler = (isEnlarged: boolean) => void + +Defines the callback invoked to notify the application when the arc slider is zoomed in or out. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------- | ---- | ------------------------------------------------------------ | +| isEnlarged | boolean | Yes | Whether the arc slider is zoomed in.
**false**: The arc slider is zoomed out.
**true**: The arc slider is zoomed in.| + +## ArcSliderOptionsConstructorOptions + +Defines the construction information for **ArcSliderOptions**. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +| Name | Type | Mandatory| Description | +| ----------------------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| valueOptions | [ArcSliderValueOptions](#arcslidervalueoptions) | No | Value of the arc slider.
Default value: default values of all properties of [ArcSliderValueOptions](#arcslidervalueoptions)| +| layoutOptions | [ArcSliderLayoutOptions](#arcsliderlayoutoptions) | No | Layout of the arc slider.
Default value: default values of all properties of [ArcSliderLayoutOptions](#arcsliderlayoutoptions)| +| styleOptions | [ArcSliderStyleOptions](#arcsliderstyleoptions) | No | Style of the arc slider.
Default value: default values of all properties of [ArcSliderStyleOptions](#arcsliderstyleoptions)| +| digitalCrownSensitivity | [CrownSensitivity](ts-appendix-enums.md#crownsensitivity18) | No | Sensitivity to the digital crown rotation.
Default value: **CrownSensitivity.MEDIUM** | +| onTouch | [ArcSliderTouchHandler](#arcslidertouchhandler) | No | Callback invoked to notify the application when the arc slider is touched.
If no value is provided, no callback is performed.| +| onChange | [ArcSliderChangeHandler](#arcsliderchangehandler) | No | Callback invoked to notify the application when the progress value of the arc slider changes.
If no value is provided, no callback is performed.| +| onEnlarge | [ArcSliderEnlargeHandler](#arcsliderenlargehandler) | No | Callback invoked to notify the application when the arc slider is zoomed in or out.
If no value is provided, no callback is performed.| + +## ArcSliderValueOptionsConstructorOptions + +Defines the construction information for **ArcSliderValueOptions**. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +| Name | Type | Mandatory| Description | +| ----- | ------ | ---- | ------------------------------------------------------------ | +| progress | number | No | Current progress.
Default value: same as the value of **min** | +| min | number | No | Minimum value.
Default value: **0** | +| max | number | No | Maximum value.
Default value: **100**
**NOTE**
If the value of **min** is greater than or equal to that of **max**, **min** is set to **0** and **max** **100**.
If the value is not within the [min, max] range, the value of **min** or **max** is used, whichever is closer.| + +## ArcSliderLayoutOptionsConstructorOptions + +Defines the construction information for **ArcSliderStyleOptions**. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | +| reverse | boolean | No | Whether the value range of the arc slider is reversed.
Default value: **true** (swipe from bottom to top)| +| position | [ArcSliderPosition](#arcsliderposition) | No | Position of the arc slider on the screen.
Default value: **ArcSliderPosition.RIGHT**| + +## ArcSliderStyleOptionsConstructorOptions + +Defines the construction information for **ArcSliderStyleOptions**. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +| Name | Type | Mandatory| Description | +| -------------------- | ------ | ---- | ------------------------------------------------------------ | +| trackThickness | number | No | Stroke width of the arc slider in the normal state, in vp.
Default value: **5**
The value ranges from 5 to 16. If an invalid value is set, the default value is used.| +| activeTrackThickness | number | No | Stroke width of the arc slider when it is zoomed in, in vp.
Default value: **24**
The value ranges from 24 to 36. If an invalid value is set, the default value is used.| +| trackColor | string | No | Background color of the stroke.
Default value: **#33FFFFFF** | +| selectedColor | string | No | Highlight color of the stroke.
Default value: **#FF5EA1FF** | +| trackBlur | number | No | Blur effect applied to the stroke background, in vp.
Default value: **20**
If a value less than 0 is set, the default value is used.| + +## Example + +```ts +// xxx.ets +import { + ArcSlider, + ArcSliderPosition, + ArcSliderOptions, + ArcSliderValueOptions, + ArcSliderLayoutOptions, + ArcSliderStyleOptions, + ArcSliderValueOptionsConstructorOptions, + ArcSliderLayoutOptionsConstructorOptions, + ArcSliderStyleOptionsConstructorOptions, + ArcSliderOptionsConstructorOptions +} from '@kit.ArkUI' + +@Entry +@ComponentV2 +struct ArcSliderExample { + valueOptionsConstructorOptions: ArcSliderValueOptionsConstructorOptions = { + progress: 60, + min: 10, + max: 110 + } + + layoutOptionsConstructorOptions: ArcSliderLayoutOptionsConstructorOptions = { + reverse: true, + position: ArcSliderPosition.RIGHT + } + styleOptionsConstructorOptions: ArcSliderStyleOptionsConstructorOptions = { + trackThickness: 8, + activeTrackThickness: 30, + trackColor: '#ffd5d5d5', + selectedColor: '#ff2787d9', + trackBlur: 20 + } + valueOptions: ArcSliderValueOptions = new ArcSliderValueOptions(this.valueOptionsConstructorOptions) + layoutOptions: ArcSliderLayoutOptions = new ArcSliderLayoutOptions(this.layoutOptionsConstructorOptions) + styleOptions: ArcSliderStyleOptions = new ArcSliderStyleOptions(this.styleOptionsConstructorOptions) + arcSliderOptionsConstructorOptions: ArcSliderOptionsConstructorOptions = { + valueOptions: this.valueOptions, + layoutOptions: this.layoutOptions, + styleOptions: this.styleOptions, + digitalCrownSensitivity:CrownSensitivity.LOW, + onTouch: (event: TouchEvent) => { + }, + onChange: (progress: number) => { + }, + onEnlarge: (isEnlarged: boolean) => { + } + } + arcSliderOptions: ArcSliderOptions = new ArcSliderOptions(this.arcSliderOptionsConstructorOptions) + + build() { + Column() { + ArcSlider({ options: this.arcSliderOptions })} + .width('100%') + } +} +``` + +![arcslider](figures/arcslider.gif) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-Chip.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-Chip.md index 2a2caf09d304ef585f4c01256e0fdb3af7d1c31e..cc50f2395da24b88931796e28a5b1056e977273b 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-Chip.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-Chip.md @@ -18,7 +18,7 @@ Not supported ## Chip -Chip({options:ChipOptions}): void +Chip(options:ChipOptions): void **Decorator**: @Builder @@ -28,9 +28,9 @@ Chip({options:ChipOptions}): void **Parameters** -| Name | Type | Mandatory| Decorator| Description | -| ------- | --------------------------- | ---- | ---------- | -------------------- | -| options | [ChipOptions](#chipoptions) | Yes | @Builder | Parameters of the chip.| +| Name | Type | Mandatory| Description | +| ------- | --------------------------- | ---- | -------------------- | +| options | [ChipOptions](#chipoptions) | Yes | Parameters of the chip.| ## ChipOptions @@ -41,25 +41,25 @@ Defines the type and style parameters of the chip. | Name | Type | Mandatory| Description | | --------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | size | [ChipSize](#chipsize) \| [SizeOptions](ts-types.md#sizeoptions) | No | Size of the chip.
Default value: **ChipSize**: **ChipSize.NORMAL**
If of the SizeOptions type, this parameter cannot be set in percentage.
**Atomic service API**: This API can be used in atomic services since API version 12.| -| enabled | boolean | No | Whether the chip can be selected.
Default value: **true**
**Atomic service API**: This API can be used in atomic services since API version 12.| -| activated | boolean | No | Whether the chip is activated.
Default value: **false**
**Atomic service API**: This API can be used in atomic services since API version 12. | +| enabled | boolean | No | Whether the chip can be selected.
Default value: **true**
**true**: The chip can be selected.
**false**: The chip cannot be selected.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| activated12+ | boolean | No | Whether the chip is activated.
Default value: **false**
**true**: The chip is activated.
**false**: The chip is not activated.
**Atomic service API**: This API can be used in atomic services since API version 12. | | prefixIcon | [PrefixIconOptions](#prefixiconoptions) | No | Prefix icon of the chip.
**Atomic service API**: This API can be used in atomic services since API version 12.| -| prefixSymbol | [ChipSymbolGlyphOptions](#chipsymbolglyphoptions12) | No | Symbol-type prefix icon of the chip.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| prefixSymbol12+ | [ChipSymbolGlyphOptions](#chipsymbolglyphoptions12) | No | Symbol-type prefix icon of the chip.
**Atomic service API**: This API can be used in atomic services since API version 12.| | label | [LabelOptions](#labeloptions) | Yes | Text of the chip.
**Atomic service API**: This API can be used in atomic services since API version 12. | | suffixIcon | [SuffixIconOptions](#suffixiconoptions) | No | Suffix icon of the chip.
**Atomic service API**: This API can be used in atomic services since API version 12.| -| suffixSymbol | [ChipSymbolGlyphOptions](#chipsymbolglyphoptions12) | No | Symbol-type suffix icon of the chip.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| suffixSymbol12+ | [ChipSymbolGlyphOptions](#chipsymbolglyphoptions12) | No | Symbol-type suffix icon of the chip.
**Atomic service API**: This API can be used in atomic services since API version 12.| | suffixSymbolOptions14+ | [ChipSuffixSymbolGlyphOptions](#chipsuffixsymbolglyphoptions14) | No| Accessibility settings of the symbol-type suffix icon.
**Atomic service API**: This API can be used in atomic services since API version 14.| | backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | No | Background color of the chip.
Default value: **$r('sys.color.ohos_id_color_button_normal')**
**Atomic service API**: This API can be used in atomic services since API version 12.| -| activatedBackgroundColor | [ResourceColor](ts-types.md#resourcecolor) | No | Background color of the chip when it is activated.
Default value: **$r('sys.color.ohos_id_color_emphasize').**
**Atomic service API**: This API can be used in atomic services since API version 12.| +| activatedBackgroundColor12+ | [ResourceColor](ts-types.md#resourcecolor) | No | Background color of the chip when it is activated.
Default value: **$r('sys.color.ohos_id_color_emphasize').**
**Atomic service API**: This API can be used in atomic services since API version 12.| | borderRadius | [Dimension](ts-types.md#dimension10) | No | Border radius of the chip. This parameter cannot be set in percentage.
Default value: **$r('sys.float.ohos_id_corner_radius_button')**
**Atomic service API**: This API can be used in atomic services since API version 12.| | allowClose | boolean | No | Whether to show the close icon.
Default value: **true**
**Atomic service API**: This API can be used in atomic services since API version 12.| | onClose | ()=>void | No | Event triggered when the close icon is clicked.
**Atomic service API**: This API can be used in atomic services since API version 12.| -| onClicked | Callback\ | No | Event triggered when the chip is clicked.
**Atomic service API**: This API can be used in atomic services since API version 12. | -| direction | [Direction](ts-appendix-enums.md#direction) | No| Layout direction.
Default value: **Direction.Auto**
**Atomic service API**: This API can be used in atomic services since API version 12.| +| onClicked12+ | Callback\ | No | Event triggered when the chip is clicked.
**Atomic service API**: This API can be used in atomic services since API version 12. | +| direction12+ | [Direction](ts-appendix-enums.md#direction) | No| Layout direction.
Default value: **Direction.Auto**
**Atomic service API**: This API can be used in atomic services since API version 12.| | closeOptions14+ | [CloseOptions](#closeoptions14) | No| Accessibility settings of the default close icon.
**Atomic service API**: This API can be used in atomic services since API version 14.| | accessibilityDescription14+ | [ResourceStr](ts-types.md#resourcestr) | No| Accessible description of the chip. You can provide comprehensive text explanations to help users understand the operation they are about to perform and its potential consequences, especially when these cannot be inferred from the component's attributes and accessibility text alone. If a component contains both text information and the accessible description, the text is announced first and then the accessible description, when the component is selected.
**Atomic service API**: This API can be used in atomic services since API version 14.| | accessibilityLevel14+ | string | No| Accessibility level of the chip. It determines whether the component can be recognized by accessibility services.
The options are as follows:
**"auto"**: It is treated as "yes" by the system.
**"yes"**: The component can be recognized by accessibility services.
**"no"**: The component cannot be recognized by accessibility services.
**"no-hide-descendants"**: Neither the component nor its child components can be recognized by accessibility services.
Default value: **"auto"**
**Atomic service API**: This API can be used in atomic services since API version 14.| -| accessibilitySelectedType14+ | [AccessibilitySelectedType](#accessibilityselectedtype14) | No| Type of selected state for the chip.
**Atomic service API**: This API can be used in atomic services since API version 14.| +| accessibilitySelectedType14+ | [AccessibilitySelectedType](#accessibilityselectedtype14) | No| Type of selected state for the chip.
Default value:
If the **activated** property is set but **accessibilitySelectedType** is not specified, the default type is **CHECKED**. If the **activated** property is not set, the default type is **CLICKED**.
**Atomic service API**: This API can be used in atomic services since API version 14.| > **NOTE** > @@ -88,7 +88,7 @@ Enumerates the size types of the chip. ## AccessibilitySelectedType14+ -Enumerates the selected state types of the chip. +Enumerates the selected state types of the chip. It allows you to specify how accessibility services convey the component's selected state to users. Different selected state types provide distinct semantics and user experiences. **Atomic service API**: This API can be used in atomic services since API version 14. @@ -96,9 +96,9 @@ Enumerates the selected state types of the chip. | Name| Value| Description| | ---- | -- | ---- | -| CLICKED | 0 | Default selected state type of the chip.| -| CHECKED | 1 | Selected state type of the chip when used as a check box.| -| SELECTED | 2 | Selected state type of the chip when used as a radio button.| +| CLICKED | 0 | Clickable type. The chip acts as a regular button, without reporting any selected state to accessibility services. Use this type when the chip triggers an action but does not maintain a selected state.| +| CHECKED | 1 | Checkbox type. The chip reports its selected state to accessibility services using the [accessibilityChecked](ts-universal-attributes-accessibility.md#accessibilitychecked13) attribute. Use this type for multi-select scenarios, such as tag filtering and attribute selection.| +| SELECTED | 2 | Radio type. The chip reports its selected state to accessibility services using the [accessibilitySelected](ts-universal-attributes-accessibility.md#accessibilityselected13) attribute. Use this type for single-select scenarios, such as navigation bar tabs and radio buttons.| ## IconCommonOptions @@ -142,7 +142,7 @@ Inherits [IconCommonOptions](#iconcommonoptions). | ------ | ---------- | ---- | ------------------ | | action | () => void | No | Action of the suffix icon.
**Atomic service API**: This API can be used in atomic services since API version 12.| | accessibilityText14+ | [ResourceStr](ts-types.md#resourcestr) | No| Accessibility text, that is, accessibility label name, of the suffix icon. If a component does not contain text information, it will not be announced by the screen reader when selected. In this case, the screen reader user cannot know which component is selected. To solve this problem, you can set accessibility text for components without text information. When such a component is selected, the screen reader announces the specified accessibility text, informing the user which component is selected.
**Atomic service API**: This API can be used in atomic services since API version 14.| -| accessibilityDescription14+ | [ResourceStr](ts-types.md#resourcestr) | No| Accessible description of the suffix icon. You can provide comprehensive text explanations to help users understand the operation they are about to perform and its potential consequences, especially when these cannot be inferred from the component's attributes and accessibility text alone. If a component contains both text information and the accessible description, the text is announced first and then the accessible description, when the component is selected.
**Atomic service API**: This API can be used in atomic services since API version 14.| +| accessibilityDescription14+ | [ResourceStr](ts-types.md#resourcestr) | No| Accessible description of the suffix icon. You can provide comprehensive text explanations to help users understand the operation they are about to perform and its potential consequences, especially when these cannot be inferred from the chip's attributes and accessibility text alone. If a component contains both text information and the accessible description, the text is announced first and then the accessible description, when the component is selected.
**Atomic service API**: This API can be used in atomic services since API version 14.| | accessibilityLevel14+ | string | No| Accessibility level of the suffix icon. It determines whether the component can be recognized by accessibility services.
The options are as follows:
**"auto"**: It is treated as "yes" when **action** is set for the component and as "no" otherwise.
**"yes"**: The component can be recognized by accessibility services.
**"no"**: The component cannot be recognized by accessibility services.
**"no-hide-descendants"**: Neither the component nor its child components can be recognized by accessibility services.
Default value: **"auto"**
**Atomic service API**: This API can be used in atomic services since API version 14.| ## AccessibilityOptions14+ @@ -261,6 +261,7 @@ struct Index { Column({ space: 10 }) { Chip({ prefixIcon: { + // Replace 'app.media.chips' with your actual icon resource. src: $r('app.media.chips'), size: { width: 16, height: 16 }, fillColor: Color.Red @@ -273,6 +274,7 @@ struct Index { labelMargin: { left: 20, right: 30 } }, suffixIcon: { + // Replace 'app.media.close' with your actual icon resource. src: $r('app.media.close'), size: { width: 16, height: 16 }, fillColor: Color.Red @@ -305,6 +307,7 @@ struct Index { Column({ space: 10 }) { Chip({ prefixIcon: { + // Replace 'app.media.chips' with your actual icon resource. src: $r('app.media.chips'), size: { width: 16, height: 16 }, fillColor: Color.Blue @@ -344,6 +347,7 @@ struct Index { Column({ space: 10 }) { Chip({ prefixIcon: { + // Replace 'app.media.chips' with your actual icon resource. src: $r('app.media.chips'), size: { width: 16, height: 16 }, fillColor: Color.Blue @@ -388,6 +392,7 @@ struct Index { Column({ space: 10 }) { Chip({ prefixIcon: { + // Replace 'app.media.chips' with your actual icon resource. src: $r('app.media.chips'), size: { width: 16, height: 16 }, fillColor: Color.Blue, @@ -443,6 +448,7 @@ struct Index { Column({ space: 10 }) { Chip({ prefixIcon: { + // Replace 'app.media.chips' with your actual icon resource. src: $r('app.media.chips'), size: { width: 16, height: 16 }, fillColor: Color.Blue, @@ -502,6 +508,7 @@ struct ChipPage { Chip({ direction: Direction.Rtl, prefixIcon: { + // Replace 'app.media.chips' with your actual icon resource. src: $r('app.media.chips'), size: { width: 16, height: 16 }, fillColor: Color.Red, @@ -514,6 +521,7 @@ struct ChipPage { localizedLabelMargin: { start: LengthMetrics.vp(20), end: LengthMetrics.vp(20) }, }, suffixIcon: { + // Replace 'app.media.close' with your actual icon resource. src: $r('app.media.close'), size: { width: 16, height: 16 }, fillColor: Color.Red, @@ -540,7 +548,7 @@ This example implements the accessibility feature for a chip with an image-type ```ts // xxx.ets -import { Chip, SymbolGlyphModifier } from '@kit.ArkUI'; +import { Chip } from '@kit.ArkUI'; @Builder function DefaultFunction(): void { @@ -754,3 +762,103 @@ struct ChipExample2 { } } ``` + +### Example 9: Implementing Chip Accessibility + +This example demonstrates how to set accessibility properties for the chip, including different selected state types. + +```ts +import { AccessibilitySelectedType, Chip, ChipSize } from '@kit.ArkUI'; + +@Entry +@Component +struct ChipAccessibilityExample { + @State clickedChipActivated: boolean = false; + @State checkedChipActivated: boolean = false; + @State selectedChipActivated: boolean = false; + + build() { + Column({ space: 20 }) { + Text("Chip accessibility example").fontSize(20).fontWeight(FontWeight.Bold) + + // Clickable chip - CLICKED type + Chip({ + label: { text: "Clickable chip" }, + prefixIcon: { + src: $r('sys.media.ohos_app_icon'), + fillColor: Color.Blue + }, + size: ChipSize.NORMAL, + accessibilitySelectedType: AccessibilitySelectedType.CLICKED, // Clickable type + accessibilityDescription: "This is a clickable chip", // Overall accessibility description + accessibilityLevel: "yes," // Make sure it can be recognized by accessibility services. + closeOptions: { + accessibilityDescription: "Remove this chip. This action cannot be undone" // Detailed description for the close icon. + }, + activated: this.clickedChipActivated, + onClicked: () => { + this.clickedChipActivated = !this.clickedChipActivated; + this.getUIContext().getPromptAction().showToast({ message: "Clickable chip is clicked" }); + }, + onClose: () => { + this.getUIContext().getPromptAction().showToast({ message: "The close icon of the clickable chip is clicked" }); + } + }) + + // Checkbox chip - CHECKED type + Chip({ + label: { text: "Checkbox chip" }, + prefixIcon: { + src: $r('sys.media.ohos_app_icon'), + fillColor: Color.Green + }, + size: ChipSize.NORMAL, + accessibilitySelectedType: AccessibilitySelectedType.CHECKED, // Checkbox chip + accessibilityDescription: "This is a checkbox chip", // Overall accessibility description + activated: this.checkedChipActivated, + onClicked: () => { + this.checkedChipActivated = !this.checkedChipActivated; + this.getUIContext().getPromptAction().showToast({ + message: this.checkedChipActivated ? "Checkbox chip is selected" : "Checkbox chip is deselected" + }); + } + }) + + // Radio chip - SELECTED type + Chip({ + label: { text: "Radio chip" }, + prefixIcon: { + src: $r('sys.media.ohos_app_icon'), + fillColor: Color.Red + }, + size: ChipSize.NORMAL, + accessibilitySelectedType: AccessibilitySelectedType.SELECTED, // Radio type + accessibilityDescription: "This is a radio chip", // Overall accessibility description + activated: this.selectedChipActivated, + onClicked: () => { + this.selectedChipActivated = !this.selectedChipActivated; + this.getUIContext().getPromptAction().showToast({ + message: this.checkedChipActivated ? "Radio chip is selected" : "Radio chip is deselected" + }); + } + }) + + // Example of setting the accessibility level + Chip({ + label: { text: ""Accessibility level set to no" }, + size: ChipSize.NORMAL, + accessibilityLevel: "no," // This chip cannot be recognized by accessibility services. + closeOptions: { + accessibilityLevel: "no" + }, + backgroundColor: '#CCCCCC', + onClicked: () => { + this.getUIContext().getPromptAction().showToast({ message: "This chip cannot be recognized by accessibility services." }); + } + }) + } + .width('100%') + .padding(16) + } +} +``` diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ChipGroup.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ChipGroup.md index 4776b32f5b06fc178f6b38dbd3b7291cf936420f..f8856dbfd4f5379a4b81bfc3ed24fa000b2998f6 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ChipGroup.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ChipGroup.md @@ -64,17 +64,17 @@ Defines the specific attributes of individual chips. | Name | Type | Mandatory| Description | | ---------- | ----------------------------- | ---- | ----------------------------------- | -| prefixIcon | [IconOptions](#iconoptions) | No | Prefix image icon of the chip.
**Atomic service API**: This API can be used in atomic services since API version 12. | -| prefixSymbol | [ChipSymbolGlyphOptions](ohos-arkui-advanced-Chip.md#chipsymbolglyphoptions12) | No | Prefix symbol glyph icon of the chip.
**Atomic service API**: This API can be used in atomic services since API version 12. | -| label | [LabelOptions](#labeloptions) | Yes | Text of the chip.
**Atomic service API**: This API can be used in atomic services since API version 12. | -| suffixIcon(deprecated) | [IconOptions](#iconoptions) | No | Suffix image icon of the chip.
**NOTE**
This API is supported since API version 12 and deprecated since API version 14. You are advised to use **suffixImageIcon** instead.| -| suffixSymbol | [ChipSymbolGlyphOptions](ohos-arkui-advanced-Chip.md#chipsymbolglyphoptions12) | No | Suffix symbol glyph icon of the chip.
**Atomic service API**: This API can be used in atomic services since API version 12. | -| allowClose | boolean | No | Whether to show the close icon.
Default value: **false**
**Atomic service API**: This API can be used in atomic services since API version 12. | -| suffixImageIcon14+ | [SuffixImageIconOptions](#suffiximageiconoptions14) | No| Suffix image icon of the chip.
**Atomic service API**: This API can be used in atomic services since API version 14.| -| suffixSymbolOptions14+ | [ChipSuffixSymbolGlyphOptions](ohos-arkui-advanced-Chip.md#chipsuffixsymbolglyphoptions14) | No| Suffix symbol icon of the chip.
**Atomic service API**: This API can be used in atomic services since API version 14.| -| closeOptions14+ | [CloseOptions](ohos-arkui-advanced-Chip.md#closeoptions14) | No| Accessibility options of the default close icon.
**Atomic service API**: This API can be used in atomic services since API version 14.| -| accessibilityDescription14+ | [ResourceStr](ts-types.md#resourcestr) | No| Accessible description of the chip. You can provide comprehensive text explanations to help users understand the operation they are about to perform and its potential consequences, especially when these cannot be inferred from the chip's attributes and accessibility text alone. If a chip contains both text information and the accessible description, the text is announced first and then the accessible description, when the chip is selected.
**Atomic service API**: This API can be used in atomic services since API version 14.| -| accessibilityLevel14+ | string | No| Accessibility level of the chip. It determines whether the chip can be recognized by accessibility services.
The options are as follows:
**"auto"**: It is treated as "yes" by the system.
**"yes"**: The chip can be recognized by accessibility services.
**"no"**: The chip cannot be recognized by accessibility services.
**"no-hide-descendants"**: Neither the chip nor its child components can be recognized by accessibility services.
Default value: **"auto"**
**Atomic service API**: This API can be used in atomic services since API version 14.| +| prefixIcon | [IconOptions](#iconoptions) | No | Prefix image icon of the chip.
**Atomic service API**: This API can be used in atomic services since API version 12. | +| prefixSymbol | [ChipSymbolGlyphOptions](ohos-arkui-advanced-Chip.md#chipsymbolglyphoptions12) | No | Prefix symbol glyph icon of the chip.
**Atomic service API**: This API can be used in atomic services since API version 12. | +| label | [LabelOptions](#labeloptions) | Yes | Text of the chip.
**Atomic service API**: This API can be used in atomic services since API version 12. | +| suffixIcon(deprecated) | [IconOptions](#iconoptions) | No | Suffix image icon of the chip.
**Atomic service API**: This API can be used in atomic services since API version 12.
**NOTE**
This API is supported since API version 12 and deprecated since API version 14. You are advised to use **suffixImageIcon** instead. | +| suffixSymbol | [ChipSymbolGlyphOptions](ohos-arkui-advanced-Chip.md#chipsymbolglyphoptions12) | No | Suffix symbol glyph icon of the chip.
**Atomic service API**: This API can be used in atomic services since API version 12. | +| allowClose | boolean | No | Whether to show the close icon.
Default value: **false**
**Atomic service API**: This API can be used in atomic services since API version 12. | +| suffixImageIcon14+ | [SuffixImageIconOptions](#suffiximageiconoptions14) | No| Suffix image icon of the chip.
**Atomic service API**: This API can be used in atomic services since API version 14.| +| suffixSymbolOptions14+ | [ChipSuffixSymbolGlyphOptions](ohos-arkui-advanced-Chip.md#chipsuffixsymbolglyphoptions14) | No| Suffix symbol icon of the chip.
**Atomic service API**: This API can be used in atomic services since API version 14.| +| closeOptions14+ | [CloseOptions](ohos-arkui-advanced-Chip.md#closeoptions14) | No| Accessibility options of the default close icon.
**Atomic service API**: This API can be used in atomic services since API version 14.| +| accessibilityDescription14+ | [ResourceStr](ts-types.md#resourcestr) | No| Accessible description of the chip. You can provide comprehensive text explanations to help users understand the operation they are about to perform and its potential consequences, especially when these cannot be inferred from the chip's attributes and accessibility text alone. If a chip contains both text information and the accessible description, the text is announced first and then the accessible description, when the chip is selected.
**Atomic service API**: This API can be used in atomic services since API version 14.| +| accessibilityLevel14+ | string | No| Accessibility level of the chip. It determines whether the chip can be recognized by accessibility services.
The options are as follows:
**"auto"**: It is treated as "yes" by the system.
**"yes"**: The chip can be recognized by accessibility services.
**"no"**: The chip cannot be recognized by accessibility services.
**"no-hide-descendants"**: Neither the chip nor its child components can be recognized by accessibility services.
Default value: **"auto"**
**Atomic service API**: This API can be used in atomic services since API version 14.| >**NOTE** @@ -91,7 +91,7 @@ Defines the common attributes shared by all chips in the chip group. | Name | Type | Mandatory| Description | | ----------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| size | [ChipSize](ohos-arkui-advanced-Chip.md#chipsize) \| [SizeOptions](ts-types.md#sizeoptions) | No | Chip size. To use this API, you must import the **ChipSize** type from the **Chip** component.
Default value: **ChipSize**: **ChipSize.NORMAL**
If this parameter is set to **undefined**, the default value is used.| +| size | [ChipSize](ohos-arkui-advanced-Chip.md#chipsize) \| [SizeOptions](ts-types.md#sizeoptions) | No | Chip size. To use this API, you must import the **ChipSize** type from the **Chip** component.
Default value: **ChipSize**: **ChipSize.NORMAL**
If this parameter is set to **undefined**, the default value is used.| | backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | No | Background color of the chip.
Default value: **$r('sys.color.ohos_id_color_button_normal')**
If this parameter is set to **undefined**, the default value is used.| | fontColor | [ResourceColor](ts-types.md#resourcecolor) | No | Font color of the chip.
Default value: **$r('sys.color.ohos_id_color_text_primary')**
If this parameter is set to **undefined**, the default value is used.| | selectedFontColor | [ResourceColor](ts-types.md#resourcecolor) | No | Font color of the chip when it is activated or selected.
Default value: **$r('sys.color.ohos_id_color_text_primary_contrary')**
If this parameter is set to **undefined**, the default value is used.| @@ -143,8 +143,8 @@ Inherits [IconOptions](#iconoptions). | Name| Type| Mandatory| Description| | ---- | ---- | --- | ---- | | action | [VoidCallback](ts-types.md#voidcallback12) | No| Action of the suffix icon.| -| accessibilityText | [ResourceStr](ts-types.md#resourcestr) | No| Accessibility text, that is, accessible label name, of the suffix icon. If an icon does not contain text information, it will not be announced by the screen reader when selected. In this case, the screen reader user cannot know which icon is selected. To solve this problem, you can set accessibility text for icons without text information. When such an icon is selected, the screen reader announces the specified accessibility text, informing the user which icon is selected. | -| accessibilityDescription | [ResourceStr](ts-types.md#resourcestr) | No| Accessible description of the suffix icon. You can provide comprehensive text explanations to help users understand the operation they are about to perform and its potential consequences, especially when these cannot be inferred from the icon's attributes and accessibility text alone. If an icon contains both text information and the accessible description, the text is announced first and then the accessible description, when the icon is selected.| +| accessibilityText | [ResourceStr](ts-types.md#resourcestr) | No| Accessibility text, that is, accessible label name, of the suffix icon. If an icon does not contain text information, it will not be announced by the screen reader when selected. In this case, the screen reader user cannot know which icon is selected. To solve this problem, you can set accessibility text for icons without text information. When such an icon is selected, the screen reader announces the specified accessibility text, informing the user which icon is selected.| +| accessibilityDescription | [ResourceStr](ts-types.md#resourcestr) | No| Accessible description of the suffix icon. You can provide comprehensive text explanations to help users understand the operation they are about to perform and its potential consequences, especially when these cannot be inferred from the chip's attributes and accessibility text alone. If an icon contains both text information and the accessible description, the text is announced first and then the accessible description, when the icon is selected.| | accessibilityLevel | string | No| Accessibility level of the suffix icon. It determines whether the icon can be recognized by accessibility services.
The options are as follows:
**"auto"**: It is treated as "yes" when **action** is set for the icon and as "no" otherwise.
**"yes"**: The icon can be recognized by accessibility services.
**"no"**: The icon cannot be recognized by accessibility services.
**"no-hide-descendants"**: Neither the icon nor its child components can be recognized by accessibility services.
Default value: **"auto"**| ## SymbolItemOptions14+ @@ -157,10 +157,10 @@ Defines the options for the trailing symbol item in a chip group. | Name| Type| Mandatory| Description| | ---- | ---- | --- | ---- | -| symbol | [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) | No| Settings of the trailing symbol item.| -| action | [VoidCallback](ts-types.md#voidcallback12) | No| Action of the trailing symbol item.| +| symbol | [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) | Yes| Settings of the trailing symbol item.| +| action | [VoidCallback](ts-types.md#voidcallback12) | Yes| Action of the trailing symbol item.| | accessibilityText | [ResourceStr](ts-types.md#resourcestr) | No| Accessibility text of the trailing symbol item. If a trailing symbol item does not contain text information, it will not be announced by the screen reader when selected. In this case, the screen reader user cannot know which item is selected. To solve this problem, you can set accessibility text for trailing symbol items without text information. When such a trailing symbol item is selected, the screen reader announces the specified accessibility text, informing the user which item is selected.| -| accessibilityDescription | [ResourceStr](ts-types.md#resourcestr) | No| Accessible description of the trailing symbol item. You can provide comprehensive text explanations to help users understand the operation they are about to perform and its potential consequences, especially when these cannot be inferred from the trailing symbol item's attributes and accessibility text alone. If a trailing symbol item contains both text information and the accessible description, the text is announced first and then the accessible description, when the trailing symbol item is selected.| +| accessibilityDescription | [ResourceStr](ts-types.md#resourcestr) | No| Accessible description of the trailing symbol item. You can provide comprehensive text explanations to help users understand the operation they are about to perform and its potential consequences, especially when these cannot be inferred from the chip's attributes and accessibility text alone. If a trailing symbol item contains both text information and the accessible description, the text is announced first and then the accessible description, when the trailing symbol item is selected.| | accessibilityLevel | string | No| Accessibility level of the trailing symbol item. It determines whether the trailing symbol item can be recognized by accessibility services.
The options are as follows:
**"auto"**: It is treated as "yes" by the system.
**"yes"**: The trailing symbol item can be recognized by accessibility services.
**"no"**: The trailing symbol item cannot be recognized by accessibility services.
**"no-hide-descendants"**: Neither the trailing symbol item nor its child components can be recognized by accessibility services.
Default value: **"auto"**| ## IconGroupSuffix @@ -173,7 +173,7 @@ Defines the options for the trailing symbol item in a chip group. | Name | Type | Mandatory| Decorator| Description | | -------- | ---------------------- | ---- | ----------------------------------------------| ----------------------------------------------| -| items | Array<[IconItemOptions](#iconitemoptions) \| [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) \| [ SymbolItemOptions](#symbolItemoptions14)> | Yes | @Require @Prop | Custom builder items.| +| items | Array<[IconItemOptions](#iconitemoptions) \| [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) \| [ SymbolItemOptions](#symbolitemoptions14)> | Yes | @Require @Prop | Custom builder items.| > **NOTE** > @@ -188,11 +188,11 @@ Defines the tail builder, which imposes limitations on the settings for the back | Name | Type | Mandatory| Description | | -------- | -------------- | ---- | ------------------------------ | -| icon | [IconOptions](#iconoptions) | Yes | Custom builder icon.
When the chip size is **ChipSize.SMALL**, the suffix is at {width: 16, height: 16} by default.
When the chip size is **ChipSize.NORMAL**, the suffix is at {width: 24, height: 24} by default.
To dynamically change the size, you must use the [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) type when importing the [IconGroupSuffix](#icongroupsuffix) API.
**Atomic service API**: This API can be used in atomic services since API version 12. | -| action | Callback\ | Yes | Callback of custom builder items.
If the value is **undefined**, the event is unbound.
**Atomic service API**: This API can be used in atomic services since API version 12. | -| accessibilityText14+ | [ResourceStr](ts-types.md#resourcestr) | No| Accessibility text. If a component does not contain text information, it will not be announced by the screen reader when selected. In this case, the screen reader user cannot know which component is selected. To solve this problem, you can set accessibility text for trailing symbol items without text information. When such a component is selected, the screen reader announces the specified accessibility text, informing the user which component is selected.
**Atomic service API**: This API can be used in atomic services since API version 14.| -| accessibilityDescription14+ | [ResourceStr](ts-types.md#resourcestr) | No| Accessible description of the trailing symbol item. You can provide comprehensive text explanations to help users understand the operation they are about to perform and its potential consequences, especially when these cannot be inferred from the component's attributes and accessibility text alone. If a component contains both text information and the accessible description, the text is announced first and then the accessible description, when the component is selected.| -| accessibilityLevel14+ | string | No| Accessibility level of the trailing symbol item. It determines whether the trailing symbol item can be recognized by accessibility services.
The options are as follows:
**"auto"**: It is treated as "yes" by the system.
**"yes"**: The trailing symbol item can be recognized by accessibility services.
**"no"**: The trailing symbol item cannot be recognized by accessibility services.
**"no-hide-descendants"**: Neither the trailing symbol item nor its child components can be recognized by accessibility services.
Default value: **"auto"**
**Atomic service API**: This API can be used in atomic services since API version 14.| +| icon | [IconOptions](#iconoptions) | Yes | Custom builder icon.
When the chip size is **ChipSize.SMALL**, the suffix is at {width: 16, height: 16} by default.
When the chip size is **ChipSize.NORMAL**, the suffix is at {width: 24, height: 24} by default.
To dynamically change the size, you must use the [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) type when importing the [IconGroupSuffix](#icongroupsuffix) API.
**Atomic service API**: This API can be used in atomic services since API version 12. | +| action | Callback\ | Yes | Callback of custom builder items.
If the value is **undefined**, the event is unbound.
**Atomic service API**: This API can be used in atomic services since API version 12. | +| accessibilityText14+ | [ResourceStr](ts-types.md#resourcestr) | No| Accessibility text of the trailing symbol item. If a trailing symbol item does not contain text information, it will not be announced by the screen reader when selected. In this case, the screen reader user cannot know which item is selected. To solve this problem, you can set accessibility text for trailing symbol items without text information. When such a component is selected, the screen reader announces the specified accessibility text, informing the user which component is selected.
**Atomic service API**: This API can be used in atomic services since API version 14.| +| accessibilityDescription14+ | [ResourceStr](ts-types.md#resourcestr) | No| Accessible description of the trailing symbol item. You can provide comprehensive text explanations to help users understand the operation they are about to perform and its potential consequences, especially when these cannot be inferred from the chip's attributes and accessibility text alone. If a trailing symbol item contains both text information and the accessible description, the text is announced first and then the accessible description, when the trailing symbol item is selected.
**Atomic service API**: This API can be used in atomic services since API version 14.| +| accessibilityLevel14+ | string | No| Accessibility level of the trailing symbol item. It determines whether the trailing symbol item can be recognized by accessibility services.
The options are as follows:
**"auto"**: It is treated as "yes" by the system.
**"yes"**: The trailing symbol item can be recognized by accessibility services.
**"no"**: The trailing symbol item cannot be recognized by accessibility services.
**"no-hide-descendants"**: Neither the trailing symbol item nor its child components can be recognized by accessibility services.
Default value: **"auto"**
**Atomic service API**: This API can be used in atomic services since API version 14.| ## IconOptions @@ -221,7 +221,7 @@ Defines the common attributes of labels. ## Example -### Example 1: Implementing a Chip Group Without a Builder-Defined Suffix +### Example 1: Implementing a Chip Group Without a Builder-defined Suffix This example shows how to implement a chip group without a builder-defined suffix. @@ -238,6 +238,7 @@ struct Index { ChipGroup({ items: [ { + // Replace 'app.media.icon' with your actual icon resource. prefixIcon: { src: $r('app.media.icon') }, label: { text: "Chip 1" }, suffixIcon: { src: $r('sys.media.ohos_ic_public_cut') }, @@ -291,7 +292,7 @@ struct Index { ![](figures/chipGroupDemo1.jpeg) -### Example 2: Implementing a Chip Group with a Builder-Defined Suffix +### Example 2: Implementing a Chip Group with a Builder-defined Suffix This example shows how to implement a chip group with a builder-defined suffix. diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ComposeListItem.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ComposeListItem.md index 656441172c71925c2be50b801096c431cfd475ad..c4118a1d4fd8d794beb689b3790a82065412be89 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ComposeListItem.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ComposeListItem.md @@ -21,7 +21,7 @@ import { ComposeListItem } from "@kit.ArkUI" Not supported ## Attributes -The [universal attributes](ts-universal-attributes-size.md) are supported. +The [universal attributes](ts-component-general-attributes.md) are not supported. ## ComposeListItem @@ -47,6 +47,7 @@ ComposeListItem({contentItem?: ContentItem, operateItem?: OperateItem}) | -------- | -------- | -------- | -------- | | iconStyle | [IconType](#icontype) | No| Icon style of the element on the left.
**Atomic service API**: This API can be used in atomic services since API version 11.| | icon | [ResourceStr](ts-types.md#resourcestr) | No| Icon resource of the element on the left.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| symbolStyle18+ | [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) | No| Symbol icon resource of the element on the left, which has higher priority than **icon**.
**Atomic service API**: This API can be used in atomic services since API version 18.| | primaryText | [ResourceStr](ts-types.md#resourcestr) | No| Primary text of the element in the center.
**Text processing rules**: Text will wrap to a new line when it exceeds the length limit.
**Atomic service API**: This API can be used in atomic services since API version 11. | | secondaryText | [ResourceStr](ts-types.md#resourcestr) | No| Secondary text of the element in the center.
**Text processing rules**: Text will wrap to a new line when it exceeds the length limit.
**Atomic service API**: This API can be used in atomic services since API version 11.| | description | [ResourceStr](ts-types.md#resourcestr) | No| Description of the element in the center.
**Text processing rules**: Text will wrap to a new line when it exceeds the length limit.
**Atomic service API**: This API can be used in atomic services since API version 11. | @@ -84,6 +85,7 @@ ComposeListItem({contentItem?: ContentItem, operateItem?: OperateItem}) | checkbox | [OperateCheck](#operatecheck) | No| Check box with a size of 24 x 24 vp.| | radio | [OperateCheck](#operatecheck) | No| Radio button with a size of 24 x 24 vp.| | image | [ResourceStr](ts-types.md#resourcestr) | No| Image with a size of 48 x 48 vp.| +| symbolStyle18+ | [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) | No| Symbol with a size of 48 x 48 vp.
**Atomic service API**: This API can be used in atomic services since API version 18.| | text | [ResourceStr](ts-types.md#resourcestr) | No| Text.| ## OperateIcon @@ -95,10 +97,11 @@ ComposeListItem({contentItem?: ContentItem, operateItem?: OperateItem}) | Name| Type| Mandatory| Description | | -------- | -------- | -------- |------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | value | [ResourceStr](ts-types.md#resourcestr) | Yes| Resource of the icon or arrow on the right. | +| symbolStyle18+ | [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) | No| Resource of the symbol icon or arrow on the right, which has higher priority than **value**.
**Atomic service API**: This API can be used in atomic services since API version 18.| | action | ()=>void | No| Click event of the icon or arrow on the right. | -| accessibilityText16+ | [ResourceStr](ts-types.md#resourcestr) | No| Accessibility text, that is, accessible label name, of the icon or arrow on the right. If a component does not contain text information, it will not be announced by the screen reader when selected. In this case, the screen reader user cannot know which component is selected. To solve this problem, you can set accessibility text for components without text information. When such a component is selected, the screen reader announces the specified accessibility text, informing the user which component is selected.
Default value: **""**
**Atomic service API**: This API can be used in atomic services since API version 16. | -| accessibilityDescription16+ | [ResourceStr](ts-types.md#resourcestr) | No| Accessible description of the icon or arrow on the right. You can provide comprehensive text explanations to help users understand the operation they are about to perform and its potential consequences, especially when these cannot be inferred from the component's attributes and accessibility text alone. If a component contains both text information and the accessible description, the text is announced first and then the accessible description, when the component is selected.
Default value: **"Double-tap to activate"**
**Atomic service API**: This API can be used in atomic services since API version 16. | -| accessibilityLevel16+ | string | No| Accessibility level of the icon or arrow on the right. It determines whether the component can be recognized by accessibility services.
The options are as follows:
**"auto"**: It is treated as "no" by the system.
**"yes"**: The component can be recognized by accessibility services.
**"no"**: The component cannot be recognized by accessibility services.
**"no-hide-descendants"**: Neither the component nor its child components can be recognized by accessibility services.
Default value: **"auto"**
**Atomic service API**: This API can be used in atomic services since API version 16.| +| accessibilityText18+ | [ResourceStr](ts-types.md#resourcestr) | No| Accessibility text, that is, accessible label name, of the icon or arrow on the right. If a component does not contain text information, it will not be announced by the screen reader when selected. In this case, the screen reader user cannot know which component is selected. To solve this problem, you can set accessibility text for components without text information. When such a component is selected, the screen reader announces the specified accessibility text, informing the user which component is selected.
Default value: **""**
**Atomic service API**: This API can be used in atomic services since API version 18. | +| accessibilityDescription18+ | [ResourceStr](ts-types.md#resourcestr) | No| Accessible description of the icon or arrow on the right. You can provide comprehensive text explanations to help users understand the operation they are about to perform and its potential consequences, especially when these cannot be inferred from the component's attributes and accessibility text alone. If a component contains both text information and the accessible description, the text is announced first and then the accessible description, when the component is selected.
Default value: **"Double-tap to activate"**
**Atomic service API**: This API can be used in atomic services since API version 18. | +| accessibilityLevel18+ | string | No| Accessibility level of the icon or arrow on the right. It determines whether the component can be recognized by accessibility services.
The options are as follows:
**"auto"**: It is treated as "no" by the system.
**"yes"**: The component can be recognized by accessibility services.
**"no"**: The component cannot be recognized by accessibility services.
**"no-hide-descendants"**: Neither the component nor its child components can be recognized by accessibility services.
Default value: **"auto"**
**Atomic service API**: This API can be used in atomic services since API version 18.| ## OperateButton @@ -109,9 +112,9 @@ ComposeListItem({contentItem?: ContentItem, operateItem?: OperateItem}) | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | text | [ResourceStr](ts-types.md#resourcestr) | No| Text of the button on the right.| -| accessibilityText16+ | [ResourceStr](ts-types.md#resourcestr) | No| Accessibility text, that is, accessible label name, of the button on the right. If a component does not contain text information, it will not be announced by the screen reader when selected. In this case, the screen reader user cannot know which component is selected. To solve this problem, you can set accessibility text for components without text information. When such a component is selected, the screen reader announces the specified accessibility text, informing the user which component is selected.
**Atomic service API**: This API can be used in atomic services since API version 16. | -| accessibilityDescription16+ | [ResourceStr](ts-types.md#resourcestr) | No| Accessible description of the button on the right. You can provide comprehensive text explanations to help users understand the operation they are about to perform and its potential consequences, especially when these cannot be inferred from the component's attributes and accessibility text alone. If a component contains both text information and the accessible description, the text is announced first and then the accessible description, when the component is selected.
**Atomic service API**: This API can be used in atomic services since API version 16. | -| accessibilityLevel16+ | string | No| Accessibility level of the button on the right. It determines whether the component can be recognized by accessibility services.
The options are as follows:
**"auto"**: It is treated as "no" by the system.
**"yes"**: The component can be recognized by accessibility services.
**"no"**: The component cannot be recognized by accessibility services.
**"no-hide-descendants"**: Neither the component nor its child components can be recognized by accessibility services.
Default value: **"auto"**
**Atomic service API**: This API can be used in atomic services since API version 16.| +| accessibilityText18+ | [ResourceStr](ts-types.md#resourcestr) | No| Accessibility text, that is, accessible label name, of the button on the right. If a component does not contain text information, it will not be announced by the screen reader when selected. In this case, the screen reader user cannot know which component is selected. To solve this problem, you can set accessibility text for components without text information. When such a component is selected, the screen reader announces the specified accessibility text, informing the user which component is selected.
**Atomic service API**: This API can be used in atomic services since API version 18. | +| accessibilityDescription18+ | [ResourceStr](ts-types.md#resourcestr) | No| Accessible description of the button on the right. You can provide comprehensive text explanations to help users understand the operation they are about to perform and its potential consequences, especially when these cannot be inferred from the component's attributes and accessibility text alone. If a component contains both text information and the accessible description, the text is announced first and then the accessible description, when the component is selected.
**Atomic service API**: This API can be used in atomic services since API version 18. | +| accessibilityLevel18+ | string | No| Accessibility level of the button on the right. It determines whether the component can be recognized by accessibility services.
The options are as follows:
**"auto"**: It is treated as "no" by the system.
**"yes"**: The component can be recognized by accessibility services.
**"no"**: The component cannot be recognized by accessibility services.
**"no-hide-descendants"**: Neither the component nor its child components can be recognized by accessibility services.
Default value: **"auto"**
**Atomic service API**: This API can be used in atomic services since API version 18.| ## OperateCheck @@ -123,12 +126,12 @@ ComposeListItem({contentItem?: ContentItem, operateItem?: OperateItem}) | -------- | -------- | -------- |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | isCheck | boolean | No| Whether the switch, check box, or radio button on the right is selected.
Default value: **false**
**true**: selected
**false**: not selected | | onChange | (value: boolean)=>void | No| Callback invoked when the selected state of the switch, check box, or radio button on the right is changed.
**true**: from not selected to selected
**false**: from selected to not selected | -| accessibilityText16+ | [ResourceStr](ts-types.md#resourcestr) | No| Accessibility text, that is, accessible label name, of the switch, check box, or radio button on the right. If a component does not contain text information, it will not be announced by the screen reader when selected. In this case, the screen reader user cannot know which component is selected. To solve this problem, you can set accessibility text for components without text information. When such a component is selected, the screen reader announces the specified accessibility text, informing the user which component is selected.
**Atomic service API**: This API can be used in atomic services since API version 16. | -| accessibilityDescription16+ | [ResourceStr](ts-types.md#resourcestr) | No| Accessible description of the switch, check box, or radio button on the right. You can provide comprehensive text explanations to help users understand the operation they are about to perform and its potential consequences, especially when these cannot be inferred from the component's attributes and accessibility text alone. If a component contains both text information and the accessible description, the text is announced first and then the accessible description, when the component is selected.
By default, the announcement rules for the basic components **Switch**, **CheckBox**, and **Radio** are applied.
**Atomic service API**: This API can be used in atomic services since API version 16.| -| accessibilityLevel16+ | string | No| Accessibility level of the switch, check box, or radio button on the right. It determines whether the component can be recognized by accessibility services.
The options are as follows:
**"auto"**: It is treated as "no" by the system.
**"yes"**: The component can be recognized by accessibility services.
**"no"**: The component cannot be recognized by accessibility services.
**"no-hide-descendants"**: Neither the component nor its child components can be recognized by accessibility services.
Default value: **"auto"**
**Atomic service API**: This API can be used in atomic services since API version 16. | +| accessibilityText18+ | [ResourceStr](ts-types.md#resourcestr) | No| Accessibility text, that is, accessible label name, of the switch, check box, or radio button on the right. If a component does not contain text information, it will not be announced by the screen reader when selected. In this case, the screen reader user cannot know which component is selected. To solve this problem, you can set accessibility text for components without text information. When such a component is selected, the screen reader announces the specified accessibility text, informing the user which component is selected.
**Atomic service API**: This API can be used in atomic services since API version 18. | +| accessibilityDescription18+ | [ResourceStr](ts-types.md#resourcestr) | No| Accessible description of the switch, check box, or radio button on the right. You can provide comprehensive text explanations to help users understand the operation they are about to perform and its potential consequences, especially when these cannot be inferred from the component's attributes and accessibility text alone. If a component contains both text information and the accessible description, the text is announced first and then the accessible description, when the component is selected.
By default, the announcement rules for the basic components **Switch**, **CheckBox**, and **Radio** are applied.
**Atomic service API**: This API can be used in atomic services since API version 18.| +| accessibilityLevel18+ | string | No| Accessibility level of the switch, check box, or radio button on the right. It determines whether the component can be recognized by accessibility services.
The options are as follows:
**"auto"**: It is treated as "no" by the system.
**"yes"**: The component can be recognized by accessibility services.
**"no"**: The component cannot be recognized by accessibility services.
**"no-hide-descendants"**: Neither the component nor its child components can be recognized by accessibility services.
Default value: **"auto"**
**Atomic service API**: This API can be used in atomic services since API version 18. | ## Events -The [universal events](ts-universal-events-click.md) are supported. +The [universal events](ts-component-general-events.md) are not supported. ## Example @@ -149,7 +152,7 @@ struct ComposeListItemExample { contentItem: ({ iconStyle: IconType.NORMAL_ICON, icon: $r('sys.media.ohos_app_icon'), - primaryText: 'Two-line list', + primaryText: 'Double-line list', secondaryText: 'Secondary text', description: 'Description' }), @@ -192,7 +195,7 @@ struct ComposeListItemExample { operateItem: ({ radio: { accessibilityText: 'Radio button', // Screen reader announcement for the radio button. - accessibilityDescription: 'Selected', // Description read by screen reader when the radio button is selected. + accessibilityDescription: 'Unselected', // Description read by screen reader when the radio button is unselected. accessibilityLevel: 'yes' // Configure this element to be focused by accessibility screen readers. } }) @@ -236,7 +239,7 @@ struct ComposeListItemExample { }, accessibilityText: 'This is an icon', // Screen reader announcement for the icon. accessibilityDescription: 'Double-tap to show the toast', // Description read by screen reader for the icon action. - accessibilityLevel: 'yes' // Configure this element to be focused by screen readers. + accessibilityLevel: 'yes' // Configure this element to be focused by screen readers. } }) }) @@ -247,3 +250,76 @@ struct ComposeListItemExample { } ``` ![Implementing screen reader announcement for right-side elements](figures/en-us_image_composelistitem_demo_02.png) + +### Example 3: Setting the Symbol Icon + +This example demonstrates how to use **symbolStyle** in **ContentItem**, **OperateItem**, and **OperateIcon** to set custom symbol icons. + +```ts +import { IconType, ComposeListItem, promptAction, SymbolGlyphModifier } from '@kit.ArkUI'; +@Entry +@Component +struct ComposeListItemExample { + build() { + Column() { + List() { + ListItem() { + ComposeListItem({ + contentItem: ({ + iconStyle: IconType.NORMAL_ICON, + icon: $r('sys.symbol.house'), + primaryText: 'Double-line list', + secondaryText: 'Secondary text', + description: 'Description' + }), + operateItem: ({ + image: $r('sys.symbol.car'), + }) + }) + } + + ListItem() { + ComposeListItem({ + contentItem: ({ + iconStyle: IconType.NORMAL_ICON, + icon: $r('sys.symbol.house'), + symbolStyle: new SymbolGlyphModifier($r('sys.symbol.bell')).fontColor([Color.Red]), + primaryText: 'Double-line list', + secondaryText: 'Secondary text', + description: 'Description' + }), + operateItem: ({ + image: $r('sys.symbol.car'), + symbolStyle: new SymbolGlyphModifier($r('sys.symbol.heart')).fontColor([Color.Pink]), + }) + }) + } + + ListItem() { + ComposeListItem({ + contentItem: ({ + iconStyle: IconType.NORMAL_ICON, + icon: $r('sys.symbol.house'), + symbolStyle: new SymbolGlyphModifier($r('sys.symbol.bell')).fontColor([Color.Blue]), + primaryText: 'Double-line list', + secondaryText: 'Secondary text', + description: 'Description' + }), + operateItem: ({ + icon: { + value: $r('sys.symbol.car'), + symbolStyle: new SymbolGlyphModifier($r('sys.symbol.heart')).fontColor([Color.Orange]), + action: () => { + promptAction.showToast({ message: 'icon' }); + } + } + }) + }) + } + } + } + } +} +``` + +![Setting the symbol icon](figures/en-us_image_composelistitem_demo_03.png) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ComposeTitleBar.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ComposeTitleBar.md index 3df9037f2cb572e1a37a7e49aae488b24929fc9a..7c60c5bcd87083b7480de98e0cb2090987601564 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ComposeTitleBar.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ComposeTitleBar.md @@ -1,7 +1,7 @@ # ComposeTitleBar -A one- or two-row title bar with profile picture is a common title bar that contains a title, subtitle (optional), and profile picture (optional). It can come with a Back button for switching between pages of different levels. +**ComposeTitleBar** represents a common title bar that contains a title, subtitle (optional), and profile picture (optional). It can come with a Back button for switching between pages of different levels. > **NOTE** @@ -21,7 +21,7 @@ import { ComposeTitleBar } from '@kit.ArkUI' Not supported ## Attributes -The [universal attributes](ts-universal-attributes-size.md) are not supported. +The [universal attributes](ts-component-general-attributes.md) are not supported. ## ComposeTitleBar @@ -51,15 +51,20 @@ ComposeTitleBar({item?: ComposeTitleBarMenuItem, title: ResourceStr, subtitle?: | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | [ResourceStr](ts-types.md#resourcestr) | Yes| Icon resource.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| symbolStyle18+ | [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) | No| Symbol icon resource, which has higher priority than **value**.
**Atomic service API**: This API can be used in atomic services since API version 18.| | label13+ | [ResourceStr](ts-types.md#resourcestr) | No| Icon label.
**Atomic service API**: This API can be used in atomic services since API version 13.| | isEnabled | boolean | No| Whether to enable the item.
Default value: **false**
**true**: The item is enabled.
**false**: The item is disabled.
This property cannot be triggered by the **item** property.
**Atomic service API**: This API can be used in atomic services since API version 11.| | action | () => void | No| Action to perform. This parameter is not available for the item attribute.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| accessibilityLevel18+ | string | No| Accessibility level. It determines whether the component can be recognized by accessibility services.
The options are as follows:
**"auto"**: It is treated as "yes" by the system.
**"yes"**: The component can be recognized by accessibility services.
**"no"**: The component cannot be recognized by accessibility services.
**"no-hide-descendants"**: Neither the component nor its child components can be recognized by accessibility services.
Default value: **"auto"**
**Atomic service API**: This API can be used in atomic services since API version 18.| +| accessibilityText18+ | ResourceStr | No| Accessibility text, that is, accessible label name. If a component does not contain text information, it will not be announced by the screen reader when selected. In this case, the screen reader user cannot know which component is selected. To solve this problem, you can set accessibility text for components without text information. When such a component is selected, the screen reader announces the specified accessibility text, informing the user which component is selected.
Default value: value of the **label** property if it is set and an empty string otherwise.
**Atomic service API**: This API can be used in atomic services since API version 18. | +| accessibilityDescription18+ | ResourceStr | No| Accessible description. You can provide comprehensive text explanations to help users understand the operation they are about to perform and its potential consequences, especially when these cannot be inferred from the component's attributes and accessibility text alone. If a component contains both text information and the accessible description, the text is announced first and then the accessible description, when the component is selected.
Default value: **"Double-tap to activate"**
**Atomic service API**: This API can be used in atomic services since API version 18. | ## Events -The [universal events](ts-universal-events-click.md) are not supported. +The [universal events](ts-component-general-events.md) are not supported. ## Example +### Example 1: Implementing a Simple Title Bar This example showcases how to implement a simple title bar, a title bar with a back arrow, and a title bar with a list of menu items on the right side. ```ts import { ComposeTitleBar, promptAction, ComposeTitleBarMenuItem } from '@kit.ArkUI' @@ -71,24 +76,24 @@ struct Index { private menuItems: Array = [ { // Resource for the menu icon - value: $r('app.media.ic_public_save'), + value: $r('sys.media.ohos_save_button_filled'), // Enable the icon. isEnabled: true, // Action triggered when the menu item is clicked. action: () => promptAction.showToast({ message: "show toast index 1" }) }, { - value: $r('app.media.ic_public_reduce'), + value: $r('sys.media.ohos_ic_public_copy'), isEnabled: true, action: () => promptAction.showToast({ message: "show toast index 1" }) }, { - value: $r('app.media.ic_public_edit'), + value: $r('sys.media.ohos_ic_public_edit'), isEnabled: true, action: () => promptAction.showToast({ message: "show toast index 1" }) }, { - value: $r('app.media.ic_public_remove'), + value: $r('sys.media.ohos_ic_public_remove'), isEnabled: true, action: () => promptAction.showToast({ message: "show toast index 1" }) }, @@ -119,12 +124,12 @@ struct Index { Divider().height(2).color(0xCCCCCC) // Define the title bar with a profile picture. ComposeTitleBar({ - menuItems: [{ isEnabled: true, value: $r('app.media.ic_public_save'), + menuItems: [{ isEnabled: true, value: $r('sys.media.ohos_save_button_filled'), action: () => promptAction.showToast({ message: "show toast index 1" }) }], title: "Title", subtitle: "Subtitle", - item: { isEnabled: true, value: $r('app.media.app_icon') } + item: { isEnabled: true, value: $r('sys.media.ohos_app_icon') } }) Divider().height(2).color(0xCCCCCC) } @@ -133,4 +138,177 @@ struct Index { } ``` -![en-us_image_0000001616913438](figures/en-us_image_0000001616913438.jpg) +![en-us_image_composetitlebar_example01](figures/en-us_image_composetitlebar_example01.png) + +### Example 2: Implementing Screen Reader Announcement for the Custom Button on the Right Side +This example customizes the screen reader announcement text by setting the **accessibilityText**, **accessibilityDescription**, and **accessibilityLevel** properties of the custom button on the right side of the title bar. +```ts +import { ComposeTitleBar, promptAction, ComposeTitleBarMenuItem } from '@kit.ArkUI' + +@Entry +@Component +struct Index { + // Define an array of menu items for the right side of the title bar. + private menuItems: Array = [ + { + // Resource for the menu icon + value: $r('sys.media.ohos_save_button_filled'), + // Enable the icon. + isEnabled: true, + // Action triggered when the menu item is clicked. + action: () => promptAction.showToast({ message: "show toast index 1" }), + // The screen reader will prioritize this text over the label. + accessibilityText: 'Save', + // The screen reader can focus on this item. + accessibilityLevel: 'yes', + // The screen reader will ultimately announce this text. + accessibilityDescription: 'Tap to save the icon' + }, + { + value: $r('sys.media.ohos_ic_public_copy'), + isEnabled: true, + action: () => promptAction.showToast({ message: "show toast index 1" }), + accessibilityText: 'Copy', + // The screen reader will not focus on this item. + accessibilityLevel: 'no', + accessibilityDescription: 'Tap to copy the icon' + }, + { + value: $r('sys.media.ohos_ic_public_edit'), + isEnabled: true, + action: () => promptAction.showToast({ message: "show toast index 1" }), + accessibilityText: 'Edit', + accessibilityLevel: 'yes', + accessibilityDescription: 'Tap to edit the icon' + }, + { + value: $r('sys.media.ohos_ic_public_remove'), + isEnabled: true, + action: () => promptAction.showToast({ message: "show toast index 1" }), + accessibilityText: 'Remove', + accessibilityLevel: 'yes', + accessibilityDescription: 'Tap to remove the icon' + }, + ] + + build() { + Row() { + Column() { + // Divider. + Divider().height(2).color(0xCCCCCC) + ComposeTitleBar({ + title: "Title", + subtitle: "Subtitle", + menuItems: this.menuItems.slice(0, 1), + }) + Divider().height(2).color(0xCCCCCC) + ComposeTitleBar({ + title: "Title", + subtitle: "Subtitle", + menuItems: this.menuItems.slice(0, 2), + }) + Divider().height(2).color(0xCCCCCC) + ComposeTitleBar({ + title: "Title", + subtitle: "Subtitle", + menuItems: this.menuItems, + }) + Divider().height(2).color(0xCCCCCC) + // Define the title bar with a profile picture. + ComposeTitleBar({ + menuItems: [{ isEnabled: true, value: $r('sys.media.ohos_save_button_filled'), + action: () => promptAction.showToast({ message: "show toast index 1" }) + }], + title: "Title", + subtitle: "Subtitle", + item: { isEnabled: true, value: $r('sys.media.ohos_app_icon') } + }) + Divider().height(2).color(0xCCCCCC) + } + }.height('100%') + } +} +``` + +![en-us_image_composetitlebar_example02](figures/en-us_image_composetitlebar_example02.png) + +### Example 3: Setting the Symbol Icon + +This example demonstrates how to use **symbolStyle** in **ComposeTitleBarMenuItem** to set custom symbol icons. + +```ts +import { ComposeTitleBar, promptAction, ComposeTitleBarMenuItem, SymbolGlyphModifier } from '@kit.ArkUI' + +@Entry +@Component +struct Index { + // Define an array of menu items for the right side of the title bar. + private menuItems: Array = [ + { + // Resource for the menu icon + value: $r('sys.symbol.house'), + // Menu symbol icon + symbolStyle: new SymbolGlyphModifier($r('sys.symbol.bell')).fontColor([Color.Red]), + // Enable the icon. + isEnabled: true, + // Action triggered when the menu item is clicked. + action: () => promptAction.showToast({ message: "show toast index 1" }) + }, + { + value: $r('sys.symbol.house'), + isEnabled: true, + action: () => promptAction.showToast({ message: "show toast index 1" }) + }, + { + value: $r('sys.symbol.car'), + symbolStyle: new SymbolGlyphModifier($r('sys.symbol.heart')).fontColor([Color.Pink]), + isEnabled: true, + action: () => promptAction.showToast({ message: "show toast index 1" }) + }, + { + value: $r('sys.symbol.car'), + isEnabled: true, + action: () => promptAction.showToast({ message: "show toast index 1" }) + }, + ] + + build() { + Row() { + Column() { + // Divider. + Divider().height(2).color(0xCCCCCC) + ComposeTitleBar({ + title: "Title", + subtitle: "Subtitle", + menuItems: this.menuItems.slice(0, 1), + }) + Divider().height(2).color(0xCCCCCC) + ComposeTitleBar({ + title: "Title", + subtitle: "Subtitle", + menuItems: this.menuItems.slice(0, 2), + }) + Divider().height(2).color(0xCCCCCC) + ComposeTitleBar({ + title: "Title", + subtitle: "Subtitle", + menuItems: this.menuItems, + }) + Divider().height(2).color(0xCCCCCC) + // Define the title bar with a profile picture. + ComposeTitleBar({ + menuItems: [{ isEnabled: true, value: $r('sys.symbol.heart'), + action: () => promptAction.showToast({ message: "show toast index 1" }) + }], + title: "Title", + subtitle: "Subtitle", + item: { isEnabled: true, value: $r('sys.media.ohos_app_icon') } + }) + Divider().height(2).color(0xCCCCCC) + } + }.height('100%') + } +} +``` + +![Setting the symbol icon](figures/en-us_image_composetitlebar_demo_03.png) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-Counter.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-Counter.md index d0cc60bd5419e6faebb883b097c8251ed45a465a..d5be979bb9f65fce6f4d996f55987e5938923600 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-Counter.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-Counter.md @@ -85,10 +85,10 @@ Defines common attributes and events of counters. | Name | Type | Mandatory| Description | | --------------- | ------------------------- | ---- | ------------------------------------------------------------ | -| focusable | boolean | No | Whether the counter is focusable.
**NOTE**
This attribute takes effect for the number style counter.
Default value: **true**| +| focusable | boolean | No | Whether the counter is focusable.
**NOTE**
This attribute takes effect for the number style counter.
Default value: **true**
**true**: The counter is focusable.
**false**: The counter is not focusable.| | step | number | No | Step of the counter.
Value range: an integer greater than or equal to 1.
Default value: **1**| -| onHoverIncrease | (isHover: boolean) =>void | No | Callback invoked when the mouse pointer is moved over or away from the Increase button of the counter.
**isHover**: whether the mouse pointer hovers over the component. The value **true** means that the mouse pointer enters the component, and the value **false** means that the mouse pointer leaves the component.| -| onHoverDecrease | (isHover: boolean) =>void | No | Callback invoked when the mouse pointer is moved over or away from the Decrease button of the counter.
**isHover**: whether the mouse pointer hovers over the component. The value **true** means that the mouse pointer enters the component, and the value **false** means that the mouse pointer leaves the component.| +| onHoverIncrease | (isHover: boolean) =>void | No | Callback invoked when the mouse pointer is moved over or away from the increase button of the counter.
**isHover**: whether the mouse pointer hovers over the component. The value **true** means that the mouse pointer enters the component, and the value **false** means that the mouse pointer leaves the component.| +| onHoverDecrease | (isHover: boolean) =>void | No | Callback invoked when the mouse pointer is moved over or away from the decrease button of the counter.
**isHover**: whether the mouse pointer hovers over the component. The value **true** means that the mouse pointer enters the component, and the value **false** means that the mouse pointer leaves the component.| ## InlineStyleOptions @@ -121,10 +121,10 @@ Inherits from [InlineStyleOptions](#inlinestyleoptions). | Name | Type | Mandatory| Description | | --------------- | -------------------------------------- | ---- | --------------------------------------------- | | label | [ResourceStr](ts-types.md#resourcestr) | No | Label of the counter. | -| onFocusIncrease | () =>void | No | Callback invoked when the Increase button of the counter gains focus.| -| onFocusDecrease | () =>void | No | Callback invoked when the Decrease button of the counter gains focus.| -| onBlurIncrease | () =>void | No | Callback invoked when the Increase button of the counter loses focus.| -| onBlurDecrease | () =>void | No | Callback invoked when the Decrease button of the counter loses focus.| +| onFocusIncrease | () =>void | No | Callback invoked when the increase button of the counter gains focus.| +| onFocusDecrease | () =>void | No | Callback invoked when the decrease button of the counter gains focus.| +| onBlurIncrease | () =>void | No | Callback invoked when the increase button of the counter loses focus.| +| onBlurDecrease | () =>void | No | Callback invoked when the decrease button of the counter loses focus.| ## DateStyleOptions diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-Dialog.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-Dialog.md index 21c5073c119bf1748ea0aa432b257ddd01aace3d..ab8f22dc77888f7835a4ff534caa31d5df162485 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-Dialog.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-Dialog.md @@ -22,7 +22,7 @@ Not supported ## Attributes -The [universal attributes](ts-universal-attributes-size.md) are not supported. +The [universal attributes](ts-component-general-attributes.md) are not supported. ## TipsDialog @@ -64,16 +64,16 @@ Displays a dialog box from which the user can select options presented in a list **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory| Description | -| ------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| controller | [CustomDialogController](ts-methods-custom-dialog-box.md#customdialogcontroller) | Yes| Dialog box controller.
**NOTE**
If not decorated by @Require, this parameter is not subject to mandatory validation during construction.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| title | [ResourceStr](ts-types.md#resourcestr) | Yes | Title of the dialog box.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| content | [ResourceStr](ts-types.md#resourcestr) | No | Content of the dialog box.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| selectedIndex | number | No | Index of the selected option in the dialog box.
Default value: **-1**
**Atomic service API**: This API can be used in atomic services since API version 11.| -| confirm | [ButtonOptions](#buttonoptions) | No | Button at the bottom of the dialog box.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| radioContent | Array<[SheetInfo](ts-methods-action-sheet.md#sheetinfo)> | Yes | List of subitems in the dialog box. You can set text and a select callback for each subitem.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| theme12+ | [Theme](../js-apis-arkui-theme.md#theme) \| [CustomTheme](../js-apis-arkui-theme.md#customtheme) | No | Theme information, which can be a custom theme or a **Theme** instance obtained from **onWillApplyTheme**.
**Atomic service API**: This API can be used in atomic services since API version 12.| -| themeColorMode12+ | [ThemeColorMode](ts-container-with-theme.md#themecolormode10) | No| Theme color mode of the dialog box.
**Atomic service API**: This API can be used in atomic services since API version 12. | +| Name | Type | Mandatory| Description | +| ------------------- | ------------------------------------------------------------ | ---- |-------------------------------------------------------------------------------------------------------------------------| +| controller | [CustomDialogController](ts-methods-custom-dialog-box.md#customdialogcontroller) | Yes| Dialog box controller.
**NOTE**
If not decorated by @Require, this parameter is not subject to mandatory validation during construction.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| title | [ResourceStr](ts-types.md#resourcestr) | Yes | Title of the dialog box.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| content | [ResourceStr](ts-types.md#resourcestr) | No | Content of the dialog box.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| selectedIndex | number | No | Index of the selected option in the dialog box.
Value range: an integer no less than -1
The default value is **-1**, indicating that there is no selected option. Values less than -1 are treated as no selected option.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| confirm | [ButtonOptions](#buttonoptions) | No | Button at the bottom of the dialog box.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| radioContent | Array<[SheetInfo](ts-methods-action-sheet.md#sheetinfo)> | Yes | List of subitems in the dialog box. You can set text and a select callback for each subitem.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| theme12+ | [Theme](../js-apis-arkui-theme.md#theme) \| [CustomTheme](../js-apis-arkui-theme.md#customtheme) | No | Theme information, which can be a custom theme or a **Theme** instance obtained from **onWillApplyTheme**.
**Atomic service API**: This API can be used in atomic services since API version 12. | +| themeColorMode12+ | [ThemeColorMode](ts-container-with-theme.md#themecolormode10) | No| Theme color mode of the dialog box.
**Atomic service API**: This API can be used in atomic services since API version 12. | ## ConfirmDialog @@ -195,7 +195,7 @@ Displays a popover dialog box that is positioned relative to the target componen | fontColor | [ResourceColor](ts-types.md#resourcecolor) | No | Font color of the button.
**Atomic service API**: This API can be used in atomic services since API version 11.| | buttonStyle12+ | [ButtonStyleMode](ts-basic-components-button.md#buttonstylemode11) | No | Style of the button.
Default value: **ButtonStyleMode.NORMAL** for 2-in-1 devices and **ButtonStyleMode.TEXTUAL** for other devices
**Atomic service API**: This API can be used in atomic services since API version 12.| | role12+ | [ButtonRole](ts-basic-components-button.md#buttonrole12) | No | Role of the button.
Default value: **ButtonRole.NORMAL**
**Atomic service API**: This API can be used in atomic services since API version 12. | -| defaultFocus16+ | boolean | No | Whether the button gains focus by default.
Default value: **false**
**Atomic service API**: This API can be used in atomic services since API version 16. | +| defaultFocus18+ | boolean | No | Whether the button gains focus by default.
Default value: **false**
**Atomic service API**: This API can be used in atomic services since API version 18. | > **NOTE** > @@ -218,7 +218,7 @@ Inherits [CustomPopupOptions](../arkui-ts/ts-universal-attributes-popup.md#custo ## Events -The [universal events](ts-universal-events-click.md) are not supported. +The [universal events](ts-component-general-events.md) are not supported. ## Example @@ -227,13 +227,10 @@ This example implements a dialog box with an image above the text content, throu ```ts import { TipsDialog } from '@kit.ArkUI'; -import { image } from '@kit.ImageKit'; @Entry @Component struct Index { - @State pixelMap: PixelMap | undefined = undefined; - isChecked = false; dialogControllerImage: CustomDialogController = new CustomDialogController({ builder: TipsDialog({ imageRes: $r('sys.media.ohos_ic_public_voice'), @@ -274,24 +271,6 @@ struct Index { .backgroundImageSize({ width: '100%', height: '100%' }) .height('100%') } - - aboutToAppear(): void { - this.getPixmapFromMedia($r('app.media.app_icon')); - } - - async getPixmapFromMedia(resource: Resource) { - let unit8Array = await getContext(this)?.resourceManager?.getMediaContent({ - bundleName: resource.bundleName, - moduleName: resource.moduleName, - id: resource.id - }) - let imageSource = image.createImageSource(unit8Array.buffer.slice(0, unit8Array.buffer.byteLength)) - this.pixelMap = await imageSource.createPixelMap({ - desiredPixelFormat: image.PixelMapFormat.RGBA_8888 - }) - await imageSource.release() - return this.pixelMap; - } } ``` @@ -306,6 +285,7 @@ import { SelectDialog } from '@kit.ArkUI' @Entry @Component struct Index { + // Set the index of the default selected option. radioIndex = 0; dialogControllerList: CustomDialogController = new CustomDialogController({ builder: SelectDialog({ @@ -349,8 +329,10 @@ struct Index { this.dialogControllerList.open() }) }.margin({ bottom: 300 }) - }.align(Alignment.Bottom) - .width('100%').height('100%') + } + .align(Alignment.Bottom) + .width('100%') + .height('100%') } .backgroundImageSize({ width: '100%', height: '100%' }) .height('100%') @@ -374,7 +356,9 @@ struct Index { builder: ConfirmDialog({ title:'Title', content: 'This is where content is displayed. This is where content is displayed.', + // Selected state of the check box isChecked: this.isChecked, + // Content of the check box checkTips: 'Don't ask again after denying', primaryButton: { value: 'Deny', @@ -405,9 +389,12 @@ struct Index { .onClick(() => { this.dialogControllerCheckBox.open() }) - }.margin({bottom: 300}) - }.align(Alignment.Bottom) - .width('100%').height('100%') + } + .margin({bottom: 300}) + } + .align(Alignment.Bottom) + .width('100%') + .height('100%') } .backgroundImageSize({ width: '100%', height: '100%' }) .height('100%') @@ -456,9 +443,12 @@ struct Index { .onClick(() => { this.dialogControllerConfirm.open() }) - }.margin({ bottom: 300 }) - }.align(Alignment.Bottom) - .width('100%').height('100%') + } + .margin({ bottom: 300 }) + } + .align(Alignment.Bottom) + .width('100%') + .height('100%') } .backgroundImageSize({ width: '100%', height: '100%' }) .height('100%') @@ -493,9 +483,12 @@ struct Index { .onClick(() => { this.dialogControllerProgress.open() }) - }.margin({ bottom: 300 }) - }.align(Alignment.Bottom) - .width('100%').height('100%') + } + .margin({ bottom: 300 }) + } + .align(Alignment.Bottom) + .width('100%') + .height('100%') } .backgroundImageSize({ width: '100%', height: '100%' }) .height('100%') @@ -503,7 +496,7 @@ struct Index { } ``` -![LoadingDialog](figures/LoadingDialog.png) +![LoadingDialog](figures/LoadingDialog.gif) ### Example 6: Dialog Box with a Custom Theme This example presents a dialog box with a custom theme, through the use of **content**, **theme**, and other properties. @@ -519,6 +512,7 @@ class CustomThemeImpl implements CustomTheme { } } +// Custom text content and colors for the dialog box theme class CustomThemeColors implements CustomColors { fontPrimary = '#ffd0a300'; iconSecondary = '#ffd000cd'; @@ -545,9 +539,12 @@ struct Index { .onClick(() => { this.dialogController.open(); }) - }.margin({ bottom: 300 }) - }.align(Alignment.Bottom) - .width('100%').height('100%') + } + .margin({ bottom: 300 }) + } + .align(Alignment.Bottom) + .width('100%') + .height('100%') } .backgroundImageSize({ width: '100%', height: '100%' }) .height('100%') @@ -583,9 +580,12 @@ struct Index { .onClick(() => { this.dialogController.open(); }) - }.margin({ bottom: 300 }) - }.align(Alignment.Bottom) - .width('100%').height('100%') + } + .margin({ bottom: 300 }) + } + .align(Alignment.Bottom) + .width('100%') + .height('100%') } .backgroundImageSize({ width: '100%', height: '100%' }) .height('100%') @@ -611,9 +611,20 @@ struct Index { contentBuilder: () => { this.buildContent(); }, - buttons: [{ value: 'Button 1', buttonStyle: ButtonStyleMode.TEXTUAL, action: () => { - console.info('Callback when the button is clicked') - } }, { value: 'Button 2', buttonStyle: ButtonStyleMode.TEXTUAL, role: ButtonRole.ERROR }], + buttons: [ + { + value: 'Button 1', + buttonStyle: ButtonStyleMode.TEXTUAL, + action: () => { + console.info('Callback when the button is clicked') + } + }, + { + value: 'Button 2', + buttonStyle: ButtonStyleMode.TEXTUAL, + role: ButtonRole.ERROR + } + ], }), }); @@ -628,12 +639,14 @@ struct Index { .height('100%') .justifyContent(FlexAlign.Center) } - + + // Custom content area of the dialog box @Builder buildContent(): void { Column() { Text('Content area') } + .width('100%') } } ``` @@ -653,9 +666,11 @@ struct Index { @State popoverOptions: PopoverOptions = { builder: () => { this.dialogBuilder(); - } + }, + width: 320, } - + + // Content of the popover dialog box @Builder dialogBuilder() { AlertDialog({ content: 'Popover dialog box', @@ -673,9 +688,11 @@ struct Index { }, }); } - + + // Builder for the button that triggers the popover dialog box @Builder buttonBuilder() { - Button('Target Component').onClick(() => { + Button('Target Component') + .onClick(() => { this.isShow = true; }); } @@ -732,9 +749,12 @@ struct Index { .onClick(() => { this.dialogController.open() }) - }.margin({ bottom: 300 }) - }.align(Alignment.Bottom) - .width('100%').height('100%') + } + .margin({ bottom: 300 }) + } + .align(Alignment.Bottom) + .width('100%') + .height('100%') } .backgroundImageSize({ width: '100%', height: '100%' }) .height('100%') diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-DialogV2.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-DialogV2.md new file mode 100644 index 0000000000000000000000000000000000000000..f4d4e5c445de48f334b26a41a358f07ced9bd7f4 --- /dev/null +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-DialogV2.md @@ -0,0 +1,747 @@ +# DialogV2 + +The dialog box is a modal window that commands attention while retaining the current context. It is frequently used to draw the user's attention to vital information or prompt the user to complete a specific task. As all modal windows, this component requires the user to interact before exiting. + +This component is implemented based on [state management V2](../../../quick-start/arkts-state-management-overview.md#state-management-v2). Compared with [state management V1](../../../quick-start/arkts-state-management-overview.md#state-management-v1), V2 offers a higher level of observation and management over data objects beyond the component level. You can now more easily manage dialog box data and states with greater flexibility, leading to faster UI updates. + +> **NOTE** +> +> This component is supported since API version 18. Updates will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + + import { TipsDialogV2, SelectDialogV2, ConfirmDialogV2, AlertDialogV2, LoadingDialogV2, CustomContentDialogV2, PopoverDialogV2 } from '@kit.ArkUI'; + +## Child Components + +Not supported + +## TipsDialogV2 + +TipsDialogV2({imageRes: ResourceStr, imageSize?: SizeOptions, imageBorderColor: ColorMetrics, imageBorderWidth: LengthMetrics, title?: ResourceStr, content?: ResourceStr, checkTips?: ResourceStr, checked?: boolean, onCheckedChange?: AdvancedDialogV2OnCheckedChange, primaryButton?: AdvancedDialogV2Button, secondaryButton?: AdvancedDialogV2Button}) + +Displays an image-attached confirmation dialog box. + +**Decorator**: @ComponentV2 + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Decorator | Description | +|------------------|-------------------------------------------------------------------------------------------------------|----|----------------------|--------------------------------------------------------------------| +| imageRes | [ResourceStr](ts-types.md#resourcestr) \| [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) | Yes | @Param
@Require | Image to be displayed. | +| imageSize | [SizeOptions](ts-types.md#sizeoptions) | No | @Param | Size of the image.
Default value: **64\*64vp** | +| imageBorderColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | No | @Param | Stroke color of the image.
Default value: **Color.Black** | +| imageBorderWidth | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | No | @Param | Stroke width of the image.
By default, there is no stroke effect. | +| title | [ResourceStr](ts-types.md#resourcestr) | No | @Param | Title of the dialog box.
It is not displayed by default. | +| content | [ResourceStr](ts-types.md#resourcestr) | No | @Param | Content of the dialog box.
It is not displayed by default. | +| checkTips | [ResourceStr](ts-types.md#resourcestr) | No | @Param | Content of the check box.
It is not displayed by default. | +| checked | boolean | No | @Param | Whether to select the check box. The value **true** means to select the check box, and **false** means the opposite.
Default value: **false**| +| onCheckedChange | [AdvancedDialogV2OnCheckedChange](#advanceddialogv2oncheckedchange) | No | @Param | Event triggered when the selected status of the check box changes.
By default, there is no event. | +| primaryButton | [AdvancedDialogV2Button](#advanceddialogv2button) | No | @Param | Left button of the dialog box.
It is not displayed by default. | +| secondaryButton | [AdvancedDialogV2Button](#advanceddialogv2button) | No | @Param | Right button of the dialog box.
It is not displayed by default. | + +## AdvancedDialogV2OnCheckedChange + +type AdvancedDialogV2OnCheckedChange = (checked: boolean) => void + +Defines the event triggered when the selected status of the check box changes. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Description | +| :------ |:--------| :- | :-------------------------------------------------- | +| checked | boolean | Yes | Whether to select the check box.
| + +## SelectDialogV2 + +SelectDialogV2({title: ResourceStr, content?: ResourceStr, selectedIndex?: number, confirm?: AdvancedDialogV2Button, radioContent: SheetInfo\[]}) + +Displays a dialog box from which the user can select items presented in a list or grid. + +**Decorator**: @ComponentV2 + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Decorator | Description | +| ------------- | -------------------------------------------------------- | -- |---------------------|-----------------------------------------------------| +| title | [ResourceStr](ts-types.md#resourcestr) | Yes | @Param
@Require | Title of the dialog box. | +| content | [ResourceStr](ts-types.md#resourcestr) | No | @Param | Content of the dialog box. It is not displayed by default. | +| selectedIndex | number | No | @Param | Index of the selected item in the dialog box.
Default value: **-1**
Value range: less than the length of the length of **radioContent**| +| confirm | [AdvancedDialogV2Button](#advanceddialogv2button) | No | @Param | Button at the bottom of the dialog box.
It is not displayed by default. | +| radioContent | [SheetInfo](ts-methods-action-sheet.md#sheetinfo)\[] | Yes | @Param
@Require | List of items displayed in the dialog box. You can set text and a selection callback for each item. | + +## ConfirmDialogV2 + +ConfirmDialogV2({title: ResourceStr, content?: ResourceStr, checkTips?: ResourceStr, ischecked?: boolean, onCheckedChange: AdvancedDialogV2OnCheckedChange, primaryButton?: AdvancedDialogV2Button, secondaryButton?: AdvancedDialogV2Button}) + +Displays an error dialog box that informs the user of an operational error (for example, a network error or low battery level) or an incorrect operation (for example, fingerprint enrollment). + +**Decorator**: @ComponentV2 + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Decorator | Description | +|-----------------| ------------------------------------------------------------------- | -- | ------ |------------------------------------------------------------| +| title | [ResourceStr](ts-types.md#resourcestr) | Yes | @Param
@Require | Title of the dialog box. | +| content | [ResourceStr](ts-types.md#resourcestr) | No | @Param | Content of the dialog box.
It is not displayed by default. | +| checkTips | [ResourceStr](ts-types.md#resourcestr) | No | @Param | Content of the check box.
It is not displayed by default. | +| checked | boolean | No | @Param | Whether to select the check box. The value **true** means to select the check box, and **false** means the opposite.
Default value: **false**| +| onCheckedChange | [AdvancedDialogV2OnCheckedChange](#advanceddialogv2oncheckedchange) | No | @Param | Event triggered when the selected status of the check box changes.
By default, there is no event. | +| primaryButton | [AdvancedDialogV2Button](#advanceddialogv2button) | No | @Param | Left button of the dialog box.
It is not displayed by default. | +| secondaryButton | [AdvancedDialogV2Button](#advanceddialogv2button) | No | @Param | Right button of the dialog box.
It is not displayed by default. | + +## AlertDialogV2 + +AlertDialogV2({primaryTitle?: ResourceStr, secondaryTitle?: ResourceStr, content: ResourceStr, primaryButton?: AdvancedDialogV2Button, secondaryButton?: AdvancedDialogV2Button}) + +Displays an alert dialog box to prompt the user to confirm an action that is irreversible and may cause serious consequences, such as deletion, reset, editing cancellation, and stop. + +**Decorator**: @ComponentV2 + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Decorator | Description | +| --------------- | ------------------------------------------------- | -- | :------------------- | -------------------- | +| primaryTitle | [ResourceStr](ts-types.md#resourcestr) | No | @Param | Primary title of the dialog box.
It is not displayed by default. | +| secondaryTitle | [ResourceStr](ts-types.md#resourcestr) | No | @Param | Secondary title of the dialog box.
It is not displayed by default. | +| content | [ResourceStr](ts-types.md#resourcestr) | Yes | @Param
@Require | Content of the dialog box.
| +| primaryButton | [AdvancedDialogV2Button](#advanceddialogv2button) | No | @Param | Left button of the dialog box.
It is not displayed by default.| +| secondaryButton | [AdvancedDialogV2Button](#advanceddialogv2button) | No | @Param | Right button of the dialog box.
It is not displayed by default.| + +## LoadingDialogV2 + +LoadingDialogV2({content?: ResourceStr}) + +Displays a loading dialog box to inform the user of the operation progress. + +**Decorator**: @ComponentV2 + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Decorator | Description | +| ------- | -------------------------------------- | -- | :----- |---------------------| +| content | [ResourceStr](ts-types.md#resourcestr) | No | @Param | Content of the dialog box.
It is empty by default.| + +## CustomContentDialogV2 + +CustomContentDialogV2({contentBuilder: () => void, primaryTitle?: ResourceStr, secondaryTitle?: ResourceStr, contentAreaPadding?: LocalizedPadding, buttons?: AdvancedDialogV2Button\[]}) + +Displays a dialog box that contains custom content and operation area. + +**Decorator**: @ComponentV2 + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Decorator | Description | +| ------------------ | ---------------------------------------------------- | -- | ------------- | ------------------------ | +| contentBuilder | [CustomBuilder](ts-types.md#custombuilder8) | Yes | @BuilderParam | Content of the dialog box. | +| primaryTitle | [ResourceStr](ts-types.md#resourcestr) | No | @Param | Primary title of the dialog box.
It is not displayed by default. | +| secondaryTitle | [ResourceStr](ts-types.md#resourcestr) | No | @Param | Secondary title of the dialog box.
It is not displayed by default. | +| contentAreaPadding | [LocalizedPadding](ts-types.md#localizedpadding12) | No | @Param | Padding of the content area of the dialog box.
It is not displayed by default. | +| buttons | [AdvancedDialogV2Button](#advanceddialogv2button)\[] | No | @Param | Buttons in the operation area of the dialog box. A maximum of four buttons are allowed.
It is not displayed by default.| + +## PopoverDialogV2OnVisibleChange + +type PopoverDialogV2OnVisibleChange = (visible: boolean) => void + +Defines the event triggered when the visibility of the popover dialog box changes. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Description | +| :------ | :------ | :- |:-----------------------------------------------------------------------| +| visible | boolean | Yes | Visibility of the popover dialog box.
**true**: The popover dialog box is displayed.
**false**: The popover dialog box is hidden.| + +## PopoverDialogV2 + +PopoverDialogV2({visible: boolean, \$visible: PopoverDialogV2OnVisibleChange, popover: PopoverDialogV2Options, targetBuilder: CustomBuilder}) + +Displays a popover dialog box that is positioned relative to the target component. This dialog box can contain a variety of content types, including: TipsDialogV2, SelectDialogV2, ConfirmDialogV2, AlertDialogV2, LoadingDialogV2, and CustomContentDialogV2. + +**Decorator**: @ComponentV2 + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Decorator | Description | +| ------------- |-------------------------------------------------------------------| -- |---------------------| -------------------------------------------------- | +| visible | boolean | Yes | @Param
@Require | Whether the popover dialog box is visible. | +| \$visible | [PopoverDialogV2OnVisibleChange](#popoverdialogv2onvisiblechange) | No | @Event | Callback invoked when the visibility of the dialog box changes. Use the **!!** syntax for two-way binding with **visible**.
By default, there is no callback.| +| popover | [PopoverDialogV2Options](#popoverdialogv2options) | Yes | @Param
@Require | Options of the popover dialog box. | +| targetBuilder | [CustomBuilder](ts-types.md#custombuilder8) | Yes | @BuilderParam | Target component relative to which the popover dialog box is positioned. | + +## PopoverDialogV2Options + +Defines a set of options used to configure the popover dialog box, including its content and position. + +Inherits [CustomPopupOptions](../arkui-ts/ts-universal-attributes-popup.md#custompopupoptions8). + +> **NOTE** +> +> The default value of **radius** is **32vp**. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +## AdvancedDialogV2ButtonAction + +type AdvancedDialogV2ButtonAction = () => void + +Defines the event triggered when a button in the popover dialog is clicked. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +## AdvancedDialogV2Button + +Defines the button used in a dialog box to perform actions. + +**Decorator type**: @ObservedV2 + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Decorator | Description | +|:-------------|:-----------------------------------------------------------------------|:---|:-------|:----------------------------------------------------------------------------| +| content | [ResourceStr](ts-types.md#resourcestr) | Yes | @Trace | Content of the button. | +| action | [AdvancedDialogV2ButtonAction](#advanceddialogv2buttonaction) | No | @Trace | Action triggered when the button is clicked.
By default, there is no action. | +| background | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | No | @Trace | Background of the button.
The setting follows **buttonStyle** by default. | +| fontColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | No | @Trace | Font color of the button.
The setting follows **buttonStyle** by default. | +| buttonStyle | [ButtonStyleMode](ts-basic-components-button.md#buttonstylemode11) | No | @Trace | Style of the button.
Default value: **ButtonStyleMode.NORMAL** for 2-in-1 devices and **ButtonStyleMode.TEXTUAL** for other devices| +| role | [ButtonRole](ts-basic-components-button.md#buttonrole12) | No | @Trace | Role of the button.
Default value: **ButtonRole.NORMAL** | +| defaultFocus | boolean | No | @Trace | Whether the button is the default focus.
Default value: **false** | +| enabled | boolean | No | @Trace | Whether the button is enabled.
Default value: **true** | + +> **NOTE** +> +> The priority of **buttonStyle** and **role** is higher than that of **fontColor** and **background**. If **buttonStyle** and **role** are at the default values, the settings of **fontColor** and **background** take effect. +> +> If **defaultFocus** is set for multiple buttons, the default focus is the first button in the display order that has **defaultFocus** set to **true**. + +### constructor + +constructor(options: AdvancedDialogV2ButtonOptions) + +A constructor used to create an **AdvancedDialogV2Button** instance. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Description | +| :------ | :-------------------------------------------------------------- | :- | :------ | +| options | [AdvancedDialogV2ButtonOptions](#advanceddialogv2buttonoptions) | Yes | Configuration options of the button.| + +## AdvancedDialogV2ButtonOptions + +Provides options used to initialize an **AdvancedDialogV2Button** object. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Description | +|:-------------|:-----------------------------------------------------------------------|:---|:----------------------------------------------------------------------------------| +| content | [ResourceStr](ts-types.md#resourcestr) | Yes | Content of the button. | +| action | [AdvancedDialogV2ButtonAction](#advanceddialogv2buttonaction) | No | Action triggered when the button is clicked.
By default, there is no action. | +| background | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | No | Background of the button.
The setting follows **buttonStyle** by default. | +| fontColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | No | Font color of the button.
The setting follows **buttonStyle** by default. | +| buttonStyle | [ButtonStyleMode](ts-basic-components-button.md#buttonstylemode11) | No | Style of the button.
Default value: **ButtonStyleMode.NORMAL** for 2-in-1 devices and **ButtonStyleMode.TEXTUAL** for other devices| +| role | [ButtonRole](ts-basic-components-button.md#buttonrole12) | No | Role of the button.
Default value: **ButtonRole.NORMAL** | +| defaultFocus | boolean | No | Whether the button is the default focus.
Default value: **false** | +| enabled | boolean | No | Whether the button is enabled.
Default value: **true** | + +## Example + +### Example 1: Dialog Box with an Image Above Text + +This example implements a dialog box with an image above the text content, through the use of **imageRes**, **content**, and other properties. + +```ts +import { TipsDialogV2, AdvancedDialogV2Button, promptAction } from '@kit.ArkUI'; + +@Entry +@ComponentV2 +struct Index { + @Local checked: boolean = false; + + @Builder + dialogBuilder(): void { + TipsDialogV2({ + imageRes: $r('sys.media.ohos_ic_public_voice'), + content: 'Delete this app?', + title: 'TipsDialogV2', + checkTips: 'Don't show again', + checked: this.checked, + primaryButton: new AdvancedDialogV2Button({ + content: 'Cancel', + action: () => { + console.info('Callback when the first button is clicked'); + }, + }), + secondaryButton: new AdvancedDialogV2Button({ + content: 'Delete', + role: ButtonRole.ERROR, + action: () => { + console.info('Callback when the second button is clicked'); + } + }), + onCheckedChange: (checked: boolean) => { + console.info('Callback when the checkbox is clicked'); + this.checked = checked; + } + }) + } + + build() { + Row() { + Stack() { + Column() { + Button("Open TipsDialogV2") + .width(96) + .height(40) + .onClick(() => { + promptAction.openCustomDialog({ + builder: () => { + this.dialogBuilder(); + }, + }); + }) + }.margin({ bottom: 300 }) + }.align(Alignment.Bottom) + .width('100%').height('100%') + } + .backgroundImageSize({ width: '100%', height: '100%' }) + .height('100%') + } +} +``` + +![TipsDialog](figures/TipsDialog.png) + +### Example 2: List-only Dialog Box + +This example presents a dialog box consisting solely of a list defined with **selectedIndex** and **radioContent**. + +```ts +import { SelectDialogV2, AdvancedDialogV2Button ,promptAction } from '@kit.ArkUI'; + +@Entry +@ComponentV2 +struct Index { + @Local radioIndex: number = 0; + @Builder + dialogBuilder(): void { + SelectDialogV2({ + title:'Title', + selectedIndex: this.radioIndex, + confirm: new AdvancedDialogV2Button({ + content: 'Cancel', + action: () => {}, + }), + radioContent: [ + { + title: 'List item', + action: () => { + this.radioIndex = 0 + } + }, + { + title: 'List item', + action: () => { + this.radioIndex = 1 + } + }, + { + title: 'List item', + action: () => { + this.radioIndex = 2 + } + }, + ] + }) + } + build() { + Row() { + Stack() { + Column() { + Button("List Dialog Box") + .width(96) + .height(40) + .onClick(() => { + promptAction.openCustomDialog({ + builder: () => { + this.dialogBuilder(); + } + }) + }) + }.margin({ bottom: 300 }) + }.align(Alignment.Bottom) + .width('100%').height('100%') + } + .backgroundImageSize({ width: '100%', height: '100%' }) + .height('100%') + } +} +``` + +![SelectDialog](figures/SelectDialog.png) + +### Example 3: Dialog Box with Text and Check Boxes + +This example illustrates a dialog box that combines text content with check boxes defined with **content** and **checkTips**. + +```ts +import { ConfirmDialogV2, AdvancedDialogV2Button, promptAction } from '@kit.ArkUI'; + +@Entry +@ComponentV2 +struct Index { + @Local checked: boolean = false; + + @Builder + dialogBuilder(): void { + ConfirmDialogV2({ + title:'Title', + content: 'This is where content is displayed. This is where content is displayed.', + checked: this.checked, + checkTips: 'Don't ask again after denying', + primaryButton: new AdvancedDialogV2Button({ + content: 'Deny', + action: () => { + }, + }), + secondaryButton: new AdvancedDialogV2Button({ + content: 'Allow', + action: () => { + this.checked = false + console.info('Callback when the second button is clicked'); + } + }), + onCheckedChange: (checked: boolean) => { + console.info('Callback when the checkbox is clicked'); + this.checked = checked; + }, + }) + } + + build() { + Row() { + Stack() { + Column() { + Button("Open ConfirmDialogV2") + .width(96) + .height(40) + .onClick(() => { + promptAction.openCustomDialog({ + builder: () => { + this.dialogBuilder(); + }, + alignment: DialogAlignment.Bottom + }); + }) + }.margin({ bottom: 300 }) + }.align(Alignment.Bottom) + .width('100%').height('100%') + } + .backgroundImageSize({ width: '100%', height: '100%' }) + .height('100%') + } +} +``` + +![2024-06-03](figures/2024-06-03_150422.png) + +### Example 4: Text-only Dialog Box + +This example demonstrates a simple text-only dialog box defined with **primaryTitle**, **secondaryTitle**, and **content**. + +```ts +import { AlertDialogV2, AdvancedDialogV2Button, promptAction } from '@kit.ArkUI'; + +@Entry +@ComponentV2 +struct Index { + @Builder + dialogBuilder(): void { + AlertDialogV2({ + primaryTitle: 'Primary title', + secondaryTitle: 'Secondary title', + content: 'This is where content is displayed.', + primaryButton: new AdvancedDialogV2Button({ + content: 'Cancel', + action: () => { + }, + }), + secondaryButton: new AdvancedDialogV2Button({ + content: 'OK', + role: ButtonRole.ERROR, + action: () => { + console.info('Callback when the second button is clicked'); + } + }), + }) + } + + build() { + Row() { + Stack() { + Column() { + Button("Open AlertDialogV2") + .width(96) + .height(40) + .onClick(() => { + promptAction.openCustomDialog({ + builder: () => { + this.dialogBuilder(); + } + }); + }) + }.margin({ bottom: 300 }) + }.align(Alignment.Bottom) + .width('100%').height('100%') + } + .backgroundImageSize({ width: '100%', height: '100%' }) + .height('100%') + } +} +``` + +![AlertDialog](figures/AlertDialog.png) + +### Example 5: Loading Dialog Box + +This example implements a loading dialog box that contains a progress indicator. + +```ts +import { LoadingDialogV2, promptAction } from '@kit.ArkUI'; + +@Entry +@ComponentV2 +struct Index { + @Builder + dialogBuilder(): void { + LoadingDialogV2({ + content: 'This is where content is displayed.', + }) + } + + build() { + Row() { + Stack() { + Column() { + Button("Open LoadingDialogV2") + .width(96) + .height(40) + .onClick(() => { + promptAction.openCustomDialog({ + builder: () => { + this.dialogBuilder(); + } + }); + }) + }.margin({ bottom: 300 }) + }.align(Alignment.Bottom) + .width('100%').height('100%') + } + .backgroundImageSize({ width: '100%', height: '100%' }) + .height('100%') + } +} +``` + +![LoadingDialog](figures/LoadingDialog.gif) + +### Example 6: Dialog Box with a Custom Theme + +This example presents a dialog box with a custom theme, through the use of **content**, **theme**, and other properties. + +```ts +import { CustomColors, CustomTheme, LoadingDialogV2, promptAction } from '@kit.ArkUI'; + +class CustomThemeImpl implements CustomTheme { + colors?: CustomColors; + + constructor(colors: CustomColors) { + this.colors = colors; + } +} + +class CustomThemeColors implements CustomColors { + fontPrimary = '#ffd0a300'; + iconSecondary = '#ffd000cd'; +} + +@Entry +@ComponentV2 +struct Index { + @Builder + dialogBuilder(): void { + WithTheme({ theme: new CustomThemeImpl(new CustomThemeColors()) }) { + LoadingDialogV2({ + content: 'This is where content is displayed.', + }) + } + } + + build() { + Row() { + Stack() { + Column() { + Button("Open LoadingDialogV2") + .width(96) + .height(40) + .onClick(() => { + promptAction.openCustomDialog({ + builder: () => { + this.dialogBuilder(); + } + }); + }) + }.margin({ bottom: 300 }) + }.align(Alignment.Bottom) + .width('100%').height('100%') + } + .backgroundImageSize({ width: '100%', height: '100%' }) + .height('100%') + } +} +``` + +![loading\_dialog\_with\_theme](figures/advanced_dialog_loading_dialog_with_theme.png) + +### Example 7: Dialog Box with Custom Content + +This example implements a dialog box with custom content defined with **contentBuilder** and **buttons**. + +```ts +import { CustomContentDialogV2, AdvancedDialogV2Button, promptAction } from '@kit.ArkUI'; + +@Entry +@ComponentV2 +struct Index { + @Builder + dialogBuilder(): void { + CustomContentDialogV2({ + primaryTitle: 'Primary title', + secondaryTitle: 'Secondary title', + contentBuilder: () => { + this.buildContent(); + }, + buttons: [ + new AdvancedDialogV2Button({ + content: 'Button 1', buttonStyle: ButtonStyleMode.TEXTUAL, + action: () => { + console.info('Callback when the button is clicked'); + } + }), + new AdvancedDialogV2Button({ + content: 'Button 2', buttonStyle: ButtonStyleMode.TEXTUAL, role: ButtonRole.ERROR, + }) + ], + }) + } + + build() { + Column() { + Button("Open CustomContentDialogV2") + .onClick(() => { + promptAction.openCustomDialog({ + builder: () => { + this.dialogBuilder(); + } + }) + }) + } + .width('100%') + .height('100%') + .justifyContent(FlexAlign.Center) + } + + @Builder + buildContent(): void { + Column() { + Text('Content area') + } + } +} +``` + +![custom\_content\_dialog](figures/advanced_dialog_custom_content_dialog.png) + +### Example 8: Popover Dialog Box + +This example demonstrates a popover dialog box for alert purposes, through the use of **visible**, **popover**, **targetBuilder**, and other properties. + +```ts +import { AlertDialogV2, PopoverDialogV2, PopoverDialogV2Options, AdvancedDialogV2Button} from '@kit.ArkUI'; + +@Entry +@ComponentV2 +struct Index { + @Local isShow: boolean = false; + @Local popoverOptions: PopoverDialogV2Options = { + builder: () => { + this.dialogBuilder(); + } + } + + @Builder dialogBuilder() { + AlertDialogV2({ + content: 'Popover dialog box', + primaryButton: new AdvancedDialogV2Button({ + content: 'Cancel', + action: () => { + this.isShow = false; + }, + }), + secondaryButton: new AdvancedDialogV2Button({ + content: 'OK', + action: () => { + this.isShow = false; + }, + }), + }); + } + + @Builder buttonBuilder() { + Button('Target Component').onClick(() => { + this.isShow = true; + }); + } + + build() { + Column() { + PopoverDialogV2({ + visible: this.isShow!!, + popover: this.popoverOptions, + targetBuilder: () => { + this.buttonBuilder(); + }, + }) + } + } +} +``` + +![popover\_dialog](figures/advanced_dialog_popover_dialog.png) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-DownloadFileButton.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-DownloadFileButton.md index 8e3d39fff3917d2d55ed8529eafe46a4be93a5fd..31c140227b556a38c45871487f40d04ba0aaa318 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-DownloadFileButton.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-DownloadFileButton.md @@ -19,7 +19,7 @@ Not supported ## Attributes -The [universal attributes](ts-universal-attributes-size.md) are supported. +The [universal attributes](ts-component-general-attributes.md) are supported. ## DownloadFileButton @@ -31,10 +31,10 @@ Creates a download file button, which by default displays both an icon and text. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory| Decorator| Description | -| -------------- | ------------------------------------------------------------ | ---- | ---------- | -------------------------------- | -| contentOptions | [DownloadContentOptions](#downloadcontentoptions) | No | @State | Content options for creating the download file button.| -| styleOptions | [DownloadStyleOptions](#downloadstyleoptions) | No | @State | Style options for creating the download file button.| +| Name | Type | Mandatory| Decorator| Description | +| -------------- | ------------------------------------------------- | ---- | ---------- | -------------------------------- | +| contentOptions | [DownloadContentOptions](#downloadcontentoptions) | Yes | @State | Content options for creating the download file button.| +| styleOptions | [DownloadStyleOptions](#downloadstyleoptions) | Yes | @State | Style options for creating the download file button.| ## DownloadContentOptions @@ -59,11 +59,11 @@ Defines the style of the icon and text in the download file button. | Name | Type | Mandatory| Description | | --------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| iconSize | Dimension | No | Icon size of the download file button.
Default value: **16vp** | +| iconSize | Dimension | No | Icon size of the download file button. The value cannot be in percentage.
Default value: **16vp** | | layoutDirection | [DownloadLayoutDirection](#downloadlayoutdirection) | No | Direction of the icon and text on the download file button.
Default value: **DownloadLayoutDirection.HORIZONTAL**| -| fontSize | Dimension | No | Font size of the download file button.
Default value: **16fp** | +| fontSize | Dimension | No | Font size of the download file button. The value cannot be in percentage.
Default value: **16fp** | | fontStyle | FontStyle | No | Font style of the download file button.
Default value: **FontStyle.Normal** | -| fontWeight | number \| FontWeight \| string | No | Font weight of the download file button.
Default value: **FontWeight.Medium** | +| fontWeight | number \| FontWeight \| string | No | Font weight of the download file button. For the number type, the value ranges from 100 to 900, at an interval of 100. The default value is **400**. A larger value indicates a heavier font weight. For the string type, only strings that represent a number, for example, **400**, and the following enumerated values of **FontWeight** are supported: **bold**, **bolder**, **lighter**, **regular**, and **medium**.
Default value: **FontWeight.Medium** | | fontFamily | string \| Resource | No | Font family of the download file button.
Default font: **'HarmonyOS Sans'** | | fontColor | ResourceColor | No | Font color of the download file button.
Default value: **#ffffffff** | | iconColor | ResourceColor | No | Icon color of the download file button.
Default value: **#ffffffff** | @@ -120,14 +120,16 @@ Defines the direction of the icon and text in the download file button. ## Events -The [universal events](ts-universal-events-click.md) are supported. +The [universal events](ts-component-general-events.md) are supported. ## Example -``` +```ts +// xxx.ets + import { picker } from '@kit.CoreFileKit'; import { BusinessError } from '@kit.BasicServicesKit'; -import { DownloadFileButton, DownloadLayoutDirection } from '@kit.ArkUI'; +import { DownloadFileButton, DownloadLayoutDirection, DownloadIconStyle, DownloadDescription } from '@kit.ArkUI'; @Entry @Component @@ -136,8 +138,8 @@ struct Index { Column() { DownloadFileButton({ contentOptions: { - // icon: DownloadIconStyle.FULL_FILLED, - // text: DownloadDescription.DOWNLOAD + icon: DownloadIconStyle.FULL_FILLED, + text: DownloadDescription.DOWNLOAD }, styleOptions: { iconSize: '16vp', diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-EditableTitleBar.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-EditableTitleBar.md index b2638e20481ee54e5e8a4d5a77a016cf05d4554e..2433b26b1c4028ebc5c60a0f93b5a3a24f30ae71 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-EditableTitleBar.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-EditableTitleBar.md @@ -21,36 +21,43 @@ import { EditableTitleBar } from '@kit.ArkUI' Not supported ## Attributes -The [universal attributes](ts-universal-attributes-size.md) are not supported. +The [universal attributes](ts-component-general-attributes.md) are not supported. ## EditableTitleBar -EditableTitleBar({leftIconStyle: EditableLeftIconType, imageItem?: EditableTitleBarItem, title: ResourceStr, subtitle?: ResourceStr, menuItems?: Array<EditableTitleBarMenuItem>, isSaveIconRequired?: boolean, onSave?: () => void, onCancel?: () =>void, options?: EditableTitleBarOptions, contentMargin?: LocalizedMargin}) +EditableTitleBar({leftIconStyle: EditableLeftIconType, imageItem?: EditableTitleBarItem, title: ResourceStr, subtitle?: ResourceStr, menuItems?: Array<EditableTitleBarMenuItem>, isSaveIconRequired: boolean, onSave?: () => void, onCancel?: () =>void, options: EditableTitleBarOptions, contentMargin?: LocalizedMargin}) **Decorator**: @Component **System capability**: SystemCapability.ArkUI.ArkUI.Full -**Parameters** - -| Name| Type| Mandatory| Decorator| Description| -| -------- | -------- | -------- | -------- | -------- | -| leftIconStyle | [EditableLeftIconType](#editablelefticontype) | Yes| - | Type of the icon on the left.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| imageItem12+ | [EditableTitleBarItem](#editabletitlebaritem12) | No| - | A single menu item for the profile picture on the left.
**Atomic service API**: This API can be used in atomic services since API version 12.| -| title | [ResourceStr](ts-types.md#resourcestr) | Yes| - | Title.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| subtitle12+ | [ResourceStr](ts-types.md#resourcestr) | No| - | Subtitle.
**Atomic service API**: This API can be used in atomic services since API version 12.| -| menuItems | Array<[EditableTitleBarMenuItem](#editabletitlebarmenuitem)> | No| - | List of menu items on the right.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| isSaveIconRequired12+ | boolean | No| - | Whether the save button on the right is required.
Default value: **true**, indicating that the save button on the right is required.
**Atomic service API**: This API can be used in atomic services since API version 12.| -| onSave | () => void | No| - | Callback invoked when the Save icon is clicked.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| onCancel | () => void | No| - | Callback that is triggered when the cancel action is performed with the left Cancel icon.
Since API version 12: Callback that is triggered when the back action is performed with the left Back icon.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| options12+ | [EditableTitleBarOptions](#editabletitlebaroptions12) | No| - | Title style.
**Atomic service API**: This API can be used in atomic services since API version 12.| -| contentMargin12+ | [LocalizedMargin](ts-types.md#localizedmargin12) | No| @Prop | Margin of the content. Negative numbers are not supported.
Default value:
{start: LengthMetrics.resource(*$r('sys.float.margin_left')*), end: LengthMetrics.resource(*$r('sys.float.margin_right')*)}
**Atomic service API**: This API can be used in atomic services since API version 12.| +| Name| Type| Mandatory| Decorator| Description | +| -------- | -------- | -------- | -------- |------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| leftIconStyle | [EditableLeftIconType](#editablelefticontype) | Yes| - | Type of the icon on the left.
Default value: **EditableLeftIconType.Back**
**Atomic service API**: This API can be used in atomic services since API version 11. | +| imageItem12+ | [EditableTitleBarItem](#editabletitlebaritem12) | No| - | A single menu item for the profile picture on the left.
Default value: **undefined**
**Atomic service API**: This API can be used in atomic services since API version 12. | +| title | [ResourceStr](ts-types.md#resourcestr) | Yes| - | Title.
Default value: **''**, indicating that the title is empty
**Atomic service API**: This API can be used in atomic services since API version 11. | +| subtitle12+ | [ResourceStr](ts-types.md#resourcestr) | No| - | Subtitle.
Default value: **''**, indicating that the subtitle is empty
**Atomic service API**: This API can be used in atomic services since API version 12. | +| menuItems | Array<[EditableTitleBarMenuItem](#editabletitlebarmenuitem)> | No| - | List of menu items on the right.
Default value: **undefined**
**Atomic service API**: This API can be used in atomic services since API version 11. | +| isSaveIconRequired12+ | boolean | Yes| - | Whether the save button on the right is required.
Default value: **true**, indicating that the save button on the right is required.
**NOTE**
If not decorated by @Require, this parameter is not subject to mandatory validation during construction.
**Atomic service API**: This API can be used in atomic services since API version 12. | +| onSave | () => void | No| - | Callback invoked when the Save icon is clicked.
Default value: **() => void**
**Atomic service API**: This API can be used in atomic services since API version 11. | +| onCancel | () => void | No| - | Callback that is triggered when the cancel action is performed with the left Cancel icon.
Default value: **() => void**
Since API version 12: Callback that is triggered when the back action is performed with the left Back icon.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| options12+ | [EditableTitleBarOptions](#editabletitlebaroptions12) | Yes| - | Title style.
Default value:
{
safeAreaTypes: [SafeAreaType.SYSTEM],
safeAreaEdges: [SafeAreaEdge.TOP],
backgroundColor: '#00000000'
}
**NOTE**
If not decorated by @Require, this parameter is not subject to mandatory validation during construction.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| contentMargin12+ | [LocalizedMargin](ts-types.md#localizedmargin12) | No| @Prop | Margin of the content. Negative numbers are not supported.
Default value:
{start: LengthMetrics.resource(*$r('sys.float.margin_left')*), end: LengthMetrics.resource(*$r('sys.float.margin_right')*)}
**Atomic service API**: This API can be used in atomic services since API version 12. | +| leftIconDefaultFocus18+ | boolean | No| - | Whether the left icon is the default focus.
Default value: **false**
**Atomic service API**: This API can be used in atomic services since API version 18. | +| saveIconDefaultFocus18+ | boolean | No| - | Whether the save icon is the default focus.
Default value: **false**
**Atomic service API**: This API can be used in atomic services since API version 18. | + +> **NOTE** +> +> The input parameter cannot be **undefined**, that is, calling **EditableTitleBar(undefined)** is not allowed. +> If multiple operable areas are set as default focus, the first one in the display order that is set as the default focus will be the default focus. ## EditableLeftIconType **Atomic service API**: This API can be used in atomic services since API version 11. +**System capability**: SystemCapability.ArkUI.ArkUI.Full + | Name| Value| Description| | -------- | -------- | -------- | | Back | 0 | Back.| @@ -58,19 +65,28 @@ EditableTitleBar({leftIconStyle: EditableLeftIconType, imageItem?: EditableTitle ## EditableTitleBarMenuItem -**Atomic service API**: This API can be used in atomic services since API version 11. +**System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | [ResourceStr](ts-types.md#resourcestr) | Yes| Icon resource.| -| label12+ | [ResourceStr](ts-types.md#resourcestr) | No| Icon label.| -| isEnabled | boolean | No| Whether to enable the item.
Default value: **false**
**true**: The item is enabled.
**false**: The item is disabled.| -| action | () => void | No| Action to perform.| +| Name| Type| Mandatory| Description | +| -------- | -------- | -------- |-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| value | [ResourceStr](ts-types.md#resourcestr) | Yes| Icon resource.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| symbolStyle18+ | [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) | No| Symbol icon resource, which has higher priority than **value**.
**Atomic service API**: This API can be used in atomic services since API version 18.| +| label12+ | [ResourceStr](ts-types.md#resourcestr) | No| Icon label.
**Atomic service API**: This API can be used in atomic services since API version 12. | +| isEnabled | boolean | No| Whether to enable the item.
Default value: **true**

**true**: The item is enabled.
**false**: The item is disabled.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| action | () => void | No| Action to perform.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| accessibilityLevel18+ | string | No| Accessibility level. It determines whether the component can be recognized by accessibility services.
The options are as follows:
**"auto"**: It is treated as "yes" by the system.
**"yes"**: The component can be recognized by accessibility services.
**"no"**: The component cannot be recognized by accessibility services.
**"no-hide-descendants"**: Neither the component nor its child components can be recognized by accessibility services.
Default value: **"auto"**
**Atomic service API**: This API can be used in atomic services since API version 18.| +| accessibilityText18+ | ResourceStr | No| Accessibility text, that is, accessible label name. If a component does not contain text information, it will not be announced by the screen reader when selected. In this case, the screen reader user cannot know which component is selected. To solve this problem, you can set accessibility text for components without text information. When such a component is selected, the screen reader announces the specified accessibility text, informing the user which component is selected.
Default value: value of the **label** property if it is set and an empty string otherwise.
**Atomic service API**: This API can be used in atomic services since API version 18. | +| accessibilityDescription18+ | ResourceStr | No| Accessible description. You can provide comprehensive text explanations to help users understand the operation they are about to perform and its potential consequences, especially when these cannot be inferred from the component's attributes and accessibility text alone. If a component contains both text information and the accessible description, the text is announced first and then the accessible description, when the component is selected.
Default value: **"Double-tap to activate"**
**Atomic service API**: This API can be used in atomic services since API version 18. | +| defaultFocus18+ | boolean | No| Whether to set the item as the default focus.
**true**: Set the item as the default focus.
**false**: Do not set the item as the default focus.
Default value: **false**
**Atomic service API**: This API can be used in atomic services since API version 18. | ## EditableTitleBarItem12+ +type EditableTitleBarItem = EditableTitleBarMenuItem + **Atomic service API**: This API can be used in atomic services since API version 12. +**System capability**: SystemCapability.ArkUI.ArkUI.Full + | Type| Description| | -------- | -------- | | [EditableTitleBarMenuItem](#editabletitlebarmenuitem) | A single menu item for the profile picture on the left.| @@ -79,22 +95,24 @@ EditableTitleBar({leftIconStyle: EditableLeftIconType, imageItem?: EditableTitle **Atomic service API**: This API can be used in atomic services since API version 12. +**System capability**: SystemCapability.ArkUI.ArkUI.Full + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| backgroundColor | [ResourceStr](ts-types.md#resourcestr) | No| Background color of the title bar.| -| backgroundBlurstyle | [BlurStyle](ts-universal-attributes-background.md#blurstyle9) | No| Background blur style of the title bar.| +| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | No| Background color of the title bar.
Default value: **'#00000000'**| +| backgroundBlurStyle | [BlurStyle](ts-universal-attributes-background.md#blurstyle9) | No| Background blur style of the title bar.
Default value: **[BlurStyle.NONE]**| | safeAreaTypes | Array <[SafeAreaType](ts-types.md#safeareatype10)> | No | Types of the expanded safe areas.
Default value: **[SafeAreaType.SYSTEM]**| | safeAreaEdges | Array <[SafeAreaEdge](ts-types.md#safeareaedge10)> | No | Edges for expanding the safe area.
Default value: **[SafeAreaEdge.TOP]**| ## Events -The [universal events](ts-universal-events-click.md) are not supported. +The [universal events](ts-component-general-events.md) are not supported. ## Example -### Example 1 +### Example 1: Implementing an Editable Title Bar with a Custom Right Icon + This example demonstrates how to implement an editable title bar with a left icon, main title, and custom right icon area. ```ts -// This example demonstrates the effects of setting the left icon, the main title, and a custom right icon area in the editable title bar. import { EditableLeftIconType, EditableTitleBar, promptAction } from '@kit.ArkUI'; @Entry @@ -104,6 +122,7 @@ struct Index { Row() { Column() { Divider().height(2).color(0xCCCCCC) + // Cancel button on the left and save button on the right. EditableTitleBar({ leftIconStyle: EditableLeftIconType.Cancel, title: 'Edit', @@ -116,12 +135,13 @@ struct Index { } }) Divider().height(2).color(0xCCCCCC) + // Back button on the left, and custom cancel (disabled) and save buttons on the right. EditableTitleBar({ leftIconStyle: EditableLeftIconType.Back, title: 'Edit', menuItems: [ { - value: $r('app.media.ic_public_reduce'), + value: $r('sys.media.ohos_ic_public_cancel'), isEnabled: false, action: () => { promptAction.showToast({ message: 'show toast index 2' }); @@ -139,18 +159,18 @@ struct Index { } ``` -![en-us_image_0000001617073302](figures/en-us_image_0000001617073302.png) +![en-us_image_editabletitlebar_example01](figures/en-us_image_editabletitlebar_example01.png) -### Example 2 +### Example 2: Implementing an Editable Title Bar with Background Blur and a Profile Picture +This example shows how to implement an editable title bar with background blur, a profile picture, and custom margins. ```ts -// This example demonstrates how to configure an editable title bar with a blurred background, profile picture, removal of the save icon on the right, and custom content margins. import { EditableLeftIconType, EditableTitleBar, LengthMetrics, promptAction, router } from '@kit.ArkUI'; @Entry @Component struct Index { - @State titlebarMargin: LocalizedMargin = { + @State titleBarMargin: LocalizedMargin = { start: LengthMetrics.vp(35), end: LengthMetrics.vp(35), }; @@ -160,7 +180,7 @@ struct Index { Column() { EditableTitleBar({ leftIconStyle: EditableLeftIconType.Cancel, - title: 'Main Title', + title: 'Main title', subtitle: 'Subtitle', // Set the background blur effect. options: { @@ -170,34 +190,28 @@ struct Index { promptAction.showToast({ message: "on save" }); }, }) - Divider().height(2).color(0xCCCCCC); - EditableTitleBar({ leftIconStyle: EditableLeftIconType.Cancel, - title: 'Main Title', + title: 'Main title', subtitle: 'Subtitle', // Remove the save button on the right. isSaveIconRequired: false, }) - Divider().height(2).color(0xCCCCCC); - EditableTitleBar({ leftIconStyle: EditableLeftIconType.Back, - title: 'Main Title', + title: 'Main title', subtitle: 'Subtitle', isSaveIconRequired: false, onCancel: () => { router.back(); }, }) - Divider().height(2).color(0xCCCCCC); - EditableTitleBar({ leftIconStyle: EditableLeftIconType.Back, - title: 'Main Title', + title: 'Main title', subtitle: 'Subtitle', menuItems: [ { @@ -214,23 +228,21 @@ struct Index { router.back(); }, }) - Divider().height(2).color(0xCCCCCC); - EditableTitleBar({ leftIconStyle: EditableLeftIconType.Back, - title: 'Main Title', + title: 'Main title', subtitle: 'Subtitle', // Set a clickable profile picture. imageItem: { - value: $r('app.media.img'), + value: $r('sys.media.ohos_ic_normal_white_grid_image'), isEnabled: true, action: () => { promptAction.showToast({ message: "show toast index 2" }); } }, // Set the content margin of the title bar. - contentMargin: this.titlebarMargin, + contentMargin: this.titleBarMargin, // Configure the icon on the right. menuItems: [ { @@ -251,4 +263,207 @@ struct Index { } ``` -![en-us_image_EditableTitleBar](figures/en-us_image_EditableTitleBar.png) +![en-us_image_editabletitlebar_example02](figures/en-us_image_editabletitlebar_example02.png) + +### Example 3: Implementing Screen Reader Announcement for the Custom Button on the Right Side +This example customizes the screen reader announcement text by setting the **accessibilityText**, **accessibilityDescription**, and **accessibilityLevel** properties of the custom button on the right side of the title bar. +```ts + +import { promptAction, router, EditableLeftIconType, EditableTitleBar } from '@kit.ArkUI'; + +@Entry +@Component +struct Index1 { + build() { + Row() { + Column() { + Divider().height(2).color(0xCCCCCC) + EditableTitleBar({ + leftIconStyle: EditableLeftIconType.Cancel, + title: 'Edit', + menuItems: [], + onCancel: () => { + promptAction.showToast({ message: 'on cancel' }); + }, + onSave: () => { + promptAction.showToast({ message: 'on save' }); + } + }) + Divider().height(2).color(0xCCCCCC) + EditableTitleBar({ + // The profile picture and custom buttons are unavailable. + leftIconStyle: EditableLeftIconType.Back, + title: 'Main title', + subtitle: 'Subtitle', + imageItem: { + value: $r('sys.media.ohos_ic_normal_white_grid_image'), + isEnabled: true, + action: () => { + promptAction.showToast({ message: "show toast index 1" }); + } + }, + menuItems: [ + { + value: $r('sys.media.ohos_ic_public_remove'), + label: 'Cancel', + isEnabled: false, + accessibilityText: 'Delete', + accessibilityDescription: 'Tap to delete', + action: () => { + promptAction.showToast({ message: "show toast index 2" }); + } + } + ], + onCancel: () => { + router.back(); + }, + }) + Divider().height(2).color(0xCCCCCC) + } + } + } +} +``` +![en-us_image_editabletitlebar_example03](figures/en-us_image_editabletitlebar_example03.png) + +### Example 4: Setting the Left Icon as the Default Focus +This example demonstrates how to set the left icon as the default focus using **leftIconDefaultFocus**. +```ts + +import { promptAction, EditableLeftIconType, EditableTitleBar } from '@kit.ArkUI'; + +@Entry +@Component +struct Index { + build() { + Column() { + EditableTitleBar({ + leftIconStyle: EditableLeftIconType.Back, + leftIconDefaultFocus: true, // Set the left icon as the default focus. + title: 'Edit', + menuItems: [], + onSave: () => { + promptAction.showToast({ message: 'on save' }); + } + }) + } + .height('100%') + .width('100%') + } +} +``` +![/editabletitlebarDefaultFocus01](figures/editabletitlebarDefaultFocus01.png) + +### Example 5: Setting a Custom Right Icon as the Default Focus +This example demonstrates how to set a custom right icon as the default focus using **defaultFocus**. +```ts + +import { promptAction, EditableLeftIconType, EditableTitleBar, router } from '@kit.ArkUI'; + +@Entry +@Component +struct Index { + build() { + Column() { + EditableTitleBar({ + leftIconStyle: EditableLeftIconType.Back, + title: 'Main title', + subtitle: 'Subtitle', + // Configure the icon on the right. + menuItems: [ + { + value: $r('sys.media.ohos_ic_public_remove'), + isEnabled: true, + action: () => { + promptAction.showToast({ message: "show toast index 1" }); + } + }, + { + value: $r('sys.media.ohos_ic_public_remove'), + isEnabled: true, + defaultFocus: true, + action: () => { + promptAction.showToast({ message: "show toast index 2" }); + } + } + ], + onCancel: () => { + router.back(); + }, + }) + } + .height('100%') + .width('100%') + } +} +``` +![/editabletitlebarDefaultFocus02](figures/editabletitlebarDefaultFocus02.png) + +### Example 6: Setting the Symbol Icon + +This example demonstrates how to use **symbolStyle** in **EditableTitleBarMenuItem** to set custom symbol icons. + +```ts +import { EditableLeftIconType, EditableTitleBar, promptAction, SymbolGlyphModifier } from '@kit.ArkUI'; + +@Entry +@Component +struct Index { + build() { + Row() { + Column() { + Divider().height(2).color(0xCCCCCC) + EditableTitleBar({ + leftIconStyle: EditableLeftIconType.Cancel, + title: 'Main title', + subtitle: 'Subtitle', + menuItems: [ + { + value: $r('sys.symbol.house'), + isEnabled: true, + action: () => { + promptAction.showToast({ message: 'show toast index 2' }); + } + }, + { + value: $r('sys.symbol.car'), + isEnabled: false, + } + ], + }) + Divider().height(2).color(0xCCCCCC) + EditableTitleBar({ + leftIconStyle: EditableLeftIconType.Back, + title: 'Main title', + subtitle: 'Subtitle', + imageItem: { + value: $r('sys.media.ohos_app_icon'), + isEnabled: true, + action: () => { + promptAction.showToast({ message: "show toast index 1" }); + } + }, + menuItems: [ + { + value: $r('sys.symbol.house'), + symbolStyle: new SymbolGlyphModifier($r('sys.symbol.bell')).fontColor([Color.Red]), + isEnabled: true, + action: () => { + promptAction.showToast({ message: 'show toast index 2' }); + } + }, + { + value: $r('sys.symbol.car'), + symbolStyle: new SymbolGlyphModifier($r('sys.symbol.heart')).fontColor([Color.Blue]), + isEnabled: false, + } + ], + }) + Divider().height(2).color(0xCCCCCC) + }.width('100%') + }.height('100%') + } +} +``` + +![Setting the Symbol Icon](figures/en-us_image_editabletitlebar_demo_06.png) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ExceptionPrompt.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ExceptionPrompt.md index 9b4b800995ce52e2b74f757e5a64c0a928cac391..016591fb23b5c47087fc131a37aceb09c59d6328 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ExceptionPrompt.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ExceptionPrompt.md @@ -22,7 +22,7 @@ Not supported ## Attributes -The [universal attributes](ts-universal-attributes-size.md) are not supported. +The [universal attributes](ts-component-general-attributes.md) are not supported. ## ExceptionPrompt @@ -53,7 +53,8 @@ Defines the exception prompt options. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| icon | [ResourceStr](ts-types.md#resourcestr) | No| Icon of the exception prompt.| +| icon | [ResourceStr](ts-types.md#resourcestr) | No| Icon style of the exception prompt.| +| symbolStyle18+ | [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) | No| Symbol icon style of the exception prompt, which has higher priority than **icon**.
**Atomic service API**: This API can be used in atomic services since API version 18.| | tip | [ResourceStr](ts-types.md#resourcestr) | No| Text content of the exception prompt.
By default, the following text resources are provided:
1. **ohos_network_not_connected**: displayed when no Internet connection.
2. **ohos_network_connected_unstable**: displayed when the Internet connection is unstable.
3. **ohos_unstable_connect_server**: displayed when the server fails to be connected.
4. **ohos_custom_network_tips_left**: displayed when an Internet connection is available but the location fails to be obtained.| | marginType | [MarginType](#margintype) | Yes| Margin type of the exception prompt.| | actionText | [ResourceStr](ts-types.md#resourcestr) | No| Text of the icon on the right of the exception prompt.| @@ -74,7 +75,7 @@ Defines the margin type. | FIT_MARGIN | 1 | Adaptable margin:
Margin 1: referenced from **ohos_id_max_padding_start**.
Margin 2: referenced from **ohos_id_max_padding_end**.| ## Events -The [universal events](ts-universal-events-click.md) are supported. +The [universal events](ts-component-general-events.md) are not supported. ## Example ### Example 1: Configuring an Exception Prompt @@ -93,7 +94,7 @@ struct Index { marginType: MarginType.DEFAULT_MARGIN, actionText: 'Set network', marginTop: 80, - isShown:true + isShown: true, } build() { @@ -101,10 +102,10 @@ struct Index { ExceptionPrompt({ options: this.options, onTipClick: () => { - // Click the text on the left to switch to the connecting state. + // Handle clicks on the left text to switch to a connected state. }, onActionTextClick: () => { - // Click Set network to open the Set network dialog box. + // Handle clicks on the Set network button to open the network settings dialog box. }, }) } @@ -123,115 +124,161 @@ import { ExceptionPrompt, PromptOptions, MarginType } from '@kit.ArkUI' @CustomDialog struct CustomDialogExample { - @Link textValue: string - @Link inputValue: string + @Link textValue: string; + @Link inputValue: string; @State options: PromptOptions = { - icon: $r('app.media.ic_public_fail'), + icon: $r('sys.media.ohos_ic_public_fail'), tip: 'Error', marginType: MarginType.DEFAULT_MARGIN, actionText: 'Settings', marginTop: 5, - isShown: true - } - cancel: () => void = () => {} - confirm: () => void = () => {} - controller: CustomDialogController - // You can pass in multiple other controllers in the CustomDialog to open one or more other CustomDialogs in the CustomDialog. In this case, you must place the controller pointing to the self behind all controllers. + isShown: true, + }; + cancel: () => void = () => { + }; + confirm: () => void = () => { + }; + controller?: CustomDialogController; + + // To pass multiple other controllers into a CustomDialog to open another or several other custom dialog boxes within it, + // place the controller pointing to itself last. build() { Column() { ExceptionPrompt({ options: this.options, }) - TextInput({ placeholder: '', text: this.textValue }).margin({top:70}).height(60).width('90%') + TextInput({ placeholder: '', text: this.textValue }).margin({ top: 70 }).height(60).width('90%') .onChange((value: string) => { - this.textValue = value + this.textValue = value; }) Text('Are you sure you want to change the text?').fontSize(16).margin({ bottom: 10 }) Flex({ justifyContent: FlexAlign.SpaceAround }) { Button('No') .onClick(() => { - this.controller.close() - this.cancel() + this.controller?.close(); + this.cancel(); }).backgroundColor(0xffffff).fontColor(Color.Black) Button('OK') .onClick(() => { - this.inputValue = this.textValue - this.controller.close() - this.confirm() + this.inputValue = this.textValue; + this.controller?.close(); + this.confirm(); }).backgroundColor(0xffffff).fontColor(Color.Red) }.margin({ bottom: 10 }) } } } + @Entry @Component struct Index1 { - @State ButtonText: string = '' - @State MAP_HEIGHT: string = '30%' - @State duration: number = 2500 - @State tips: string = '' - @State actionText: string = '' - controller: TextInputController = new TextInputController() - cancel: () => void = () => {} - confirm: () => void = () => {} + @State ButtonText: string = ''; + @State MAP_HEIGHT: string = '30%'; + @State duration: number = 2500; + @State tips: string = ''; + @State actionText: string = ''; + controller: TextInputController = new TextInputController(); + cancel: () => void = () => { + }; + confirm: () => void = () => { + }; @State options: PromptOptions = { - icon: $r('app.media.ic_public_fail'), + icon: $r('sys.media.ohos_ic_public_fail'), tip: '', marginType: MarginType.DEFAULT_MARGIN, actionText: '', marginTop: 80, - isShown: true + isShown: true, } - @State textValue: string = '' - @State inputValue: string = 'click me' + @State textValue: string = ''; + @State inputValue: string = 'click me'; dialogController: CustomDialogController | undefined = new CustomDialogController({ builder: CustomDialogExample({ cancel: this.onCancel, confirm: this.onAccept, textValue: $textValue, - inputValue: $inputValue + inputValue: $inputValue, }), cancel: this.existApp, autoCancel: true, alignment: DialogAlignment.Bottom, offset: { dx: 0, dy: -20 }, gridCount: 4, - customStyle: false + customStyle: false, }) aboutToDisappear() { - this.dialogController = undefined // Set dialogController to undefined. + this.dialogController = undefined; // Set dialogController to undefined. } onCancel() { - console.info('Callback when the first button is clicked') + console.info('Callback when the first button is clicked'); } onAccept() { - console.info('Callback when the second button is clicked') + console.info('Callback when the second button is clicked'); } existApp() { - console.info('Click the callback in the blank area') + console.info('Click the callback in the blank area'); } build() { Column() { Button('Click Me') .width('30%') - .margin({top:420}) + .margin({ top: 420 }) .zIndex(999) - .onClick(()=>{ + .onClick(() => { if (this.dialogController != undefined) { - this.dialogController.open() + this.dialogController.open(); } }) } .height('100%') .width('100%') - } } ``` ![ExceptionPrompt2](figures/ExceptionPrompt2.gif) + +### Example 3: Setting the Symbol Icon + +This example demonstrates how to use **symbolStyle** in **PromptOptions** to set custom symbol icons. + +```ts +import { ExceptionPrompt, MarginType, SymbolGlyphModifier } from '@kit.ArkUI' + +@Entry +@Component +struct Index { + build() { + Column() { + ExceptionPrompt({ + options: { + icon: $r('sys.symbol.house'), + tip: 'Exception prompt Exception prompt Exception prompt', + marginType: MarginType.DEFAULT_MARGIN, + actionText: 'Set network Set network Set network Set network', + marginTop: 80, + isShown: true, + }, + }) + ExceptionPrompt({ + options: { + icon: $r('sys.symbol.house'), + symbolStyle: new SymbolGlyphModifier($r('sys.symbol.bell')).fontColor([Color.Red]), + tip: 'Exception prompt Exception prompt Exception prompt', + marginType: MarginType.DEFAULT_MARGIN, + actionText: 'Set network Set network Set network Set network', + marginTop: 80, + isShown: true, + }, + }) + } + } +} +``` + +![ExceptionPrompt1](figures/ExceptionPrompt3.png) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-Filter.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-Filter.md index 7a8d6d9277b0a9858f4d2cc9a517628bcf474121..91d17a7680d892ba8c9e77f40bb13e80402ef8a5 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-Filter.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-Filter.md @@ -21,11 +21,11 @@ import { Filter } from '@kit.ArkUI' Not supported ## Attributes -The [universal attributes](ts-universal-attributes-size.md) are supported. +The [universal attributes](ts-component-general-attributes.md) are not supported. ## Filter -Filter({ multiFilters: Array<FilterParams>, additionFilters: FilterParams, filterType: FilterType, onFilterChanged: (Array<FilterResult>) => void, container: ()=> void }) +Filter({ multiFilters: Array<FilterParams>, additionFilters?: FilterParams, filterType?: FilterType, onFilterChanged: (Array<FilterResult>) => void, container: ()=> void }) **Decorator**: @Component @@ -50,10 +50,10 @@ Filter({ multiFilters: Array<FilterParams>, additionFilters: FilterParams **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| name | [ResourceStr](ts-types.md#resourcestr) | Yes| Name of the filter criterion.| -| options | Array<[ResourceStr](ts-types.md#resourcestr)> | Yes| Options of the filter criterion.| +| Name| Type| Mandatory| Description | +| -------- | -------- | -------- |-----------------------------------------------------------------| +| name | [ResourceStr](ts-types.md#resourcestr) | Yes| Name of the filter criterion.
The default value is an empty string.
**NOTE**
If the text is longer than the column width, it will be truncated. | +| options | Array<[ResourceStr](ts-types.md#resourcestr)> | Yes| Options of the filter criterion.
The default value is an empty string.
**NOTE**
The text is truncated with an ellipsis (...) if it is too long.| ## FilterType @@ -72,30 +72,44 @@ Filter({ multiFilters: Array<FilterParams>, additionFilters: FilterParams **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| name | [ResourceStr](ts-types.md#resourcestr) | Yes| Name of the filter criterion.| -| index | number | Yes| Index of the selected option of the filter criterion.| -| value | [ResourceStr](ts-types.md#resourcestr) | Yes| Value of the selected option of the filter criterion.| +| Name| Type| Mandatory| Description | +| -------- | -------- | -------- |--------------------------------------------------------------------------| +| name | [ResourceStr](ts-types.md#resourcestr) | Yes| Name of the filter criterion.
The default value is an empty string.
**NOTE**
If the text is longer than the column width, it will be truncated. | +| index | number | Yes| Index of the selected option of the filter criterion.
Value range: an integer no less than -1
The default value is **-1**, indicating that there is no selected option. Values less than -1 are treated as no selected option.| +| value | [ResourceStr](ts-types.md#resourcestr) | Yes| Value of the selected option of the filter criterion.
The default value is an empty string.
**NOTE**
If the text is longer than the column width, it will be truncated. | ## Events -The [universal events](ts-universal-events-click.md) are not supported. +The [universal events](ts-component-general-events.md) are not supported. ## Example This example shows how to implement a multi-line collapsible filter by setting **FilterType** to **MULTI_LINE_FILTER**. ```ts -import { Filter, FilterParams, FilterResult, FilterType } from '@kit.ArkUI' +import { Filter, FilterParams, FilterResult, FilterType } from '@kit.ArkUI'; @Entry @Component struct Index { - private filterParam: Array = [{name:'Month', options: ['All', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']}, - {name: 'Year', options: ['All','2023','2022','2021','2020','2019','2018','2017','2016','2015','2014','2013','2012','2011','2010','2009','2008']}, - {name: 'Week', options: ['All','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24']}] - private additionParam: FilterParams = { name: 'Suggestions', options: ['Category 1','Category 2','Category 3','Category 4','Category 5','Category 6']} - private arr: number[] = [1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10]; + private filterParam: Array = [{ + name: 'Month', + options: ['All', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], + }, + { + name: 'Year', + options: ['All', '2023', '2022', '2021', '2020', '2019', '2018', '2017', '2016', '2015', '2014', '2013', '2012', + '2011', '2010', '2009', '2008'], + }, + { + name: 'Day', + options: ['All', '1', '2', '3', '4', '5',' 6', '7','8', '9','10', '11', '12', + '13','14', '15', '16', '17', '18','19','20','21','22', '23'], + }]; + // Addition filter parameter. The name of the filter dimension must be specified. Otherwise, the entire filter dimension is not displayed. + private additionParam: FilterParams = + { name: 'Suggestions', options: ['Category 1', 'Category 2', 'Category 3', 'Category 4', 'Category 5', 'Category 6'] }; + private arr: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + build() { Column() { Filter({ @@ -103,23 +117,23 @@ struct Index { additionFilters: this.additionParam, filterType: FilterType.MULTI_LINE_FILTER, onFilterChanged: (select: Array) => { - console.log('rec filter change') + console.log('rec filter change'); for (let filter of select) { - console.log('name:' + filter.name + ',index:' + filter.index + ',value:' + filter.value) + console.log('name:' + filter.name + ',index:' + filter.index + ',value:' + filter.value); } } - }){ + }) { List({ initialIndex: 0 }) { - ForEach(this.arr, (item:string, index: number) => { + ForEach(this.arr, (item: string, index: number) => { ListItem() { Text(item.toString()) - .width("100%") + .width('100%') .height(100) .fontSize(16) .textAlign(TextAlign.Center) .borderRadius(10) .backgroundColor(Color.White) - .margin({ top:10, bottom: 10 }) + .margin({ top: 10, bottom: 10 }) } }) }.backgroundColor(Color.Gray) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-FoldSplitContainer.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-FoldSplitContainer.md index d35dff9f9a1d644ef8aabadfb339c14c93d518bb..eb3ae74a9f5a32b8d2099e0b05099441f9ee0d7f 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-FoldSplitContainer.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-FoldSplitContainer.md @@ -24,13 +24,15 @@ FoldSplitContainer({ primary: Callback<void>, secondary: Callback<void>, extra?: Callback<void>, - expandedLayoutOptions?: ExpandedRegionLayoutOptions, - hoverModeLayoutOptions?: HoverModeRegionLayoutOptions, - foldedLayoutOptions?: FoldedRegionLayoutOptions, + expandedLayoutOptions: ExpandedRegionLayoutOptions, + hoverModeLayoutOptions: HoverModeRegionLayoutOptions, + foldedLayoutOptions: FoldedRegionLayoutOptions, animationOptions?: AnimateParam, - onHoverStatusChange?: onHoverStatusChangeHandler + onHoverStatusChange?: OnHoverStatusChangeHandler }) +Creates a **FoldSplitContainer** component to manage regions for two-panel and three-panel arrangements on a foldable device across various states, including the expanded state, the hover state, and the folded state. + **Decorator**: \@Component **Atomic service API**: This API can be used in atomic services since API version 12. @@ -39,14 +41,14 @@ FoldSplitContainer({ | Name| Type| Mandatory| Decorator| Description| | -------- | -------- | -------- | -------- | -------- | -| primary | ()=>void | No| @BuilderParam | Callback function for the primary region.| -| secondary | ()=>void | No| @BuilderParam | Callback function for the secondary region.| +| primary | ()=>void | Yes| @BuilderParam | Callback function for the primary region.| +| secondary | ()=>void | Yes| @BuilderParam | Callback function for the secondary region.| | extra | ()=>void | No| @BuilderParam | Callback function for the extra region. If this parameter is not provided, there is no corresponding region.| -| expandedLayoutOptions | [ExpandedRegionLayoutOptions](#expandedregionlayoutoptions) | No| @Prop | Layout information for the expanded state.| -| hoverModeLayoutOptions | [HoverModeRegionLayoutOptions](#hovermoderegionlayoutoptions) | No| @Prop | Layout information for the hover state.| -| foldedLayoutOptions | [FoldedRegionLayoutOptions](#foldedregionlayoutoptions) | No| @Prop | Layout information for the folded state.| +| expandedLayoutOptions | [ExpandedRegionLayoutOptions](#expandedregionlayoutoptions) | Yes| @Prop | Layout information for the expanded state.| +| hoverModeLayoutOptions | [HoverModeRegionLayoutOptions](#hovermoderegionlayoutoptions) | Yes| @Prop | Layout information for the hover state.| +| foldedLayoutOptions | [FoldedRegionLayoutOptions](#foldedregionlayoutoptions) | Yes| @Prop | Layout information for the folded state.| | animationOptions | [AnimateParam](ts-explicit-animation.md#animateparam) \| null | No| @Prop | Animation settings. The value **null** indicates that the animation is disabled.| -| onHoverStatusChange | [onHoverStatusChangeHandler](#onhoverstatuschangehandler) | No| - | Callback function triggered when the foldable device enters or exits the hover state.| +| onHoverStatusChange | [OnHoverStatusChangeHandler](#onhoverstatuschangehandler) | No| - | Callback function triggered when the foldable device enters or exits the hover state.| ## ExpandedRegionLayoutOptions @@ -84,17 +86,17 @@ Defines the layout information for the hover state. ## FoldedRegionLayoutOptions +Defines the layout information for the folded state. + **Atomic service API**: This API can be used in atomic services since API version 12. **System capability**: SystemCapability.ArkUI.ArkUI.Full -Defines the layout information for the folded state. - | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | verticalSplitRatio | number | No| Height ratio between the primary and secondary regions. Default value: **PresetSplitRatio.LAYOUT_1V1**| -## onHoverStatusChangeHandler +## OnHoverStatusChangeHandler type OnHoverStatusChangeHandler = (status: HoverModeStatus) => void @@ -112,7 +114,7 @@ Implements a handler for the **onHoverStatusChange** event. ## HoverModeStatus -Defines the layout information for the folded state. +Provides information about the device or application's folding, rotation, and window state. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -120,10 +122,10 @@ Defines the layout information for the folded state. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| foldStatus | [display.FoldStatus10+](../js-apis-display.md#foldstatus10) | Yes| Fold status of the device.| +| foldStatus | [display.FoldStatus](../js-apis-display.md#foldstatus10) | Yes| Fold status of the device.| | isHoverMode | boolean | Yes| Whether the application is in the hover state.| | appRotation | number | Yes| Rotation angle of the application.| -| windowStatusType | [window.WindowStatusType11+](../js-apis-window.md#windowstatustype11) | Yes| Window mode.| +| windowStatusType | [window.WindowStatusType](../js-apis-window.md#windowstatustype11) | Yes| Window mode.| ## ExtraRegionPosition @@ -148,9 +150,9 @@ Enumerates the split ratios. | Name| Value| Description| | -------- | -------- | -------- | -| LAYOUT_1V1 | 1/1 | 1:1.| -| LAYOUT_3V2 | 3/2 | 3:2.| -| LAYOUT_2V3 | 2/3 | 2:3.| +| LAYOUT_1V1 | 1 | 1:1.| +| LAYOUT_3V2 | 1.5 | 3:2.| +| LAYOUT_2V3 | 0.6666666666666666 | 2:3.| ## Example diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-FullScreenLaunchComponent.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-FullScreenLaunchComponent.md index a74b69b41fa6baf466f137947088da6bc8386d86..0d773e7f8e2794b97bc6fa56cd2a9a188182236f 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-FullScreenLaunchComponent.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-FullScreenLaunchComponent.md @@ -13,7 +13,7 @@ ## Modules to Import -``` +```ts import { FullScreenLaunchComponent } from '@kit.ArkUI' ``` @@ -23,30 +23,31 @@ import { FullScreenLaunchComponent } from '@kit.ArkUI' Not supported ## Attributes -The [universal attributes](ts-universal-attributes-size.md) are not supported. +The [universal attributes](ts-component-general-attributes.md) are not supported. + +## Events +The [universal events](ts-component-general-events.md) are not supported. ## FullScreenLaunchComponent -FullScreenLaunchComponent({ content: Callback\, appId: string, options?: AtomicServiceOptions }) +FullScreenLaunchComponent({ content: Callback\, appId: string, options?: AtomicServiceOptions, onError?: ErrorCallback, onTerminated?: Callback\ }) **Decorator**: \@Component -**Atomic service API**: This API can be used in atomic services since API version 12. - **System capability**: SystemCapability.ArkUI.ArkUI.Full - -**Parameters** - - | Name| Type| Mandatory| Decorator Type| Description| | -------- | -------- | -------- | -------- | -------- | -| content | Callback\ | Yes| \@BuilderParam | Content displayed in the component.| -| appId | string | Yes| - | Application ID for the atomic service.| -| options | [AtomicServiceOptions](../../apis-ability-kit/js-apis-app-ability-atomicServiceOptions.md) | No| - | Parameters for launching the atomic service.| +| content | Callback\ | Yes| \@BuilderParam | Custom placeholder icon displayed before launching the atomic service. This allows you to create a large launch icon similar to those used by desktop applications. Clicking the placeholder icon will launch the atomic service.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| appId | string | Yes| - | Application ID of the atomic service to be launched. It is the unique identifier for the atomic service.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| options | [AtomicServiceOptions](../../apis-ability-kit/js-apis-app-ability-atomicServiceOptions.md) | No| - | Parameters for launching the atomic service.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| onError18+ | [ErrorCallback](../../apis-basic-services-kit/js-apis-base.md#errorcallback) | No| - | Triggered when an exception occurs during the execution of an embedded atomic service. You can obtain the error information based on the **code**, **name**, and **message** parameters in the callback and rectify the exception accordingly.
**Atomic service API**: This API can be used in atomic services since API version 18.| +| onTerminated18+ | [Callback](../../apis-basic-services-kit/js-apis-base.md#callback)\<[TerminationInfo](ts-container-embedded-component.md#terminationinfo)> | No| - | Triggered when an embedded atomic service exits properly by calling [terminateSelfWithResult](../../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) or [terminateSelf](../../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself).
**Atomic service API**: This API can be used in atomic services since API version 18.| -## Events -The [universal events](ts-universal-events-click.md) are not supported. +> **NOTE** +> +> - If the atomic service exits by calling [terminateSelfWithResult](../../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult), the information it carries is passed to the callback parameter. +> - If the atomic service exits by calling [terminateSelf](../../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself), the callback parameter has a default **code** value of **0** and **want** of **undefined**. ## Example @@ -56,7 +57,7 @@ import { FullScreenLaunchComponent } from '@kit.ArkUI'; @Entry @Component struct Index { - @State appId: string = '6918661953712445909'; + @State appId: string = '6918661953712445909'; // Application ID of the atomic service. build() { Row() { @@ -64,7 +65,13 @@ struct Index { FullScreenLaunchComponent({ content: ColumChild, appId: this.appId, - options: {} + options: {}, + onTerminated: (info) => { + console.info("onTerminated code: " + info.code.toString()); + }, + onError: (err) => { + console.error("onError code: " + err.code + ", message: ", err.message); + } }).width("80vp").height("80vp") } .width('100%') diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-GridObjectSortComponent.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-GridObjectSortComponent.md index c62bee7767d1ef977c8b7dd30e9fc05d894a7ced..0eda822f10a63584728f3e7acdd109bad40b2fe9 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-GridObjectSortComponent.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-GridObjectSortComponent.md @@ -12,7 +12,7 @@ ## Modules to Import ```ts -import { GridObjectSortComponent, GridObjectSortComponentItem, GridObjectSortComponentOptions, GridObjectSortComponentType } from '@kit.ArkUI' +import { GridObjectSortComponent, GridObjectSortComponentItem, GridObjectSortComponentOptions, GridObjectSortComponentType , SymbolGlyphModifier } from '@kit.ArkUI'; ``` ## Child Components @@ -21,7 +21,7 @@ Not supported ## Attributes -The [universal attributes](ts-universal-attributes-size.md) are supported. +The [universal attributes](ts-component-general-attributes.md) are not supported. ## GridObjectSortComponent @@ -47,14 +47,14 @@ GridObjectSortComponent({options: GridObjectSortComponentOptions, dataList: Arra **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory| Description | -| -------------- | ------------------------- | ---- | ------------------------------------------------------ | +| Name | Type | Mandatory| Description | +| -------------- | ------------------------- | ---- |-------------------------------------------------------------| | type | [GridObjectSortComponentType](#gridobjectsortcomponenttype) | No | Component display form: text only or\|text and imagery.
Default value: **GridObjectSortComponentType.text**| -| imageSize | number \| [Resource](ts-types.md#resource) | No | Image size.
Default value: **56** | -| normalTitle | [ResourceStr](ts-types.md#resourcestr) | No | Title displayed in the non-editing state.
Default value: **Channel** | -| showAreaTitle | [ResourceStr](ts-types.md#resourcestr) | No | First subtitle of the display area.
Default value: **Drag to sort**| -| addAreaTitle | [ResourceStr](ts-types.md#resourcestr) | No | Second subtitle of the display area.
Default value: **Touch to add** | -| editTitle | [ResourceStr](ts-types.md#resourcestr) | No | Title displayed in the editing state.
Default value: **Edit** | +| imageSize | number \| [Resource](ts-types.md#resource) | No | Image size, in vp.
The value must be greater than or equal to 0.
Default value: **56vp** | +| normalTitle | [ResourceStr](ts-types.md#resourcestr) | No | Title displayed in the non-editing state.
Default value: **Channel** | +| showAreaTitle | [ResourceStr](ts-types.md#resourcestr) | No | First subtitle of the display area.
Default value: **Drag to sort** | +| addAreaTitle | [ResourceStr](ts-types.md#resourcestr) | No | Second subtitle of the display area.
Default value: **Tap to add** | +| editTitle | [ResourceStr](ts-types.md#resourcestr) | No | Title displayed in the editing state.
Default value: **Edit** | ## GridObjectSortComponentType @@ -69,27 +69,26 @@ GridObjectSortComponent({options: GridObjectSortComponentOptions, dataList: Arra ## GridObjectSortComponentItem -**Atomic service API**: This API can be used in atomic services since API version 12. - **System capability**: SystemCapability.ArkUI.ArkUI.Full | Name | Type | Mandatory| Description | | -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | -| id | number \| string | Yes | Data ID, which must be unique. | -| text | [ResourceStr](ts-types.md#resourcestr) | Yes | Text information. | -| selected | boolean | Yes | Whether the grid object has been added. The value **true** means that grid object has been added, and **false** means the opposite. | -| url | [ResourceStr](ts-types.md#resourcestr) | No | URL of the image. This parameter is required when **GridObjectSortComponentType** is set to **IMAGE_TEXT**.| -| order | number | Yes | Sequence number. | +| id | number \| string | Yes | Data ID, which must be unique.
The default value is an empty string.
**Atomic service API**: This API can be used in atomic services since API version 12. | +| text | [ResourceStr](ts-types.md#resourcestr) | Yes | Text information.
**Atomic service API**: This API can be used in atomic services since API version 12. | +| selected | boolean | Yes | Whether the grid object has been added. The value **true** means that grid object has been added, and **false** means the opposite.
**Atomic service API**: This API can be used in atomic services since API version 12. | +| url | [ResourceStr](ts-types.md#resourcestr) | No | URL of the image. Required when **GridObjectSortComponentType** is set to **IMAGE_TEXT**.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| symbolStyle18+ | [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) | No | Symbol resource of the image. Required when **GridObjectSortComponentType** is set to **IMAGE_TEXT**.
**Atomic service API**: This API can be used in atomic services since API version 18.| +| order | number | Yes | Sequence number.
The value must be greater than or equal to 0.
Default value: **0**
**Atomic service API**: This API can be used in atomic services since API version 12. | ## Events -The [universal events](ts-universal-events-click.md) are not supported. +The [universal events](ts-component-general-events.md) are not supported. ## Example This example illustrates the basic usage of the **GridObjectSortComponent** component, involving component configuration initialization, data initialization, and the use of the save and cancel APIs. ```ts -import { GridObjectSortComponent, GridObjectSortComponentItem, GridObjectSortComponentOptions, GridObjectSortComponentType } from '@kit.ArkUI' +import { GridObjectSortComponent, GridObjectSortComponentItem, GridObjectSortComponentOptions, GridObjectSortComponentType, SymbolGlyphModifier } from '@kit.ArkUI'; @Entry @Component @@ -98,67 +97,32 @@ struct Index { @State dataList: GridObjectSortComponentItem[] = [ { id: 0, - url: $r('app.media.ic_controlcenter_location_filled'), - text: 'Location', + url: $r('sys.media.ohos_save_button_filled'), + text: 'Download', selected: true, order: 3 }, { id: 1, - url: $r('app.media.ic_controlcenter_mobiledata_filled'), - text: 'Mobile data', + url: $r('sys.media.ohos_ic_public_web'), + text: 'Network', selected: true, order: 9 }, { id: 2, - url: $r('app.media.ic_controlcenter_nfc_filled'), - text: 'NFC', + url: $r('sys.media.ohos_ic_public_video'), + text: 'Video', selected: false, order: 1 }, { id: 3, - url: $r('app.media.ic_controlcenter_ring_off_filled'), - text: 'Silent', - selected: true, - order: 4 - }, - { - id: 4, - url: $r('app.media.ic_controlcenter_ring_on_filled'), - text: 'Ring', - selected: false, - order: 5 - }, - { - id: 5, - url: $r('app.media.ic_controlcenter_ultra_power_saver_filled'), - text: 'Low power', - selected: true, - order: 6 - }, - { - id: 6, - url: $r('app.media.ic_controlcenter_screenshot_filled'), - text: 'Screenshot', - selected: true, - order: 7 - }, - { - id: 7, - url: $r('app.media.ic_controlcenter_screen_recording_filled'), - text: 'Screen recording', - selected: true, - order: 8 - }, - { - id: 8, - url: $r('app.media.ic_controlcenter_super_power_saver_filled'), - text: 'Ultra power saving', + symbolStyle: new SymbolGlyphModifier($r('sys.symbol.record_circle')), + text: 'Recording', selected: false, - order: 9 - }, + order: 4 + } ] // Initialize the component configuration information. diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-InnerFullScreenLaunchComponent-sys.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-InnerFullScreenLaunchComponent-sys.md index ce7a4b9c4f9784947a25de863a42388fee6aca52..3a19c5b66f425c52de25e4c5c56ccfc92f9e7679 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-InnerFullScreenLaunchComponent-sys.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-InnerFullScreenLaunchComponent-sys.md @@ -22,7 +22,7 @@ import { InnerFullScreenLaunchComponent, LauncherController } from '@kit.ArkUI' Not supported ## Attributes -The [universal attributes](ts-universal-attributes-size.md) are not supported. +The [universal attributes](ts-component-general-attributes.md) are not supported. ## InnerFullScreenLaunchComponent @@ -65,7 +65,7 @@ InnerFullScreenLaunchComponent({ content: Callback\, controller: LaunchCon | options | [AtomicServiceOptions](../../apis-ability-kit/js-apis-app-ability-atomicServiceOptions.md) | No| Parameters for launching the atomic service.| ## Events -The [universal events](ts-universal-events-click.md) are not supported. +The [universal events](ts-component-general-events.md) are not supported. ## Example diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-MultiNavigation.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-MultiNavigation.md index ea7c25dcd44ca09c01805cd2b3f6cfab500ebd56..56faa83c30515f1a117cf9231f77c99ec59c4ae4 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-MultiNavigation.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-MultiNavigation.md @@ -7,6 +7,8 @@ > This component is supported since API version 14. Updates will be marked with a superscript to indicate their earliest API version. > > Due to the nested stack structure of **MultiNavigation**, calling APIs explicitly stated as unsupported in this document or APIs not listed in the supported API list (such as **getParent**, **setInterception**, and **pushDestination**) may lead to unpredictable issues. +> +> In scenarios with deep nesting, **MultiNavigation** may encounter routing animation issues. ## Modules to Import @@ -20,7 +22,7 @@ Not supported ## MultiNavigation -MultiNavigation(navDestination: navDestination, multiStack: MultiNavPathStack, onNavigationModeChange?: OnNavigationModeChangeCallback, onHomeShowOnTop?: OnHomeShowOnTopCallback) +MultiNavigation({navDestination: navDestination, multiStack: MultiNavPathStack, onNavigationModeChange?: OnNavigationModeChangeCallback, onHomeShowOnTop?: OnHomeShowOnTopCallback}) Creates and initializes a **MultiNavigation** component. @@ -32,8 +34,6 @@ The **MultiNavigation** component follows the default left-to-right stack cleari **System capability**: SystemCapability.ArkUI.ArkUI.Full -**Parameters** - | Name | Type | Mandatory | Decorator| Description| |:---------:|:----------------------:|-----| ------ |-----------| | multiStack | [MultiNavPathStack](#multinavpathstack) | Yes | @State | Navigation stack.| @@ -45,6 +45,10 @@ The **MultiNavigation** component follows the default left-to-right stack cleari Implements a navigation stack of the **MultiNavigation** component. Currently, this stack can be created only by the user and cannot be obtained through callbacks. Do not use events or APIs such as **onReady** of **NavDestination** to obtain the navigation stack and perform stack operations, as this may lead to unpredictable issues. +### constructor + +constructor() + **Atomic service API**: This API can be used in atomic services since API version 14. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -55,12 +59,16 @@ pushPath(info: NavPathInfo, animated?: boolean, policy?: SplitPolicy): void Pushes the specified navigation destination page to the navigation stack. +**Atomic service API**: This API can be used in atomic services since API version 14. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | :------: | :----------------------------------------------------------: | :--: | ----------------------------------------- | | info | [NavPathInfo](./ts-basic-components-navigation.md#navpathinfo10) | Yes | Information about the navigation destination page. | -| animated | boolean | No | Whether to support transition animations.
Default value: **true** | +| animated | boolean | No | Whether to support the transition animation.
Default value: **true**
**true**: The transition animation is supported.
**false**: The transition animation is not supported. | | policy | [SplitPolicy](#splitpolicy) | No | Policy for the current page being pushed.
Default value: **DETAIL_PAGE**| ### pushPath @@ -69,6 +77,10 @@ pushPath(info: NavPathInfo, options?: NavigationOptions, policy?: SplitPolicy): Pushes the specified navigation destination page to the navigation stack, with stack operation settings through **NavigationOptions**. +**Atomic service API**: This API can be used in atomic services since API version 14. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Parameters** | Name | Type | Mandatory| Description | @@ -83,29 +95,37 @@ pushPathByName(name: string, param: Object, animated?: boolean, policy?: SplitPo Pushes the navigation destination page specified by **name** to the navigation stack, passing the data specified by **param**. +**Atomic service API**: This API can be used in atomic services since API version 14. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | |:---------------------:|:------------:|:------:| --------------------- | | name | string | Yes | Name of the navigation destination page. | | param | Object | Yes | Detailed parameters of the navigation destination page.| -| animated | boolean | No | Whether to support transition animations.
Default value: **true**| +| animated | boolean | No | Whether to support the transition animation.
Default value: **true**
**true**: The transition animation is supported.
**false**: The transition animation is not supported.| | policy | [SplitPolicy](#splitpolicy) | No | Policy for the current page being pushed.
Default value: **DETAIL_PAGE** | ### pushPathByName -pushPathByName(name: string, param: Object, onPop: Callback\, animated?: boolean, policy?: SplitPolicy): void +pushPathByName(name: string, param: Object, onPop?: base.Callback\, animated?: boolean, policy?: SplitPolicy): void Pushes the navigation destination page specified by **name** to the navigation stack, passing the data specified by **param**. This API uses the **onPop** callback to handle the result returned when the page is popped out of the stack. +**Atomic service API**: This API can be used in atomic services since API version 14. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Parameters** -| Name | Type | Mandatory | Description| +| Name | Type | Mandatory| Description | |:---------:|:-------------------------------------------------------------:|:------:|------| | name | string | Yes | Name of the navigation destination page. | | param | Object | Yes | Detailed parameters of the navigation destination page.| -| onPop | Callback\<[PopInfo](ts-basic-components-navigation.md#popinfo11)> | Yes | Callback used to handle the return result.| -| animated | boolean | No | Whether to support transition animations.
Default value: **true**| +| onPop | base.[Callback](../../apis-basic-services-kit/js-apis-base.md#callback)\<[PopInfo](ts-basic-components-navigation.md#popinfo11)> | No | Callback used to handle the return result.| +| animated | boolean | No | Whether to support the transition animation.
Default value: **true**
**true**: The transition animation is supported.
**false**: The transition animation is not supported.| | policy | [SplitPolicy](#splitpolicy) | No | Policy for the current page being pushed.
Default value: **DETAIL_PAGE** | ### replacePath @@ -114,12 +134,16 @@ replacePath(info: NavPathInfo, animated?: boolean): void Replaces the current top page on the stack with the specified navigation destination page. The new page inherits the split policy of the original top page. +**Atomic service API**: This API can be used in atomic services since API version 14. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | :------: | :----------------------------------------------------------: | :--: | -------------------------------- | | info | [NavPathInfo](./ts-basic-components-navigation.md#navpathinfo10) | Yes | Information about the navigation destination page. | -| animated | boolean | No | Whether to support transition animations.
Default value: **true**| +| animated | boolean | No | Whether to support the transition animation.
Default value: **true**
**true**: The transition animation is supported.
**false**: The transition animation is not supported.| ### replacePath @@ -127,12 +151,16 @@ replacePath(info: NavPathInfo, options?: NavigationOptions): void Replaces the current top page on the stack with the specified navigation destination page, with stack operation settings through **NavigationOptions**. The new page inherits the split policy of the original top page. +**Atomic service API**: This API can be used in atomic services since API version 14. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | :-----: | :----------------------------------------------------------: | :--: | ------------------------------------------ | | info | [NavPathInfo](./ts-basic-components-navigation.md#navpathinfo10) | Yes | Information about the navigation destination page. | -| options | [NavigationOptions](./ts-basic-components-navigation.md#navigationoptions12) | No | Navigation options. Only the **animated** field is supported.| +| options | [NavigationOptions](./ts-basic-components-navigation.md#navigationoptions12) | No | Stack operation settings. Only the **animated** field is supported.| ### replacePathByName @@ -140,13 +168,17 @@ replacePathByName(name: string, param: Object, animated?: boolean): void Replaces the current top page on the stack with the navigation destination page specified by **name**. The new page inherits the split policy of the original top page. +**Atomic service API**: This API can be used in atomic services since API version 14. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | |:--------:|:---------:|:------:|----------------------| | name | string | Yes | Name of the navigation destination page. | | param | Object | Yes | Detailed parameters of the navigation destination page.| -| animated | boolean | No | Whether to support transition animations.
Default value: **true** | +| animated | boolean | No | Whether to support the transition animation.
Default value: **true**
**true**: The transition animation is supported.
**false**: The transition animation is not supported. | ### removeByIndexes @@ -154,11 +186,15 @@ removeByIndexes(indexes: Array): number Removes the navigation destination pages specified by **indexes** from the navigation stack. +**Atomic service API**: This API can be used in atomic services since API version 14. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | |:--------:|:---------------:|:------:| --------------------- | -| indexes | Array | Yes | Array of indexes of the navigation destination pages to remove. | +| indexes | Array | Yes | Array of indexes of the navigation destination pages to remove.
Value range of the number type: [0, +∞)| **Return value** @@ -172,9 +208,13 @@ removeByName(name: string): number Removes the navigation destination page specified by **name** from the navigation stack. +**Atomic service API**: This API can be used in atomic services since API version 14. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | |:-------:| ------- | ---- | --------------------- | | name | string | Yes | Name of the navigation destination page to be removed.| @@ -194,11 +234,15 @@ Pops the top element out of the navigation stack. > > If [keepBottomPage](#keepbottompage) is called with **true**, the bottom page of the navigation stack is retained. +**Atomic service API**: This API can be used in atomic services since API version 14. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | |:-----------:|:--------:|:------:| -------------------- | -| animated | boolean | No | Whether to support transition animations.
Default value: **true**| +| animated | boolean | No | Whether to support the transition animation.
Default value: **true**
**true**: The transition animation is supported.
**false**: The transition animation is not supported.| **Return value** @@ -208,7 +252,7 @@ Pops the top element out of the navigation stack. ### pop -pop(result: Object, animated?: boolean): NavPathInfo | undefined +pop(result?: Object, animated?: boolean): NavPathInfo | undefined Pops the top element out of the navigation stack and invokes the **onPop** callback to pass the page processing result. @@ -216,12 +260,16 @@ Pops the top element out of the navigation stack and invokes the **onPop** callb > > If [keepBottomPage](#keepbottompage) is called with **true**, the bottom page of the navigation stack is retained. +**Atomic service API**: This API can be used in atomic services since API version 14. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | |:---------:|:-------------------------------:|:------:| -------------------- | -| result | Object | Yes | Custom processing result on the page.| -| animated | boolean | No | Whether to support transition animations.
Default value: **true**| +| result | Object | No | Custom processing result on the page.| +| animated | boolean | No | Whether to support the transition animation.
Default value: **true**
**true**: The transition animation is supported.
**false**: The transition animation is not supported.| **Return value** @@ -235,18 +283,22 @@ popToName(name: string, animated?: boolean): number Pops pages until the first navigation destination page that matches **name** from the bottom of the navigation stack is at the top of the stack. +**Atomic service API**: This API can be used in atomic services since API version 14. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | |:----------:|:--------:|:------:| ------------------- | | name | string | Yes | Name of the navigation destination page.| -| animated | boolean | No | Whether to support transition animations.
Default value: **true**| +| animated | boolean | No | Whether to support the transition animation.
Default value: **true**
**true**: The transition animation is supported.
**false**: The transition animation is not supported.| **Return value** | Type | Description | | ------ | ---------------------------------------- | -| number | Returns the index of the first navigation destination page that matches **name** from the bottom of the navigation stack; returns **-1** if no such a page is found.| +| number | Returns the index of the first navigation destination page that matches **name** from the bottom of the navigation stack; returns **-1** if no such a page is found.
Value range: [-1, +∞)| ### popToName @@ -254,13 +306,17 @@ popToName(name: string, result: Object, animated?: boolean): number Pops pages until the first navigation destination page that matches **name** from the bottom of the navigation stack is at the top of the stack. This API uses the **onPop** callback to pass in the page processing result. +**Atomic service API**: This API can be used in atomic services since API version 14. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | |:---------:|:--------:|:------:| ------------------- | | name | string | Yes | Name of the navigation destination page.| | result | Object | Yes | Custom processing result on the page.| -| animated | boolean | No | Whether to support transition animations.
Default value: **true**| +| animated | boolean | No | Whether to support the transition animation.
Default value: **true**
**true**: The transition animation is supported.
**false**: The transition animation is not supported.| **Return value** @@ -274,12 +330,16 @@ popToIndex(index: number, animated?: boolean): void Returns the navigation stack to the page specified by **index**. +**Atomic service API**: This API can be used in atomic services since API version 14. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | |:------------:|:--------:|:------:| ---------------------- | -| index | number | Yes | Index of the navigation destination page.| -| animated | boolean | No | Whether to support transition animations.
Default value: **true**| +| index | number | Yes | Index of the navigation destination page.
Value range: [0, +∞)| +| animated | boolean | No | Whether to support the transition animation.
Default value: **true**
**true**: The transition animation is supported.
**false**: The transition animation is not supported.| ### popToIndex @@ -287,13 +347,17 @@ popToIndex(index: number, result: Object, animated?: boolean): void Returns the navigation stack to the page specified by **index** and invokes the **onPop** callback to pass the page processing result. +**Atomic service API**: This API can be used in atomic services since API version 14. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ----- | ------ | ---- | ---------------------- | | index | number | Yes | Index of the navigation destination page.| | result | Object | Yes| Custom processing result on the page.| -| animated | boolean | No | Whether to support transition animations.
Default value: **true**| +| animated | boolean | No | Whether to support the transition animation.
Default value: **true**
**true**: The transition animation is supported.
**false**: The transition animation is not supported.| ### moveToTop @@ -315,10 +379,16 @@ Moves the first navigation destination page that matches **name** from the botto > > 5. If the found page is a non-topmost full-screen page, it is moved to the top. -| Name | Type | Mandatory | Description | +**Atomic service API**: This API can be used in atomic services since API version 14. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | |:---------:|:--------:|:------:| ------------------- | | name | string | Yes | Name of the navigation destination page.| -| animated | boolean | No | Whether to support transition animations.
Default value: **true**| +| animated | boolean | No | Whether to support the transition animation.
Default value: **true**
**true**: The transition animation is supported.
**false**: The transition animation is not supported.| **Return value** @@ -346,10 +416,16 @@ Moves the navigation destination page specified by **index** to the top of the n > > 5. If the found page is a non-topmost full-screen page, it is moved to the top. -| Name | Type | Mandatory | Description | +**Atomic service API**: This API can be used in atomic services since API version 14. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | |:---------:|:-------:|:------:| ------------------- | -| index | number | Yes | Index of the navigation destination page.| -| animated | boolean | No | Whether to support transition animations.
Default value: **true**| +| index | number | Yes | Index of the navigation destination page.
Value range: [0, +∞)| +| animated | boolean | No | Whether to support the transition animation.
Default value: **true**
**true**: The transition animation is supported.
**false**: The transition animation is not supported.| ### clear @@ -361,11 +437,15 @@ Clears the navigation stack. > > If [keepBottomPage](#keepbottompage) is called with **true**, the bottom page of the navigation stack is retained. +**Atomic service API**: This API can be used in atomic services since API version 14. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | |:---------:|:--------:|:------:| ---------------------- | -| animated | boolean | No | Whether to support transition animations.
Default value: **true**| +| animated | boolean | No | Whether to support the transition animation.
Default value: **true**
**true**: The transition animation is supported.
**false**: The transition animation is not supported.| ### getAllPathName @@ -373,6 +453,10 @@ getAllPathName(): Array Obtains the names of all navigation destination pages in the navigation stack. +**Atomic service API**: This API can be used in atomic services since API version 14. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Return value** | Type | Description | @@ -385,11 +469,15 @@ getParamByIndex(index: number): Object | undefined Obtains the parameter information of the navigation destination page specified by **index**. +**Atomic service API**: This API can be used in atomic services since API version 14. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | |:-------:|:--------:|:------:| ---------------------- | -| index | number | Yes | Index of the navigation destination page.| +| index | number | Yes | Index of the navigation destination page.
Value range: [0, +∞)| **Return value** @@ -404,9 +492,13 @@ getParamByName(name: string): Array Obtains the parameter information of all the navigation destination pages that match **name**. +**Atomic service API**: This API can be used in atomic services since API version 14. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | |:------:|:--------:|:------:| ------------------- | | name | string | Yes | Name of the navigation destination page.| @@ -422,9 +514,13 @@ getIndexByName(name: string): Array Obtains the indexes of all the navigation destination pages that match **name**. +**Atomic service API**: This API can be used in atomic services since API version 14. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | |:------:|:--------:|:------:| ------------------- | | name | string | Yes | Name of the navigation destination page.| @@ -432,7 +528,7 @@ Obtains the indexes of all the navigation destination pages that match **name**. | Type | Description | | -------------- | --------------------------------- | -| Array | Indexes of all the matching navigation destination pages.| +| Array | Indexes of all the matching navigation destination pages.
Value range of the number type: [0, +∞)| ### size @@ -440,23 +536,31 @@ size(): number Obtains the stack size. +**Atomic service API**: This API can be used in atomic services since API version 14. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Return value** | Type | Description | | ------ | ------ | -| number | Stack size.| +| number | Stack size.
Value range: [0, +∞)| ### disableAnimation -disableAnimation(value: boolean): void +disableAnimation(disable: boolean): void Disables or enables the transition animation in the **MultiNavigation** component. +**Atomic service API**: This API can be used in atomic services since API version 14. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ----- | ------ | ---- | ---------------------- | -| value | boolean | No | Whether to disable the transition animation.
Default value: **false**| +| disable | boolean | Yes | Whether to disable the transition animation.
Default value: **false**
**true**:The transition animation is disabled.
**false**: The transition animation is not disabled.| ### switchFullScreenState @@ -464,17 +568,21 @@ switchFullScreenState(isFullScreen?: boolean): boolean Switches the display mode of the current top detail page in the stack. The value **true** means to enable full-screen mode, and **false** means to enable split-screen mode. +**Atomic service API**: This API can be used in atomic services since API version 14. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | :----------: | :-----: | :--: | ----------------------------------------------------- | -| isFullScreen | boolean | Yes | Whether to enable full-screen mode. The value **true** means to enable full-screen mode, and **false** means to enable split-screen mode.| +| isFullScreen | boolean | No | Whether to enable full-screen mode. The value **true** means to enable full-screen mode, and **false** means to enable split-screen mode.| **Return value** | Type | Description | |:--------:|:----------:| -| boolean | Whether the switching is successful. | +| boolean | Whether the switching is successful.
**true**: The switching is successful.
**false**: The switching failed. | ### setHomeWidthRange @@ -482,9 +590,13 @@ setHomeWidthRange(minPercent: number, maxPercent: number): void Sets the draggable range for the home page width. If not set, the width defaults to 50% and is not draggable. +**Atomic service API**: This API can be used in atomic services since API version 14. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | |:-------------:|:--------:|:-----:|-------------------| | minPercent | number | Yes | Minimum width percentage of the home page.| | maxPercent | number | Yes | Maximum width percentage of the home page.| @@ -500,11 +612,15 @@ Sets whether to retain the bottom page when the **pop** or **clear** APIs is cal > **MultiNavigation** treats the home page as a navigation destination page in the stack. By default, calling **pop** or **clea**r will also remove the bottom page. > If this API is called with **TRUE**, **MultiNavigation** will retain the bottom page when the **pop** or **clear** API is called. +**Atomic service API**: This API can be used in atomic services since API version 14. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | |:-------------:|:--------:|:-----:|--------------------| -| keepBottom | boolean | Yes | Whether to retain the bottom page.
Default value: **FALSE**| +| keepBottom | boolean | Yes | Whether to retain the bottom page.
Default value: **false**
**true**: The bottom page is retained.
**false**: The bottom page is not retained.| ### setPlaceholderPage @@ -519,9 +635,13 @@ Sets a placeholder page. > In scenarios where the application's drawable area is less than 600 vp, or when a foldable screen switches from the expanded state to the folded state, or when a tablet switches from landscape to portrait mode, the placeholder page will be automatically removed, resulting in only the home page being shown. > Conversely, when the application's drawable area is greater than or equal to 600 vp, or when a foldable screen switches from the folded state to the expanded state, or when a tablet switches from portrait to landscape mode, the placeholder page will be automatically added to form a split-screen. +**Atomic service API**: This API can be used in atomic services since API version 14. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | |:-------------:|:--------:|:-----:|----------| | info | NavPathInfo | Yes | Information about the placeholder page.| @@ -584,11 +704,11 @@ Represents the callback invoked when the home page is displayed at the top of th ## Attributes -The [universal attributes](ts-universal-attributes-size.md) are not supported. +The [universal attributes](ts-component-general-attributes.md) are not supported. ## Events -The [universal events](ts-universal-events-click.md) are not supported. +The [universal events](ts-component-general-events.md) are not supported. ## Example @@ -637,7 +757,7 @@ struct Index { } } ``` - + ```typescript // pages/PageHome1.ets, corresponding to the home page import { MultiNavPathStack, SplitPolicy } from '@ohos.arkui.advanced.MultiNavigation'; @@ -847,7 +967,7 @@ export struct PageHome1 { } } ``` - + ```typescript // pages/PageDetail1.ets: detail page import { MultiNavPathStack, SplitPolicy } from '@ohos.arkui.advanced.MultiNavigation'; @@ -1067,7 +1187,7 @@ export struct PageDetail1 { } } ``` - + ```typescript // pages/PageDetail2.ets: detail page import { MultiNavPathStack, SplitPolicy } from '@ohos.arkui.advanced.MultiNavigation'; @@ -1229,7 +1349,7 @@ export struct PageDetail2 { } } ``` - + ```typescript // pages/PageFull1.ets: page that does not participate in split-screen display and is displayed in full-screen mode by default import { MultiNavPathStack, SplitPolicy } from '@ohos.arkui.advanced.MultiNavigation'; @@ -1363,7 +1483,7 @@ export struct PageFull1 { } } ``` - + ```typescript // pages/PagePlaceholder.ets: placeholder page import { MultiNavPathStack, SplitPolicy } from '@ohos.arkui.advanced.MultiNavigation'; diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-Popup.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-Popup.md index 96cbe5de877697a3813683f09a16138e6aca3a13..073e58e1890c7499ee6570abf78db1c2784f8d31 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-Popup.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-Popup.md @@ -38,19 +38,18 @@ Popup(options: PopupOptions): void Defines the style parameters of the popup. -**Atomic service API**: This API can be used in atomic services since API version 12. - **System capability**: SystemCapability.ArkUI.ArkUI.Full | Name | Type | Mandatory | Description | | ----------- | ---------- | ------| --------------------------------- | -| icon | [PopupIconOptions](#popupiconoptions) | No | Icon of the popup.
**NOTE**
The icon is not displayed when **size** is set to an invalid value or **0**.| -| title | [PopupTextOptions](#popuptextoptions) | No | Title of the popup. | -| message | [PopupTextOptions](#popuptextoptions) | Yes | Content of the popup.
**NOTE**
**fontWeight** is not available for **messages**.| -| showClose | boolean \| [Resource](ts-types.md#resource) | No | Whether to show the close button.
Default value: **true**| -| onClose | () => void | No | Callback for the popup close button.| -| buttons | [[PopupButtonOptions](#popupbuttonoptions)?,[PopupButtonOptions](#popupbuttonoptions)?] | No | Buttons of the popup. A maximum of two buttons can be set.| -| direction12+ | [Direction](ts-appendix-enums.md#direction) | No | Layout direction.
Default value: **Direction.Auto** | +| icon | [PopupIconOptions](#popupiconoptions) | No | Icon of the popup.
**NOTE**
The icon is not displayed when **size** is set to an invalid value or **0**.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| title | [PopupTextOptions](#popuptextoptions) | No | Title of the popup.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| message | [PopupTextOptions](#popuptextoptions) | Yes | Content of the popup.
**NOTE**
**fontWeight** is not available for **messages**.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| showClose | boolean \| [Resource](ts-types.md#resource) | No | Whether to show the close button.
Default value: **true**
**Atomic service API**: This API can be used in atomic services since API version 12.| +| onClose | () => void | No | Callback for the popup close button.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| buttons | [[PopupButtonOptions](#popupbuttonoptions)?,[PopupButtonOptions](#popupbuttonoptions)?] | No | Buttons of the popup. A maximum of two buttons can be set.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| direction12+ | [Direction](ts-appendix-enums.md#direction) | No | Layout direction.
Default value: **Direction.Auto**
**Atomic service API**: This API can be used in atomic services since API version 12.| +| maxWidth18+ | [Dimension](ts-types.md#dimension10) | No | Maximum width of the popup. This API allows you to display the popup with a custom width.
Default value: 400 vp
**Atomic service API**: This API can be used in atomic services since API version 18.| ## PopupTextOptions @@ -63,9 +62,9 @@ Defines the text parameters of the popup. | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------ | | text | [ResourceStr](ts-types.md#resourcestr) | Yes | Text content. | -| fontSize | number \| string \| [Resource](ts-types.md#resource) | No | Text font size.
Default value: **$r('sys.float.ohos_id_text_size_body2')** | +| fontSize | number \| string \| [Resource](ts-types.md#resource) | No | Text font size.
Default value: **$r('sys.float.ohos_id_text_size_body2')**
The string value must be convertible to a number (for example, **'10'**) or include a length unit (for example, **'10px'**); percentage-based strings are not supported.
Value range of number values: (0, +∞)| | fontColor | [ResourceColor](ts-types.md#resourcecolor) | No | Text font color.
Default value: **$r('sys.color.ohos_id_color_text_secondary')**| -| fontWeight | number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string | No | Text font weight.
Default value: **FontWeight.Regular**| +| fontWeight | number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string | No | Text font weight.
For the number type, the value ranges from 100 to 900, at an interval of 100. A larger value indicates a heavier font weight. The default value is **400**.
For the string type, only strings of the number type are supported, for example, **"400"**, **"bold"**, **"bolder"**, **"lighter"**, **"regular"**, and **"medium"**, which correspond to the enumerated values in **FontWeight**.
Default value: **FontWeight.Regular**| ## PopupButtonOptions @@ -84,7 +83,7 @@ Defines the button attributes and events. ## PopupIconOptions -Defines the attributes of the icon (in the upper right corner). +Defines the attributes of the icon (in the upper left corner). **Atomic service API**: This API can be used in atomic services since API version 12. @@ -170,8 +169,8 @@ struct PopupExample { ![](figures/popup_7.png) -### Example 2: Implementing a Mirroring Effect -This example shows how to achieve a mirroring effect for a popup by configuring **direction**. +### Example 2: Implementing a Mirror Effect +This example shows how to achieve a mirror effect for a popup by configuring **direction**. ```ts // xxx.ets @@ -242,3 +241,68 @@ struct PopupPage { ``` ![](figures/popup_8.png) + +### Example 3: Setting the Custom Width +This example demonstrates how to set the custom width for a popup using **maxWidth**. + +```ts +// xxx.ets +import { Popup, PopupTextOptions, PopupButtonOptions, PopupIconOptions } from '@kit.ArkUI' + +@Entry +@Component +struct PopupPage { + @State currentDirection: Direction = Direction.Rtl + + build() { + Row() { + // Define a popup. + Popup({ + // Set the custom width. + maxWidth:'50%', + // Set the icon through PopupIconOptions. + icon: { + image: $r('app.media.startIcon'), + width: 32, + height: 32, + fillColor: Color.White, + borderRadius: 16, + } as PopupIconOptions, + // Set the text through PopupTextOptions. + message: { + text: 'This is the message. This is the message. This is the message. This is the message.', + fontSize: 15, + fontColor: Color.Black + } as PopupTextOptions, + showClose: false, + onClose: () => { + console.info('close Button click') + }, + // Set the button through PopupButtonOptions. + buttons: [{ + text: 'OK', + action: () => { + console.info('confirm button click') + }, + fontSize: 15, + fontColor: Color.Black, + }, + { + text: 'Cancel', + action: () => { + console.info('cancel button click') + }, + fontSize: 15, + fontColor: Color.Black + },] as [PopupButtonOptions?, PopupButtonOptions?] + }) + } + .width(400) + .height(200) + .borderWidth(2) + .justifyContent(FlexAlign.Center) + } +} +``` + +![](figures/popup_9.png) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ProgressButton.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ProgressButton.md index d1e27379cd9fd321922df341b5b400a2a16013d8..574d6e8b9d1bc4b909765efe9d83c09016465398 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ProgressButton.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ProgressButton.md @@ -16,45 +16,45 @@ import { ProgressButton } from '@kit.ArkUI' ``` ## Attributes -The [universal attributes](ts-universal-attributes-size.md) are not supported. +The [universal attributes](ts-component-general-attributes.md) are not supported. ## ProgressButton -ProgressButton({progress: number, content: string, progressButtonWidth?: Length, clickCallback: () => void, enable: boolean}) +ProgressButton({progress: number, content: string, progressButtonWidth?: Length, clickCallback: () => void, enable: +boolean, colorOptions?: ProgressButtonColorOptions, progressButtonRadius?: LengthMetrics}) **Decorator**: @Component -**Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory| Decorator | Description | -|-----------------------------------|---------------------------------------------------------------|----|--------|---------------------------------------------------------------------------------| -| progress | number | Yes | \@Prop | Current download progress. | -| content | string | Yes | \@Prop | Button text. | -| progressButtonWidth | [Length](ts-types.md#length) | No | - | Width of the button.
Default value: **44** | -| clickCallback | () => void | Yes | - | Callback invoked when the button is clicked. | -| enable | boolean | Yes | \@Prop | Whether the button can be clicked.
**true**: The button can be clicked.
**false**: The button cannot be clicked. | -| colorOptions16+ | [ProgressButtonColorOptions](#progressbuttoncoloroptions16) | No | \@Prop | Color options of the button. | -| progressButtonRadius16+ | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | No | \@Prop | Corner radius of the button. It cannot be set in percentage.
Value range: [0, height/2]
Default value: height/2
If an invalid value is set, the default value is used.| +| Name | Type | Mandatory| Decorator | Description | +|-----------------------------------|---------------------------------------------------------------|----|--------|--------------------------------------------------------------------------------------------------------------------------------------| +| progress | number | Yes | \@Prop | Current download progress.
The value ranges from 0 to 100. Values less than 0 are adjusted to **0**, and values greater than 100 are capped at **100**.
Default value: **0**
**Atomic service API**: This API can be used in atomic services since API version 11. | +| content | string | Yes | \@Prop | Button text.
The default value is an empty string.
**NOTE**
The text is truncated with an ellipsis (...) if it exceeds the maximum display width of the component.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| progressButtonWidth | [Length](ts-types.md#length) | No | - | Button width, in vp.
The value must be greater than or equal to 44 vp.
The default value is **44vp**. Values less than the default value and invalid values are adjusted to the default value.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| clickCallback | () => void | Yes | - | Callback invoked when the button is clicked.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| enable | boolean | Yes | \@Prop | Whether the button can be clicked.
**true**: The button can be clicked.
**false**: The button cannot be clicked.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| colorOptions18+ | [ProgressButtonColorOptions](#progressbuttoncoloroptions18) | No | \@Prop | Color options of the button.
**Atomic service API**: This API can be used in atomic services since API version 18. | +| progressButtonRadius18+ | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | No | \@Prop | Corner radius of the button. It cannot be set in percentage.
Value range: [0, height/2]
Default value: height/2
If an invalid value is set, the default value is used.
**Atomic service API**: This API can be used in atomic services since API version 18.| -## ProgressButtonColorOptions16+ +## ProgressButtonColorOptions18+ Defines the color options for the download button. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Attributes | Type | Mandatory| Description | -|-----------------|----------------------------------------|----|---------| -| progressColor | [ResourceStr](ts-types.md#resourcestr) | No | Color of the progress indicator. | -| borderColor | [ResourceStr](ts-types.md#resourcestr) | No | Border color of the button.| -| textColor | [ResourceStr](ts-types.md#resourcestr) | No | Text color of the button.| -| backgroundColor | [ResourceStr](ts-types.md#resourcestr) | No | Background color of the button. | +| Name | Type | Mandatory| Description | +|-----------------|----------------------------------------|----|-------------------------------------------------------------------| +| progressColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the progress indicator.
Default value: **#330A59F7** | +| borderColor | [ResourceColor](ts-types.md#resourcecolor) | No | Border color of the button.
Default value: **#330A59F7** | +| textColor | [ResourceColor](ts-types.md#resourcecolor) | No | Text color of the button.
Default value: system default value | +| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | No | Background color of the button.
Default value: **\$r('sys.color.ohos_id_color_foreground_contrary')**| ## Events -The [universal events](ts-universal-events-click.md) are not supported. +The [universal events](ts-component-general-events.md) are not supported. ## Example diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ProgressButtonV2.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ProgressButtonV2.md new file mode 100644 index 0000000000000000000000000000000000000000..0a962d05e192d9aaa0acc7f328ae9b13a4bdd301 --- /dev/null +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ProgressButtonV2.md @@ -0,0 +1,159 @@ +# ProgressButtonV2 + + +The **ProgressButtonV2** component is a download button with a progress indicator that shows the download progress. + +This component is implemented based on [state management V2](../../../quick-start/arkts-state-management-overview.md#state-management-v2). Compared with [state management V1](../../../quick-start/arkts-state-management-overview.md#state-management-v1), V2 offers a higher level of observation and management over data objects beyond the component level. You can now more easily manage download button data and states with greater flexibility, leading to faster UI updates. + + +> **NOTE** +> +> - This component is supported since API version 18. Updates will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + +``` +import { ColorMetrics, LengthMetrics, ProgressButtonV2, ProgressButtonV2Color } from '@kit.ArkUI' +``` + +## ProgressButtonV2 + +ProgressButtonV2({progress: number, content: ResourceStr, progressButtonWidth?: LengthMetrics, onClicked: ClickCallback, +isEnabled: boolean, colorOptions?: ProgressButtonColorOptions, progressButtonRadius?: LengthMetrics}) + +The **ProgressButton** component is a download button with a progress indicator that shows the download progress. + +**Decorator**: \@ComponentV2 + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Decorator | Description | +|-----------------------------------|---------------------------------------------------------------|----|------------------------|------------------------------------------------------------------------------------| +| progress | number | Yes | \@Require
\@Param | Current download progress.
The value ranges from 0 to 100. Values less than 0 are adjusted to **0**, and values greater than 100 are capped at **100**.
Default value: **0** | +| content | [ResourceStr](ts-types.md#resourcestr) | Yes | \@Require
\@Param | Button text. | +| progressButtonWidth | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | No | \@Param
\@Once | Width of the button.
Default value: **44vp** | +| onClicked | [ClickCallback](#clickcallback) | Yes | \@Param | Callback invoked when the button is clicked. | +| isEnabled | boolean | Yes | \@Param | Whether the button can be clicked.
**true**: The button can be clicked.
**false**: The button cannot be clicked.| +| colorOptions | [ProgressButtonV2Color](#progressbuttonv2color) | No | \@Param | Color options for the button.
Default value: **undefined** | +| progressButtonRadius18+ | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | No | \@Param | Corner radius of the button. It cannot be set in percentage.
Value range: [0, height/2]
Default value: height/2
If an invalid value is set, the default value is used. | + +## Attributes +The [universal attributes](ts-component-general-attributes.md) are not supported. + +## ClickCallback + +type ClickCallback = () => void + +Callback invoked when the button is clicked. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +## ProgressButtonV2Color +Defines the color options for the download button. + +**Decorator type**: @ObservedV2 + +### Properties + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Decorator | Description | +|-----------------|--------------|----|---------|---------------------------| +| progressColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | No | \@Trace | Color of the progress indicator.
Default value: **undefined** | +| borderColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | No | \@Trace | Border color of the button.
Default value: **undefined**| +| textColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | No | \@Trace | Text color of the button.
Default value: **undefined**| +| backgroundColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | No | \@Trace | Background color of the button.
Default value: **undefined**| + +### constructor +constructor(options: ProgressButtonV2ColorOptions); + +A constructor used to create a **ProgressButtonV2Color** object. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Description | +|---------|------------------------------|----|-------| +| options | ProgressButtonV2ColorOptions | Yes | Color settings.| + +## ProgressButtonV2ColorOptions + +Provides options for customizing the color of the download button. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Description | +|-----------------|--------------|----|----------------------------| +| progressColor | ColorMetrics | No | Color of the progress indicator.
Default value: **undefined** | +| borderColor | ColorMetrics | No | Border color of the button.
Default value: **undefined**| +| textColor | ColorMetrics | No | Text color of the button.
Default value: **undefined**| +| backgroundColor | ColorMetrics | No | Background color of the button.
Default value: **undefined**| + +## Events +The [universal events](ts-component-general-events.md) are not supported. + +## Example + +This example demonstrates how to create a simple download button with a progress indicator that shows the loading status of a text file. +```ts +import { ColorMetrics, LengthMetrics, ProgressButtonV2, ProgressButtonV2Color } from '@kit.ArkUI' + +@Entry +@ComponentV2 +struct Index { + @Local progressIndex: number = 0; + @Local textState: string = 'Download'; + @Local ButtonWidth: LengthMetrics = LengthMetrics.vp(200); + @Local isRunning: boolean = false; + @Local enableState: boolean = true; + + build() { + Column() { + Scroll() { + Column({ space: 20 }) { + ProgressButtonV2({ + progress: this.progressIndex, + progressButtonWidth: this.ButtonWidth, + content: this.textState, + isEnabled: this.enableState, + onClicked: () => { + if (this.textState && !this.isRunning && this.progressIndex < 100) { + this.textState = 'Continue'; + } + this.isRunning = !this.isRunning; + let timer = setInterval(() => { + if (this.isRunning) { + if (this.progressIndex === 100) { + + } else { + this.progressIndex++ + if (this.progressIndex === 100) { + this.textState = 'Completed'; + this.enableState = false; + } + } + } else { + clearInterval(timer); + } + }, 20); + } + }) + }.alignItems(HorizontalAlign.Center).width('100%').margin({ top: 20 }); + } + } + } +} +``` + + +![img.png](./figures/img.png) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-SegmentButton.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-SegmentButton.md index 5bf3c539ae4474caa981b7f75b53ee0d2c0a5f18..b4047fd011332981d98c16baeb65a84ca751f282 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-SegmentButton.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-SegmentButton.md @@ -29,7 +29,7 @@ SegmentButton({ options: SegmentButtonOptions, selectedIndexes: number[], onItem | options | [SegmentButtonOptions](#segmentbuttonoptions) | Yes | @ObjectLink | Options of the **SegmentButton** component.
**Atomic service API**: This API can be used in atomic services since API version 12.| | selectedIndexes | number[] | Yes | @Link | Indexes of selected items of the **SegmentButton**. The index starts from 0 and increments by 1.
**NOTE**
**selectedIndexes** is decorated with [@Link](../../../quick-start/arkts-link.md) to implement parent-child two-way synchronization. If no items are selected, an empty array **[]** can be passed in.
**Atomic service API**: This API can be used in atomic services since API version 12.| | onItemClicked13+ | Callback\ | No| - | Callback invoked when an item in the **SegmentButton** is clicked. The index of the clicked item is passed in as the parameter.
**Atomic service API**: This API can be used in atomic services since API version 13.| -| maxFontScale14+ | number \| [Resource](ts-types.md#resource) | No| @Prop | Maximum font scale for the text in the **SegmentButton**.
Default value: **1**
Value range: [1, 2]
**NOTE**
Values less than 1 are treated as 1, and values greater than 2 are treated as 2.
**Atomic service API**: This API can be used in atomic services since API version 14.| +| maxFontScale14+ | number \| [Resource](ts-types.md#resource) | Yes| @Prop | Maximum font scale for the text in the **SegmentButton**.
Default value: **1**
Value range: [1, 2]
**NOTE**
Values less than 1 are treated as 1, and values greater than 2 are treated as 2.
**Atomic service API**: This API can be used in atomic services since API version 14.| >**NOTE** > @@ -39,18 +39,18 @@ SegmentButton({ options: SegmentButtonOptions, selectedIndexes: number[], onItem Provides initial data and custom properties for the **SegmentButton** component. -### Properties - **Decorator Type**: @Observed **Atomic service API**: This API can be used in atomic services since API version 12. **System capability**: SystemCapability.ArkUI.ArkUI.Full +### Properties + | Name | Type | Mandatory | Description | | ----------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | | type | 'tab' \| 'capsule' | Yes | Type of the **SegmentButton**. | -| multiply | boolean | Yes | Whether multiple items can be selected.
**NOTE**
For the **SegmentButton** component consisting of tab-style buttons, only one item can be selected. In this case, setting **multiply** to **true** does not take effect.| +| multiply | boolean | Yes | Whether multiple items can be selected.
**NOTE**
The default value is **false**.
**true**: Multiple items can be selected.
**false**: Multiple items cannot be selected. For the **SegmentButton** component consisting of tab-style buttons, only one item can be selected. In this case, setting **multiply** to **true** does not take effect.| | buttons | [SegmentButtonItemOptionsArray](#segmentbuttonitemoptionsarray) | Yes| Button information, including the icon and text. | | fontColor | [ResourceColor](ts-types.md#resourcecolor) | Yes | Font color of the unselected item.
Default value: **$r('sys.color.ohos_id_color_text_secondary')**| | selectedFontColor | [ResourceColor](ts-types.md#resourcecolor) | Yes | Font color of the selected item.
Default value: **$r('sys.color.ohos_id_color_text_primary')** when **type** is **"tab"** and **$r('sys.color.ohos_id_color_foreground_contrary')** when **type** is **"capsule"**| @@ -664,15 +664,20 @@ struct Index { buttons: [{ text: 'Tab 1' }, { text: 'Tab 2' }, { text: 'Tab 3' }] as ItemRestriction, - backgroundColor: Color.Green, - selectedBackgroundColor: Color.Orange, - textPadding: { top: 10, right: 10, bottom: 10, left: 10 }, + backgroundColor: 'rgb(213,213,213)', + selectedBackgroundColor: 'rgb(112,112,112)', + textPadding: { + top: 10, + right: 10, + bottom: 10, + left: 10 + }, }) @State singleSelectCapsuleOptions: SegmentButtonOptions = SegmentButtonOptions.capsule({ buttons: [{ text: 'Single-select 1' }, { text: 'Single-select 2' }, { text: 'Single-select 3' }] as SegmentButtonItemTuple, multiply: false, - fontColor: Color.Black, - selectedFontColor: Color.Yellow, + fontColor: 'rgb(0,74,175)', + selectedFontColor: 'rgb(247,247,247)', backgroundBlurStyle: BlurStyle.BACKGROUND_THICK }) @State multiplySelectCapsuleOptions: SegmentButtonOptions = SegmentButtonOptions.capsule({ @@ -692,7 +697,12 @@ struct Index { ] as SegmentButtonItemTuple, multiply: false, imageSize: { width: 40, height: 40 }, - buttonPadding: { top: 6, right: 10, bottom: 6, left: 10 }, + buttonPadding: { + top: 6, + right: 10, + bottom: 6, + left: 10 + }, backgroundBlurStyle: BlurStyle.BACKGROUND_THICK }) @State iconTextCapsuleOptions: SegmentButtonOptions = SegmentButtonOptions.capsule({ @@ -717,14 +727,22 @@ struct Index { Column() { Column({ space: 20 }) { SegmentButton({ options: this.tabOptions, selectedIndexes: $tabSelectedIndexes }) - SegmentButton({ options: this.singleSelectCapsuleOptions, - selectedIndexes: $singleSelectCapsuleSelectedIndexes }) - SegmentButton({ options: this.multiplySelectCapsuleOptions, - selectedIndexes: $multiplySelectCapsuleSelectedIndexes }) - SegmentButton({ options: this.iconCapsuleOptions, - selectedIndexes: $singleSelectIconCapsuleSelectedIndexes }) - SegmentButton({ options: this.iconTextCapsuleOptions, - selectedIndexes: $multiplySelectIconTextCapsuleSelectedIndexes }) + SegmentButton({ + options: this.singleSelectCapsuleOptions, + selectedIndexes: $singleSelectCapsuleSelectedIndexes + }) + SegmentButton({ + options: this.multiplySelectCapsuleOptions, + selectedIndexes: $multiplySelectCapsuleSelectedIndexes + }) + SegmentButton({ + options: this.iconCapsuleOptions, + selectedIndexes: $singleSelectIconCapsuleSelectedIndexes + }) + SegmentButton({ + options: this.iconTextCapsuleOptions, + selectedIndexes: $multiplySelectIconTextCapsuleSelectedIndexes + }) }.width('90%') }.width('100%') }.height('100%') diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-SegmentButtonV2.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-SegmentButtonV2.md new file mode 100644 index 0000000000000000000000000000000000000000..8b759fc395f81f6874da00b52cd4b3380e3e5965 --- /dev/null +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-SegmentButtonV2.md @@ -0,0 +1,815 @@ +# SegmentButtonV2 + +**SegmentButtonV2** is a component used to create tab-style, single-select, and multi-select capsule-style buttons. + +> **NOTE** +> +> This component and its child components are supported since API version 18. Updates will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +``` +import { TabSegmentButtonV2, CapsuleSegmentButtonV2, MultiCapsuleSegmentButtonV2, SegmentButtonV2Items } from '@kit.ArkUI'; +``` + +## Child Components + +Not supported + +## TabSegmentButtonV2 + +```ts +TabSegmentButtonV2({ + items: SegmentButtonV2Items, + selectedIndex: number, + $selectedIndex?: OnSelectedIndexChange, + onItemClicked?: Callback, + itemMinFontScale?: number | Resource, + itemMaxFontScale?: number | Resource, + itemSpace?: LengthMetrics, + itemFontSize?: LengthMetrics, + itemSelectedFontSize?: LengthMetrics, + itemFontColor?: ColorMetrics, + itemSelectedFontColor?: ColorMetrics, + itemFontWeight?: FontWeight, + itemSelectedFontWeight?: FontWeight, + itemBorderRadius?: LengthMetrics, + itemSelectedBackgroundColor?: ColorMetrics, + itemIconSize?: SizeT, + itemIconFillColor?: ColorMetrics, + itemSelectedIconFillColor?: ColorMetrics, + itemSymbolFontSize?: LengthMetrics, + itemSymbolFontColor?: ColorMetrics, + itemSelectedSymbolFontColor?: ColorMetrics, + itemMinHeight?: LengthMetrics, + itemPadding?: LocalizedPadding, + itemShadow?: ShadowOptions | ShadowStyle, + buttonBackgroundColor?: ColorMetrics, + buttonBackgroundBlurStyle?: BlurStyle, + buttonBackgroundBlurStyleOptions?: BackgroundBlurStyleOptions, + buttonBackgroundEffect?: BackgroundEffectOptions, + buttonBorderRadius?: LengthMetrics, + buttonMinHeight?: LengthMetrics, + buttonPadding?: LengthMetrics, + languageDirection?: Direction +}) +``` + +**Decorator**: @ComponentV2 + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Read-Only| Optional| Decorator | Description | +| -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | ---- | ---- | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| items | [SegmentButtonV2Items](#segmentbuttonv2items) | Yes | No | @Require
@Param | Items of the **TabSegmentButtonV2** component. | +| selectedIndex | number | Yes | No | @Require
@Param | Index of the selected item of the **TabSegmentButtonV2** component. | +| $selectedIndex | [OnSelectedIndexChange](#onselectedindexchange) | No | Yes | @Event | Callback invoked when the selected item of the **TabSegmentButtonV2** component changes. | +| onItemClicked | Callback\ | No | Yes | @Event | Callback invoked when an item in the **TabSegmentButtonV2** component is clicked. | +| buttonBackgroundColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | Yes | Yes | @Param | Background color of the **TabSegmentButtonV2** component.
Default value: **$r('sys.color.segment_button_v2_tab_button_background')** | +| buttonBackgroundBlurStyle | [BlurStyle](ts-universal-attributes-background.md#blurstyle9) | Yes | Yes | @Param | Background blur style of the **TabSegmentButtonV2** component. | +| buttonBackgroundBlurStyleOptions | [BackgroundBlurStyleOptions](ts-universal-attributes-background.md#backgroundblurstyleoptions10) | Yes | Yes | @Param | Background blur style options of the **TabSegmentButtonV2** component. | +| buttonBackgroundEffect | [BackgroundEffectOptions](ts-universal-attributes-background.md#backgroundeffectoptions11) | Yes | Yes | @Param | Background blur effect options of the **TabSegmentButtonV2** component. | +| buttonBorderRadius | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes | Yes | @Param | Radius of the background rounded corner.
Value range: [0, +∞)
Default value: **$r('sys.float.segment_button_v2_background_corner_radius')** | +| buttonMinHeight | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes | Yes | @Param | Minimum height of the **TabSegmentButtonV2** component.
Value range: [0, +∞)
Default value: **$r('sys.float.segment_button_v2_singleline_background_height')** for text-only buttons and icon-only buttons, and **$r('sys.float.segment_button_v2_doubleline_background_height')** for buttons with both an icon and text. | +| buttonPadding | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes | Yes | @Param | Padding of the **TabSegmentButtonV2** component.
Value range: [0, +∞)
Default value: **$r('sys.float.padding_level1')** | +| onItemClicked | Callback\ | Yes | Yes | @Event | Callback invoked when an item in the **TabSegmentButtonV2** component is clicked. | +| itemSelectedBackgroundColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | Yes | Yes | @Param | Background color of the selected item of the **TabSegmentButtonV2** component.
Default value: **$r('sys.color.segment_button_v2_tab_selected_item_background')** | +| itemMinHeight | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes | Yes | @Param | Minimum height of the item of the **TabSegmentButtonV2** component.
Value range: [0, +∞)
Default value:
**$r('sys.float.segment_button_v2_singleline_selected_height')** for text-only buttons and icon-only buttons, and **$r('sys.float.segment_button_v2_doubleline_selected_height')** for buttons with both an icon and text. | +| itemPadding | [LocalizedPadding](ts-types.md#localizedpadding12) | Yes | Yes | @Param | Padding of the item of the **TabSegmentButtonV2** component.
Default value: **{top: LengthMetrics.resource ($r('sys.float.padding_level2')), bottom: LengthMetrics.resource ($r('sys.float.padding_level2')), start: LengthMetrics.resource($r('sys.float.padding_level4')), end: LengthMetrics.resource($r('sys.float.padding_level4'))}**| +| itemShadow | [ShadowOptions](ts-universal-attributes-image-effect.md#shadowoptions) \| [ShadowStyle](ts-universal-attributes-image-effect.md#shadowstyle10)| Yes | Yes | @Param | Shadow of the item of the **TabSegmentButtonV2** component.
Default value: **ShadowStyle.OUTER_DEFAULT_XS** | +| itemSpace | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes | Yes | @Param | Space between items of the **TabSegmentButtonV2** component.
Value range: [0, +∞)
Default value: **LengthMetrics.vp(0)**
**NOTE**
This parameter cannot be set in percentage. If an invalid value is set, the default value is used. | +| itemMinFontScale | number \| [Resource](ts-types.md#resource) | Yes | Yes | @Param | Minimum font scale for the item of the **TabSegmentButtonV2** component.
Value range: [0, 1]
**NOTE**
A value less than 0 is handled as **0**. A value greater than 1 is handled as **1**. Abnormal values are ineffective by default. | +| itemMaxFontScale | number \| [Resource](ts-types.md#resource) | Yes | Yes | @Param | Maximum font scale for the item of the **TabSegmentButtonV2** component.
Value range: [1, 2]
Default value: **1**
**NOTE**
A value less than 1 is handled as **1**. A value greater than 2 is handled as **2**. Abnormal values are ineffective by default. | +| itemFontSize | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes | Yes | @Param | Font size of the unselected item of the **TabSegmentButtonV2** component.
Value range: [0, +∞)
Default value: **14fp**
**NOTE**
This parameter cannot be set in percentage. If an invalid value is set, the default value is used. | +| itemSelectedFontSize | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes | Yes | @Param | Font size of the selected item of the **TabSegmentButtonV2** component.
Value range: [0, +∞)
Default value: **14fp**
**NOTE**
This parameter cannot be set in percentage. If an invalid value is set, the default value is used. | +| itemFontColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | Yes | Yes | @Param | Font color of the unselected item of the **TabSegmentButtonV2** component.
Default value: **$r('sys.color.font_secondary')** | +| itemSelectedFontColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | Yes | Yes | @Param | Font color of the selected item of the **TabSegmentButtonV2** component.
Default value: **$r('sys.color.font_primary')** | +| itemFontWeight | [FontWeight](ts-appendix-enums.md#fontweight) | Yes | Yes | @Param | Font weight of the unselected item of the **TabSegmentButtonV2** component.
Default value: **FontWeight.Medium** | +| itemSelectedFontWeight | [FontWeight](ts-appendix-enums.md#fontweight) | Yes | Yes | @Param | Font weight of the selected item of the **TabSegmentButtonV2** component.
Default value: **FontWeight.Medium** | +| itemBorderRadius | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes | Yes | @Param | Rounded corner radius of the item of the **TabSegmentButtonV2** component.
Value range: [0, +∞)
Default value: **$r('sys.float.segment_button_v2_selected_corner_radius')** | +| itemIconSize | [SizeT](../js-apis-arkui-graphics.md#sizett12)\<[LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12)> | Yes | Yes | @Param | Size of the image icon of the item in the **TabSegmentButtonV2** component.
Value range: [0, +∞)
Default value: **{ width: LengthMetrics.vp(24), height: LengthMetrics.vp(24) }** | +| itemIconFillColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | Yes | Yes | @Param | Icon color of the unselected item of the **TabSegmentButtonV2** component.
Default value: **$r('sys.color.font_secondary')** | +| itemSelectedIconFillColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | Yes | Yes | @Param | Icon color of the selected item of the **TabSegmentButtonV2** component.
Default value: **$r('sys.color.font_primary')** | +| itemSymbolFontSize | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes | Yes | @Param | Size of the HM Symbol icon of the item in the **TabSegmentButtonV2** component.
Value range: [0, +∞)
Default value: **20fp**
**NOTE**
This parameter cannot be set in percentage. If an invalid value is set, the default value is used. | +| itemSymbolFontColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | Yes | Yes | @Param | Color of the HM Symbol icon of the unselected items in the **TabSegmentButtonV2** component.
Default value: **$r('sys.color.font_secondary')** | +| itemSelectedSymbolFontColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | Yes | Yes | @Param | Color of the HM Symbol icon of the selected item in the **TabSegmentButtonV2** component.
Default value: **$r('sys.color.font_primary')** | +| languageDirection | [Direction](ts-appendix-enums.md#direction) | Yes | Yes | @Param | Language direction of the **TabSegmentButtonV2** component.
Default value: **Direction.Auto** | + +## CapsuleSegmentButtonV2 + +```ts +CapsuleSegmentButtonV2({ + items: SegmentButtonV2Items, + selectedIndex: number, + $selectedIndex?: OnSelectedIndexChange, + onItemClicked?: Callback, + itemMinFontScale?: number | Resource, + itemMaxFontScale?: number | Resource, + itemSpace?: LengthMetrics, + itemFontSize?: LengthMetrics, + itemSelectedFontSize?: LengthMetrics, + itemFontColor?: ColorMetrics, + itemSelectedFontColor?: ColorMetrics, + itemFontWeight?: FontWeight, + itemSelectedFontWeight?: FontWeight, + itemBorderRadius?: LengthMetrics, + itemSelectedBackgroundColor?: ColorMetrics, + itemIconSize?: SizeT, + itemIconFillColor?: ColorMetrics, + itemSelectedIconFillColor?: ColorMetrics, + itemSymbolFontSize?: LengthMetrics, + itemSymbolFontColor?: ColorMetrics, + itemSelectedSymbolFontColor?: ColorMetrics, + itemMinHeight?: LengthMetrics, + itemPadding?: LocalizedPadding, + itemShadow?: ShadowOptions | ShadowStyle, + buttonBackgroundColor?: ColorMetrics, + buttonBackgroundBlurStyle?: BlurStyle, + buttonBackgroundBlurStyleOptions?: BackgroundBlurStyleOptions, + buttonBackgroundEffect?: BackgroundEffectOptions, + buttonBorderRadius?: LengthMetrics, + buttonMinHeight?: LengthMetrics, + buttonPadding?: LengthMetrics, + languageDirection?: Direction +}) +``` + +**Decorator**: @ComponentV2 + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Read-Only| Mandatory| Decorator | Description | +| -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | ---- | ---- | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| items | [SegmentButtonV2Items](#segmentbuttonv2items) | Yes | No | @Require
@Param | Items of the **CapsuleSegmentButtonV2** component. | +| selectedIndex | number | Yes | No | @Require
@Param | Index of the selected item of the **CapsuleSegmentButtonV2** component. | +| $selectedIndex | [OnSelectedIndexChange](#onselectedindexchange) | No | Yes | @Event | Callback invoked when the selected item of the **CapsuleSegmentButtonV2** component changes. | +| onItemClicked | Callback\ | No | Yes | @Event | Callback invoked when an item in the **CapsuleSegmentButtonV2** component is clicked. | +| buttonBackgroundColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | Yes | Yes | @Param | Background color of the **CapsuleSegmentButtonV2** component.
Default value: **$r('sys.color.segment_button_v2_tab_button_background')** | +| buttonBackgroundBlurStyle | [BlurStyle](ts-universal-attributes-background.md#blurstyle9) | Yes | Yes | @Param | Background blur style of the **CapsuleSegmentButtonV2** component. | +| buttonBackgroundBlurStyleOptions | [BackgroundBlurStyleOptions](ts-universal-attributes-background.md#backgroundblurstyleoptions10) | Yes | Yes | @Param | Background blur style options of the **TabSegmentButtonV2** component. | +| buttonBackgroundEffect | [BackgroundEffectOptions](ts-universal-attributes-background.md#backgroundeffectoptions11) | Yes | Yes | @Param | Background blur effect options of the **TabSegmentButtonV2** component. | +| buttonBorderRadius | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes | Yes | @Param | Radius of the background rounded corner of the **CapsuleSegmentButtonV2** component.
Value range: [0, +∞)
Default value: **$r('sys.float.segment_button_v2_background_corner_radius')** | +| buttonMinHeight | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes | Yes | @Param | Minimum height of the **CapsuleSegmentButtonV2** component.
Value range: [0, +∞)
Default value: **$r('sys.float.segment_button_v2_singleline_background_height')** for text-only buttons and icon-only buttons, and **$r('sys.float.segment_button_v2_doubleline_background_height')** for buttons with both an icon and text. | +| buttonPadding | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes | Yes | @Param | Padding of the **CapsuleSegmentButtonV2** component.
Value range: [0, +∞)
Default value: **$r('sys.float.padding_level1')** | +| onItemClicked | Callback\ | Yes | Yes | @Event | Callback invoked when an item in the **CapsuleSegmentButtonV2** component is clicked. | +| itemSelectedBackgroundColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | Yes | Yes | @Param | Background color of the selected item of the **CapsuleSegmentButtonV2** component.
Default value: **$r('sys.color.comp_background_emphasize')** | +| itemMinHeight | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes | Yes | @Param | Minimum height of the item of the **CapsuleSegmentButtonV2** component.
Value range: [0, +∞)
Default value:
**$r('sys.float.segment_button_v2_singleline_selected_height')** for text-only buttons and icon-only buttons, and **$r('sys.float.segment_button_v2_doubleline_selected_height')** for buttons with both an icon and text. | +| itemPadding | [LocalizedPadding](ts-types.md#localizedpadding12) | Yes | Yes | @Param | Padding of the item of the **CapsuleSegmentButtonV2** component.
Default value: **{top: LengthMetrics.resource ($r('sys.float.padding_level2')), bottom: LengthMetrics.resource ($r('sys.float.padding_level2')), start: LengthMetrics.resource($r('sys.float.padding_level4')), end: LengthMetrics.resource($r('sys.float.padding_level4'))}**| +| itemShadow | [ShadowOptions](ts-universal-attributes-image-effect.md#shadowoptions) \| [ShadowStyle](ts-universal-attributes-image-effect.md#shadowstyle10)| Yes | Yes | @Param | Shadow of the item of the **CapsuleSegmentButtonV2** component.
Default value: **ShadowStyle.OUTER_DEFAULT_XS** | +| itemSpace | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes | Yes | @Param | Space between items of the **CapsuleSegmentButtonV2** component.
Value range: [0, +∞)
Default value: **LengthMetrics.vp(0)**
**NOTE**
This parameter cannot be set in percentage. If an invalid value is set, the default value is used. | +| itemMinFontScale | number \| [Resource](ts-types.md#resource) | Yes | Yes | @Param | Minimum font scale for the item of the **CapsuleSegmentButtonV2** component.
Value range: [0, 1]
**NOTE**
A value less than 0 is handled as **0**. A value greater than 1 is handled as **1**. Abnormal values are ineffective by default. | +| itemMaxFontScale | number \| [Resource](ts-types.md#resource) | Yes | Yes | @Param | Maximum font scale for the item of the **CapsuleSegmentButtonV2** component.
Value range: [1, 2]
Default value: **1**
**NOTE**
A value less than 1 is handled as **1**. A value greater than 2 is handled as **2**. Abnormal values are ineffective by default. | +| itemFontSize | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes | Yes | @Param | Font size of the unselected item of the **CapsuleSegmentButtonV2** component.
Value range: [0, +∞)
Default value: **14fp**
**NOTE**
This parameter cannot be set in percentage. If an invalid value is set, the default value is used. | +| itemSelectedFontSize | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes | Yes | @Param | Font size of the selected item of the **CapsuleSegmentButtonV2** component.
Value range: [0, +∞)
Default value: **14fp**
**NOTE**
This parameter cannot be set in percentage. If an invalid value is set, the default value is used. | +| itemFontColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | Yes | Yes | @Param | Font color of the unselected item of the **CapsuleSegmentButtonV2** component.
Default value: **$r('sys.color.font_secondary')** | +| itemSelectedFontColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | Yes | Yes | @Param | Font color of the selected item of the **CapsuleSegmentButtonV2** component.
Default value: **$r('sys.color.font_on_primary')** | +| itemFontWeight | [FontWeight](ts-appendix-enums.md#fontweight) | Yes | Yes | @Param | Font weight of the unselected item of the **CapsuleSegmentButtonV2** component.
Default value: **FontWeight.Medium** | +| itemSelectedFontWeight | [FontWeight](ts-appendix-enums.md#fontweight) | Yes | Yes | @Param | Font weight of the selected item of the **CapsuleSegmentButtonV2** component.
Default value: **FontWeight.Medium** | +| itemBorderRadius | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes | Yes | @Param | Rounded corner radius of the item of the **CapsuleSegmentButtonV2** component.
Value range: [0, +∞)
Default value: **$r('sys.float.segment_button_v2_selected_corner_radius')** | +| itemIconSize | [SizeT](../js-apis-arkui-graphics.md#sizett12)\<[LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12)> | Yes | Yes | @Param | Size of the image icon of the item in the **CapsuleSegmentButtonV2** component.
Value range: [0, +∞)
Default value: **{ width: LengthMetrics.vp(24), height: LengthMetrics.vp(24) }** | +| itemIconFillColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | Yes | Yes | @Param | Icon color of the unselected item of the **CapsuleSegmentButtonV2** component.
Default value: **$r('sys.color.font_secondary')** | +| itemSelectedIconFillColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | Yes | Yes | @Param | Icon color of the selected item of the **CapsuleSegmentButtonV2** component.
Default value: **$r('sys.color.font_on_primary')** | +| itemSymbolFontSize | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes | Yes | @Param | Size of the HM Symbol icon of the item in the **CapsuleSegmentButtonV2** component.
Value range: [0, +∞)
Default value: **20fp**
**NOTE**
This parameter cannot be set in percentage. If an invalid value is set, the default value is used. | +| itemSymbolFontColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | Yes | Yes | @Param | Color of the HM Symbol icon of the unselected items in the **CapsuleSegmentButtonV2** component.
Default value: **$r('sys.color.font_secondary')** | +| itemSelectedSymbolFontColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | Yes | Yes | @Param | Color of the HM Symbol icon of the selected item in the **CapsuleSegmentButtonV2** component.
Default value: **$r('sys.color.font_on_primary')** | +| languageDirection | [Direction](ts-appendix-enums.md#direction) | Yes | Yes | @Param | Language direction of the **CapsuleSegmentButtonV2** component.
Default value: **Direction.Auto** | + +## MultiCapsuleSegmentButtonV2 + +```ts +MultiCapsuleSegmentButtonV2({ + items: SegmentButtonV2Items, + selectedIndexes: number[], + $selectedIndexes: OnSelectedIndexesChange, + onItemClicked?: Callback, + itemMinFontScale?: number | Resource, + itemMaxFontScale?: number | Resource, + itemSpace?: LengthMetrics, + itemFontColor?: ColorMetrics, + itemSelectedFontColor?: ColorMetrics, + itemFontSize?: LengthMetrics, + itemSelectedFontSize?: LengthMetrics, + itemFontWeight?: FontWeight, + itemSelectedFontWeight?: FontWeight, + itemBorderRadius?: LengthMetrics, + itemBackgroundColor?: ColorMetrics, + itemBackgroundEffect?: BackgroundEffectOptions, + itemBackgroundBlurStyle?: BlurStyle, + itemBackgroundBlurStyleOptions?: BackgroundBlurStyleOptions, + itemSelectedBackgroundColor?: ColorMetrics, + itemIconSize?: SizeT, + itemIconFillColor?: ColorMetrics, + itemSelectedIconFillColor?: ColorMetrics, + itemSymbolFontSize?: LengthMetrics, + itemSymbolFontColor?: ColorMetrics, + itemSelectedSymbolFontColor?: ColorMetrics, + itemMinHeight?: LengthMetrics, + itemPadding?: LocalizedPadding, + languageDirection?: Direction +}) +``` + +**Decorator**: @ComponentV2 + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Read-Only| Mandatory| Decorator | Description | +| ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- | ---- | ---- | ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| items | [SegmentButtonV2Items](#segmentbuttonv2items) | Yes | No | @Require
@Param | Items of the **MultiCapsuleSegmentButtonV2** component. | +| selectedIndexes | number[] | Yes | No | @Require
@Param | Index of the selected item of the **MultiCapsuleSegmentButtonV2** component. | +| $selectedIndexes | [OnSelectedIndexesChange](#onselectedindexeschange) | No | Yes | @Event | Callback invoked when the selected item of the **MultiCapsuleSegmentButtonV2** component changes. | +| onItemClicked | Callback\ | No | Yes | @Event | Callback invoked when an item in the **MultiCapsuleSegmentButtonV2** component is clicked. | +| itemBackgroundColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | Yes | Yes | @Param | Background color of the unselected item of the **MultiCapsuleSegmentButtonV2** component.
Default value: **$r('sys.color.segment_button_v2_multi_capsule_button_background')** | +| itemBackgroundEffect | [BackgroundEffectOptions](ts-universal-attributes-background.md#backgroundeffectoptions11) | Yes | Yes | @Param | Background effect of the unselected item of the **MultiCapsuleSegmentButtonV2** component. | +| itemBackgroundBlurStyle | [BlurStyle](ts-universal-attributes-background.md#blurstyle9) | Yes | Yes | @Param | Background blur effect of the unselected item of the **MultiCapsuleSegmentButtonV2** component. | +| itemBackgroundBlurStyleOptions | [BackgroundBlurStyleOptions](ts-universal-attributes-background.md#backgroundblurstyleoptions10) | Yes | Yes | @Param | Background blur style options of the unselected item of the **MultiCapsuleSegmentButtonV2** component. | +| itemSelectedBackgroundColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | Yes | Yes | @Param | Background color of the selected item of the **MultiCapsuleSegmentButtonV2** component.
Default value: **$r('sys.color.comp_background_emphasize')** | +| itemMinHeight | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes | Yes | @Param | Minimum height of the item of the **MultiCapsuleSegmentButtonV2** component.
Value range: [0, +∞)
Default value:
**$r('sys.float.segment_button_v2_singleline_selected_height')** for text-only buttons and icon-only buttons, and **$r('sys.float.segment_button_v2_doubleline_selected_height')** for buttons with both an icon and text. | +| itemPadding | [LocalizedPadding](ts-types.md#localizedpadding12) | Yes | Yes | @Param | Padding of the item of the **MultiCapsuleSegmentButtonV2** component.
Default value: **{top: LengthMetrics.resource ($r('sys.float.padding_level2')), bottom: LengthMetrics.resource ($r('sys.float.padding_level2')), start: LengthMetrics.resource($r('sys.float.padding_level4')), end: LengthMetrics.resource($r('sys.float.padding_level4'))}**| +| itemShadow | [ShadowOptions](ts-universal-attributes-image-effect.md#shadowoptions) \| [ShadowStyle](ts-universal-attributes-image-effect.md#shadowstyle10)| Yes | Yes | @Param | Shadow of the item of the **MultiCapsuleSegmentButtonV2** component.
Default value: **ShadowStyle.OUTER_DEFAULT_XS** | +| itemSpace | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes | Yes | @Param | Space between items of the **MultiCapsuleSegmentButtonV2** component.
Value range: [0, +∞)
Default value: **LengthMetrics.vp(1)**
**NOTE**
This parameter cannot be set in percentage. If an invalid value is set, the default value is used. | +| itemMinFontScale | number \| [Resource](ts-types.md#resource) | Yes | Yes | @Param | Minimum font scale for the item of the **MultiCapsuleSegmentButtonV2** component.
Value range: [0, 1]
**NOTE**
A value less than 0 is handled as **0**. A value greater than 1 is handled as **1**. Abnormal values are ineffective by default. | +| itemMaxFontScale | number \| [Resource](ts-types.md#resource) | Yes | Yes | @Param | Maximum font scale for the item of the **MultiCapsuleSegmentButtonV2** component.
Value range: [1, 2]
Default value: **1**
**NOTE**
A value less than 1 is handled as **1**. A value greater than 2 is handled as **2**. Abnormal values are ineffective by default. | +| itemSelectedFontSize | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes | Yes | @Param | Font size of the selected item of the **MultiCapsuleSegmentButtonV2** component.
Value range: [0, +∞)
Default value: **14fp**
**NOTE**
This parameter cannot be set in percentage. If an invalid value is set, the default value is used. | +| itemFontColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | Yes | Yes | @Param | Font color of the unselected item of the **MultiCapsuleSegmentButtonV2** component.
Default value: **$r('sys.color.font_secondary')** | +| itemSelectedFontColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | Yes | Yes | @Param | Font color of the selected item of the **MultiCapsuleSegmentButtonV2** component.
Default value: **$r('sys.color.font_on_primary')** | +| itemFontWeight | [FontWeight](ts-appendix-enums.md#fontweight) | Yes | Yes | @Param | Font weight of the unselected item of the **MultiCapsuleSegmentButtonV2** component.
Default value: **FontWeight.Medium** | +| itemSelectedFontWeight | [FontWeight](ts-appendix-enums.md#fontweight) | Yes | Yes | @Param | Font weight of the selected item of the **MultiCapsuleSegmentButtonV2** component.
Default value: **FontWeight.Medium** | +| itemBorderRadius | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes | Yes | @Param | Rounded corner radius of the item of the **MultiCapsuleSegmentButtonV2** component.
Value range: [0, +∞)
Default value: **$r('sys.float.segment_button_v2_multi_corner_radius')** | +| itemIconSize | [SizeT](../js-apis-arkui-graphics.md#sizett12)\<[LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12)> | Yes | Yes | @Param | Size of the image icon of the item in the **MultiCapsuleSegmentButtonV2** component.
Value range: [0, +∞)
Default value: **{ width: LengthMetrics.vp(24), height: LengthMetrics.vp(24) }** | +| itemIconFillColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | Yes | Yes | @Param | Icon color of the unselected item of the **MultiCapsuleSegmentButtonV2** component.
Default value: **$r('sys.color.font_secondary')** | +| itemSelectedIconFillColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | Yes | Yes | @Param | Icon color of the selected item of the **MultiCapsuleSegmentButtonV2** component.
Default value: **$r('sys.color.font_on_primary')** | +| itemSymbolFontSize | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes | Yes | @Param | Size of the HM Symbol icon of the item in the **MultiCapsuleSegmentButtonV2** component.
Value range: [0, +∞)
Default value: **20fp**
**NOTE**
This parameter cannot be set in percentage. If an invalid value is set, the default value is used. | +| itemSymbolFontColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | Yes | Yes | @Param | Color of the HM Symbol icon of the unselected items in the **MultiCapsuleSegmentButtonV2** component.
Default value: **$r('sys.color.font_secondary')** | +| itemSelectedSymbolFontColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | Yes | Yes | @Param | Color of the HM Symbol icon of the selected item in the **MultiCapsuleSegmentButtonV2** component.
Default value: **$r('sys.color.font_on_primary')** | +| languageDirection | [Direction](ts-appendix-enums.md#direction) | Yes | Yes | @Param | Language direction of the **MultiCapsuleSegmentButtonV2** component.
Default value: **Direction.Auto** | + +## SegmentButtonV2Items + +Represents items of the **SegmentButtonV2** component. + +This parameter is inherited from Array\<[SegmentButtonV2Item](#segmentbuttonv2item)>. + +**Decorator type**: @ObservedV2 + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +### Properties + +**Decorator type**: @ObservedV2 + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +### constructor + +constructor(items: SegmentButtonV2ItemOptions[]) + +Constructs a **SegmentButtonV2ItemOptions** instance. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----- | ----------------------------------------------------------------- | ---- | -------------------------- | +| items | Array\<[SegmentButtonV2ItemOptions](#segmentbuttonv2itemoptions)> | Yes | Options of the item of the **SegmentButtonV2** component.| + +### isHybrid + +get hasHybrid() + +Obtains whether there is an item with both an icon and text. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Return value** + +| Type | Description | +| ------- | -------------------- | +| boolean | Whether there is an item with both an icon and text.
The value **true** indicates that there is an item with both an icon and text; the value **false** indicates the opposite.| + +## SegmentButtonV2Item + +### Properties + +**Decorator type**: @ObservedV2 + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Decorator| Mandatory| Description | +| ------------------------ | -------------------------------------------------------------------- | ------ | ---- | ----------------------------------------------- | +| text | [ResourceStr](ts-types.md#resourcestr) | @Trace | No | Item text of the **SegmentButtonV2** component. | +| icon | [ResourceStr](ts-types.md#resourcestr) | @Trace | No | Image icon of the item of the **SegmentButtonV2** component. | +| symbol | [Resource](ts-types.md#resource) | @Trace | No | HM symbol icon of the item of the **SegmentButtonV2** component. | +| enabled | boolean | @Trace | No | Whether the item of the **SegmentButtonV2** component is enabled.
Default value: **true**
The value **true** indicates that the item is enabled; the value **false** indicates the opposite. | +| textModifier | [TextModifier](ts-universal-attributes-attribute-modifier.md) | @Trace | No | Text modifier for the item of the **SegmentButtonV2** component. | +| iconModifier | [ImageModifier](ts-universal-attributes-attribute-modifier.md) | @Trace | No | Image icon modifier for the item of the **SegmentButtonV2** component. | +| symbolModifier | [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) | @Trace | No | HM Symbol icon modifier for the item of the **SegmentButtonV2** component.| +| accessibilityText | [ResourceStr](ts-types.md#resourcestr) | @Trace | No | Accessibility text of the item of the **SegmentButtonV2** component. | +| accessibilityDescription | [ResourceStr](ts-types.md#resourcestr) | @Trace | No | Accessibility description of the item of the **SegmentButtonV2** component. | +| accessibilityLevel | string | @Trace | No | Accessibility level of the **SegmentButtonV2** component. | + +> **Description** +> +> 1. When both **symbol** and **icon** are set, **symbol** has a higher display priority. +> 2. When both **symbol** and **symbolModifier** are set with HM Symbol, **symbolModifier** has a higher display priority. + +### constructor + +constructor(options: SegmentButtonV2ItemOptions) + +Constructs a **SegmentButtonV2ItemOptions** instance. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | --------------------------------------------------------- | ---- | ---------------------- | +| options | [SegmentButtonV2ItemOptions](#segmentbuttonv2itemoptions) | Yes | Options of the item of the **SegmentButtonV2** component.| + +### isHybrid + +get isHybrid() + +Obtains whether the item is set with both an icon and text. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Return value** + +| Type | Description | +| ------- | ------------------------------ | +| boolean | Whether the item is set with both an icon and text.| + +## SegmentButtonV2ItemOptions + +Represents options of the item of the **SegmentButtonV2** component. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +### Properties + +| Name | Type | Mandatory| Description | +| ------------------------ | -------------------------------------------------------------------- | ---- | ----------------------------------------------- | +| text | [ResourceStr](ts-types.md#resourcestr) | No | Item text of the **SegmentButtonV2** component. | +| icon | [ResourceStr](ts-types.md#resourcestr) | No | Image icon of the item of the **SegmentButtonV2** component. | +| symbol | [Resource](ts-types.md#resource) | No | HM symbol icon of the item of the **SegmentButtonV2** component. | +| enabled | boolean | No | Whether the item of the **SegmentButtonV2** component is enabled. | +| textModifier | [TextModifier](ts-universal-attributes-attribute-modifier.md) | No | Text modifier for the item of the **SegmentButtonV2** component. | +| iconModifier | [ImageModifier](ts-universal-attributes-attribute-modifier.md) | No | Image icon modifier for the item of the **SegmentButtonV2** component. | +| symbolModifier | [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) | No | HM Symbol icon modifier for the item of the **SegmentButtonV2** component.| +| accessibilityText | [ResourceStr](ts-types.md#resourcestr) | No | Accessibility text of the item of the **SegmentButtonV2** component. | +| accessibilityDescription | [ResourceStr](ts-types.md#resourcestr) | No | Accessibility description of the item of the **SegmentButtonV2** component. | +| accessibilityLevel | string | No | Accessibility level of the **SegmentButtonV2** component. | + +> **Description** +> +> 1. When both **symbol** and **icon** are set, **symbol** has a higher display priority. +> 2. When both **symbol** and **symbolModifier** are set with HM Symbol, **symbolModifier** has a higher display priority. + +## OnSelectedIndexChange + +type OnSelectedIndexChange = (selectedIndex: number) => void + +Defines a callback invoked when the selected item of the **SegmentButtonV2** component changes. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | ------ | ---- | ------------------ | +| selectedIndex | number | Yes | Index of the selected item of the **SegmentButtonV2** component.| + +## OnSelectedIndexesChange + +type OnSelectedIndexesChange = (selectedIndexes: number[]) => void + +Defines a callback invoked when selected items of the **SegmentButtonV2** component changes. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | -------- | ---- | ---------------------- | +| selectedIndexes | number[] | Yes | Indexes of selected items of the **SegmentButtonV2** component.| + +## Example + +### Example 1 (**TabSegmentButtonV2**) + +The following example describes how to use the **TabSegmentButtonV2** component. + +```ts +import { SegmentButtonV2Items, TabSegmentButtonV2 } from '@kit.ArkUI'; + +@Entry +@ComponentV2 +struct TabSegmentButtonV2Example { + @Local textItems: SegmentButtonV2Items = new SegmentButtonV2Items([ + { text: 'Phone'}, + { text: 'Tablet' }, + { text: '2-in-1' }, + { text: 'Wearable' }, + ]); + @Local textSelectedIndex: number = 0; + @Local imageItems: SegmentButtonV2Items = new SegmentButtonV2Items([ + { icon: $r('sys.media.ohos_ic_public_device_phone') }, + { icon: $r('sys.media.ohos_ic_public_device_pad') }, + { icon: $r('sys.media.ohos_ic_public_device_matebook') }, + { icon: $r('sys.media.ohos_ic_public_device_watch') }, + ]); + @Local imageSelectedIndex: number = 0; + @Local symbolItems: SegmentButtonV2Items = new SegmentButtonV2Items([ + { symbol: $r('sys.symbol.phone') }, + { symbol: $r('sys.symbol.pad') }, + { symbol: $r('sys.symbol.matebook') }, + { symbol: $r('sys.symbol.watch') }, + ]); + @Local symbolSelectedIndex: number = 0; + @Local hybridItems: SegmentButtonV2Items = new SegmentButtonV2Items([ + { text: 'Phone', symbol: $r('sys.symbol.phone') }, + { text: 'Tablet', symbol: $r('sys.symbol.pad') }, + { text: '2-in-1', symbol: $r('sys.symbol.matebook') }, + { text: 'Wearable', symbol: $r('sys.symbol.watch') }, + ]); + @Local hybridSelectedIndex: number = 0; + @Local freeItems: SegmentButtonV2Items = new SegmentButtonV2Items([ + { text: 'Year' }, + { text: 'Month' }, + { text: 'Week' }, + { text: 'Day' }, + { icon: $r('sys.media.ohos_ic_public_search_filled') }, + ]); + @Local freeSelectedIndex: number = 0; + + build() { + Scroll() { + Column({ space: 12 }) { + VCard({ title: 'Text Button' }) { + TabSegmentButtonV2({ + items: this.textItems, + selectedIndex: this.textSelectedIndex!!, + }) + } + + VCard({ title: 'Image Button' }) { + TabSegmentButtonV2({ + items: this.imageItems, + selectedIndex: this.imageSelectedIndex!!, + }) + } + + VCard({ title: 'Symbol Button' }) { + TabSegmentButtonV2({ + items: this.symbolItems, + selectedIndex: this.symbolSelectedIndex!!, + }) + } + + VCard({ title: 'Text and Icon Button' }) { + TabSegmentButtonV2({ + items: this.hybridItems, + selectedIndex: this.hybridSelectedIndex!!, + }) + } + + VCard({ title: 'Custom Button' }) { + TabSegmentButtonV2({ + items: this.freeItems, + selectedIndex: this.freeSelectedIndex!!, + }) + } + } + .constraintSize({ minHeight: '100%' }) + .justifyContent(FlexAlign.Start) + .padding(16) + } + .backgroundColor('#f1f3f5') + .width('100%') + .height('100%') + } +} + +@Builder +function Noop() { +} + +@Component +export struct VCard { + @Prop + title: ResourceStr; + @BuilderParam + content: () => void = Noop; + + build() { + Column({ space: 8 }) { + if (this.title) { + Text(this.title) + .maxLines(1) + .textOverflow({ overflow: TextOverflow.Ellipsis }) + .constraintSize({ maxWidth: '80%' }) + } + this.content() + } + .backgroundColor(Color.White) + .borderRadius(8) + .padding(8) + .width('100%') + } +} +``` + +![TabSegmentButtonV2](figures/TabSegmentButtonV2.gif) + +### Example 2 (**CapsuleSegmentButtonV2**) + +The following example describes how to use the **CapsuleSegmentButtonV2** button. + +```ts +import { CapsuleSegmentButtonV2, SegmentButtonV2Items } from '@kit.ArkUI'; + +@Entry +@ComponentV2 +struct CapsuleSegmentButtonV2Example { + @Local textItems: SegmentButtonV2Items = new SegmentButtonV2Items([ + { text: 'Phone'}, + { text: 'Tablet'}, + { text: '2-in-1' }, + { text: 'Wearable' }, + ]); + @Local textSelectedIndex: number = 0; + @Local imageItems: SegmentButtonV2Items = new SegmentButtonV2Items([ + { icon: $r('sys.media.ohos_ic_public_device_phone') }, + { icon: $r('sys.media.ohos_ic_public_device_pad') }, + { icon: $r('sys.media.ohos_ic_public_device_matebook') }, + { icon: $r('sys.media.ohos_ic_public_device_watch') }, + ]); + @Local imageSelectedIndex: number = 0; + @Local symbolItems: SegmentButtonV2Items = new SegmentButtonV2Items([ + { symbol: $r('sys.symbol.phone') }, + { symbol: $r('sys.symbol.pad') }, + { symbol: $r('sys.symbol.matebook') }, + { symbol: $r('sys.symbol.watch') }, + ]); + @Local symbolSelectedIndex: number = 0; + @Local hybridItems: SegmentButtonV2Items = new SegmentButtonV2Items([ + { text: 'Phone', symbol: $r('sys.symbol.phone') }, + { text: 'Tablet', symbol: $r('sys.symbol.pad') }, + { text: '2-in-1', symbol: $r('sys.symbol.matebook') }, + { text: 'Wearable', symbol: $r('sys.symbol.watch') }, + ]); + @Local hybridSelectedIndex: number = 0; + @Local freeItems: SegmentButtonV2Items = new SegmentButtonV2Items([ + { text: 'Year' }, + { text: 'Month' }, + { text: 'Week' }, + { text: 'Day' }, + { icon: $r('sys.media.ohos_ic_public_search_filled') }, + ]); + @Local freeSelectedIndex: number = 0; + + build() { + Scroll() { + Column({ space: 12 }) { + VCard({ title: 'Text Button' }) { + CapsuleSegmentButtonV2({ + items: this.textItems, + selectedIndex: this.textSelectedIndex!!, + }) + } + + VCard({ title: 'Image Button' }) { + CapsuleSegmentButtonV2({ + items: this.imageItems, + selectedIndex: this.imageSelectedIndex!!, + }) + } + + VCard({ title: 'Symbol Button' }) { + CapsuleSegmentButtonV2({ + items: this.symbolItems, + selectedIndex: this.symbolSelectedIndex!!, + }) + } + + VCard({ title: 'Text and Icon Button' }) { + CapsuleSegmentButtonV2({ + items: this.hybridItems, + selectedIndex: this.hybridSelectedIndex!!, + }) + } + + VCard({ title: 'Custom Button' }) { + CapsuleSegmentButtonV2({ + items: this.freeItems, + selectedIndex: this.freeSelectedIndex!!, + }) + } + } + .constraintSize({ minHeight: '100%' }) + .justifyContent(FlexAlign.Start) + .padding(16) + } + .backgroundColor('#f1f3f5') + .width('100%') + .height('100%') + } +} + +@Builder +function Noop() { +} + +@Component +export struct VCard { + @Prop + title: ResourceStr; + @BuilderParam + content: () => void = Noop; + + build() { + Column({ space: 8 }) { + if (this.title) { + Text(this.title) + .maxLines(1) + .textOverflow({ overflow: TextOverflow.Ellipsis }) + .constraintSize({ maxWidth: '80%' }) + } + this.content() + } + .backgroundColor(Color.White) + .borderRadius(8) + .padding(8) + .width('100%') + } +} + +``` + +![CapsuleSegmentButtonV2](figures/CapsuleSegmentButtonV2.gif) + +### Example 3 (**MultiCapsuleSegmentButtonV2**) + +The following example describes how to use the **MultiCapsuleSegmentButtonV2** button. + +```ts +import { MultiCapsuleSegmentButtonV2, SegmentButtonV2Items } from '@kit.ArkUI'; + +@Entry +@ComponentV2 +struct MultiCapsuleSegmentButtonV2Example { + @Local textItems: SegmentButtonV2Items = new SegmentButtonV2Items([ + { text: 'Phone'}, + { text: 'Tablet'}, + { text: '2-in-1' }, + { text: 'Wearable' }, + ]); + @Local textSelectedIndexes: number[] = [0]; + @Local imageItems: SegmentButtonV2Items = new SegmentButtonV2Items([ + { icon: $r('sys.media.ohos_ic_public_device_phone') }, + { icon: $r('sys.media.ohos_ic_public_device_pad') }, + { icon: $r('sys.media.ohos_ic_public_device_matebook') }, + { icon: $r('sys.media.ohos_ic_public_device_watch') }, + ]); + @Local imageSelectedIndexes: number[] = [0]; + @Local symbolItems: SegmentButtonV2Items = new SegmentButtonV2Items([ + { symbol: $r('sys.symbol.phone') }, + { symbol: $r('sys.symbol.pad') }, + { symbol: $r('sys.symbol.matebook') }, + { symbol: $r('sys.symbol.watch') }, + ]); + @Local symbolSelectedIndexes: number[] = [0]; + @Local hybridItems: SegmentButtonV2Items = new SegmentButtonV2Items([ + { text: 'Phone', symbol: $r('sys.symbol.phone') }, + { text: 'Tablet', symbol: $r('sys.symbol.pad') }, + { text: '2-in-1', symbol: $r('sys.symbol.matebook') }, + { text: 'Wearable', symbol: $r('sys.symbol.watch') }, + ]); + @Local hybridSelectedIndexes: number[] = [0]; + @Local freeItems: SegmentButtonV2Items = new SegmentButtonV2Items([ + { text: 'Year' }, + { text: 'Month' }, + { text: 'Week' }, + { text: 'Day' }, + { icon: $r('sys.media.ohos_ic_public_search_filled') }, + ]); + @Local freeSelectedIndexes: number[] = [0]; + + build() { + Scroll() { + Column({ space: 12 }) { + VCard({ title: 'Text Button' }) { + MultiCapsuleSegmentButtonV2({ + items: this.textItems, + selectedIndexes: this.textSelectedIndexes!!, + }) + } + + VCard({ title: 'Image Button' }) { + MultiCapsuleSegmentButtonV2({ + items: this.imageItems, + selectedIndexes: this.imageSelectedIndexes!!, + }) + } + + VCard({ title: 'Symbol Button' }) { + MultiCapsuleSegmentButtonV2({ + items: this.symbolItems, + selectedIndexes: this.symbolSelectedIndexes!!, + }) + } + + VCard({ title: 'Text and Icon Button' }) { + MultiCapsuleSegmentButtonV2({ + items: this.hybridItems, + selectedIndexes: this.hybridSelectedIndexes!!, + }) + } + + VCard({ title: 'Custom Button' }) { + MultiCapsuleSegmentButtonV2({ + items: this.freeItems, + selectedIndexes: this.freeSelectedIndexes!!, + }) + } + } + .constraintSize({ minHeight: '100%' }) + .justifyContent(FlexAlign.Start) + .padding(16) + } + .backgroundColor('#f1f3f5') + .width('100%') + .height('100%') + } +} + +@Builder +function Noop() { +} + +@Component +export struct VCard { + @Prop + title: ResourceStr; + @BuilderParam + content: () => void = Noop; + + build() { + Column({ space: 8 }) { + if (this.title) { + Text(this.title) + .maxLines(1) + .textOverflow({ overflow: TextOverflow.Ellipsis }) + .constraintSize({ maxWidth: '80%' }) + } + this.content() + } + .backgroundColor(Color.White) + .borderRadius(8) + .padding(8) + .width('100%') + } +} + +``` + +![MultiCapsuleSegmentButtonV2.gif](figures/MultiCapsuleSegmentButtonV2.gif) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-SelectTitleBar.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-SelectTitleBar.md index 4fa55108a011f74c3ebc18cf1e9d4ce7315580f3..68146082e9f5ad07e425c439f66b9308ecedf41c 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-SelectTitleBar.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-SelectTitleBar.md @@ -21,7 +21,7 @@ import { SelectTitleBar } from '@kit.ArkUI' Not supported ## Attributes -The [universal attributes](ts-universal-attributes-size.md) are not supported. +The [universal attributes](ts-component-general-attributes.md) are not supported. ## SelectTitleBar @@ -54,64 +54,60 @@ SelectTitleBar({selected: number, options: Array<SelectOption>, menuItems? | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | [ResourceStr](ts-types.md#resourcestr) | Yes| Icon resource.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| symbolStyle18+ | [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) | No| Symbol icon resource, which has higher priority than **value**.
**Atomic service API**: This API can be used in atomic services since API version 18.| | label13+ | [ResourceStr](ts-types.md#resourcestr) | No| Icon label.
**Atomic service API**: This API can be used in atomic services since API version 13.| | isEnabled | boolean | No| Whether to enable the item.
Default value: **false**
The value **true** means to enable the item, and **false** means the opposite.
**Atomic service API**: This API can be used in atomic services since API version 11.| | action | () => void | No| Action to perform.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| accessibilityLevel16+ | string | No| Accessibility level. It determines whether the component can be recognized by accessibility services.
The options are as follows:
**"auto"**: It is treated as "yes" by the system.
**"yes"**: The component can be recognized by accessibility services.
**"no"**: The component cannot be recognized by accessibility services.
**"no-hide-descendants"**: Neither the component nor its child components can be recognized by accessibility services.
Default value: **"auto"**
**Atomic service API**: This API can be used in atomic services since API version 16.| -| accessibilityText16+ | ResourceStr | No| Accessibility text, that is, accessible label name. If a component does not contain text information, it will not be announced by the screen reader when selected. In this case, the screen reader user cannot know which component is selected. To solve this problem, you can set accessibility text for components without text information. When such a component is selected, the screen reader announces the specified accessibility text, informing the user which component is selected.
Default value: value of the **label** property if it is set and an empty string otherwise.
**Atomic service API**: This API can be used in atomic services since API version 16. | -| accessibilityDescription16+ | ResourceStr | No| Accessible description. You can provide comprehensive text explanations to help users understand the operation they are about to perform and its potential consequences, especially when these cannot be inferred from the component's attributes and accessibility text alone. If a component contains both text information and the accessible description, the text is announced first and then the accessible description, when the component is selected.
Default value: **"Double-tap to activate"**
**Atomic service API**: This API can be used in atomic services since API version 16. | +| accessibilityLevel18+ | string | No| Accessibility level. It determines whether the component can be recognized by accessibility services.
The options are as follows:
**"auto"**: It is treated as "yes" by the system.
**"yes"**: The component can be recognized by accessibility services.
**"no"**: The component cannot be recognized by accessibility services.
**"no-hide-descendants"**: Neither the component nor its child components can be recognized by accessibility services.
Default value: **"auto"**
**Atomic service API**: This API can be used in atomic services since API version 18.| +| accessibilityText18+ | ResourceStr | No| Accessibility text, that is, accessible label name. If a component does not contain text information, it will not be announced by the screen reader when selected. In this case, the screen reader user cannot know which component is selected. To solve this problem, you can set accessibility text for components without text information. When such a component is selected, the screen reader announces the specified accessibility text, informing the user which component is selected.
Default value: value of the **label** property if it is set and an empty string otherwise.
**Atomic service API**: This API can be used in atomic services since API version 18. | +| accessibilityDescription18+ | ResourceStr | No| Accessible description. You can provide comprehensive text explanations to help users understand the operation they are about to perform and its potential consequences, especially when these cannot be inferred from the component's attributes and accessibility text alone. If a component contains both text information and the accessible description, the text is announced first and then the accessible description, when the component is selected.
Default value: **"Double-tap to activate"**
**Atomic service API**: This API can be used in atomic services since API version 18. | ## Events -The [universal events](ts-universal-events-click.md) are not supported. +The [universal events](ts-component-general-events.md) are not supported. ## Example ### Example 1: Implementing a Simple Drop-down Menu Title Bar This example demonstrates how to implement a simple drop-down menu title bar with various configurations, including one with a back arrow and one with a right-side menu item list. ```ts -import { SelectTitleBar, promptAction } from '@kit.ArkUI' +import { SelectTitleBar, promptAction, SelectTitleBarMenuItem } from '@kit.ArkUI' -interface menuItems { - value: Resource; - isEnabled?: boolean; - action?: () => void -} @Entry @Component struct Index { // Define an array of menu items for the right side of the title bar. - private menuItems:Array = - [ - { - // Resource for the menu icon. - value:$r('app.media.ic_public_save'), - // Enable the image. - isEnabled:true, - // Action triggered when the menu item is clicked. - action:() => promptAction.showToast({ message: "show toast index 1" }) - }, - { - value:$r('app.media.ic_public_reduce'), - isEnabled:true, - action:() => promptAction.showToast({ message: "show toast index 2" }) - }, - { - value:$r('app.media.ic_public_edit'), - isEnabled:true, - action:() => promptAction.showToast({ message: "show toast index 3" }) - }, - { - value:$r('app.media.ic_public_reduce'), - isEnabled:true, - action:() => promptAction.showToast({ message: "show toast index 4" }) - } - ] + private menuItems: Array = + [ + { + // Resource for the menu icon. + value: $r('sys.media.ohos_save_button_filled'), + // Enable the image. + isEnabled: true, + // Action triggered when the menu item is clicked. + action: () => promptAction.showToast({ message: 'show toast index 1' }), + }, + { + value: $r('sys.media.ohos_ic_public_copy'), + isEnabled: true, + action: () => promptAction.showToast({ message: 'show toast index 2' }), + }, + { + value: $r('sys.media.ohos_ic_public_edit'), + isEnabled: true, + action: () => promptAction.showToast({ message: 'show toast index 3' }), + }, + { + value: $r('sys.media.ohos_ic_public_remove'), + isEnabled: true, + action: () => promptAction.showToast({ message: 'show toast index 4' }), + }, + ] build() { Row() { Column() { - Divider().height(2).color(0xCCCCCC) + Divider().height(2).color(0xCCCCCC) SelectTitleBar({ // Define items in the drop-down list. options: [ @@ -124,57 +120,57 @@ struct Index { // Function triggered when the item is selected. onSelected: (index) => promptAction.showToast({ message: 'page index ' + index }), // Hide the back arrow on the left. - hidesBackButton: true + hidesBackButton: true, }) Divider().height(2).color(0xCCCCCC) SelectTitleBar({ options: [ { value: 'All photos' }, { value: 'Local (device)' }, - { value: 'Local (memory card)'} + { value: 'Local (memory card)' }, ], selected: 0, onSelected: (index) => promptAction.showToast({ message: 'page index ' + index }), - hidesBackButton: false + hidesBackButton: false, }) Divider().height(2).color(0xCCCCCC) SelectTitleBar({ options: [ { value: 'All photos' }, { value: 'Local (device)' }, - { value: 'Local (memory card)'} + { value: 'Local (memory card)' }, ], selected: 1, onSelected: (index) => promptAction.showToast({ message: 'page index ' + index }), - subtitle: "example@example.com" + subtitle: 'example@example.com', }) Divider().height(2).color(0xCCCCCC) SelectTitleBar({ options: [ { value: 'All photos' }, { value: 'Local (device)' }, - { value: 'Local (memory card)'} + { value: 'Local (memory card)' }, ], selected: 1, onSelected: (index) => promptAction.showToast({ message: 'page index ' + index }), - subtitle: "example@example.com", - menuItems: [{ isEnabled: true, value: $r('app.media.ic_public_save'), - action: () => promptAction.showToast({ message: "show toast index 1" }) - }] + subtitle: 'example@example.com', + menuItems: [{ isEnabled: true, value: $r('sys.media.ohos_save_button_filled'), + action: () => promptAction.showToast({ message: 'show toast index 1' }), + }], }) Divider().height(2).color(0xCCCCCC) SelectTitleBar({ options: [ { value: 'All photos' }, { value: 'Local (device)' }, - { value: 'Local (memory card)'} + { value: 'Local (memory card)' }, ], selected: 0, onSelected: (index) => promptAction.showToast({ message: 'page index ' + index }), - subtitle: "example@example.com", + subtitle: 'example@example.com', menuItems: this.menuItems, badgeValue: 99, - hidesBackButton: true + hidesBackButton: true, }) Divider().height(2).color(0xCCCCCC) }.width('100%') @@ -183,136 +179,261 @@ struct Index { } ``` -![en-us_image_0000001616959836](figures/en-us_image_0000001616959836.jpg) +![en-us_image_selecttitlebar_example01](figures/en-us_image_selecttitlebar_example01.png) ### Example 2: Implementing Screen Reader Announcement for the Custom Button on the Right Side This example customizes the screen reader announcement text by setting the **accessibilityText**, **accessibilityDescription**, and **accessibilityLevel** properties of the custom button on the right side of the title bar. ```ts -import { SelectTitleBar, promptAction } from '@kit.ArkUI' +import { SelectTitleBar, promptAction, SelectTitleBarMenuItem } from '@kit.ArkUI' + +@Entry +@Component +struct Index { + // Define an array of menu items for the right side of the title bar. + private menuItems: Array = + [ + { + // Resource for the menu icon. + value: $r('sys.media.ohos_save_button_filled'), + // Enable the image. + isEnabled: true, + // Action triggered when the menu item is clicked. + action: () => promptAction.showToast({ message: 'show toast index 1' }), + // The screen reader will prioritize this text over the label. + accessibilityText: 'Save', + // The screen reader can focus on this item. + accessibilityLevel: 'yes', + // The screen reader will ultimately announce this text. + accessibilityDescription: 'Tap to save the icon', + }, + { + value: $r('sys.media.ohos_ic_public_copy'), + isEnabled: true, + action: () => promptAction.showToast({ message: 'show toast index 2' }), + accessibilityText: 'Copy', + // The screen reader will not focus on this item. + accessibilityLevel: 'no', + accessibilityDescription: 'Tap to copy the icon', + }, + { + value: $r('sys.media.ohos_ic_public_edit'), + isEnabled: true, + action: () => promptAction.showToast({ message: 'show toast index 3' }), + accessibilityText: 'Edit', + accessibilityLevel: 'yes', + accessibilityDescription: 'Tap to edit the icon', + }, + { + value: $r('sys.media.ohos_ic_public_remove'), + isEnabled: true, + action: () => promptAction.showToast({ message: "show toast index 4" }), + accessibilityText: 'Remove', + accessibilityLevel: 'yes', + accessibilityDescription: 'Tap to remove the icon', + } + ] + + build() { + Row() { + Column() { + Divider().height(2).color(0xCCCCCC) + SelectTitleBar({ + // Define items in the drop-down list. + options: [ + { value: 'All photos' }, + { value: 'Local (device)' }, + { value: 'Local (memory card)' }, + ], + // Initially select the first item in the drop-down list. + selected: 0, + // Function triggered when the item is selected. + onSelected: (index) => promptAction.showToast({ message: 'page index ' + index }), + // Hide the back arrow on the left. + hidesBackButton: true, + }) + Divider().height(2).color(0xCCCCCC) + SelectTitleBar({ + options: [ + { value: 'All photos' }, + { value: 'Local (device)' }, + { value: 'Local (memory card)' }, + ], + selected: 0, + onSelected: (index) => promptAction.showToast({ message: 'page index ' + index }), + hidesBackButton: false, + }) + Divider().height(2).color(0xCCCCCC) + SelectTitleBar({ + options: [ + { value: 'All photos' }, + { value: 'Local (device)' }, + { value: 'Local (memory card)' }, + ], + selected: 1, + onSelected: (index) => promptAction.showToast({ message: 'page index ' + index }), + subtitle: 'example@example.com', + }) + Divider().height(2).color(0xCCCCCC) + SelectTitleBar({ + options: [ + { value: 'All photos' }, + { value: 'Local (device)' }, + { value: 'Local (memory card)' }, + ], + selected: 1, + onSelected: (index) => promptAction.showToast({ message: 'page index ' + index }), + subtitle: 'example@example.com', + menuItems: [{ isEnabled: true, value: $r('sys.media.ohos_save_button_filled'), + action: () => promptAction.showToast({ message: 'show toast index 1' }), + }], + }) + Divider().height(2).color(0xCCCCCC) + SelectTitleBar({ + options: [ + { value: 'All photos' }, + { value: 'Local (device)' }, + { value: 'Local (memory card)' }, + ], + selected: 0, + onSelected: (index) => promptAction.showToast({ message: 'page index ' + index }), + subtitle: 'example@example.com', + menuItems: this.menuItems, + badgeValue: 99, + hidesBackButton: true, + }) + Divider().height(2).color(0xCCCCCC) + }.width('100%') + }.height('100%') + } +} +``` +![en-us_image_selecttitlebar_example02](figures/en-us_image_selecttitlebar_example02.png) -interface menuItems { - value: Resource; - isEnabled?: boolean; - action?: () => void; - accessibilityText?: ResourceStr; - accessibilityDescription?: ResourceStr; - accessibilityLevel?: string -} +### Example 3: Setting the Symbol Icon +This example demonstrates how to use **symbolStyle** in **SelectTitleBarMenuItem** to set custom symbol icons. +```ts +import { SelectTitleBar, promptAction, SelectTitleBarMenuItem, SymbolGlyphModifier } from '@kit.ArkUI' @Entry @Component struct Index { // Define an array of menu items for the right side of the title bar. - private menuItems:Array = - [ - { - // Resource for the menu icon. - value:$r('app.media.ic_public_save'), - // Enable the image. - isEnabled:true, - // Action triggered when the menu item is clicked. - action:() => promptAction.showToast({ message: "show toast index 1" }), - // The screen reader will prioritize this text over the label. - accessibilityText: 'Save', - // The screen reader can focus on this item. - accessibilityLevel: 'yes', - // The screen reader will ultimately announce this text. - accessibilityDescription: 'Tap to save the icon' - }, - { - value:$r('app.media.ic_public_reduce'), - isEnabled:true, - action:() => promptAction.showToast({ message: "show toast index 2" }), - accessibilityText: 'Shrink', - // The screen reader will not focus on this item. - accessibilityLevel: 'no', - accessibilityDescription: 'Tap to shrink the icon' - }, - { - value:$r('app.media.ic_public_edit'), - isEnabled:true, - action:() => promptAction.showToast({ message: "show toast index 3" }), - accessibilityText: 'Edit', - accessibilityLevel: 'yes', - accessibilityDescription: 'Tap to edit the icon' - }, - { - value:$r('app.media.ic_public_reduce'), - isEnabled:true, - action:() => promptAction.showToast({ message: "show toast index 4" }), - accessibilityText: 'Remove', - accessibilityLevel: 'yes', - accessibilityDescription: 'Tap to remove the icon' - } - ] + private menuItems: Array = + [ + { + // Resource for the menu icon. + value: $r('sys.media.ohos_save_button_filled'), + // Resource for the menu symbol icon. + symbolStyle: new SymbolGlyphModifier($r('sys.symbol.save')), + // Enable the image. + isEnabled: true, + // Action triggered when the menu item is clicked. + action: () => promptAction.showToast({ message: 'show toast index 1' }), + // The screen reader will prioritize this text over the label. + accessibilityText: 'Save', + // The screen reader can focus on this item. + accessibilityLevel: 'yes', + // The screen reader will ultimately announce this text. + accessibilityDescription: 'Tap to save the icon', + }, + { + value: $r('sys.media.ohos_ic_public_copy'), + symbolStyle: new SymbolGlyphModifier($r('sys.symbol.car')), + isEnabled: true, + action: () => promptAction.showToast({ message: 'show toast index 2' }), + accessibilityText: 'Copy', + // The screen reader will not focus on this item. + accessibilityLevel: 'no', + accessibilityDescription: 'Tap to copy the icon', + }, + { + value: $r('sys.media.ohos_ic_public_edit'), + symbolStyle: new SymbolGlyphModifier($r('sys.symbol.ai_edit')), + isEnabled: true, + action: () => promptAction.showToast({ message: 'show toast index 3' }), + accessibilityText: 'Edit', + accessibilityLevel: 'yes', + accessibilityDescription: 'Tap to edit the icon', + }, + { + value: $r('sys.media.ohos_ic_public_remove'), + symbolStyle: new SymbolGlyphModifier($r('sys.symbol.remove_songlist')), + isEnabled: true, + action: () => promptAction.showToast({ message: "show toast index 4" }), + accessibilityText: 'Remove', + accessibilityLevel: 'yes', + accessibilityDescription: 'Tap to remove the icon', + } + ] build() { Row() { Column() { - Divider().height(2).color(0xCCCCCC) + Divider().height(2).color(0xCCCCCC) SelectTitleBar({ // Define items in the drop-down list. options: [ { value: 'All photos' }, { value: 'Local (device)' }, - { value: 'Local (memory card)'} + { value: 'Local (memory card)' }, ], // Initially select the first item in the drop-down list. selected: 0, // Function triggered when the item is selected. onSelected: (index) => promptAction.showToast({ message: 'page index ' + index }), // Hide the back arrow on the left. - hidesBackButton: true + hidesBackButton: true, }) Divider().height(2).color(0xCCCCCC) SelectTitleBar({ options: [ { value: 'All photos' }, { value: 'Local (device)' }, - { value: 'Local (memory card)'} + { value: 'Local (memory card)' }, ], selected: 0, onSelected: (index) => promptAction.showToast({ message: 'page index ' + index }), - hidesBackButton: false + hidesBackButton: false, }) Divider().height(2).color(0xCCCCCC) SelectTitleBar({ options: [ { value: 'All photos' }, { value: 'Local (device)' }, - { value: 'Local (memory card)'} + { value: 'Local (memory card)' }, ], selected: 1, onSelected: (index) => promptAction.showToast({ message: 'page index ' + index }), - subtitle: "example@example.com" + subtitle: 'example@example.com', }) Divider().height(2).color(0xCCCCCC) SelectTitleBar({ options: [ { value: 'All photos' }, { value: 'Local (device)' }, - { value: 'Local (memory card)'} + { value: 'Local (memory card)' }, ], selected: 1, onSelected: (index) => promptAction.showToast({ message: 'page index ' + index }), - subtitle: "example@example.com", - menuItems: [{ isEnabled: true, value: $r('app.media.ic_public_save'), - action: () => promptAction.showToast({ message: "show toast index 1" }) - }] + subtitle: 'example@example.com', + menuItems: [{ + isEnabled: true, value: $r('sys.media.ohos_save_button_filled'), + action: () => promptAction.showToast({ message: 'show toast index 1' }), + }], }) Divider().height(2).color(0xCCCCCC) SelectTitleBar({ options: [ { value: 'All photos' }, { value: 'Local (device)' }, - { value: 'Local (memory card)'} + { value: 'Local (memory card)' }, ], selected: 0, onSelected: (index) => promptAction.showToast({ message: 'page index ' + index }), - subtitle: "example@example.com", + subtitle: 'example@example.com', menuItems: this.menuItems, badgeValue: 99, - hidesBackButton: true + hidesBackButton: true, }) Divider().height(2).color(0xCCCCCC) }.width('100%') @@ -320,4 +441,4 @@ struct Index { } } ``` -![en-us_image_0000001616959836](figures/en-us_image_0000001616959836.jpg) +![en-us_image_selecttitlebar_example03](figures/en-us_image_selecttitlebar_example03.png) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-SelectionMenu.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-SelectionMenu.md index a8468558fca22e27b638707c4980bfeb46d6df60..b23cdf2942b16ba9332b47cff702d29e939e9ed8 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-SelectionMenu.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-SelectionMenu.md @@ -67,6 +67,7 @@ Describes the edit menu options. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | icon | [ResourceStr](ts-types.md#resourcestr) | Yes| Icon.| +| symbolStyle18+ | [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) | No| Symbol icon resource, which has higher priority than **icon**.
**Atomic service API**: This API can be used in atomic services since API version 18.| | builder | () => void | No| Builder of the custom component displayed upon click. It must be used with @Builder for building the custom component.| | action | () => void | No| Action triggered when the menu option is clicked.| @@ -99,49 +100,57 @@ Provides the information about the selected content. ## Attributes -The [universal attributes](ts-universal-attributes-size.md) are not supported. The default width is 224 vp, and the height is adaptive. +The [universal attributes](ts-component-general-attributes.md) are not supported. The default width is 224 vp, and the height is adaptive. ## Events -The [universal events](ts-universal-events-click.md) are not supported. +The [universal events](ts-component-general-events.md) are not supported. ## Example +### Example 1: Binding Context Menus on Selection with Different Trigger Methods This example demonstrates the effects of a custom context menu on selection bound to text with different triggering modes. ```ts -import { SelectionMenu, EditorMenuOptions, ExpandedMenuOptions, EditorEventInfo, SelectionMenuOptions } from '@kit.ArkUI' +import { + SelectionMenu, + EditorMenuOptions, + ExpandedMenuOptions, + EditorEventInfo, + SelectionMenuOptions +} from '@kit.ArkUI' @Entry @Component struct Index { - @State select: boolean = true + @State select: boolean = true; controller: RichEditorController = new RichEditorController(); - options: RichEditorOptions = { controller: this.controller } - @State message: string = 'Hello word' - @State textSize: number = 30 - @State fontWeight: FontWeight = FontWeight.Normal - @State start: number = -1 - @State end: number = -1 - @State visibleValue: Visibility = Visibility.Visible - @State colorTransparent: Color = Color.Transparent - @State textStyle: RichEditorTextStyle = {} + options: RichEditorOptions = { controller: this.controller }; + @State message: string = 'Hello world'; + @State textSize: number = 30; + @State fontWeight: FontWeight = FontWeight.Normal; + @State start: number = -1; + @State end: number = -1; + @State visibleValue: Visibility = Visibility.Visible; + @State colorTransparent: Color = Color.Transparent; + @State textStyle: RichEditorTextStyle = {}; private editorMenuOptions: Array = [ - { icon: $r("app.media.ic_notepad_textbold"), action: () => { + { + icon: $r("app.media.ic_notepad_textbold"), action: () => { if (this.controller) { let selection = this.controller.getSelection(); - let spans = selection.spans + let spans = selection.spans; spans.forEach((item: RichEditorTextSpanResult | RichEditorImageSpanResult, index) => { if (typeof (item as RichEditorTextSpanResult)['textStyle'] != 'undefined') { - let span = item as RichEditorTextSpanResult - this.textStyle = span.textStyle - let start = span.offsetInSpan[0] - let end = span.offsetInSpan[1] - let offset = span.spanPosition.spanRange[0] + let span = item as RichEditorTextSpanResult; + this.textStyle = span.textStyle; + let start = span.offsetInSpan[0]; + let end = span.offsetInSpan[1]; + let offset = span.spanPosition.spanRange[0]; if (this.textStyle.fontWeight != 11) { - this.textStyle.fontWeight = FontWeight.Bolder + this.textStyle.fontWeight = FontWeight.Bolder; } else { - this.textStyle.fontWeight = FontWeight.Normal + this.textStyle.fontWeight = FontWeight.Normal; } this.controller.updateSpanStyle({ start: offset + start, @@ -151,22 +160,24 @@ struct Index { } }) } - } }, - { icon: $r("app.media.ic_notepad_texttilt"), action: () => { + } + }, + { + icon: $r("app.media.ic_notepad_texttilt"), action: () => { if (this.controller) { let selection = this.controller.getSelection(); - let spans = selection.spans + let spans = selection.spans; spans.forEach((item: RichEditorTextSpanResult | RichEditorImageSpanResult, index) => { if (typeof (item as RichEditorTextSpanResult)['textStyle'] != 'undefined') { - let span = item as RichEditorTextSpanResult - this.textStyle = span.textStyle - let start = span.offsetInSpan[0] - let end = span.offsetInSpan[1] - let offset = span.spanPosition.spanRange[0] + let span = item as RichEditorTextSpanResult; + this.textStyle = span.textStyle; + let start = span.offsetInSpan[0]; + let end = span.offsetInSpan[1]; + let offset = span.spanPosition.spanRange[0]; if (this.textStyle.fontStyle == FontStyle.Italic) { - this.textStyle.fontStyle = FontStyle.Normal + this.textStyle.fontStyle = FontStyle.Normal; } else { - this.textStyle.fontStyle = FontStyle.Italic + this.textStyle.fontStyle = FontStyle.Italic; } this.controller.updateSpanStyle({ start: offset + start, @@ -176,24 +187,26 @@ struct Index { } }) } - } }, - { icon: $r("app.media.ic_notepad_underline"), + } + }, + { + icon: $r("app.media.ic_notepad_underline"), action: () => { if (this.controller) { let selection = this.controller.getSelection(); - let spans = selection.spans + let spans = selection.spans; spans.forEach((item: RichEditorTextSpanResult | RichEditorImageSpanResult, index) => { if (typeof (item as RichEditorTextSpanResult)['textStyle'] != 'undefined') { - let span = item as RichEditorTextSpanResult - this.textStyle = span.textStyle - let start = span.offsetInSpan[0] - let end = span.offsetInSpan[1] - let offset = span.spanPosition.spanRange[0] + let span = item as RichEditorTextSpanResult; + this.textStyle = span.textStyle; + let start = span.offsetInSpan[0]; + let end = span.offsetInSpan[1]; + let offset = span.spanPosition.spanRange[0]; if (this.textStyle.decoration) { if (this.textStyle.decoration.type == TextDecorationType.Underline) { - this.textStyle.decoration.type = TextDecorationType.None + this.textStyle.decoration.type = TextDecorationType.None; } else { - this.textStyle.decoration.type = TextDecorationType.Underline + this.textStyle.decoration.type = TextDecorationType.Underline; } } else { this.textStyle.decoration = { type: TextDecorationType.Underline, color: Color.Black } @@ -208,23 +221,26 @@ struct Index { } } }, - { icon: $r("app.media.app_icon"), action: () => { - }, builder: (): void => this.sliderPanel() }, - { icon: $r("app.media.ic_notepad_textcolor"), action: () => { + { + icon: $r("app.media.ic_notepad_fontsize"), action: () => { + }, builder: (): void => this.sliderPanel() + }, + { + icon: $r("app.media.ic_notepad_textcolor"), action: () => { if (this.controller) { let selection = this.controller.getSelection(); - let spans = selection.spans + let spans = selection.spans; spans.forEach((item: RichEditorTextSpanResult | RichEditorImageSpanResult, index) => { if (typeof (item as RichEditorTextSpanResult)['textStyle'] != 'undefined') { - let span = item as RichEditorTextSpanResult - this.textStyle = span.textStyle - let start = span.offsetInSpan[0] - let end = span.offsetInSpan[1] - let offset = span.spanPosition.spanRange[0] + let span = item as RichEditorTextSpanResult; + this.textStyle = span.textStyle; + let start = span.offsetInSpan[0]; + let end = span.offsetInSpan[1]; + let offset = span.spanPosition.spanRange[0]; if (this.textStyle.fontColor == Color.Orange || this.textStyle.fontColor == '#FFFFA500') { - this.textStyle.fontColor = Color.Black + this.textStyle.fontColor = Color.Black; } else { - this.textStyle.fontColor = Color.Orange + this.textStyle.fontColor = Color.Orange; } this.controller.updateSpanStyle({ start: offset + start, @@ -234,12 +250,19 @@ struct Index { } }) } - } }] + } + }] private expandedMenuOptions: Array = - [{ startIcon: $r("app.media.icon"), content: 'Dictionary', action: () => { - } }, { startIcon: $r("app.media.icon"), content: 'Translate', action: () => { - } }, { startIcon: $r("app.media.icon"), content: 'Search', action: () => { - } }] + [{ + startIcon: $r("app.media.startIcon"), content: 'Dictionary', action: () => { + } + }, { + startIcon: $r("app.media.startIcon"), content: 'Translate', action: () => { + } + }, { + startIcon: $r("app.media.startIcon"), content: 'Search', action: () => { + } + }] private expandedMenuOptions1: Array = [] private editorMenuOptions1: Array = [] private selectionMenuOptions: SelectionMenuOptions = { @@ -250,9 +273,9 @@ struct Index { if (event && event.content) { event.content.spans.forEach((item: RichEditorTextSpanResult | RichEditorImageSpanResult, index) => { if (typeof (item as RichEditorTextSpanResult)['textStyle'] != 'undefined') { - let span = item as RichEditorTextSpanResult - console.info('test cut' + span.value) - console.info('test start ' + span.offsetInSpan[0] + ' end: ' + span.offsetInSpan[1]) + let span = item as RichEditorTextSpanResult; + console.info('test cut' + span.value); + console.info('test start ' + span.offsetInSpan[0] + ' end: ' + span.offsetInSpan[1]); } }) } @@ -261,9 +284,9 @@ struct Index { if (event && event.content) { event.content.spans.forEach((item: RichEditorTextSpanResult | RichEditorImageSpanResult, index) => { if (typeof (item as RichEditorTextSpanResult)['textStyle'] != 'undefined') { - let span = item as RichEditorTextSpanResult - console.info('test onPaste' + span.value) - console.info('test start ' + span.offsetInSpan[0] + ' end: ' + span.offsetInSpan[1]) + let span = item as RichEditorTextSpanResult; + console.info('test onPaste' + span.value); + console.info('test start ' + span.offsetInSpan[0] + ' end: ' + span.offsetInSpan[1]); } }) } @@ -272,9 +295,9 @@ struct Index { if (event && event.content) { event.content.spans.forEach((item: RichEditorTextSpanResult | RichEditorImageSpanResult, index) => { if (typeof (item as RichEditorTextSpanResult)['textStyle'] != 'undefined') { - let span = item as RichEditorTextSpanResult - console.info('test cut' + span.value) - console.info('test start ' + span.offsetInSpan[0] + ' end: ' + span.offsetInSpan[1]) + let span = item as RichEditorTextSpanResult; + console.info('test cut' + span.value); + console.info('test start ' + span.offsetInSpan[0] + ' end: ' + span.offsetInSpan[1]); } }) } @@ -283,16 +306,17 @@ struct Index { if (event && event.content) { event.content.spans.forEach((item: RichEditorTextSpanResult | RichEditorImageSpanResult, index) => { if (typeof (item as RichEditorTextSpanResult)['textStyle'] != 'undefined') { - let span = item as RichEditorTextSpanResult - console.info('test onPaste' + span.value) - console.info('test start ' + span.offsetInSpan[0] + ' end: ' + span.offsetInSpan[1]) + let span = item as RichEditorTextSpanResult; + console.info('test onPaste' + span.value); + console.info('test start ' + span.offsetInSpan[0] + ' end: ' + span.offsetInSpan[1]); } }) } } } - @Builder sliderPanel() { + @Builder + sliderPanel() { Column() { Flex({ justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) { Text('A').fontSize(15) @@ -303,19 +327,19 @@ struct Index { let selection = this.controller.getSelection(); if (mode == SliderChangeMode.End) { if (this.textSize == undefined) { - this.textSize = 0 + this.textSize = 0; } - let spans = selection.spans + let spans = selection.spans; spans.forEach((item: RichEditorTextSpanResult | RichEditorImageSpanResult, index) => { if (typeof (item as RichEditorTextSpanResult)['textStyle'] != 'undefined') { - this.textSize = Math.max(this.textSize, (item as RichEditorTextSpanResult).textStyle.fontSize) + this.textSize = Math.max(this.textSize, (item as RichEditorTextSpanResult).textStyle.fontSize); } }) } if (mode == SliderChangeMode.Moving || mode == SliderChangeMode.Click) { - this.start = selection.selection[0] - this.end = selection.selection[1] - this.textSize = value + this.start = selection.selection[0]; + this.end = selection.selection[1]; + this.textSize = value; this.controller.updateSpanStyle({ start: this.start, end: this.end, @@ -360,7 +384,7 @@ struct Index { MyMenu3() { Column() { SelectionMenu({ - editorMenuOptions: this.editorMenuOptions1, + editorMenuOptions: this.editorMenuOptions, expandedMenuOptions: this.expandedMenuOptions, controller: this.controller, }) @@ -374,21 +398,21 @@ struct Index { Button("SetSelection") .onClick((event: ClickEvent) => { if (this.controller) { - this.controller.setSelection(0, 2) + this.controller.setSelection(0, 2); } }) RichEditor(this.options) .onReady(() => { - this.controller.addTextSpan(this.message, { style: { fontColor: Color.Orange, fontSize: 30 } }) - this.controller.addTextSpan(this.message, { style: { fontColor: Color.Black, fontSize: 25 } }) + this.controller.addTextSpan(this.message, { style: { fontColor: Color.Orange, fontSize: 30 } }); + this.controller.addTextSpan(this.message, { style: { fontColor: Color.Black, fontSize: 25 } }); }) .onSelect((value: RichEditorSelection) => { if (value.selection[0] == -1 && value.selection[1] == -1) { - return + return; } - this.start = value.selection[0] - this.end = value.selection[1] + this.start = value.selection[0]; + this.end = value.selection[1]; }) .bindSelectionMenu(RichEditorSpanType.TEXT, this.MyMenu3(), RichEditorResponseType.RIGHT_CLICK) .bindSelectionMenu(RichEditorSpanType.TEXT, this.MyMenu2(), RichEditorResponseType.SELECT) @@ -396,6 +420,7 @@ struct Index { .borderColor(Color.Red) .width(200) .height(200) + .margin(10) } } } @@ -404,4 +429,331 @@ struct Index { > > Icons in bold and italics are not preset in the system. The sample code uses the default icons. You need to replace the icons in **editorMenuOptions** with the desired icons. -![selectionmenu](figures/selectionmenu.jpeg) +![selectionmenu](figures/selectionmenu.gif) + +### Example 2: Setting the Symbol Icon + +This example demonstrates how to use **symbolStyle** in **EditorMenuOptions** to set custom symbol icons. + +```ts +import { + SelectionMenu, + EditorMenuOptions, + ExpandedMenuOptions, + EditorEventInfo, + SelectionMenuOptions, + SymbolGlyphModifier +} from '@kit.ArkUI' + +@Entry +@Component +struct Index { + @State select: boolean = true; + controller: RichEditorController = new RichEditorController(); + options: RichEditorOptions = { controller: this.controller }; + @State message: string = 'Hello world'; + @State textSize: number = 30; + @State fontWeight: FontWeight = FontWeight.Normal; + @State start: number = -1; + @State end: number = -1; + @State visibleValue: Visibility = Visibility.Visible; + @State colorTransparent: Color = Color.Transparent; + @State textStyle: RichEditorTextStyle = {}; + private editorMenuOptions: Array = + [ + { + icon: $r("sys.media.wifi_router_fill"), + symbolStyle: new SymbolGlyphModifier($r('sys.symbol.save')), + action: () => { + if (this.controller) { + let selection = this.controller.getSelection(); + let spans = selection.spans; + spans.forEach((item: RichEditorTextSpanResult | RichEditorImageSpanResult, index) => { + if (typeof (item as RichEditorTextSpanResult)['textStyle'] != 'undefined') { + let span = item as RichEditorTextSpanResult; + this.textStyle = span.textStyle; + let start = span.offsetInSpan[0]; + let end = span.offsetInSpan[1]; + let offset = span.spanPosition.spanRange[0]; + if (this.textStyle.fontWeight != 11) { + this.textStyle.fontWeight = FontWeight.Bolder; + } else { + this.textStyle.fontWeight = FontWeight.Normal; + } + this.controller.updateSpanStyle({ + start: offset + start, + end: offset + end, + textStyle: this.textStyle + }) + } + }) + } + } + }, + { + icon: $r("sys.media.save_button_picture"), + symbolStyle: new SymbolGlyphModifier($r('sys.symbol.camera')), + action: () => { + if (this.controller) { + let selection = this.controller.getSelection(); + let spans = selection.spans; + spans.forEach((item: RichEditorTextSpanResult | RichEditorImageSpanResult, index) => { + if (typeof (item as RichEditorTextSpanResult)['textStyle'] != 'undefined') { + let span = item as RichEditorTextSpanResult; + this.textStyle = span.textStyle; + let start = span.offsetInSpan[0]; + let end = span.offsetInSpan[1]; + let offset = span.spanPosition.spanRange[0]; + if (this.textStyle.fontStyle == FontStyle.Italic) { + this.textStyle.fontStyle = FontStyle.Normal; + } else { + this.textStyle.fontStyle = FontStyle.Italic; + } + this.controller.updateSpanStyle({ + start: offset + start, + end: offset + end, + textStyle: this.textStyle + }) + } + }) + } + } + }, + { + icon: $r("sys.media.waveform_folder_fill"), + symbolStyle: new SymbolGlyphModifier($r('sys.symbol.car')), + action: () => { + if (this.controller) { + let selection = this.controller.getSelection(); + let spans = selection.spans; + spans.forEach((item: RichEditorTextSpanResult | RichEditorImageSpanResult, index) => { + if (typeof (item as RichEditorTextSpanResult)['textStyle'] != 'undefined') { + let span = item as RichEditorTextSpanResult; + this.textStyle = span.textStyle; + let start = span.offsetInSpan[0]; + let end = span.offsetInSpan[1]; + let offset = span.spanPosition.spanRange[0]; + if (this.textStyle.decoration) { + if (this.textStyle.decoration.type == TextDecorationType.Underline) { + this.textStyle.decoration.type = TextDecorationType.None; + } else { + this.textStyle.decoration.type = TextDecorationType.Underline; + } + } else { + this.textStyle.decoration = { type: TextDecorationType.Underline, color: Color.Black } + } + this.controller.updateSpanStyle({ + start: offset + start, + end: offset + end, + textStyle: this.textStyle + }) + } + }) + } + } + }, + { + icon: $r("app.media.app_icon"), action: () => { + }, builder: (): void => this.sliderPanel() + }, + { + icon: $r("sys.media.thermometer_fill"), action: () => { + if (this.controller) { + let selection = this.controller.getSelection(); + let spans = selection.spans; + spans.forEach((item: RichEditorTextSpanResult | RichEditorImageSpanResult, index) => { + if (typeof (item as RichEditorTextSpanResult)['textStyle'] != 'undefined') { + let span = item as RichEditorTextSpanResult; + this.textStyle = span.textStyle; + let start = span.offsetInSpan[0]; + let end = span.offsetInSpan[1]; + let offset = span.spanPosition.spanRange[0]; + if (this.textStyle.fontColor == Color.Orange || this.textStyle.fontColor == '#FFFFA500') { + this.textStyle.fontColor = Color.Black; + } else { + this.textStyle.fontColor = Color.Orange; + } + this.controller.updateSpanStyle({ + start: offset + start, + end: offset + end, + textStyle: this.textStyle + }) + } + }) + } + } + }] + private expandedMenuOptions: Array = + [{ + startIcon: $r("app.media.startIcon"), content: 'Dictionary', action: () => { + } + }, { + startIcon: $r("app.media.startIcon"), content: 'Translate', action: () => { + } + }, { + startIcon: $r("app.media.startIcon"), content: 'Search', action: () => { + } + }] + private expandedMenuOptions1: Array = [] + private editorMenuOptions1: Array = [] + private selectionMenuOptions: SelectionMenuOptions = { + editorMenuOptions: this.editorMenuOptions, + expandedMenuOptions: this.expandedMenuOptions, + controller: this.controller, + onCut: (event?: EditorEventInfo) => { + if (event && event.content) { + event.content.spans.forEach((item: RichEditorTextSpanResult | RichEditorImageSpanResult, index) => { + if (typeof (item as RichEditorTextSpanResult)['textStyle'] != 'undefined') { + let span = item as RichEditorTextSpanResult; + console.info('test cut' + span.value); + console.info('test start ' + span.offsetInSpan[0] + ' end: ' + span.offsetInSpan[1]); + } + }) + } + }, + onPaste: (event?: EditorEventInfo) => { + if (event && event.content) { + event.content.spans.forEach((item: RichEditorTextSpanResult | RichEditorImageSpanResult, index) => { + if (typeof (item as RichEditorTextSpanResult)['textStyle'] != 'undefined') { + let span = item as RichEditorTextSpanResult; + console.info('test onPaste' + span.value); + console.info('test start ' + span.offsetInSpan[0] + ' end: ' + span.offsetInSpan[1]); + } + }) + } + }, + onCopy: (event?: EditorEventInfo) => { + if (event && event.content) { + event.content.spans.forEach((item: RichEditorTextSpanResult | RichEditorImageSpanResult, index) => { + if (typeof (item as RichEditorTextSpanResult)['textStyle'] != 'undefined') { + let span = item as RichEditorTextSpanResult; + console.info('test cut' + span.value); + console.info('test start ' + span.offsetInSpan[0] + ' end: ' + span.offsetInSpan[1]); + } + }) + } + }, + onSelectAll: (event?: EditorEventInfo) => { + if (event && event.content) { + event.content.spans.forEach((item: RichEditorTextSpanResult | RichEditorImageSpanResult, index) => { + if (typeof (item as RichEditorTextSpanResult)['textStyle'] != 'undefined') { + let span = item as RichEditorTextSpanResult; + console.info('test onPaste' + span.value); + console.info('test start ' + span.offsetInSpan[0] + ' end: ' + span.offsetInSpan[1]); + } + }) + } + } + } + + @Builder + sliderPanel() { + Column() { + Flex({ justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) { + Text('A').fontSize(15) + Slider({ value: this.textSize, step: 10, style: SliderStyle.InSet }) + .width(210) + .onChange((value: number, mode: SliderChangeMode) => { + if (this.controller) { + let selection = this.controller.getSelection(); + if (mode == SliderChangeMode.End) { + if (this.textSize == undefined) { + this.textSize = 0; + } + let spans = selection.spans; + spans.forEach((item: RichEditorTextSpanResult | RichEditorImageSpanResult, index) => { + if (typeof (item as RichEditorTextSpanResult)['textStyle'] != 'undefined') { + this.textSize = Math.max(this.textSize, (item as RichEditorTextSpanResult).textStyle.fontSize); + } + }) + } + if (mode == SliderChangeMode.Moving || mode == SliderChangeMode.Click) { + this.start = selection.selection[0]; + this.end = selection.selection[1]; + this.textSize = value; + this.controller.updateSpanStyle({ + start: this.start, + end: this.end, + textStyle: { fontSize: this.textSize } + }) + } + } + }) + Text('A').fontSize(20).fontWeight(FontWeight.Medium) + }.borderRadius($r('sys.float.ohos_id_corner_radius_card')) + } + .shadow(ShadowStyle.OUTER_DEFAULT_MD) + .backgroundColor(Color.White) + .borderRadius($r('sys.float.ohos_id_corner_radius_card')) + .padding(15) + .height(48) + } + + @Builder + MyMenu() { + Column() { + SelectionMenu(this.selectionMenuOptions) + } + .width(256) + .backgroundColor(Color.Transparent) + } + + @Builder + MyMenu2() { + Column() { + SelectionMenu({ + editorMenuOptions: this.editorMenuOptions, + expandedMenuOptions: this.expandedMenuOptions1, + controller: this.controller, + }) + } + .width(256) + .backgroundColor(Color.Transparent) + } + + @Builder + MyMenu3() { + Column() { + SelectionMenu({ + editorMenuOptions: this.editorMenuOptions1, + expandedMenuOptions: this.expandedMenuOptions, + controller: this.controller, + }) + } + .width(256) + .backgroundColor(Color.Transparent) + } + + build() { + Column() { + Button("SetSelection") + .onClick((event: ClickEvent) => { + if (this.controller) { + this.controller.setSelection(0, 2); + } + }) + + RichEditor(this.options) + .onReady(() => { + this.controller.addTextSpan(this.message, { style: { fontColor: Color.Orange, fontSize: 30 } }); + this.controller.addTextSpan(this.message, { style: { fontColor: Color.Black, fontSize: 25 } }); + }) + .onSelect((value: RichEditorSelection) => { + if (value.selection[0] == -1 && value.selection[1] == -1) { + return; + } + this.start = value.selection[0]; + this.end = value.selection[1]; + }) + .bindSelectionMenu(RichEditorSpanType.TEXT, this.MyMenu3(), RichEditorResponseType.RIGHT_CLICK) + .bindSelectionMenu(RichEditorSpanType.TEXT, this.MyMenu2(), RichEditorResponseType.SELECT) + .borderWidth(1) + .borderColor(Color.Red) + .width(200) + .height(200) + } + } +} +``` + +![selectionmenu02](figures/selectionmenu02.jpg) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-SplitLayout.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-SplitLayout.md index 10a11a6ba06223873ba5e8cd65f40bdc77417745..e7559eadce7ef57252b3ec6c7577c9084dbf2c2c 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-SplitLayout.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-SplitLayout.md @@ -12,7 +12,7 @@ ## Modules to Import ``` -import { SplitLayout } from '@kit.ArkUI' +import { SplitLayout } from '@kit.ArkUI'; ``` @@ -21,7 +21,7 @@ import { SplitLayout } from '@kit.ArkUI' Not supported ## Attributes -The [universal attributes](ts-universal-attributes-size.md) are not supported. +The [universal attributes](ts-component-general-attributes.md) are not supported. ## SplitLayout @@ -36,40 +36,40 @@ SplitLayout({mainImage: Resource, primaryText: string, secondaryText?: string, t | Name| Type| Mandatory| Decorator | Description | | -------- | -------- | -------- |---------------|--------| -| mainImage | [ResourceStr](ts-types.md#resourcestr) | Yes| - | Image. | +| mainImage | [ResourceStr](ts-types.md#resourcestr) | Yes| @State | Image. | | primaryText | [ResourceStr](ts-types.md#resourcestr) | Yes| @Prop | Title. | | secondaryText | [ResourceStr](ts-types.md#resourcestr) | No| @Prop | Subtitle.| | tertiaryText | [ResourceStr](ts-types.md#resourcestr) | No| @Prop | Auxiliary text. | | container | () => void | Yes| @BuilderParam | Container in the component.| ## Events -The [universal events](ts-universal-events-click.md) are not supported. +The [universal events](ts-component-general-events.md) are not supported. ## Example This example demonstrates how to use **SplitLayout** to achieve a page layout that is both adaptable and responsive. ```ts -import { SplitLayout } from '@kit.ArkUI' +import { SplitLayout } from '@kit.ArkUI'; @Entry @Component struct Index { - @State demoImage: Resource = $r("app.media.music") + @State demoImage: Resource = $r("app.media.background"); build() { - Column() { - SplitLayout({ - mainImage: this.demoImage, - primaryText:'New music recommendation', - secondaryText: 'Get a playlist tailored to your taste;', - tertiaryText: "Updated every day", - }) { - Text('Example: Components can be added to a blank area container.') - .margin({top:36}) - } + Column() { + SplitLayout({ + mainImage: this.demoImage, + primaryText:'New music recommendation', + secondaryText: 'Get a playlist tailored to your taste;', + tertiaryText: 'Updated every day', + }) { + Text('Example: Components can be added to a blank area container.') + .margin({ top: 36 }) } - .justifyContent(FlexAlign.SpaceBetween) - .height('100%') - .width('100%') + } + .justifyContent(FlexAlign.SpaceBetween) + .height('100%') + .width('100%') } } ``` diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-SubHeader.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-SubHeader.md index 546468bba4bea6ca6ca1a094c8c88892d982583f..a6d0214792af789581695f3401e8bedc75a6b85f 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-SubHeader.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-SubHeader.md @@ -22,7 +22,7 @@ Not supported ## Attributes -The [universal attributes](ts-universal-attributes-size.md) are supported. +The [universal attributes](ts-component-general-attributes.md) are not supported. > **NOTE** > @@ -30,27 +30,30 @@ The [universal attributes](ts-universal-attributes-size.md) are supported. ## SubHeader -SubHeader({icon?: ResourceStr, iconSymbolOptions?: SymbolOptions, primaryTitle?: ResourceStr, secondaryTitle?: ResourceStr, select?: SelectOptions, operationType?: OperationType, operationItem?: Array<OperationOption>, operationSymbolOptions?: Array<SymbolOptions>}) +SubHeader({icon?: ResourceStr, iconSymbolOptions?: SymbolOptions, primaryTitle?: ResourceStr, secondaryTitle?: +ResourceStr, select?: SelectOptions, operationType?: OperationType, operationItem?: Array<OperationOption>, +operationSymbolOptions?: Array<SymbolOptions>, primaryTitleModifier?: TextModifier, secondaryTitleModifier?: +TextModifier, titleBuilder?: () => void, contentMargin?: LocalizedMargin, contentPadding?: LocalizedPadding}) **Decorator**: @Component **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name| Type| Mandatory| Decorator| Description| -| -------- | -------- | -------- | -------- | -------- | -| icon | [ResourceStr](ts-types.md#resourcestr) | No| \@Prop | Icon.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| iconSymbolOptions12+ | [SymbolOptions](#symboloptions12) | No| - | Icon symbol options. This parameter is available when **icon** is set to a [symbol glyph](ts-basic-components-symbolGlyph.md).
**Atomic service API**: This API can be used in atomic services since API version 12.| -| primaryTitle | [ResourceStr](ts-types.md#resourcestr) | No| \@Prop | Primary title.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| secondaryTitle | [ResourceStr](ts-types.md#resourcestr) | No| \@Prop | Secondary title.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| select | [SelectOptions](#selectoptions) | No| - | Content and events for selection.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| operationType | [OperationType](#operationtype) | No| \@Prop | Type of operation in the operation area (right).
Default value: **OperationType.BUTTON**
**Atomic service API**: This API can be used in atomic services since API version 11.| -| operationItem | Array<[OperationOption](#operationoption)> | No| - | Items in the operation area (right).
**Atomic service API**: This API can be used in atomic services since API version 11.| -| operationSymbolOptions12+ | Array<[SymbolOptions](#symboloptions12)> | No| - | Icon symbol options.
This parameter is available when **operationType** is set to **OperationType.ICON_GROUP** and **operationItem** is set to an array of items.
**Atomic service API**: This API can be used in atomic services since API version 12.| -| primaryTitleModifier12+ | [TextModifier](ts-universal-attributes-attribute-modifier.md) | No| - | Text attributes of the primary title, such as the font color, font size, and font weight.
**Atomic service API**: This API can be used in atomic services since API version 12.| -| secondaryTitleModifier12+ | [TextModifier](ts-universal-attributes-attribute-modifier.md) | No| - | Text attributes of the secondary title, such as the font color, font size, and font weight.
**Atomic service API**: This API can be used in atomic services since API version 12.| -| titleBuilder12+ | () => void | No| @BuildParam | Content of the custom title area.
**Atomic service API**: This API can be used in atomic services since API version 12.| -| contentMargin12+ | [LocalizedMargin](ts-types.md#localizedmargin12) | No| @Prop | Margin of the content. Negative numbers are not supported.
Default value:
`{start: LengthMetrics.resource(`
`$r('sys.float.margin_left'))`,
`end: LengthMetrics.resource(`
`$r('sys.float.margin_right'))}`
**Atomic service API**: This API can be used in atomic services since API version 12.| -| contentPadding12+ | [LocalizedPadding](ts-types.md#localizedpadding12) | No| @Prop | Padding of the content.
Default value:
If a secondary title, with or without an icon, is displayed on the left:
{start: LengthMetircs.vp(12), end: LengthMetrics.vp(12)}
**Atomic service API**: This API can be used in atomic services since API version 12.| +| Name| Type| Mandatory| Decorator | Description| +| -------- | -------- | -------- |---------------| -------- | +| icon | [ResourceStr](ts-types.md#resourcestr) | No| \@Prop | Icon.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| iconSymbolOptions12+ | [SymbolOptions](#symboloptions12) | No| - | Icon symbol options. This parameter is available when **icon** is set to a [symbol glyph](ts-basic-components-symbolGlyph.md).
**Atomic service API**: This API can be used in atomic services since API version 12.| +| primaryTitle | [ResourceStr](ts-types.md#resourcestr) | No| \@Prop | Primary title.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| secondaryTitle | [ResourceStr](ts-types.md#resourcestr) | No| \@Prop | Secondary title.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| select | [SelectOptions](#selectoptions) | No| - | Content and events for selection.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| operationType | [OperationType](#operationtype) | No| \@Prop | Type of operation in the operation area (right).
Default value: **OperationType.BUTTON**
**Atomic service API**: This API can be used in atomic services since API version 11.| +| operationItem | Array<[OperationOption](#operationoption)> | No| - | Items in the operation area (right).
**Atomic service API**: This API can be used in atomic services since API version 11.| +| operationSymbolOptions12+ | Array<[SymbolOptions](#symboloptions12)> | No| - | Icon symbol options.
This parameter is available when **operationType** is set to **OperationType.ICON_GROUP** and **operationItem** is set to an array of [symbol glyphs](ts-basic-components-symbolGlyph.md).
**Atomic service API**: This API can be used in atomic services since API version 12.| +| primaryTitleModifier12+ | [TextModifier](ts-universal-attributes-attribute-modifier.md) | No| - | Text attributes of the primary title, such as the font color, font size, and font weight.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| secondaryTitleModifier12+ | [TextModifier](ts-universal-attributes-attribute-modifier.md) | No| - | Text attributes of the secondary title, such as the font color, font size, and font weight.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| titleBuilder12+ | () => void | No| @BuilderParam | Content of the custom title area.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| contentMargin12+ | [LocalizedMargin](ts-types.md#localizedmargin12) | No| @Prop | Margin of the content. Negative numbers are not supported.
Default value:
`{start: LengthMetrics.resource(`
`$r('sys.float.margin_left'))`,
`end: LengthMetrics.resource(`
`$r('sys.float.margin_right'))}`
**Atomic service API**: This API can be used in atomic services since API version 12.| +| contentPadding12+ | [LocalizedPadding](ts-types.md#localizedpadding12) | No| @Prop | Padding of the content.
Default value:
If a secondary title, with or without an icon, is displayed on the left:
{start: LengthMetrics.vp(12), end: LengthMetrics.vp(12)}
**Atomic service API**: This API can be used in atomic services since API version 12.| ## OperationType @@ -68,53 +71,51 @@ SubHeader({icon?: ResourceStr, iconSymbolOptions?: SymbolOptions, primaryTitle?: ## SelectOptions -**Atomic service API**: This API can be used in atomic services since API version 11. - **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| options | Array<[SelectOption](ts-basic-components-select.md#selectoption)> | Yes| Options of an item in the drop-down list box.| -| selected | number | No| Index of the initially selected item in the drop-down list box.
The index of the first item is 0.
If this property is not set,
the default value **-1** is used, indicating that the option is not selected.| -| value | string | No| Text content of the drop-down list button itself.| -| onSelect | (index: number, value?: string) => void | No| Callback invoked when an item in the drop-down list box is selected.
- **index**: index of the selected option.
- **value**: value of the selected option.| +| Name| Type| Mandatory| Description | +| -------- | -------- | -------- |--------------------------------------------------------------------------------------------------------------------------------------------------------------| +| options | Array<[SelectOption](ts-basic-components-select.md#selectoption)> | Yes| Options of an item in the drop-down list box.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| selected | number | No| Index of the initially selected item in the drop-down list box.
The value must be greater than or equal to -1.
The index of the first item is 0.
If this property is not set, the default value **-1** is used, indicating that the option is not selected.
Values less than -1 are treated as no selection.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| value | string | No| Text content of the drop-down list button itself.
The default value is an empty string.
**NOTE**
If the text is longer than the column width, it will be truncated.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| onSelect | (index: number, value?: string) => void | No| Callback invoked when an item in the drop-down list box is selected.
- **index**: index of the selected option.
- **value**: value of the selected option.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| defaultFocus18+ | boolean | No| Whether the drop-down button is the default focus.
**true**: The drop-down button is the default focus.
**false**: The drop-down button is not the default focus.
Default value: **false**
**Atomic service API**: This API can be used in atomic services since API version 18. | ## OperationOption -**Atomic service API**: This API can be used in atomic services since API version 11. - **System capability**: SystemCapability.ArkUI.ArkUI.Full | Name| Type| Mandatory| Description | | -------- | -------- | -------- |----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| value | [ResourceStr](ts-types.md#resourcestr) | Yes| Text content. | -| action | ()=>void | No| Event. | -| accessibilityLevel16+ | string | No| Accessibility level. It determines whether the component can be recognized by accessibility services.
The options are as follows:
**"auto"**: It is treated as "yes" by the system.
**"yes"**: The component can be recognized by accessibility services.
**"no"**: The component cannot be recognized by accessibility services.
**"no-hide-descendants"**: Neither the component nor its child components can be recognized by accessibility services.
Default value: **"auto"**
**Atomic service API**: This API can be used in atomic services since API version 16.| -| accessibilityText16+ | ResourceStr | No| Accessibility text, that is, accessible label name. If a component does not contain text information, it will not be announced by the screen reader when selected. In this case, the screen reader user cannot know which component is selected. To solve this problem, you can set accessibility text for components without text information. When such a component is selected, the screen reader announces the specified accessibility text, informing the user which component is selected.
Default value: value of the **value** property if the operation type is **TEXT_ARROW** or **BUTTON** and an empty string otherwise.
**Atomic service API**: This API can be used in atomic services since API version 16. | -| accessibilityDescription16+ | ResourceStr | No| Accessible description. You can provide comprehensive text explanations to help users understand the operation they are about to perform and its potential consequences, especially when these cannot be inferred from the component's attributes and accessibility text alone. If a component contains both text information and the accessible description, the text is announced first and then the accessible description, when the component is selected.
Default value: "Loading" when the operation type is **LOADING** and **"Double-tap to activate"** otherwise.
**Atomic service API**: This API can be used in atomic services since API version 16. | +| value | [ResourceStr](ts-types.md#resourcestr) | Yes| Text content.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| action | ()=>void | No| Event.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| accessibilityLevel18+ | string | No| Accessibility level. It determines whether the component can be recognized by accessibility services.
The options are as follows:
**"auto"**: It is treated as "yes" by the system.
**"yes"**: The component can be recognized by accessibility services.
**"no"**: The component cannot be recognized by accessibility services.
**"no-hide-descendants"**: Neither the component nor its child components can be recognized by accessibility services.
Default value: **"auto"**
**Atomic service API**: This API can be used in atomic services since API version 18.| +| accessibilityText18+ | ResourceStr | No| Accessibility text, that is, accessible label name. If a component does not contain text information, it will not be announced by the screen reader when selected. In this case, the screen reader user cannot know which component is selected. To solve this problem, you can set accessibility text for components without text information. When such a component is selected, the screen reader announces the specified accessibility text, informing the user which component is selected.
Default value: value of the **value** property if the operation type is **TEXT_ARROW** or **BUTTON** and an empty string otherwise.
**Atomic service API**: This API can be used in atomic services since API version 18.| +| accessibilityDescription18+ | ResourceStr | No| Accessible description. You can provide comprehensive text explanations to help users understand the operation they are about to perform and its potential consequences, especially when these cannot be inferred from the component's attributes and accessibility text alone. If a component contains both text information and the accessible description, the text is announced first and then the accessible description, when the component is selected.
Default value: "Loading" when the operation type is **LOADING** and **"Double-tap to activate"** otherwise.
**Atomic service API**: This API can be used in atomic services since API version 18. | +| defaultFocus18+ | boolean | No| Whether to receive default focus.
**true**: Receive default focus.
**false**: Do not receive default focus.
Default value: **false**
**Atomic service API**: This API can be used in atomic services since API version 18. | ## SymbolOptions12+ **Atomic service API**: This API can be used in atomic services since API version 12. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| fontColor | Array<[ResourceColor](ts-types.md#resourcecolor)> | No| Color of the [symbol glyph](ts-basic-components-symbolGlyph.md).
Default value: depending on the rendering strategy| -| fontSize | number \|string \|[Resource](ts-types.md#Resource) | No| Size of the [symbol glyph](ts-basic-components-symbolGlyph.md).
Default value: system default value| +| Name| Type| Mandatory| Description | +| -------- | -------- | -------- |-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| fontColor | Array<[ResourceColor](ts-types.md#resourcecolor)> | No| Color of the [symbol glyph](ts-basic-components-symbolGlyph.md).
Default value: depending on the rendering strategy | +| fontSize | number \|string \|[Resource](ts-types.md#Resource) | No| Size of the [symbol glyph](ts-basic-components-symbolGlyph.md).
The value must be greater than or equal to 0.
Default value: system default value | | fontWeight | number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string | No| Font weight of the [symbol glyph](ts-basic-components-symbolGlyph.md).
For the number type, the value ranges from 100 to 900, at an interval of 100. A larger value indicates a heavier font weight. The default value is **400**.
For the string type, only strings of the number type are supported, for example, **"400"**, **"bold"**, **"bolder"**, **"lighter"**, **"regular"**, and **"medium"**, which correspond to the enumerated values in **FontWeight**.
Default value: **FontWeight.Normal**| -| renderingStrategy | [SymbolRenderingStrategy](ts-basic-components-symbolGlyph.md#symbolrenderingstrategy11) | No| Rendering strategy of the [symbol glyph](ts-basic-components-symbolGlyph.md).
Default value: **SymbolRenderingStrategy.SINGLE**
**NOTE**
For the resources referenced in **$r('sys.symbol.ohos_*')**, only **ohos_trash_circle**, **ohos_folder_badge_plus**, and **ohos_lungs** support the **MULTIPLE_COLOR** modes.| -| effectStrategy | [SymbolEffectStrategy](ts-basic-components-symbolGlyph.md#symboleffectstrategy11) | No| Effect strategy of the [symbol glyph](ts-basic-components-symbolGlyph.md).
Default value: **SymbolEffectStrategy.NONE**
**NOTE**
For the resources referenced in **$r('sys.symbol.ohos_*')**, only **ohos_wifi** supports the hierarchical effect.| +| renderingStrategy | [SymbolRenderingStrategy](ts-basic-components-symbolGlyph.md#symbolrenderingstrategy11) | No| Rendering strategy of the [symbol glyph](ts-basic-components-symbolGlyph.md).
Default value: **SymbolRenderingStrategy.SINGLE**
**NOTE**
For the resources referenced in **$r('sys.symbol.ohos_*')**, only **ohos_trash_circle**, **ohos_folder_badge_plus**, and **ohos_lungs** support the **MULTIPLE_COLOR** modes. | +| effectStrategy | [SymbolEffectStrategy](ts-basic-components-symbolGlyph.md#symboleffectstrategy11) | No| Effect strategy of the [symbol glyph](ts-basic-components-symbolGlyph.md).
Default value: **SymbolEffectStrategy.NONE**
**NOTE**
For the resources referenced in **$r('sys.symbol.ohos_*')**, only **ohos_wifi** supports the hierarchical effect. | ## Events -The [universal events](ts-universal-events-click.md) are supported. +The [universal events](ts-component-general-events.md) are not supported. ## Example ### Example 1: Implementing an Efficiency-Oriented Subheader This example demonstrates how to implement a subheader where the left side contains an icon and a secondary title, and the right side has a text button. ```ts -import { promptAction, OperationType, SubHeader } from '@kit.ArkUI' +import { promptAction, OperationType, SubHeader } from '@kit.ArkUI'; @Entry @Component @@ -122,12 +123,13 @@ struct SubHeaderExample { build() { Column() { SubHeader({ - icon: $r('app.media.ic_public_community_messages'), + icon: $r('sys.media.ohos_ic_public_email'), secondaryTitle: 'Secondary title', operationType: OperationType.BUTTON, - operationItem: [{ value: 'Operation', + operationItem: [{ + value: 'Operation', action: () => { - promptAction.showToast({ message: 'demo' }) + promptAction.showToast({ message: 'demo' }); } }] }) @@ -136,13 +138,13 @@ struct SubHeaderExample { } ``` -![Subheader 1](figures/en-us_image_subheader_example01.png) +![en-us_image_subheader_example01](figures/en-us_image_subheader_example01.png) -### Example 2: Implementing a Double-Line Text Content-Rich Subheader +### Example 2: Implementing a Double-Line Text Content-rich Subheader This example showcases a subheader with a primary title and a secondary title on the left, and a text button with a right arrow on the right. ```ts -import { promptAction, OperationType, SubHeader } from '@kit.ArkUI' +import { promptAction, OperationType, SubHeader } from '@kit.ArkUI'; @Entry @Component @@ -153,9 +155,10 @@ struct SubHeaderExample { primaryTitle: 'Primary title', secondaryTitle: 'Secondary title', operationType: OperationType.TEXT_ARROW, - operationItem: [{value:'More', + operationItem: [{ + value: 'More', action: () => { - promptAction.showToast({ message: 'demo' }) + promptAction.showToast({ message: 'demo' }); } }] }) @@ -166,11 +169,11 @@ struct SubHeaderExample { ![Subheader 2](figures/en-us_image_subheader_example02.png) -### Example 3: Implementing a Spinner Content-Rich Subheader +### Example 3: Implementing a Spinner Content-rich Subheader This example showcases a subheader with content and events for selection on the left, and an icon-attached button on the right. ```ts -import { promptAction, OperationType, SubHeader } from '@kit.ArkUI' +import { promptAction, OperationType, SubHeader } from '@kit.ArkUI'; @Entry @Component @@ -178,29 +181,31 @@ struct SubHeaderExample { build() { Column() { SubHeader({ + // The left side is a drop-down box for selection. select: { options: [{ value: 'aaa' }, { value: 'bbb' }, { value: 'ccc' }], - value: 'selectdemo', + value: 'selectDemo', selected: 2, - onSelect: (index: number, value?: string) => { - promptAction.showToast({ message: 'demo' }) + onSelect: () => { + promptAction.showToast({ message: 'demo' }); } }, operationType: OperationType.ICON_GROUP, + // The right side has three icons. operationItem: [{ - value: $r('app.media.ic_public_community_messages'), + value: $r('sys.media.ohos_ic_public_email'), action: () => { promptAction.showToast({ message: 'demo' }) } }, { - value: $r('app.media.ic_public_community_messages'), + value: $r('sys.media.ohos_ic_public_email'), action: () => { - promptAction.showToast({ message: 'demo' }) + promptAction.showToast({ message: 'demo' }); } }, { - value: $r('app.media.ic_public_community_messages'), + value: $r('sys.media.ohos_ic_public_email'), action: () => { - promptAction.showToast({ message: 'demo' }) + promptAction.showToast({ message: 'demo' }); } }] }) @@ -209,14 +214,14 @@ struct SubHeaderExample { } ``` -![Subheader 3](figures/en-us_image_subheader_example03.png) +![en-us_image_subheader_example03](figures/en-us_image_subheader_example03.png) ### Example 4: Setting the Icon Symbol for the Left Side This example demonstrates how to set the icon symbol for the left side of the subheader. ```ts -import { promptAction, OperationType, SubHeader } from '@kit.ArkUI' +import { promptAction, OperationType, SubHeader } from '@kit.ArkUI'; @Entry @Component @@ -224,15 +229,17 @@ struct SubHeaderExample { build() { Column() { SubHeader({ + // Set the icon to a symbol icon. icon: $r('sys.symbol.ohos_wifi'), iconSymbolOptions: { effectStrategy: SymbolEffectStrategy.HIERARCHICAL, }, secondaryTitle: 'Title', operationType: OperationType.BUTTON, - operationItem: [{ value: 'Operation', + operationItem: [{ + value: 'Operation', action: () => { - promptAction.showToast({ message: 'demo' }) + promptAction.showToast({ message: 'demo' }); } }] }) @@ -247,7 +254,7 @@ struct SubHeaderExample { The following example shows how to set **operationType** to **OperationType.ICON_GROUP** for the right side of the subheader, with **operationItem** set to a symbol icon. ```ts -import { promptAction, OperationType, SubHeader } from '@kit.ArkUI' +import { promptAction, OperationType, SubHeader } from '@kit.ArkUI'; @Entry @Component @@ -255,31 +262,34 @@ struct SubHeaderExample { build() { Column() { SubHeader({ + // Set the left side to a drop-down box for selection. select: { options: [{ value: 'aaa' }, { value: 'bbb' }, { value: 'ccc' }], - value: 'selectdemo', + value: 'selectDemo', selected: 2, - onSelect: (index: number, value?: string) => { - promptAction.showToast({ message: 'demo' }) + onSelect: () => { + promptAction.showToast({ message: 'demo' }); } }, operationType: OperationType.ICON_GROUP, + // Set the right side to icons. operationItem: [{ value: $r('sys.symbol.ohos_lungs'), action: () => { - promptAction.showToast({ message: 'icon1' }) + promptAction.showToast({ message: 'icon1' }); } }, { value: $r('sys.symbol.ohos_lungs'), action: () => { - promptAction.showToast({ message: 'icon2' }) + promptAction.showToast({ message: 'icon2' }); } }, { value: $r('sys.symbol.ohos_lungs'), action: () => { - promptAction.showToast({ message: 'icon3' }) + promptAction.showToast({ message: 'icon3' }); } }], + // Set the symbol style for the right side icons. operationSymbolOptions: [{ fontWeight: FontWeight.Lighter, }, { @@ -295,7 +305,7 @@ struct SubHeaderExample { } ``` -![Subheader 5](figures/en-us_image_subheader_example05.png) +![en-us_image_subheader_example05](figures/en-us_image_subheader_example05.png) ### Example 6: Customizing Title Content This example demonstrates how to customize the title content with a **titleBuilder** object for the subheader. @@ -306,17 +316,19 @@ import { promptAction, OperationType, SubHeader } from '@kit.ArkUI'; @Entry @Component struct SubHeaderExample { + // Set the custom title on the left side. @Builder TitleBuilder(): void { Text('Custom title') .fontSize(24) - .fontColor(Color.Red) + .fontColor(Color.Blue) .fontWeight(FontWeight.Bold) } build() { Column() { SubHeader({ + // Call the custom title builder. titleBuilder: () => { this.TitleBuilder(); }, @@ -327,7 +339,7 @@ struct SubHeaderExample { operationItem: [{ value: 'More info', action: () => { - promptAction.showToast({ message: 'demo'}) + promptAction.showToast({ message: 'demo' }); } }] }) @@ -335,10 +347,9 @@ struct SubHeaderExample { } } ``` +![en-us_image_subheader_example06](figures/en-us_image_subheader_example06.png) -![Subheader 6](figures/en-us_image_subheader_example06.png) - -### Example 7: Customizing Title Style +### Example 7: Customizing the Title Style This example demonstrates how to set the font style, margin, and padding for the primary and secondary titles in the subheader. ```ts @@ -347,8 +358,9 @@ import { promptAction, OperationType, SubHeader, LengthMetrics, TextModifier } f @Entry @Component struct SubHeaderExample { - @State primaryModifier: TextModifier = new TextModifier().fontColor(Color.Red); - @State secondaryModifier: TextModifier = new TextModifier().fontColor(Color.Red); + // Set the font color for the primary and secondary titles. + @State primaryModifier: TextModifier = new TextModifier().fontColor(Color.Blue); + @State secondaryModifier: TextModifier = new TextModifier().fontColor(Color.Blue); build() { Column() { @@ -361,9 +373,10 @@ struct SubHeaderExample { operationItem: [{ value: 'More info', action: () => { - promptAction.showToast({ message: 'demo'}) + promptAction.showToast({ message: 'demo' }); } }], + // Set the margin and padding for the subheader. contentMargin: { start: LengthMetrics.vp(20), end: LengthMetrics.vp(20) }, contentPadding: { start: LengthMetrics.vp(20), end: LengthMetrics.vp(20) } }) @@ -375,10 +388,10 @@ struct SubHeaderExample { ![Subheader 7](figures/en-us_image_subheader_example07.png) -### Example 8: Implementing Screen Reader Announcement for the Button on the Right Side +### Example 8: Implementing Announcement for the Button on the Right Side This example customizes the screen reader announcement text by setting the **accessibilityText**, **accessibilityDescription**, and **accessibilityLevel** properties of the button on the right side of the subheader. ```ts -import { promptAction, OperationType, SubHeader, TextModifier, LengthMetrics } from '@kit.ArkUI'; +import { promptAction, OperationType, SubHeader } from '@kit.ArkUI'; @Entry @Component @@ -388,7 +401,7 @@ struct SubHeaderExample { Divider().color('grey').width('100%').height('2vp') SubHeader({ // Icon + secondary title, with a button on the right - icon: $r('app.media.app_icon'), + icon: $r('sys.media.ohos_ic_public_email'), secondaryTitle: 'Secondary title', operationType: OperationType.BUTTON, operationItem: [{ @@ -416,7 +429,7 @@ struct SubHeaderExample { // Selection on the left and icons (focused in sequence) on the right select: { options: [{ value: 'aaa' }, { value: 'bbb' }, { value: 'ccc' }], - value: 'selectdemo', + value: 'selectDemo', selected: 0, onSelect: (index: number, value?: string) => { console.log(`subheader onselect index : ${index}, value: ${value}`); @@ -424,15 +437,15 @@ struct SubHeaderExample { }, operationType: OperationType.ICON_GROUP, operationItem: [{ - value: $r('app.media.app_icon'), + value: $r('sys.media.ohos_ic_public_email'), accessibilityText: 'Icon 1', accessibilityLevel: 'yes', }, { - value: $r('app.media.app_icon'), + value: $r('sys.media.ohos_ic_public_email'), accessibilityText: 'Icon 2', - accessibilityLevel: 'no', + accessibilityLevel: 'no', }, { - value: $r('app.media.app_icon'), + value: $r('sys.media.ohos_ic_public_email'), accessibilityText: 'Icon 3', accessibilityDescription: 'Tap to operate icon 3', }] @@ -442,4 +455,33 @@ struct SubHeaderExample { } } ``` -![/en-us_image_subheader_example08](figures/en-us_image_subheader_example08.png) +![figures/en-us_image_subheader_example08](figures/en-us_image_subheader_example08.png) + +### Example 9: Enabling the Button on the Right Side to Receive Default Focus +This example demonstrates how to use **defaultFocus** to enable the button on the right side of the subheader to receive default focus. +```ts +import { promptAction, OperationType, SubHeader } from '@kit.ArkUI'; + +@Entry +@Component +struct SubHeaderExample { + build() { + Column() { + SubHeader({ + // Icon + secondary title, with a button on the right + icon: $r('app.media.app_icon'), + secondaryTitle: 'Secondary title', + operationType: OperationType.BUTTON, + operationItem: [{ + value: 'Action', + defaultFocus: true, + action: () => { + promptAction.showToast({ message: 'demo' }) + } + }] + }) + } + } +} +``` +![/SubHeaderDefaultFocus](figures/SubHeaderDefaultFocus.png) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-SubHeaderV2.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-SubHeaderV2.md new file mode 100644 index 0000000000000000000000000000000000000000..928884088ba845ef9e3d064c4b05f3bbba3fa4c5 --- /dev/null +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-SubHeaderV2.md @@ -0,0 +1,873 @@ +# SubHeaderV2 + + +The **SubHeader** component represents a subheader that signifies the top of a list or the beginning a subdivision of content and tells the user what the list or subdivision is about. + +This component is implemented based on [state management V2](../../../quick-start/arkts-state-management-overview.md#state-management-v2). Compared with [state management V1](../../../quick-start/arkts-state-management-overview.md#state-management-v1), V2 offers a higher level of observation and management over data objects beyond the component level. You can now more easily manage subheader data and states with greater flexibility, leading to faster UI updates. + + + +> **NOTE** +> +> - This component is supported since API version 18. Updates will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + +```ts +import { SubHeader } from '@kit.ArkUI' +``` + + +## Child Components + +Not supported + +## Attributes + +The [universal attributes](ts-component-general-attributes.md) are not supported. + +## SubHeaderV2 + +SubHeaderV2({ +icon?: SubHeaderV2IconType, +title?: SubHeaderV2Title, +select?: SubHeaderV2Select, +operationType?: SubHeaderV2OperationType, +operationItems?: SubHeaderV2OperationItem +}) + +The **SubHeader** component represents a subheader that signifies the top of a list or the beginning a subdivision of content and tells the user what the list or subdivision is about. + +**Decorator**: \@ComponentV2 + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name| Type | Mandatory| Decorator| Description | +| -------- |---------------------------------------------------------| -------- | -------- |----------------------------------------| +| icon| [SubHeaderV2IconType](#subheaderv2icontype) | No| @Param | Icon.
Default value: **undefined** | +| title| [SubHeaderV2Title](#subheaderv2title) | No| @Param| Title of the subheader.
Default value: **undefined** | +| select| [SubHeaderV2Select](#subheaderv2select) | No| @Param | Content and events for selection.
Default value: **undefined** | +| operationType | [SubHeaderV2OperationType](#subheaderv2operationtype) | No| @Param| Style of elements in the operation area.
Default value: **OperationType.BUTTON**| +| operationItems | [SubHeaderV2OperationItem](#subheaderv2operationitem)[] | No| @Param| Items in the operation area.
Default value: **undefined** | +| titleBuilder | [SubHeaderV2TitleBuilder](#subheaderv2titlebuilder) | No| @BuildParam| Custom content for the title area.
Default value: **() => void** | + +## SubHeaderV2IconType + +type SubHeaderV2IconType = ResourceStr | SymbolGlyphModifier + +Defines the union type for the icon content. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Type | Description | +| ----------------------------- |------------------------| +| ResourceStr | Resource type for defining common icons. | +| SymbolGlyphModifier | Symbol type for defining symbol icons.| + +## SubHeaderV2Title +Defines the title settings for the subheader. + +**Decorator type**: @ObservedV2 + +### Properties + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name| Type| Mandatory| Decorator| Description | +| -------- | -------- | -------- | -------- |------------------------------| +| primaryTitle| [ResourceStr](ts-types.md#resourcestr) | No| @Trace | Primary title.
Default value: **undefined** | +| secondaryTitle| [ResourceStr](ts-types.md#resourcestr) | No| @Trace | Secondary title.
Default value: **undefined** | +| primaryTitleModifier| [TextModifier](ts-universal-attributes-attribute-modifier.md) | No| @Trace | Text attributes of the primary title, such as the font color, font size, and font weight.
Default value: **undefined** | +| secondaryTitleModifier| [TextModifier](ts-universal-attributes-attribute-modifier.md) | No| @Trace | Text attributes of the secondary title, such as the font color, font size, and font weight.
Default value: **undefined**| + +### constructor + +constructor(options: SubHeaderV2TitleOptions) + +A constructor used to create a **SubHeaderV2Title** object. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- |-----------------------------------------------------| ------ | ------------------ | +| options | [SubHeaderV2TitleOptions](#subheaderv2titleoptions) | Yes | Options for initializing the title.| + +## SubHeaderV2TitleOptions + +Defines the options for initializing a **SubHeaderV2Title** object. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name| Type| Mandatory | Description | +| -------- | -------- | -------- |-----------------------------| +| primaryTitle| [ResourceStr](ts-types.md#resourcestr) | No| Primary title.
Default value: **undefined** | +| secondaryTitle| [ResourceStr](ts-types.md#resourcestr) | No| Secondary title.
Default value: **undefined** | +| primaryTitleModifier| [TextModifier](ts-universal-attributes-attribute-modifier.md) | No| Text attributes of the primary title, such as the font color, font size, and font weight.
Default value: **undefined**| +| secondaryTitleModifier| [TextModifier](ts-universal-attributes-attribute-modifier.md) | No| Text attributes of the secondary title, such as the font color, font size, and font weight.
Default value: **undefined**| + +## SubHeaderV2Select + +Defines the content and events for selection. + +**Decorator type**: @ObservedV2 + +### Properties + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name| Type | Mandatory| Decorator| Description | +| -------- |------------------------------------------------------------------| -------- | -------- |---------------------------------------------------------------------------| +| options | [SelectOption](ts-basic-components-select.md#selectoption)[] | Yes| @Trace | Options for the drop-down list box. | +| selectedIndex | number | No|@Trace | Index of the initially selected item in the drop-down list box.
The index of the first item is 0.
If this property is not set,
the default value **-1** is used, indicating that no item is selected.| +| selectedContent | string | No| @Trace | Text content of the drop-down button. Default value: **''** | +| onSelect | [SubHeaderV2SelectOnSelect](#subheaderv2selectonselect) | No| @Trace | Callback invoked when an item in the drop-down list box is selected.
Default value: **undefined** | +| defaultFocus | boolean | No| Whether the drop-down button is the default focus.
**true**: The drop-down button is the default focus.
**false**: The drop-down button is not the default focus.
Default value: **false** | + +### constructor + +constructor(options: SubHeaderV2SelectOptions) + +A constructor used to create a **SubHeaderV2Select** object. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- |-------------------------------| ------ | ------------------ | +| options | [SubHeaderV2SelectOptions](#subheaderv2selectoptions) | Yes | Configuration options of the drop-down list box.| + +## SubHeaderV2SelectOptions + +Defines the options for initializing a **SubHeaderV2Select** object. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name| Type | Mandatory | Description | +| -------- |------------------------------------------------------------------| -------- |---------------------------------------------------------------------------| +| options | [SelectOption](ts-basic-components-select.md#selectoption)[] | Yes| Options for the drop-down list box. | +| selectedIndex | number | No| Index of the initially selected item in the drop-down list box.
The index of the first item is 0.
If this property is not set,
the default value **-1** is used, indicating that no item is selected.| +| selectedContent | string | No| Text content of the drop-down button. Default value: **''** | +| onSelect | [SubHeaderV2SelectOnSelect](#subheaderv2selectonselect) | No| Callback invoked when an item in the drop-down list box is selected.
Default value: **undefined** | +| defaultFocus | boolean | No| Whether the drop-down button is the default focus.
**true**: The drop-down button is the default focus.
**false**: The drop-down button is not the default focus.
Default value: **false** | + +## SubHeaderV2SelectOnSelect + +type SubHeaderV2SelectOnSelect = (selectedIndex: number, selectedContent?: string) => void + +Defines the callback invoked when an item in the drop-down list box is selected. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Type | Description | +|:--------------|:--------------------------------------------| +| selectIndex | Index of the selected item.| +| selectContent | Text content of the selected item.| + +## SubHeaderV2OperationType + +Defines the style of elements in the operation area. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name| Value| Description| +| -------- | -------- | -------- | +| TEXT_ARROW | 0 | Text button with a right arrow.| +| BUTTON | 1 | Text button without a right arrow.| +| ICON_GROUP | 2 | Icon-attached button (A maximum of three icons can be configured.)| +| LOADING | 3 | Loading animation.| + +## SubHeaderV2OperationItemType + +type SubHeaderV2OperationItemType = ResourceStr | SymbolGlyphModifier + +Defines the union type for the content of elements in the operation area. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Type | Description | +| ----------------------------- |-----------------------------------| +| ResourceStr | String type for defining text display or common icons; resource type for defining common icons.| +| SymbolGlyphModifier | Symbol type for defining symbol icons. | + +## SubHeaderV2OperationItem + +Represents an item in the operation area. + +**Decorator type**: @ObservedV2 + +### Properties + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name| Type| Mandatory| Decorator| Description | +| -------- | -------- | -------- | -------- |-----------------------------------------------------| +| content | [SubHeaderV2OperationItemType](#subheaderv2operationitemtype) | Yes| @Trace | Content of the item in the operation area. | +| action | SubHeaderV2OperationItemAction | No| @Trace | Event triggered when the item is operated. Default value: **() => void** | +| accessibilityText |[ResourceStr](ts-types.md#resourcestr) | No|@Trace | Accessibility text.
Default value: **undefined** | +| accessibilityLevel |[string](ts-types.md#resourcestr) | No|@Trace | Accessibility level.
Default value: **"yes"** | +| accessibilityDescription|[ResourceStr](ts-types.md#resourcestr) | No|@Trace | Accessibility description.
Default value: **"Double-tap to activate"**| +| defaultFocus | boolean | No| Whether to receive default focus.
**true**: Receive default focus.
**false**: Do not receive default focus.
Default value: **false** | + +### constructor + +constructor(options: SubHeaderV2OperationItemOptions) + +A constructor used to create a **SubHeaderV2OperationItem** object. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | -------------------- | ------ | ------------------ | +| options | SubHeaderV2OperationItemOptions| Yes | Configuration options of the operation item.| + +## SubHeaderV2OperationItemAction + +type SubHeaderV2OperationItemAction = () => void + +Defines the callback for items in the operation area. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +## SubHeaderV2OperationItemOptions + +Defines the options for initializing a **SubHeaderV2OperationItem** object. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +|--------------------------|---------------------------------------------| -------- |-----------------------------------------------------| +| content | [SubHeaderV2OperationItemType](#subheaderv2operationitemtype) | Yes| Content of the item in the operation area. | +| action | [SubHeaderV2OperationItemAction](#subheaderv2operationitemaction) | No| Event triggered when the item is operated. Default value: **() => void** | +| accessibilityText | [ResourceStr](ts-types.md#resourcestr) | No| Accessibility text.
Default value: **undefined** | +| accessibilityLevel | [string](ts-types.md#resourcestr) | No| Accessibility level.
Default value: **"yes"** | +| accessibilityDescription | [ResourceStr](ts-types.md#resourcestr) | No| Accessibility description.
Default value: **"Double-tap to activate"**| +| defaultFocus | boolean | No| Whether to receive default focus.
**true**: Receive default focus.
**false**: Do not receive default focus.
Default value: **false** | + +## SubHeaderV2TitleBuilder + +type SubHeaderV2TitleBuilder= () => void + +Defines the callback used to customize the content of the title area. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +## Events +The [universal events](ts-component-general-events.md) are not supported. + +## Example +### Example 1: Implementing an Efficiency-Oriented Subheader +This example demonstrates how to implement a subheader where the left side contains an icon and a secondary title, and the right side has a text button. + +```ts +import { + SubHeaderV2OperationType, + SubHeaderV2, + SubHeaderV2Title, + SubHeaderV2OperationItem, + promptAction, + TextModifier +} from '@kit.ArkUI' + +@Entry +@ComponentV2 +struct SubHeaderExample { + @Local selectText: string = "TTTTT" + @Local selectIndex: number = 2 + @Local flag: boolean = true; + @Local index: number = 1; + @Local primaryTitle: ResourceStr = 'Primary title'; + @Local secondaryTitle: ResourceStr = 'Secondary title'; + @Local subHeaderIcon: Resource = $r('sys.media.ohos_ic_public_email'); + @Local title: SubHeaderV2Title = new SubHeaderV2Title({ primaryTitle: 'Primary title' }); + @Local primaryModifier: TextModifier = new TextModifier().fontColor(Color.Red); + @Local secondaryModifier: TextModifier = new TextModifier().fontColor(Color.Red); + @Local subHeaderOperationType: SubHeaderV2OperationType = SubHeaderV2OperationType.BUTTON; + @Local operationItems: SubHeaderV2OperationItem[] = []; + + aboutToAppear(): void { + this.title = new SubHeaderV2Title({ + primaryTitle: this.primaryTitle, + secondaryTitle: this.secondaryTitle, + }); + this.operationItems = [new SubHeaderV2OperationItem({ + content: 'Operation', + action: () => { + promptAction.showToast({ message: 'demo2' }) + } + })] + } + + build() { + Column() { + Column() { + SubHeaderV2({ + icon: this.subHeaderIcon, + title: this.title, + operationType: this.subHeaderOperationType, + operationItems: this.operationItems + }); + } + } + } +} +``` + +![Subheader 1](figures/en-us_image_subheader_example01.png) + +### Example 2: Implementing a Double-Line Text Content-rich Subheader +This example showcases a subheader with a primary title and a secondary title on the left, and a text button with a right arrow on the right. + +```ts +import { + SubHeaderV2OperationType, + SubHeaderV2, + SubHeaderV2Title, + SubHeaderV2OperationItem, + promptAction, + TextModifier +} from '@kit.ArkUI' + +@Entry +@ComponentV2 +struct SubHeaderExample { + @Local title: SubHeaderV2Title = new SubHeaderV2Title({ primaryTitle: 'Primary title', secondaryTitle: 'Secondary title' }); + @Local primaryModifier: TextModifier = new TextModifier().fontColor(Color.Red); + @Local secondaryModifier: TextModifier = new TextModifier().fontColor(Color.Red); + @Local subHeaderOperationType: SubHeaderV2OperationType = SubHeaderV2OperationType.TEXT_ARROW; + @Local operationItems: SubHeaderV2OperationItem[] = []; + + aboutToAppear(): void { + this.title = new SubHeaderV2Title({ + primaryTitle: 'Primary title', + secondaryTitle: 'Secondary title' + }); + this.operationItems = [new SubHeaderV2OperationItem({ + content: 'More', + action: () => { + promptAction.showToast({ message: 'demo2' }) + } + })] + } + + build() { + Column() { + Column() { + SubHeaderV2({ + title: this.title, + operationType: this.subHeaderOperationType, + operationItems: this.operationItems + }); + } + } + } +} +``` + +![Subheader 2](figures/en-us_image_subheader_example02.png) + +### Example 3: Implementing a Spinner Content-rich Subheader +This example showcases a subheader with content and events for selection on the left, and an icon-attached button on the right. + +```ts +import { + SubHeaderV2, + SubHeaderV2OperationType, + SubHeaderV2OperationItem, + SubHeaderV2Title, + SubHeaderV2Select, + promptAction +} from '@kit.ArkUI' + +@Entry +@ComponentV2 +struct SubHeaderExample { + @Local selectedValue: string = 'aaa'; + @Local selectedIndex: number = 0; + @Local title: SubHeaderV2Title = new SubHeaderV2Title({ primaryTitle: 'Primary title', secondaryTitle: 'Secondary title' }); + @Local operationItems: SubHeaderV2OperationItem[] = []; + @Local select: SubHeaderV2Select = + new SubHeaderV2Select({ options: [{ value: 'aaa' }, { value: 'bbb' }, { value: 'ccc' }] }); + + aboutToAppear(): void { + + this.title = new SubHeaderV2Title({ + primaryTitle: 'Primary title', + secondaryTitle: 'Secondary title' + }); + + this.selectedValue = 'selectDemo'; + this.select = new SubHeaderV2Select({ + options: [{ value: 'aaa' }, { value: 'bbb' }, { value: 'ccc' }], + selectedContent: this.selectedValue, + selectedIndex: this.selectedIndex, + onSelect: (index: number, value?: string) => { + promptAction.showToast({ message: 'selectdemo' }) + } + }) + + this.operationItems = [ + new SubHeaderV2OperationItem({ + content: $r('sys.media.ohos_ic_public_email'), + action: () => { + promptAction.showToast({ message: 'demo' }) + } + }), + new SubHeaderV2OperationItem({ + content: $r('sys.media.ohos_ic_public_email'), + action: () => { + promptAction.showToast({ message: 'demo' }) + } + }), + new SubHeaderV2OperationItem({ + content: $r('sys.media.ohos_ic_public_email'), + action: () => { + promptAction.showToast({ message: 'demo' }) + } + })] + } + + build() { + Column() { + Column() { + SubHeaderV2({ + select: this.select, + operationType: SubHeaderV2OperationType.ICON_GROUP, + operationItems: this.operationItems + }) + } + } + } +} +``` + +![Subheader 3](figures/en-us_image_subheader_example03.png) + +### Example 4: Setting the Icon Symbol for the Left Side +This example demonstrates how to set the icon symbol for the left side of the subheader. + +```ts +import { + SubHeaderV2, + SubHeaderV2OperationType, + SubHeaderV2OperationItem, + SubHeaderV2Title, + promptAction, + SymbolGlyphModifier +} from '@kit.ArkUI' + +@Entry +@ComponentV2 +struct SubHeaderExample { + @Local icon: SymbolGlyphModifier = new SymbolGlyphModifier($r('sys.symbol.ohos_wifi')); + + aboutToAppear(): void { + this.icon = new SymbolGlyphModifier($r('sys.symbol.ohos_wifi')).fontSize(24); + this.icon.effectStrategy(SymbolEffectStrategy.HIERARCHICAL) + } + + build() { + Column() { + SubHeaderV2({ + icon: this.icon, + title: new SubHeaderV2Title({ secondaryTitle: 'Title' }), + operationType: SubHeaderV2OperationType.BUTTON, + operationItems: [new SubHeaderV2OperationItem({ + content: 'Operation', + action: () => { + promptAction.showToast({ message: 'demo' }) + } + })] + }) + } + } +} +``` + +![Subheader 4](figures/en-us_image_subheader_example04.gif) + +### Example 5: Setting the Icon Symbol for the Right Side +The following example shows how to set **operationType** to **OperationType.ICON_GROUP** for the right side of the subheader, with **operationItem** set to a symbol icon. + +```ts +import { + SubHeaderV2, + SubHeaderV2OperationType, + SubHeaderV2OperationItem, + SubHeaderV2Title, + SubHeaderV2Select, + promptAction, + SymbolGlyphModifier +} from '@kit.ArkUI' + +@Entry +@ComponentV2 +struct SubHeaderExample { + @Local icon: SymbolGlyphModifier = new SymbolGlyphModifier($r('sys.symbol.ohos_wifi')); + @Local selectedValue: string = 'aaa'; + @Local selectedIndex: number = 2; + @Local title: SubHeaderV2Title = new SubHeaderV2Title({ primaryTitle: 'Primary title', secondaryTitle: 'Secondary title' }); + @Local operationItem: SubHeaderV2OperationItem[] = []; + @Local select: SubHeaderV2Select = + new SubHeaderV2Select({ options: [{ value: 'aaa' }, { value: 'bbb' }, { value: 'ccc' }] }); + + aboutToAppear(): void { + this.icon = new SymbolGlyphModifier($r('sys.symbol.ohos_wifi')); + this.icon.effectStrategy(SymbolEffectStrategy.HIERARCHICAL); + + this.selectedValue = 'selectDemo'; + this.selectedIndex = 2; + this.title = new SubHeaderV2Title({ + primaryTitle: 'Primary title', + secondaryTitle: 'Secondary title' + }); + this.select = new SubHeaderV2Select({ + options: [{ value: 'aaa' }, { value: 'bbb' }, { value: 'ccc' }], + selectedContent: this.selectedValue, + selectedIndex: this.selectedIndex, + onSelect: (index: number, value?: string) => { + promptAction.showToast({ message: 'demo' }) + } + }) + + this.operationItem = [ + new SubHeaderV2OperationItem({ + content: new SymbolGlyphModifier($r('sys.symbol.ohos_lungs')).fontWeight(FontWeight.Lighter), + action: () => { + promptAction.showToast({ message: 'demo1' }) + } + }), + new SubHeaderV2OperationItem({ + content: new SymbolGlyphModifier($r('sys.symbol.ohos_lungs')) + .renderingStrategy(SymbolRenderingStrategy.MULTIPLE_COLOR) + .fontColor([Color.Blue, Color.Grey, Color.Green]) + , + action: () => { + promptAction.showToast({ message: 'demo2' }) + } + }), + new SubHeaderV2OperationItem({ + content: new SymbolGlyphModifier($r('sys.symbol.ohos_lungs')) + .renderingStrategy(SymbolRenderingStrategy.MULTIPLE_OPACITY) + .fontColor([Color.Blue, Color.Grey, Color.Green]) + , + action: () => { + promptAction.showToast({ message: 'demo3' }) + } + })] + } + + build() { + Column() { + SubHeaderV2({ + select: this.select, + operationType: SubHeaderV2OperationType.ICON_GROUP, + operationItems: this.operationItem + }) + } + } +} +``` + +![Subheader 5](figures/en-us_image_subheader_example05.png) + +### Example 6: Customizing Title Content + This example demonstrates how to customize the title content with a **titleBuilder** object for the subheader. + +```ts +import { + SubHeaderV2, + SubHeaderV2OperationType, + SubHeaderV2OperationItem, + SubHeaderV2Title, + promptAction +} from '@kit.ArkUI' + +@Entry +@ComponentV2 +struct SubHeaderExample { + @Local title: SubHeaderV2Title = new SubHeaderV2Title({ primaryTitle: 'Primary title' }); + @Local operationItem: SubHeaderV2OperationItem[] = []; + + aboutToAppear(): void { + this.title = new SubHeaderV2Title({ + primaryTitle: 'Primary title', + secondaryTitle: 'Secondary title' + }); + this.operationItem = [new SubHeaderV2OperationItem({ + content: 'More info', + action: () => { + promptAction.showToast({ message: 'demo' }) + } + })] + } + + @Builder + TitleBuilder(): void { + Text('Custom title') + .fontSize(24) + .fontColor(Color.Blue) + .fontWeight(FontWeight.Bold) + } + + build() { + Column() { + SubHeaderV2({ + titleBuilder: () => { + this.TitleBuilder(); + }, + title: this.title, + + operationType: SubHeaderV2OperationType.TEXT_ARROW, + operationItems: this.operationItem + }) + } + } +} +``` + +![Subheader 6](figures/en-us_image_subheader_example06.png) + +### Example 7: Customizing the Title Style +This example demonstrates how to set custom font styles for the primary and secondary titles. + +```ts +import { + SubHeaderV2, + SubHeaderV2OperationType, + SubHeaderV2OperationItem, + SubHeaderV2Title, + promptAction, + TextModifier +} from '@kit.ArkUI' + +@Entry +@ComponentV2 +struct SubHeaderExample { + @Local primaryModifier: TextModifier = new TextModifier().fontColor(Color.Blue); + @Local secondaryModifier: TextModifier = new TextModifier().fontColor(Color.Blue); + @Local title: SubHeaderV2Title = new SubHeaderV2Title({ primaryTitle: 'Primary title' }); + @Local operationItems4: SubHeaderV2OperationItem[] = []; + + aboutToAppear(): void { + this.title = new SubHeaderV2Title({ + primaryTitle: 'Primary title', + primaryTitleModifier: this.primaryModifier, + secondaryTitle: 'Secondary title', + secondaryTitleModifier: this.secondaryModifier + }); + this.operationItems4 = [new SubHeaderV2OperationItem({ + content: 'More info', + action: () => { + promptAction.showToast({ message: 'demo' }) + } + })] + } + + build() { + Column() { + SubHeaderV2({ + title: this.title, + operationType: SubHeaderV2OperationType.TEXT_ARROW, + operationItems: this.operationItems4 + }) + } + } +} +``` + +![Subheader 7](figures/en-us_image_subheaderv2_example07.png) + + +### Example 8: Implementing Announcement for the Button on the Right Side +This example customizes the screen reader announcement text by setting the **accessibilityText**, **accessibilityDescription**, and **accessibilityLevel** properties of the button on the right side of the subheader. +```ts +import { + SubHeaderV2OperationType, + SubHeaderV2, + SubHeaderV2Title, + SubHeaderV2OperationItem, + SubHeaderV2IconType, + SubHeaderV2Select, + promptAction +} from '@kit.ArkUI' + +@Entry +@ComponentV2 +struct SubHeaderExample { + @Local index: number = 1; + @Local primaryTitle: ResourceStr = 'Primary title'; + @Local secondaryTitle: ResourceStr = 'Secondary title'; + @Local subHeaderIcon: SubHeaderV2IconType | undefined = $r('sys.media.ohos_ic_public_email'); + @Local title: SubHeaderV2Title = new SubHeaderV2Title({ primaryTitle: 'Primary title' }); + @Local title2: SubHeaderV2Title = new SubHeaderV2Title({ primaryTitle: 'Primary title', secondaryTitle: 'Secondary title' }); + @Local subHeaderOperationType: SubHeaderV2OperationType = SubHeaderV2OperationType.BUTTON; + @Local subHeaderOperationType2: SubHeaderV2OperationType = SubHeaderV2OperationType.TEXT_ARROW; + @Local subHeaderOperationType3: SubHeaderV2OperationType = SubHeaderV2OperationType.ICON_GROUP; + @Local operationItems: SubHeaderV2OperationItem[] = []; + @Local selectedValue: string | undefined = 'selectDemo'; + @Local selectedIndex: number = 0; + @Local select: SubHeaderV2Select = + new SubHeaderV2Select({ options: [{ value: 'aaa' }, { value: 'bbb' }, { value: 'ccc' }] }); + + aboutToAppear(): void { + this.select = new SubHeaderV2Select({ options: [] }); + this.title = new SubHeaderV2Title({ + primaryTitle: this.primaryTitle, + secondaryTitle: this.secondaryTitle, + }); + this.operationItems = [new SubHeaderV2OperationItem({ + content: 'Operation', + action: () => { + promptAction.showToast({ message: 'demo2' }) + } + })] + } + + build() { + Column() { + Column() { + SubHeaderV2({ + icon: this.subHeaderIcon, + title: this.title, + select: this.select, + operationType: this.subHeaderOperationType, + operationItems: this.operationItems + }); + Divider().color('grey').width('100%').height('2vp') + SubHeaderV2({ + title: this.title2, + select: this.select, + operationType: this.subHeaderOperationType2, + operationItems: this.operationItems + }); + Divider().color('grey').width('100%').height('2vp') + SubHeaderV2({ + select: new SubHeaderV2Select({ + options: [{ value: 'aaa' }, { value: 'bbb' }, { value: 'ccc' }], + selectedIndex: this.selectedIndex, + selectedContent: this.selectedValue, + onSelect: (index: number, value?: string) => { + this.selectedIndex = index; + this.selectedValue = value; + promptAction.showToast({ message: this.selectedValue }) + } + }), + operationType: this.subHeaderOperationType3, + operationItems: [new SubHeaderV2OperationItem({ + content: $r('sys.media.ohos_ic_public_email'), + accessibilityText: 'Icon 1', + accessibilityLevel: 'yes', + }), new SubHeaderV2OperationItem({ + content: $r('sys.media.ohos_ic_public_email'), + accessibilityText: 'Icon 2', + accessibilityLevel: 'no', + }), new SubHeaderV2OperationItem({ + content: $r('sys.media.ohos_ic_public_email'), + accessibilityText: 'Icon 3', + accessibilityDescription: 'Tap to operate icon 3', + })] + }); + } + Divider().color('grey').width('100%').height('2vp') + } + } +} +``` +![Subheader 8](figures/en-us_image_subheader_example08.png) + +### Example 9: Implementing Announcement for the Button on the Right Side +This example customizes the screen reader announcement text by setting the **accessibilityText**, **accessibilityDescription**, and **accessibilityLevel** properties of the button on the right side of the subheader. +```ts +import { + SubHeaderV2OperationType, + SubHeaderV2, + SubHeaderV2Title, + SubHeaderV2OperationItem, + promptAction, + TextModifier +} from '@kit.ArkUI' + +@Entry +@ComponentV2 +struct SubHeaderExample { + @Local selectText: string = "TTTTT" + @Local selectIndex: number = 2 + @Local flag: boolean = true; + @Local index: number = 1; + @Local primaryTitle: ResourceStr = 'Primary title'; + @Local secondaryTitle: ResourceStr = 'Secondary title'; + @Local subHeaderIcon: Resource = $r('app.media.app_icon'); + @Local title: SubHeaderV2Title = new SubHeaderV2Title({ primaryTitle: 'Primary title' }); + @Local primaryModifier: TextModifier = new TextModifier().fontColor(Color.Red); + @Local secondaryModifier: TextModifier = new TextModifier().fontColor(Color.Red); + @Local subHeaderOperationType: SubHeaderV2OperationType = SubHeaderV2OperationType.BUTTON; + @Local operationItems: SubHeaderV2OperationItem[] = []; + + aboutToAppear(): void { + this.title = new SubHeaderV2Title({ + secondaryTitle: this.secondaryTitle, + }); + this.operationItems = [new SubHeaderV2OperationItem({ + content: 'Operation', + defaultFocus: true, + action: () => { + promptAction.showToast({ message: 'demo2' }) + } + })] + } + + build() { + Column() { + Column() { + SubHeaderV2({ + icon: this.subHeaderIcon, + title: this.title, + operationType: this.subHeaderOperationType, + operationItems: this.operationItems + }); + } + } + } +} +``` +![/SubHeaderDefaultFocus](figures/SubHeaderDefaultFocus.png) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-SwipeRefresher.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-SwipeRefresher.md index 674b901cd0578c32f7dac5a9c07f791840853208..e5a671747429a311573f632a24dab0875de23712 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-SwipeRefresher.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-SwipeRefresher.md @@ -11,7 +11,7 @@ The swipe refresher is a component used to obtain and load content, typically wi ## Modules to Import ``` -import { SwipeRefresher } from '@kit.ArkUI' +import { SwipeRefresher } from '@kit.ArkUI'; ``` @@ -20,14 +20,14 @@ import { SwipeRefresher } from '@kit.ArkUI' Not supported ## Attributes -The [universal attributes](ts-universal-attributes-size.md) are supported. +The [universal attributes](ts-component-general-attributes.md) are not supported. ## SwipeRefresher SwipeRefresher ({content?: string, isLoading: boolean}) -**Decorator**: \@Component +**Decorator**: @Component **Atomic service API**: This API can be used in atomic services since API version 11. @@ -35,13 +35,13 @@ SwipeRefresher ({content?: string, isLoading: boolean}) **Parameters** -| Name| Type| Mandatory| Decorator| Description| -| -------- | -------- | -------- | -------- | -------- | -| content | string | No| \@Prop | Text displayed when the content is loaded.| -| isLoading | boolean | If yes, | \@Prop | Whether content is being loaded.
The value **true** means that content is being loaded, and **false** means the opposite.| +| Name| Type| Mandatory| Decorator| Description | +| -------- | -------- | -------- | -------- |--------------------------------------------------------------------| +| content | string | No| \@Prop | Text displayed when the content is loaded.
The default value is an empty string.
**NOTE**
If the text is longer than the column width, it will be truncated. | +| isLoading | boolean | If yes, | \@Prop | Whether content is being loaded.
The value **true** means that content is being loaded,
and **false** means the opposite.| ## Events -The [universal events](ts-universal-events-click.md) are supported. +The [universal events](ts-component-general-events.md) are not supported. ## Example This example demonstrates how setting the **content** parameter to empty or non-empty strings and toggling the **isLoading** parameter between **true** and **false** affects the loading effect. diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-TabTitleBar.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-TabTitleBar.md index 9b37142b9cf63af1e864a4e345da1e8463d9d7ad..8e3949be7fc33627e1ae5332432117758829e550 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-TabTitleBar.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-TabTitleBar.md @@ -21,7 +21,7 @@ import { TabTitleBar } from '@kit.ArkUI' Not supported ## Attributes -The [universal attributes](ts-universal-attributes-size.md) are not supported. +The [universal attributes](ts-component-general-attributes.md) are not supported. ## TabTitleBar @@ -51,12 +51,13 @@ TabTitleBar({tabItems: Array<TabTitleBarTabItem>, menuItems?: Array<Tab | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | [ResourceStr](ts-types.md#resourcestr) | Yes| Icon resource.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| symbolStyle18+ | [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) | No| Symbol icon resource, which has higher priority than **value**.
**Atomic service API**: This API can be used in atomic services since API version 18.| | label13+ | [ResourceStr](ts-types.md#resourcestr) | No| Icon label.
**Atomic service API**: This API can be used in atomic services since API version 13.| | isEnabled | boolean | No| Whether to enable the item.
Default value: **false**
The value **true** means to enable the item, and **false** means the opposite.
**Atomic service API**: This API can be used in atomic services since API version 11.| | action | () => void | No| Action to perform.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| accessibilityLevel16+ | string | No| Accessibility level. It determines whether the component can be recognized by accessibility services.
The options are as follows:
**"auto"**: It is treated as "yes" by the system.
**"yes"**: The component can be recognized by accessibility services.
**"no"**: The component cannot be recognized by accessibility services.
**"no-hide-descendants"**: Neither the component nor its child components can be recognized by accessibility services.
Default value: **"auto"**
**Atomic service API**: This API can be used in atomic services since API version 16.| -| accessibilityText16+ | ResourceStr | No| Accessibility text, that is, accessibility label name. If a component does not contain text information, it will not be announced by the screen reader when selected. In this case, the screen reader user cannot know which component is selected. To solve this problem, you can set accessibility text for components without text information. When such a component is selected, the screen reader announces the specified accessibility text, informing the user which component is selected.
Default value: value of the **label** property if it is set and an empty string otherwise.
**Atomic service API**: This API can be used in atomic services since API version 16. | -| accessibilityDescription16+ | ResourceStr | No| Accessible description. You can provide comprehensive text explanations to help users understand the operation they are about to perform and its potential consequences, especially when these cannot be inferred from the component's attributes and accessibility text alone. If a component contains both text information and the accessible description, the text is announced first and then the accessible description, when the component is selected.
Default value: **"Double-tap to activate"**
**Atomic service API**: This API can be used in atomic services since API version 16. | +| accessibilityLevel18+ | string | No| Accessibility level. It determines whether the component can be recognized by accessibility services.
The options are as follows:
**"auto"**: It is treated as "yes" by the system.
**"yes"**: The component can be recognized by accessibility services.
**"no"**: The component cannot be recognized by accessibility services.
**"no-hide-descendants"**: Neither the component nor its child components can be recognized by accessibility services.
Default value: **"auto"**
**Atomic service API**: This API can be used in atomic services since API version 18.| +| accessibilityText18+ | ResourceStr | No| Accessibility text, that is, accessibility label name. If a component does not contain text information, it will not be announced by the screen reader when selected. In this case, the screen reader user cannot know which component is selected. To solve this problem, you can set accessibility text for components without text information. When such a component is selected, the screen reader announces the specified accessibility text, informing the user which component is selected.
Default value: value of the **label** property if it is set and an empty string otherwise.
**Atomic service API**: This API can be used in atomic services since API version 18. | +| accessibilityDescription18+ | ResourceStr | No| Accessible description. You can provide comprehensive text explanations to help users understand the operation they are about to perform and its potential consequences, especially when these cannot be inferred from the component's attributes and accessibility text alone. If a component contains both text information and the accessible description, the text is announced first and then the accessible description, when the component is selected.
Default value: **"Double-tap to activate"**
**Atomic service API**: This API can be used in atomic services since API version 18. | ## TabTitleBarTabItem @@ -68,34 +69,18 @@ TabTitleBar({tabItems: Array<TabTitleBarTabItem>, menuItems?: Array<Tab | -------- | -------- | -------- | -------- | | title | [ResourceStr](ts-types.md#resourcestr) | Yes| Text of the tab.| | icon | [ResourceStr](ts-types.md#resourcestr) | No| Icon of the tab.| +| symbolStyle18+ | [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) | No| Symbol icon of the tab, which has higher priority than **icon**.
**Atomic service API**: This API can be used in atomic services since API version 18.| ## Events -The [universal events](ts-universal-events-click.md) are not supported. +The [universal events](ts-component-general-events.md) are not supported. ## Example ### Example 1: Implementing a Simple Tab Title Bar This example demonstrates a tab title bar with tabs on the left and a menu list on the right. ```ts -import { TabTitleBar, promptAction } from '@kit.ArkUI' - -// Define the class for tab items on the left side of the title bar. -class tabItem { - title: ResourceStr; - icon?: ResourceStr; - constructor(title: ResourceStr,icon?: ResourceStr) { - this.title = title - this.icon = icon - } -} - -// Define the API for menu items on the right side of the title bar. -interface menuItem { - value: ResourceStr; - isEnabled?: boolean; - action?: () => void -} +import { TabTitleBar, promptAction, TabTitleBarTabItem, TabTitleBarMenuItem } from '@kit.ArkUI' @Entry @Component @@ -141,21 +126,28 @@ struct Index { } // Define several tab items on the left. - private readonly tabItems: Array = [new tabItem('Tab 1'),new tabItem('Tab 2'),new tabItem('Tab 3'),new tabItem("Happy",$r('app.media.emoji_happy')),new tabItem('Tab 4')] + private readonly tabItems: Array = + [ + { title: 'Tab 1' }, + { title: 'Tab 2' }, + { title: 'Tab 3' }, + { title: 'icon', icon: $r('sys.media.ohos_app_icon') }, + { title: 'Tab 4' }, + ] // Define several menu items on the right. - private readonly menuItems: Array = [ + private readonly menuItems: Array = [ { - value: $r('app.media.ic_public_reduce'), + value: $r('sys.media.ohos_save_button_filled'), isEnabled: true, action: () => promptAction.showToast({ message: "on item click! index 0" }) }, { - value: $r('app.media.ic_public_edit'), + value: $r('sys.media.ohos_ic_public_copy'), isEnabled: true, action: () => promptAction.showToast({ message: "on item click! index 1" }) }, { - value: $r('app.media.ic_public_save'), + value: $r('sys.media.ohos_ic_public_edit'), isEnabled: true, action: () => promptAction.showToast({ message: "on item click! index 2" }) }, @@ -176,32 +168,117 @@ struct Index { } ``` -![en-us_image_0000001616916278](figures/en-us_image_0000001616916278.png) -### Example 2: Implementing Screen Reader Announcement for the Custom Button on the Right Side + +### Example 2: Implementing Announcement for the Custom Button on the Right Side This example customizes the screen reader announcement text by setting the **accessibilityText**, **accessibilityDescription**, and **accessibilityLevel** properties of the custom button on the right side of the title bar. ```ts -import { TabTitleBar, promptAction } from '@kit.ArkUI' - -// Define the class for tab items on the left side of the title bar. -class tabItem { - title: ResourceStr; - icon?: ResourceStr; - constructor(title: ResourceStr,icon?: ResourceStr) { - this.title = title - this.icon = icon +import { TabTitleBar, promptAction, TabTitleBarTabItem, TabTitleBarMenuItem } from '@kit.ArkUI' + +@Entry +@Component +struct Index { + @Builder + // Define the pages associated with the tab list. + componentBuilder() { + Text("#1ABC9C\nTURQUOISE") + .fontWeight(FontWeight.Bold) + .fontSize(14) + .width("100%") + .textAlign(TextAlign.Center) + .fontColor("#CCFFFFFF") + .backgroundColor("#1ABC9C") + Text("#16A085\nGREEN SEA") + .fontWeight(FontWeight.Bold) + .fontSize(14) + .width("100%") + .textAlign(TextAlign.Center) + .fontColor("#CCFFFFFF") + .backgroundColor("#16A085") + Text("#2ECC71\nEMERALD") + .fontWeight(FontWeight.Bold) + .fontSize(14) + .width("100%") + .textAlign(TextAlign.Center) + .fontColor("#CCFFFFFF") + .backgroundColor("#2ECC71") + Text("#27AE60\nNEPHRITIS") + .fontWeight(FontWeight.Bold) + .fontSize(14) + .width("100%") + .textAlign(TextAlign.Center) + .fontColor("#CCFFFFFF") + .backgroundColor("#27AE60") + Text("#3498DB\nPETER RIVER") + .fontWeight(FontWeight.Bold) + .fontSize(14) + .width("100%") + .textAlign(TextAlign.Center) + .fontColor("#CCFFFFFF") + .backgroundColor("#3498DB") } -} -// Define the API for menu items on the right side of the title bar. -interface menuItem { - value: ResourceStr; - isEnabled?: boolean; - action?: () => void; - accessibilityText?: ResourceStr; - accessibilityDescription?: ResourceStr; - accessibilityLevel?: string + // Define several tab items on the left. + private readonly tabItems: Array = + [ + { title: 'Tab 1' }, + { title: 'Tab 2' }, + { title: 'Tab 3' }, + { title: 'icon', icon: $r('sys.media.ohos_app_icon') }, + { title: 'Tab 4' }, + ] + // Define several menu items on the right. + private readonly menuItems: Array = [ + { + value: $r('sys.media.ohos_save_button_filled'), + isEnabled: true, + action: () => promptAction.showToast({ message: "on item click! index 0" }), + accessibilityText: 'Save', + // The screen reader will not focus on this item. + accessibilityLevel: 'no', + accessibilityDescription: 'Tap to save the icon' + }, + { + value: $r('sys.media.ohos_ic_public_copy'), + isEnabled: true, + action: () => promptAction.showToast({ message: "on item click! index 1" }), + accessibilityText: 'Copy', + accessibilityLevel: 'yes', + accessibilityDescription: 'Tap to copy the icon' + }, + { + value: $r('sys.media.ohos_ic_public_edit'), + isEnabled: true, + action: () => promptAction.showToast({ message: "on item click! index 2" }), + // The screen reader will prioritize this text over the label. + accessibilityText: 'Edit', + // The screen reader can focus on this item. + accessibilityLevel: 'yes', + // The screen reader will ultimately announce this text. + accessibilityDescription: 'Tap to edit the icon' + }, + ] + + // Display the tab title bar. + build() { + Row() { + Column() { + TabTitleBar({ + swiperContent: this.componentBuilder, + tabItems: this.tabItems, + menuItems: this.menuItems, + }) + }.width('100%') + }.height('100%') + } } +``` + + +### Example 3: Setting the Symbol Icon +This example demonstrates how to use **symbolStyle** in **TabTitleBarTabItem** and **TabTitleBarMenuItem** to set custom symbol icons. +```ts +import { TabTitleBar, promptAction, TabTitleBarTabItem, TabTitleBarMenuItem, SymbolGlyphModifier } from '@kit.ArkUI' @Entry @Component @@ -247,36 +324,50 @@ struct Index { } // Define several tab items on the left. - private readonly tabItems: Array = [new tabItem('Tab 1'),new tabItem('Tab 2'),new tabItem('Tab 3'),new tabItem("Happy",$r('app.media.emoji_happy')),new tabItem('Tab 4')] + private readonly tabItems: Array = + [ + { title: 'Tab 1' }, + { title: 'Tab 2' }, + { title: 'Tab 3' }, + { + title: 'icon', + icon: $r('sys.media.ohos_app_icon'), + symbolStyle: new SymbolGlyphModifier($r('sys.symbol.car')) + }, + { title: 'Tab 4' }, + ] // Define several menu items on the right. - private readonly menuItems: Array = [ + private readonly menuItems: Array = [ { - value: $r('app.media.ic_public_reduce'), + value: $r('sys.media.ohos_save_button_filled'), + symbolStyle: new SymbolGlyphModifier($r('sys.symbol.save')), isEnabled: true, action: () => promptAction.showToast({ message: "on item click! index 0" }), - accessibilityText: 'Shrink', + accessibilityText: 'Save', // The screen reader will not focus on this item. accessibilityLevel: 'no', - accessibilityDescription: 'Tap to shrink the icon' + accessibilityDescription: 'Tap to save the icon' }, { - value: $r('app.media.ic_public_edit'), + value: $r('sys.media.ohos_ic_public_copy'), + symbolStyle: new SymbolGlyphModifier($r('sys.symbol.car')), isEnabled: true, action: () => promptAction.showToast({ message: "on item click! index 1" }), - accessibilityText: 'Edit', + accessibilityText: 'Copy', accessibilityLevel: 'yes', - accessibilityDescription: 'Tap to edit the icon' + accessibilityDescription: 'Tap to copy the icon' }, { - value: $r('app.media.ic_public_save'), + value: $r('sys.media.ohos_ic_public_edit'), + symbolStyle: new SymbolGlyphModifier($r('sys.symbol.ai_edit')), isEnabled: true, action: () => promptAction.showToast({ message: "on item click! index 2" }), // The screen reader will prioritize this text over the label. - accessibilityText: 'Save', + accessibilityText: 'Edit', // The screen reader can focus on this item. accessibilityLevel: 'yes', // The screen reader will ultimately announce this text. - accessibilityDescription: 'Tap to save the icon' + accessibilityDescription: 'Tap to edit the icon' }, ] @@ -294,4 +385,4 @@ struct Index { } } ``` -![en-us_image_0000001616916278](figures/en-us_image_0000001616916278.png) + diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ToolBar.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ToolBar.md index 0d50a9195efbaf8259963b5d397259c626f0e88b..2e76ab0d564d273b8979cac4508990b108e76c0e 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ToolBar.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ToolBar.md @@ -21,25 +21,23 @@ import { SymbolGlyphModifier, DividerModifier, ToolBar, ToolBarOptions, ToolBarM Not supported ## Attributes -The [universal attributes](ts-universal-attributes-size.md) are supported. +The [universal attributes](ts-component-general-attributes.md) are not supported. ## ToolBar -Toolbar({toolBarList: ToolBarOptions, activateIndex?: number, controller: TabsController, dividerModifier: DividerModifier, toolBarModifier: ToolBarModifier}) +Toolbar({toolBarList: ToolBarOptions, activateIndex?: number, controller: TabsController, dividerModifier?: DividerModifier, toolBarModifier?: ToolBarModifier}) -**Decorator**: \@Component - -**Atomic service API**: This API can be used in atomic services since API version 11. +**Decorator**: @Component **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory| Decorator | Description | -| ----------------------------- | ------------------------------------------------------------ | ---- | ----------- | ------------------------------------------------------------ | -| toolBarList | [ToolBarOptions](#toolbaroptions) | Yes | @ObjectLink | Toolbar list. | -| activateIndex | number | No | @Prop | Index of the active item.
Default value: **-1** | -| controller | [TabsController](ts-container-tabs.md#tabscontroller) | Yes | - | Toolbar controller. | -| dividerModifier13+ | [DividerModifier](ts-universal-attributes-attribute-modifier.md) | No | @Prop | Modifier for the toolbar header divider, which can be used to customize the divider's height, color, and other attributes.
**Atomic service API**: This API can be used in atomic services since API version 13.| -| toolBarModifier13+ | [ToolBarModifier](#toolbarmodifier13) | No | @Prop | Modifier for the toolbar, which can be used to set the toolbar's height, background color, padding (which only takes effect when there are fewer than five toolbar items), and whether to display the pressed state.
**Atomic service API**: This API can be used in atomic services since API version 13.| +| Name | Type | Mandatory| Decorator | Description | +| ----------------------------- | ------------------------------------------------------------ | ---- | ----------- |----------------------------------------------------------------------------------------------------------------------------------------------------------------| +| toolBarList | [ToolBarOptions](#toolbaroptions) | Yes | @ObjectLink | Toolbar list.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| activateIndex | number | No | @Prop | Index of the active item.
The value must be greater than or equal to -1.
The default value is **-1**, indicating that there is no active item. Values less than -1 are treated as no active item.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| controller | [TabsController](ts-container-tabs.md#tabscontroller) | Yes | - | Toolbar controller, which cannot be used for controlling individual toolbar items.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| dividerModifier13+ | [DividerModifier](ts-universal-attributes-attribute-modifier.md) | No | @Prop | Modifier for the toolbar header divider, which can be used to customize the divider's height, color, and other attributes.
Default value: system default value
**Atomic service API**: This API can be used in atomic services since API version 13. | +| toolBarModifier13+ | [ToolBarModifier](#toolbarmodifier13) | No | @Prop | Modifier for the toolbar, which can be used to set the toolbar's height, background color, padding (which only takes effect when there are fewer than five toolbar items), and whether to display the pressed state.
Default value:
Height of the toolbar: **56vp**
Background color: **ohos_id_toolbar_bg**
Padding: **24vp**
Whether to display the pressed state: yes
**Atomic service API**: This API can be used in atomic services since API version 13.| ## ToolBarOptions @@ -57,17 +55,20 @@ Inherits Array<[ToolBarOption](#toolbaroption)>. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory| Description | -|------------------------------------|-----------------------------------------------------------| -------- |--------------------------------------------------------------------------------------------------------------| -| content | [ResourceStr](ts-types.md#resourcestr) | Yes| Text of the toolbar item.
**Atomic service API**: This API can be used in atomic services since API version 11. | -| action | () => void | No| Click event of the toolbar item.
**Atomic service API**: This API can be used in atomic services since API version 11. | -| icon | [Resource](ts-types.md#resource) | No| Icon of the toolbar item.
If **toolBarSymbolOptions** has input parameters, **icon** is ineffective.
**Atomic service API**: This API can be used in atomic services since API version 11. | -| state | [ItemState](#itemstate) | No| State of the toolbar item.
Default value: **ENABLE**
**Atomic service API**: This API can be used in atomic services since API version 11. | -| iconColor13+ | [ResourceColor](ts-types.md#resourcecolor) | No| Icon fill color of the toolbar item.
Default value: **$r('sys.color.icon_primary')**
**Atomic service API**: This API can be used in atomic services since API version 13. | -| activatedIconColor13+ | [ResourceColor](ts-types.md#resourcecolor) | No| Icon fill color of the toolbar item in the activated state.
Default value: **$r('sys.color.icon_emphasize')**
**Atomic service API**: This API can be used in atomic services since API version 13.| -| textColor13+ | [ResourceColor](ts-types.md#resourcecolor) | No| Font color of the toolbar item.
Default value: **$r('sys.color.font_primary')**
**Atomic service API**: This API can be used in atomic services since API version 13. | -| activatedTextColor13+ | [ResourceColor](ts-types.md#resourcecolor) | No| Font color of the toolbar item in the activated state.
Default value: **$r('sys.color.font_emphasize')**
**Atomic service API**: This API can be used in atomic services since API version 13. | -| toolBarSymbolOptions13+ | [ToolBarSymbolGlyphOptions](#toolbarsymbolglyphoptions13) | No| Icon symbol options of the toolbar item.
**Atomic service API**: This API can be used in atomic services since API version 13. | +| Name | Type | Mandatory| Description | +|----------------------------------------|-----------------------------------------------------------| -------- |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| content | [ResourceStr](ts-types.md#resourcestr) | Yes| Text of the toolbar item.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| action | () => void | No| Click event of the toolbar item.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| icon | [Resource](ts-types.md#resource) | No| Icon of the toolbar item.
If **toolBarSymbolOptions** has input parameters, **icon** is ineffective.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| state | [ItemState](#itemstate) | No| State of the toolbar item.
Default value: **ENABLE**
**Atomic service API**: This API can be used in atomic services since API version 11. | +| iconColor13+ | [ResourceColor](ts-types.md#resourcecolor) | No| Icon fill color of the toolbar item.
Default value: **$r('sys.color.icon_primary')**
**Atomic service API**: This API can be used in atomic services since API version 13. | +| activatedIconColor13+ | [ResourceColor](ts-types.md#resourcecolor) | No| Icon fill color of the toolbar option in the activated state.
Default value: **$r('sys.color.icon_emphasize')**
**Atomic service API**: This API can be used in atomic services since API version 13. | +| textColor13+ | [ResourceColor](ts-types.md#resourcecolor) | No| Font color of the toolbar item.
Default value: **$r('sys.color.font_primary')**
**Atomic service API**: This API can be used in atomic services since API version 13. | +| activatedTextColor13+ | [ResourceColor](ts-types.md#resourcecolor) | No| Font color of the toolbar item in the activated state.
Default value: **$r('sys.color.font_emphasize')**
**Atomic service API**: This API can be used in atomic services since API version 13. | +| toolBarSymbolOptions13+ | [ToolBarSymbolGlyphOptions](#toolbarsymbolglyphoptions13) | No| Icon symbol options of the toolbar item.
**Atomic service API**: This API can be used in atomic services since API version 13. | +| accessibilityText18+ | [ResourceStr](ts-types.md#resourcestr) | No| Accessibility text, that is, accessible label name, of the toolbar item. If a component does not contain text information, it will not be announced by the screen reader when selected. In this case, the screen reader user cannot know which component is selected. To solve this problem, you can set accessibility text for components without text information. When such a component is selected, the screen reader announces the specified accessibility text, informing the user which component is selected.
Default value: value of **content**
**Atomic service API**: This API can be used in atomic services since API version 18. | +| accessibilityDescription18+ | [ResourceStr](ts-types.md#resourcestr) | No| Accessible description of the toolbar item. You can provide comprehensive text explanations to help users understand the operation they are about to perform and its potential consequences, especially when these cannot be inferred from the component's attributes and accessibility text alone. If a component contains both text information and the accessible description, the text is announced first and then the accessible description, when the component is selected.
Default value: **"Double-tap to activate"**
**Atomic service API**: This API can be used in atomic services since API version 18. | +| accessibilityLevel18+ | string | No| Accessibility level of the toolbar item. It determines whether the component can be recognized by accessibility services.
The options are as follows:
**"auto"**: It is treated as "yes" by the system.
**"yes"**: The component can be recognized by accessibility services.
**"no"**: The component cannot be recognized by accessibility services.
**"no-hide-descendants"**: Neither the component nor its child components can be recognized by accessibility services.
Default value: **"auto"**
**Atomic service API**: This API can be used in atomic services since API version 18.| ## ToolBarModifier13+ Provides APIs for setting the height (**height**), background color (**backgroundColor**), left and right padding (**padding**, which only takes effect when there are fewer than five items) of the toolbar, and whether to display the pressed state effect (**stateEffect**). @@ -164,19 +165,20 @@ Defines the icon symbol options. | activated| [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) | No | Icon symbol of the toolbar item in activated state.
Default value: **fontColor: $r('sys.color.icon_emphasize'), fontSize: 24vp**| ## Events -The [universal events](ts-universal-events-click.md) are supported. +The [universal events](ts-component-general-events.md) are not supported. ## Example ### Example 1: Setting Toolbar Items to Different States This example shows the various display effects when the **state** property of toolbar items is set to **ENABLE**, **DISABLE**, or **ACTIVATE**. ```ts -import { ToolBar, ToolBarOptions, ItemState } from '@kit.ArkUI' +import { ToolBar, ToolBarOptions, ItemState } from '@kit.ArkUI'; @Entry @Component struct Index { - @State toolbarList: ToolBarOptions = new ToolBarOptions() + @State toolbarList: ToolBarOptions = new ToolBarOptions(); + aboutToAppear() { this.toolbarList.push({ content: 'Cut Super Long Text', @@ -189,14 +191,14 @@ struct Index { icon: $r('sys.media.ohos_ic_public_copy'), action: () => { }, - state:ItemState.DISABLE + state: ItemState.DISABLE }) this.toolbarList.push({ content: 'Paste', icon: $r('sys.media.ohos_ic_public_paste'), action: () => { }, - state:ItemState.ACTIVATE + state: ItemState.ACTIVATE }) this.toolbarList.push({ content: 'Select All', @@ -217,6 +219,7 @@ struct Index { }, }) } + build() { Row() { Stack() { @@ -226,8 +229,10 @@ struct Index { toolBarList: this.toolbarList, }) } - }.align(Alignment.Bottom) - .width('100%').height('100%') + } + .align(Alignment.Bottom) + .width('100%') + .height('100%') } } } @@ -235,20 +240,30 @@ struct Index { ![en-us_image_toolbar_example01](figures/en-us_image_toolbar_example01.png) -### Example 2 (Customizing the Toolbar Style) -In this example, you can set the ToolBarModifier attribute to customize the toolbar height, background color, and pressing effect. +### Example 2: Customizing the Toolbar Style +This example demonstrates how to customize the toolbar's height, background color, and other styles using **ToolBarModifier**. ```ts -import { SymbolGlyphModifier, DividerModifier, ToolBar, ToolBarOptions, ToolBarModifier, ItemState, LengthMetrics } from '@kit.ArkUI'; +import { + SymbolGlyphModifier, + DividerModifier, + ToolBar, + ToolBarOptions, + ToolBarModifier, + ItemState, + LengthMetrics, +} from '@kit.ArkUI'; @Entry @Component struct Index { @State toolbarList: ToolBarOptions = new ToolBarOptions(); + // Custom toolbar style private toolBarModifier: ToolBarModifier = - new ToolBarModifier().height(LengthMetrics.vp(52)).backgroundColor(Color.Transparent).stateEffect(false); + new ToolBarModifier().height(LengthMetrics.vp(52)).backgroundColor(Color.Transparent).stateEffect(false); @State dividerModifier: DividerModifier = new DividerModifier().height(0); aboutToAppear() { + // Add toolbar items. this.toolbarList.push({ content: 'Long long long long long long long long text', icon: $r('sys.media.ohos_ic_public_share'), @@ -256,8 +271,8 @@ struct Index { }, state: ItemState.ACTIVATE, toolBarSymbolOptions: { - normal: new SymbolGlyphModifier($r('sys.symbol.ohos_star')).fontColor([Color.Green]), - activated: new SymbolGlyphModifier($r('sys.symbol.ohos_star')).fontColor([Color.Red]), + normal: new SymbolGlyphModifier($r('sys.symbol.ohos_star')).fontColor([Color.Green]), // Symbol icon in the normal state. + activated: new SymbolGlyphModifier($r('sys.symbol.ohos_star')).fontColor([Color.Red]), // Symbol icon in the activated state. }, activatedTextColor: $r('sys.color.font_primary'), }) @@ -266,17 +281,17 @@ struct Index { icon: $r('sys.media.ohos_ic_public_copy'), action: () => { }, - state:ItemState.DISABLE, + state: ItemState.DISABLE, iconColor: '#ff18cb53', - activatedIconColor: '#ffec5d5d', - activatedTextColor: '#ffec5d5d', + activatedIconColor: '#ffec5d5d', // Icon fill color of the toolbar item in the activated state. + activatedTextColor: '#ffec5d5d', // Font color of the toolbar item in the activated state. }) this.toolbarList.push({ content: 'Paste', icon: $r('sys.media.ohos_ic_public_paste'), action: () => { }, - state:ItemState.ACTIVATE, + state: ItemState.ACTIVATE, textColor: '#ff18cb53', }) this.toolbarList.push({ @@ -284,7 +299,7 @@ struct Index { icon: $r('sys.media.ohos_ic_public_select_all'), action: () => { }, - state:ItemState.ACTIVATE, + state: ItemState.ACTIVATE, }) this.toolbarList.push({ content: 'Share', @@ -299,6 +314,7 @@ struct Index { }, }) } + build() { Row() { Stack() { @@ -311,11 +327,89 @@ struct Index { }) .height(52) } - }.align(Alignment.Bottom) - .width('100%').height('100%') + } + .align(Alignment.Bottom) + .width('100%') + .height('100%') } } } ``` ![en-us_image_toolbar_example02](figures/en-us_image_toolbar_example02.png) + + +### Example 3: Implementing Screen Reader Announcement +This example customizes the screen reader announcement text by setting the **accessibilityText**, **accessibilityDescription**, and **accessibilityLevel** properties of the toolbar item. +```ts +import { ToolBar, ToolBarOptions, ItemState } from '@kit.ArkUI'; + +@Entry +@Component +struct Index { + @State toolbarList: ToolBarOptions = new ToolBarOptions(); + + aboutToAppear() { + // Add toolbar items. + this.toolbarList.push({ + content: 'Cut Super Long Text', + icon: $r('sys.media.ohos_ic_public_share'), + action: () => { + }, + accessibilityText: 'Clip', // Screen reader announcement for the item. + accessibilityDescription: 'Double-tap to clip', // Screen reader announcement for the item. + accessibilityLevel: 'yes' // Configure this element to be focused by accessibility screen readers. + }) + this.toolbarList.push({ + content: 'Copy', + icon: $r('sys.media.ohos_ic_public_copy'), + action: () => { + }, + state: ItemState.DISABLE, + accessibilityLevel: 'no' // Configure this button to be not recognizable by screen readers. + }) + this.toolbarList.push({ + content: 'Paste', + icon: $r('sys.media.ohos_ic_public_paste'), + action: () => { + }, + state: ItemState.ACTIVATE + }) + this.toolbarList.push({ + content: 'Select All', + icon: $r('sys.media.ohos_ic_public_select_all'), + action: () => { + }, + }) + this.toolbarList.push({ + content: 'Share', + icon: $r('sys.media.ohos_ic_public_share'), + action: () => { + }, + }) + this.toolbarList.push({ + content: 'Share', + icon: $r('sys.media.ohos_ic_public_share'), + action: () => { + }, + }) + } + + build() { + Row() { + Stack() { + Column() { + ToolBar({ + activateIndex: 2, + toolBarList: this.toolbarList, + }) + } + } + .align(Alignment.Bottom) + .width('100%') + .height('100%') + } + } +} +``` +![en-us_image_toolbar_example01](figures/en-us_image_toolbar_example01.png) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ToolBarV2.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ToolBarV2.md new file mode 100644 index 0000000000000000000000000000000000000000..f5fa1d39f5587a8cbb791e21d7ad02e3fd4b2e7f --- /dev/null +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-ToolBarV2.md @@ -0,0 +1,743 @@ +# ToolBarV2 + +The **Toolbar** component is designed to present a set of action options related to the current screen, displayed at the bottom of the screen. It can display up to five child components. If there are six or more child components, the first four are shown directly, and the additional ones are grouped under a **More** item on the rightmost side of the toolbar.
+This component is implemented based on [state management V2](../../../quick-start/arkts-state-management-overview.md#state-management-v2). Compared with [state management V1](../../../quick-start/arkts-state-management-overview.md#state-management-v1), V2 offers a higher level of observation and management over data objects beyond the component level. You can now more easily manage toolbar data and states with greater flexibility, leading to faster UI updates.
+ +> **NOTE** +> +> - This component is supported since API version 18. Updates will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```ts +import { ToolBarV2 } from '@kit.ArkUI'; +``` + +## Child Components + +Not supported + + +## ToolBarV2 + +ToolbarV2({toolBarList: ToolBarV2Item\[], activatedIndex?: number, dividerModifier: DividerModifier, toolBarModifier: ToolBarV2Modifier}) + +Creates a toolbar. + +**Decorator**: @ComponentV2 + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Decorator | Description | +| -------------------- | ---------------------------------------------------------------- | -- |---------------------|--------------------------------------------------------------| +| toolBarList | [ToolBarV2Item](#toolbarv2item)\[] | Yes | @Param
@Require | Toolbar list. | +| activatedIndex | number | No | @Param | Index of the active item.
Default value: **-1**, indicating that no toolbar item is activated
Value range: [-1, 4] | +| dividerModifier | [DividerModifier](ts-universal-attributes-attribute-modifier.md) | No | @Param | Modifier for the toolbar header divider, which can be used to customize the divider's height, color, and other attributes.
This parameter does not take effect by default. | +| toolBarModifier | [ToolBarV2Modifier](#toolbarv2modifier) | No | @Param | Modifier for the toolbar, which can be used to set the toolbar's height, background color, padding (which only takes effect when there are fewer than five toolbar items), and whether to display the pressed state.
This parameter does not take effect by default.| + +## ToolBarV2Item +Defines an item in the toolbar. + +**Decorator type**: @ObservedV2 + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +### Properties + +| Name | Type | Mandatory| Decorator | Description | +| ---------------------------- | ----------------------------------------------- | -- | :----- |-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| content | [ToolBarV2ItemText](#toolbarv2itemtext) | Yes | @Trace | Text of the toolbar item. | +| action | [ToolBarV2ItemAction](#toolbarv2itemaction) | No | @Trace | Click event of the toolbar item.

By default, there is no click event. | +| icon | [ToolBarV2ItemIconType](#toolbarv2itemicontype) | No | @Trace | Icon of the toolbar item.

By default, there is no icon. | +| state | [ToolBarV2ItemState](#toolbarv2itemstate) | No | @Trace | State of the toolbar item.
Default value: **ENABLE**
| +| accessibilityText | [ResourceStr](ts-types.md#resourcestr) | No | @Trace | Accessibility text, that is, accessible label name, of the toolbar item. If a component does not contain text information, it will not be announced by the screen reader when selected. In this case, the screen reader user cannot know which component is selected. To solve this problem, you can set accessibility text for components without text information. When such a component is selected, the screen reader announces the specified accessibility text, informing the user which component is selected.

Default value: value of **content** | +| accessibilityDescription | [ResourceStr](ts-types.md#resourcestr) | No | @Trace | Accessible description of the toolbar item. You can provide comprehensive text explanations to help users understand the operation they are about to perform and its potential consequences, especially when these cannot be inferred from the component's attributes and accessibility text alone. If a component contains both text information and the accessible description, the text is announced first and then the accessible description, when the component is selected.
Default value: **"Double-tap to activate"** | +| accessibilityLevel | string | No | @Trace | Accessibility level of the toolbar item. It determines whether the component can be recognized by accessibility services.

The options are as follows:
**"auto"**: It is treated as "yes" by the system.
**"yes"**: The component can be recognized by accessibility services.
**"no"**: The component cannot be recognized by accessibility services.
**"no-hide-descendants"**: Neither the component nor its child components can be recognized by accessibility services.
Default value: **"auto"**
| + +### constructor + +constructor(options: ToolBarV2ItemOptions) + +A constructor used to create a **ToolBarV2Item** instance. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Description | +| :------ |:----------------------------------------------| :- | :------- | +| options | [ToolBarV2ItemOptions](#toolbarv2itemoptions) | Yes | Configuration options of the toolbar item.| + +## ToolBarV2ItemOptions + +Defines the options for initializing a **ToolBarV2Item** object. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Description | +|:-------------------------| :---------------------------------------------- | :- |:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| content | [ToolBarV2ItemText](#toolbarv2itemtext) | Yes | Text of the toolbar item. | +| action | [ToolBarV2ItemAction](#toolbarv2itemaction) | No | Click event of the toolbar item.
By default, there is no click event. | +| icon | [ToolBarV2ItemIconType](#toolbarv2itemicontype) | No | Icon of the toolbar item.
By default, there is no icon. | +| state | [ToolBarV2ItemState](#toolbarv2itemstate) | No | State of the toolbar item.
Default value: **ENABLE** | +| accessibilityText | [ResourceStr](ts-types.md#resourcestr) | No | Accessibility text, that is, accessible label name, of the toolbar item. If a component does not contain text information, it will not be announced by the screen reader when selected. In this case, the screen reader user cannot know which component is selected. To solve this problem, you can set accessibility text for components without text information. When such a component is selected, the screen reader announces the specified accessibility text, informing the user which component is selected.
Default value: value of **content** | +| accessibilityDescription | [ResourceStr](ts-types.md#resourcestr) | No | Accessible description of the toolbar item. You can provide comprehensive text explanations to help users understand the operation they are about to perform and its potential consequences, especially when these cannot be inferred from the component's attributes and accessibility text alone. If a component contains both text information and the accessible description, the text is announced first and then the accessible description, when the component is selected.
Default value: **"Double-tap to activate"** | +| accessibilityLevel | string | No | Accessibility level of the toolbar item. It determines whether the component can be recognized by accessibility services.
The options are as follows:
**"auto"**: It is treated as "yes" by the system.
**"yes"**: The component can be recognized by accessibility services.
**"no"**: The component cannot be recognized by accessibility services.
**"no-hide-descendants"**: Neither the component nor its child components can be recognized by accessibility services.
Default value: **"auto"** | + +## ToolBarV2ItemAction + +type ToolBarV2ItemAction = (index: number) => void + +Defines the callback for the click event of a toolbar item. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description| +|:------|:-------|:---|----| +| index | number | Yes |Index of the toolbar item that triggers the click event.
| + +## ToolBarV2ItemText + +Defines the text of a toolbar item. + +**Decorator type**: @ObservedV2 + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +### Properties + +| Name | Type | Mandatory| Decorator | Description | +|:--------------------|:------------------------------------------------------------| :- | :----- |:---------------------------------------------------------| +| text | [ResourceStr](ts-types.md#resourcestr) | Yes | @Trace | Text of the toolbar item. | +| color | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | No | @Trace | Font color of the toolbar item.
Default value: **$r('sys.color.font_primary')** | +| activatedColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | No | @Trace | Font color of the toolbar item in the activated state.
Default value: **$r('sys.color.font_emphasize')** | + +### constructor + +constructor(options: ToolBarV2ItemTextOptions) + +A constructor used to create a **ToolBarV2ItemText** instance. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Description | +| :------ |:------------------------------------------------------| :- | :--------- | +| options | [ToolBarV2ItemTextOptions](#toolbarv2itemtextoptions) | Yes | Configuration options of the text content.| + +## ToolBarV2ItemTextOptions + +Defines the options for initializing a **ToolBarV2ItemText** object. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Description | +| :------------------ |:------------------------------------------------------------| :- |:---------------------------------------------------------| +| text | [ResourceStr](ts-types.md#resourcestr) | Yes | Text of the toolbar item. | +| color | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | No | Font color of the toolbar item.
Default value: **$r('sys.color.font_primary')** | +| activatedColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | No | Font color of the toolbar item in the activated state.
Default value: **$r('sys.color.font_emphasize')**| + +## ToolBarV2ItemImage + +Defines the icon content of a toolbar item. + +**Decorator type**: @ObservedV2 + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +### Properties + +| Name | Type | Mandatory| Decorator | Description | +|:-------------------|:------------------------------------------------------------| :- | :----- |:---------------------------------------------------------| +| src | [ResourceStr](ts-types.md#resourcestr) | Yes | @Trace | Resource path of the icon. | +| color | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | No | @Trace | Color of the icon.
Default value: **$r('sys.color.icon_primary')** | +| activatedColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | No | @Trace | Color of the icon when the toolbar item is activated.
Default value: **$r('sys.color.icon_emphasize')**| + +### constructor + +constructor(options: ToolBarV2ItemImageOptions) + +A constructor used to create a **ToolBarV2ItemImage** instance. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Description | +| :------ | :------------------------------------------------------ | :- | :--------- | +| options | [ToolBarV2ItemImageOptions](#toolbarv2itemimageoptions) | Yes | Configuration options for the icon content of the toolbar item.| + +## ToolBarV2ItemImageOptions + +Defines the options for initializing a **ToolBarV2ItemImage** object. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Description | +|:--------------------|:------------------------------------------------------------| :- |:---------------------------------------------------------| +| src | [ResourceStr](ts-types.md#resourcestr) | Yes | Resource path of the icon. | +| color | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | No | Color of the icon.
Default value: **$r('sys.color.icon_primary')** | +| activatedColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | No | Color of the icon when the toolbar item is activated.
Default value: **$r('sys.color.icon_emphasize')**| + +## ToolBarV2ItemIconType + +type ToolBarV2ItemIconType = ToolBarV2ItemImage | ToolBarV2SymbolGlyph + +Defines the union type for the icon content of a toolbar item. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Type | Description | +| :------------------- | :------------ | +| ToolBarV2ItemImage | Type for defining a common icon. | +| ToolBarV2SymbolGlyph | Type for defining a symbol icon.| + +## ToolBarV2Modifier + +Provides APIs for setting the height (**height**), background color (**backgroundColor**), left and right padding (**padding**, which only takes effect when there are fewer than five items) of the toolbar, and whether to display the pressed state effect (**stateEffect**). + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +### backgroundColor + +backgroundColor(backgroundColor: ColorMetrics): ToolBarV2Modifier + +Sets the background color of the toolbar. By overriding this API, you can implement custom drawing for the background color of the toolbar. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- |-------------------------------------------------------------| -- | ----------------------------------------------------------------- | +| backgroundColor | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | Yes | Toolbar background color
Default value: **\$r('sys.color.ohos\_id\_color\_toolbar\_bg')**| +**Return value** + +| Type | Description | +|-----------------------------------------|-----------------------------------------| +| [ToolBarV2Modifier](#toolbarv2modifier) | **ToolBarV2Modifier** object after the background color is set.| + +### padding + +padding(padding: LengthMetrics): ToolBarV2Modifier + +Sets the left and right padding of the toolbar. By overriding this API, you can implement custom drawing for the left and right padding of the toolbar. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- |---------------------------------------------------------------| -- | ------------------------------------------------------------------- | +| padding | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes | Left and right padding of the toolbar, which is effective only when there are fewer than five items.

By default, the padding is 24 vp when there are fewer than five items and 0 when there are five or more items.| + +**Return value** + +| Type | Description | +|-----------------------------------------|---------------------------------| +| [ToolBarV2Modifier](#toolbarv2modifier) | **ToolBarV2Modifier** object after the padding is set.| +### height + +height(height: LengthMetrics): ToolBarV2Modifier + +Sets the height of the toolbar. By overriding this API, you can implement custom drawing for the height of the toolbar, which does not include the height of the divider. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------ | ------------------------------------------------------------------ | -- | --------------------------------- | +| height | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes | Height of the toolbar.
The default height of the toolbar is 56 vp, which does not include the divider.| + +**Return value** + +| Type | Description | +|-----------------------------------------|--------------------------------| +| [ToolBarV2Modifier](#toolbarv2modifier) | **ToolBarV2Modifier** object after the height is set.| + +### stateEffect + +stateEffect(stateEffect: boolean): ToolBarV2Modifier + +Sets whether to display the pressed state effect. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------- | -- |--------------------------------------------------------| +| stateEffect | boolean | Yes | Whether to display the pressed state effect on the toolbar.
**true**: Display the pressed state effect.
**false**: Do not display the pressed state effect.
Default value: **true**| + +**Return value** + +| Type | Description | +|-----------------------------------------|-------------------------------------| +| [ToolBarV2Modifier](#toolbarv2modifier) | **ToolBarV2Modifier** object after the pressed state effect is set.| + +## ToolBarV2ItemState + +Enumerates the states of the toolbar item. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Value| Description | +| -------- | - | --------------- | +| ENABLE | 1 | The toolbar item is enabled. | +| DISABLE | 2 | The toolbar item is disabled. | +| ACTIVATE | 3 | The toolbar item is activated.| + +## ToolBarV2SymbolGlyph + +Defines the configuration options of the symbol icon. + +**Decorator type**: @ObservedV2 + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +### Properties + +| Name | Type | Mandatory| Decorator | Description | +| :-------- | :------------------------------------------------------------------- | :- | :----- | :----------------------------------------------------------------------------------- | +| normal | [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) | Yes | @Trace | Icon symbol of the toolbar item in normal state. | +| activated | [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) | No | @Trace | Icon symbol of the toolbar item in activated state.
Default value:
**fontColor**: **\$r('sys.color.icon\_emphasize')**, **fontSize**: **24vp**| + +### constructor + +constructor(options: ToolBarV2SymbolGlyphOptions) + +A constructor used to create a **ToolBarV2SymbolGlyph** object. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Description | +| :------ | :---------------------------------------------------------- | :- | :---------- | +| options | [ToolBarV2SymbolGlyphOptions](#toolbarv2symbolglyphoptions) | Yes | Configuration options of the symbol icon.| + +## ToolBarV2SymbolGlyphOptions + +Defines the options for initializing a **ToolBarV2SymbolGlyph** object. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Description | +| --------- | -------------------------------------------------------------------- | -- | ------------------------------------------------------------------------------------ | +| normal | [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) | Yes | Icon symbol of the toolbar item in normal state. | +| activated | [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) | No | Icon symbol of the toolbar item in activated state.
Default value:
**fontColor**: **\$r('sys.color.icon\_emphasize')**, **fontSize**: **24vp**| + +## Example + +### Example 1: Setting Toolbar Items to Different States + +This example shows the various display effects when the **state** property of toolbar items is set to **ENABLE**, **DISABLE**, or **ACTIVATE**. + +```ts +import { ToolBarV2ItemImage, ToolBarV2ItemState, ToolBarV2ItemText, ToolBarV2Item, ToolBarV2 } from '@kit.ArkUI' + +@Entry +@ComponentV2 +struct Index { + @Local toolbarList: ToolBarV2Item[] = [] + + aboutToAppear() { + this.toolbarList.push(new ToolBarV2Item({ + content: new ToolBarV2ItemText( + { + text: 'Cut Super Long Text' + } + ), + icon: new ToolBarV2ItemImage({ + src: $r('sys.media.ohos_ic_public_share') + }), + action: () => { + }, + })) + this.toolbarList.push( + new ToolBarV2Item({ + content: new ToolBarV2ItemText( + { + text: 'Copy' + } + ), + icon: new ToolBarV2ItemImage({ + src: $r('sys.media.ohos_ic_public_copy') + }), + action: () => { + }, + state: ToolBarV2ItemState.DISABLE + }) + ) + this.toolbarList.push( + new ToolBarV2Item({ + content: new ToolBarV2ItemText( + { + text: 'Paste' + } + ), + icon: new ToolBarV2ItemImage({ + src: $r('sys.media.ohos_ic_public_paste') + }), + action: () => { + }, + state: ToolBarV2ItemState.ACTIVATE + }) + ) + this.toolbarList.push( + new ToolBarV2Item({ + content: new ToolBarV2ItemText( + { + text:'Select All' + } + ), + icon: new ToolBarV2ItemImage({ + src: $r('sys.media.ohos_ic_public_select_all') + }), + action: () => { + }, + }) + ) + this.toolbarList.push( + new ToolBarV2Item({ + content: new ToolBarV2ItemText( + { + text: 'Share' + } + ), + icon: new ToolBarV2ItemImage({ + src: $r('sys.media.ohos_ic_public_share') + }), + action: () => { + }, + }) + ) + this.toolbarList.push( + new ToolBarV2Item({ + content: new ToolBarV2ItemText( + { + text: 'Share' + } + ), + icon: new ToolBarV2ItemImage({ + src: $r('sys.media.ohos_ic_public_share') + }), + action: () => { + }, + }) + ) + } + + build() { + Row() { + Stack() { + Column() { + ToolBarV2({ + activatedIndex: 2, + toolBarList: this.toolbarList, + }) + } + }.align(Alignment.Bottom) + .width('100%').height('100%') + } + } +} +``` + +![en-us\_image\_toolbar\_example01](figures/en-us_image_toolbar_example01.png) + +### Example 2: Customizing the Toolbar Style + +This example demonstrates how to customize the toolbar's height, background color, and other styles using **ToolBarV2Modifier**. + +```ts +import { + SymbolGlyphModifier, + DividerModifier, + LengthMetrics, + ColorMetrics, + ToolBarV2Item, + ToolBarV2Modifier, + ToolBarV2ItemText, + ToolBarV2ItemImage, + ToolBarV2, + ToolBarV2ItemState, + ToolBarV2SymbolGlyph +} from '@kit.ArkUI'; + +@Entry +@ComponentV2 +struct Index { + @Local toolbarList: ToolBarV2Item[] = []; + private toolBarModifier: ToolBarV2Modifier = + new ToolBarV2Modifier().height(LengthMetrics.vp(52)) + .backgroundColor(ColorMetrics.resourceColor(Color.Transparent)) + .stateEffect(false); + @Local dividerModifier: DividerModifier = new DividerModifier().height(0); + + aboutToAppear() { + this.toolbarList.push( + new ToolBarV2Item({ + content: new ToolBarV2ItemText({ + text: 'Long long long long long long long long text', + activatedColor: ColorMetrics.resourceColor($r('sys.color.font_primary')) + }), + icon: new ToolBarV2SymbolGlyph({ + normal: new SymbolGlyphModifier($r('sys.symbol.ohos_star')).fontColor([Color.Green]), + activated: new SymbolGlyphModifier($r('sys.symbol.ohos_star')).fontColor([Color.Red]), + }), + action: () => { + }, + state: ToolBarV2ItemState.ACTIVATE, + }) + ) + this.toolbarList.push( + new ToolBarV2Item({ + content: new ToolBarV2ItemText({ + text: 'Copy', + activatedColor: ColorMetrics.resourceColor('#ffec5d5d') + }), + icon: new ToolBarV2ItemImage({ + src: $r('sys.media.ohos_ic_public_copy'), + color: ColorMetrics.resourceColor('#ff18cb53'), + activatedColor: ColorMetrics.resourceColor('#ffec5d5d'), + }), + action: () => { + }, + state: ToolBarV2ItemState.DISABLE, + })) + this.toolbarList.push( + new ToolBarV2Item({ + content: new ToolBarV2ItemText({ + text: 'Paste', + color: ColorMetrics.resourceColor('#ff18cb53') + }), + icon: new ToolBarV2ItemImage({ + src: $r('sys.media.ohos_ic_public_paste'), + }), + action: () => { + }, + state: ToolBarV2ItemState.ACTIVATE, + }) + ) + this.toolbarList.push( + new ToolBarV2Item({ + content: new ToolBarV2ItemText({ + text: 'All', + }), + icon: new ToolBarV2ItemImage({ + src: $r('sys.media.ohos_ic_public_select_all'), + }), + action: () => { + }, + state: ToolBarV2ItemState.ACTIVATE, + })) + this.toolbarList.push( + new ToolBarV2Item({ + content: new ToolBarV2ItemText({ + text: 'Share', + }), + icon: new ToolBarV2ItemImage({ + src: $r('sys.media.ohos_ic_public_share'), + }), + action: () => { + }, + })) + this.toolbarList.push( + new ToolBarV2Item({ + content: new ToolBarV2ItemText({ + text: 'Share', + }), + icon: new ToolBarV2ItemImage({ + src: $r('sys.media.ohos_ic_public_share'), + }), + action: () => { + }, + }) + ) + } + + build() { + Row() { + Stack() { + Column() { + ToolBarV2({ + toolBarModifier: this.toolBarModifier, + dividerModifier: this.dividerModifier, + activatedIndex: 0, + toolBarList: this.toolbarList, + }) + .height(52) + } + }.align(Alignment.Bottom) + .width('100%').height('100%') + } + } +} +``` + +![en-us\_image\_toolbar\_example02](figures/en-us_image_toolbar_example02.png) + +### Example 3: Implementing Screen Reader Announcement + +This example customizes the screen reader announcement text by setting the **accessibilityText**, **accessibilityDescription**, and **accessibilityLevel** properties of the toolbar item. + +```ts +import { + DividerModifier, + LengthMetrics, + ColorMetrics, + ToolBarV2Item, + ToolBarV2Modifier, + ToolBarV2ItemText, + ToolBarV2ItemImage, + ToolBarV2, + ToolBarV2ItemState, +} from '@kit.ArkUI'; + +@Entry +@ComponentV2 +struct Index { + @Local toolbarList: ToolBarV2Item[] = []; + private toolBarModifier: ToolBarV2Modifier = + new ToolBarV2Modifier().height(LengthMetrics.vp(52)) + .backgroundColor(ColorMetrics.resourceColor(Color.Transparent)) + .stateEffect(false); + @Local dividerModifier: DividerModifier = new DividerModifier().height(0); + + aboutToAppear() { + this.toolbarList.push( + new ToolBarV2Item({ + content: new ToolBarV2ItemText({ + text: 'Cut Super Long Text', + }), + icon: new ToolBarV2ItemImage({ + src: $r('sys.media.ohos_ic_public_share') + }), + action: () => { + }, + accessibilityText: 'Clip', // Screen reader announcement for the item. + accessibilityDescription: 'Double-tap to clip', // Screen reader announcement for the item. + accessibilityLevel: 'yes' // Configure this element to be focused by screen readers. + }) + ) + this.toolbarList.push( + new ToolBarV2Item({ + content: new ToolBarV2ItemText({ + text: 'Copy', + }), + icon: new ToolBarV2ItemImage({ + src: $r('sys.media.ohos_ic_public_copy'), + }), + action: () => { + }, + state: ToolBarV2ItemState.DISABLE, + accessibilityLevel: 'no' // Configure this button to be not recognizable by screen readers. + })) + this.toolbarList.push( + new ToolBarV2Item({ + content: new ToolBarV2ItemText({ + text: 'Paste', + }), + icon: new ToolBarV2ItemImage({ + src: $r('sys.media.ohos_ic_public_paste'), + }), + action: () => { + }, + state: ToolBarV2ItemState.ACTIVATE, + }) + ) + this.toolbarList.push( + new ToolBarV2Item({ + content: new ToolBarV2ItemText({ + text: 'Select All', + }), + icon: new ToolBarV2ItemImage({ + src: $r('sys.media.ohos_ic_public_select_all'), + }), + action: () => { + }, + })) + this.toolbarList.push( + new ToolBarV2Item({ + content: new ToolBarV2ItemText({ + text: 'Share', + }), + icon: new ToolBarV2ItemImage({ + src: $r('sys.media.ohos_ic_public_share'), + }), + action: () => { + }, + })) + this.toolbarList.push( + new ToolBarV2Item({ + content: new ToolBarV2ItemText({ + text: 'Share', + }), + icon: new ToolBarV2ItemImage({ + src: $r('sys.media.ohos_ic_public_share'), + }), + action: () => { + }, + }) + ) + } + + build() { + Row() { + Stack() { + Column() { + ToolBarV2({ + toolBarModifier: this.toolBarModifier, + dividerModifier: this.dividerModifier, + activatedIndex: 0, + toolBarList: this.toolbarList, + }) + .height(52) + } + }.align(Alignment.Bottom) + .width('100%').height('100%') + } + } +} +``` + +![en-us\_image\_toolbar\_example01](figures/en-us_image_toolbar_example01.png) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-TreeView.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-TreeView.md index d8d00fa872b5223237b2a1a90b20dc803f242929..627c4eada2f0a04fe1dde2f8b952b6c8f1f9face 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-TreeView.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-TreeView.md @@ -24,7 +24,7 @@ import { TreeView } from "@kit.ArkUI" Not supported ## Attributes -The [universal attributes](ts-universal-attributes-size.md) are not supported. +The [universal attributes](ts-component-general-attributes.md) are not supported. ## TreeView @@ -125,21 +125,22 @@ Refreshes the tree view. You can call this API to update the information about t ## NodeParam -**Atomic service API**: This API can be used in atomic services since API version 11. - **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| parentNodeId | number | No| Parent node.| -| currentNodeId | number | No| Current child node.| -| isFolder | boolean | No| Whether the node is a directory.
Default value: **false**.
**true**: The node is a directory.
**false**: The node is not a directory.| -| icon | [ResourceStr](ts-types.md#resourcestr) | No| Icon.| -| selectedIcon | [ResourceStr](ts-types.md#resourcestr) | No| Icon of the selected node.| -| editIcon | [ResourceStr](ts-types.md#resourcestr) | No| Edit icon.| -| primaryTitle | [ResourceStr](ts-types.md#resourcestr) | No| Primary title.| -| secondaryTitle | [ResourceStr](ts-types.md#resourcestr) | No| Secondary title.| -| container | () => void | No| Right-click child component bound to the node. The child component is decorated with @Builder.| +| Name| Type| Mandatory| Description | +| -------- | -------- | -------- |--------------------------------------------------------------------------------------------------------------------------------------------------| +| parentNodeId | number | No| Parent node.
The value must be greater than or equal to -1.
Default value: -1. The root node ID is -1. If the value is less than -1, the setting does not take effect.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| currentNodeId | number | No| Current child node.
The value must be greater than or equal to -1.
The value cannot be the root node ID, cannot be null, and cannot be duplicated.
Default value: **-1**
**Atomic service API**: This API can be used in atomic services since API version 11.| +| isFolder | boolean | No| Whether the node is a directory.
Default value: **false**.
**true**: The node is a directory.
**false**: The node is not a directory.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| icon | [ResourceStr](ts-types.md#resourcestr) | No| Icon.
The default value is an empty string.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| symbolIconStyle18+ | [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) | No| Symbol icon, which has higher priority than **icon**.
Default value: **undefined**
**Atomic service API**: This API can be used in atomic services since API version 18. | +| selectedIcon | [ResourceStr](ts-types.md#resourcestr) | No| Icon of the selected node.
The default value is an empty string.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| symbolSelectedIconStyle18+ | [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) | No| Symbol icon of the selected node., which has higher priority than **selectedIcon**.
Default value: **undefined**
**Atomic service API**: This API can be used in atomic services since API version 18. | +| editIcon | [ResourceStr](ts-types.md#resourcestr) | No| Edit icon.
The default value is an empty string.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| symbolEditIconStyle18+ | [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) | No| Symbol edit icon, which has a higher priority than **editIcon**.
Default value: **undefined**
**Atomic service API**: This API can be used in atomic services since API version 18. | +| primaryTitle | [ResourceStr](ts-types.md#resourcestr) | No| Primary title.
The default value is an empty string.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| secondaryTitle | [ResourceStr](ts-types.md#resourcestr) | No| Secondary title.
The default value is an empty string.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| container | () => void | No| Right-click child component bound to the node. The child component is decorated with @Builder.
Default value: **() => void**
**Atomic service API**: This API can be used in atomic services since API version 11. | ## TreeListenerManager @@ -255,17 +256,21 @@ Unregisters a listener. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| currentNodeId | number | Yes| Current child node.| -| parentNodeId | number | No| Parent node.| -| childIndex | number | No| Child index.| +| Name| Type| Mandatory| Description | +| -------- | -------- | -------- |------------------------------------------| +| currentNodeId | number | Yes| ID of the current child node.
The value must be greater than or equal to 0. | +| parentNodeId | number | No| ID of the current parent node.
The value must be greater than or equal to -1.
Default value: **-1**| +| childIndex | number | No| Child index.
The value must be greater than or equal to -1.
Default value: **-1** | ## Events -The [universal events](ts-universal-events-click.md) are not supported. +The [universal events](ts-component-general-events.md) are not supported. ## Example + +### Example 1: Configuring a Simple Tree View + This example showcases how to use **TreeController** to perform operations on tree nodes, such as adding, deleting, and renaming. It also demonstrates the effects of adding nodes with different parameters. + ```ts import { TreeController, TreeListener, TreeListenerManager, TreeListenType, NodeParam, TreeView, CallbackParam } from '@kit.ArkUI' @@ -274,7 +279,7 @@ import { TreeController, TreeListener, TreeListenerManager, TreeListenType, Node struct TreeViewDemo { private treeController: TreeController = new TreeController(); private treeListener: TreeListener = TreeListenerManager.getInstance().getTreeListener(); - @State clickNodeId: number = 0; + @State clickId: number = 0; aboutToDisappear(): void { this.treeListener.off(TreeListenType.NODE_CLICK, undefined); @@ -304,23 +309,23 @@ struct TreeViewDemo { aboutToAppear(): void { this.treeListener.on(TreeListenType.NODE_CLICK, (callbackParam: CallbackParam) => { - this.clickNodeId = callbackParam.currentNodeId; + this.clickId = callbackParam.currentNodeId; }) this.treeListener.on(TreeListenType.NODE_ADD, (callbackParam: CallbackParam) => { - this.clickNodeId = callbackParam.currentNodeId; + this.clickId = callbackParam.currentNodeId; }) this.treeListener.on(TreeListenType.NODE_DELETE, (callbackParam: CallbackParam) => { - this.clickNodeId = callbackParam.currentNodeId; + this.clickId = callbackParam.currentNodeId; }) this.treeListener.once(TreeListenType.NODE_MOVE, (callbackParam: CallbackParam) => { - this.clickNodeId = callbackParam.currentNodeId; + this.clickId = callbackParam.currentNodeId; }) - let normalResource: Resource = $r('app.media.ic_public_collect_normal'); - let selectedResource: Resource = $r('app.media.ic_public_collect_selected'); - let editResource: Resource = $r('app.media.ic_public_collect_edit'); + let normalResource: Resource = $r('sys.media.ohos_ic_normal_white_grid_folder'); + let selectedResource: Resource = $r('sys.media.ohos_ic_public_select_all'); + let editResource: Resource = $r('sys.media.ohos_ic_public_edit'); let nodeParam: NodeParam = { parentNodeId:-1, currentNodeId: 1, isFolder: true, icon: normalResource, selectedIcon: selectedResource, - editIcon: editResource, primaryTitle: "Directory 1: Verify the effect of the floating box", + editIcon: editResource, primaryTitle: "Directory 1 to verify the adaptive effect", secondaryTitle: "6" }; this.treeController .addNode(nodeParam) @@ -351,7 +356,7 @@ struct TreeViewDemo { Row() { Divider().vertical(true).strokeWidth(2).color(0x000000).lineCap(LineCapStyle.Round) Column({ space: 30 }) { - Text('ClickNodeId=' + this.clickNodeId).fontSize('16fp') + Text('ClickId=' + this.clickId).fontSize('16fp') Button('Add', { type: ButtonType.Normal, stateEffect: true }) .borderRadius(8).backgroundColor(0x317aff).width(90) .onClick((event: ClickEvent) => { @@ -378,3 +383,129 @@ struct TreeViewDemo { ``` ![en-us_image_0000001664822257](figures/en-us_image_0000001664822257.png) + +### Example 2: Setting the Symbol Icon + +This example demonstrates how to use **symbolIconStyle**, **symbolEditIconStyle**, and **symbolSelectedIconStyle** in **NodeParam** to set custom symbol icons. + +```ts +import { TreeController, TreeListener, TreeListenerManager, TreeListenType, NodeParam, TreeView, CallbackParam, + SymbolGlyphModifier } from '@kit.ArkUI' + +@Entry +@Component +struct TreeViewDemo { + private treeController: TreeController = new TreeController(); + private treeListener: TreeListener = TreeListenerManager.getInstance().getTreeListener(); + @State clickNodeId: number = 0; + + aboutToDisappear(): void { + this.treeListener.off(TreeListenType.NODE_CLICK, undefined); + this.treeListener.off(TreeListenType.NODE_ADD, undefined); + this.treeListener.off(TreeListenType.NODE_DELETE, undefined); + this.treeListener.off(TreeListenType.NODE_MOVE, undefined); + } + + @Builder menuBuilder1() { + Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { + Text('Add').fontSize(16).width(100).height(30).textAlign(TextAlign.Center) + .onClick((event: ClickEvent) => { + this.treeController.addNode(); + }) + Divider() + Text('Delete').fontSize(16).width(100).height(30).textAlign(TextAlign.Center) + .onClick((event: ClickEvent) => { + this.treeController.removeNode(); + }) + Divider() + Text('Rename').fontSize(16).width(100).height(30).textAlign(TextAlign.Center) + .onClick((event: ClickEvent) => { + this.treeController.modifyNode(); + }) + }.width(100).border({width: 1, color: 0x80808a, radius: '16dp'}) + } + + aboutToAppear(): void { + this.treeListener.on(TreeListenType.NODE_CLICK, (callbackParam: CallbackParam) => { + this.clickNodeId = callbackParam.currentNodeId; + }) + this.treeListener.on(TreeListenType.NODE_ADD, (callbackParam: CallbackParam) => { + this.clickNodeId = callbackParam.currentNodeId; + }) + this.treeListener.on(TreeListenType.NODE_DELETE, (callbackParam: CallbackParam) => { + this.clickNodeId = callbackParam.currentNodeId; + }) + this.treeListener.once(TreeListenType.NODE_MOVE, (callbackParam: CallbackParam) => { + this.clickNodeId = callbackParam.currentNodeId; + }) + + let normalResource: Resource = $r('sys.symbol.house'); + let selectedResource: Resource = $r('sys.symbol.car'); + let editResource: Resource = $r('sys.symbol.calendar'); + let normalSymbolResource: SymbolGlyphModifier = new SymbolGlyphModifier($r('sys.symbol.bell')).fontColor([Color.Red]); + let selectedSymbolResource: SymbolGlyphModifier = new SymbolGlyphModifier($r('sys.symbol.heart')).fontColor([Color.Blue]); + let editSymbolResource: SymbolGlyphModifier = new SymbolGlyphModifier($r('sys.symbol.cake')).fontColor([Color.Pink]); + let nodeParam: NodeParam = { parentNodeId:-1, currentNodeId: 1, isFolder: true, icon: normalResource, selectedIcon: selectedResource, + editIcon: editResource, primaryTitle: "Directory 1", + secondaryTitle: "6" }; + this.treeController + .addNode(nodeParam) + .addNode({parentNodeId:1, currentNodeId: 2, isFolder: false, primaryTitle: "Project 1_1" }) + .addNode({ parentNodeId:-1, currentNodeId: 7, isFolder: true, primaryTitle: "Directory 2" }) + .addNode({ parentNodeId:-1, currentNodeId: 23, isFolder: true, icon: normalResource, symbolIconStyle: normalSymbolResource, + selectedIcon: selectedResource, symbolSelectedIconStyle: selectedSymbolResource, editIcon: editResource, + symbolEditIconStyle: editSymbolResource, primaryTitle: "Directory 3" }) + .addNode({ parentNodeId:-1, currentNodeId: 24, isFolder: false, primaryTitle: "Project 4" }) + .addNode({ parentNodeId:-1, currentNodeId: 31, isFolder: true, icon: normalResource, symbolIconStyle: normalSymbolResource, + selectedIcon: selectedResource, symbolSelectedIconStyle: selectedSymbolResource, editIcon: editResource, + symbolEditIconStyle: editSymbolResource, primaryTitle: "Directory 5", secondaryTitle: "0" }) + .addNode({ parentNodeId:-1, currentNodeId: 32, isFolder: true, icon: normalResource, symbolIconStyle: normalSymbolResource, + selectedIcon: selectedResource, symbolSelectedIconStyle: selectedSymbolResource, editIcon: editResource, + symbolEditIconStyle: editSymbolResource, primaryTitle: "Directory 6", secondaryTitle: "0" }) + .addNode({ parentNodeId:32, currentNodeId: 35, isFolder: true, icon: normalResource, symbolIconStyle: normalSymbolResource, + selectedIcon: selectedResource, symbolSelectedIconStyle: selectedSymbolResource, editIcon: editResource, + symbolEditIconStyle: editSymbolResource, primaryTitle: "Directory 6-1", secondaryTitle: "0" }) + .addNode({ parentNodeId:-1, currentNodeId: 33, isFolder: true, icon: normalResource, symbolIconStyle: normalSymbolResource, + selectedIcon: selectedResource, symbolSelectedIconStyle: selectedSymbolResource, editIcon: editResource, + symbolEditIconStyle: editSymbolResource, primaryTitle: "Directory 7", secondaryTitle: "0" }) + .addNode({ parentNodeId:33, currentNodeId: 34, isFolder: false, primaryTitle: "Project 8" }) + .addNode({ parentNodeId:-1, currentNodeId: 36, isFolder: false, primaryTitle: "Project 9" }) + .buildDone(); + this.treeController.refreshNode (-1, "Parent", "Child"); + } + + build() { + Column(){ + SideBarContainer(SideBarContainerType.Embed) + { + TreeView({ treeController: this.treeController }) + Row() { + Divider().vertical(true).strokeWidth(2).color(0x000000).lineCap(LineCapStyle.Round) + Column({ space: 30 }) { + Text('ClickNodeId=' + this.clickNodeId).fontSize('16fp') + Button('Add', { type: ButtonType.Normal, stateEffect: true }) + .borderRadius(8).backgroundColor(0x317aff).width(90) + .onClick((event: ClickEvent) => { + this.treeController.addNode(); + }) + Button('Modify', { type: ButtonType.Normal, stateEffect: true }) + .borderRadius(8).backgroundColor(0x317aff).width(90) + .onClick((event: ClickEvent) => { + this.treeController.modifyNode(); + }) + Button('Remove', { type: ButtonType.Normal, stateEffect: true }) + .borderRadius(8).backgroundColor(0x317aff).width(120) + .onClick((event: ClickEvent) => { + this.treeController.removeNode(); + }) + }.height('100%').width('80%').alignItems(HorizontalAlign.Start).margin(10) + } + } + .focusable(true) + .showControlButton(false) + .showSideBar(true) + } + }} +``` + +![Example 2-Setting the Symbol Icon](figures/en-us_image_treeview_demo_02.png) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-formmenu.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-formmenu.md index e32c61d84060cab1a6bc3f67b9b17592edc39ab5..1961c836bbc07dc464e1f05ae8b1d0591576c86b 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-formmenu.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-arkui-advanced-formmenu.md @@ -28,7 +28,7 @@ import { AddFormMenuItem } from '@kit.ArkUI'; Not supported ## Attributes -The [universal attributes](ts-universal-attributes-size.md) are not supported. +The [universal attributes](ts-component-general-attributes.md) are not supported. ## AddFormMenuItem @@ -40,7 +40,7 @@ AddFormMenuItem( ): void -**Decorator**: @Component +**Decorator**: @Builder **Atomic service API**: This API can be used in atomic services since API version 12. @@ -48,11 +48,11 @@ AddFormMenuItem( **Parameters** -| Name | Type | Mandatory| Decorator| Description | -| -------------- | ------------------------------- | ---- | ---------- | ---------------------------------------------------------------- | -| want | [Want](../../apis-ability-kit/js-apis-app-ability-want.md#want) | Yes | \@Prop | Want information of the functional component. | -| componentId | string | Yes | - | In-application functional component ID, which corresponds to a UI similar to the UI of the service widget to add.| -| AddFormOptions| [AddFormOptions](#addformoptions) | No | - | Options for adding the service widget. | +| Name | Type | Mandatory| Description | +| -------------- | ------------------------------- | ---- | ---------------------------------------------------------------- | +| want | [Want](../../apis-ability-kit/js-apis-app-ability-want.md#want) | Yes | Want information of the functional component. | +| componentId | string | Yes | In-application functional component ID, which corresponds to a UI similar to the UI of the service widget to add.| +| options| [AddFormOptions](#addformoptions) | No | Options for adding the service widget. | ## AddFormOptions @@ -218,6 +218,6 @@ struct WidgetCard { **Result of using Add to home screen with the FormMenu component** -On the left is the result of using **Add to home screen** with **formbdingdata** empty, and on the right is the result with **formbdingdata** as **{ data: 'share' }**. +The figure below shows the results when **formbindingdata** is empty (left), and when it is set to **{ data: 'share' }** (right). ![en-us_image_0000001616959836](figures/en-us_image_add_form_to_desktop_result.jpeg) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-atomicservice-AtomicServiceNavigation.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-atomicservice-AtomicServiceNavigation.md index e771600f2c798ccfe271039abcb24a0ecb49b915..77976b2d9721cf28a808ed9ce887ca6c0bd08ef4 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-atomicservice-AtomicServiceNavigation.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-atomicservice-AtomicServiceNavigation.md @@ -23,13 +23,17 @@ AtomicServiceNavigation({ navPathStack?: NavPathStack, navigationContent: Callback, title?: ResourceStr, - titleBackgroundColor?: ResourceColor, + titleOptions?: TitleOptions, + gradientBackground?: GradientBackground, hideTitleBar?: boolean, navBarWidth?: Length, mode?: NavigationMode, navDestinationBuilder?: NavDestinationBuilder, navBarWidthRange?: [Dimension, Dimension], minContentWidth?: Dimension, + sideBarOptions?: sideBarOptions, + sideBarContent?: Callback, + menus?: CustomBuilder | Array, stateChangeCallback?: Callback, modeChangeCallback?: Callback }) @@ -49,17 +53,21 @@ AtomicServiceNavigation({ | navigationContent | Callback\ | No| @BuilderParam | Content of the navigation container.| | title | [ResourceStr](ts-types.md#resourcestr) | No|@Prop | Page title.| | titleOptions | [TitleOptions](#titleoptions) | No| @Prop | Title bar options.| +| gradientBackground18+ | [GradientBackground](#gradientbackground18) | No| @Prop | Background color options.| | hideTitleBar | boolean | No| @Prop | Whether to hide the title bar.| | navBarWidth | [Length](ts-types.md#length)| No| @Prop | Width of the navigation bar.
This attribute takes effect only when the component is split.| | mode| [NavigationMode](ts-basic-components-navigation.md#navigationmode9)| No| @Prop |Display mode of the navigation bar.
Available options are **Stack**, **Split**, and **Auto**.| | navDestinationBuilder | [NavDestinationBuilder](#navdestinationbuilder) | No| @BuilderParam | Builder data required for creating the [NavDestination](ts-basic-components-navdestination.md) component.| | navBarWidthRange | [[Dimension](ts-types.md#dimension10), [Dimension](ts-types.md#dimension10)] | No| @Prop |Minimum and maximum widths of the navigation bar (effective in dual-column mode).| | minContentWidth | [Dimension](ts-types.md#dimension10) | No| @Prop | Minimum width of the navigation bar content area (effective in dual-column mode).| +| sideBarOptions18+ | [SideBarOptions](#sidebaroptions18) | No| @Prop | Sidebar options.| +| sideBarContent18+ | Callback\ | No| @BuilderParam | Content of the sidebar.| +| menus18+ | [CustomBuilder](ts-types.md#custombuilder8) \| Array\<[NavigationMenuItem](ts-basic-components-navigation.md#navigationmenuitem)\> | No| @BuilderParam | Custom layouts for wide-screen scenarios. The default value is empty, with no styles displayed.| | stateChangeCallback | Callback\ | No| - | Callback invoked when the navigation bar visibility status changes.| | modeChangeCallback | Callback\<[NavigationMode](ts-basic-components-navigation.md#navigationmode9)\>| No| - | Callback invoked when the component is displayed for the first time or its display mode switches between single-column and dual-column.| ## TitleOptions - +Title bar options. **Atomic service API**: This API can be used in atomic services since API version 12. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -68,7 +76,24 @@ AtomicServiceNavigation({ | --------------- | ------ | ---- | ---------- | | backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | No| Background color of the title bar.| | isBlurEnabled | boolean | No| Whether the title bar is blurred.
Default value: **true**| -| barStyle | [BarStyle12+](ts-basic-components-navigation.md#barstyle12) | No| Style options of the title bar.| +| barStyle | [BarStyle](ts-basic-components-navigation.md#barstyle12) | No| Style options of the title bar.| +| titleBarType18+ | [TitleBarType](#titlebartype18) | No| Type of the title bar.
Default value: **TitleBarType.ROUND_ICON**| +| titleIcon18+ | [Resource](ts-types.md#resource) \| [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) | No| Icon of the title bar. Default value: **$r('sys.color.ohos_id_color_titlebar_icon')**| + +## GradientBackground18+ +Provides options for setting gradient colors for branding. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name| Type| Mandatory| Description| +| --------------- | ------ | ---- | ---------- | +| primaryColor | [ResourceColor](ts-types.md#resourcecolor) | Yes| Color value for single-color gradients and the first color in dual-color gradients.
No default value.| +| secondaryColor |[ResourceColor](ts-types.md#resourcecolor) | No|Second color in dual-color gradients.
No default value.| +| backgroundTheme |[BackgroundTheme18+](#backgroundtheme18) | No|Background theme of the navigation bar.
Default value: **DEFAULT**| +| mixMode | [MixMode18+](#mixmode18) | No|How the two colors blend in dual-color gradients. It is effective only when both **primaryColor** and **secondaryColor** are set.
Default value: **TOWARDS**| +| alpha | [GradientAlpha18+](#gradientalpha18) | No|Transparency level for the gradient display area.
Default value: **OPACITY_20**| ## NavDestinationBuilder @@ -83,12 +108,80 @@ type NavDestinationBuilder = (name: string, param?: Object) => void | name | string | Yes| Name of the [NavDestination](ts-basic-components-navdestination.md) page.| | param | Object | Yes| Settings of the [NavDestination](ts-basic-components-navdestination.md) page.| +## MixMode18+ +Provides options for background color blending modes. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name| Value| Description| +| --------------- | ------ |-----| +| AVERAGE | 1 | Both colors are evenly mixed. | +| CROSS | 2 | One color passes through the other.| +| TOWARDS | 3 | One color gradually blends into the other.| + +## TitleBarType18+ +Enumerates the title bar types. The default type is **ROUND_ICON**. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name| Value| Description| +| --------------- | ------ |-----| +| SQUARED_ICON | 1 | Square icon style.| +| ROUND_ICON | 2 | Round icon style.| +| DRAWER | 3 | Drawer style.| + +## GradientAlpha18+ +Enumerates the transparency levels of the navigation bar background. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name| Value| Description| +| --------------- | ------ |-----| +| OPACITY_20| 1 | Transparency level of 0.2.| +| OPACITY_60| 2 | Transparency level of 0.6.| +| OPACITY_80| 3 | Transparency level of 0.8.| +| OPACITY_100| 4 | Transparency level of 1.0.| + +## BackgroundTheme18+ +Enumerates the navigation bar background themes. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name| Value| Description| +| --------------- | ------ |-----| +| DARK | 1 | Dark theme.| +| LIGHT | 2 | Light theme.| +| DEFAULT | 3 | Light gray theme, with the color value of #F1F3F5.| + +## SideBarOptions18+ +Provides sidebar options. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name| Type| Mandatory| Description| +| --------------- | ------ | ---- | ---------- | +| sideBarBackground | [ResourceColor](ts-types.md#resourcecolor) | No| Background color of the sidebar.
Default value: **$r('sys.color.ohos_id_color_sub_background')**| +| onChange | Callback\ | No| Callback triggered when the sidebar is shown or hidden.| +| sideBarIcon | [Resource](ts-types.md#resource) \| [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) | No| Icon of the sidebar. Default value: **$r('sys.symbol.open_sidebar')**| + ## Example +### Example 1: Setting the Layout and Gradient Background +This example demonstrates how to set the basic style of the **AtomicServiceNavigation** component with a gradient background. + ```ts -// Index.ets import { AtomicServiceNavigation, NavDestinationBuilder, AtomicServiceTabs, TabBarOptions, TabBarPosition } from '@kit.ArkUI'; - +import { MixMode, GradientAlpha, BackgroundTheme} from '@ohos.atomicservice.AtomicServiceNavigation' @Entry @Component struct Index { @@ -163,9 +256,15 @@ struct Index { }, title: this.message, titleOptions: { - backgroundColor: 'rgb(61, 157, 180)', isBlurEnabled: false }, + gradientBackground: { + primaryColor: 'red', + secondaryColor: 'green', + backgroundTheme: BackgroundTheme.LIGHT, + mixMode: MixMode.AVERAGE, + alpha: GradientAlpha.OPACITY_100 + }, navDestinationBuilder: this.pageMap, navPathStack: this.childNavStack, mode: NavigationMode.Stack @@ -211,4 +310,297 @@ export struct PageTwo { } ``` -![](figures/AtomicServiceNavigationDemo01.png) +![](figures/AtomicServiceNavigationDemo02.jpg) + +### Example 2: Implementing the Drawer Style with Custom Layouts for Wide-Screen Scenarios + +This example demonstrates how to implement the drawer style and insert custom layouts into the title bar in wide-screen scenarios (width > 600 vp). + +```ts +import { AtomicServiceNavigation, TitleBarType } from '@kit.ArkUI'; +import { AtomicServiceTabs, TabBarOptions, TabBarPosition } from '@kit.ArkUI'; + +@Entry +@Component +struct Index { + @State message: string = 'Hello World'; + childNavStack: NavPathStack = new NavPathStack(); + + @Builder + tabContent1() { + Text('First page') + .onClick(() => { + this.childNavStack.pushPath({ name: 'page one' }) + }) + } + + @Builder + tabContent2() { + Text('Second page') + } + + @Builder + tabContent3() { + Text('Third page') + } + + @Builder + navigationContent() { + AtomicServiceTabs({ + tabContents: [ + () => { + this.tabContent1() + }, + () => { + this.tabContent2() + }, + () => { + this.tabContent3() + } + ], + tabBarOptionsArray: [ + new TabBarOptions($r('sys.media.ohos_ic_public_phone'), 'Feature 1'), + new TabBarOptions($r('sys.media.ohos_ic_public_location'), 'Feature 2', Color.Green, Color.Red), + new TabBarOptions($r('sys.media.ohos_ic_public_more'), 'Feature 3') + ], + tabBarPosition: TabBarPosition.BOTTOM, + barBackgroundColor: $r('sys.color.ohos_id_color_bottom_tab_bg'), + onTabBarClick: (index: Number) => { + if (index == 0) { + this.message = 'Feature 1'; + } else if (index == 1) { + this.message = 'Feature 2'; + } else { + this.message = 'Feature 3'; + } + } + }) + } + + @Builder + pageMap(name: string) { + if (name === 'page one') { + PageOne() + } else if (name === 'page two') { + PageTwo() + } + } + + @State showText: string = 'time: '; + @State time: number = 0; + + @Builder + insertComp() { + Text('This is the menu area') + .fontColor(Color.Red) + .width(200) + .height('100%') + } + + build() { + Column() { + AtomicServiceNavigation({ + navigationContent: () => { + this.navigationContent() + }, + navDestinationBuilder: this.pageMap, + navPathStack: this.childNavStack, + title: this.message, + titleOptions: { + titleIcon: $r('app.media.startIcon'), + backgroundColor: 'rgb(61, 157, 180)', + titleBarType: TitleBarType.DRAWER + }, + menus: () => { this.insertComp() }, + mode: NavigationMode.Stack + }) + } + .width('100%') + } +} + +@Component +export struct PageOne { + pageInfo: NavPathStack = new NavPathStack(); + + build() { + NavDestination() { + Button('Next') + .onClick(() => { + this.pageInfo.pushPath({ name: 'page two'}) + }) + } + .title('PageOne') + .onReady((context: NavDestinationContext) => { + this.pageInfo = context.pathStack; + }) + } +} + +@Component +export struct PageTwo { + pageInfo: NavPathStack = new NavPathStack(); + + build() { + NavDestination() { + Button('End') + } + .title('PageTwo') + .onReady((context: NavDestinationContext) => { + this.pageInfo = context.pathStack; + }) + } +} +``` +![](figures/AtomicServiceNavigationDemo03.png) + +### Example 3: Configuring the Sidebar + +This example demonstrates how to set the sidebar background color and content style. + +```ts +import { AtomicServiceNavigation, TitleBarType } from '@kit.ArkUI'; +import { AtomicServiceTabs, TabBarOptions, TabBarPosition } from '@kit.ArkUI'; + +@Entry +@Component +struct Index { + @State message: string = 'Hello World'; + childNavStack: NavPathStack = new NavPathStack(); + + @Builder + tabContent1() { + Text('first page') + .onClick(() => { + this.childNavStack.pushPath({ name: 'page one' }) + }) + } + + @Builder + tabContent2() { + Text('second page') + } + + @Builder + tabContent3() { + Text('third page') + } + + @Builder + navigationContent() { + AtomicServiceTabs({ + tabContents: [ + () => { + this.tabContent1() + }, + () => { + this.tabContent2() + }, + () => { + this.tabContent3() + } + ], + tabBarOptionsArray: [ + new TabBarOptions($r('sys.media.ohos_ic_public_phone'), 'Feature 1'), + new TabBarOptions($r('sys.media.ohos_ic_public_location'), 'Feature 2', Color.Green, Color.Red), + new TabBarOptions($r('sys.media.ohos_ic_public_more'), 'Feature 3') + ], + tabBarPosition: TabBarPosition.BOTTOM, + barBackgroundColor: $r('sys.color.ohos_id_color_bottom_tab_bg'), + onTabBarClick: (index: Number) => { + if (index == 0) { + this.message = 'Feature 1'; + } else if (index == 1) { + this.message = 'Feature 2'; + } else { + this.message = 'Feature 3'; + } + } + }) + } + + @Builder + pageMap(name: string) { + if (name === 'page one') { + PageOne() + } else if (name === 'page two') { + PageTwo() + } + } + + @State showText: string = 'time: '; + @State time: number = 0; + + @Builder + insertComp() { + Text('This is menus area') + .fontColor(Color.Red) + .width(200) + .height('100%') + } + + @Builder + sideBarContentBuilder() { + Text('This is sideBar content area') + .fontSize(20) + } + + build() { + Column() { + AtomicServiceNavigation({ + navigationContent: () => { + this.navigationContent() + }, + navDestinationBuilder: this.pageMap, + navPathStack: this.childNavStack, + title: this.message, + titleOptions: { + titleIcon: $r('app.media.startIcon'), + backgroundColor: 'rgb(61, 157, 180)', + titleBarType: TitleBarType.DRAWER + }, + sideBarOptions: { + sideBarBackground: '#409EFF' + }, + sideBarContent: () => { this.sideBarContentBuilder() }, + mode: NavigationMode.Stack + }) + } + .width('100%') + } +} + +@Component +export struct PageOne { + pageInfo: NavPathStack = new NavPathStack(); + + build() { + NavDestination() { + Button('Next') + .onClick(() => { + this.pageInfo.pushPath({ name: 'page two'}) + }) + } + .title('PageOne') + .onReady((context: NavDestinationContext) => { + this.pageInfo = context.pathStack; + }) + } +} + +@Component +export struct PageTwo { + pageInfo: NavPathStack = new NavPathStack(); + + build() { + NavDestination() { + Button('End') + } + .title('PageTwo') + .onReady((context: NavDestinationContext) => { + this.pageInfo = context.pathStack; + }) + } +} +``` +![](figures/AtomicServiceNavigationDemo04.png) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-atomicservice-AtomicServiceSearch.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-atomicservice-AtomicServiceSearch.md new file mode 100644 index 0000000000000000000000000000000000000000..76fc961f48e7d1ba48df5013fdd3e74ba33f0b76 --- /dev/null +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-atomicservice-AtomicServiceSearch.md @@ -0,0 +1,1044 @@ +# AtomicServiceSearch + +**AtomicServiceSearch** allows you to customize the default search area, customizable selection area, and function area (a maximum of two). + +> **NOTE** +> +> This component is supported since API version 18. Updates will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + +``` +import { AtomicServiceSearch } from '@kit.ArkUI'; +``` + + +## AtomicServiceSearch +```ts +AtomicServiceSearch({ + value?: ResourceStr, + placeholder?: ResourceStr, + controller?: SearchController, + select?: SelectParams, + search?: SearchParams, + operation?: OperationParams, +}) +``` + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**Decorator**: @Component + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Decorator| Description | +| ----------- | :--------------- | ---- | ---------- | ------------------------------------------------------------ | +| value | [ResourceStr](ts-types.md#resourcestr) | No| @Prop | Text input in the search text box. The default value is an empty string.| +| placeholder | [ResourceStr](ts-types.md#resourcestr) | No| @Prop | Default prompt text displayed in the search box. The default value is **Search**.| +| controller | [SearchController](ts-basic-components-search.md#searchcontroller) | No | - | Native **Search** component controller, which is used to set the position of the input cursor and exit the editing state. The default value is **undefined**.| +| select | [SelectParams](#selectparams) | No| @Prop | Content, event, and style of the selection area. The default value is **undefined**.| +| search | [SearchParams](#searchparams) | No| @Prop | Events and styles supported by the search area. The default value is **undefined**.| +| operation | [OperationParams](#operationparams) | No| - | Function setting items on the right of the selection area. The default value is **undefined**.| + + +## SelectParams + +Provides optional attributes for the selection area. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ----------------------- | -------------------------------------------- | ------------------------------------------------------------ | ---- | +| options | Array<[SelectOption](ts-basic-components-select.md#selectoption)> | No| Value of an option in the drop-down menu. The default value is **undefined**.| +| selected | number| No| Index of the initially selected item in the drop-down list box. The index of the first item is 0. If this attribute is not set, the default value **-1** is used, indicating that the option is not selected.| +| selectValue | [ResourceStr](ts-types.md#resourcestr) | No| Text content of the drop-down list button itself. The default value is **undefined**.| +| onSelect | [OnSelectCallback](#onselectcallback) | No| Callback invoked when an item in the drop-down list box is selected. The default value is **undefined**.| +| menuItemContentModifier | [ContentModifier\](ts-basic-components-select.md#menuitemconfiguration12)| No| Content modifier to apply to the drop-down list box.
**modifier**: content modifier. You need a custom class to implement the **ContentModifier** API. The default value is **undefined**.| +| divider | [Optional](ts-universal-attributes-custom-property.md#optional12)<[DividerOptions](ts-basic-components-textpicker.md#divideroptions12)> \| null | No| Divider options.
1. If **DividerOptions** is set, the divider is displayed in the configured style. Default value: **{strokeWidth: '1px', color: '#33182431'}**
2. If this parameter is set to **null**, the divider is not displayed.
3. If the value of **strokeWidth** is too larger, the divider may overlap the text. The divider extends both upwards and downwards from the bottom of each item.
4. The default values for **startMargin** and **endMargin** are consistent with the style of the divider when the **divider** attribute is not set. If the sum of **startMargin** and **endMargin** is equal to the value of **optionWidth**, the divider is not displayed. If the sum of **startMargin** and **endMargin** exceeds the value of **optionWidth**, the divider line is displayed in the default style.| +| font | [Font](ts-types.md#font) | No| Text font of the drop-down list button. Default value: **{size: $r('sys.float.ohos_id_text_size_body1')}**| +| fontColor | [ResourceColor](ts-types.md#resourcecolor) | No| Font color of the selected option in the drop-down list box. Default value: **{fontColor: $r('sys.color.ohos_id_color_text_primary')}** | +| selectedOptionBgColor | [ResourceColor](ts-types.md#resourcecolor) | No| Background color of the selected option in the drop-down list box. Default value: **$r('sys.color.ohos_id_color_component_activated')** with the opacity of **$r('sys.color.ohos_id_alpha_highlight_bg')**| +| selectedOptionFont | [Font](ts-types.md#font) | No| Text font of the selected option in the drop-down list box. Default value: **{size: $r('sys.color.ohos_id_text_size_body1'), weight: FontWeight.Regular}**| +| selectedOptionFontColor | [ResourceColor](ts-types.md#resourcecolor) | No| Font color of the selected option in the drop-down list box. Default value: **$r('sys.color.ohos_id_color_text_primary_activated')**| +| optionBgColor | [ResourceColor](ts-types.md#resourcecolor) | No| Background color of an option in the drop-down list box. Default value: **Color.Transparent**| +| optionFont | [Font](ts-types.md#font) | No| Text font of options in the drop-down list box. Default value: **{size: $r('sys.float.ohos_id_text_size_body1'), weight: FontWeight.Regular}**| +| optionFontColor | [ResourceColor](ts-types.md#resourcecolor) | No| Font color of an option in the drop-down list box. Default value: **$r('sys.color.ohos_id_color_text_primary')**| +| optionWidth | [Dimension](ts-types.md#dimension10) \| [OptionWidthMode](ts-appendix-enums.md#optionwidthmode11) | No| Option width in the drop-down list box. This attribute cannot be set in percentage. **OptionWidthMode** is of the enum type and it determines whether the drop-down list box inherits the width of the drop-down list button. If an invalid value or a value less than the minimum width of 56 vp is set, the attribute does not take effect, and the option width uses the default value, which is two columns.| +| optionHeight | [Dimension](ts-types.md#dimension10) | No| Maximum height for the option in the drop-down list box. This attribute cannot be set in percentage. The default maximum height is 80% of the available height of the screen. The maximum height set cannot exceed the default maximum height.| +| space | [Length](ts-types.md#length) | No| Spacing between the text and arrow of an option. Default value: **8**| +| arrowPosition | [ArrowPosition](ts-basic-components-select.md#arrowposition10)| No| Alignment between the text and arrow of an option. Default value: **ArrowPosition.END**| +| menuAlign | [MenuAlignParams](#menualignparams) | No| Alignment between the drop-down list button and the drop-down list box. Default value: **{alignType: MenuAlignType.START, offset: {dx: 0, dy: 0}}**| +| menuBackgroundColor | [ResourceColor](ts-types.md#resourcecolor) | No| Background color of the drop-down list box. Default value: **Color.Transparent** | +| menuBackgroundBlurStyle | [BlurStyle](ts-universal-attributes-background.md#blurstyle9) | No| Background blur style of the drop-down list box. Default value: **BlurStyle.COMPONENT_ULTRA_THICK**| + + +## SearchParams + +Sets optional attributes for the search area. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ------------------------ | ---------------------------------------------- | ------------------------------------------------------------ | ---- | +| searchKey | [ResourceStr](ts-types.md#resourcestr) | No| Search key used to find a unique **search** component. Default value: **undefined** | +| componentBackgroundColor | [ResourceColor](ts-types.md#resourcecolor) | No| Background color of a component. Default value: **$r('sys.color.ohos_id_color_text_field_sub_bg')** | +| pressedBackgroundColor | [ResourceColor](ts-types.md#resourcecolor) | No| Background color of the pressed component. Default value: **$r('sys.color.ohos_id_color_click_effect')**| +| searchButton | [SearchButtonParams](#searchbuttonparams) | No| Search button located next to the search text box. Clicking the search button triggers both **onSubmit** and **onClick** callbacks.
- **value**: Text on the search button located next to the search text box.
- **option**: Font of the search text box. Default value: **{fontSize: '16fp', fontColor: '#ff3f97e9'}**| +| placeholderColor | [ResourceColor](ts-types.md#resourcecolor) | No| Placeholder text color. Default value: **$r('sys.color.ohos_id_color_text_secondary')** | +| placeholderFont | [Font](ts-types.md#font) | No| Placeholder text style, including the font size, font weight, font family, and font style. Default value: **{size: $r('sys_float.ohos_id_text_size_body1')}**| +| textFont | [Font](ts-types.md#font) | No| Style of the text entered in the search box, including the font size, font width, font family, and font style. Currently, only the default font family is supported. Default value: **{size: $r('sys_float.ohos_id_text_size_body1')}**| +| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | No| Text alignment mode in the search text box. Default value: **TextAlign.Start** | +| copyOptions | [CopyOptions](ts-appendix-enums.md#copyoptions9) | No| Whether copy and paste is allowed. Default value: **CopyOptions.LocalDevice** | +| searchIcon | [IconOptions](ts-basic-components-search.md#iconoptions10) \| [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) | No| Style of the search icon on the left.
Default value in light mode: **{size: '16vp', color: '#99182431', src:' '}**
Default value in dark mode: **{size: '16vp', color: '#99ffffff', src:' '}** | +| cancelIcon | [IconOptions](ts-basic-components-search.md#iconoptions10)| No| Style of the cancel button on the right. Default value: **{style: CancelButtonStyle.INPUT, icon: {size: '16vp', color: '#99ffffff', src:' '}}**
When style is set to **CancelButtonStyle.CONSTANT**, the cancel button is displayed in a default style. | +| fontColor | [ResourceColor](ts-types.md#resourcecolor) | No| Font color of the input text. Default value: **$r('sys.color.ohos_id_color_text_secondary')**| +| caretStyle | [CaretStyle](ts-text-common.md#caretstyle10) | No| Pointer style. Default value: **{width: '1.5vp', color: '#007DFF'}** | +| enableKeyboardOnFocus | boolean | No| Whether to enable the input method when the **search** component obtains focus in a way other than clicking. Default value: **true** | +| hideSelectionMenu | boolean | No| Whether to hide the system text selection menu.
**true**: The system text selection menu does not appear under the following circumstances: clicking the text box cursor, long-pressing the text box, double-tapping the text box, triple-tapping the text box, or right-clicking the text box. **false**: The system text selection menu appears under the following circumstances: clicking the text box cursor, long-pressing the text box, double-tapping the text box, triple-tapping the text box, or right-clicking the text box. Default value: **false** | +| type | [SearchType](ts-basic-components-search.md#searchtype11)| No| Text box type. Default value: **SearchType.Normal** | +| maxLength | number | No| Maximum number of characters in the text input. By default, there is no maximum number of characters. When the maximum number is reached, no more characters can be entered. Default value: **-1** | +| enterKeyType | [EnterKeyType](ts-basic-components-textinput.md#enterkeytype)| No| Type of the Enter key. Default value: **EnterKeyType.Search** | +| decoration | [TextDecorationOptions](ts-types.md#textdecorationoptions12)| No| Text decorative line options. Default value: **{type: TextDecorationType.None, color: Color.Black, style: TextDecorationStyle.SOLID}** | +| letterSpacing | number \| string \| [Resource](ts-types.md#resource) | No| Letter spacing. If the value specified is a percentage or **0**, the default value is used. If the value specified is a negative value, the text is compressed. A negative value too small may result in the text being compressed to 0 and no content being displayed. Default value: **0** | +| fontFeature | [ResourceStr](ts-types.md#resourcestr) | No| Font feature, for example, monospaced digits.
Format: normal \| \
Syntax for \: \ \[ \ \| on \| off ]
There can be multiple **\** values, which are separated by commas (,).
For example, the input format for monospaced digits is "ss01" on. The default value is **undefined**. | +| selectedBackgroundColor | [ResourceColor](ts-types.md#resourcecolor) | No| Background color of the selected text. By default, a 20% opacity is applied.| +| inputFilter | [InputFilterParams](#inputfilterparams) | No| Regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are filtered out. The specified regular expression can match single characters, but not strings. The default value is **undefined**.
- **value**: regular expression.
- **error**: Filtered-out content to return when regular expression matching fails.| +| textIndent | [Dimension](ts-types.md#dimension10) | No| Indent of the first line text. Default value: **0** | +| minFontSize | number \| string \| [Resource](ts-types.md#resource) | No| Minimum font size. For the setting to take effect, this attribute must be used together with **maxFontSize** or layout constraint settings. The default value is **undefined**. | +| maxFontSize | number \| string \| [Resource](ts-types.md#resource) | No| Maximum font size. For the setting to take effect, this attribute must be used together with **minFontSize** or layout constraint settings. The default value is **undefined**. | +| editMenuOptions | [EditMenuOptions](ts-text-common.md#editmenuoptions) | No| Extended options of the custom context menu on selection, including the text content, icon, and callback. The default value is **undefined**. | +| enablePreviewText | boolean | No| Whether to enable preview text. Default value: **true**
Preview text of the input method should be enabled. Preview text is in a temporary state and does not support text interception. As such, it does not trigger **onWillInsert** and **onDidInsert** callbacks. | +| enableHapticFeedback | boolean | No| Whether to enable haptic feedback. Default value: **true** | +| onSubmit | Callback<string> \| [SearchSubmitCallback](ts-basic-components-search.md#searchsubmitcallback14) | No| Callback triggered when users click the search icon or the search button, or touch the search button on a soft keyboard. The default value is **undefined**. | +| onChange | [EditableTextOnChangeCallback](ts-text-common.md#editabletextonchangecallback12) | No| Callback triggered when the content in the text box changes. The default value is **undefined**. | +| onCopy | Callback<string> | No| Callback triggered when a copy operation is performed. The default value is **undefined**. | +| onCut | Callback<string> | No| Callback triggered when a cut operation is performed. The default value is **undefined**. | +| onPaste | [OnPasteCallback](#onpastecallback) | No| Callback triggered when a paste operation is performed. The default value is **undefined**. | +| onTextSelectionChange | [OnTextSelectionChangeCallback](#ontextselectionchangecallback) | No| Callback triggered when the position of the text selection changes or when the cursor position changes during the editing state. The default value is **undefined**. | +| onContentScroll | [OnContentScrollCallback](#oncontentscrollcallback) | No| Callback triggered when the text content is scrolled. The default value is **undefined**. | +| onEditChange | Callback<boolean> | No| Callback triggered when the input status changes. If a cursor is displayed, that is, the value of **isEditing** is **true**, the text box is in the editing state. The default value is **undefined**. | +| onWillInsert | Callback<InsertValue, boolean> | No| Callback triggered when text is about to be inserted. The default value is **undefined**. | +| onDidInsert | Callback<InsertValue> | No| Callback triggered when text is inserted. The default value is **undefined**. | +| onWillDelete | Callback<DeleteValue, boolean> | No| Callback triggered when text is about to be deleted. The default value is **undefined**. | +| onDidDelete | Callback<DeleteValue> | No| Callback triggered when text is deleted. The default value is **undefined**. | + + +## OperationParams + +Sets initialization parameters of the function area. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ------------- | --------------- | ---------------------------- | ---- | +| auxiliaryItem | [OperationOption ](ohos-arkui-advanced-SubHeader.md#operationoption)| No| Auxiliary item on the right of the search area. The default value is **undefined**.| +| independentItem | [OperationOption ](ohos-arkui-advanced-SubHeader.md#operationoption)| No| Independent item on the right of the search area. The default value is **undefined**.| + + +## InputFilterParams + +Sets regular expression for input filtering. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Description | +| ---------------- | ---------------- | ---- | ---------------------------------- | +| inputFilterValue | [ResourceStr](ts-types.md#resourcestr) | Yes| Regular expression.| +| error | Callback<string> | No| Callback used to return the filtered-out content when regular expression matching fails. The default value is **undefined**.| + +## SearchButtonParams + +Sets the search button located next to the search text box. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Description | +| ----------------- | ------------------- | ---- | ------------------------------------------------------------ | +| searchButtonValue | [ResourceStr](ts-types.md#resourcestr) | Yes | Text on the search button located next to the search text box.| +| options | [SearchButtonOptions](ts-basic-components-search.md#searchbuttonoptions10)| No | Font of the search text box. Default value: **{fontSize: '16fp',fontColor: '#ff3f97e9'}**| + + +## MenuAlignParams + +Sets the alignment between the drop-down list button and the drop-down list box. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Description | +| --------- | ------------- | ---- | ------------------------------------------------------------ | +| alignType | [MenuAlignType](ts-basic-components-select.md#menualigntype10)| Yes| Alignment type. Default value: **MenuAlignType.START**| +| offset | [Offset](ts-types.md#offset) | No| Offset of the drop-down list box relative to the drop-down list button after alignment based on the alignment type. Default value: **{dx: 0, dy: 0}**| + + +## OnSelectCallback + +type OnSelectCallback = (index: number, selectValue: string) => void + +Called when an item in the drop-down list box is selected. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------------------- | +| index | number | Yes| Index of the selected option.| +| selectValue | string | Yes| Value of the selected option.| + + +## OnPasteCallback + +type OnPasteCallback = (pasteValue: string, event: PasteEvent) => void + +Called when a paste operation is performed. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------------------- | +| pasteValue | string | Yes| Text to be pasted.| +| event | [PasteEvent](ts-basic-components-richeditor.md#pasteevent) | Yes| Custom paste event.| + + +## OnTextSelectionChangeCallback + +type OnTextSelectionChangeCallback = (selectionStart: number, selectionEnd: number) => void + +Called when the position of the text selection changes or when the cursor position changes during the editing state. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------------------- | +| selectionStart | number | Yes| Start position of the text to be selected.| +| selectionEnd | number | Yes| End position of the text to be selected.| + + +## OnContentScrollCallback + +type OnContentScrollCallback = (totalOffsetX: number, totalOffsetY: number) => void + +Called when the text content is scrolled. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------------------- | +| totalOffsetX | number | Yes| X coordinate offset of the text in the content area.| +| totalOffsetY | number | Yes| Y coordinate offset of the text in the content area.| + + +## Examples + +### Example 1: Adding a Selection Area to AtomicServiceSearch +This example demonstrates how to use the **select** parameter to add a selection area on the left to the **AtomicServiceSearch** component. + +```ts +import { AtomicServiceSearch } from '@kit.ArkUI'; + +@Entry +@Component +struct Index { + build() { + Column({ space: 6 }) { + Text('AtomicServiceSearch + selection area').alignSelf(ItemAlign.Start).decoration({ + type: TextDecorationType.Underline, + color: Color.Black, + style: TextDecorationStyle.SOLID + }).margin({top:20, bottom: 20}) + + AtomicServiceSearch({ + select: { + options: [ + { value: 'Select1', icon: $r("app.media.sweep") }, // Custom resource + { value: 'Select2', icon: $r("app.media.sweep") }, // Custom resource + { value: 'Select3', icon: $r("app.media.sweep") }, // Custom resource + { value: 'Select4', icon: $r("app.media.sweep") } // Custom resource + ], + selected: -1, + selectValue: 'Select1', + onSelect: (index: number, selectValue: string) => { // Custom event + if (index === 0) { + this.alert(`index: ${index}, selectValue: ${selectValue}`); + } else if (index === 1) { + this.alert(`index: ${index}, selectValue: ${selectValue}`); + } else if (index === 2) { + this.alert(`index: ${index}, selectValue: ${selectValue}`); + } else if (index === 3) { + this.alert(`index: ${index}, selectValue: ${selectValue}`); + } + }, + } + }) + }.padding({ left: 16, right: 16 }) + } + + private alert(message: string): void { + AlertDialog.show({ + message: message + }) + } +} +``` + +![](figures/AtomicServiceSearchDemo01.gif) + + + +### Example 2: Adding a Function Item to AtomicServiceSearch +This example demonstrates how to use the **operation** parameter to add a function item on the right to the **AtomicServiceSearch** component. + +```ts +import { AtomicServiceSearch } from '@kit.ArkUI'; + +@Entry +@Component +struct Index { + build() { + Column({ space: 6 }) { + Text('AtomicServiceSearch + function items').alignSelf(ItemAlign.Start).decoration({ + type: TextDecorationType.Underline, + color: Color.Black, + style: TextDecorationStyle.SOLID + }).margin({top:20, bottom: 20}) + + AtomicServiceSearch({ + operation: { + // Auxiliary item of the Search component. + auxiliaryItem: { + value: $r("app.media.sweep"), // Custom resource + action: () => { + this.alert('Scan'); // Custom event + } + }, + // Independent item of the Search component. + independentItem: { + value: $r("app.media.dingding"), // Custom resource + action: () => { + this.alert('Notifications'); // Custom event + } + } + } + }) + }.padding({ left: 16, right: 16 }) + } + + private alert(message: string): void { + AlertDialog.show({ + message: message + }) + } +} +``` + +![](figures/AtomicServiceSearchDemo02.gif) + + + +### Example 3: Adding a Selection Area and Function Item to AtomicServiceSearch +This example demonstrates how to add the selection area and function items on the left and right to the AtomicServiceSearch component. + +```ts +import { AtomicServiceSearch } from '@kit.ArkUI'; + +@Entry +@Component +struct Index { + build() { + Column({ space: 6 }) { + Text('AtomicServiceSearch + selection area + function items').alignSelf(ItemAlign.Start).decoration({ + type: TextDecorationType.Underline, + color: Color.Black, + style: TextDecorationStyle.SOLID + }).margin({top:20, bottom: 20}) + + AtomicServiceSearch({ + select: { + options: [ + { value: 'Select1', icon: $r("app.media.sweep") }, // Custom resource + { value: 'Select2', icon: $r("app.media.sweep") }, // Custom resource + { value: 'Select3', icon: $r("app.media.sweep") }, // Custom resource + { value: 'Select4', icon: $r("app.media.sweep") } // Custom resource + ], + selected: -1, + selectValue: 'Select1', + onSelect: (index: number, selectValue:string) => { + if (index === 0) { + this.alert(`index: ${index}, selectValue: ${selectValue}`); + } else if (index === 1) { + this.alert(`index: ${index}, selectValue: ${selectValue}`); + } else if (index === 2) { + this.alert(`index: ${index}, selectValue: ${selectValue}`); + } else if (index === 3) { + this.alert(`index: ${index}, selectValue: ${selectValue}`); + } + }, + }, + operation: { + auxiliaryItem: { + value: $r("app.media.sweep"), // Custom resource + action: () => { + this.alert('Scan'); // Custom event + } + }, + independentItem: { + value: $r("app.media.dingding"), // Custom resource + action: () => { + this.alert('Notifications'); // Custom event + } + } + } + }) + }.padding({ left: 16, right: 16 }) + } + + private alert(message: string): void { + AlertDialog.show({ + message: message + }) + } +} +``` + +![](figures/AtomicServiceSearchDemo03.gif) + + + +### Example 4: Binding the Search Callback Events to AtomicServiceSearch +This example demonstrates how to use the **onWillInsert**, **onDidInsert**, **onWillDelete**, and **onDidDelete** APIs to implement insert and delete operations. +The **onSubmit** API is used to submit content in the search area. +The **onChange** API is used to listen for the content changes in the search area. + +```ts +import { AtomicServiceSearch } from '@kit.ArkUI'; + +@Entry +@Component +struct Index { + @State insertValue: string = ""; + @State deleteValue: string = ""; + @State insertOffset: number = 0; + @State deleteOffset: number = 0; + @State deleteDirection: number = 0; + @State startIndex: number = 0; + @State endIndex: number = 0; + @State offsetX: number = 0; + @State offsetY: number = 0; + @State changeValue: string = ''; + @State value: string = 'false'; + @State submitValue: string = ''; + @State text: string = 'Search editMenuOptions'; + + build() { + Column({ space: 6 }) { + Text('Binding events to AtomicServiceSearch').alignSelf(ItemAlign.Start).decoration({ + type: TextDecorationType.Underline, + color: Color.Black, + style: TextDecorationStyle.SOLID + }).margin({top:20, bottom: 20}) + + Column({ space: 6 }) { + Text('editing: ' + this.value).width('100%').height(25).borderRadius(15).padding({ left: 15 }) + .backgroundColor('rgba(0, 0, 0, 0.1)').maxLines(1).textOverflow({ overflow: TextOverflow.MARQUEE }); + Text('onSubmit:' + this.submitValue).width('100%').height(25).borderRadius(15).padding({ left: 15 }) + .backgroundColor('rgba(0, 0, 0, 0.1)').maxLines(1).textOverflow({ overflow: TextOverflow.MARQUEE }); + Text('onChange:' + this.changeValue).width('100%').height(25).borderRadius(15).padding({ left: 15 }) + .backgroundColor('rgba(0, 0, 0, 0.1)').maxLines(1).textOverflow({ overflow: TextOverflow.MARQUEE }); + Text('offset x:' + this.offsetX + ' y:' + this.offsetY).width('100%').height(25).borderRadius(15).padding({ left: 15 }) + .backgroundColor('rgba(0, 0, 0, 0.1)').maxLines(1).textOverflow({ overflow: TextOverflow.MARQUEE }); + Text("insertValue:" + this.insertValue + " insertOffset:" + this.insertOffset).width('100%').height(25) + .borderRadius(15).padding({ left: 15 }).backgroundColor('rgba(0, 0, 0, 0.1)').maxLines(1) + .textOverflow({ overflow: TextOverflow.MARQUEE }); + Text("deleteValue:" + this.deleteValue + " deleteOffset:" + this.deleteOffset).width('100%').height(25) + .borderRadius(15).padding({ left: 15 }).backgroundColor('rgba(0, 0, 0, 0.1)').maxLines(1) + .textOverflow({ overflow: TextOverflow.MARQUEE }); + Text("deleteDirection:" + (this.deleteDirection == 0 ? "BACKWARD" : "FORWARD")).width('100%').height(25) + .borderRadius(15).padding({ left: 15 }).backgroundColor('rgba(0, 0, 0, 0.1)').maxLines(1) + .textOverflow({ overflow: TextOverflow.MARQUEE }); + AtomicServiceSearch({ + select: { + options: [ + { value: 'Select1', icon: $r("app.media.sweep") }, + { value: 'Select2', icon: $r("app.media.sweep") }, + { value: 'Select3', icon: $r("app.media.sweep") }, + { value: 'Select4', icon: $r("app.media.sweep") } + ], + selected: -1, + selectValue: 'Select1', + onSelect: (index: number) => { + if (index === 0) { + this.alert('Select1'); + } else if (index === 1) { + this.alert('Select2'); + } else if (index === 2) { + this.alert('Select3'); + } else if (index === 3) { + this.alert('Select4'); + } + }, + }, + search: { + onSubmit: (value: string) => { + this.submitValue = value + }, + onChange: (value: string) => { + this.changeValue = value + }, + onCopy: () => { + this.alert('onCopy'); + }, + onCut: () => { + this.alert('onCut'); + }, + onPaste: () => { + this.alert('onPaste'); + }, + onTextSelectionChange: (selectionStart: number, selectionEnd: number) => { + this.startIndex = selectionStart + this.endIndex = selectionEnd + }, + onContentScroll: (totalOffsetX: number, totalOffsetY: number) => { + this.offsetX = totalOffsetX + this.offsetY = totalOffsetY + }, + onEditChange: (data: boolean) => { + this.value = data ? 'true' : 'false' + }, + onWillInsert: (info: InsertValue) => { + this.insertValue = info.insertValue + return true; + }, + onDidInsert: (info: InsertValue) => { + this.insertOffset = info.insertOffset + }, + onWillDelete: (info: DeleteValue) => { + this.deleteValue = info.deleteValue + info.direction + return true; + }, + onDidDelete: (info: DeleteValue) => { + this.deleteOffset = info.deleteOffset + this.deleteDirection = info.direction + } + } + }) + } + }.padding({ left: 16, right: 16 }) + } + + private alert(message: string): void { + AlertDialog.show({ + message: message + }) + } +} +``` + +![](figures/AtomicServiceSearchDemo04.gif) + + +### Example 5: Customizing the Style of AtomicServiceSearch +This example demonstrates how to use the **search**, **select**, **value**, and **placeholder** parameters to customize the style of the **AtomicServiceSearch** component. + +```ts +import { AtomicServiceSearch } from '@kit.ArkUI'; + +@Entry +@Component +struct Index { + @State private placeholder: string = 'Type to Search...'; + @State private defaultValue: string = 'default'; + @State private search?: SearchParams = {}; + @State private select?: SelectParams = { + options: [ + { value: 'Select1', icon: $r("app.media.sweep") }, + { value: 'Select2', icon: $r("app.media.sweep") }, + { value: 'Select3', icon: $r("app.media.sweep") }, + { value: 'Select4', icon: $r("app.media.sweep") } + ], + selected: -1, + selectValue: 'Select1', + onSelect: (index: number) => { + if (index === 0) { + this.alert('Select1'); + } else if (index === 1) { + this.alert('Select2'); + } else if (index === 2) { + this.alert('Select3'); + } else if (index === 3) { + this.alert('Select4'); + } + } + }; + + build() { + Column({ space: 8 }) { + Text('Customizing styles').alignSelf(ItemAlign.Start).decoration({ + type: TextDecorationType.Underline, + color: Color.Black, + style: TextDecorationStyle.SOLID + }).margin({ top: 20, bottom: 20 }) + + AtomicServiceSearch({ + value: this.defaultValue, + placeholder: this.placeholder, + select: this.select, + search: this.search, + operation: { + independentItem: { + value: $r(`app.media.dingding`), + action: () => { + this.alert('Notification'); + } + } + } + }) + Button("Change placeholder") + .width('100%') + .type(ButtonType.Normal) + .borderRadius(20) + .onClick(() => { + if (this.placeholder === 'Search...') { + this.placeholder = 'Type to Search...'; + } else { + this.placeholder = 'Search...'; + } + }); + Button("Change defaultValue") + .width('100%') + .type(ButtonType.Normal) + .borderRadius(20) + .onClick(() => { + if (this.defaultValue === 'value') { + this.defaultValue = 'defaultValue'; + } else { + this.defaultValue = 'value'; + } + }); + Button("Change selection area style") + .width('100%') + .type(ButtonType.Normal) + .borderRadius(20) + .onClick(() => { + this.select = { + options: [ + { value: 'Option 1', icon: $r("app.media.dingding") }, + { value: 'Option 2', icon: $r("app.media.dingding") }, + ], + selected: -1, + selectValue: 'Option 1', + onSelect: (index: number) => { + if (index === 0) { + this.alert('Option 1'); + } else if (index === 1) { + this.alert('Option 2'); + } + } + }; + }); + + Button("Change search area style") + .width('100%') + .type(ButtonType.Normal) + .borderRadius(20) + .onClick(() => { + this.search = { + componentBackgroundColor: '#e0eee8' + } + }); + }.padding({ left: 16, right: 16 }) + } + + private alert(message: string): void { + AlertDialog.show({ + message: message + }) + } +} +``` + +![](figures/AtomicServiceSearchDemo05.gif) + + + + +### Example 6: Setting the Caret Position Using controller +This example demonstrates how to use the **controller** parameter to set the caret position, select the content in the specified area, and disable the editing state. + + +```ts +import { AtomicServiceSearch } from '@kit.ArkUI'; + +@Entry +@Component +struct Index { + controller: SearchController = new SearchController(); + + build() { + Column({ space : 10 }) { + Text('Setting the caret position using controller').alignSelf(ItemAlign.Start).decoration({ + type: TextDecorationType.Underline, + color: Color.Black, + style: TextDecorationStyle.SOLID + }).margin({top:20, bottom: 20}) + + AtomicServiceSearch( + { + value: 'Default Value', + placeholder: 'Type to Search...', + controller: this.controller, + search: { + searchButton: { + searchButtonValue: 'SEARCH', + options: { fontSize: '12fp', fontColor: '#ff0e1216' } + } + } + }, + ); + Button('caretPosition to 1').onClick(() => { + this.controller.caretPosition(1); + }).width('100%') + Button('stopEditing').onClick(() => { + this.controller.stopEditing(); + }).width('100%') + Button('Selection [0,3]').onClick(() => { + this.controller.setTextSelection(0, 3) + }).width('100%') + }.padding({ left: 16, right: 16 }) + } + + public alert(message: string): void { + AlertDialog.show({ + message: message, + }) + } +} +``` + +![](figures/AtomicServiceSearchDemo06.gif) + + + + +### Example 7: Setting the Enter Key Type +This example demonstrates how to use the **enterKeyType** attribute to dynamically change the effect of the Enter key on the soft keyboard. + +```ts +import { AtomicServiceSearch } from '@kit.ArkUI'; + +@Entry +@Component +struct Index { + @State enterTypes: Array = [EnterKeyType.Go, EnterKeyType.Search, EnterKeyType.Send, EnterKeyType.Done, EnterKeyType.Next, EnterKeyType.PREVIOUS, EnterKeyType.NEW_LINE] + @State index: number = 0 + + build() { + Column({ space : 10 }) { + Text('Enter key type as search').alignSelf(ItemAlign.Start).decoration({ + type: TextDecorationType.Underline, + color: Color.Black, + style: TextDecorationStyle.SOLID + }).margin({top:20, bottom: 20}) + + AtomicServiceSearch({ + placeholder: 'Enter key type as search', + search: { + enterKeyType: this.enterTypes[this.index] + } + }) + + Button('Change EnterKeyType').onClick(() => { + this.index = (this.index + 1) % this.enterTypes.length; + }).width('100%') + + }.padding({ left: 16, right: 16 }) + } + + public alert(message: string): void { + AlertDialog.show({ + message: message, + }) + } +} +``` + +![](figures/AtomicServiceSearchDemo07.gif) + + + +### Example 8: Setting Text Feature Effects +This example demonstrates how to use the **fontFeature** attribute to display text with various typographic features. + +```ts +import { AtomicServiceSearch } from '@kit.ArkUI'; + +@Entry +@Component +struct Index { + build() { + Column({ space : 10 }) { + Text('Setting text feature effects').alignSelf(ItemAlign.Start).decoration({ + type: TextDecorationType.Underline, + color: Color.Black, + style: TextDecorationStyle.SOLID + }).margin({top:20, bottom: 20}) + + AtomicServiceSearch({ + value: 'This is ss01 on : 0123456789', + search: { + fontFeature: "\"ss012\" on" + } + }); + + AtomicServiceSearch({ + value: 'This is ss01 off : 0123456789', + search: { + fontFeature: "\"ss01\" off" + } + }); + }.padding({ left: 16, right: 16 }) + } + + public alert(message: string): void { + AlertDialog.show({ + message: message, + }) + } +} +``` + +![](figures/AtomicServiceSearchDemo08.png) + + + +### Example 9: Setting Text Auto-Adaptation +This example demonstrates how to use the **minFontSize** and **maxFontSize** attributes to implement the text auto-adaptation features. + +```ts +import { AtomicServiceSearch } from '@kit.ArkUI'; + +@Entry +@Component +struct Index { + build() { + Column({ space : 10 }) { + Text('Setting text auto-adaptation').alignSelf(ItemAlign.Start).decoration({ + type: TextDecorationType.Underline, + color: Color.Black, + style: TextDecorationStyle.SOLID + }).margin({top:20, bottom: 20}) + + AtomicServiceSearch({ + value: 'This is the text without the adaptive font', + }).width('80%').height(40).borderWidth(1).borderRadius(20) + + AtomicServiceSearch({ + value: 'This is the text without the adaptive font', + search: { + minFontSize: 4, + maxFontSize: 40 + } + }).width('80%').height(40).borderWidth(1).borderRadius(20) + }.padding({ left: 16, right: 16 }) + } + + public alert(message: string): void { + AlertDialog.show({ + message: message, + }) + } +} +``` + +![](figures/AtomicServiceSearchDemo09.png) + + + +### Example 10: Setting Custom Menu Extensions +This example demonstrates how to use the **editMenuOptions** API to create custom menu extensions for text settings. It includes customizing text content, icons, and callbacks for these extensions. + +```ts +import { AtomicServiceSearch } from '@kit.ArkUI'; + +@Entry +@Component +struct Index { + onCreateMenu = (menuItems: Array) => { + let item1: TextMenuItem = { + content: 'custom1', + icon: $r('app.media.startIcon'), + id: TextMenuItemId.of('custom1'), + } + let item2: TextMenuItem = { + content: 'custom2', + id: TextMenuItemId.of('custom2'), + icon: $r('app.media.startIcon'), + } + menuItems.push(item1) + menuItems.unshift(item2) + return menuItems + } + + onMenuItemClick = (menuItem: TextMenuItem, textRange: TextRange) => { + if (menuItem.id.equals(TextMenuItemId.of("custom2"))) { + console.log("Intercept id: custom2 start:" + textRange.start + "; end:" + textRange.end) + return true + } + if (menuItem.id.equals(TextMenuItemId.COPY)) { + console.log("Intercept COPY start:" + textRange.start + "; end:" + textRange.end) + return true + } + if (menuItem.id.equals(TextMenuItemId.SELECT_ALL)) { + console.log("Do not intercept SELECT_ALL start:" + textRange.start + "; end:" + textRange.end) + return false + } + return false + } + + @State editMenuOptions: EditMenuOptions = { + onCreateMenu: this.onCreateMenu, onMenuItemClick: this.onMenuItemClick + } + + build() { + Column({ space : 10 }) { + Text('Setting custom menu extensions').alignSelf(ItemAlign.Start).decoration({ + type: TextDecorationType.Underline, + color: Color.Black, + style: TextDecorationStyle.SOLID + }).margin({top:20, bottom: 20}) + + AtomicServiceSearch({ + value:'Default input', + search: { + editMenuOptions : this.editMenuOptions + } + }) + }.padding({ left: 16, right: 16 }) + } + + public alert(message: string): void { + AlertDialog.show({ + message: message, + }) + } +} +``` + +![](figures/AtomicServiceSearchDemo10.gif) + + + + + +### Example 11: Setting the Horizontal Alignment, Caret Style, and Background Color of the Selected Text +This example shows how to set the horizontal alignment, caret style, and background color of the selected text using **textAlign**, **caretStyle**, and **selectedBackgroundColor**. + +```ts +import { AtomicServiceSearch } from '@kit.ArkUI'; + +@Entry +@Component +struct Index { + build() { + Column() { + Text('Setting horizontal alignment/caret style/background color of selected text').alignSelf(ItemAlign.Start).decoration({ + type: TextDecorationType.Underline, + color: Color.Black, + style: TextDecorationStyle.SOLID + }).margin({top:20, bottom: 20}) + + AtomicServiceSearch({ + value: 'Search textAlign sample', + search: { + textAlign: TextAlign.Center, + caretStyle: { width: 3, color: Color.Green }, + selectedBackgroundColor: Color.Gray + } + }) + }.padding({ left: 16, right: 16 }) + } + + public alert(message: string): void { + AlertDialog.show({ + message: message, + }) + } +} +``` + +![](figures/AtomicServiceSearchDemo11.gif) + + + +### Example 12: Setting Input Filtering +This example shows how to set input filtering using **inputFilter**. + +```ts +import { AtomicServiceSearch } from '@kit.ArkUI'; + +@Entry +@Component +struct Index { + @State filterValue: string = ''; + + build() { + Column() { + Column({ space: 10 }) { + Text('Setting input filtering').alignSelf(ItemAlign.Start).decoration({ + type: TextDecorationType.Underline, + color: Color.Black, + style: TextDecorationStyle.SOLID + }).margin({top:20, bottom: 20}) + AtomicServiceSearch({ + placeholder: 'please enter...', + search: { + inputFilter: { + inputFilterValue : '[a-z]', + error: (filterValue: string) => {this.filterValue = filterValue} + } + } + }) + Text('Filter:' + this.filterValue).alignSelf(ItemAlign.Start) + + } + }.padding({ left: 16, right: 16 }) + } + + public alert(message: string): void { + AlertDialog.show({ + message: message, + }) + } +} +``` + +![](figures/AtomicServiceSearchDemo12.gif) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-atomicservice-AtomicServiceTabs.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-atomicservice-AtomicServiceTabs.md index e132c873d69d13f4485c918b2dc20531cf98ac7d..bfb217924a0e296abe1e12358e4bf4357b8df27a 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-atomicservice-AtomicServiceTabs.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-atomicservice-AtomicServiceTabs.md @@ -18,7 +18,7 @@ Not supported ## Attributes -The [universal attributes](ts-universal-attributes-size.md) are not supported. +The [universal attributes](ts-component-general-attributes.md) are not supported. ## AtomicServiceTabs @@ -37,6 +37,7 @@ AtomicServiceTabs ({ TabBarOptions? ], tabBarPosition?: TabBarPosition, + layoutMode?: LayoutMode, barBackgroundColor?: ResourceColor, index?: number, barOverlap?: boolean, @@ -59,10 +60,11 @@ AtomicServiceTabs ({ | tabContents | [[TabContentBuilder?](#tabcontentbuilder),[TabContentBuilder?](#tabcontentbuilder), [TabContentBuilder?](#tabcontentbuilder),[TabContentBuilder?](#tabcontentbuilder), [TabContentBuilder?](#tabcontentbuilder)] | No| @BuilderParam| Array of content view containers.| | tabBarOptionsArray | [[TabBarOptions?](#tabbaroptions),[TabBarOptions?](#tabbaroptions), [TabBarOptions?](#tabbaroptions),[TabBarOptions?](#tabbaroptions), [TabBarOptions?](#tabbaroptions)] | Yes| @Prop | Array of tab bar container configurations.| | tabBarPosition | [TabBarPosition](#tabbarposition) | No |@Prop | Position of the tab bar.| +| layoutMode16+ | [LayoutMode](ts-container-tabcontent.md#layoutmode10) | No |@Prop | Sets the layout mode of the images and texts on the bottom tab.| | barBackgroundColor | [ResourceColor](ts-types.md#resourcecolor) | No| @Prop | Background color of the tab bar.| | index | number | No| @Prop | Index of the currently displayed tab.| | barOverlap | boolean| No| @Prop | Whether the tab bar is superimposed on the **TabContent** component after having its background blurred.| -| controller|[TabsController](ts-container-tabs#tabscontroller) | No| - |Tab controller, which is used to control switching of tabs.| +| controller|[TabsController](ts-container-tabs.md#tabscontroller) | No| - |Tab controller, which is used to control switching of tabs.| | onChange | Callback\ | No| - | Callback invoked when a tab is switched.| | onTabBarClick | Callback\ | No| - |Callback invoked when a tab is clicked.| | onContentWillChange | [OnContentWillChangeCallback](#oncontentwillchangecallback) | No| - | Callback invoked when a new page is about to be displayed.| @@ -81,22 +83,23 @@ type TabContentBuilder = () => void ## TabBarOptions -Defines tab bar options, including **icon**, **text**, **unselectColor**, and **SelectedColor**. - ### constructor +constructor(icon: ResourceStr | TabBarSymbol, text: ResourceStr, unselectedColor?: ResourceColor, selectedColor?: ResourceColor) -constructor(icon: ResourceStr | TabBarSymbol, text: ResourceStr, unselectedColor?: ResourceColor, selectedColor?: ResourceColor); +A constructor used to create an **TabBarOptions** instance. **Atomic service API**: This API can be used in atomic services since API version 12. **System capability**: SystemCapability.ArkUI.ArkUI.Full +**Parameters** + | Name| Type| Mandatory| Description| | --------------- | ------ |------ |------ | -| icon | [ResourceStr](ts-types.md#resourcestr) \| [TabBarSymbol](#tabbarsymbol12) | Yes| Icon of the tab.| +| icon | [ResourceStr](ts-types.md#resourcestr) \| [TabBarSymbol](ts-container-tabcontent.md#tabbarsymbol12) | Yes| Icon of the tab.| | text | [ResourceStr](ts-types.md#resourcestr) | Yes| Text of the tab.| -| unselectedColor | [ResourceColor](ts-types.md#resourcecolor) | Yes| Color of the tab when it is not selected.| -| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | Yes| Color of the tab when it is selected.| +| unselectedColor | [ResourceColor](ts-types.md#resourcecolor) | No| Color of the tab when it is not selected.
Default value: **#99182431**| +| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | No| Color of the tab when it is selected.
Default value: **#FF007DFF**| ## TabBarPosition @@ -124,6 +127,8 @@ type OnContentWillChangeCallback = (currentIndex: number, comingIndex: number) = ## Example +### Example 1: Pure Text Style + ```ts // Index.ets import { AtomicServiceTabs, TabBarOptions, TabBarPosition, OnContentWillChangeCallback } from '@kit.ArkUI'; @@ -175,9 +180,81 @@ struct Index { } ], tabBarOptionsArray: [ - new TabBarOptions($r('sys.media.ohos_ic_public_phone'), 'Green', Color.Black, Color.Blue), - new TabBarOptions($r('sys.media.ohos_ic_public_location'), 'Blue', Color.Black, Color.Blue), - new TabBarOptions($r('sys.media.ohos_ic_public_more'), 'Yellow', Color.Black, Color.Blue) + new TabBarOptions('', 'Green', Color.Black, Color.Green), + new TabBarOptions('', 'Blue', Color.Black, Color.Blue), + new TabBarOptions('', 'Yellow', Color.Black, Color.Yellow), + ], + tabBarPosition: TabBarPosition.BOTTOM, + barBackgroundColor: $r('sys.color.ohos_id_color_bottom_tab_bg'), + onTabBarClick:this.onTabClick, + onContentWillChange: this.onContentWillChangeCallBack, + }) + Column() { + Text("onchange callback times:" + this.onClickNumber) + Text("comingIndex = " + this.comingIndex + ", currentIndex = " + this.currentIndex) + }.margin({top:500}) + }.height('100%') + } +} +``` +![atomicservicetabs](figures/atomicserviceTabs_text.PNG) + +### Example 2: Pure Icon Style + +```ts +// Index.ets +import { AtomicServiceTabs, TabBarOptions, TabBarPosition, OnContentWillChangeCallback } from '@kit.ArkUI'; + +@Entry +@Component +struct Index { + @State message: string = 'Home'; + @State onClickNumber: number = 0; + @State currentIndex: number = 0; + @State comingIndex: number = 0; + onContentWillChangeCallBack: OnContentWillChangeCallback = (currentIndex: number, comingIndex: number): boolean => { + this.currentIndex = currentIndex; + this.comingIndex = comingIndex; + console.log('OnContentWillChangeCallback') + return true; + } + onTabClick: Callback = (index:number)=>{ + this.onClickNumber ++; + console.log('onTabClick'); + } + @Builder + tabContent1() { + Column().width('100%').height('100%').alignItems(HorizontalAlign.Center).backgroundColor('#00CB87') + } + + @Builder + tabContent2() { + Column().width('100%').height('100%').backgroundColor('#007DFF') + } + + @Builder + tabContent3() { + Column().width('100%').height('100%').backgroundColor('#FFBF00') + } + + build() { + Stack() { + AtomicServiceTabs({ + tabContents: [ + () => { + this.tabContent1() + }, + () => { + this.tabContent2() + }, + () => { + this.tabContent3() + } + ], + tabBarOptionsArray: [ + new TabBarOptions($r('sys.media.ohos_ic_public_phone'), '', Color.Black, Color.Blue), + new TabBarOptions($r('sys.media.ohos_ic_public_location'), '', Color.Black, Color.Blue), + new TabBarOptions($r('sys.media.ohos_ic_public_more'), '', Color.Black, Color.Blue), ], tabBarPosition: TabBarPosition.BOTTOM, barBackgroundColor: $r('sys.color.ohos_id_color_bottom_tab_bg'), @@ -192,4 +269,99 @@ struct Index { } } ``` -![atomicservicetabs](figures/atomicservicetabs.gif) +![atomicservicetabs](figures/atomicserviceTabs_icon.PNG) + + +### Example 3: Custom Layout with Text and Icons + +```ts +// Index.ets +import { AtomicServiceTabs, TabBarOptions, TabBarPosition, OnContentWillChangeCallback } from '@kit.ArkUI'; + +@Entry +@Component +struct AtomicserviceTabs { + @State flag: boolean = false; + @State message: string = 'Home'; + @State onClickNumber: number = 0; + @State currentIndex: number = 0; + @State comingIndex: number = 0; + @State layoutMode: LayoutMode = LayoutMode.VERTICAL; + onContentWillChangeCallBack: OnContentWillChangeCallback = (currentIndex: number, comingIndex: number): boolean => { + this.currentIndex = currentIndex; + this.comingIndex = comingIndex; + console.log('OnContentWillChangeCallback') + return true; + } + onTabClick: Callback = (index: number) => { + this.onClickNumber++; + console.log('onTabClick'); + } + onChange: Callback = (Index: number) => { + console.log('onChange'); + console.log('onChange2'); + } + + @Builder + tabContent1() { + Column().width('100%').height('100%').alignItems(HorizontalAlign.Center).backgroundColor('#00CB87') + } + + @Builder + tabContent2() { + Column().width('100%').height('100%').backgroundColor(Color.Blue) + } + + @Builder + tabContent3() { + Column().width('100%').height('100%').backgroundColor('#FFBF00') + } + + build() { + Stack() { + AtomicServiceTabs({ + tabContents: [ + () => { + this.tabContent1() + }, + () => { + this.tabContent2() + }, + () => { + this.tabContent3() + }, + ], + tabBarOptionsArray: [ + new TabBarOptions($r('sys.media.ohos_ic_public_phone'), 'Green', Color.Black, Color.Blue), + new TabBarOptions($r('sys.media.ohos_ic_public_location'), 'Blue', Color.Black, Color.Blue), + new TabBarOptions($r('sys.media.ohos_ic_public_more'), 'Yellow', Color.Black, Color.Blue), + ], + tabBarPosition: TabBarPosition.BOTTOM, + barBackgroundColor: $r('sys.color.ohos_id_color_bottom_tab_bg'), + onTabBarClick: this.onTabClick, + onContentWillChange: this.onContentWillChangeCallBack, + onChange: this.onChange, + layoutMode: this.layoutMode, + }) + + Column() { + Button("Vertical Layout") + .width('30%') + .height(50) + .margin({ top: 5 }) + .onClick((event?: ClickEvent) => { + this.layoutMode = LayoutMode.VERTICAL; + }) + Button("Horizontal Layout") + .width('30%') + .height(50) + .margin({ top: 5 }) + .onClick((event?: ClickEvent) => { + this.layoutMode = LayoutMode.HORIZONTAL; + }) + }.margin({ top: 10 }) + }.height('100%') + } +} +``` +![atomicservicetabs](figures/atomicservicetabs_layoutMode.gif) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-atomicservice-HalfScreenLaunchComponent.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-atomicservice-HalfScreenLaunchComponent.md new file mode 100644 index 0000000000000000000000000000000000000000..048f8d5476c96bced9f4279803a74a1b878e5734 --- /dev/null +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-atomicservice-HalfScreenLaunchComponent.md @@ -0,0 +1,83 @@ +# HalfScreenLaunchComponent + +**HalfScreenLaunchComponent** is a component designed for launching atomic services in half screen. If the invoked application (the one being launched) grants the invoker the authorization to run the atomic service in an embedded manner, the invoker can operate the atomic service in half-screen embedded mode. If authorization is not provided, the invoker will launch the atomic service in a pop-up manner. + +> **NOTE** +> +> This component is supported since API version 18. Updates will be marked with a superscript to indicate their earliest API version. +> +> To implement an embeddable atomic service, make sure it inherits from [EmbeddableUIAbility](../../apis-ability-kit/js-apis-app-ability-embeddableUIAbility.md). This ensures that it functions properly. + +## Modules to Import + +``` +import { HalfScreenLaunchComponent } from '@kit.ArkUI'; +``` + +## Child Components + +Not supported + +## Attributes +The [universal attributes](ts-component-general-attributes.md) are not supported. + +## HalfScreenLaunchComponent + +HalfScreenLaunchComponent({ + content: Callback\, + appId: string, + options?: AtomicServiceOptions, + onError?: ErrorCallback, + onTerminated?: Callback<TerminationInfo> + }) + +**Decorator**: \@Component + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type| Mandatory| Decorator| Description| +| -------- | -------- | -------- | -------- | -------- | +| content | Callback\ | Yes| \@BuilderParam | Content displayed in the component.| +| appId | string | Yes| - | Application ID for the atomic service.| +| options | [AtomicServiceOptions](../../apis-ability-kit/js-apis-app-ability-atomicServiceOptions.md) | No| - | Parameters for starting the atomic service. The default value is empty.| +| onError |[ErrorCallback](../../apis-basic-services-kit/js-apis-base.md#errorcallback) | No| - | Invoked when an error occurs during the running of the atomic service.| +| onTerminated | [Callback](../../apis-basic-services-kit/js-apis-base.md#callback)\ | No| - | Callback used to return the result of the atomic service. The input parameter is of type **TerminationInfo**.| + +## Example + +This example demonstrates how to start a top-up service in embedded mode. + +```ts +import { HalfScreenLaunchComponent } from '@kit.ArkUI'; + +@Entry +@Component +struct Index { + appId: string = "5765880207853275489"; // Application ID of the top-up service + + build() { + Column() { + HalfScreenLaunchComponent({ + appId: this.appId, + options: {}, + onTerminated: (info:TerminationInfo)=> { + console.log('onTerminated info = '+ info.want); + }, + onError: (err) => { + console.error(" onError code: " + err.code + ", message: ", err.message); + } + }) { + Column() { + Image($r('app.media.app_icon')) + Text('Start top-up') + }.width("80vp").height("80vp").margin({bottom:30}) + } // Content is passed as a trailing closure. + } + } + +} +``` diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-atomicservice-InterstitialDialogAction.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-atomicservice-InterstitialDialogAction.md index e35adb486ab51a179fa649f6732d941324529132..22ffa23446997f625668a41a01c348a7969af1b9 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-atomicservice-InterstitialDialogAction.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-atomicservice-InterstitialDialogAction.md @@ -18,7 +18,7 @@ Not supported ## Attributes -The [universal attributes](ts-universal-attributes-size.md) are not supported. +The [universal attributes](ts-component-general-attributes.md) are not supported. ## InterstitialDialogAction @@ -71,7 +71,7 @@ Defines the attributes specific to the dialog box and custom click actions for t | Name| Type| Mandatory| Description| | - | - | - | - | | uiContext | [UIContext](../js-apis-arkui-UIContext.md#uicontext) | Yes| UI context.| -| bottomOffsetType | [BottomOffset](#bottomoffset) | Yes| Bottom offset type of the dialog box.| +| bottomOffsetType | [BottomOffset](#bottomoffset) | No| Bottom offset type of the dialog box.| | title | [ResourceStr](ts-types.md#resourcestr) | No| Title of the dialog box.| | subtitle | [ResourceStr](ts-types.md#resourcestr) | No| Subtitle of the dialog box.| | titleColor | [ResourceStr](ts-types.md#resourcestr) \| [Color](ts-appendix-enums.md#color) | No| Font color of the dialog box title.| @@ -123,7 +123,7 @@ Defines the distance between the popup and the bottom in different scenario mode | OFFSET_FOR_NONE | 1 | Distance from the bottom of the window when there is no menu bar.
It sets the dialog box 44 vp away from the bottom of the window.| ## Events -The [universal events](ts-universal-events-click.md) are not supported. +The [universal events](ts-component-general-events.md) are not supported. ## Example diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-atomicservice-NavPushPathHelper.md b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-atomicservice-NavPushPathHelper.md index f74b45f8defbd0d5decc83d3d9d2b095c74fa94c..e67c650cf5930647907c13bcae643b772e093bcf 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ohos-atomicservice-NavPushPathHelper.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ohos-atomicservice-NavPushPathHelper.md @@ -18,7 +18,7 @@ Not supported ## Attributes -The [universal attributes](ts-universal-attributes-size.md) are not supported. +The [universal attributes](ts-component-general-attributes.md) are not supported. ## NavPushPathHelper @@ -417,7 +417,7 @@ For details about the error codes, see [Router Error Codes](../errorcode-router. ## Events -The [universal events](ts-universal-events-click.md) are not supported. +The [universal events](ts-component-general-events.md) are not supported. ## Example diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-appendix-enums.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-appendix-enums.md index ce2b45084b03b28ea8fc172aeb729950fd903c9f..80f723ce184efcf44e2c617a0c559b6889bdd661 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-appendix-enums.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-appendix-enums.md @@ -31,24 +31,24 @@ **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Description | -| --------- | ------------------------------- | -| Contain | The image is scaled with its aspect ratio retained for the content to be completely displayed within the display boundaries.
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11.
![ImageFit-Examples01](figures/image_fit_contain.png) | -| Cover | The image is scaled with its aspect ratio retained for both sides to be greater than or equal to the display boundaries.
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11.
![ImageFit-Examples02](figures/image_fit_cover.png) | -| Auto | The image is scaled automatically based on its own size and the size of the component to fit the display area.
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11.
![ImageFit-Examples03](figures/image_fit_auto.png) | -| Fill | The image is scaled to fill the display area, and its aspect ratio is not retained.
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11.
![ImageFit-Examples04](figures/image_fit_fill.png) | -| ScaleDown | The image is displayed with its aspect ratio retained, in a size smaller than or equal to the original size.
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11.
![ImageFit-Examples05](figures/image_fit_scaleDown.png) | -| None | The image is displayed in its original size.
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11.
![ImageFit-Examples06](figures/image_fit_none.png) | -| TOP_START12+ | The image is displayed at the top start corner of the **Image** component, keeping its original size.
**Widget capability**: This API can be used in ArkTS widgets since API version 12.
**Atomic service API**: This API can be used in atomic services since API version 12.
![ImageFit-Examples07](figures/image_fit_top_start.png) | -| TOP12+ | The image is displayed horizontally centered at the top of the **Image** component, keeping its original size.
**Widget capability**: This API can be used in ArkTS widgets since API version 12.
**Atomic service API**: This API can be used in atomic services since API version 12.
![ImageFit-Examples08](figures/image_fit_top.png) | -| TOP_END12+ | The image is displayed at the top end corner of the **Image** component, keeping its original size.
**Widget capability**: This API can be used in ArkTS widgets since API version 12.
**Atomic service API**: This API can be used in atomic services since API version 12.
![ImageFit-Examples09](figures/image_fit_top_end.png) | -| START12+ | The image is displayed vertically centered at the start of the **Image** component, keeping its original size.
**Widget capability**: This API can be used in ArkTS widgets since API version 12.
**Atomic service API**: This API can be used in atomic services since API version 12.
![ImageFit-Examples10](figures/image_fit_start.png) | -| CENTER12+ | The image is displayed at the center of the **Image** component both horizontally and vertically, keeping its original size.
**Widget capability**: This API can be used in ArkTS widgets since API version 12.
**Atomic service API**: This API can be used in atomic services since API version 12.
![ImageFit-Examples11](figures/image_fit_center.png) | -| END12+ | The image is displayed vertically centered at the end of the **Image** component, keeping its original size.
**Widget capability**: This API can be used in ArkTS widgets since API version 12.
**Atomic service API**: This API can be used in atomic services since API version 12.
![ImageFit-Examples12](figures/image_fit_end.png) | -| BOTTOM_START12+ | The image is displayed at the bottom start corner of the **Image** component, keeping its original size.
**Widget capability**: This API can be used in ArkTS widgets since API version 12.
**Atomic service API**: This API can be used in atomic services since API version 12.
![ImageFit-Examples13](figures/image_fit_bottom_start.png) | -| BOTTOM12+ | The image is displayed horizontally centered at the bottom of the **Image** component, keeping its original size.
**Widget capability**: This API can be used in ArkTS widgets since API version 12.
**Atomic service API**: This API can be used in atomic services since API version 12.
![ImageFit-Examples14](figures/image_fit_bottom.png) | -| BOTTOM_END12+| The image is displayed at the bottom end corner of the **Image** component, keeping its original size.
**Widget capability**: This API can be used in ArkTS widgets since API version 12.
**Atomic service API**: This API can be used in atomic services since API version 12.
![ImageFit-Examples15](figures/image_fit_bottom_end.png) | -| MATRIX15+| The image, with the use of [imageMatrix](ts-basic-components-image.md#imagematrix15), is displayed in the specified position of the **Image component**, keeping its original size. SVG images are not supported.
**Widget capability**: This API can be used in ArkTS widgets since API version 15.
**Atomic service API**: This API can be used in atomic services since API version 15.| +| Name | Value | Description | +| --------- | ----- | ------------------------------- | +| Contain | 0 | The image is scaled with its aspect ratio retained for the content to be completely displayed within the display boundaries.
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11.
![ImageFit-Examples01](figures/image_fit_contain.png) | +| Cover | 1 | The image is scaled with its aspect ratio retained for both sides to be greater than or equal to the display boundaries.
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11.
![ImageFit-Examples02](figures/image_fit_cover.png) | +| Auto | 2 | The image is scaled automatically based on its own size and the size of the component to fit the display area.
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11.
![ImageFit-Examples03](figures/image_fit_auto.png) | +| Fill | 3 | The image is scaled to fill the display area, and its aspect ratio is not retained.
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11.
![ImageFit-Examples04](figures/image_fit_fill.png) | +| ScaleDown | 4 | The image is displayed with its aspect ratio retained, in a size smaller than or equal to the original size.
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11.
![ImageFit-Examples05](figures/image_fit_scaleDown.png) | +| None | 5 | The image is displayed in its original size.
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11.
![ImageFit-Examples06](figures/image_fit_none.png) | +| TOP_START12+ | 7 | The image is displayed at the top start corner of the **Image** component, keeping its original size.
**Widget capability**: This API can be used in ArkTS widgets since API version 12.
**Atomic service API**: This API can be used in atomic services since API version 12.
![ImageFit-Examples07](figures/image_fit_top_start.png) | +| TOP12+ | 8 | The image is displayed horizontally centered at the top of the **Image** component, keeping its original size.
**Widget capability**: This API can be used in ArkTS widgets since API version 12.
**Atomic service API**: This API can be used in atomic services since API version 12.
![ImageFit-Examples08](figures/image_fit_top.png) | +| TOP_END12+ | 9 | The image is displayed at the top end corner of the **Image** component, keeping its original size.
**Widget capability**: This API can be used in ArkTS widgets since API version 12.
**Atomic service API**: This API can be used in atomic services since API version 12.
![ImageFit-Examples09](figures/image_fit_top_end.png) | +| START12+ | 10 | The image is displayed vertically centered at the start of the **Image** component, keeping its original size.
**Widget capability**: This API can be used in ArkTS widgets since API version 12.
**Atomic service API**: This API can be used in atomic services since API version 12.
![ImageFit-Examples10](figures/image_fit_start.png) | +| CENTER12+ | 11 | The image is displayed at the center of the **Image** component both horizontally and vertically, keeping its original size.
**Widget capability**: This API can be used in ArkTS widgets since API version 12.
**Atomic service API**: This API can be used in atomic services since API version 12.
![ImageFit-Examples11](figures/image_fit_center.png) | +| END12+ | 12 | The image is displayed vertically centered at the end of the **Image** component, keeping its original size.
**Widget capability**: This API can be used in ArkTS widgets since API version 12.
**Atomic service API**: This API can be used in atomic services since API version 12.
![ImageFit-Examples12](figures/image_fit_end.png) | +| BOTTOM_START12+ | 13 | The image is displayed at the bottom start corner of the **Image** component, keeping its original size.
**Widget capability**: This API can be used in ArkTS widgets since API version 12.
**Atomic service API**: This API can be used in atomic services since API version 12.
![ImageFit-Examples13](figures/image_fit_bottom_start.png) | +| BOTTOM12+ | 14 | The image is displayed horizontally centered at the bottom of the **Image** component, keeping its original size.
**Widget capability**: This API can be used in ArkTS widgets since API version 12.
**Atomic service API**: This API can be used in atomic services since API version 12.
![ImageFit-Examples14](figures/image_fit_bottom.png) | +| BOTTOM_END12+| 15 | The image is displayed at the bottom end corner of the **Image** component, keeping its original size.
**Widget capability**: This API can be used in ArkTS widgets since API version 12.
**Atomic service API**: This API can be used in atomic services since API version 12.
![ImageFit-Examples15](figures/image_fit_bottom_end.png) | +| MATRIX15+| 16 | The image, with the use of [imageMatrix](ts-basic-components-image.md#imagematrix15), is displayed in the specified position of the **Image component**, keeping its original size. SVG images are not supported.
**Atomic service API**: This API can be used in atomic services since API version 15.| ## BorderStyle @@ -108,17 +108,15 @@ ## MouseAction8+ -**Atomic service API**: This API can be used in atomic services since API version 11. - **System capability**: SystemCapability.ArkUI.ArkUI.Full | Name | Description | | ------- | ------- | -| Press | The mouse button is pressed.| -| Release | The mouse button is released.| -| Move | The mouse cursor moves. | -| Hover | The mouse pointer is hovered on an element.
**NOTE**
This value has no effect. | -| Cancel16+ | The mouse button action is canceled.| +| Press | The mouse button is pressed.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| Release | The mouse button is released.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| Move | The mouse cursor moves.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| Hover | The mouse pointer is hovered on an element.
**NOTE**
This value has no effect.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| CANCEL18+ | The mouse button action is canceled.
**Atomic service API**: This API can be used in atomic services since API version 18.| ## ModifierKey10+ @@ -253,7 +251,7 @@ Enumerates the interpolation curves. For details about the animation, see \ No newline at end of file + +## InteractionHand15+ + +Defines whether an event is triggered by a left-hand or right-hand tap. + +**Atomic service API**: This API can be used in atomic services since API version 15. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Value | Description | +| -------- | ---- | ---------------------- | +| NONE | 0 | Unknown.| +| LEFT | 1 | Left hand.| +| RIGHT | 2 | Right hand.| + +## FocusDrawLevel18+ + +Enumerates the drawing levels of the focus box for a node. + +**Widget capability**: This API can be used in ArkTS widgets since API version 18. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Value | Description | +| -------------- | -- | ---------------------------------------- | +| SELF | 0 | The focus box is drawn on the node's own layer. | +| TOP | 1 | The focus box is drawn on the topmost layer of the current instance's z-order. | diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-arcscrollbar.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-arcscrollbar.md index 31c0093b5c7e191529e319c425da4144d46de9c0..80837e3943bf9e971b4790be8187c02bd13010af 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-arcscrollbar.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-arcscrollbar.md @@ -1,10 +1,10 @@ # ArcScrollBar -The **ArcScrollBar** component is designed to be used with scrollable components such as [List](ts-container-list.md), [Grid](ts-container-grid.md), and [Scroll](ts-container-scroll.md) to provide a circular scrollbar. +The **ArcScrollBar** component is designed to be used together with scrollable components such as [ArcList](ts-container-arclist.md), [List](ts-container-list.md), [Grid](ts-container-grid.md), [Scroll](ts-container-scroll.md), and [WaterFlow](ts-container-waterflow.md) to provide a circular scrollbar. > **NOTE** > -> - This component is supported since API version 16. Updates will be marked with a superscript to indicate their earliest API version. +> - This component is supported since API version 18. Updates will be marked with a superscript to indicate their earliest API version. > - If no width or height is set for the **ArcScrollBar** component, it will inherit the size of its parent component. @@ -18,9 +18,9 @@ ArcScrollBar(options: ArcScrollBarOptions) Creates an instance of the **ArcScrollBar** component. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. -**System capability**: SystemCapability.ArkUI.ArkUI.Full +**System capability**: SystemCapability.ArkUI.ArkUI.Circle **Parameters** @@ -32,9 +32,9 @@ Creates an instance of the **ArcScrollBar** component. Represents the parameters used to construct an **ArcScrollBar** component. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. -**System capability**: SystemCapability.ArkUI.ArkUI.Full +**System capability**: SystemCapability.ArkUI.ArkUI.Circle | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-blank.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-blank.md index 7f0b6bf777d815f1414905b79eed9b5e9b8b36cb..37610e0cc30081dd08c97807a3c3378014e02098 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-blank.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-blank.md @@ -31,11 +31,11 @@ Since API version 10: | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| min | number \| string | No| Minimum size of the **Blank** component in the container along the main axis.
Default value: **0**
**NOTE**
This parameter cannot be set in percentage. If the value is negative, the default value is used. If the minimum size is larger than the available space of the container, it is used as the component size, and the component extends beyond the container.| +| min | number \| string | No| Minimum size of the **Blank** component in the container along the main axis.
Default value: **0**
If the type is number, the default unit is vp. If the type is string, the [pixel unit](ts-pixel-units.md) can be explicitly specified, for example, '**10px'**. If the unit is not specified, the default unit vp is used, in which case **'10'** is equivalent to **10vp**.
**NOTE**
This parameter cannot be set in percentage. If the value is negative, the default value is used. If the minimum size is larger than the available space of the container, it is used as the component size, and the component extends beyond the container.| ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### color @@ -53,16 +53,18 @@ Sets the color to fill the blank. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | [ResourceColor](ts-types.md#resourcecolor) | Yes| Color to fill the blank.

Default value: **Color.Transparent**| +| value | [ResourceColor](ts-types.md#resourcecolor) | Yes| Color to fill the blank.
Default value: **Color.Transparent**| ## Events -The [universal events](ts-universal-events-click.md) are supported. +The [universal events](ts-component-general-events.md) are supported. ## Example -### Example 1 -The sample below shows how the **Blank** component fills the empty spaces in the container in landscape and portrait modes. +### Example 1: Filling Remaining Space + +This example shows how the **Blank** component fills the remaining space in landscape and portrait modes. + ```ts // xxx.ets @Entry @@ -89,8 +91,9 @@ Landscape mode ![en-us_image_0000001212378418](figures/en-us_image_0000001212378418.gif) -### Example 2 -Set the **min** parameter when the width of the parent container of the **Blank** component is not set. +### Example 2: Filling a Fixed Width + +This example shows the effect of using the **min** parameter of the **Blank** component when its parent component does not have a width set. ```ts // xxx.ets diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-button.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-button.md index c9dd63e644a3b07470b449b4d05418c585a1cae3..de316e323a82d345de77f24ba00afb1b77d24f8d 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-button.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-button.md @@ -50,16 +50,28 @@ By default, the text content is displayed in a one line. | Name | Type | Mandatory| Description | | ------- | --------------------------------------- | ---- | -------------------- | -| label | [ResourceStr](ts-types.md#resourcestr) | Yes | Button text. | +| label | [ResourceStr](ts-types.md#resourcestr) | Yes | Button text.
**NOTE**
If the text is longer than the width of the button, it is truncated.| | options | [ButtonOptions](#buttonoptions) | No | Button settings.| +### Button + +Button() + +Creates an empty button. + +**Widget capability**: This API can be used in ArkTS widgets since API version 9. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + ## ButtonOptions **System capability**: SystemCapability.ArkUI.ArkUI.Full | Name | Type | Mandatory| Description | | ------------------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [ButtonType](#buttontype) | No | Button type.
Default value: Since API version 16: **ButtonType.ROUNDED_RECTANGLE**
API version 15 and earlier versions: **ButtonType.Capsule**
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| type | [ButtonType](#buttontype) | No | Button type.
Default value:
- API version 18 and later versions: **ButtonType.ROUNDED_RECTANGLE**
- Versions earlier than API version 18: **ButtonType.Capsule**
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11.| | stateEffect | boolean | No | Whether to enable the pressed effect on the click of the button. The value **false** means to disable the pressed effect.
Default value: **true**
**NOTE**
When the pressed effect is enabled on the click of the button and the state style is set, the background color is applied based on the state style.
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11.| | buttonStyle11+ | [ButtonStyleMode](#buttonstylemode11) | No | Style and primacy of the button.
Default value: **ButtonStyleMode.EMPHASIZED**
**NOTE**
The button primacy is as follows, from high to low: emphasized button, normal button, text button.
**Widget capability**: This API can be used in ArkTS widgets since API version 11.
**Atomic service API**: This API can be used in atomic services since API version 12.| | controlSize11+ | [ControlSize](#controlsize11) | No | Size of the button.
Default value: **ControlSize.NORMAL**
**Widget capability**: This API can be used in ArkTS widgets since API version 11.
**Atomic service API**: This API can be used in atomic services since API version 12.| @@ -67,7 +79,7 @@ By default, the text content is displayed in a one line. ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### type @@ -103,7 +115,7 @@ Sets the font size for the button. | Name| Type | Mandatory| Description | | ------ | ---------------------------- | ---- | ------------------------------------------------------------ | -| value | [Length](ts-types.md#length) | Yes | Font size of the button.
Default value:
**$r('sys.float.Body_L')** when **controlSize** is set to **ControlSize.NORMAL**
**$r('sys.float.Body_S')** when **controlSize** is set to **ControlSize.SMALL**| +| value | [Length](ts-types.md#length) | Yes | Font size of the button.
Default value:
**$r('sys.float.Body_L')** when **controlSize** is set to **ControlSize.NORMAL**
**$r('sys.float.Body_S')** when **controlSize** is set to **ControlSize.SMALL**
**NOTE**
For the string type, percentage values are not supported.| ### fontColor @@ -285,13 +297,13 @@ Creates a content modifier. | ------ | --------------------------------------------- | ---- | ------------------------------------------------ | | modifier | [ContentModifier\](#buttonconfiguration12) | Yes | Content modifier to apply to the button.
**modifier**: content modifier. You need a custom class to implement the **ContentModifier** API.| -### minFontScale16+ +### minFontScale18+ minFontScale(scale: number | Resource) Sets the minimum font scale factor for text. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -301,13 +313,13 @@ Sets the minimum font scale factor for text. | ------ | --------------------------------------------- | ---- | --------------------------------------------- | | scale | number \| [Resource](ts-types.md#resource) | Yes | Minimum font scale factor for text.
Value range: [0, 1]
**NOTE**
A value less than 0 is handled as **0**. A value greater than 1 is handled as **1**. Abnormal values are ineffective by default.
If the multiplier is set to 0, no content is displayed.| -### maxFontScale16+ +### maxFontScale18+ maxFontScale(scale: number | Resource) Setting the scale factor to **0** hides the content. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -401,8 +413,8 @@ You need a custom class to implement the **ContentModifier** API. | Name | Type | Read Only | Optional| Description | | ------ | ------ | ---------------- | ---------------- | ---------------- | -| label | string | No| No| Text label of the button.| -| pressed | boolean | No| No| Whether the button is pressed.
**NOTE**
The button here refers to the original button, not the new component constructed using the builder. If the new component is larger than the original button, this parameter does not signify the pressed state of the excess part.| +| label | string | No| No| Text label of the button.
**NOTE**
If the text is longer than the width of the button, it is truncated.| +| pressed | boolean | No| No| Whether the button is pressed. **true**: The button is pressed.
**false**: The button is not pressed.
**NOTE**
The button here refers to the original button, not the new component constructed using the builder. If the new component is larger than the original button, this parameter does not signify the pressed state of the excess part.
Default value: **false**| | triggerClick | [ButtonTriggerClickCallback](#buttontriggerclickcallback12) | No| No| Click event of the new component constructed using the builder.| ## ButtonTriggerClickCallback12+ @@ -419,12 +431,12 @@ Defines the callback type used in **ButtonConfiguration**. | Name | Type | Mandatory| Description | | ------ | ------ | ---- | ---------------- | -| xPos | number | Yes| X-coordinate of the click point.| -| yPos | number | Yes| Y-coordinate of the click point.| +| xPos | number | Yes| X-coordinate of the click point.
Unit: vp| +| yPos | number | Yes| Y-coordinate of the click point.
Unit: vp| ## Events -The [universal events](ts-universal-events-click.md) are supported. +The [universal events](ts-component-general-events.md) are supported. ## Example ### Example 1: Setting the Button Display Style @@ -629,7 +641,7 @@ struct ButtonExample { ``` ![buttonrole](figures/buttonrole.jpeg) -### Example 6: ImplementIng a Custom Button +### Example 6: Implementing a Custom Button This example implements a custom button in the shape of a circle. The circle is red when pressed, accompanied by the text "Pressed" in the title. It is black when not pressed, accompanied by the text "Not pressed" in the title. ```ts class MyButtonStyle implements ContentModifier { diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-calendarpicker.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-calendarpicker.md index 5bd0d94388e3a4ce6df8ee39e0e3b0e8146f55d5..93c3971fac9cc11734b5df5308c10a18bc662191 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-calendarpicker.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-calendarpicker.md @@ -29,7 +29,7 @@ Creates a calendar picker. ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### edgeAlign @@ -45,9 +45,26 @@ How the picker is aligned with the entry component. | Name | Type | Mandatory| Description | | --------- | --------------------------------------- | ---- | ------------------------------------------------------------ | -| alignType | [CalendarAlign](#calendaralign) | Yes | Alignment type.
Default value: **CalendarAlign.END** | +| alignType | [CalendarAlign](#calendaralign) | Yes | Alignment type.
Default value: **CalendarAlign.END** | | offset | [Offset](ts-types.md#offset) | No | Offset of the picker relative to the entry component after alignment based on the specified alignment type.
Default value: **{dx: 0, dy: 0}**| +### edgeAlign18+ + +edgeAlign(alignType: Optional\, offset?: Offset) + +How the picker is aligned with the entry component. Compared to [edgeAlign](#edgealign), this API supports the **undefined** type for the **alignType** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| alignType | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[CalendarAlign](#calendaralign)> | Yes | Alignment type.
If **alignType** is set to **undefined**, the default value **CalendarAlign.END** is used.| +| offset | [Offset](ts-types.md#offset) | No | Offset of the picker relative to the entry component after alignment based on the specified alignment type.
Default value: **{dx: 0, dy: 0}**| + ### textStyle textStyle(value: PickerTextStyle) @@ -64,13 +81,45 @@ Sets the font color, font size, and font weight in the entry area. | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | value | [PickerTextStyle](./ts-basic-components-datepicker.md#pickertextstyle10) | Yes | Font color, font size, and font weight in the entry area.
Default value:
{
color: '#ff182431',
font: {
size: '16fp',
weight: FontWeight.Regular
}
} | +### textStyle16+ + +textStyle(style: Optional\) + +Sets the font color, font size, and font weight in the entry area. Compared to [textStyle](#textstyle), this API supports the **undefined** type for the **style** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 16. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| style | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[PickerTextStyle](./ts-basic-components-datepicker.md#pickertextstyle10)> | Yes | Font color, font size, and font weight in the entry area.
If **style** is set to **undefined**, the default value is used:
{
color: '#ff182431',
font: {
size: '16fp',
weight: FontWeight.Regular
}
} | + +### markToday18+ + +markToday(enabled: boolean) + +Sets whether to highlight the current system date. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| enabled | boolean | Yes | Whether to highlight the current system date.
Default value: **false**
The value **true** means to highlight the current system date, and **false** means the opposite.| + ## Events -In addition to the [universal events](ts-universal-events-click.md), the following events are supported. +In addition to the [universal events](ts-component-general-events.md), the following events are supported. ### onChange -onChange(callback: (value: Date) => void) +onChange(callback: Callback\) Triggered when a date is selected. @@ -82,7 +131,23 @@ Triggered when a date is selected. | Name| Type| Mandatory| Description | | ------ | ---- | ---- | -------------- | -| value | Date | Yes | Selected date value| +| callback | [Callback](ts-types.md#callback12)\ | Yes | Selected date value| + +### onChange16+ + +onChange(callback: Optional\>) + +Triggered when a date is selected. Compared to [onChange](#onchange), this API supports the **undefined** type for the **callback** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 16. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| callback | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[Callback](ts-types.md#callback12)\> | Yes | Selected date value
If **callback** is set to **undefined**, the callback function is not used.| ## CalendarOptions @@ -92,13 +157,29 @@ Triggered when a date is selected. | Name | Type | Mandatory | Description | | ----------- | ---------- | ------| --------------------------------- | -| hintRadius | number \| [Resource](ts-types.md#resource) | No | Style of the background of the selected state.
Default value: The background is a circle.
**NOTE**
If the value is **0**, the background is a rectangle with square corners. If the value is in the 0–16 range, the background is a rectangle with rounded corners. If the value is equal to or greater than 16, the background is a circle.| +| hintRadius | number \| [Resource](ts-types.md#resource) | No | Style of the background of the selected state.
Default value: The background is a circle.
**NOTE**
If the value is **0**, the background is a rectangle with square corners. If the value is in the 0–16 range, the background is a rectangle with rounded corners. If the value is greater than or equal to 16, the background is a circle.| | selected | Date | No | Date of the selected item. If the value is not set or does not comply with the date format specifications, the default value will be used.
Default value: current system date| +| start16+ | Date | No | Start date.| +| end16+ | Date | No | End date.| +| disabledDateRange16+ | DateRange[] | No | Disabled date range.
**NOTE**
1. If the start date or end date within a date range is invalid, the entire date range does not take effect.
2. If the end date is earlier than the start date within a date range, the entire date range does not take effect.
3. When users select a date and adjust it with the up or down arrow keys, the system skips over all dates in the disabled date range.| + +**Rules for setting start and end** + +| Scenario | Description | +| -------- | ------------------------------------------------------------ | +| The start date is later than the end date. | Both start and end dates are invalid, and the selected date is the default value. | +| The selected date is earlier than the start date. | The selected date is set to the start date. | +| The selected date is later than the end date. | The selected date is set to the end date. | +| The start date is later than the current system date, and the selected date is not set. | The selected date is set to the start date. | +| The end date is earlier than the current system date, and the selected date is not set. | The selected date is set to the end date. | +| The set date is in invalid format, for example, **'1999-13-32'**.| The start or end date setting is invalid, and the selected date is the default value. | ## CalendarAlign **Atomic service API**: This API can be used in atomic services since API version 11. +**System capability**: SystemCapability.ArkUI.ArkUI.Full + | Name | Description | | ------ | ------------------------ | | START | The picker is left aligned with the entry component. | @@ -106,6 +187,9 @@ Triggered when a date is selected. | END | The picker is right aligned with the entry component. | ## Example +### Example 1: Implementing a Calendar Picker + +This example shows how to implement a calendar picker component. ```ts // xxx.ets @@ -116,7 +200,6 @@ struct CalendarPickerExample { build() { Column() { - Text('Calendar date picker').fontSize(30) Column() { CalendarPicker({ hintRadius: 10, selected: this.selectedDate }) .edgeAlign(CalendarAlign.END) @@ -126,9 +209,74 @@ struct CalendarPickerExample { console.info("CalendarPicker onChange:" + JSON.stringify(value)) }) }.alignItems(HorizontalAlign.End).width("100%") + + Text('Calendar picker').fontSize(30) }.width('100%').margin({ top: 350 }) } } ``` ![CalendarPicker](figures/CalendarPicker.gif) + +### Example 2: Setting Start and End Dates + +This example demonstrates how to set the start and end dates for the calendar picker using **start** and **end**. + +```ts +// xxx.ets +@Entry +@Component +struct CalendarPickerExample { + private selectedDate: Date = new Date('2025-01-15') + private startDate: Date = new Date('2025-01-05') + private endDate: Date = new Date('2025-01-25') + + build() { + Column() { + Column() { + CalendarPicker({ hintRadius: 10, selected: this.selectedDate, start: this.startDate, end: this.endDate }) + .edgeAlign(CalendarAlign.END) + .textStyle({ color: "#ff182431", font: { size: 20, weight: FontWeight.Normal } }) + .margin(10) + .onChange((value) => { + console.info("CalendarPicker onChange:" + JSON.stringify(value)) + }) + }.alignItems(HorizontalAlign.End).width("100%") + }.width('100%').margin({ top: 350 }) + } +} +``` + + + +### Example 3: Highlighting the Current System Date and Disabling a Specific Date Range + +This example shows how to highlight the current system date using **markToday** and disable a specific date range using **disabledDateRange**. + +```ts +// xxx.ets +@Entry +@Component +struct CalendarPickerExample { + private disabledDateRange: DateRange[] = [ + { start: new Date('2025-01-01'), end: new Date('2025-01-02') }, + { start: new Date('2025-01-09'), end: new Date('2025-01-10') }, + { start: new Date('2025-01-15'), end: new Date('2025-01-16') }, + { start: new Date('2025-01-19'), end: new Date('2025-01-19') }, + { start: new Date('2025-01-22'), end: new Date('2025-01-25') } + ] + + build() { + Column() { + CalendarPicker({ disabledDateRange: this.disabledDateRange }) + .margin(10) + .markToday(true) + .onChange((value) => { + console.info("CalendarPicker onChange:" + JSON.stringify(value)) + }) + }.alignItems(HorizontalAlign.End).width('100%') + } +} +``` + + diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-checkbox.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-checkbox.md index 718d8965b75af02171a9c85ee21c61f9d845b8b6..b0e2889171cd705be0fd9ee8450e61fb6a4cb86a 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-checkbox.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-checkbox.md @@ -42,15 +42,16 @@ Creates a check box. ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### select -select(value: Optional\) +select(value: boolean) Sets whether the check box is selected. Since API version 10, this attribute supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md). +Since API version 18, this attribute supports two-way binding through [!!](../../../quick-start/arkts-new-binding.md#two-way-binding-between-built-in-component-parameters). **Widget capability**: This API can be used in ArkTS widgets since API version 9. @@ -60,13 +61,33 @@ Since API version 10, this attribute supports two-way binding through [$$](../.. **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------- | ---- | ---------------------------------- | -| value | [Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Whether the check box is selected.
Default value: **false**| +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------------------------------------ | +| value | boolean | Yes | Whether the check box is selected.
Default value: **false**
**true**: The check box is selected. **false**: The check box is not selected.| + +### select18+ + +select(isSelected: Optional\) + +Sets whether the check box is selected. Compared to [select](#select), this API supports the **undefined** type for the **isSelected** parameter. + +This attribute supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md). This attribute supports two-way binding through [!!](../../../quick-start/arkts-new-binding.md). + +**Widget capability**: This API can be used in ArkTS widgets since API version 18. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| isSelected | [Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Whether the check box is selected.
If **isSelected** is set to **undefined**, the default value **false** is used.
**true**: The check box is selected. **false**: The check box is not selected.| ### selectedColor -selectedColor(value: Optional\) +selectedColor(value: ResourceColor) Sets the color of the check box when it is selected. @@ -80,11 +101,29 @@ Sets the color of the check box when it is selected. | Name| Type | Mandatory| Description | | ------ | ------------------------------------------ | ---- | ------------------------------------------------------------ | -| value | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[ResourceColor](ts-types.md#resourcecolor)> | Yes | Color of the check box when it is selected.
Default value: **$r('sys.color.ohos_id_color_text_primary_activated')**
An invalid value is handled as the default value.| +| value | [ResourceColor](ts-types.md#resourcecolor) | Yes | Color of the check box when it is selected.
Default value: **$r('sys.color.ohos_id_color_text_primary_activated')**
An invalid value is handled as the default value.| + +### selectedColor18+ + +selectedColor(resColor: Optional\) + +Sets the color of the check box when it is selected. Compared to [selectedColor](#selectedcolor), this API supports the **undefined** type for the **resColor** parameter. + +**Widget capability**: This API can be used in ArkTS widgets since API version 18. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| resColor | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[ResourceColor](ts-types.md#resourcecolor)> | Yes | Color of the check box when it is selected.
If **resColor** is set to **undefined**, the default value **$r('sys.color.ohos_id_color_text_primary_activated')** is used.
An invalid value is handled as the default value.| ### unselectedColor10+ -unselectedColor(value: Optional\) +unselectedColor(value: ResourceColor) Sets the border color of the check box when it is not selected. @@ -96,11 +135,27 @@ Sets the border color of the check box when it is not selected. | Name| Type | Mandatory| Description | | ------ | ------------------------------------------ | ---- | -------------------------- | -| value | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[ResourceColor](ts-types.md#resourcecolor)> | Yes | Border color of the check box when it is not selected.
Default value: **$r('sys.color.ohos_id_color_switch_outline_off')**| +| value | [ResourceColor](ts-types.md#resourcecolor) | Yes | Border color of the check box when it is not selected.
Default value: **$r('sys.color.ohos_id_color_switch_outline_off')**| + +### unselectedColor18+ + +unselectedColor(resColor: Optional\) + +Sets the border color of the check box when it is not selected. Compared to [unselectedColor](#unselectedcolor10)10+, this API supports the **undefined** type for the **resColor** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| resColor | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[ResourceColor](ts-types.md#resourcecolor)> | Yes | Border color of the check box when it is not selected.
If **resColor** is set to **undefined**, the default value **$r('sys.color.ohos_id_color_switch_outline_off')** is used.| ### mark10+ -mark(value: Optional\) +mark(value: MarkStyle) Sets the check mark style of the check box. @@ -112,11 +167,27 @@ Sets the check mark style of the check box. | Name| Type | Mandatory| Description | | ------ | -------------------------------------------- | ---- | ------------------------------------------------------------ | -| value | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[MarkStyle](ts-types.md#markstyle10)> | Yes | Check mark style of the check box. Since API version 12, if **indicatorBuilder** is set, the content configured in **indicatorBuilder** will be displayed accordingly.
Default value: {
strokeColor : `$r('sys.color.ohos_id_color_foreground_contrary')`,
strokeWidth: `$r('sys.float.ohos_id_checkbox_stroke_width')`,
size: '20vp'
} | +| value | [MarkStyle](ts-types.md#markstyle10) | Yes | Check mark style of the check box. Since API version 12, if **indicatorBuilder** is set, the style is determined by **indicatorBuilder**.
Default value: {
strokeColor : `$r('sys.color.ohos_id_color_foreground_contrary')`,
strokeWidth: `$r('sys.float.ohos_id_checkbox_stroke_width')`,
size: '20vp'
} | + +### mark18+ + +mark(style: Optional\) + +Sets the check mark style of the check box. Compared to [mark](#mark10)10+, this API supports the **undefined** type for the **style** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| style | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[MarkStyle](ts-types.md#markstyle10)> | Yes | Check mark style of the check box. If **indicatorBuilder** is set, the style is determined by **indicatorBuilder**.
If **style** is set to **undefined**, the default value is used: {
strokeColor : `$r('sys.color.ohos_id_color_foreground_contrary')`,
strokeWidth: `$r('sys.float.ohos_id_checkbox_stroke_width')`,
size: '20vp'
} | ### shape11+ -shape(value: Optional\) +shape(value: CheckBoxShape) Sets the shape of the check box. @@ -128,13 +199,31 @@ Sets the shape of the check box. **Parameters** +| Name| Type | Mandatory| Description | +| ------ | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | +| value | [CheckBoxShape](ts-appendix-enums.md#checkboxshape11) | Yes | Shape of the check box.
Default value: **CheckBoxShape.CIRCLE**| + +### shape18+ + +shape(shape: Optional\) + +Sets the shape of the check box. Compared to [shape](#shape11)11+, this API supports the **undefined** type for the **shape** parameter. + +**Widget capability**: This API can be used in ArkTS widgets since API version 18. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| value | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[CheckBoxShape](ts-appendix-enums.md#checkboxshape11)> | Yes | Shape of the check box.
Default value: **CheckBoxShape.CIRCLE**| +| shape | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[CheckBoxShape](ts-appendix-enums.md#checkboxshape11)> | Yes | Shape of the check box.
If **shape** is set to **undefined**, the default value **CheckBoxShape.CIRCLE** is used.| ### contentModifier12+ -contentModifier(modifier: Optional>) +contentModifier(modifier: ContentModifier\) Creates a content modifier. @@ -146,15 +235,31 @@ Creates a content modifier. | Name| Type | Mandatory| Description | | ------ | --------------------------------------------- | ---- | ------------------------------------------------ | -| modifier | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[ContentModifier\](#checkboxconfiguration12)> | Yes | Content modifier to apply to the check box.
**modifier**: content modifier. You need a custom class to implement the **ContentModifier** API.| +| modifier | [ContentModifier\](#checkboxconfiguration12) | Yes | Content modifier to apply to the check box.
**modifier**: content modifier. You need a custom class to implement the **ContentModifier** API.| + +### contentModifier18+ + +contentModifier(modifier: Optional>) + +Creates a content modifier. Compared to [contentModifier](#contentmodifier12)12+, this API supports the **undefined** type for the **modifier** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| modifier | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[ContentModifier\](#checkboxconfiguration12)> | Yes | Content modifier to apply to the check box.
**modifier**: content modifier. You need a custom class to implement the **ContentModifier** API.
If **modifier** is set to **undefined**, no content modifier is used.| ## Events -In addition to the [universal events](ts-universal-events-click.md), the following attributes are supported. +In addition to the [universal events](ts-component-general-events.md), the following events are supported. ### onChange -onChange(callback: Optional\) +onChange(callback: OnCheckboxChangeCallback) Invoked when the selected state of the check box changes. @@ -168,17 +273,35 @@ Invoked when the selected state of the check box changes. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------- | ---- | ---------------- | -| callback | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[OnCheckboxChangeCallback](#oncheckboxchangecallback14)> | Yes | Callback used to return the selected state.| +| callback | [OnCheckboxChangeCallback](#oncheckboxchangecallback18) | Yes | Callback used to return the selected state.| + +### onChange18+ + +onChange(callback: Optional\) + +Invoked when the selected state of the check box changes. Compared to [onChange](#onchange), this API supports the **undefined** type for the **callback** parameter. + +**Widget capability**: This API can be used in ArkTS widgets since API version 18. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| callback | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[OnCheckboxChangeCallback](#oncheckboxchangecallback18)> | Yes | Callback used to return the selected state.
If **callback** is set to **undefined**, the callback function is not used.| -## OnCheckboxChangeCallback14+ +## OnCheckboxChangeCallback18+ type OnCheckboxChangeCallback = (value: boolean) => void Represents the callback invoked when the selected state of the check box changes. -**Widget capability**: This API can be used in ArkTS widgets since API version 14. +**Widget capability**: This API can be used in ArkTS widgets since API version 18. -**Atomic service API**: This API can be used in atomic services since API version 14. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -200,7 +323,7 @@ You need a custom class to implement the **ContentModifier** API. | ------ | ------ | ------ |-------------------------------- |-------------------------------- | | name | string | No| No|Name of the check box.| | selected | boolean| No| No| Whether the check box is selected.
If the **select** attribute is not set, the default value **false** is used.
If the **select** attribute is set, the attribute value is used here.| -| triggerChange |Callback\| No| No|Changes the selected state of the check box.| +| triggerChange |Callback\| No| No|Changes the selected state of the check box.
The value **true** means that the check box changes from unselected to selected, and **false** means that the check box changes from selected to unselected.| ## Example @@ -214,7 +337,7 @@ This example shows how to set **CheckBoxShape** to implement check boxes in circ @Component struct CheckboxExample { build() { - Flex({ justifyContent: FlexAlign.SpaceAround }) { + Flex({ justifyContent: FlexAlign.SpaceEvenly }) { Checkbox({ name: 'checkbox1', group: 'checkboxGroup' }) .select(true) .selectedColor(0xed6f21) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-checkboxgroup.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-checkboxgroup.md index a89aa84c49ad2440faba12838e0caf53df9fd93b..9ec505e0ab6453db670ef5a1aac170e6e2f47cd9 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-checkboxgroup.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-checkboxgroup.md @@ -44,15 +44,16 @@ When this API is used with components that come with a pre-loading mechanism, su ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### selectAll -selectAll(value: Optional\) +selectAll(value: boolean) Sets whether to select all. If the **select** attribute is set for a [Checkbox](ts-basic-components-checkbox.md) component in the same group, the setting of the **Checkbox** has a higher priority. Since API version 10, this attribute supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md). +Since API version 18, this attribute supports two-way binding through [!!](../../../quick-start/arkts-new-binding.md#two-way-binding-between-built-in-component-parameters). **Widget capability**: Since API version 9, this feature is supported in ArkTS widgets. @@ -62,15 +63,35 @@ Since API version 10, this attribute supports two-way binding through [$$](../.. **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------- | ---- | ---------------------------- | -| value | [Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Whether to select all.
Default value: **false**| +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------------------------------------ | +| value | boolean | Yes | Whether to select all.
Default value: **false**
**true**: Select all check boxes in the group. **false**: Do not select any check box in the group.| + +### selectAll18+ + +selectAll(isAllSelected: Optional\) + +Sets whether to select all. If the **select** attribute is set for a [Checkbox](ts-basic-components-checkbox.md) component in the same group, the setting of the **Checkbox** has a higher priority. Compared to [selectAll](#selectall), this API supports the **undefined** type for the **isAllSelected** parameter. + +This attribute supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md) or [!!](../../../quick-start/arkts-new-binding.md). + +**Widget capability**: This API can be used in ArkTS widgets since API version 18. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| isAllSelected | [Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Whether to select all.
If **isAllSelected** is set to **undefined**, the default value **false** is used.
**true**: Select all check boxes in the group. **false**: Do not select any check box in the group.| ### selectedColor -selectedColor(value: Optional\) +selectedColor(value: ResourceColor) -Sets the color of the selected check box. +Sets the color of the selected check box. **Widget capability**: Since API version 9, this feature is supported in ArkTS widgets. @@ -82,11 +103,29 @@ Sets the color of the selected check box. | Name| Type | Mandatory| Description | | ------ | ------------------------------------------ | ---- | ------------------------------------------------------------ | -| value | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[ResourceColor](ts-types.md#resourcecolor)> | Yes | Color of the selected check box.
Default value: **$r('sys.color.ohos_id_color_text_primary_activated')**
An invalid value is handled as the default value.| +| value | [ResourceColor](ts-types.md#resourcecolor) | Yes | Color of the selected check box.
Default value: **$r('sys.color.ohos_id_color_text_primary_activated')**
An invalid value is handled as the default value.| + +### selectedColor18+ + +selectedColor(resColor: Optional\) + +Sets the color of the selected check box. Compared to [selectedColor](#selectedcolor), this API supports the **undefined** type for the **resColor** parameter. + +**Widget capability**: This API can be used in ArkTS widgets since API version 18. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| resColor | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[ResourceColor](ts-types.md#resourcecolor)> | Yes | Color of the selected check box.
If **resColor** is set to **undefined**, the default value **$r('sys.color.ohos_id_color_text_primary_activated')** is used.
An invalid value is handled as the default value.| ### unselectedColor10+ -unselectedColor(value: Optional\) +unselectedColor(value: ResourceColor) Sets the border color of the check box when it is not selected. @@ -96,13 +135,29 @@ Sets the border color of the check box when it is not selected. **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------------------------ | ---- | -------------------- | -| value | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[ResourceColor](ts-types.md#resourcecolor)> | Yes | Border color of the check box when it is not selected.
Default value: **$r('sys.color.ohos_id_color_switch_outline_off')**| +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------ | ---- | ------------------------------------------------------------ | +| value | [ResourceColor](ts-types.md#resourcecolor) | Yes | Border color of the check box when it is not selected.
Default value: **$r('sys.color.ohos_id_color_switch_outline_off')**| + +### unselectedColor18+ + +unselectedColor(resColor: Optional\) + +Sets the border color of the check box when it is not selected. Compared to [unselectedColor](#unselectedcolor10)10+, this API supports the **undefined** type for the **resColor** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| resColor | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[ResourceColor](ts-types.md#resourcecolor)> | Yes | Border color of the check box when it is not selected.
If **resColor** is set to **undefined**, the default value **$r('sys.color.ohos_id_color_switch_outline_off')** is used.| ### mark10+ -mark(value: Optional\) +mark(value: MarkStyle) Sets the check mark style of the check box. @@ -112,13 +167,29 @@ Sets the check mark style of the check box. **Parameters** -| Name| Type | Mandatory| Description | -| ------ | --------------------------------- | ---- | -------------------- | -| value | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[MarkStyle](ts-types.md#markstyle10)> | Yes | Check mark style of the check box.| +| Name| Type | Mandatory| Description | +| ------ | -------------------------------------------- | ---- | -------------------- | +| value | [MarkStyle](ts-types.md#markstyle10) | Yes | Check mark style of the check box.| + +### mark18+ + +mark(style: Optional\) + +Sets the check mark style of the check box. Compared to [mark](#mark10)10+, this API supports the **undefined** type for the **style** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| style | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[MarkStyle](ts-types.md#markstyle10)> | Yes | Check mark style of the check box.
If **style** is set to **undefined**, the previous value is retained.| ### checkboxShape12+ -checkboxShape(value: Optional\) +checkboxShape(value: CheckBoxShape) Sets the check box shape of the check box group. @@ -130,17 +201,35 @@ Sets the check box shape of the check box group. **Parameters** +| Name| Type | Mandatory| Description | +| ------ | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | +| value | [CheckBoxShape](ts-appendix-enums.md#checkboxshape11) | Yes | Check box shape of the check box group.
Default value: **CheckBoxShape.CIRCLE**
**NOTE**
The shape of the check box group component follows the settings configured.
All check boxes within the check box group that do not have an individual shape set will conform to the shape of the check box group.
If a check box within the check box group has an individual shape set, that shape takes precedence over the check box group's shape.| + +### checkboxShape18+ + +checkboxShape(shape: Optional\) + +Sets the check box shape of the check box group. Compared to [checkboxShape](#checkboxshape12)12+, this API supports the **undefined** type for the **shape** parameter. + +**Widget capability**: This API can be used in ArkTS widgets since API version 18. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| value | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[CheckBoxShape](ts-appendix-enums.md#checkboxshape11)> | Yes | Check box shape of the check box group.
Default value: **CheckBoxShape.CIRCLE**
**NOTE**
The shape of the check box group component follows the settings configured.
All check boxes within the check box group that do not have an individual shape set will conform to the shape of the check box group.
If a check box within the check box group has an individual shape set, that shape takes precedence over the check box group's shape.| +| shape | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[CheckBoxShape](ts-appendix-enums.md#checkboxshape11)> | Yes | Check box shape of the check box group.
If **shape** is set to **undefined**, the default value **CheckBoxShape.CIRCLE** is used.
**NOTE**
The shape of the check box group component follows the settings configured.
All check boxes within the check box group that do not have an individual shape set will conform to the shape of the check box group.
If a check box within the check box group has an individual shape set, that shape takes precedence over the check box group's shape.| ## Events -In addition to the [universal events](ts-universal-events-click.md), the following events are supported. +In addition to the [universal events](ts-component-general-events.md), the following events are supported. ### onChange -onChange(callback: Optional\) +onChange(callback: OnCheckboxGroupChangeCallback) Triggered when the selected status of the check box group or any check box wherein changes. @@ -154,17 +243,35 @@ Triggered when the selected status of the check box group or any check box where | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------ | -| callback | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[OnCheckboxGroupChangeCallback](#oncheckboxgroupchangecallback14)> | Yes | Information about the check box group.| +| callback | [OnCheckboxGroupChangeCallback](#oncheckboxgroupchangecallback18) | Yes | Information about the check box group.| + +### onChange18+ + +onChange(callback: Optional\) + +Triggered when the selected status of the check box group or any check box wherein changes. Compared to [onChange](#onchange), this API supports the **undefined** type for the **callback** parameter. + +**Widget capability**: This API can be used in ArkTS widgets since API version 18. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| callback | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[OnCheckboxGroupChangeCallback](#oncheckboxgroupchangecallback18)> | Yes | Information about the check box group.
If **callback** is set to **undefined**, the callback function is not used.| -## OnCheckboxGroupChangeCallback14+ +## OnCheckboxGroupChangeCallback18+ type OnCheckboxGroupChangeCallback = (value: CheckboxGroupResult) => void Information about the check box group. -**Widget capability**: This API can be used in ArkTS widgets since API version 14. +**Widget capability**: This API can be used in ArkTS widgets since API version 18. -**Atomic service API**: This API can be used in atomic services since API version 14. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-component3d.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-component3d.md index 6f9007794b85d1b8ecad5ebf0a7b3d8657901ad2..1432a07fdd1dc5839138aa352d1c77152d6689cf 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-component3d.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-component3d.md @@ -65,7 +65,7 @@ Represents a 3D scene object. ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### environment @@ -146,7 +146,7 @@ Set the animation parameters used for custom rendering. | Name| Type | Mandatory| Description | | ------ | -------------- | ---- | -------------------------- | -| buffer | Array | Yes | Animation parameters used for custom rendering.| +| buffer | Array | Yes | Animation parameters used for custom rendering.Array length range: [0, 1048576]| ### renderWidth @@ -166,7 +166,7 @@ The rendering resolution cannot be dynamically changed after the component is cr | Name| Type | Mandatory| Description | | ------ | ------------------------------------ | ---- | -------------------- | -| value | [Dimension](ts-types.md#dimension10) | Yes | Width of the 3D rendering resolution.| +| value | [Dimension](ts-types.md#dimension10) | Yes | Width of the 3D rendering resolution. Currently, only **Dimension.Percentage** can be set, with the value range of [0, 100%].| ### renderHeight @@ -186,11 +186,11 @@ The rendering resolution cannot be dynamically changed after the component is cr | Name| Type | Mandatory| Description | | ------ | ------------------------------------ | ---- | -------------------- | -| value | [Dimension](ts-types.md#dimension10) | Yes | Height of the 3D rendering resolution.| +| value | [Dimension](ts-types.md#dimension10) | Yes | Height of the 3D rendering resolution. Currently, only **Dimension.Percentage** can be set, with the value range of [0, 100%].| ## Events -The [universal events](ts-universal-events-click.md) are supported. +The [universal events](ts-component-general-events.md) are supported. ## Example You can preview how this component looks on a real device, but not in DevEco Studio Previewer.
diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-containerspan.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-containerspan.md index c64fa4e9b9f0f4e4b26cb4a1c36d52e30fb6794d..d106a0d29bbc9ced949787bee32edbde80e131ba 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-containerspan.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-containerspan.md @@ -56,11 +56,12 @@ Creates an attribute modifier. ## Events -The [universal events](ts-universal-events-click.md) are not supported. +The [universal events](ts-component-general-events.md) are not supported. ## Example +### Example 1: Setting the Background Style -This example demonstrates the effect of setting a background style for text using the **textBackgroundStyle** attribute. +This example demonstrates how to set the background style for text using **textBackgroundStyle**. ```ts // xxx.ets @@ -76,7 +77,7 @@ struct Index { .height('40vp') .verticalAlign(ImageSpanAlignment.CENTER) Span(' Hello World ! ').fontSize('16fp').fontColor(Color.White) - }.textBackgroundStyle({color: "#7F007DFF", radius: "12vp"}) + }.textBackgroundStyle({ color: "#7F007DFF", radius: "12vp" }) } }.width('100%').alignItems(HorizontalAlign.Center) } @@ -84,3 +85,41 @@ struct Index { ``` ![imagespan](figures/container_span.png) + +### Example 2: Setting the Background Style Using attributeModifier + +This example demonstrates how to set the background style for text using **attributeModifier**. + +```ts +// xxx.ets +import { ContainerSpanModifier } from '@ohos.arkui.modifier' + +class MyContainerSpanModifier extends ContainerSpanModifier { + applyNormalAttribute(instance: ContainerSpanAttribute): void { + super.applyNormalAttribute?.(instance); + this.textBackgroundStyle({ color: "#7F007DFF", radius: "12vp" }) + } +} + +@Entry +@Component +struct ContainerSpanModifierExample { + @State containerSpanModifier: ContainerSpanModifier = new MyContainerSpanModifier() + + build() { + Column() { + Text() { + ContainerSpan() { + ImageSpan($r('app.media.app_icon')) + .width('40vp') + .height('40vp') + .verticalAlign(ImageSpanAlignment.CENTER) + Span(' I\'m ContainerSpan attributeModifier ').fontSize('16fp').fontColor(Color.White) + }.attributeModifier(this.containerSpanModifier as MyContainerSpanModifier) + } + }.width('100%').alignItems(HorizontalAlign.Center) + } +} +``` + +![imagespan](figures/container_attributeModifier.png) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-datapanel.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-datapanel.md index eee4102eeb7f5464450d747658f8347906de5694..cbb9f18e5a255737c6a9e1dce77659b042816eda 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-datapanel.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-datapanel.md @@ -59,7 +59,7 @@ DataPanel(options: DataPanelOptions) ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### closeEffect @@ -77,7 +77,7 @@ Sets whether to disable the rotation and shadow effects for the component. This | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------------------------------ | -| value | boolean | Yes | Whether to disable the rotation and shadow effects for the component.
Default value: **false**| +| value | boolean | Yes | Whether to disable the rotation and shadow effects for the component.
Default value: **false**
**false**: Disable the rotation and shadow effects.**true**: Enable the rotation and shadow effects.| ### valueColors10+ @@ -214,8 +214,8 @@ You need a custom class to implement the **ContentModifier** API. | Name | Type | Mandatory | Description | | ------ | ------ | ------ |-------------------------------- | -| values | number[] | Yes| Current values of the data panel. The maximum length is 9.| -| maxValue | number | Yes| Maximum value displayed in the data panel.
Default value: **100**| +| values | number[] | Yes| Current values of the data panel.
Value range: [0, 9]
Values less than 0 are adjusted to **0**.| +| maxValue | number | Yes| Maximum value displayed in the data panel.
Default value: **100**
**NOTE**
If the value is less than or equal to 0, **maxValue** is set to the sum of all items in the **values** array and displayed proportionally.| ## Example diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-datepicker.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-datepicker.md index cd054912cb43db7823149934824340162702247c..b74ac6ca388d4c3d5665caff707c597d1d37fb2c 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-datepicker.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-datepicker.md @@ -39,6 +39,27 @@ Creates a date picker in the given date range. | start | Date | No | Start date of the picker.
Default value: **Date('1970-1-1')** | | end | Date | No | End date of the picker.
Default value: **Date('2100-12-31')** | | selected | Date | No | Date of the selected item.
Default value: current system date
Since API version 10, this parameter supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md).| +| mode18+ | [DatePickerMode](#datepickermode18) | No | Date columns to be displayed.
Default value: **DatePickerMode.DATE**, which means to display three columns: year, month, and day. Decimal values are rounded off.
In **DatePickerDialog**, with **showTime=true**, this parameter has no effect and the default three columns for year, month, and day are displayed.| + +> **NOTE** +> +> For details about how to use **Date**, see [TimePickerOptions](ts-basic-components-timepicker.md). +> Modifying the **DatePickerOptions** properties, such as **start**, **end**, or **selected**, during the scrolling process of the **DatePicker** component may not take effect. + + +## DatePickerMode18+ + +Sets the date columns to be displayed. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name| Description| +| -------- | -------- | +| DATE | The date displays three columns: year, month, and day.| +| YEAR_AND_MONTH | The date displays two columns: year and month.| +| MONTH_AND_DAY | The date displays two columns: month and day.
In this mode, if the month changes from December to January, the year does not increment by one; if the month changes from January to December, the year does not decrement by one. The year remains fixed at the currently set value.| **Handling in the case of exceptions** @@ -64,7 +85,7 @@ The exception detection and handling with the selected date comes after that wit ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### lunar @@ -82,6 +103,22 @@ Specifies whether to display the lunar calendar. | ------ | ------- | ---- | ------------------------------------------------------------ | | value | boolean | Yes | Whether to display the lunar calendar.
- **true**: Display the lunar calendar.
- **false**: Do not display the lunar calendar.
Default value: **false**| +### lunar18+ + +lunar(isLunar: Optional\) + +Specifies whether to display the lunar calendar. Compared to [lunar](#lunar), this API supports the **undefined** type for the **isLunar** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------------------------------------ | +| isLunar | [Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Whether to display the lunar calendar.
- **true**: Display the lunar calendar.
- **false**: Do not display the lunar calendar.
If **isLunar** is set to **undefined**, the default value **false** is used.| + ### disappearTextStyle10+ disappearTextStyle(value: PickerTextStyle) @@ -98,6 +135,22 @@ Sets the text style for the top and bottom items. | ------ | --------------------------------------------- | ---- | ------------------------------------------------------------ | | value | [PickerTextStyle](#pickertextstyle10) | Yes | Font color, font size, and font weight of the top and bottom items.
Default value:
{
color: '#ff182431',
font: {
size: '14fp',
weight: FontWeight.Regular
}
} | +### disappearTextStyle18+ + +disappearTextStyle(style: Optional\) + +Sets the text style for the top and bottom items. Compared to [disappearTextStyle](#disappeartextstyle10)10+, this API supports the **undefined** type for the **style** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| style | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[PickerTextStyle](#pickertextstyle10)> | Yes | Font color, font size, and font weight of the top and bottom items.
If **style** is set to **undefined**, the default value is used:
{
color: '#ff182431',
font: {
size: '14fp',
weight: FontWeight.Regular
}
} | + ### textStyle10+ textStyle(value: PickerTextStyle) @@ -114,6 +167,22 @@ Sets the text style for all items except the top, bottom, and selected items. | ------ | --------------------------------------------- | ---- | ------------------------------------------------------------ | | value | [PickerTextStyle](#pickertextstyle10) | Yes | Font color, font size, and font weight of all items except the top, bottom, and selected items.
Default value:
{
color: '#ff182431',
font: {
size: '16fp',
weight: FontWeight.Regular
}
} | +### textStyle18+ + +textStyle(style: Optional\) + +Sets the text style for all items except the top, bottom, and selected items. Compared to [textStyle](#textstyle10)10+, this API supports the **undefined** type for the **style** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| style | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[PickerTextStyle](#pickertextstyle10)> | Yes | Font color, font size, and font weight of all items except the top, bottom, and selected items.
If **style** is set to **undefined**, the default value is used:
{
color: '#ff182431',
font: {
size: '16fp',
weight: FontWeight.Regular
}
} | + ### selectedTextStyle10+ selectedTextStyle(value: PickerTextStyle) @@ -130,6 +199,64 @@ Sets the text style for the selected item. | ------ | --------------------------------------------- | ---- | ------------------------------------------------------------ | | value | [PickerTextStyle](#pickertextstyle10) | Yes | Font color, font size, and font weight of the selected item.
Default value:
{
color: '#ff007dff',
font: {
size: '20vp',
weight: FontWeight.Medium
}
} | +### selectedTextStyle18+ + +selectedTextStyle(style: Optional\) + +Sets the text style for the selected item. Compared to [selectedTextStyle](#selectedtextstyle10)10+, this API supports the **undefined** type for the **style** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| style | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[PickerTextStyle](#pickertextstyle10)> | Yes | Font color, font size, and font weight of the selected item.
If **style** is set to **undefined**, the default value is used:
{
color: '#ff007dff',
font: {
size: '20vp',
weight: FontWeight.Medium
}
} | + +### enableHapticFeedback18+ + +enableHapticFeedback(enable: Optional\) + +Sets whether to enable haptic feedback. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name| Type | Mandatory | Description | +| ------ | --------------------------------------------- |-----|-------------------------------------------------------------------------------------| +| enable | [Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Whether to enable haptic feedback.
**true** (default): Haptic feedback is enabled.
**false**: Haptic feedback is disabled.| + +> **NOTE** +> +> To enable haptic feedback, you must declare the ohos.permission.VIBRATE permission under **requestPermissions** in the **module.json5** file of the project. +> ```json +> "requestPermissions": [ +> { +> "name": "ohos.permission.VIBRATE", +> } +> ] +> ``` + +### digitalCrownSensitivity18+ +digitalCrownSensitivity(sensitivity: Optional\) + +Sets the sensitivity to the digital crown rotation. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ----- | ---------------------------------------- | ---- | ------------------------- | +| sensitivity | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[CrownSensitivity](ts-appendix-enums.md#crownsensitivity18)> | Yes | Sensitivity to the digital crown rotation.
Default value: **CrownSensitivity.MEDIUM** | + +> **NOTE** +> +> This API is only available to circular screens on wearable devices. The component needs to obtain focus before responding to the [crown event](ts-universal-events-crown.md). + ## PickerTextStyle10+ **Atomic service API**: This API can be used in atomic services since API version 11. @@ -137,11 +264,11 @@ Sets the text style for the selected item. | Name | Type | Mandatory | Description | | ----- | ---------------------------------------- | ---- | ------------------------- | | color | [ResourceColor](ts-types.md#resourcecolor) | No | Font color. | -| font | [Font](ts-types.md#font) | No | Text style. Only the font size and font weight are supported. | +| font | [Font](ts-types.md#font) | No | Text style.| ## Events -In addition to the [universal events](ts-universal-events-click.md), the following events are supported. +In addition to the [universal events](ts-component-general-events.md), the following events are supported. ### onChange(deprecated) @@ -175,6 +302,22 @@ Triggered when a date is selected. | ------ | ---- | ---- | ------------------------------------------------------------ | | value | Date | Yes | Selected time, where the year, month, and day portions are subject to the selection, the hour and minute portions are subject to the current system time, and the second portion is always **00**.| +### onDateChange18+ + +onDateChange(callback: Optional\>) + +Triggered when a date is selected. Compared to [onDateChange](#ondatechange10)10+, this API supports the **undefined** type for the **callback** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| callback | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[Callback](ts-types.md#callback12)\> | Yes | Selected time, where the year, month, and day portions are subject to the selection, the hour and minute portions are subject to the current system time, and the second portion is always **00**.
If **callback** is set to **undefined**, the callback function is not used.| + ## DatePickerResult **Atomic service API**: This API can be used in atomic services since API version 11. @@ -183,13 +326,16 @@ Triggered when a date is selected. | Name | Type | Read Only| Optional| Description | | ----- | ------ | ---- | ---- | ------------------------------------------ | -| year | number | No | No | Year of the selected date. | -| month | number | No | No | Month of the selected date. The value ranges from 0 to 11. The value **0** indicates January, and **11** indicates December.| -| day | number | No | No | Day of the selected date. | - +| year | number | No | No | Year of the selected date.
Value range: depends on **start** and **end**. If **start** and **end** are not set, the default range is [1970, 2100]. | +| month | number | No | No | Month index of the selected date. The index is zero-based.
**0** indicates January, and **11** indicates December.
Value range: depends on **start** and **end**. If **start** and **end** are not set, the default range is [0, 11].| +| day | number | No | No | Day of the selected date.
Value range: depends on **start** and **end**. If **start** and **end** are not set, the default range is [1, 31]. | ## Example +### Example 1: Switching Between Gregorian and Lunar Calendars + +This example implements a date picker that allows users to switch between the Gregorian (solar) calendar and the lunar calendar by clicking a button. + ```ts // xxx.ets @@ -211,9 +357,6 @@ struct DatePickerExample { end: new Date('2100-1-1'), selected: this.selectedDate }) - .disappearTextStyle({color: Color.Gray, font: {size: '16fp', weight: FontWeight.Bold}}) - .textStyle({color: '#ff182431', font: {size: '18fp', weight: FontWeight.Normal}}) - .selectedTextStyle({color: '#ff0000FF', font: {size: '26fp', weight: FontWeight.Regular}}) .lunar(this.isLunar) .onDateChange((value: Date) => { this.selectedDate = value @@ -226,3 +369,86 @@ struct DatePickerExample { ``` ![datePicker](figures/DatePickerApi10.gif) + +### Example 2: Setting the Text Style + +This example shows how to customize the text style using **disappearTextStyle**, **textStyle**, and **selectedTextStyle**. + +```ts +// xxx.ets +@Entry +@Component +struct DatePickerExample { + private selectedDate: Date = new Date('2021-08-08') + + build() { + Column() { + DatePicker({ + start: new Date('1970-1-1'), + end: new Date('2100-1-1'), + selected: this.selectedDate + }) + .disappearTextStyle({ color: Color.Gray, font: { size: '16fp', weight: FontWeight.Bold } }) + .textStyle({ color: '#ff182431', font: { size: '18fp', weight: FontWeight.Normal } }) + .selectedTextStyle({ color: '#ff0000FF', font: { size: '26fp', weight: FontWeight.Regular, family: "HarmonyOS Sans", style: FontStyle.Normal } }) + .onDateChange((value: Date) => { + this.selectedDate = value + console.info('select current date is: ' + value.toString()) + }) + + }.width('100%') + } +} +``` + +![datePicker](figures/DatePickerDemo2.png) + +### Example 3: Displaying Year and Month, or Month and Day Columns + +This example demonstrates how to display year and month, or month and day columns using **mode**. + +```ts +// xxx.ets +@Entry +@Component +struct DatePickerExample { + @State isLunar: boolean = false + private selectedDate: Date = new Date('2025-01-15') + @State datePickerModeList: (DatePickerMode)[] = [ + DatePickerMode.DATE, + DatePickerMode.YEAR_AND_MONTH, + DatePickerMode.MONTH_AND_DAY, + ] + @State datePickerModeIndex: number = 0; + + build() { + Column() { + Button('Switch Calendar') + .margin({ top: 30, bottom: 30 }) + .onClick(() => { + this.isLunar = !this.isLunar + }) + DatePicker({ + start: new Date('1970-1-1'), + end: new Date('2100-1-1'), + selected: this.selectedDate, + mode:this.datePickerModeList[this.datePickerModeIndex] + }) + .lunar(this.isLunar) + .onDateChange((value: Date) => { + this.selectedDate = value + console.info('select current date is: ' + value.toString()) + }) + + Button('mode :' + this.datePickerModeIndex).margin({ top: 20 }) + .onClick(() => { + this.datePickerModeIndex++ + if(this.datePickerModeIndex >= this.datePickerModeList.length){ + this.datePickerModeIndex = 0 + } + }) + }.width('100%') + } +} +``` +![datePicker](figures/DatePickerDemo3.gif) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-divider.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-divider.md index 6d37a5d0a8df267829302d73c6a2ce77b8ab41c4..ffc68a1699b24cb75eaef932981bb6bb35f2dda8 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-divider.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-divider.md @@ -22,7 +22,7 @@ Divider() ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### vertical @@ -58,7 +58,7 @@ Sets the color of the divider. | Name| Type | Mandatory| Description | | ------ | ------------------------------------------ | ---- | ------------------------------------- | -| value | [ResourceColor](ts-types.md#resourcecolor) | Yes | Color of the divider.
Default value: **'\#33182431'**| +| value | [ResourceColor](ts-types.md#resourcecolor) | Yes | Color of the divider.
Default value: **'\#33182431'**
You can set a common divider color using [WithTheme](ts-container-with-theme.md#withtheme).| ### strokeWidth @@ -99,6 +99,8 @@ Sets the cap style of the divider. ## Example +This example demonstrates how to define the style of a divider, including its direction, color, and width. + ```ts // xxx.ets @Entry diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-formcomponent-sys.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-formcomponent-sys.md index 67820ce1f37289f9301ae55fa60fde0877d024d0..27ced2051771c9105a330f63f6ae800393c77797 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-formcomponent-sys.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-formcomponent-sys.md @@ -56,8 +56,8 @@ Represents the parameters for obtaining a widget ID (**formId**) when querying o | Name | Type | Mandatory| Description | | --------- | ------------------------------- | ---- | ----------------------------------------------------------------------- | | id | number | Yes | Widget ID of the number type.
**NOTE**
If the obtained ID is **-1**, the ID is greater than or equal to 2^53. In this case, you need to use **idString** to obtain the ID. | -| idString | string | Yes | Widget ID of the string type. | -| isLocked16+ |boolean | Yes | Whether the widget is [locked](../../apis-form-kit/js-apis-app-form-formHost-sys.md#updateformlockedstate16). The value **true** means that the widget is locked, and **false** means the opposite. | +| idString | string | Yes | Widget ID of the string type. | +| isLocked18+ |boolean | Yes | Whether the widget is [locked](../../apis-form-kit/js-apis-app-form-formHost-sys.md#updateformlockedstate18). The value **true** means that the widget is locked, and **false** means the opposite. | ## FormDimension @@ -70,8 +70,8 @@ Represents the parameters for obtaining a widget ID (**formId**) when querying o | Dimension_2_19+ | 2 x 1 widget.| | Dimension_1_111+ | 1 x 1 widget.| | Dimension_6_412+ | 6 x 4 widget.| -| Dimension_2_314+ | 2 x 3 widget. Available for wearable devices.| -| Dimension_3_314+ | 3 x 3 widget. Available for wearable devices.| +| Dimension_2_318+ | 2 x 3 widget. Available for wearable devices.| +| Dimension_3_318+ | 3 x 3 widget. Available for wearable devices.| ## FormRenderingMode11+ | Name | Description | @@ -285,4 +285,3 @@ struct CardExample { ``` ![Form](figures/form.png) - \ No newline at end of file diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-gauge.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-gauge.md index 19f47fa99539e7285988d5cd26826b78a6820372..a67582811506fd95ebd50235122cfd34543e1f66 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-gauge.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-gauge.md @@ -47,13 +47,13 @@ Creates a gauge. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | number | Yes| Current value of the gauge, that is, the position to which the indicator points in the gauge. It is used as the initial value of the gauge when it is created.
**NOTE**
If the value is not within the range defined by the **min** and **max** parameters, the value of **min** is used.| -| min | number | No| Minimum value of the current data segment.
Default value: **0**| -| max | number | No| Maximum value of the current data segment.
Default value: **100**
**NOTE**
If the value of **max** is less than that of **min**, the default values **0** and **100** are used.
The values of **max** and **min** can be negative numbers.| +| value8+ | number | Yes| Current value of the gauge, that is, the position to which the indicator points in the gauge. It is used as the initial value of the gauge when it is created.
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11.
**NOTE**
If the value is not within the range defined by the **min** and **max** parameters, the value of **min** is used.| +| min8+ | number | No| Minimum value of the current data segment.
Default value: **0**
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| max8+ | number | No| Maximum value of the current data segment.
Default value: **100**
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11.
**NOTE**
If the value of **max** is less than that of **min**, the default values **0** and **100** are used.
The values of **max** and **min** can be negative numbers.| ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### value @@ -153,7 +153,7 @@ Sets the stroke width of the gauge. | Name| Type | Mandatory| Description | | ------ | ---------------------------- | ---- | ------------------------------------------------------------ | -| length | [Length](ts-types.md#length) | Yes | Stroke width of the gauge.
Default value: **4**
Unit: vp
**NOTE**
A value less than 0 evaluates to the default value.
The value cannot be in percentage.| +| length | [Length](ts-types.md#length) | Yes | Stroke width of the gauge.
Default value: **4**
Unit: vp
**NOTE**
If a value less than 0 is set, the default value is used.
If the value exceeds the maximum value, the radius of the gauge, the maximum value is used.
The value cannot be in percentage.| ### description11+ @@ -278,7 +278,8 @@ This example demonstrates how to implement a multi-color gauge using the **color @Entry @Component struct Gauge1 { - @Builder descriptionBuilder() { + @Builder + descriptionBuilder() { Text('Description') .maxFontSize('30sp') .minFontSize("10.0vp") @@ -338,7 +339,7 @@ struct Gauge1 { ``` ![gauge](figures/gauge-image1.png) -### Example 1: Implementing a Single-color Gauge +### Example 2: Implementing a Single-Color Gauge This example demonstrates how to implement a single-color gauge using the **colors** attribute. @@ -346,7 +347,8 @@ This example demonstrates how to implement a single-color gauge using the **colo @Entry @Component struct Gauge2 { - @Builder descriptionBuilderImage() { + @Builder + descriptionBuilderImage() { Image($r('sys.media.ohos_ic_public_clock')).width(72).height(72) } @@ -388,7 +390,8 @@ This example illustrates how to configure a custom description area using the ** @Entry @Component struct Gauge3 { - @Builder descriptionBuilder() { + @Builder + descriptionBuilder() { Text('Description') .maxFontSize('30sp') .minFontSize("10.0vp") @@ -749,3 +752,35 @@ struct GaugeExample { } ``` ![gauge](figures/gauge-privacysensitive.gif) + +### Example 10: Implementing a Custom Indicator + +This example demonstrates how to implement a custom indicator using **indicator**. You can import an SVG image to replace the default indicator. + +```ts +@Entry +@Component +struct Gauge2 { + build() { + Column() { + Gauge({ value: 50, min: 1, max: 100 }) + .indicator({ space: 10, icon: $r('app.media.indicator') }) + .startAngle(210) + .endAngle(150) + .colors('#cca5d61d') + .width('80%') + .height('80%') + .strokeWidth(18) + .padding(18) + }.margin({ top: 40 }).width('100%').height('100%') + } +} +``` +```xml + + + + +``` +![gauge](figures/gauge-image8.png) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-image.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-image.md index 611d7f9ed03a0188ca9d3689cf2266acc2d8bb5b..d66283b8cc813d226c8f79274486246a3d5eed35 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-image.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-image.md @@ -1,6 +1,6 @@ # Image -The **Image** component is usually used to display images in applications. It supports images in PNG, JPG, JPEG, BMP, SVG, WEBP, GIF, or HEIF format from the following data sources: [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7), [ResourceStr](ts-types.md#resourcestr), or [DrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#drawabledescriptor). +The **Image** component is usually used to display images in applications. It supports images in PNG, JPG, JPEG, BMP, SVG, WEBP, GIF, or HEIF format from the following data sources: [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7), [ResourceStr](ts-types.md#resourcestr), or [DrawableDescriptor](#drawabledescriptor10). > **NOTE** > @@ -11,6 +11,8 @@ The **Image** component is usually used to display images in applications. It su > The **Image** component supports SVG image sources. For details about SVG tags, see [SVG Tags](./ts-basic-svg.md). > > For animated images, animation playback is disabled by default and depends on the visibility of the **Image** component. When the component is visible, the animation is started through the callback. When the component is invisible, the animation is stopped. The visibility status of the **Image** component can be identified through the [onVisibleAreaChange](./ts-universal-component-visible-area-change-event.md#onvisibleareachange) event. If the value of **ratios** is greater than 0, the component is visible. +> +> Since API version 18, the **Image** component offloads the tasks of downloading and caching online images to the [download and cache module](../../apis-basic-services-kit/js-apis-request-cacheDownload.md). This module provides a pre-download API that allows you to download images before using the **Image** component. Once the component is created, it requests the image data from the download and cache module. This way, the display performance of the **Image** component is improved. Regarding cache locations:
- For versions before API version 18, the cache is stored in the local sandbox directory of the application.
- For versions API version 18 and later, the cache is stored in the cache directory under the application's root directory. ## Required Permissions @@ -46,7 +48,7 @@ If the **Image** component does not have its width and height set, its size adap | Name | Type | Mandatory | Description | | ---- | ---------------------------------------- | ---- | ---------------------------------------- | -| src | [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) \| [ResourceStr](ts-types.md#resourcestr)\| [DrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#drawabledescriptor) | Yes | Data source of the image. Local and online sources are supported. For details about how to reference an image, see [Loading Image Resources](../../../ui/arkts-graphics-display.md#loading-image-resources).
1. **PixelMap**: an array of pixels storing graphical information. This type is usually used in image editing scenarios.
2. **ResourceStr**: a string or a **Resource** object.
The string format can be used to load local images and, more frequently, online images. When using an image referenced using a relative path, for example, **Image("common/test.jpg")**, the **Image** component cannot be called across bundles or modules. If an image needs to be used globally, you are advised to use the **Resource** format. The following types of strings are supported:
- Base64 strings in the format of data:image/[png\|jpeg\|bmp\|webp\|heif];base64,[base64 data], where *[base64 data]* is a Base64 string.
- Strings with the **file://** prefix, that is, [application sandbox URIs](../../apis-core-file-kit/js-apis-file-fileuri.md#constructor10): **file://\/\**, When accessing a path that contains special characters, use [fileUri.getUriFromPath(path)](../../apis-core-file-kit/js-apis-file-fileuri.md#fileurigeturifrompath) to transform the path into a URI that can handle special symbols. In addition, ensure that the application has the read permission to the files in the specified path.
The **Resource** format allows for access across bundles and modules. It is recommended for accessing local images.
3. **DrawableDescriptor**: an object created when the passed resource ID or name belongs to a common image. If the [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12) type is passed in, the PixelMap array animation can be played.
**NOTE**
- ArkTS widgets support GIF animations, but the animations only play once on display.
- ArkTS widgets do not support the strings with the **http:/\/** or **file:/\/** prefix.
- ArkTS widgets do not support the [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) type.
- When a local image is being loaded, any modification or replacement of it may cause application crash. Therefore, to overwrite an image file, delete the file first and then create one with the same name.
- Online images must support the RFC 9113 standard to be successfully loaded.
- If images to download are greater than 10 MB or in large number, consider using [HTTP](../../../network/http-request.md) to preload them to improve the image loading performance and facilitate data management on the application side.
- Directly passing a URL to the **Image** component can lead to potential performance issues, such as: (1) Large images cannot be preloaded, resulting in longer display times for white blocks; (2) Small images set to load synchronously can block the UI thread in weak network environments, causing screen freezing issues; (3) In fast-scrolling water flow layouts, images that are about to be displayed could not be preloaded, leading to more white blocks during scrolling. Performance issues manifest differently in different scenarios. To address these issues, decouple the network downloading part from the display of the **Image** component, which allows for preloading or asynchronous downloading.
- To display an SVG image that does not have the native size, you must set the width and height for the **Image** component.
- If an SVG image references another local image through the Image tag, the referenced image cannot be in .svg or .gif format.
- When the **src** attribute changes from a valid value to an invalid one, the image remains unchanged.
- If this parameter is of the [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) type, the **Image** component can detect data changes only when the reference to the **PixelMap** object is updated to point to a new instance. If modifications are made to the content of the **PixelMap** object, such as pixel values, but the reference to the object remains the same, the **Image** component will not recognize these modifications as a data change.| +| src | [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) \| [ResourceStr](ts-types.md#resourcestr)\| [DrawableDescriptor](#drawabledescriptor10) | Yes | Data source of the image. Local and online sources are supported. For details about how to reference an image, see [Loading Image Resources](../../../ui/arkts-graphics-display.md#loading-image-resources).
1. **PixelMap**: an array of pixels storing graphical information. This type is usually used in image editing scenarios.
2. **ResourceStr**: a string or a **Resource** object.
The string type can be used to load local images and, more frequently, online images. When using an image referenced using a relative path, for example, **Image("common/test.jpg")**, the **Image** component cannot be called across bundles or modules. If an image needs to be used globally, you are advised to use the **Resource** format. The following types of strings are supported:
- Base64 strings in the format of data:image/[png\|jpeg\|bmp\|webp\|heif];base64,[base64 data], where *[base64 data]* is a Base64 string.
- Strings with the **file://** prefix, that is, [application sandbox URIs](../../apis-core-file-kit/js-apis-file-fileuri.md#constructor10): **file://\/\**, When accessing a path that contains special characters, use [fileUri.getUriFromPath(path)](../../apis-core-file-kit/js-apis-file-fileuri.md#fileurigeturifrompath) to transform the path into a URI that can handle special symbols. In addition, ensure that the application has the read permission to the files in the specified path.
The **Resource** format allows for access across bundles and modules. It is recommended for accessing local images.
3. **DrawableDescriptor**: an object created when the passed resource ID or name belongs to a common image. If the [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12) type is passed in, the PixelMap array animation can be played.
**NOTE**
- ArkTS widgets support GIF animations, but the animations only play once on display.
- ArkTS widgets do not support the strings with the **http:/\/** or **file:/\/** prefix.
- When a local image is being loaded, any modification or replacement of it may cause application crash. Therefore, to overwrite an image file, delete the file first and then create one with the same name.
- Online images must support the RFC 9113 standard to be successfully loaded.
- If images to download are greater than 10 MB or in large number, consider using [HTTP](../../../network/http-request.md) to preload them to improve the image loading performance and facilitate data management on the application side.
- Directly passing a URL to the **Image** component can lead to potential performance issues, such as: (1) Large images cannot be preloaded, resulting in longer display times for white blocks; (2) Small images set to load synchronously can block the UI thread in weak network environments, causing screen freezing issues; (3) In fast-scrolling water flow layouts, images that are about to be displayed could not be preloaded, leading to more white blocks during scrolling. Performance issues manifest differently in different scenarios. To address these issues, decouple the network downloading part from the display of the **Image** component, which allows for preloading or asynchronous downloading.
- To display an SVG image that does not have the native size, you must set the width and height for the **Image** component.
- If an SVG image references another local image through the Image tag, the referenced image cannot be in .svg or .gif format.
- When the **src** attribute changes from a valid value to an invalid one, the image remains unchanged.
- If this parameter is of the [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) type, the **Image** component can detect data changes only when the reference to the **PixelMap** object is updated to point to a new instance. If modifications are made to the content of the **PixelMap** object, such as pixel values, but the reference to the object remains the same, the **Image** component will not recognize these modifications as a data change.| ### Image12+ @@ -64,7 +66,7 @@ Obtains an image. The [ImageContent](#imagecontent12) type allows you to specify | Name | Type | Mandatory | Description | | ---- | ---------------------------------------- | ---- | ---------------------------------------- | -| src | [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) \| [ResourceStr](ts-types.md#resourcestr)\| [DrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#drawabledescriptor)\| [ImageContent](#imagecontent12) | Yes | Data source of the image. Local and online sources are supported. For details about how to reference an image, see [Loading Image Resources](../../../ui/arkts-graphics-display.md#loading-image-resources).
1. **PixelMap**: an array of pixels storing graphical information. This type is usually used in image editing scenarios.
2. **ResourceStr**: a string or a **Resource** object.
The string format can be used to load local images and, more frequently, online images. When using an image referenced using a relative path, for example, **Image("common/test.jpg")**, the **Image** component cannot be called across bundles or modules. If an image needs to be used globally, you are advised to use the **Resource** format. The following types of strings are supported:
- Base64 strings in the format of data:image/[png\|jpeg\|bmp\|webp\|heif];base64,[base64 data], where *[base64 data]* is a Base64 string.
- Strings with the **file://** prefix, that is, [application sandbox URIs](../../apis-core-file-kit/js-apis-file-fileuri.md#constructor10): **file://\/\**, When accessing a path that contains special characters, use [fileUri.getUriFromPath(path)](../../apis-core-file-kit/js-apis-file-fileuri.md#fileurigeturifrompath) to transform the path into a URI that can handle special symbols. In addition, ensure that the application has the read permission to the files in the specified path.
The **Resource** format allows for access across bundles and modules. It is recommended for accessing local images.
3. **DrawableDescriptor**: an object created when the passed resource ID or name belongs to a common image. If the [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12) type is passed in, the PixelMap array animation can be played.
4. [ImageContent](#imagecontent12): image content.
**NOTE**
- ArkTS widgets support GIF animations, but the animations only play once on display.
- ArkTS widgets do not support the strings with the **http:/\/** or **file:/\/** prefix.
- ArkTS widgets do not support the [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) type.
- When a local image is being loaded, any modification or replacement of it may cause application crash. Therefore, to overwrite an image file, delete the file first and then create one with the same name.
- Online images must support the RFC 9113 standard to be successfully loaded.
- If images to download are greater than 10 MB or in large number, consider using [HTTP](../../../network/http-request.md) to preload them to improve the image loading performance and facilitate data management on the application side.
- Directly passing a URL to the **Image** component can lead to potential performance issues, such as: (1) Large images cannot be preloaded, resulting in longer display times for white blocks; (2) Small images set to load synchronously can block the UI thread in weak network environments, causing screen freezing issues; (3) In fast-scrolling water flow layouts, images that are about to be displayed could not be preloaded, leading to more white blocks during scrolling. Performance issues manifest differently in different scenarios. To address these issues, decouple the network downloading part from the display of the **Image** component, which allows for preloading or asynchronous downloading.
- To display an SVG image that does not have the native size, you must set the width and height for the **Image** component.
- If an SVG image references another local image through the Image tag, the referenced image cannot be in .svg or .gif format.
- When the **src** attribute changes from a valid value to an invalid one, the image remains unchanged.
- If this parameter is of the [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) type, the **Image** component can detect data changes only when the reference to the **PixelMap** object is updated to point to a new instance. If modifications are made to the content of the **PixelMap** object, such as pixel values, but the reference to the object remains the same, the **Image** component will not recognize these modifications as a data change.| +| src | [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) \| [ResourceStr](ts-types.md#resourcestr)\| [DrawableDescriptor](#drawabledescriptor10)\| [ImageContent](#imagecontent12) | Yes | Data source of the image. Local and online sources are supported. For details about how to reference an image, see [Loading Image Resources](../../../ui/arkts-graphics-display.md#loading-image-resources).
1. **PixelMap**: an array of pixels storing graphical information. This type is usually used in image editing scenarios.
2. **ResourceStr**: a string or a **Resource** object.
The string type can be used to load local images and, more frequently, online images. When using an image referenced using a relative path, for example, **Image("common/test.jpg")**, the **Image** component cannot be called across bundles or modules. If an image needs to be used globally, you are advised to use the **Resource** format. The following types of strings are supported:
- Base64 strings in the format of data:image/[png\|jpeg\|bmp\|webp\|heif];base64,[base64 data], where *[base64 data]* is a Base64 string.
- Strings with the **file://** prefix, that is, [application sandbox URIs](../../apis-core-file-kit/js-apis-file-fileuri.md#constructor10): **file://\/\**, When accessing a path that contains special characters, use [fileUri.getUriFromPath(path)](../../apis-core-file-kit/js-apis-file-fileuri.md#fileurigeturifrompath) to transform the path into a URI that can handle special symbols. In addition, ensure that the application has the read permission to the files in the specified path.
The **Resource** format allows for access across bundles and modules. It is recommended for accessing local images.
3. **DrawableDescriptor**: an object created when the passed resource ID or name belongs to a common image. If the [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12) type is passed in, the PixelMap array animation can be played.
4. [ImageContent](#imagecontent12): image content.
**NOTE**
- ArkTS widgets support GIF animations, but the animations only play once on display.
- ArkTS widgets do not support the strings with the **http:/\/** or **file:/\/** prefix.
- When a local image is being loaded, any modification or replacement of it may cause application crash. Therefore, to overwrite an image file, delete the file first and then create one with the same name.
- Online images must support the RFC 9113 standard to be successfully loaded.
- If images to download are greater than 10 MB or in large number, consider using [HTTP](../../../network/http-request.md) to preload them to improve the image loading performance and facilitate data management on the application side.
- Directly passing a URL to the **Image** component can lead to potential performance issues, such as: (1) Large images cannot be preloaded, resulting in longer display times for white blocks; (2) Small images set to load synchronously can block the UI thread in weak network environments, causing screen freezing issues; (3) In fast-scrolling water flow layouts, images that are about to be displayed could not be preloaded, leading to more white blocks during scrolling. Performance issues manifest differently in different scenarios. To address these issues, decouple the network downloading part from the display of the **Image** component, which allows for preloading or asynchronous downloading.
- To display an SVG image that does not have the native size, you must set the width and height for the **Image** component.
- If an SVG image references another local image through the Image tag, the referenced image cannot be in .svg or .gif format.
- When the **src** attribute changes from a valid value to an invalid one, the image remains unchanged.
- If this parameter is of the [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) type, the **Image** component can detect data changes only when the reference to the **PixelMap** object is updated to point to a new instance. If modifications are made to the content of the **PixelMap** object, such as pixel values, but the reference to the object remains the same, the **Image** component will not recognize these modifications as a data change.| ### Image12+ @@ -80,12 +82,12 @@ Obtains an image. The [imageAIOptions](ts-image-common.md#imageaioptions) parame | Name | Type | Mandatory | Description | | ---- | ---------------------------------------- | ---- | ---------------------------------------- | -| src | [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) \| [ResourceStr](ts-types.md#resourcestr)\| [DrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#drawabledescriptor) | Yes | Data source of the image. Local and online sources are supported. For details about how to reference an image, see [Loading Image Resources](../../../ui/arkts-graphics-display.md#loading-image-resources).
1. **PixelMap**: an array of pixels storing graphical information. This type is usually used in image editing scenarios.
2. **ResourceStr**: a string or a **Resource** object.
The string format can be used to load local images and, more frequently, online images. When using an image referenced using a relative path, for example, **Image("common/test.jpg")**, the **Image** component cannot be called across bundles or modules. If an image needs to be used globally, you are advised to use the **Resource** format. The following types of strings are supported:
- Base64 strings in the format of data:image/[png\|jpeg\|bmp\|webp\|heif];base64,[base64 data], where *[base64 data]* is a Base64 string.
- Strings with the **file://** prefix, that is, [application sandbox URIs](../../apis-core-file-kit/js-apis-file-fileuri.md#constructor10): **file://\/\**, When accessing a path that contains special characters, use [fileUri.getUriFromPath(path)](../../apis-core-file-kit/js-apis-file-fileuri.md#fileurigeturifrompath) to transform the path into a URI that can handle special symbols. In addition, ensure that the application has the read permission to the files in the specified path.
The **Resource** format allows for access across bundles and modules. It is recommended for accessing local images.
3. **DrawableDescriptor**: an object created when the passed resource ID or name belongs to a common image. If the [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12) type is passed in, the PixelMap array animation can be played.
**NOTE**
- ArkTS widgets support GIF animations, but the animations only play once on display.
- ArkTS widgets do not support the strings with the **http:/\/** or **file:/\/** prefix.
- ArkTS widgets do not support the [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) type.
- When a local image is being loaded, any modification or replacement of it may cause application crash. Therefore, to overwrite an image file, delete the file first and then create one with the same name.
- Online images must support the RFC 9113 standard to be successfully loaded.
- If images to download are greater than 10 MB or in large number, consider using [HTTP](../../../network/http-request.md) to preload them to improve the image loading performance and facilitate data management on the application side.
- Directly passing a URL to the **Image** component can lead to potential performance issues, such as: (1) Large images cannot be preloaded, resulting in longer display times for white blocks; (2) Small images set to load synchronously can block the UI thread in weak network environments, causing screen freezing issues; (3) In fast-scrolling water flow layouts, images that are about to be displayed could not be preloaded, leading to more white blocks during scrolling. Performance issues manifest differently in different scenarios. To address these issues, decouple the network downloading part from the display of the **Image** component, which allows for preloading or asynchronous downloading.
- To display an SVG image that does not have the native size, you must set the width and height for the **Image** component.
- If an SVG image references another local image through the Image tag, the referenced image cannot be in .svg or .gif format.
- When the **src** attribute changes from a valid value to an invalid one, the image remains unchanged.
- If this parameter is of the [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) type, the **Image** component can detect data changes only when the reference to the **PixelMap** object is updated to point to a new instance. If modifications are made to the content of the **PixelMap** object, such as pixel values, but the reference to the object remains the same, the **Image** component will not recognize these modifications as a data change.| +| src | [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) \| [ResourceStr](ts-types.md#resourcestr)\| [DrawableDescriptor](#drawabledescriptor10) | Yes | Data source of the image. Local and online sources are supported. For details about how to reference an image, see [Loading Image Resources](../../../ui/arkts-graphics-display.md#loading-image-resources).
1. **PixelMap**: an array of pixels storing graphical information. This type is usually used in image editing scenarios.
2. **ResourceStr**: a string or a **Resource** object.
The string type can be used to load local images and, more frequently, online images. When using an image referenced using a relative path, for example, **Image("common/test.jpg")**, the **Image** component cannot be called across bundles or modules. If an image needs to be used globally, you are advised to use the **Resource** format. The following types of strings are supported:
- Base64 strings in the format of data:image/[png\|jpeg\|bmp\|webp\|heif];base64,[base64 data], where *[base64 data]* is a Base64 string.
- Strings with the **file://** prefix, that is, [application sandbox URIs](../../apis-core-file-kit/js-apis-file-fileuri.md#constructor10): **file://\/\**, When accessing a path that contains special characters, use [fileUri.getUriFromPath(path)](../../apis-core-file-kit/js-apis-file-fileuri.md#fileurigeturifrompath) to transform the path into a URI that can handle special symbols. In addition, ensure that the application has the read permission to the files in the specified path.
The **Resource** format allows for access across bundles and modules. It is recommended for accessing local images.
3. **DrawableDescriptor**: an object created when the passed resource ID or name belongs to a common image. If the [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12) type is passed in, the PixelMap array animation can be played.
**NOTE**
- ArkTS widgets support GIF animations, but the animations only play once on display.
- ArkTS widgets do not support the strings with the **http:/\/** or **file:/\/** prefix.
- When a local image is being loaded, any modification or replacement of it may cause application crash. Therefore, to overwrite an image file, delete the file first and then create one with the same name.
- Online images must support the RFC 9113 standard to be successfully loaded.
- If images to download are greater than 10 MB or in large number, consider using [HTTP](../../../network/http-request.md) to preload them to improve the image loading performance and facilitate data management on the application side.
- Directly passing a URL to the **Image** component can lead to potential performance issues, such as: (1) Large images cannot be preloaded, resulting in longer display times for white blocks; (2) Small images set to load synchronously can block the UI thread in weak network environments, causing screen freezing issues; (3) In fast-scrolling water flow layouts, images that are about to be displayed could not be preloaded, leading to more white blocks during scrolling. Performance issues manifest differently in different scenarios. To address these issues, decouple the network downloading part from the display of the **Image** component, which allows for preloading or asynchronous downloading.
- To display an SVG image that does not have the native size, you must set the width and height for the **Image** component.
- If an SVG image references another local image through the Image tag, the referenced image cannot be in .svg or .gif format.
- When the **src** attribute changes from a valid value to an invalid one, the image remains unchanged.
- If this parameter is of the [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) type, the **Image** component can detect data changes only when the reference to the **PixelMap** object is updated to point to a new instance. If modifications are made to the content of the **PixelMap** object, such as pixel values, but the reference to the object remains the same, the **Image** component will not recognize these modifications as a data change.| | imageAIOptions | [ImageAIOptions](ts-image-common.md#imageaioptions) | Yes | AI image analysis options. You can configure the analysis type or bind an analyzer controller through this parameter.| ## Attributes -For details about how to use the attributes, see [Setting Attributes](../../../ui/arkts-graphics-display.md#setting-attributes). In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +For details about how to use the attributes, see [Setting Attributes](../../../ui/arkts-graphics-display.md#setting-attributes). In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. > **NOTE** > @@ -129,15 +131,17 @@ Sets how the image is resized to fit its container. | ------ | ----------------------------------------- | ---- | ------------------------------------------- | | value | [ImageFit](ts-appendix-enums.md#imagefit) | Yes | How the image is resized to fit its container.
Default value: **ImageFit.Cover**| -### imageMatrix16+ +### imageMatrix15+ imageMatrix(matrix: ImageMatrix) -Sets the transformation matrix of the image. +Sets the transformation matrix of the image. This API allows you to use the APIs provided by the [ImageMatrix](#imagematrix15) object, such as translate, rotate, and scale, to achieve the optimal display of grid thumbnails. This attribute is not applicable to SVG images. + +This attribute does not take effect when the **resizable** or **objectRepeat** attributes are set. This attribute only processes the image source and does not trigger any callback events of the **Image** component. -**Widget capability**: This API can be used in ArkTS widgets since API version 16. +This attribute is strongly related to the [objectFit](#objectfit) setting and only works when [objectFit](#objectfit) is set to **[ImageFit](ts-appendix-enums.md#imagefit).MATRIX**. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 15. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -145,7 +149,7 @@ Sets the transformation matrix of the image. | Name| Type | Mandatory| Description | | ------ | --------------------------------------------------- | ---- | -------------- | -| matrix | [ImageMatrix](../js-apis-matrix4.md#matrix4transit) | Yes | Transformation matrix of the image.| +| matrix | [ImageMatrix](#imagematrix15) | Yes | Transformation matrix of the image.| ### objectRepeat @@ -247,7 +251,7 @@ This attribute does not take effect when the parameter type of the component is | Name| Type | Mandatory| Description | | ------ | ------- | ---- | -------------------------------------------- | -| value | boolean | Yes | Whether to display the image in the system language direction.
Default value: **false**| +| value | boolean | Yes | Whether to display the image in the system language direction.
Default value: **false**
**true**: Display the image in the system language direction.
**false**: Do not display the image in the system language direction.| ### fitOriginalSize @@ -287,7 +291,25 @@ This attribute does not take effect when the parameter type of the component is | Name| Type | Mandatory| Description | | ------ | ------------------------------------------ | ---- | -------------- | -| value | [ResourceColor](ts-types.md#resourcecolor) | Yes | Fill color to be superimposed on the image.| +| value | [ResourceColor](ts-types.md#resourcecolor) | Yes | Fill color to be superimposed on the image.
**NOTE**
By default, no fill color is applied. If an invalid value is passed, the system uses the default theme color: black in light mode and white in dark mode.| + +### fillColor15+ + +fillColor(color: ResourceColor|ColorContent) + +Sets the fill color to be superimposed on the image. This attribute applies only to SVG images. Once set, the fill color will replace the fill colors of all drawable elements within the SVG image. To set the fill color for a PNG image, use [colorFilter](#colorfilter9). To reset the fill color, pass a value of the [ColorContent](#colorcontent15) type. + +This attribute does not take effect when the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12). + +**Atomic service API**: This API can be used in atomic services since API version 15. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------ | ---- | -------------- | +| color | [ResourceColor](ts-types.md#resourcecolor)\|[ColorContent](#colorcontent15) | Yes | Fill color to be superimposed on the image.
**NOTE**
By default, no fill color is applied. If an invalid value is passed, the system uses the default theme color: black in light mode and white in dark mode.| ### autoResize @@ -301,7 +323,7 @@ When the image is scaled down: .autoResize(false) + .interpolation(.Medium) When the image is scaled up: .interpolation(.High) -This attribute does not take effect when the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12). +This attribute does not take effect when the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12) or SVG. **Widget capability**: This API can be used in ArkTS widgets since API version 9. @@ -313,7 +335,7 @@ This attribute does not take effect when the parameter type of the component is | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------------------------------------ | -| value | boolean | Yes | Whether to resize the image source based on the size of the display area during image decoding. This resizing can help reduce the memory usage. For example, if the size of the original image is 1920 x 1080 and the size of the display area is 200 x 200, you can set this attribute to **true** so that the image is downsampled to 200 x 200.
Default value: **false**| +| value | boolean | Yes | Whether to resize the image source based on the size of the display area during image decoding. This resizing can help reduce the memory usage. For example, if the size of the original image is 1920 x 1080 and the size of the display area is 200 x 200, you can set this attribute to **true** so that the image is downsampled to 200 x 200.
Default value: **false**
**true**: Enable resizing.
**false**: Disable resizing.| ### syncLoad8+ @@ -333,7 +355,7 @@ This attribute does not take effect when the parameter type of the component is | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------------------------------------ | -| value | boolean | Yes | Whether to load the image synchronously. By default, the image is loaded asynchronously. During synchronous loading, the UI thread is blocked and the placeholder image is not displayed.
Default value: **false**| +| value | boolean | Yes | Whether to load the image synchronously. By default, the image is loaded asynchronously. During synchronous loading, the UI thread is blocked and the placeholder image is not displayed.
Default value: **false**
**true**: Load the image synchronously.
**false**: Load the image asynchronously.| ### copyOption9+ @@ -373,7 +395,7 @@ When this attribute is set, [renderMode](#rendermode) is not effective. | Name| Type | Mandatory| Description | | ------ | --------------------------------------- | ---- | ------------------------------------------------------------ | -| value | [ColorFilter](ts-types.md#colorfilter9) \| [DrawingColorFilter](../../apis-arkgraphics2d/js-apis-graphics-drawing.md#colorfilter)12+ | Yes | 1. Color filter of the image. The input parameter is a 4 x 5 RGBA transformation matrix.
The first row of the matrix represents a vector value of R (red), the second row represents a vector value of G (green), the third row represents a vector value of B (blue), and the fourth row represents a vector value of A (alpha). The four rows represent different RGBA vector values.
If the matrix contains entries of 1 on the diagonal and entries of 0 in other places, the original color of the image is retained.
**Calculation rule:**
If the input filter matrix is as follows:
![image-matrix-1](figures/image-matrix-1.jpg)
Wherein the color is [R, G, B, A].
Then the color after filtering is [R', G', B', A'].
![image-matrix-2](figures/image-matrix-2.jpg)
2. The ColorFilter type of **@ohos.graphics.drawing** can be used as the input parameter since API Version 12.
**NOTE**
This parameter is not available for SVG images in API version 11 and earlier versions.
The DrawingColorfilter type can be used in atomic services since API version 12. The SVG image to set as the source must have the **stroke** attribute.| +| value | [ColorFilter](ts-types.md#colorfilter9) \| [DrawingColorFilter](#drawingcolorfilter12) | Yes | 1. Color filter of the image. The input parameter is a 4 x 5 RGBA transformation matrix.
The first row of the matrix represents a vector value of R (red), the second row represents a vector value of G (green), the third row represents a vector value of B (blue), and the fourth row represents a vector value of A (alpha). The four rows represent different RGBA vector values.
If the matrix contains entries of 1 on the diagonal and entries of 0 in other places, the original color of the image is retained.
**Calculation rule:**
If the input filter matrix is as follows:
![image-matrix-1](figures/image-matrix-1.jpg)
Wherein the color is [R, G, B, A].
Then the color after filtering is [R', G', B', A'].
![image-matrix-2](figures/image-matrix-2.jpg)
2. The ColorFilter type of **@ohos.graphics.drawing** can be used as the input parameter since API Version 12.
**NOTE**
This parameter is not available for SVG images in API version 11 and earlier versions.
The DrawingColorfilter type can be used in atomic services since API version 12. The SVG image to set as the source must have the **stroke** attribute.| ### draggable9+ @@ -419,7 +441,7 @@ This attribute does not take effect when the parameter type of the component is | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------------------------------------ | -| enable | boolean | Yes | Whether to enable the AI analyzer. The value **true** means to enable the AI analyzer.
Default value: **false**| +| enable | boolean | Yes | Whether to enable the AI analyzer.
Default value: **false**
**true**: Enable the AI analyzer.
**false**: Disable the AI analyzer.| ### resizable11+ @@ -431,7 +453,7 @@ When [ResizableOptions](#resizableoptions11) is set to a valid value, the **obje When the sum of the values of **top** and **bottom** is greater than the source image height, or the sum of the values of **left** and **right** is greater than the source image width, the [ResizableOptions](#resizableoptions11) attribute does not take effect. -This attribute does not take effect when the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12). +This attribute does not take effect when the parameter type of the component is [AnimatedDrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#animateddrawabledescriptor12) or SVG. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -465,7 +487,7 @@ Sets whether to secure sensitive information on widgets. dynamicRangeMode(value: DynamicRangeMode) -Sets the dynamic range of the image to be displayed. +Sets the dynamic range of the image to be displayed. This attribute is not applicable to SVG images. @@ -477,7 +499,23 @@ Sets the dynamic range of the image to be displayed. | Name| Type | Mandatory| Description | | ------ | --------------------------------------- | ---- | -------------------------------- | -| value | [DynamicRangeMode](#dynamicrangemode12-1) | Yes | Dynamic range of the image.
Default value: **dynamicRangeMode.Standard**| +| value | [DynamicRangeMode](#dynamicrangemode12) | Yes | Dynamic range of the image.
Default value: **dynamicRangeMode.Standard**| + +### orientation14+ + +orientation(orientation: ImageRotateOrientation) + +Sets the display orientation of the image content. + +**Atomic service API**: This API can be used in atomic services since API version 14. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | --------------------------------------- | ---- | -------------------------------- | +| orientation | [ImageRotateOrientation](#imagerotateorientation14) | Yes | Display orientation of the image content.
Default value: **ImageRotateOrientation.UP**| ## ImageContent12+ @@ -489,9 +527,9 @@ Defines the image content. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Description | -| ------ | -------------------------- | -| EMPTY | Empty image. | +| Name | Value | Description | +| ------ | ----- | -------------------------- | +| EMPTY | 0 | Empty image. | ## ImageInterpolation @@ -531,8 +569,8 @@ Defines the resizable image options. | Name| Type| Mandatory| Description| | --------- |-----------|-----------|-----------| -| slice | [EdgeWidths](#edgewidths) | No | Edge widths in different directions of a component.
**NOTE**
This parameter takes effect only when values of **bottom** and **right** are both greater than 0.| -| lattice12+ | [DrawingLattice](../../apis-arkgraphics2d/js-apis-graphics-drawing.md#lattice12) | No | Lattice object, which is used to divide the image by lattice.
**NOTE**
A lattice object can be created through the **createImageLattice** API of the **@ohos.graphics.drawing** module. The lattices on both even columns and even rows are fixed.
This parameter does not take effect for the [backgroundImageResizable](ts-universal-attributes-background.md#backgroundimageresizable12) API.| +| slice | [EdgeWidths](#edgewidths) | No | Edge widths in different directions of a component.
**NOTE**
This parameter takes effect only when values of **bottom** and **right** are both greater than 0.
When a number is passed, the default unit is vp.| +| lattice12+ | [DrawingLattice](#drawinglattice12) | No | Lattice object, which is used to divide the image by lattice.
**NOTE**
A lattice object can be created through the **createImageLattice** API of the **@ohos.graphics.drawing** module. The lattices on both even columns and even rows are fixed.
This parameter does not take effect for the [backgroundImageResizable](ts-universal-attributes-background.md#backgroundimageresizable12) API.
When a number is passed, the default unit is px.| ## EdgeWidths @@ -542,10 +580,10 @@ Defines the resizable image options. | Name| Type| Mandatory| Description| | --------- |-----------|-----------|-----------| -| top | [Length](ts-types.md#length) | No | Width of the top edge.
Default value: **0**
Unit: vp| -| right | [Length](ts-types.md#length) | No | Width of the right edge.
Default value: **0**
Unit: vp| -| bottom | [Length](ts-types.md#length) | No | Width of the bottom edge.
Default value: **0**
Unit: vp| -| left | [Length](ts-types.md#length) | No | Width of the left edge.
Default value: **0**
Unit: vp| +| top | [Length](ts-types.md#length) | No | Pixel value of the image that remains unchanged when the top side of the image is stretched.
Default value: **0**
Unit: vp| +| right | [Length](ts-types.md#length) | No | Pixel value of the image that remains unchanged when the right side of the image is stretched.
Default value: **0**
Unit: vp| +| bottom | [Length](ts-types.md#length) | No | Pixel value of the image that remains unchanged when the bottom side of the image is stretched.
Default value: **0**
Unit: vp| +| left | [Length](ts-types.md#length) | No | Pixel value of the image that remains unchanged when the left side of the image is stretched.
Default value: **0**
Unit: vp| ![edgewidths](figures/edgewidths.png) @@ -563,6 +601,22 @@ Describes the dynamic range of the image to be displayed. | CONSTRAINT | 1 | Restricted dynamic range, which brightens an image within certain constraints. | | STANDARD | 2 | Standard dynamic range, which does not brighten an image. | +## ImageRotateOrientation14+ + +Describes the desired display orientation for image content. + +**Atomic service API**: This API can be used in atomic services since API version 14. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Value | Description | +| ------ | -------------------------- | -------------------------- | +| AUTO | 0 | Use the EXIF metadata of the image to determine the display orientation. | +| UP | 1 | Display the image in its original orientation without any EXIF processing. Default value. | +| RIGHT | 2 | Rotate the image 90 degrees clockwise before displaying it. | +| DOWN | 3| Rotate the image 180 degrees before displaying it. | +| LEFT | 4 | Rotate the image 90 degrees counterclockwise before displaying it. | + ## ImageSourceSize14+ **Widget capability**: This API can be used in ArkTS widgets since API version 14. @@ -573,12 +627,80 @@ Describes the dynamic range of the image to be displayed. | Name| Type | Mandatory| Description | | ------ | --------- | ---- | ------------- | -| width | number | Yes | Decoded width of the image.
Unit: vp| -| height | number | Yes | Decoded height of the image.
Unit: vp| +| width7+ | number | Yes | Decoded width of the image.
Unit: vp
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| height7+ | number | Yes | Decoded height of the image.
Unit: vp
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11.| + +## DrawableDescriptor10+ + +type DrawableDescriptor = DrawableDescriptor + +Represents a parameter object for the **Image** component. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Type | Description | +| ------ | ---------- | +| [DrawableDescriptor](../js-apis-arkui-drawableDescriptor.md#drawabledescriptor) | **DrawableDescriptor** object.| + +## DrawingColorFilter12+ + +type DrawingColorFilter = ColorFilter + +Represents a color filter object. + +**Atomic service API**: This API can be used in atomic services since API version 12. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Type | Description | +| ------ | ---------- | +| [ColorFilter](../../apis-arkgraphics2d/js-apis-graphics-drawing.md#colorfilter) | Color filter created.| + +## DrawingLattice12+ + +type DrawingLattice = Lattice + +Represents a matrix grid object that divides an image into a rectangular grid. + +**Atomic service API**: This API can be used in atomic services since API version 12. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Type | Description | +| ------ | ---------- | +| [Lattice](../../apis-arkgraphics2d/js-apis-graphics-drawing.md#lattice12) | Matrix grid object used to divide the image into a rectangular grid.| + +## ImageMatrix15+ + +type ImageMatrix = Matrix4Transit + +Represents the current matrix object. + +**Atomic service API**: This API can be used in atomic services since API version 15. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Type | Description | +| ------ | ---------- | +| [Matrix4Transit](../js-apis-matrix4.md#matrix4transit) | Current matrix object.| + +## ColorContent15+ + +Defines the content for color filling. + +**Atomic service API**: This API can be used in atomic services since API version 15. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name| Type | Mandatory| Description | +| ------ | --------- | --- | ------------- | +| ORIGIN | ColorContent | Yes| Resets the [fillColor](#fillcolor) API, effectively the same as not setting [fillColor](#fillcolor).| ## Events -In addition to the [universal events](ts-universal-events-click.md), the following events are supported. +In addition to the [universal events](ts-component-general-events.md), the following events are supported. ### onComplete @@ -626,7 +748,7 @@ This event is not triggered if the parameter type of the component is [AnimatedD | Name | Type | Mandatory| Description | | -------- | ------------------------------------------ | ---- | -------------------------- | -| callback | [ImageErrorCallback](#imageerrorcallback9) | Yes | Callback triggered when an error occurs during image loading.
**NOTE**
- You are advised to use this callback to quickly identify the specific causes for image loading failures.| +| callback | [ImageErrorCallback](#imageerrorcallback9) | Yes | Callback triggered when an error occurs during image loading.
**NOTE**
You are advised to use this callback to quickly identify the specific causes for image loading failures.| ### onFinish @@ -878,21 +1000,21 @@ This example shows how to resize an image in different directions. @Entry @Component struct Index { - @State top: number = 40 - @State bottom: number = 5 - @State left: number = 40 + @State top: number = 10 + @State bottom: number = 10 + @State left: number = 10 @State right: number = 10 build() { Column({ space: 5 }) { // Original image effect - Image($r("app.media.sky")) + Image($r("app.media.landscape")) .width(200).height(200) .border({ width: 2, color: Color.Pink }) .objectFit(ImageFit.Contain) // Set the resizable attribute to resize the image in different directions. - Image($r("app.media.sky")) + Image($r("app.media.landscape")) .resizable({ slice: { left: this.left, @@ -909,22 +1031,22 @@ struct Index { Row() { Button("add top to " + this.top).fontSize(10) .onClick(() => { - this.top += 2 + this.top += 10 }) Button("add bottom to " + this.bottom).fontSize(10) .onClick(() => { - this.bottom += 2 + this.bottom += 10 }) } Row() { Button("add left to " + this.left).fontSize(10) .onClick(() => { - this.left += 2 + this.left += 10 }) Button("add right to " + this.right).fontSize(10) .onClick(() => { - this.right += 2 + this.right += 10 }) } @@ -1254,3 +1376,197 @@ struct ImageExample11 { ``` ![imageContent](figures/imageScanEffect.gif) + +### Example 12: Adding Transform Effects to Images + +This example demonstrates how to apply rotation and translation effects to images using [imageMatrix](#imagematrix15) and [objectFit](#objectfit). + +```ts +import { matrix4 } from '@kit.ArkUI' + +@Entry +@Component +struct Test { + private matrix1 = matrix4.identity() + .translate({ x: -400, y: -750 }) + .scale({ x: 0.5, y: 0.5 }) + .rotate({ + x: 2, + y: 0.5, + z: 3, + centerX: 10, + centerY: 10, + angle: -10 + }) + + build() { + Row() { + Column({ space: 50 }) { + Column({ space: 5 }) { + Image($r("app.media.example")) + .border({ width:2, color: Color.Black }) + .objectFit(ImageFit.Contain) + .width(150) + .height(150) + Text("No transformation") + .fontSize('25px') + } + Column({ space: 5 }) { + Image($r("app.media.example")) + .border({ width:2, color: Color.Black }) + .objectFit(ImageFit.None) + .translate({ x: 10, y: 10 }) + .scale({ x: 0.5, y: 0.5 }) + .width(100) + .height(100) + Text("Direct transformation on the image, with the upper left corner of the image source displayed by default") + .fontSize('25px') + } + Column({ space: 5 }) { + Image($r("app.media.example")) + .objectFit(ImageFit.MATRIX) + .imageMatrix(this.matrix1) + .border({ width:2, color: Color.Black }) + .width(150) + .height(150) + Text("Transformation using imageMatrix to adjust the source position for optimal display") + .fontSize('25px') + } + } + .width('100%') + } + } +} +``` + +![imageMatrix](figures/imageMatrix.jpeg) + +### Example 13: Setting the Image Decoding Size Using sourceSize + +This example uses the [sourceSize](ts-basic-components-image.md#sourcesize) API to customize the decoding size of the image. + +```ts +@Entry +@Component +struct Index { + @State borderRadiusValue: number = 10; + build() { + Column() { + Image($r("app.media.sky")) + .sourceSize({width:1393, height:1080}) + .height(300) + .width(300) + .objectFit(ImageFit.Contain) + .borderWidth(1) + Image($r("app.media.sky")) + .sourceSize({width:13, height:10}) + .height(300) + .width(300) + .objectFit(ImageFit.Contain) + .borderWidth(1) + } + .height('100%') + .width('100%') + } +} +``` + +![sourceSizeExample](figures/sourceSizeExample.png) + +### Example 14: Setting the Image Rendering Mode Using renderMode + +This example uses the [renderMode](ts-basic-components-image.md#rendermode) API to set the image rendering mode to grayscale. + +```ts +@Entry +@Component +struct Index { + @State borderRadiusValue: number = 10; + build() { + Column() { + Image($r("app.media.sky")) + .renderMode(ImageRenderMode.Template) + .height(300) + .width(300) + .objectFit(ImageFit.Contain) + .borderWidth(1) + } + .height('100%') + .width('100%') + } +} +``` + +![renderModeExample](figures/renderModeExample.png) + +### Example 15: Setting the Image Repeat Pattern Using objectRepeat + +This example uses the [objectRepeat](ts-basic-components-image.md#objectrepeat) API to repeat the image along the vertical axis. + +```ts +@Entry +@Component +struct Index { + @State borderRadiusValue: number = 10; + build() { + Column() { + Image($r("app.media.sky")) + .objectRepeat(ImageRepeat.Y) + .height(300) + .width(300) + .objectFit(ImageFit.Contain) + .borderWidth(1) + } + .height('100%') + .width('100%') + } +} +``` + +![objectRepeatExample](figures/objectRepeatExample.png) + +### Example 16: Setting the Fill Color for SVG Images + +This example shows how to use [fillColor](#fillcolor15) to set different fill colors for SVG images. + +```ts +@Entry +@Component +struct Index { + build() { + Column() { + Text("FillColor not set") + Image($r("app.media.svgExample")) + .height(100) + .width(100) + .objectFit(ImageFit.Contain) + .borderWidth(1) + Text("fillColor set to ColorContent.ORIGIN") + Image($r("app.media.svgExample")) + .height(100) + .width(100) + .objectFit(ImageFit.Contain) + .borderWidth(1) + .fillColor(ColorContent.ORIGIN) + Text("fillColor set to Color.Blue") + Image($r("app.media.svgExample")) + .height(100) + .width(100) + .objectFit(ImageFit.Contain) + .borderWidth(1) + .fillColor(Color.Blue) + Text("fillColor set to undefined") + Image($r("app.media.svgExample")) + .height(100) + .width(100) + .objectFit(ImageFit.Contain) + .borderWidth(1) + .fillColor(undefined) + } + .height('100%') + .width('100%') + } +} +``` + +![fillColorExample](figures/fillColorExample.png) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-imageanimator.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-imageanimator.md index ebc585abdcc040a2f6618f9559044c825fa2687e..cbfc4812862ff577dfda842d0d096a80a65ccd42 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-imageanimator.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-imageanimator.md @@ -43,7 +43,7 @@ Sets the image frame information. Dynamic update is not supported. | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| value | Array<[ImageFrameInfo](#imageframeinfo)> | Yes | Image frame information. The information of each frame includes the image path, image size, image position, and image playback duration. For details, see **ImageFrameInfo**.
Default value: **[]**| +| value | Array<[ImageFrameInfo](#imageframeinfo)> | Yes | Image frame information. The information of each frame includes the image path, image size, image position, and image playback duration. For details, see **ImageFrameInfo**.
Default value: **[]**
**NOTE**
If the input array is too large, memory usage may increase. Therefore, as the controller of memory usage, be sure to assess potential memory consumption before passing in the data to avoid issues such as insufficient memory.| ### state @@ -167,13 +167,13 @@ Sets the number of times that the animation is played. | ------ | ------ | ---- | ------------------------------------------------------ | | value | number | Yes | Number of times that the animation is played. By default, the animation is played once. The value **-1** indicates that the animation is played for an unlimited number of times.
Default value: **1**| -### monitorInvisibleArea16+ +### monitorInvisibleArea18+ monitorInvisibleArea(monitorInvisibleArea: boolean) Sets whether the component should automatically pause or resume based on its visibility, using the system's [onVisibleAreaChange](./ts-universal-component-visible-area-change-event.md#onvisibleareachange) event. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -192,10 +192,10 @@ Sets whether the component should automatically pause or resume based on its vis | Name | Type | Mandatory| Description| | -------- | -------------- | -------- | -------- | | src | string \| [Resource](ts-types.md#resource)9+ \| [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7)12+ | Yes | Image path. The image format can be .jpg, .jpeg, .svg, .png, .bmp, .webp, .ico, or .heif. The [Resource](ts-types.md#resource) type is supported since API version 9, and the [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) type is supported since API version 12.
**Widget capability**: This API can be used in ArkTS widgets since API version 10.| -| width | number \| string | No | Image width.
Default value: **0**
**Widget capability**: This API can be used in ArkTS widgets since API version 10. | -| height | number \| string | No | Image height.
Default value: **0**
**Widget capability**: This API can be used in ArkTS widgets since API version 10. | -| top | number \| string | No | Vertical coordinate of the image relative to the upper left corner of the widget
Default value: **0**
**Widget capability**: This API can be used in ArkTS widgets since API version 10. | -| left | number \| string | No | Horizontal coordinate of the image relative to the upper left corner of the widget
Default value: **0**
**Widget capability**: This API can be used in ArkTS widgets since API version 10. | +| width | number \| string | No | Image width. For the string type, numeric string values with optional units, for example, **"2"** or **"2px"**, are supported.
Default value: **0**
Unit: vp
**Widget capability**: This API can be used in ArkTS widgets since API version 10. | +| height | number \| string | No | Image height. For the string type, numeric string values with optional units, for example, **"2"** or **"2px"**, are supported.
Default value: **0**
Unit: vp
**Widget capability**: This API can be used in ArkTS widgets since API version 10. | +| top | number \| string | No | Vertical coordinate of the image relative to the upper left corner of the widget For the string type, numeric string values with optional units, for example, **"2"** or **"2px"**, are supported.
Default value: **0**
Unit: vp
**Widget capability**: This API can be used in ArkTS widgets since API version 10. | +| left | number \| string | No | Horizontal coordinate of the image relative to the upper left corner of the widget For the string type, numeric string values with optional units, for example, **"2"** or **"2px"**, are supported.
Default value: **0**
Unit: vp
**Widget capability**: This API can be used in ArkTS widgets since API version 10. | | duration | number | No | Playback duration of each image frame, in milliseconds.
Default value: **0** | ## Events @@ -430,7 +430,7 @@ struct ImageAnimatorExample { ### Example 3: Enabling Automatic Pause on Invisibility -This example demonstrates how to use [monitorInvisibleArea](#monitorinvisiblearea16) to automatically pause the **ImageAnimator** component when it becomes invisible and resume playback when it becomes visible again. This behavior is controlled based on the component's [state](#state) being set to **AnimationStatus.Running**. +This example demonstrates how to use [monitorInvisibleArea](#monitorinvisiblearea18) to automatically pause the **ImageAnimator** component when it becomes invisible and resume playback when it becomes visible again. This behavior is controlled based on the component's [state](#state) being set to **AnimationStatus.Running**. ```ts @Entry @@ -519,4 +519,3 @@ struct ImageAnimatorAutoPauseTest { ``` ![imageAnimatorMonitorInvisibleAreaExample](figures/imageAnimatorMonitorInvisibleArea.gif) - diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-imagespan.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-imagespan.md index 9b36477282a75d0b878f0eb16d83a7e2c5a4a08a..c5c5efe13b6a3430bfcef42e07adfbb91b030e16 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-imagespan.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-imagespan.md @@ -31,22 +31,6 @@ ImageSpan(value: ResourceStr | PixelMap) The attributes inherit from [BaseSpan](ts-basic-components-span.md#basespan). Among the universal attributes, [size](ts-universal-attributes-size.md#size), [background](ts-universal-attributes-background.md#background), and [border](ts-universal-attributes-border.md#border) are supported. -### alt12+ - -alt(value: PixelMap) - -Sets the placeholder image displayed during loading. - -**Atomic service API**: This API can be used in atomic services since API version 12. - -**System capability**: SystemCapability.ArkUI.ArkUI.Full - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | -------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| value | [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) | Yes | Placeholder image displayed during loading. The [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) type is supported.
Default value: **null**| - ### verticalAlign verticalAlign(value: ImageSpanAlignment) @@ -79,9 +63,25 @@ Sets the image scale type. | ------ | ----------------------------------------- | ---- | ------------------------------------------- | | value | [ImageFit](ts-appendix-enums.md#imagefit) | Yes | Image scale type.
Default value: **ImageFit.Cover**| +### alt12+ + +alt(value: PixelMap) + +Sets the placeholder image displayed during loading. + +**Atomic service API**: This API can be used in atomic services since API version 12. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| value | [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) | Yes | Placeholder image displayed during loading. The [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) type is supported.
Default value: **null**| + ### colorFilter14+ -colorFilter(value: ColorFilter | DrawingColorFilter) +colorFilter(filter: ColorFilter | DrawingColorFilter) Sets the color filter for the image. @@ -93,7 +93,7 @@ Sets the color filter for the image. | Name| Type | Mandatory| Description | | ------ | --------------------------------------- | ---- | ------------------------------------------------------------ | -| value | [ColorFilter](ts-types.md#colorfilter9) \| [DrawingColorFilter](../../apis-arkgraphics2d/js-apis-graphics-drawing.md#colorfilter) | Yes | 1. Color filter of the image. The input parameter is a 4 x 5 RGBA transformation matrix.
The first row of the matrix represents a vector value of R (red), the second row represents a vector value of G (green), the third row represents a vector value of B (blue), and the fourth row represents a vector value of A (alpha). The four rows represent different RGBA vector values.
If the matrix contains entries of 1 on the diagonal and entries of 0 in other places, the original color of the image is retained.
**Calculation rule:**
If the input filter matrix is as follows:
![image-matrix-1](figures/image-matrix-1.jpg)
Wherein the color is [R, G, B, A].
Then the color after filtering is [R', G', B', A'].
![image-matrix-2](figures/image-matrix-2.jpg)
2. The ColorFilter type of **@ohos.graphics.drawing** can be used as the input parameter.
**NOTE**
The DrawingColorfilter type can be used in atomic services. The SVG image to set as the source must have the **stroke** attribute.| +| filter | [ColorFilter](ts-types.md#colorfilter9) \| [DrawingColorFilter](ts-basic-components-image.md#drawingcolorfilter12) | Yes | 1. Color filter of the image. The input parameter is a 4 x 5 RGBA transformation matrix.
The first row of the matrix represents a vector value of R (red), the second row represents a vector value of G (green), the third row represents a vector value of B (blue), and the fourth row represents a vector value of A (alpha). The four rows represent different RGBA vector values.
If the matrix contains entries of 1 on the diagonal and entries of 0 in other places, the original color of the image is retained.
**Calculation rule:**
If the input filter matrix is as follows:
![image-matrix-1](figures/image-matrix-1.jpg)
Wherein the color is [R, G, B, A].
Then the color after filtering is [R', G', B', A'].
![image-matrix-2](figures/image-matrix-2.jpg)
2. The ColorFilter type of **@ohos.graphics.drawing** can be used as the input parameter.
**NOTE**
The DrawingColorfilter type can be used in atomic services. The SVG image to set as the source must have the **stroke** attribute.| ## Events @@ -135,7 +135,7 @@ Triggered when an error occurs during image loading. type ImageCompleteCallback = (result: ImageLoadResult) => void -Triggered when the image is successfully loaded. +Defines the callback triggered when the image is successfully loaded or decoded. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -186,25 +186,25 @@ struct SpanExample { }.width('100%').textAlign(TextAlign.Center) Text() { - ImageSpan($r('app.media.icon')) + ImageSpan($r('app.media.app_icon')) .width('200px') .height('200px') .objectFit(ImageFit.Fill) .verticalAlign(ImageSpanAlignment.CENTER) Span('I am LineThrough-span') .decoration({ type: TextDecorationType.LineThrough, color: Color.Red }).fontSize(25) - ImageSpan($r('app.media.icon')) + ImageSpan($r('app.media.app_icon')) .width('50px') .height('50px') .verticalAlign(ImageSpanAlignment.TOP) Span('I am Underline-span') .decoration({ type: TextDecorationType.Underline, color: Color.Red }).fontSize(25) - ImageSpan($r('app.media.icon')) + ImageSpan($r('app.media.app_icon')) .size({ width: '100px', height: '100px' }) .verticalAlign(ImageSpanAlignment.BASELINE) Span('I am Underline-span') .decoration({ type: TextDecorationType.Underline, color: Color.Red }).fontSize(25) - ImageSpan($r('app.media.icon')) + ImageSpan($r('app.media.app_icon')) .width('70px') .height('70px') .verticalAlign(ImageSpanAlignment.BOTTOM) @@ -230,15 +230,18 @@ This example demonstrates the effect of setting a background style for text usin @Entry struct Index { build() { - Column() { - Text() { - ImageSpan($r('app.media.app_icon')) - .width('60vp') - .height('60vp') - .verticalAlign(ImageSpanAlignment.CENTER) - .textBackgroundStyle({color: Color.Green, radius: "5vp"}) - } - }.width('100%').alignItems(HorizontalAlign.Center) + Row() { + Column() { + Text() { + ImageSpan($r('app.media.sky'))// You are advised to use a custom local image. + .width('60vp') + .height('60vp') + .verticalAlign(ImageSpanAlignment.CENTER) + .borderRadius(20) + .textBackgroundStyle({ color: '#7F007DFF', radius: "5vp" }) + } + }.width('100%') + }.height('100%') } } ``` @@ -253,17 +256,18 @@ This example demonstrates how to add load success and load error events to the * @Entry @Component struct Index { - @State src: ResourceStr = $r('app.media.icon'); - build(){ - Column(){ - Text(){ + @State src: ResourceStr = $r('app.media.app_icon'); + + build() { + Column() { + Text() { ImageSpan(this.src) .width(100).height(100) - .onError((err)=>{ - console.log("onError:" + err.message) + .onError((err) => { + console.log("onError: " + err.message); }) - .onComplete((event)=>{ - console.log("onComplete: " + event.loadingStatus) + .onComplete((event) => { + console.log("onComplete: " + event.loadingStatus); }) } }.width('100%').height('100%') @@ -276,37 +280,43 @@ This example demonstrates the effect of setting a color filter for the **ImageSp ```ts // xxx.ets -import { drawing, common2D } from '@kit.ArkGraphics2D'; +import { drawing } from '@kit.ArkGraphics2D'; @Entry @Component struct SpanExample { private ColorFilterMatrix: number[] = [0.239, 0, 0, 0, 0, 0, 0.616, 0, 0, 0, 0, 0, 0.706, 0, 0, 0, 0, 0, 1, 0]; - @State DrawingColorFilterFirst: ColorFilter | undefined = new ColorFilter(this.ColorFilterMatrix) + @State DrawingColorFilterFirst: ColorFilter | undefined = new ColorFilter(this.ColorFilterMatrix); build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Text() { - ImageSpan($r('app.media.icon')) - .width('50px') - .height('50px') - .colorFilter(this.DrawingColorFilterFirst) - } - .width('50%') - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Row() { + Column({ space: 10 }) { + // Use a ColorFilter object to apply a color filter to the image. Text() { - ImageSpan($r('app.media.icon')) - .width('50px') - .height('50px') - .colorFilter(drawing.ColorFilter.createBlendModeColorFilter({ alpha: 255, red: 112, green: 112, blue: 112 }, drawing.BlendMode.SRC)) + ImageSpan($r('app.media.sky'))// You are advised to use a custom local image. + .width('60vp') + .height('60vp') + .colorFilter(this.DrawingColorFilterFirst) } - .width('50%') - }.width('100%').height('10%') - }.width('200%').height('100%') + + // Create a color filter using the drawing.ColorFilter API. + Text() { + ImageSpan($r('app.media.sky'))// You are advised to use a custom local image. + .width('60vp') + .height('60vp') + .colorFilter(drawing.ColorFilter.createBlendModeColorFilter({ + alpha: 255, + red: 112, + green: 112, + blue: 112 + }, drawing.BlendMode.SRC)) + } + }.width('100%') + }.height('100%') } } ``` -![imagespan](figures/image_span_colorfilter.gif) +![imagespan](figures/image_span_colorfilter.png) ### Example 5: Setting a Placeholder Image @@ -314,9 +324,9 @@ This example shows how a placeholder image is used in the **ImageSpan** componen ```ts // xxx.ets -import { http } from '@kit.NetworkKit' -import { image } from '@kit.ImageKit' -import { BusinessError } from '@kit.BasicServicesKit' +import { http } from '@kit.NetworkKit'; +import { image } from '@kit.ImageKit'; +import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component @@ -327,15 +337,15 @@ struct SpanExample { // Enter an image URL. http.createHttp().request("https://www.example.com/xxx.png", (error: BusinessError, data: http.HttpResponse) => { if (error) { - console.error(`http request failed with. Code: ${error.code}, message: ${error.message}`) + console.error(`http request failed with. Code: ${error.code}, message: ${error.message}`); } else { - console.log(`http request success.`) - let imageData: ArrayBuffer = data.result as ArrayBuffer - let imageSource: image.ImageSource = image.createImageSource(imageData) + console.log(`http request success.`); + let imageData: ArrayBuffer = data.result as ArrayBuffer; + let imageSource: image.ImageSource = image.createImageSource(imageData); class tmp { - height: number = 100 - width: number = 100 + height: number = 100; + width: number = 100; } let option: Record = { @@ -344,10 +354,10 @@ struct SpanExample { 'pixelFormat': 3, // Pixel format. 'scaleMode': 1, // Scale mode. 'size': { height: 100, width: 100 } - } + }; // Image size. imageSource.createPixelMap(option).then((pixelMap: PixelMap) => { - this.imageAlt = pixelMap + this.imageAlt = pixelMap; }) } }) @@ -357,7 +367,7 @@ struct SpanExample { Column() { Button("Get Online Image") .onClick(() => { - this.httpRequest() + this.httpRequest(); }) Text() { diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-loadingprogress.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-loadingprogress.md index 4988f1c49b63e44fdd9a97168e2344ac6c66bcae..875bcba4d2464c819fad2cbb19b89f1ec263c928 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-loadingprogress.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-loadingprogress.md @@ -28,7 +28,11 @@ Creates a **LoadingProgress** component. ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. + +> **NOTE** +> +> Set the component's width and height to reasonable values. If they are too large, the loading animation might not work as expected. ### color @@ -63,7 +67,7 @@ Sets whether to show the loading animation. The component still takes up space i | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ---------------------------------------------- | -| value | boolean | Yes | Whether to show the loading animation.
Default value: **true**| +| value | boolean | Yes | Whether to show the loading animation.
Default value: **true**
**true**: Show the loading animation.
**false**: Do not show the loading animation.| ### contentModifier12+ @@ -83,7 +87,7 @@ Creates a content modifier. ## Events -The [universal events](ts-universal-events-click.md) are supported. +The [universal events](ts-component-general-events.md) are supported. ## LoadingProgressConfiguration12+ @@ -95,7 +99,7 @@ You need a custom class to implement the **ContentModifier** API. | Name | Type | Read Only | Optional | Description | | ------ | ------ | ------ |-------------------------------- |-------------------------------- | -| enableLoading | boolean | No| No|Whether to show the loading animation.
Default value: **true**| +| enableLoading | boolean | No| No|Whether to show the loading animation.
Default value: **true**
**true**: Show the loading animation.
**false**: Do not show the loading animation.| ## LoadingProgressStyle(deprecated) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-marquee.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-marquee.md index 0e787eea48e0d434a7c05446d6d0533ffe8426f6..4ed9cc723ef987e4776bef8a26d75297794e7813 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-marquee.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-marquee.md @@ -28,15 +28,15 @@ Marquee(options: MarqueeOptions) | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| options | [MarqueeOptions](#marqueeoptions14) | Yes| Parameters of the marquee.| +| options | [MarqueeOptions](#marqueeoptions18) | Yes| Parameters of the marquee.| -## MarqueeOptions14+ +## MarqueeOptions18+ Describes the initialization options of the **Marquee** component. -**Widget capability**: This API can be used in ArkTS widgets since API version 14. +**Widget capability**: This API can be used in ArkTS widgets since API version 18. -**Atomic service API**: This API can be used in atomic services since API version 14. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -44,15 +44,15 @@ Describes the initialization options of the **Marquee** component. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| start | boolean | Yes| Whether to start scrolling.
**NOTE**
This parameter cannot be used to restart scrolling that has been completed.| -| step | number | No| Scrolling step. If the step is greater than the text width, the default value is taken.
Default value: **6**, in vp| -| loop | number | No| Number of times the marquee will scroll. If the value is less than or equal to **0**, the marquee will scroll continuously.
Default value: **-1**
**NOTE**
Regardless of the value, the marquee scrolls only once on an ArkTS widget.| -| fromStart | boolean | No| Whether the text scrolls from the start.
Default value: **true**| -| src | string | Yes| Text to scroll.| +| start8+ | boolean | Yes| Whether to start scrolling.
**true**: Start scrolling.
**false**: Do not start scrolling.
**NOTE**
This parameter cannot be used to restart scrolling that has been completed.
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| step8+ | number | No| Step length of the scrolling animation text. If the value is greater than the text width of the marquee, the default value is used.
Default value: **6**
Unit: vp
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| loop8+ | number | No| Number of times the marquee will scroll. If the value is less than or equal to **0**, the marquee will scroll continuously.
Default value: **-1**
**NOTE**
Regardless of the value, the marquee scrolls only once on an ArkTS widget.
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| fromStart8+ | boolean | No| Whether the text scrolls from the start.
Default value: **true**
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| src8+ | string | Yes| Text to scroll.
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11.| ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### fontColor @@ -207,19 +207,20 @@ This example demonstrates the dynamic updating of a marquee's content by setting @Entry @Component struct MarqueeExample { - @State start: boolean = false - @State src: string = '' - @State marqueeText: string = 'Running Marquee' - private fromStart: boolean = true - private step: number = 10 - private loop: number = Number.POSITIVE_INFINITY - controller: TextClockController = new TextClockController() - convert2time(value: number): string{ - let date = new Date(Number(value+'000')); + @State start: boolean = false; + @State src: string = ''; + @State marqueeText: string = 'Running Marquee'; + private fromStart: boolean = true; + private step: number = 10; + private loop: number = Number.POSITIVE_INFINITY; + controller: TextClockController = new TextClockController(); + + convert2time(value: number): string { + let date = new Date(Number(value + '000')); let hours = date.getHours().toString().padStart(2, '0'); let minutes = date.getMinutes().toString().padStart(2, '0'); let seconds = date.getSeconds().toString().padStart(2, '0'); - return hours+ ":" + minutes + ":" + seconds; + return hours + ":" + minutes + ":" + seconds; } build() { @@ -236,23 +237,25 @@ struct MarqueeExample { .height('80vp') .fontColor('#FFFFFF') .fontSize('48fp') + .allowScale(true) // Set this to true if you want the marquee text to scale with the system font size when using the fp unit for fontSize. .fontWeight(700) + .fontFamily('HarmonyOS Sans') // Use 'HarmonyOS Sans' to avoid following the theme font. .backgroundColor('#182431') .margin({ bottom: '40vp' }) .onStart(() => { - console.info('Succeeded in completing the onStart callback of marquee animation') + console.info('Succeeded in completing the onStart callback of marquee animation'); }) .onBounce(() => { - console.info('Succeeded in completing the onBounce callback of marquee animation') + console.info('Succeeded in completing the onBounce callback of marquee animation'); }) .onFinish(() => { - console.info('Succeeded in completing the onFinish callback of marquee animation') + console.info('Succeeded in completing the onFinish callback of marquee animation'); }) Button('Start') .onClick(() => { this.start = true // Start the text clock. - this.controller.start() + this.controller.start(); }) .width('120vp') .height('40vp') diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-menu.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-menu.md index 46f93ac798cc45f137bf2960bc3efb0617f9d2e6..4fc1ff6286f1f3f466a5a127f71fbd3386973764 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-menu.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-menu.md @@ -36,7 +36,7 @@ Creates a fixed container for a menu. This API does not have any parameters. ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### fontSize(deprecated) @@ -99,7 +99,7 @@ Sets the radius of the menu border corners. | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| value | [Dimension](ts-types.md#dimension10) \| [BorderRadiuses](ts-types.md#borderradiuses9) | Yes | Radius of the menu border corners.
Default value: **8vp** for 2-in-1 devices and **20vp** for other devices

Since API version 12, if the sum of the two maximum corner radii in the horizontal direction exceeds the menu width, or if the sum of the two maximum corner radii in the vertical direction exceeds the menu height, the default corner radius will be used for all four corners of the menu.| +| value | [Dimension](ts-types.md#dimension10) \| [BorderRadiuses](ts-types.md#borderradiuses9) | Yes | Radius of the menu border corners.
Default value: **8vp** for 2-in-1 devices and **20vp** for other devices
Since API version 12, if the sum of the two maximum corner radii in the horizontal direction exceeds the menu width, or if the sum of the two maximum corner radii in the vertical direction exceeds the menu height, the default corner radius will be used for all four corners of the menu.| ### menuItemDivider12+ @@ -117,7 +117,7 @@ If the sum of **startMargin** and **endMargin** exceeds the component width, bot | Name | Type | Mandatory | Description | |---------|--------------------------------------------------------|------------| -------------- | -| options | [DividerStyleOptions](ts-types.md#dividerstyleoptions12) \| undefined | Yes | Style of the menu item divider.
- **strokeWidth**: stroke width of the divider.
- **color**: color of the divider.
- **startMargin**: distance between the divider and the start edge of the menu item.
- **endMargin**: distance between the divider and the end edge of the menu item.| +| options | [DividerStyleOptions](ts-types.md#dividerstyleoptions12) \| undefined | Yes | Style of the menu item divider.
- **strokeWidth**: stroke width of the divider.
- **color**: color of the divider.
- **startMargin**: distance between the divider and the start edge of the menu item.
- **endMargin**: distance between the divider and the end edge of the menu item.
- **mode**: mode of the divider, which is **FLOATING_ABOVE_MENU** by default.| ### menuItemGroupDivider12+ @@ -133,7 +133,7 @@ Sets the style of the top and bottom dividers for the menu item group. If this a | Name | Type | Mandatory | Description | |---------|--------------------------------------------------------|------------| -------------- | -| options | [DividerStyleOptions](ts-types.md#dividerstyleoptions12) \| undefined | Yes | Style of the top and bottom dividers for the menu item group.
- **strokeWidth**: stroke width of the divider. The default value is 1 px.
- **color**: color of the divider. The default value is **#33000000**.
- **startMargin**: distance between the divider and the start edge of the menu item group. The default value is **16**.
- **endMargin**: distance between the divider and the end edge of the menu item group. The default value is **16**.| +| options | [DividerStyleOptions](ts-types.md#dividerstyleoptions12) \| undefined | Yes | Style of the top and bottom dividers for the menu item group.
- **strokeWidth**: stroke width of the divider. The default value is 1 px.
- **color**: color of the divider. The default value is **#33000000**.
- **startMargin**: distance between the divider and the start edge of the menu item group. The default value is **16**.
- **endMargin**: distance between the divider and the end edge of the menu item group. The default value is **16**.
- **mode**: mode of the divider, which is **FLOATING_ABOVE_MENU** by default.| ### subMenuExpandingMode12+ @@ -159,15 +159,17 @@ Enumerates the submenu expanding modes. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Description | -| --------------- | ------------------------------------------ | -| SIDE_EXPAND | Default mode. Submenus are expanded on the side on the same plane.| -| EMBEDDED_EXPAND | Embedded mode. Submenus are expanded while embedded within the main menu. | -| STACK_EXPAND | Stack mode. Submenus are expanded above the main menu. | +| Name | Value| Description | +| --------------- | - | ------------------------------------------ | +| SIDE_EXPAND | 0 | Default mode. Submenus are expanded on the side on the same plane.| +| EMBEDDED_EXPAND | 1 | Embedded mode. Submenus are expanded while embedded within the main menu. | +| STACK_EXPAND | 2 | Stack mode. Submenus are expanded above the main menu. | ## Example -### Example 1 +### Example 1: Implementing a Multi-Level Menu + +This example demonstrates how to implement a multi-level menu by configuring the **builder** parameter in **MenuItem**. ```ts @Entry @@ -235,9 +237,9 @@ struct Index { ![menu](figures/menu.png) -### Example 2 +### Example 2: Setting the Symbol Icon -This example demonstrates a regular menu (using symbol-type icons). +This example demonstrates how to implement a menu with symbol icons by configuring **symbolStartIcon** and **symbolEndIcon**. ```ts // xxx.ets @@ -307,4 +309,4 @@ struct Index { } ``` -![en-us_image_0000001174582862](figures/normal-symbol.jpg) +![en-us_image_0000001174582862](figures/normal-symbol.png) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-menuitem.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-menuitem.md index 3980a0b044519e235f4d2c2fcaa51dda1088d65d..0a8f7b618be5017e71b200e750b24a7fe46e9aca 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-menuitem.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-menuitem.md @@ -26,24 +26,22 @@ MenuItem(value?: MenuItemOptions| CustomBuilder) ## MenuItemOptions -**Atomic service API**: This API can be used in atomic services since API version 11. - **System capability**: SystemCapability.ArkUI.ArkUI.Full | Name | Type | Mandatory| Description | | --------- | ------------------------------------------- | ---- | -------------------------------------- | -| startIcon | [ResourceStr](ts-types.md#resourcestr) | No | Path to the icon displayed on the left of the menu item. | -| content | [ResourceStr](ts-types.md#resourcestr) | No | Content of the menu item. | -| endIcon | [ResourceStr](ts-types.md#resourcestr) | No | Path to the icon displayed on the right of the menu item. | -| labelInfo | [ResourceStr](ts-types.md#resourcestr) | No | Information about the ending label, for example, shortcut **Ctrl+C**.| -| builder | [CustomBuilder](ts-types.md#custombuilder8) | No | Builder for a level-2 menu. | +| startIcon | [ResourceStr](ts-types.md#resourcestr) | No | Path to the icon displayed on the left of the menu item.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| content | [ResourceStr](ts-types.md#resourcestr) | No | Content of the menu item.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| endIcon | [ResourceStr](ts-types.md#resourcestr) | No | Path to the icon displayed on the right of the menu item.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| labelInfo | [ResourceStr](ts-types.md#resourcestr) | No | Information about the ending label, for example, shortcut **Ctrl+C**.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| builder | [CustomBuilder](ts-types.md#custombuilder8) | No | Builder for a level-2 menu.
**Atomic service API**: This API can be used in atomic services since API version 11. | | symbolStartIcon12+ | [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) | No | Path to the symbol icon displayed on the left of the menu item. When this parameter is set, the icon set through **startIcon** is not displayed.
**Atomic service API**: This API can be used in atomic services since API version 12.| | symbolEndIcon12+ | [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) | No | Path to the symbol icon displayed on the right of the menu item. When this parameter is set, the icon set through **endIcon** is not displayed.
**Atomic service API**: This API can be used in atomic services since API version 12.| ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### selected @@ -51,7 +49,8 @@ selected(value: boolean) Sets whether the menu item is selected. -Since API version 10, this parameter supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md). +Since API version 10, this attribute supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md). +Since API version 18, this attribute supports two-way binding through [!!](../../../quick-start/arkts-new-binding.md#two-way-binding-between-built-in-component-parameters). **Atomic service API**: This API can be used in atomic services since API version 11. @@ -59,9 +58,9 @@ Since API version 10, this parameter supports two-way binding through [$$](../.. **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------- | ---- | ----------------------------------- | -| value | boolean | Yes | Whether the menu item is selected.
Default value: **false**| +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------------------------------------ | +| value | boolean | Yes | Whether the menu item is selected.
Default value: **false**
**true**: The menu item is selected.
**false**: The menu item is not selected.| ### selectIcon diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-navdestination.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-navdestination.md index 250b5fdb5fd720340d1b17ce5475f93b337b67c3..1253ab220c9f07705f034c0436cd8bc900a20064 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-navdestination.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-navdestination.md @@ -31,7 +31,7 @@ NavDestination() ## Attributes -The [universal attributes](ts-universal-attributes-size.md) are supported. +The [universal attributes](ts-component-general-attributes.md) are supported. Avoid setting layout-related attributes such as the position and size. They may result in display issues on the page. @@ -160,9 +160,31 @@ Sets the icon of the back button on the title bar. | ------ | ------------------------------------------------------------ | ---- | ------------------ | | value | [ResourceStr](ts-types.md#resourcestr) \| [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) \| [SymbolGlyphModifier12+](ts-universal-attributes-attribute-modifier.md) | Yes | Icon of the back button on the title bar.| +### backButtonIcon18+ + +backButtonIcon(icon: ResourceStr | PixelMap | SymbolGlyphModifier, accessibilityText?: ResourceStr) + +> **NOTE** +> +> The following are not allowed: modify the icon size through the **fontSize** attribute of the **SymbolGlyphModifier** object, change the animation effects through the **effectStrategy** attribute, or change the type of animation effects through the **symbolEffect** attribute. + + +Sets the icon and accessibility text for the back button on the title bar. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------ | +| icon | [ResourceStr](ts-types.md#resourcestr) \| [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) \| [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) | Yes | Icon of the back button on the title bar.| +| accessibilityText | [ResourceStr](ts-types.md#resourcestr) | No| Accessibility text for the back button.
Default value: **back** when the system language is English.| + ### menus12+ -menus(value: Array<NavigationMenuItem> | CustomBuilder) +menus(items: Array<NavigationMenuItem> | CustomBuilder, options?: NavigationMenuOptions) > **NOTE** > @@ -179,7 +201,8 @@ Sets the menu items in the upper right corner of the page. If this attribute is | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------ | -| value | Array<[NavigationMenuItem](ts-basic-components-navigation.md#navigationmenuitem)> \| [CustomBuilder](ts-types.md#custombuilder8) | Yes | Menu items in the upper right corner of the page.| +| items | Array<[NavigationMenuItem](ts-basic-components-navigation.md#navigationmenuitem)> \| [CustomBuilder](ts-types.md#custombuilder8) | Yes | Menu items in the upper right corner of the page.| +| options18+ | [NavigationMenuOptions](ts-basic-components-navigation.md#navigationmenuoptions18) | No | Optional settings for menu items in the upper right corner of the page.| ### ignoreLayoutSafeArea12+ @@ -219,7 +242,7 @@ Sets the style of the system status bar when this **NavDestination** page is dis | Name| Type | Mandatory| Description | | ------ | -------------- | ---- | ------------------ | -| style | Optional<[SystemBarStyle](../js-apis-window.md#systembarstyle12)> | Yes | Style of the system status bar.| +| style | [Optional](ts-universal-attributes-custom-property.md#optional12)<[SystemBarStyle](../js-apis-window.md#systembarstyle12)> | Yes | Style of the system status bar.| > **NOTE** > @@ -247,15 +270,13 @@ recoverable(recoverable: Optional<boolean>) Sets whether the **NavDestination** component is recoverable. If set to recoverable, when the application process exits unexpectedly and restarts, the **NavDestination** component will be automatically recreated. To use this feature, ensure that the **recoverable** attribute is set for the **Navigation** component associated with the **NavDestination** component. -**Atomic service API**: This API can be used in atomic services since API version 14. - **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** | Name| Type | Mandatory| Description | | ------ | -------------- | ---- | ------------------ | -| recoverable | Optional<boolean> | Yes | Whether the **NavDestination** component is recoverable. By default, it is not recoverable.
Default value: **false**
**true**: The **NavDestination** component is recoverable.
**false**: The **NavDestination** component is not recoverable.| +| recoverable | [Optional](ts-universal-attributes-custom-property.md#optional12)<boolean> | Yes | Whether the **NavDestination** component is recoverable. By default, it is not recoverable.
Default value: **false**
**true**: The **NavDestination** component is recoverable.
**false**: The **NavDestination** component is not recoverable.| > **NOTE** > @@ -264,7 +285,7 @@ Sets whether the **NavDestination** component is recoverable. If set to recovera ### bindToScrollable14+ bindToScrollable(scrollers: Array<Scroller>) -Binds the **NavDestination** component to a scrollable container, which can be [List](./ts-container-list.md), [Scroll](./ts-container-scroll.md), [Grid](./ts-container-grid.md), or [WaterFlow](./ts-container-waterflow.md). After the binding, scrolling in the scrollable container will trigger the animations for showing or hiding the title bar and toolbar of all bound **NavDestination** components. A single **NavDestination** component can be bound to multiple scrollable containers, and a single scrollable container can be bound to multiple **NavDestination** components. For details, see [Example 1](#example-1). +Binds the **NavDestination** component with a scrollable container, which can be a [List](./ts-container-list.md), [Scroll](./ts-container-scroll.md), [Grid](./ts-container-grid.md), or [WaterFlow](./ts-container-waterflow.md) component. This way, scrolling in the scrollable container triggers the display and hide animations of the title bar and toolbar of all **NavDestination** components that are bound to it – scrolling up triggers the hide animation, and scrolling down triggers the show animation. A single **NavDestination** component can be bound to multiple scrollable containers, and a single scrollable container can be bound to multiple **NavDestination** components. For details, see [Example 1](#example-1-linking-the-title-bar-and-toolbar-with-scrollable-components). > **NOTE** > @@ -282,9 +303,9 @@ Binds the **NavDestination** component to a scrollable container, which can be [ | scrollers | Array<[Scroller](./ts-container-scroll.md#scroller)> | Yes | Controller of the target scrollable container.| ### bindToNestedScrollable14+ -bindToNestedScrollable(scrollers: Array<NestedScrollInfo>) +bindToNestedScrollable(scrollInfos: Array<NestedScrollInfo>) -Binds the **NavDestination** component to nested scrollable containers, which can be [List](./ts-container-list.md), [Scroll](./ts-container-scroll.md), [Grid](./ts-container-grid.md), or [WaterFlow](./ts-container-waterflow.md). After the binding, scrolling in any of these scrollable containers will trigger the animations for showing or hiding the title bar and toolbar of all bound **NavDestination** components. A single **NavDestination** component can be bound to multiple nested scrollable containers, and a single nested scrollable container can be bound to multiple **NavDestination** components. For details, see [Example 1](#example-1). +Binds the **NavDestination** component with a nested scrollable container, which can be a [List](./ts-container-list.md), [Scroll](./ts-container-scroll.md), [Grid](./ts-container-grid.md), or [WaterFlow](./ts-container-waterflow.md) component. This way, scrolling in the scrollable container triggers the display and hide animations of the title bar and toolbar of all **NavDestination** components that are bound to it – scrolling up triggers the hide animation, and scrolling down triggers the show animation. A single **NavDestination** component can be bound to multiple nested scrollable containers, and a single nested scrollable container can be bound to multiple **NavDestination** components. For details, see [Example 1](#example-1-linking-the-title-bar-and-toolbar-with-scrollable-components). > **NOTE** > @@ -301,13 +322,58 @@ Binds the **NavDestination** component to nested scrollable containers, which ca | ------ | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | | scrollInfos | Array<[NestedScrollInfo](#nestedscrollinfo14)> | Yes | Controller of the target nested scrollable containers.| -### hideBackButton16+ +### hideBackButton15+ hideBackButton(hide: Optional<boolean>) Sets whether to hide the back button in the title bar. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 15. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------------------------------------ | +| hide | [Optional](ts-universal-attributes-custom-property.md#optional12)<boolean> | Yes | Whether to hide the back button in the title bar.
Default value: **false**
**true**: Hide the back button.
**false**: Show the back button.| + +### customTransition15+ + +customTransition(delegate: NavDestinationTransitionDelegate) + +Sets a custom transition animation for the **NavDestination** component. + +> **NOTE** +> +> If both this attribute and [systemTransition](#systemtransition14) are set, whichever is set later takes effect. + +**Atomic service API**: This API can be used in atomic services since API version 15. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------------------------------------ | +| delegate | [NavDestinationTransitionDelegate](#navdestinationtransitiondelegate15) | Yes | Delegate function for custom animations of the **NavDestination** component.| + +### preferredOrientation18+ + +preferredOrientation(orientation: Optional<Orientation>) + +Sets the display orientation for the **NavDestination** component. After the transition to the NavDestination, the system also switches the application's main window to the specified display orientation. + +> **NOTE** +> +> This attribute is effective only if the following conditions are all met: +> 1. The **NavDestination** component belongs to the application's main window page, and the main window is a full-screen window. +> 2. The size of the **Navigation** container to which the **NavDestination** component belongs occupies the entire application page. +> 3. The type of **NavDestination** is [STANDARD](#navdestinationmode11). +> +> The actual effect of setting the display orientation depends on the specific device support. For details, see [setPreferredOrientation](../js-apis-window.md#setpreferredorientation9-1). + +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -315,7 +381,60 @@ Sets whether to hide the back button in the title bar. | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------------------------------------ | -| hide | Optional<boolean> | Yes | Whether to hide the back button in the title bar.
Default value: **false**
**true**: Hide the back button.
**false**: Show the back button.| +| orientation | [Optional](ts-universal-attributes-custom-property.md#optional12)<[Orientation](../js-apis-window.md#orientation9)> | Yes | Display orientation to set.| + +### enableStatusBar18+ + +enableStatusBar(enabled: Optional<boolean>, animated?: boolean) + +Sets whether to show or hide the system status bar when entering this **NavDestination** component. + +> **NOTE** +> +> This attribute is effective only if the following conditions are all met: +> 1. The **NavDestination** component belongs to the application's main window page, and the main window is a full-screen window. +> 2. The size of the **Navigation** container to which the **NavDestination** component belongs occupies the entire application page. +> 3. The size of the **NavDestination** component occupies the entire **Navigation** container. +> 4. The type of **NavDestination** is [STANDARD](#navdestinationmode11). +> +> The actual effect of setting the system status bar depends on the specific device support. For details, see [setSpecificSystemBarEnabled](../js-apis-window.md#setspecificsystembarenabled11). + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------------------------------------ | +| enabled | [Optional](ts-universal-attributes-custom-property.md#optional12)<boolean> | Yes | Whether to show or hide the system status bar when entering the current **NavDestination** component.| +| animated | boolean | No | Whether to use an animation to show or hide the system status bar.
Default value: **false**| + +### enableNavigationIndicator18+ + +enableNavigationIndicator(enabled: Optional<boolean>) + +Sets whether to show or hide the system navigation bar when entering this **NavDestination** component. + +> **NOTE** +> +> This attribute is effective only if the following conditions are all met: +> 1. The **NavDestination** component belongs to the application's main window page, and the main window is a full-screen window. +> 2. The size of the **Navigation** container to which the **NavDestination** component belongs occupies the entire application page. +> 3. The size of the **NavDestination** component occupies the entire **Navigation** container. +> 4. The type of **NavDestination** is [STANDARD](#navdestinationmode11). +> +> The actual effect of setting the system navigation bar depends on the specific device support. For details, see [setSpecificSystemBarEnabled](../js-apis-window.md#setspecificsystembarenabled11). + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------------------------------------ | +| enabled | [Optional](ts-universal-attributes-custom-property.md#optional12)<boolean> | Yes | Whether to show or hide the system navigation bar when entering the current **NavDestination** component.| ## NavDestinationMode11+ @@ -323,23 +442,25 @@ Sets whether to hide the back button in the title bar. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Description | -| ---- | ---------------------------------------- | -| STANDARD | Standard mode. | -| DIALOG | Dialog mode, where the navigation destination is transparent by default, and adding or removing the navigation destination from the navigation stack does not affect the lifecycle of the lower-layer navigation destinations.
System transition animations are supported since API version 13. | +| Name | Value| Description | +| ---- | --- | ---------------------------------------- | +| STANDARD | 0 | Standard mode. | +| DIALOG | 1 | Dialog mode, where the navigation destination is transparent by default, and adding or removing the navigation destination from the navigation stack does not affect the lifecycle of the lower-layer navigation destinations.
System transition animations are supported since API version 13. | ## NavigationSystemTransitionType14+ -**Atomic service API**: This API can be used in atomic services since API version 14. - **System capability**: SystemCapability.ArkUI.ArkUI.Full | Name | Value | Description| | ---- | --- | ----- | -| DEFAULT | 0 | Default system transition animation.| -| NONE| 1 | No system transition animation.| -| TITLE | 2 | System transition animation of the title bar.| -| CONTENT | 3 | System transition animation of the content area.| +| DEFAULT | 0 | Default system transition animation.
**Atomic service API**: This API can be used in atomic services since API version 14.| +| NONE| 1 | No system transition animation.
**Atomic service API**: This API can be used in atomic services since API version 14.| +| TITLE | 2 | System transition animation of the title bar.
**Atomic service API**: This API can be used in atomic services since API version 14.| +| CONTENT | 3 | System transition animation of the content area.
**Atomic service API**: This API can be used in atomic services since API version 14.| +| FADE15+ | 4 | Fade-type system transition animation.
**Atomic service API**: This API can be used in atomic services since API version 15.| +| EXPLODE15+ | 5 | Center-scale type system transition animation.
**Atomic service API**: This API can be used in atomic services since API version 15.| +| SLIDE_RIGHT15+ | 6 | Right-slide type system transition animation.
**Atomic service API**: This API can be used in atomic services since API version 15.| +| SLIDE_BOTTOM15+ | 7 | Bottom-slide type system transition animation.
**Atomic service API**: This API can be used in atomic services since API version 15.| **NOTE** > @@ -353,7 +474,7 @@ Sets whether to hide the back button in the title bar. ## Events -In addition to the [universal events](ts-universal-events-click.md), the following events are supported. +In addition to the [universal events](ts-component-general-events.md), the following events are supported. ### onShown10+ @@ -437,6 +558,70 @@ Called when the **NavDestination** component is about to build a child component **System capability**: SystemCapability.ArkUI.ArkUI.Full +### onResult15+ + +onResult(callback: Optional\\>) + +Triggered when the **NavDestination** component returns. + +**Atomic service API**: This API can be used in atomic services since API version 15. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name| Type| Mandatory| Description| +| ------ | ------ | ---- | ---------------- | +|callback | [Optional](./ts-universal-attributes-custom-property.md)\<[Callback](../../apis-basic-services-kit/js-apis-base.md#callback)\\>| Yes| Callback for page returning, with the parameter being the **result** parameter passed to the **pop** API. If this parameter is not passed, the input is **undefined**.| + +### onActive18+ + +onActive(callback: Optional\\>) + +Triggered when the **NavDestination** component becomes active (on top of the stack and operable, with no special components blocking it). + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name| Type| Mandatory| Description| +| ------ | ------ | ---- | ---------------- | +|callback | [Optional](./ts-universal-attributes-custom-property.md#optional12)\<[Callback](../../apis-basic-services-kit/js-apis-base.md#callback)\<[NavDestinationActiveReason](#navdestinationactivereason18)\>\>| Yes| Reason why the **NavDestination** component switches from inactive to active.| + +### onInactive18+ + +onInactive(callback: Optional\\>) + +Triggered when **NavDestination** component becomes inactive (not on top of the stack and inoperable, or on top but blocked by special components). + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name| Type| Mandatory| Description| +| ------ | ------ | ---- | ---------------- | +|callback | [Optional](./ts-universal-attributes-custom-property.md#optional12)\<[Callback](../../apis-basic-services-kit/js-apis-base.md#callback)\<[NavDestinationActiveReason](#navdestinationactivereason18)\>\>| Yes| Reason why the **NavDestination** component switches from active to inactive.| + +### onNewParam18+ + +onNewParam(callback: Optional\\>) + +Triggered when a **NavDestination** page that already exists in the stack is moved to the top using [launchMode.MOVE_TO_TOP_SINGLETON](./ts-basic-components-navigation.md#launchmode12) or [launchMode.POP_TO_SINGLETON](./ts-basic-components-navigation.md#launchmode12). + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name| Type| Mandatory| Description| +| ------ | ------ | ---- | ---------------- | +|callback | [Optional](./ts-universal-attributes-custom-property.md#optional12)\<[Callback](../../apis-basic-services-kit/js-apis-base.md#callback)\\>| Yes| Callback triggered by **onNewParam**, with the parameter being the data passed to the target page during navigation.| + +> **NOTE** +> +> This callback is not triggered by [replacePath](./ts-basic-components-navigation.md#replacepath11) or [replaceDestination](./ts-basic-components-navigation.md#replacedestination18). + ## NavDestinationCommonTitle **Atomic service API**: This API can be used in atomic services since API version 11. @@ -457,7 +642,7 @@ Called when the **NavDestination** component is about to build a child component | Name | Type | Mandatory | Description | | ------- | ---------------------------------------- | ---- | -------- | | builder | [CustomBuilder](ts-types.md#custombuilder8) | Yes | Content of the title bar.| -| height | [TitleHeight](ts-appendix-enums.md#titleheight9) \| [Length](ts-types.md#length) | Yes | Height of the title bar.| +| height | [TitleHeight](ts-appendix-enums.md#titleheight9) \| [Length](ts-types.md#length) | Yes | Height of the title bar.
Value range: [0, +∞)| ## NavDestinationContext11+ @@ -509,9 +694,65 @@ Provides the information about the nested scrollable containers. | parent | [Scroller](./ts-container-scroll.md#scroller) | Yes| Controller of the target scrollable container.| | child | [Scroller](./ts-container-scroll.md#scroller) | Yes| Controller of the scrollable container nested within the target scrollable container. This scrollable container is a child component of the target scrollable container.| +### NavDestinationActiveReason18+ + +Enumerates the reasons why the activation state of the **NavDestination** component changes. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Value| Description | +| ---- | -- | ---------------------------------------- | +| TRANSITION | 0 | The activation state changes through page navigation. | +| CONTENT_COVER | 1 | The activation state changes due to the opening or closing of a modal page. | +| SHEET | 2 | The activation state changes due to the opening or closing of a sheet.| +| DIALOG | 3 | The activation state changes due to the opening or closing of a custom dialog box.| +| OVERLAY | 4 | The activation state changes due to the opening or closing of an overlay using **OverlayManager**.| +| APP_STATE | 5 | The activation state changes due to switching between foreground and background states of the application.| + +## NavDestinationTransition15+ + +Defines a custom transition animation for the **NavDestination** component. + +**Atomic service API**: This API can be used in atomic services since API version 15. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type |Mandatory| Description| +| ---- | --- | ---- |----- | +| onTransitionEnd | Callback\ | No| Callback triggered when the transition animation ends.| +| duration | number | No| Duration of the transition animation.
Default value: **1000** (in milliseconds)| +| curve | [Curve](ts-appendix-enums.md#curve) | No| Curve type of the animation.
Default value: Curve.EaseInOut](ts-appendix-enums.md#curve)| +| delay | number | No| Delay of the transition animation.
Default value: **0** (in milliseconds)| +| event | Callback\ | Yes| Closure function specifying the transition animation. The system generates the corresponding transition animation based on the modifications to the component's UI state within the closure. For details, see **event** in [animateTo](../js-apis-arkui-UIContext.md#animateto).| + +## NavDestinationTransitionDelegate15+ + +type NavDestinationTransitionDelegate = (operation: NavigationOperation, isEnter: boolean) => Array\ | undefined + +Defines the delegate function for custom transition animations of the **NavDestination** component. + +**Atomic service API**: This API can be used in atomic services since API version 15. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +|------|--------|----|-----------------------| +| operation | [NavigationOperation](ts-basic-components-navigation.md#navigationoperation11) | Yes | Type of navigation operation for the current page transition.| +| isEnter | boolean | Yes | Whether the current page is an entry page.
**true**: The current page is an entry page.
**false**: The current page is not an entry page.| + +**Return value** + +| Type | Description | +|---------|-----------| +| Array<[NavDestinationTransition](#navdestinationtransition15)> \| undefined | Array of custom animations for the **NavDestination** page. If **undefined** is returned, the default system animation is used.| + ## Example -### Example 1 +### Example 1: Linking the Title Bar and Toolbar with Scrollable Components This example shows how to bind a **NavDestination** component to scrollable containers so that scrolling in the scrollable containers triggers the animations for showing or hiding the title bar and toolbar of the **NavDestination** component. @@ -534,7 +775,7 @@ struct MyPageOne { NavDestination() { Scroll(this.scrollScroller) { Column() { - List({space: 0, initialIndex: 0, scroller: this.listScroller}) { + List({ space: 0, initialIndex: 0, scroller: this.listScroller }) { ForEach(this.arr, (item: number, index: number) => { ListItem() { Text('' + item) @@ -542,13 +783,14 @@ struct MyPageOne { .fontSize(16) .textAlign(TextAlign.Center) .width('90%') - .margin({left: '5%'}) + .margin({ left: '5%' }) .borderRadius(10) .backgroundColor(Color.Gray) } }, (item: string) => item); }.width('100%').height('80%').scrollBar(BarState.Off) - .nestedScroll({scrollForward: NestedScrollMode.SELF_FIRST, scrollBackward: NestedScrollMode.SELF_FIRST}) + .nestedScroll({ scrollForward: NestedScrollMode.SELF_FIRST, scrollBackward: NestedScrollMode.SELF_FIRST }) + ForEach(this.arr, (item: number, index: number) => { ListItem() { Text('' + item) @@ -556,7 +798,7 @@ struct MyPageOne { .fontSize(16) .textAlign(TextAlign.Center) .width('90%') - .margin({top: '5%'}) + .margin({ top: '5%' }) .borderRadius(10) .backgroundColor(Color.Pink) } @@ -568,15 +810,15 @@ struct MyPageOne { .scrollable(ScrollDirection.Vertical) .edgeEffect(EdgeEffect.Spring) } - .title('PageOne', {backgroundColor: Color.Yellow, barStyle: BarStyle.STACK}) + .title('PageOne', { backgroundColor: Color.Yellow, barStyle: BarStyle.STACK }) .toolbarConfiguration([ { value: 'item1', symbolIcon: new SymbolGlyphModifier($r('sys.symbol.phone_badge_star')) } - ], {backgroundColor: Color.Orange, barStyle: BarStyle.STACK}) + ], { backgroundColor: Color.Orange, barStyle: BarStyle.STACK }) // Bind the NavDestination component to nested scrollable containers. - .bindToNestedScrollable([{parent: this.scrollScroller, child: this.listScroller}]) + .bindToNestedScrollable([{ parent: this.scrollScroller, child: this.listScroller }]) } } @@ -593,7 +835,7 @@ struct MyPageTwo { build() { NavDestination() { - List({scroller: this.listScroller}) { + List({ scroller: this.listScroller }) { ForEach(this.arr, (item: number, index: number) => { ListItem() { Text('' + item) @@ -601,20 +843,20 @@ struct MyPageTwo { .fontSize(16) .textAlign(TextAlign.Center) .width('90%') - .margin({left: '5%'}) + .margin({ left: '5%' }) .borderRadius(10) .backgroundColor(Color.Gray) } }, (item: string) => item); }.width('100%') } - .title('PageTwo', {backgroundColor: Color.Yellow, barStyle: BarStyle.STACK}) + .title('PageTwo', { backgroundColor: Color.Yellow, barStyle: BarStyle.STACK }) .toolbarConfiguration([ { value: 'item1', symbolIcon: new SymbolGlyphModifier($r('sys.symbol.phone_badge_star')) } - ], {backgroundColor: Color.Orange, barStyle: BarStyle.STACK}) + ], { backgroundColor: Color.Orange, barStyle: BarStyle.STACK }) // Bind the NavDestination component to a scrollable container. .bindToScrollable([this.listScroller]) } @@ -638,19 +880,486 @@ struct Index { Navigation(this.stack) { Column() { Button('push PageOne').onClick(() => { - this.stack.pushPath({name: 'myPageOne'}) + this.stack.pushPath({ name: 'myPageOne' }) }) Button('push PageTwo').onClick(() => { - this.stack.pushPath({name: 'myPageTwo'}) + this.stack.pushPath({ name: 'myPageTwo' }) }) }.height('40%').justifyContent(FlexAlign.SpaceAround) }.width('100%') .height('100%') - .title({main: 'MainTitle', sub: 'subTitle'}) + .title({ main: 'MainTitle', sub: 'subTitle' }) .navDestination(this.MyPageMap) } } ``` ![navdestination_bind_scrollable](figures/navdestination_bind_scrollable.gif) -For more examples, see [Example in Navigation](ts-basic-components-navigation.md#example-1-implementing-a-navigation-page-layout). +### Example 2: Setting a Custom Transitions for the NavDestination Component + +The following example demonstrates how to set a custom transition animation for the **NavDestination** component using [customTransition](#customtransition15). + +```ts +@Entry +@Component +struct NavDestinationCustomTransition { + stack: NavPathStack = new NavPathStack() + + @Builder + pageMap(name: string) { + if (name) { + NavDest() + } + } + + aboutToAppear(): void { + this.stack.pushPath({name: 'dest0'}) + } + + build() { + Navigation(this.stack) { + // empty + } + .navDestination(this.pageMap) + .hideNavBar(true) + .title('Main Page') + .titleMode(NavigationTitleMode.Mini) + } +} + +declare type voidFunc = () => void; + +@Component +struct NavDest { + @State name: string = 'NA' + @State destWidth: string = '100%' + stack: NavPathStack = new NavPathStack() + @State y: string = '0'; + + build() { + NavDestination() { + Column() { + Button('push next page', { stateEffect: true, type: ButtonType.Capsule }) + .width('80%') + .height(40) + .margin(20) + .onClick(() => { + this.stack.pushPath({ name: this.name == 'PageOne' ? "PageTwo" : "PageOne" }) + }) + } + .size({ width: '100%', height: '100%' }) + } + .title(this.name) + .translate({ y: this.y }) + .onReady((context) => { + this.name = context.pathInfo.name; + this.stack = context.pathStack; + }) + .backgroundColor(this.name == 'PageOne' ? '#F1F3F5' : '#ff11dee5') + .customTransition( + (op: NavigationOperation, isEnter: boolean) + : Array | undefined => { + console.log('[NavDestinationTransition]', 'reached delegate in frontend, op: ' + op + ', isEnter: ' + isEnter); + + let transitionOneEvent: voidFunc = () => { console.log('[NavDestinationTransition]', 'reached transitionOne, empty now!'); } + let transitionOneFinishEvent: voidFunc = () => { console.log('[NavDestinationTransition]', 'reached transitionOneFinish, empty now!'); } + let transitionOneDuration: number = 500; + if (op === NavigationOperation.PUSH) { + if (isEnter) { + // ENTER_PUSH + this.y = '100%'; + transitionOneEvent = () => { + console.log('[NavDestinationTransition]', 'transitionOne, push & isEnter'); + this.y = '0'; + } + } else { + // EXIT_PUSH + this.y = '0'; + transitionOneEvent = () => { + console.log('[NavDestinationTransition]', 'transitionOne, push & !isEnter'); + this.y = '0'; + } + transitionOneDuration = 450 + } + } else if (op === NavigationOperation.POP) { + if (isEnter) { + // ENTER_POP + this.y = '0'; + transitionOneEvent = () => { + console.log('[NavDestinationTransition]', 'transitionOne, pop & isEnter'); + this.y = '0'; + } + } else { + // EXIT_POP + this.y = '0'; + transitionOneEvent = () => { + console.log('[NavDestinationTransition]', 'transitionOne, pop & !isEnter'); + this.y = '100%'; + } + } + } else { + console.log('[NavDestinationTransition]', '----- NOT-IMPL BRANCH of NAV-DESTINATION CUSTOM TRANSITION -----'); + } + + let transitionOne: NavDestinationTransition = { + duration: transitionOneDuration, + delay: 0, + curve: Curve.Friction, + event: transitionOneEvent, + onTransitionEnd: transitionOneFinishEvent + }; + + let transitionTwoEvent: voidFunc = () => { console.log('[NavDestinationTransition]', 'reached transitionTwo, empty now!'); } + let transitionTwo: NavDestinationTransition = { + duration: 1000, + delay: 0, + curve: Curve.EaseInOut, + event: transitionTwoEvent, + onTransitionEnd: () => { console.log('[NavDestinationTransition]', 'reached Two\'s finish'); } + }; + + return [ + transitionOne, + transitionTwo, + ]; + }) + } +} +``` +![navdestination_custom_transition](figures/navdestination_custom_transition.gif) + +### Example 3: Setting System Transition Animations for the NavDestination Component + +The following example demonstrates how to set system transition animations using [systemTransition](#systemtransition14) with **Fade**, **Explode**, **SlideBottom**, and **SlideRight** effects. + +```ts +@Entry +@Component +struct NavDestinationSystemTransition { + @Provide stack: NavPathStack = new NavPathStack() + @Provide homePageTransitionType: NavigationSystemTransitionType = NavigationSystemTransitionType.DEFAULT; + + @Builder + pageMap(name: string) { + if (name === 'Fade') { + Fade() + } else if (name === 'Explode') { + Explode() + } else if (name === 'SlideRight') { + SlideRight() + } else if (name === 'SlideBottom') { + SlideBottom() + } else { + Dest() + } + } + + aboutToAppear(): void { + this.stack.pushPath({name: 'Dest'}) + } + + build() { + Navigation(this.stack) { + // empty + } + .navDestination(this.pageMap) + .hideNavBar(true) + } +} + +@Component +struct Dest { + @Consume stack: NavPathStack; + @Consume homePageTransitionType: NavigationSystemTransitionType; + @State name: string = 'NA'; + + build() { + NavDestination() { + HomeBody() + } + .title('Navigation System Animation') + .onReady((context) => { + this.name = context.pathInfo.name + }) + .systemTransition(this.homePageTransitionType) + } +} + +@Component +struct Fade { + @Consume stack: NavPathStack; + @State name: string = 'NA'; + + build() { + NavDestination() { + DestBody({ + name: this.name + }) + } + .title(this.name) + .onReady((context) => { + this.name = context.pathInfo.name + }) + .systemTransition(NavigationSystemTransitionType.FADE) + } +} + +@Component +struct Explode { + @Consume stack: NavPathStack; + @State name: string = 'NA'; + + build() { + NavDestination() { + DestBody({ + name: this.name + }) + } + .title(this.name) + .onReady((context) => { + this.name = context.pathInfo.name + }) + .systemTransition(NavigationSystemTransitionType.EXPLODE) + } +} + +@Component +struct SlideRight { + @Consume stack: NavPathStack; + @State name: string = 'NA'; + + build() { + NavDestination() { + DestBody({ + name: this.name + }) + } + .title(this.name) + .onReady((context) => { + this.name = context.pathInfo.name + }) + .systemTransition(NavigationSystemTransitionType.SLIDE_RIGHT) + } +} + +@Component +struct SlideBottom { + @Consume stack: NavPathStack; + @State name: string = 'NA'; + + build() { + NavDestination() { + DestBody({ + name: this.name + }) + } + .title(this.name) + .onReady((context) => { + this.name = context.pathInfo.name + }) + .systemTransition(NavigationSystemTransitionType.SLIDE_BOTTOM) + } +} + +@Component +struct DestBody { + name: string = 'NA' + + columnTextSize: number = 22 + columnTextFontWeight: FontWeight = FontWeight.Bolder + columnWidth: string = '65%' + columnPadding: number = 22 + columnMargin: number = 10 + columnBorderRadius: number = 10 + + build() { + Column() { + Column() + .width('85') + .height(50) + .backgroundColor(Color.White) + Column() { + Text(this.name) + .fontSize(this.columnTextSize) + .fontWeight(this.columnTextFontWeight) + } + .width(this.columnWidth) + .padding(this.columnPadding) + .margin(this.columnMargin) + .borderRadius(this.columnBorderRadius) + .shadow(ShadowStyle.OUTER_DEFAULT_LG) + } + } +} + +@Component +struct HomeBody { + @Consume stack: NavPathStack; + @Consume homePageTransitionType: NavigationSystemTransitionType; + + columnTextSize: number = 22 + columnTextFontWeight: FontWeight = FontWeight.Bolder + columnWidth: string = '85%' + columnPadding: number = 22 + columnMargin: number = 10 + columnBorderRadius: number = 10 + columnShadow: ShadowStyle = ShadowStyle.OUTER_DEFAULT_MD + + build() { + Column() { + Search({ value: 'Search' }) + .width(this.columnWidth) + + Column() { + Text('fade') + .fontSize(this.columnTextSize) + .fontWeight(this.columnTextFontWeight) + } + .width(this.columnWidth) + .padding(this.columnPadding) + .margin(this.columnMargin) + .borderRadius(this.columnBorderRadius) + .shadow(this.columnShadow) + .onClick(() => { + this.homePageTransitionType = NavigationSystemTransitionType.FADE + this.stack.pushPath({name: 'Fade'}) + }) + + Column() { + Text('explode') + .fontSize(this.columnTextSize) + .fontWeight(this.columnTextFontWeight) + } + .width(this.columnWidth) + .padding(this.columnPadding) + .margin(this.columnMargin) + .borderRadius(this.columnBorderRadius) + .shadow(this.columnShadow) + .onClick(() => { + this.homePageTransitionType = NavigationSystemTransitionType.EXPLODE + this.stack.pushPath({name: 'Explode'}) + }) + + Column() { + Text('slide right') + .fontSize(this.columnTextSize) + .fontWeight(this.columnTextFontWeight) + } + .width(this.columnWidth) + .padding(this.columnPadding) + .margin(this.columnMargin) + .borderRadius(this.columnBorderRadius) + .shadow(this.columnShadow) + .onClick(() => { + this.homePageTransitionType = NavigationSystemTransitionType.SLIDE_RIGHT + this.stack.pushPath({name: 'SlideRight'}) + }) + + Column() { + Text('slide bottom') + .fontSize(this.columnTextSize) + .fontWeight(this.columnTextFontWeight) + } + .width(this.columnWidth) + .padding(this.columnPadding) + .margin(this.columnMargin) + .borderRadius(this.columnBorderRadius) + .shadow(this.columnShadow) + .onClick(() => { + this.homePageTransitionType = NavigationSystemTransitionType.SLIDE_BOTTOM + this.stack.pushPath({name: 'SlideBottom'}) + }) + } + } +} +``` +![navdestination_fade](figures/navdestination_fade_transition.gif) +![navdestination_explode](figures/navdestination_explode_transition.gif) +![navdestination_slide_bottom](figures/navdestination_slide_bottom_transition.gif) +![navdestination_slide_right](figures/navdestination_slide_right_transition.gif) + +### Example 4: Configuring Display Orientation and Status Bar and Navigation Bar Visibility + +This example demonstrates how to configure each **NavDestination** component with specific display orientations and control the visibility of the status bar and navigation bar. + +```ts +import { window } from '@kit.ArkUI'; + +@Component +struct PortraitPage { + private stack: NavPathStack | undefined = undefined; + build() { + NavDestination() { + Stack({alignContent: Alignment.Center}) { + Button('push LANDSCAPE page').onClick(() => { + this.stack?.pushPath({name: 'landscape'}) + }) + }.width('100%').height('100%') + } + .width('100%').height('100%') + .title('PortraitPage') + .preferredOrientation(window.Orientation.PORTRAIT) // Portrait orientation. + .enableStatusBar (true) // Show the status bar. + .enableNavigationIndicator(true) // Show the navigation bar. + .backgroundColor('#ffbaece9') + .onReady((ctx: NavDestinationContext) => { + this.stack = ctx.pathStack; + }) + } +} + +@Component +struct LandscapePage { + private stack: NavPathStack | undefined = undefined; + build() { + NavDestination() { + Stack({alignContent: Alignment.Center}) { + Button('push PORTRAIT page').onClick(() => { + this.stack?.pushPath({name: 'portrait'}) + }) + }.width('100%').height('100%') + } + .width('100%').height('100%') + .title('LandscapePage') + .preferredOrientation(window.Orientation.LANDSCAPE) // Landscape orientation. + .enableStatusBar(false) // Hide the status bar. + .enableNavigationIndicator(false) // Hide the navigation bar. + .backgroundColor('#ffecb8b8') + .ignoreLayoutSafeArea([LayoutSafeAreaType.SYSTEM], [LayoutSafeAreaEdge.TOP, LayoutSafeAreaEdge.BOTTOM]) + .onReady((ctx: NavDestinationContext) => { + this.stack = ctx.pathStack; + }) + } +} + +@Entry +@Component +struct ExamplePage { + private stack: NavPathStack = new NavPathStack(); + + aboutToAppear(): void { + this.stack.pushPath({name: "portrait"}) + } + + @Builder + MyPageMap(name: string) { + if (name === 'portrait') { + PortraitPage() + } else { + LandscapePage() + } + } + + build() { + Navigation(this.stack) { + } + .width('100%') + .height('100%') + .hideNavBar(true) + .navDestination(this.MyPageMap) + } +} +``` +![navdestination_orientation](figures/navdestination_orientation.gif) + +For more usage of the **NavDestination** component, see [Example in Navigation](ts-basic-components-navigation.md#example). diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-navigation.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-navigation.md index 9d353a594ad0380742c55ad172045538b30be0ea..0a0c60096f760051d894aed213b8dc90a3da1f03 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-navigation.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-navigation.md @@ -49,7 +49,7 @@ Binds a navigation stack to the **Navigation** component. ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### title @@ -65,7 +65,7 @@ Sets the page title. | Name | Type | Mandatory| Description | | ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| value | [ResourceStr](ts-types.md#resourcestr)10+ \| [CustomBuilder](ts-types.md#custombuilder8) \| [NavigationCommonTitle](#navigationcommontitle9)9+ \| [NavigationCustomTitle](#navigationcustomtitle9)9+ | Yes | Page title. When the NavigationCustomTitle type is used to set the height, [titleMode](#titlemode) does not take effect. When the title string is too long: (1) If no subtitle is set, the string is scaled down, wrapped in two lines, and then clipped with an ellipsis (...); (2) If a subtitle is set, the subtitle is scaled down and then clipped with an ellipsis (...).| +| value | [ResourceStr](ts-types.md#resourcestr)10+ \| [CustomBuilder](ts-types.md#custombuilder8) \| [NavigationCommonTitle](#navigationcommontitle9)9+ \| [NavigationCustomTitle](#navigationcustomtitle9)9+ | Yes | Page title. When the NavigationCustomTitle type is used to set the height, [titleMode](#titlemode) does not take effect. When the title string is too long: (1) If no subtitle is set, the string is scaled down, wrapped in two lines, and then clipped. (2) If a subtitle is set, the subtitle is scaled down and then clipped.| | options | [NavigationTitleOptions](#navigationtitleoptions11)11+ | No | Title bar options. | ### subTitle(deprecated) @@ -86,7 +86,7 @@ This API is deprecated since API version 9. You are advised to use [title](#titl ### menus -menus(value: Array<NavigationMenuItem> | CustomBuilder) +menus(items: Array<NavigationMenuItem> | CustomBuilder, options?: NavigationMenuOptions) > **NOTE** > @@ -103,7 +103,8 @@ Sets the menu items in the upper right corner of the page. If this attribute is | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ---------------- | -| value | Array<[NavigationMenuItem](#navigationmenuitem)> \| [CustomBuilder](ts-types.md#custombuilder8) | Yes | Menu items in the upper right corner of the page.| +| items | Array<[NavigationMenuItem](#navigationmenuitem)> \| [CustomBuilder](ts-types.md#custombuilder8) | Yes | Menu items in the upper right corner of the page.| +| options18+ | [NavigationMenuOptions](#navigationmenuoptions18) | No | Optional settings for menu items in the upper right corner of the page.| ### titleMode @@ -125,7 +126,7 @@ Sets the display mode of the page title bar. toolBar(value: object | CustomBuilder) -Sets the content of the toolbar. If this attribute is not set, no toolbar is displayed. Toolbar items are evenly distributed on the bottom toolbar, with text and icons evenly spaced in each content area. If any item contains overlong text and there are fewer than five items, the toolbar will reduce the text size progressively, wrap the text over two lines if necessary, and then clip the text with an ellipsis (...) to fit. +Sets the content of the toolbar. If this attribute is not set, no toolbar is displayed. Toolbar items are evenly distributed on the bottom toolbar, with text and icons evenly spaced in each content area. If any item contains overlong text and there are fewer than five items, the toolbar will reduce the text size progressively, wrap the text over two lines if necessary, and then clip the text to fit. This API is deprecated since API version 10. You are advised to use [toolbarConfiguration](#toolbarconfiguration10) instead. @@ -164,7 +165,7 @@ Sets the content of the toolbar. If this attribute is not set, no toolbar is dis | Name | Type | Mandatory| Description | | ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| value | Array<[ToolbarItem](#toolbaritem10)> \| [CustomBuilder](ts-types.md#custombuilder8) | Yes | Content of the toolbar. When configured with Array<[ToolbarItem](#toolbaritem10)>, the toolbar follows the rules below:
Toolbar items are evenly distributed on the bottom toolbar, with text and icons evenly spaced in each content area.
- If any item contains overlong text and there are fewer than five items, the toolbar will: 1. Increase the item width to accommodate the text until the toolbar spans the screen width; 2. Reduce the text size progressively; 3. Wrap the text over two lines; 4. Clip the text with an ellipsis (...).
In portrait mode, the toolbar shows a maximum of five icons, with any additional icons placed under an automatically generated **More** icon. In landscape mode, the behavior of the toolbar is determined by the display mode: (1) If the display mode is [Split](#navigationmode9), the toolbar follows the same rules as in portrait mode. (2) If the display mode is [Stack](#navigationmode9), the toolbar must be used together with Array<[NavigationMenuItem](#navigationmenuitem)> of the **menus** attribute; in this configuration, the bottom toolbar is automatically hidden, and all items on the toolbar are relocated to the menu in the upper right corner of the screen.
When configured with [CustomBuilder](ts-types.md#custombuilder8), the toolbar does not follow the above rules, except for evenly distributing items at the bottom of the toolbar.| +| value | Array<[ToolbarItem](#toolbaritem10)> \| [CustomBuilder](ts-types.md#custombuilder8) | Yes | Content of the toolbar. When configured with Array<[ToolbarItem](#toolbaritem10)>, the toolbar follows the rules below:
Toolbar items are evenly distributed on the bottom toolbar, with text and icons evenly spaced in each content area.
- If any item contains overlong text and there are fewer than five items, the toolbar will: 1. Increase the item width to accommodate the text until the toolbar spans the screen width; 2. Reduce the text size progressively; 3. Wrap the text over two lines; 4. Clip the text.
In portrait mode, the toolbar shows a maximum of five icons, with any additional icons placed under an automatically generated **More** icon. In landscape mode, the behavior of the toolbar is determined by the display mode: (1) If the display mode is [Split](#navigationmode9), the toolbar follows the same rules as in portrait mode. (2) If the display mode is [Stack](#navigationmode9), the toolbar must be used together with Array<[NavigationMenuItem](#navigationmenuitem)> of the **menus** attribute; in this configuration, the bottom toolbar is automatically hidden, and all items on the toolbar are relocated to the menu in the upper right corner of the screen.
When configured with [CustomBuilder](ts-types.md#custombuilder8), the toolbar does not follow the above rules, except for evenly distributing items at the bottom of the toolbar.| | options | [NavigationToolbarOptions](#navigationtoolbaroptions11)11+ | No | Toolbar options. | ### hideToolBar @@ -285,7 +286,7 @@ Sets the position of the navigation bar. This attribute takes effect only when t mode(value: NavigationMode) -Sets the display mode of the navigation bar. Available options are **Stack**, **Split**, and **Auto**. +Sets the display mode of the page title bar. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -318,6 +319,28 @@ Sets the icon of the back button in the title bar. | ------ | ------------------------------------------------------------ | ---- | -------------------- | | value | string \| [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) \| [SymbolGlyphModifier12+](ts-universal-attributes-attribute-modifier.md) | Yes | Icon of the back button in the title bar.| +### backButtonIcon18+ + +backButtonIcon(icon: ResourceStr | PixelMap | SymbolGlyphModifier, accessibilityText?: ResourceStr) + +> **NOTE** +> +> The following are not allowed: modify the icon size through the **fontSize** attribute of the **SymbolGlyphModifier** object, change the animation effects through the **effectStrategy** attribute, or change the type of animation effects through the **symbolEffect** attribute. + + +Sets the icon and accessibility text for the back button on the title bar. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------ | +| icon | [ResourceStr](ts-types.md#resourcestr) \| [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) \| [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) | Yes | Icon of the back button in the title bar.| +| accessibilityText | [ResourceStr](ts-types.md#resourcestr) | No| Accessibility text for the back button.
Default value: **back** when the system language is English.| + ### hideNavBar9+ hideNavBar(value: boolean) @@ -334,7 +357,7 @@ From API version 9 to API version 10, this attribute takes effect only in dual-c | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ---------------------------------- | -| value | boolean | Yes | Whether to hide the navigation bar.
Default value: **false**| +| value | boolean | Yes | Whether to hide the navigation bar.
Default value: **false**
**true**: Hide the navigation bar.
**false**: Show the navigation bar.| ### navDestination10+ @@ -434,7 +457,7 @@ Sets the style of the system status bar when the home page of the **Navigation** | Name| Type | Mandatory| Description | | ------ | -------------- | ---- | ------------------ | -| style | Optional<[SystemBarStyle](#systembarstyle12)> | Yes | Style of the system status bar.| +| style | [Optional](ts-universal-attributes-custom-property.md#optional12)<[SystemBarStyle](#systembarstyle12)> | Yes | Style of the system status bar.| > **Instructions** > @@ -454,15 +477,13 @@ recoverable(recoverable: Optional<boolean>) Sets whether the **Navigation** component is recoverable. If set to recoverable, when the application process exits unexpectedly and restarts, the **Navigation** component will be automatically recreated, and the navigation stack will be restored to the state at the time of the unexpected exit. -**Atomic service API**: This API can be used in atomic services since API version 14. - **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** | Name| Type | Mandatory| Description | | ------ | -------------- | ---- | ------------------ | -| recoverable | Optional<boolean> | Yes | Whether the **Navigation** component is recoverable. By default, it is not recoverable.
Default value: **false**
**true**: The **Navigation** component is recoverable.
**false**: The **Navigation** component is not recoverable.| +| recoverable | [Optional](ts-universal-attributes-custom-property.md#optional12)<boolean> | Yes | Whether the **Navigation** component is recoverable. By default, it is not recoverable.
Default value: **false**
**true**: The **Navigation** component is recoverable.
**false**: The **Navigation** component is not recoverable.| > **Instructions** > @@ -484,7 +505,7 @@ Sets whether to display a drag bar in split-column scenarios. | Name| Type | Mandatory| Description | | ------ | -------------- | ---- | ------------------ | -| enableDragBar | Optional<boolean> | Yes | Whether to enable the drag bar. By default, there is no drag bar.
Default value: **false**
**true**: Enable the drag bar.
**false**: Disable the drag bar.| +| isEnabled | [Optional](ts-universal-attributes-custom-property.md#optional12)<boolean> | Yes | Whether to enable the drag bar. By default, there is no drag bar.
Default value: **false**
**true**: Enable the drag bar.
**false**: Disable the drag bar.| ### enableModeChangeAnimation15+ @@ -500,7 +521,23 @@ Sets whether to enable the animation for switching between single and double col | Name| Type | Mandatory| Description | | ------ | -------------- | ---- | ------------------ | -| enableModeChangeAnimation | Optional<boolean> | Yes | Whether to enable the animation for switching between single and double column modes.
Default value: **true**
**true**: Enable the animation.
**false**: Disable the animation.| +| isEnabled | [Optional](ts-universal-attributes-custom-property.md#optional12)<boolean> | Yes | Whether to enable the animation for switching between single and double column modes.
Default value: **true**
**true**: Enable the animation for switching between single and double column modes.
**false**: Disable the animation for switching between single and double column modes.| + +### enableToolBarAdaptation18+ + +enableToolBarAdaptation(enable: Optional<boolean>) + +Sets whether to enable toolbar adaptation for the **Navigation** and **NavDestination** components. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------- | ---- | ------------------ | +| enable | Optional<boolean> | Yes |Whether to enable toolbar adaptation. Default value: **true**
**true**: Enable toolbar adaptation.
**false**: Disable toolbar adaptation.| ## Events @@ -610,7 +647,7 @@ Pushes the navigation destination page specified by **info** onto the navigation | Name | Type | Mandatory | Description | | ---- | ----------------------------- | ---- | -------------------- | | info | [NavPathInfo](#navpathinfo10) | Yes | Information about the navigation destination page.| -| animated11+ | boolean | No | Whether to support transition animation.
Default value: **true**| +| animated11+ | boolean | No | Whether to support the transition animation.
Default value: **true**
**true**: The transition animation is supported.
**false**: The transition animation is not supported.| ### pushPath12+ @@ -645,7 +682,7 @@ Pushes the navigation destination page specified by **name**, with the data spec | ----- | ------- | ---- | --------------------- | | name | string | Yes | Name of the navigation destination page. | | param | unknown | Yes | Detailed parameters of the navigation destination page.| -| animated11+ | boolean | No | Whether to support transition animation.
Default value: **true**| +| animated11+ | boolean | No | Whether to support the transition animation.
Default value: **true**
**true**: The transition animation is supported.
**false**: The transition animation is not supported.| ### pushPathByName11+ @@ -664,7 +701,7 @@ Pushes the navigation destination page specified by **name**, with the data spec | name | string | Yes | Name of the navigation destination page. | | param | Object | Yes | Detailed parameters of the navigation destination page.| | onPop | Callback\<[PopInfo](#popinfo11)> | Yes| Callback used to receive the result. It is invoked only after the **result** parameter is set in **pop**.| -| animated | boolean | No | Whether to support transition animation.
Default value: **true**| +| animated | boolean | No | Whether to support the transition animation.
Default value: **true**
**true**: The transition animation is supported.
**false**: The transition animation is not supported.| ### pushDestination11+ @@ -681,7 +718,7 @@ Pushes the navigation destination page specified by **info** onto the navigation | Name | Type | Mandatory | Description | | ---- | ----------------------------- | ---- | -------------------- | | info | [NavPathInfo](#navpathinfo10) | Yes | Information about the navigation destination page.| -| animated | boolean | No | Whether to support transition animation.
Default value: **true**| +| animated | boolean | No | Whether to support the transition animation.
Default value: **true**
**true**: The transition animation is supported.
**false**: The transition animation is not supported.| **Return value** @@ -750,7 +787,7 @@ Pushes the navigation destination page specified by **name**, with the data spec | ----- | ------- | ---- | --------------------- | | name | string | Yes | Name of the navigation destination page. | | param | Object | Yes | Detailed parameters of the navigation destination page.| -| animated | boolean | No | Whether to support transition animation.
Default value: **true**| +| animated | boolean | No | Whether to support the transition animation.
Default value: **true**
**true**: The transition animation is supported.
**false**: The transition animation is not supported.| **Return value** @@ -786,7 +823,7 @@ Pushes the navigation destination page specified by **name**, with the data spec | name | string | Yes | Name of the navigation destination page. | | param | Object | Yes | Detailed parameters of the navigation destination page.| | onPop | Callback\<[PopInfo](#popinfo11)> | Yes | Callback used to handle the result returned when the page is popped out of the stack. It is invoked only after the **result** parameter is set in **pop**.| -| animated | boolean | No | Whether to support transition animation.
Default value: **true**| +| animated | boolean | No | Whether to support the transition animation.
Default value: **true**
**true**: The transition animation is supported.
**false**: The transition animation is not supported.| **Return value** @@ -819,8 +856,8 @@ Replaces the top of the navigation stack with the page specified by **info**. | Name | Type | Mandatory | Description | | ---- | ----------------------------- | ---- | -------------------- | -| info | [NavPathInfo](#navpathinfo10) | Yes | Parameters of the page to replace the top of the navigation stack.| -| animated11+ | boolean | No | Whether to support transition animation.
Default value: **true**| +| info | [NavPathInfo](#navpathinfo10) | Yes | Parameters for the new top page of the navigation stack.| +| animated11+ | boolean | No | Whether to support the transition animation.
Default value: **true**
**true**: The transition animation is supported.
**false**: The transition animation is not supported.| ### replacePath12+ @@ -855,15 +892,15 @@ Replaces the top of the navigation stack with the page specified by **name**. | ----- | ------- | ---- | --------------------- | | name | string | Yes | Name of the navigation destination page. | | param | Object | Yes | Detailed parameters of the navigation destination page.| -| animated11+ | boolean | No | Whether to support transition animation.
Default value: **true**| +| animated11+ | boolean | No | Whether to support the transition animation.
Default value: **true**
**true**: The transition animation is supported.
**false**: The transition animation is not supported.| -### replaceDestination14+ +### replaceDestination18+ replaceDestination(info: NavPathInfo, options?: NavigationOptions): Promise<void> Performs a replacement operation on the navigation stack This API uses a promise to return the result. Its behavior varies depending on the value of [LaunchMode](#launchmode12) specified in **options**. -**Atomic service API**: This API can be used in atomic services since API version 14. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -905,7 +942,7 @@ Removes the navigation destination pages specified by **indexes** from the navig | Name | Type | Mandatory | Description | | ----- | ------- | ---- | --------------------- | -| indexes | Array | Yes | Array of indexes of the navigation destination pages to remove. | +| indexes | Array | Yes | Array of indexes of the navigation destination pages to remove. The index is zero-based. | **Return value** @@ -955,7 +992,7 @@ Removes the navigation destination page specified by **navDestinationId** from t | Type | Description | | ----------- | ------------------------ | -| boolean | Whether the page is removed successfully. The value **true** indicates that the page is removed successfully.| +| boolean | Whether the page is removed successfully.
**true**: success
**false**: failure| ### pop10+ @@ -971,7 +1008,7 @@ Pops the top element out of the navigation stack. | Name | Type | Mandatory | Description | | ---- | ----------------------------- | ---- | -------------------- | -| animated11+ | boolean | No | Whether to support transition animation.
Default value: **true**| +| animated11+ | boolean | No | Whether to support the transition animation.
Default value: **true**
**true**: The transition animation is supported.
**false**: The transition animation is not supported.| **Return value** @@ -995,7 +1032,7 @@ Pops the top element out of the navigation stack and invokes the **onPop** callb | Name | Type | Mandatory | Description | | ---- | ----------------------------- | ---- | -------------------- | | result | Object | Yes| Custom processing result on the page. The boolean type is not supported.| -| animated | boolean | No | Whether to support transition animation.
Default value: **true**| +| animated | boolean | No | Whether to support the transition animation.
Default value: **true**
**true**: The transition animation is supported.
**false**: The transition animation is not supported.| **Return value** @@ -1019,7 +1056,7 @@ Pops pages until the first navigation destination page that matches **name** fro | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ------------------- | | name | string | Yes | Name of the navigation destination page.| -| animated11+ | boolean | No | Whether to support transition animation.
Default value: **true**| +| animated11+ | boolean | No | Whether to support the transition animation.
Default value: **true**
**true**: The transition animation is supported.
**false**: The transition animation is not supported.| **Return value** @@ -1043,7 +1080,7 @@ Pops pages until the first navigation destination page that matches **name** fro | ---- | ------ | ---- | ------------------- | | name | string | Yes | Name of the navigation destination page.| | result | Object | Yes| Custom processing result on the page. The boolean type is not supported.| -| animated | boolean | No | Whether to support transition animation.
Default value: **true**| +| animated | boolean | No | Whether to support the transition animation.
Default value: **true**
**true**: The transition animation is supported.
**false**: The transition animation is not supported.| **Return value** @@ -1065,8 +1102,8 @@ Returns the navigation stack to the page specified by **index**. | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ---------------------- | -| index | number | Yes | Index of the navigation destination page.| -| animated11+ | boolean | No | Whether to support transition animation.
Default value: **true**| +| index | number | Yes | Index of the navigation destination page. The index is zero-based.| +| animated11+ | boolean | No | Whether to support the transition animation.
Default value: **true**
**true**: The transition animation is supported.
**false**: The transition animation is not supported.| ### popToIndex11+ @@ -1082,9 +1119,9 @@ Returns the navigation stack to the page specified by **index** and invokes the | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ---------------------- | -| index | number | Yes | Index of the navigation destination page.| +| index | number | Yes | Index of the navigation destination page. The index is zero-based.| | result | Object | Yes| Custom processing result on the page. The boolean type is not supported.| -| animated | boolean | No | Whether to support transition animation.
Default value: **true**| +| animated | boolean | No | Whether to support the transition animation.
Default value: **true**
**true**: The transition animation is supported.
**false**: The transition animation is not supported.| ### moveToTop10+ @@ -1101,7 +1138,7 @@ Moves the first navigation destination page that matches **name** from the botto | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ------------------- | | name | string | Yes | Name of the navigation destination page.| -| animated11+ | boolean | No | Whether to support transition animation.
Default value: **true**| +| animated11+ | boolean | No | Whether to support the transition animation.
Default value: **true**
**true**: The transition animation is supported.
**false**: The transition animation is not supported.| **Return value** @@ -1123,8 +1160,8 @@ Moves to the top of the navigation stack the navigation destination page specifi | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ---------------------- | -| index | number | Yes | Index of the navigation destination page.| -| animated11+ | boolean | No | Whether to support transition animation.
Default value: **true**| +| index | number | Yes | Index of the navigation destination page. The index is zero-based.| +| animated11+ | boolean | No | Whether to support the transition animation.
Default value: **true**
**true**: The transition animation is supported.
**false**: The transition animation is not supported.| ### clear10+ @@ -1140,7 +1177,7 @@ Clears the navigation stack. | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ---------------------- | -| animated11+ | boolean | No | Whether to support transition animation.
Default value: **true**| +| animated11+ | boolean | No | Whether to support the transition animation.
Default value: **true**
**true**: The transition animation is supported.
**false**: The transition animation is not supported.| ### getAllPathName10+ @@ -1172,7 +1209,7 @@ Obtains the parameter information of the navigation destination page specified b | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ---------------------- | -| index | number | Yes | Index of the navigation destination page.| +| index | number | Yes | Index of the navigation destination page. The index is zero-based.| **Return value** @@ -1223,7 +1260,7 @@ Obtains the indexes of all the navigation destination pages that match **name**. | Type | Description | | -------------- | --------------------------------- | -| Array | Indexes of all the matching navigation destination pages.| +| Array | Indexes of all the matching navigation destination pages. If no pages with the specified name exist in the navigation stack, an empty array is returned. The index range is [0, navigation stack size - 1].| ### size10+ @@ -1239,7 +1276,7 @@ Obtains the stack size. | Type | Description | | ------ | ------ | -| number | Stack size.| +| number | Stack size.
Value range: [0, +∞)| ### disableAnimation11+ @@ -1255,7 +1292,7 @@ Disables or enables the transition animation in the **Navigation** component. | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ---------------------- | -| value | boolean | Yes | Whether to disable the transition animation.
Default value: **false**| +| value | boolean | Yes | Whether to disable the transition animation.
Default value: **false**
**true**:The transition animation is disabled.
**false**: The transition animation is not disabled.| ### getParent11+ @@ -1289,6 +1326,45 @@ Sets the interception callback for navigation page redirection. | ---- | ---- | --- | ---| |interception| [NavigationInterception](#navigationinterception12)| Yes| Object to be intercepted during navigation redirection.| +### getPathStack18+ + +getPathStack(): Array\ + +Obtains the array of route page information from this navigation stack. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Return value** + +| Type | Description | +| ------ | ------ | +| Array\<[NavPathInfo](#navpathinfo10)\> | Array of route page information in the current navigation stack.| + +### setPathStack18+ + +setPathStack(pathStack: Array\, animated?: boolean): void + +Updates the array of route page information in this navigation stack to the specified content and performs route transitions. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ---- | --- | ---| +|pathStack| Array\<[NavPathInfo](#navpathinfo10)\>| Yes| Array of route page information in the current navigation stack.| +|animated| boolean | No| Whether to enable the transition animation.
Default value: **true**
**true**: The transition animation is enabled.
**false**: The transition animation is disabled.| + +> **NOTE** +> +> 1. You can add or remove pages in batches based on the existing stack. Among the pages added in batches, only the visible pages will trigger creation; other pages, although added to the stack, will not be created immediately. They will only be created when they become visible. +> 2. For the page stack updated through the batch adding functionality, the lifecycle events of the pages are triggered from the top of the stack to the bottom, which is different from other stack push APIs that trigger from the bottom to the top. +> 3. You can operate existing pages using **navDestinationId** (unique ID) in [NavPathInfo](#navpathinfo10). This ID is system-generated and globally unique (it can be obtained using the [getPathStack](#getpathstack18) API and should not be manually reassigned). If the specified ID does not exist in the current page stack, it indicates a new page. If it exists and the corresponding name is the same, it indicates reuse of an existing page. + ## NavPathInfo10+ Provides the navigation page information. @@ -1306,7 +1382,7 @@ constructor(name: string, param: unknown, onPop?: Callback\, isEntry?: | name | string | Yes | Name of the navigation destination page. | | param | unknown | Yes | Detailed parameters of the navigation destination page.| | onPop11+ | Callback\<[PopInfo](#popinfo11)> | No| Callback returned when [pop](#pop11) is called on the navigation destination page. It is invoked only after the **result** parameter is set in [pop](#pop11).| -| isEntry12+ | boolean | No| Whether the navigation destination page is the entry page.
Default value: **false**
The value of this parameter is reviewed or reset under the following conditions:
- When a global back event is triggered on the current navigation destination page.
- When the application is switched to the background.
**NOTE**
The navigation destination page serving as an entry does not respond to the in-app global back events; instead, it directly triggers the global back event between applications.| +| isEntry12+ | boolean | No| Whether the navigation destination page is the entry page.
Default value: **false**
**true**: The navigation destination page is the entry page.
**false**: The navigation destination page is not the entry page.
The value of this parameter is reviewed or reset under the following conditions:
- When a global back event is triggered on the current navigation destination page.
- When the application is switched to the background.
**NOTE**
The navigation destination page serving as an entry does not respond to the in-app global back events; instead, it directly triggers the global back event between applications.| ### Properties @@ -1317,7 +1393,8 @@ constructor(name: string, param: unknown, onPop?: Callback\, isEntry?: | name | string | Yes | Name of the navigation destination page.
**Atomic service API**: This API can be used in atomic services since API version 11.| | param | unknown | No | Detailed parameters of the navigation destination page.
**Atomic service API**: This API can be used in atomic services since API version 11.| | onPop11+ | Callback\<[PopInfo](#popinfo11)> | No| Callback returned when [pop](#pop11) is called on the navigation destination page. It is invoked only after the **result** parameter is set in [pop](#pop11).
**Atomic service API**: This API can be used in atomic services since API version 12.| -| isEntry12+ | boolean | No| Whether the navigation destination page is the entry page.
Default value: **false**
The value of this parameter is reviewed or reset under the following conditions:
- When a global back event is triggered on the current navigation destination page.
- When the application is switched to the background.
**NOTE**
The navigation destination page serving as an entry does not respond to the in-app global back events; instead, it directly triggers the global back event between applications.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| isEntry12+ | boolean | No| Whether the navigation destination page is the entry page.
Default value: **false**
**true**: The navigation destination page is the entry page.
**false**: The navigation destination page is not the entry page.
The value of this parameter is reviewed or reset under the following conditions:
- When a global back event is triggered on the current navigation destination page.
- When the application is switched to the background.
**NOTE**
The navigation destination page serving as an entry does not respond to the in-app global back events; instead, it directly triggers the global back event between applications.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| navDestinationId18+ | string | No | Unique ID of the navigation destination page. This ID is system-generated and globally unique. It can be obtained using the [getPathStack](#getpathstack18) API and should not be manually reassigned.
**Atomic service API**: This API can be used in atomic services since API version 18. | ## PopInfo11+ @@ -1343,7 +1420,7 @@ Provides the destination information. | Name | Type | Mandatory | Description | |-------|-------|------|-------| | name | string | No| Name of the navigation destination. If the view is a root view (**NavBar**), the return value is **undefined**.| -| index | number | Yes| Index of the navigation destination in the navigation stack. If the view is a root view (**NavBar**), the return value is **-1**.| +| index | number | Yes| Index of the navigation destination in the navigation stack. If the view is a root view (**NavBar**), the return value is **-1**.
Value range: [-1, +∞)| | mode | [NavDestinationMode](ts-basic-components-navdestination.md#navdestinationmode11) | No| Mode of the navigation destination. If the view is a root view (**NavBar**), the return value is **undefined**.| | param12+ | Object | No| Parameters loaded on the navigation destination page.| | navDestinationId12+ | string | No| Unique identifier of the navigation destination page.| @@ -1358,10 +1435,10 @@ Defines the custom transition animation protocol. You need to implement this pro | Name| Type| Mandatory| Description| |------|-----|-----|------| -| timeout | number | No| Animation timeout time.
Unit: ms
Default value: no default value for interactive animations; 1000 ms for non-interactive animations.| +| timeout | number | No| Animation timeout time.
Unit: ms
Value range: [0, +∞)
Default value: no default value for interactive animations; 1000 ms for non-interactive animations.| | transition | (transitionProxy : [NavigationTransitionProxy](#navigationtransitionproxy-11)) => void | Yes| Callback for executing the custom transition animation.
**transitionProxy**: proxy for the custom transition animation.| | onTransitionEnd | (success: boolean) => void | No| Callback invoked when the transition is complete.
**success**: whether the transition is successful.| -| isInteractive12+ | boolean | No| Whether the transition animation is interactive.
Default value: **false**| +| isInteractive12+ | boolean | No| Whether the transition animation is interactive.
Default value: **false**
**true**: The transition animation is interactive.
**false**: The transition animation is not interactive.| ## NavigationTransitionProxy 11+ @@ -1369,7 +1446,7 @@ Implements a custom transition animation proxy. **System capability**: SystemCapability.ArkUI.ArkUI.Full -### Attributes +### Properties **Atomic service API**: This API can be used in atomic services since API version 12. @@ -1379,7 +1456,7 @@ Implements a custom transition animation proxy. |------|-------|-----|-------| | from | [NavContentInfo](#navcontentinfo11) | Yes| Information about the exit page.| | to | [NavContentInfo](#navcontentinfo11) | Yes| Information about the enter page.| -| isInteractive12+ | boolean | No| Whether the transition animation is interactive.| +| isInteractive12+ | boolean | No| Whether the transition animation is interactive.
**true**: The transition animation is interactive.
**false**: The transition animation is not interactive.| ### finishTransition @@ -1446,7 +1523,7 @@ Represents the interception callback before and after the navigation page. | from | [NavDestinationContext](ts-basic-components-navdestination.md#navdestinationcontext11) \|[NavBar](#navbar12) | Yes| Information about the top page in the navigation stack before page redirection. The value **navBar** indicates that the top page is the home page.| | to | [NavDestinationContext](ts-basic-components-navdestination.md#navdestinationcontext11) \|[NavBar](#navbar12) | Yes| Information about the top page in the navigation stack after page redirection. The value **navBar** indicates that the top page is the home page.| | operation | [NavigationOperation](#navigationoperation11) | Yes| Current page redirection type.| -| isAnimated | boolean | Yes| Whether to support transition animation.| +| isAnimated | boolean | Yes| Whether to enable the transition animation.
**true**: The transition animation is enabled.
**false**: The transition animation is disabled.| ### InterceptionModeCallback12+ @@ -1510,11 +1587,11 @@ Defines the name of the navigation home page. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Description | -| -------- | ------------------------------------------------------------ | -| NORMAL | Normal state. In this state, the toolbar item takes on the default style and can switch to another state-specific style by responding to the hover, press, and focus events.| -| DISABLED | Disabled state. In this state, the toolbar item is disabled and does not allow for user interactions.| -| ACTIVE | Active state. In this state, the toolbar item can update its icon to the one specified by **activeIcon** by responding to a click event.| +| Name | Value| Description | +| -------- | --- | ------------------------------------------------------------ | +| NORMAL | 0 | Normal state. In this state, the toolbar item takes on the default style and can switch to another state-specific style by responding to the hover, press, and focus events.| +| DISABLED | 1 | Disabled state. In this state, the toolbar item is disabled and does not allow for user interactions.| +| ACTIVE | 2 | Active state. In this state, the toolbar item can update its icon to the one specified by **activeIcon** by responding to a click event.| ## NavigationTitleMode @@ -1522,11 +1599,11 @@ Defines the name of the navigation home page. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name| Description | -| ---- | ------------------------------------------------------------ | -| Free | When the content is more than one screen in a scrollable component, the main title shrinks as the content scrolls down (the subtitle fades out with its size remaining unchanged) and restores as the content scrolls up to the top.
**NOTE**
The effect where the main title's size changes in response to content scrolling is effective only when **title** is set to **ResourceStr** or **NavigationCommonTitle**. If **title** is set to any other value type, the main title changes in mere location when pulled down.
For this effect to work when the content is less than one screen in a scrollable component, set the **options** parameter of the scrollable component's [edgeEffect](ts-container-list.md#edgeeffect) attribute to **true**. In the non-scrolling state, the height of the title bar is the same as in **Full** mode; in the scrolling state, the minimum height of the title bar is the same as in **Mini** mode.| -| Mini | The title is fixed at mini mode.
Default value:
In versions earlier than API version 12, if there is only a main title, the title bar height is 56 vp; if there is both a main title and a subtitle, the title bar height is 82 vp.
Since API version 12, the title bar height is 56 vp.| -| Full | The title is fixed at full mode.
Default value: If there is only a main title, the title bar height is 112 vp; if there is both a main title and a subtitle, the title bar height is 138 vp.| +| Name| Value| Description | +| ---- | --- | ------------------------------------------------------------ | +| Free | 0 | When the content is more than one screen in a scrollable component, the main title shrinks as the content scrolls down (the subtitle fades out with its size remaining unchanged) and restores as the content scrolls up to the top.
**NOTE**
The effect where the main title's size changes in response to content scrolling is effective only when **title** is set to **ResourceStr** or **NavigationCommonTitle**. If **title** is set to any other value type, the main title changes in mere location when pulled down.
For this effect to work when the content is less than one screen in a scrollable component, set the **options** parameter of the scrollable component's [edgeEffect](ts-container-list.md#edgeeffect) attribute to **true**. In the non-scrolling state, the height of the title bar is the same as in **Full** mode; in the scrolling state, the minimum height of the title bar is the same as in **Mini** mode.| +| Mini | 1 | The title is fixed at mini mode.
Default value:
In versions earlier than API version 12, if there is only a main title, the title bar height is 56 vp; if there is both a main title and a subtitle, the title bar height is 82 vp.
Since API version 12, the title bar height is 56 vp.| +| Full | 2 | The title is fixed at full mode.
Default value: If there is only a main title, the title bar height is 112 vp; if there is both a main title and a subtitle, the title bar height is 138 vp.| ## NavigationCommonTitle9+ @@ -1579,11 +1656,11 @@ Defines the name of the navigation home page. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Description| -|---------|------| -|PUSH | The transition is enter transition.| -|POP | The transition is exit transition.| -| REPLACE | The transition is page replacement.| +| Name | Value| Description| +|---------| --- |------| +|PUSH | 1 | The transition is enter transition.| +|POP | 2 | The transition is exit transition.| +| REPLACE | 3 | The transition is page replacement.| ## BarStyle12+ @@ -1591,11 +1668,11 @@ Enumerates the layout styles of the title bar and toolbar. Note that this API is **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Description| -|---------|------| -|STANDARD | In this mode, the title bar or toolbar is laid out above the content area.
**Atomic service API**: This API can be used in atomic services since API version 12.| -|STACK | In this mode, the title bar or toolbar is overlaid on top of the content area.
**Atomic service API**: This API can be used in atomic services since API version 12.| -|SAFE_AREA_PADDING14+ | In this mode, the title bar or toolbar is configured to respect the [component-level safe area](./ts-universal-attributes-size.md#safeareapadding14).
**Atomic service API**: This API can be used in atomic services since API version 14.| +| Name | Value| Description| +|---------| --- |------| +|STANDARD | 0 | In this mode, the title bar or toolbar is laid out above the content area.
**Atomic service API**: This API can be used in atomic services since API version 12.| +|STACK | 1 | In this mode, the title bar or toolbar is overlaid on top of the content area.
**Atomic service API**: This API can be used in atomic services since API version 12.| +|SAFE_AREA_PADDING14+ | 2 | In this mode, the title bar or toolbar is configured to respect the [component-level safe area](./ts-universal-attributes-size.md#safeareapadding14).
**Atomic service API**: This API can be used in atomic services since API version 14.| ## NavigationTitleOptions11+ @@ -1605,12 +1682,14 @@ Enumerates the layout styles of the title bar and toolbar. Note that this API is | ------ | ------------- | ---- | --------------- | | backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | No | Background color of the title bar. If this parameter is not set, the default color is used.
**Atomic service API**: This API can be used in atomic services since API version 11.| | backgroundBlurStyle | [BlurStyle](ts-universal-attributes-background.md#blurstyle9) | No | Background blur style of the title bar. If this parameter is not set, the background blur effect is disabled.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| backgroundBlurStyleOptions18+ | [BackgroundBlurStyleOptions](ts-universal-attributes-background.md#backgroundblurstyleoptions10) | No | Options for the title bar background blur style.
**NOTE**
This parameter is only effective when **backgroundBlurStyle** is set.
**Atomic service API**: This API can be used in atomic services since API version 18.| +| backgroundEffect18+ | [BackgroundEffectOptions](ts-universal-attributes-background.md#backgroundeffectoptions11) | No | Title bar background properties, including blur radius, brightness, saturation, and color.
**NOTE**
If both **backgroundBlurStyleOptions** and **backgroundEffect** are set, only **backgroundEffect** takes effect.
**Atomic service API**: This API can be used in atomic services since API version 18.| | barStyle12+ | [BarStyle](#barstyle12) | No | Layout style of the title bar.
Default value: **BarStyle.STANDARD**
**Atomic service API**: This API can be used in atomic services since API version 12.| | paddingStart12+ | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | No | Padding at the start of the title bar.
Only supported in one of the following scenarios:
1. Displaying the back icon, that is, [hideBackButton](#hidebackbutton) is **false**
2. Using a non-custom title, that is, the [title value](#title) type is **ResourceStr** or **NavigationCommonTitle**
Default value:
LengthMetrics.resource(**$r('sys.float.margin_left')**)
**Atomic service API**: This API can be used in atomic services since API version 12.| | paddingEnd12+ | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | No | Padding at the end of the title bar.
Only supported in one of the following scenarios:
1. Using a non-custom menu, that is, the [menu value](#menus) is Array<NavigationMenuItem>
2. Using a non-custom menu without a menu in the upper right corner, that is, the [title value](#title) type is **ResourceStr** or **NavigationCommonTitle**
Default value:
LengthMetrics.resource(**$r('sys.float.margin_right')**)
**Atomic service API**: This API can be used in atomic services since API version 12.| | mainTitleModifier13+ | [TextModifier](./ts-universal-attributes-attribute-modifier.md) | No| Main title attribute modifier.
Notes for using this modifier:
1. Attribute settings configured by this modifier will override the system's default attribute settings. For example, if the modifier is used to set font size attributes, such as **fontSize**, **maxFontSize**, and **minFontSize**, the settings will take precedence over the system's default settings for size-related attributes.
2. If no modifier is used or an invalid value is set, the system reverts to its default settings.
3. In [Free](#navigationtitlemode) mode, setting the font size will disable the effect where the main title's size changes in response to content scrolling.
**Atomic service API**: This API can be used in atomic services since API version 13.| | subTitleModifier13+ | [TextModifier](./ts-universal-attributes-attribute-modifier.md) | No| Subtitle attribute modifier.
Notes for using this modifier:
1. Attribute settings configured by this modifier will override the system's default attribute settings. For example, if the modifier is used to set font size attributes, such as **fontSize**, **maxFontSize**, and **minFontSize**, the settings will take precedence over the system's default settings for size-related attributes.
2. If no modifier is used or an invalid value is set, the system reverts to its default settings.
**Atomic service API**: This API can be used in atomic services since API version 13.| -| enableHoverMode13+ | boolean | No| Whether to enable the hover mode.
Observe the following when using this API:
1. Make sure the **Navigation** component is in full screen.
2. When the title bar is in [Free](#navigationtitlemode) display mode or in [STANDARD](#barstyle12) layout style, this API has no effect.
Default value: **false**
**Atomic service API**: This API can be used in atomic services since API version 13.| +| enableHoverMode13+ | boolean | No| Whether to enable the hover mode.
Observe the following when using this API:
1. Make sure the **Navigation** component is in full screen.
2. When the title bar is in [Free](#navigationtitlemode) display mode or in [STANDARD](#barstyle12) layout style, this API has no effect.
Default value: **false**
**true**: Enable the hover mode.
**false**: Disable the hover mode.
**Atomic service API**: This API can be used in atomic services since API version 13.| ## NavigationToolbarOptions11+ @@ -1620,7 +1699,23 @@ Enumerates the layout styles of the title bar and toolbar. Note that this API is | ------ | ------------- | ---- | --------------- | | backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | No | Background color of the toolbar. If this parameter is not set, the default color is used.
**Atomic service API**: This API can be used in atomic services since API version 11.| | backgroundBlurStyle | [BlurStyle](ts-universal-attributes-background.md#blurstyle9) | No | Background blur style of the toolbar. If this parameter is not set, the background blur effect is disabled.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| backgroundBlurStyleOptions18+ | [BackgroundBlurStyleOptions](ts-universal-attributes-background.md#backgroundblurstyleoptions10) | No | Options for the toolbar background blur style.
**NOTE**
This parameter is only effective when **backgroundBlurStyle** is set.
**Atomic service API**: This API can be used in atomic services since API version 18.| +| backgroundEffect18+ | [BackgroundEffectOptions](ts-universal-attributes-background.md#backgroundeffectoptions11) | No | Toolbar background properties, including blur radius, brightness, saturation, and color.
**NOTE**
If both **backgroundBlurStyleOptions** and **backgroundEffect** are set, only **backgroundEffect** takes effect.
**Atomic service API**: This API can be used in atomic services since API version 18.| | barStyle14+ | [BarStyle](#barstyle12) | No | Layout style of the toolbar.
**Atomic service API**: This API can be used in atomic services since API version 14.| +| hideItemValue18+ | boolean | No | Whether to hide the toolbar text.
Default value: **false**
Default value: **false**
**true**: Hide the toolbar text.
**false**: Do not hide the toolbar text.| +| moreButtonOptions18+ | [MoreButtonOptions](#morebuttonoptions18) | No | Options for the toolbar's more button menu.| + +## NavigationMenuOptions18+ + +Defines options for menu items in the upper right corner of the page. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ------ | ------------- | ---- | --------------- | +| moreButtonOptions | [MoreButtonOptions](#morebuttonoptions18) | No | Options for the more button menu. ## LaunchMode12+ @@ -1628,12 +1723,12 @@ Enumerates the layout styles of the title bar and toolbar. Note that this API is **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Description| -| --------- | ------ | -| STANDARD | Default navigation stack operation mode.
In this mode, push operations add the specified **NavDestination** page to the stack; replace operations replace the current top **NavDestination** page.| -| MOVE_TO_TOP_SINGLETON | This mode searches from the bottom to the top of the navigation stack. If a **NavDestination** page with the specified name exists, it moves that page to the top of the stack (for a replace operation, it replaces the last top **NavDestination** page with the specified one); otherwise, it behaves like **STANDARD**.| -| POP_TO_SINGLETON | This mode searches from the bottom to the top of the navigation stack. If a **NavDestination** page with the specified name exists, it removes all **NavDestination** pages above it(for a replace operation, it replaces the last top **NavDestination** page with the specified one); otherwise, it behaves like **STANDARD**.| -| NEW_INSTANCE | This mode creates an instance of **NavDestination**. Compared with **STANDARD**, this mode does not reuse the instance with the same name in the stack.| +| Name | Value| Description| +| --------- | --- | ------ | +| STANDARD | 0 | Default navigation stack operation mode.
In this mode, push operations add the specified **NavDestination** page to the stack; replace operations replace the current top **NavDestination** page.| +| MOVE_TO_TOP_SINGLETON | 1 | This mode searches from the bottom to the top of the navigation stack. If a **NavDestination** page with the specified name exists, it moves that page to the top of the stack (for a replace operation, it replaces the last top **NavDestination** page with the specified one); otherwise, it behaves like **STANDARD**.| +| POP_TO_SINGLETON | 2 | This mode searches from the bottom to the top of the navigation stack. If a **NavDestination** page with the specified name exists, it removes all **NavDestination** pages above it(for a replace operation, it replaces the last top **NavDestination** page with the specified one); otherwise, it behaves like **STANDARD**.| +| NEW_INSTANCE | 3 | This mode creates an instance of **NavDestination**. Compared with **STANDARD**, this mode does not reuse the instance with the same name in the stack.| ## NavigationOptions12+ @@ -1644,7 +1739,21 @@ Enumerates the layout styles of the title bar and toolbar. Note that this API is | Name | Type | Mandatory | Description | | ------ | ------------- | ---- | --------------- | | launchMode | [LaunchMode](#launchmode12) | No | Navigation stack operation mode.
Default value: **LaunchMode.STANDARD**| -| animated | boolean | No | Whether to support transition animation.
Default value: **true**| +| animated | boolean | No | Whether to support transition animation.
Default value: **true**
**true**: The transition animation is supported.
**false**: The transition animation is not supported.| + +## MoreButtonOptions18+ + +Defines the options for the More icon. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ------ | ------------- | ---- | --------------- | +| backgroundBlurStyle | [BlurStyle](ts-universal-attributes-background.md#blurstyle9) | No | Background blur style of the More icon. If this parameter is not set, the background blur effect is disabled.| +| backgroundBlurStyleOptions | [BackgroundBlurStyleOptions](ts-universal-attributes-background.md#backgroundblurstyleoptions10) | No | Background blur style options of the More icon.
**NOTE**
This parameter is only effective when **backgroundBlurStyle** is set.| +| backgroundEffect | [BackgroundEffectOptions](ts-universal-attributes-background.md#backgroundeffectoptions11) | No | Background properties of the More icon, including blur radius, brightness, saturation, and color.
**NOTE**
If both **backgroundBlurStyleOptions** and **backgroundEffect** are set, only **backgroundEffect** takes effect. | ## SystemBarStyle12+ @@ -1779,7 +1888,6 @@ This example demonstrates the use of methods in **NavPathStack** and route inter ```ts // Index.ets - @Entry @Component struct NavigationExample { @@ -2040,6 +2148,7 @@ export struct PageTwo { This sample demonstrates how to set a custom transition animation and an interactive transition animation for each **NavDestination** page. + ```ts // Index.ets import { CustomTransition, AnimateCallback } from './CustomNavigationUtils' @@ -2139,6 +2248,7 @@ struct NavigationExample { } ``` + ```ts // PageOne.ets import { CustomTransition } from './CustomNavigationUtils'; @@ -2249,6 +2359,7 @@ export struct PageOne { } } ``` + ```ts // PageTwo.ets import { CustomTransition } from './CustomNavigationUtils' @@ -2521,7 +2632,6 @@ This example demonstrates how to use the APIs in **NavPathStack** to pass parame ```ts // Index.ets - @Entry @Component struct NavigationExample { @@ -2701,7 +2811,6 @@ export struct PageOne { ``` ```ts // PageTwo.ets - class resultClass { constructor(count: number) { this.count = count; @@ -2813,6 +2922,34 @@ let COLOR1: string = "#80004AAF"; let COLOR2: string = "#802787D9"; let BLUR_STYLE_1: BlurStyle = BlurStyle.BACKGROUND_THIN; let BLUR_STYLE_2: BlurStyle = BlurStyle.BACKGROUND_THICK; +let BLUR_STYLE_OPTION_1: BackgroundBlurStyleOptions = { + colorMode: ThemeColorMode.DARK, + adaptiveColor: AdaptiveColor.DEFAULT, + blurOptions: { grayscale: [20, 20] }, + scale: 1 +}; +let BLUR_STYLE_OPTION_2: BackgroundBlurStyleOptions = { + colorMode: ThemeColorMode.LIGHT, + adaptiveColor: AdaptiveColor.AVERAGE, + blurOptions: { grayscale: [20, 20] }, + scale: 1 +}; +let EFFECT_OPTION_1: BackgroundEffectOptions = { + radius: 20, + saturation: 10, + brightness: 0, + color: '#66FFFFFF', + adaptiveColor: AdaptiveColor.DEFAULT, + blurOptions: { grayscale: [0, 0] }, +}; +let EFFECT_OPTION_2: BackgroundEffectOptions = { + radius: 60, + saturation: 40, + brightness: 1, + color: '#661A1A1A', + adaptiveColor: AdaptiveColor.AVERAGE, + blurOptions: { grayscale: [20, 20] }, +}; @Component struct BackComponent { @@ -2845,6 +2982,7 @@ struct BackComponent { struct ColorAndBlur { @State useColor1: boolean = true; @State useBlur1: boolean = true; + @State useEffect1: boolean = true; build() { NavDestination() { @@ -2870,6 +3008,15 @@ struct ColorAndBlur { } .width('100%') .layoutWeight(1) + + Stack({ alignContent: Alignment.Center }) { + Button("switch effect") + .onClick(() => { + this.useEffect1 = !this.useEffect1; + }) + } + .width('100%') + .layoutWeight(1) } .width('100%') .height('100%') @@ -2879,10 +3026,37 @@ struct ColorAndBlur { .width('100%') .height('100%') // You can set the background color and background blur style of the title bar. - .title("switch titlebar color and blur", { + .title("Destination Title", { backgroundColor: this.useColor1 ? COLOR1 : COLOR2, backgroundBlurStyle: this.useBlur1 ? BLUR_STYLE_1 : BLUR_STYLE_2, - barStyle: BarStyle.STACK + barStyle: BarStyle.STACK, + backgroundEffect: this.useEffect1 ? EFFECT_OPTION_1 : EFFECT_OPTION_2, + }) + // You can set the background color and background blur style for the menu + .menus([ + { value: "A" }, + { value: "B" }, + { value: "C" }, + { value: "D" }, + ], { + moreButtonOptions: { + backgroundEffect: this.useEffect1 ? EFFECT_OPTION_1 : EFFECT_OPTION_2, + } + }) + // You can set the background color and background blur style of the toolbar. + .toolbarConfiguration([ + { value: "A" }, + { value: "B" }, + { value: "C" }, + { value: "D" }, + { value: "E" }, + { value: "F" } + ], { + backgroundEffect: this.useEffect1 ? EFFECT_OPTION_1 : EFFECT_OPTION_2, + // You can set the background color and background blur style for the menu in the toolbar. + moreButtonOptions: { + backgroundEffect: this.useEffect1 ? EFFECT_OPTION_1 : EFFECT_OPTION_2, + } }) } } @@ -2890,17 +3064,20 @@ struct ColorAndBlur { @Entry @Component struct Index { - private stack: NavPathStack = new NavPathStack(); + @Provide('navPathStack') navPathStack: NavPathStack = new NavPathStack(); @State useColor1: boolean = true; @State useBlur1: boolean = true; + @State useBlurOption1: boolean = true; @Builder - PageBuilder(name: string) { - ColorAndBlur() + PageBuilder(name: string, param?: Object) { + if (name === 'NavigationMenu') { + ColorAndBlur(); + } } build() { - Navigation(this.stack) { + Navigation(this.navPathStack) { Stack({ alignContent: Alignment.Center }) { BackComponent() .width('100%') @@ -2924,10 +3101,19 @@ struct Index { .width('100%') .layoutWeight(1) + Stack({ alignContent: Alignment.Center }) { + Button("switch blurOption") + .onClick(() => { + this.useBlurOption1 = !this.useBlurOption1; + }) + } + .width('100%') + .layoutWeight(1) + Stack({ alignContent: Alignment.Center }) { Button("push page") .onClick(() => { - this.stack.pushPath({ name: "page" }) + this.navPathStack.pushPathByName('NavigationMenu', null); }) } .width('100%') @@ -2945,16 +3131,37 @@ struct Index { .title("NavTitle", { backgroundColor: this.useColor1 ? COLOR1 : COLOR2, backgroundBlurStyle: this.useBlur1 ? BLUR_STYLE_1 : BLUR_STYLE_2, - barStyle: BarStyle.STACK + barStyle: BarStyle.STACK, + backgroundBlurStyleOptions: this.useBlurOption1 ? BLUR_STYLE_OPTION_1 : BLUR_STYLE_OPTION_2, + }) + // You can set the background color and background blur style for the menu + .menus([ + { value: "A" }, + { value: "B" }, + { value: "C" }, + { value: "D" }, + ], { + moreButtonOptions: { + backgroundBlurStyle: this.useBlur1 ? BLUR_STYLE_1 : BLUR_STYLE_2, + backgroundBlurStyleOptions: this.useBlurOption1 ? BLUR_STYLE_OPTION_1 : BLUR_STYLE_OPTION_2, + } }) // You can set the background color and background blur style of the toolbar. .toolbarConfiguration([ - { value: "a" }, - { value: "b" }, - { value: "c" } + { value: "A" }, + { value: "B" }, + { value: "C" }, + { value: "D" }, + { value: "E" }, + { value: "F" } ], { backgroundColor: this.useColor1 ? COLOR1 : COLOR2, - backgroundBlurStyle: this.useBlur1 ? BLUR_STYLE_1 : BLUR_STYLE_2 + backgroundBlurStyle: this.useBlur1 ? BLUR_STYLE_1 : BLUR_STYLE_2, + // You can set the background color and background blur style for the menu in the toolbar. + moreButtonOptions: { + backgroundBlurStyle: this.useBlur1 ? BLUR_STYLE_1 : BLUR_STYLE_2, + backgroundBlurStyleOptions: this.useBlurOption1 ? BLUR_STYLE_OPTION_1 : BLUR_STYLE_OPTION_2, + } }) } } @@ -3003,13 +3210,13 @@ struct NavigationExample1 { ``` ```ts // PageOne.ets - @Builder - export function PageOneBuilder(name: string) { - NavDestination() { - Text("this is " + name) - } - .title(name) +@Builder +export function PageOneBuilder(name: string) { + NavDestination() { + Text("this is " + name) } + .title(name) +} ``` ```json // Configure {"routerMap": "$profile:route_map"} in the project configuration file module.json5. @@ -3801,6 +4008,8 @@ export struct NavDestinationExample { ### Example 13: Implementing a Custom Transition Animation This example shows how to implement a custom transition animation for navigation between pages. + + ```ts // Index.ets import { AnimateCallback, CustomTransition } from './CustomTransitionUtils' diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-navrouter.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-navrouter.md index 1e6e8ea713842f0a89301232de26e37f3194c873..e1e40485b05c5f2771ef8d3465392aa360bbac1f 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-navrouter.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-navrouter.md @@ -48,7 +48,7 @@ Provides route information so that clicking the **NavRouter** component redirect ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### mode10+ @@ -64,7 +64,7 @@ Sets the route mode used for redirecting the user from the **NavRouter** compone | Name | Type | Mandatory | Description | | ----------------------------- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | -| mode | [NavRouteMode](#navroutemode) | Yes | Route mode used for redirection.
Default value: **NavRouteMode.PUSH_WITH_RECREATE**| +| mode | [NavRouteMode](#navroutemode10) | Yes | Route mode used for redirection.
Default value: **NavRouteMode.PUSH_WITH_RECREATE**| ## RouteInfo10+ @@ -77,7 +77,7 @@ Sets the route mode used for redirecting the user from the **NavRouter** compone | name | string | Yes | Name of the navigation destination page to be redirected to.| | param | unknown | No | Parameter transferred during redirection.| -## NavRouteMode +## NavRouteMode10+ **Atomic service API**: This API can be used in atomic services since API version 11. diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-nodecontainer.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-nodecontainer.md index 715a4d995a104d96da0e031c43bb399c6efa7c52..9a2814082c9b70bb8eff46b2454010d1362c75fe 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-nodecontainer.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-nodecontainer.md @@ -10,6 +10,8 @@ The **NodeContainer** component is a basic component that accepts an instance of > [Proxy nodes](../js-apis-arkui-frameNode.md#ismodifiable12) of built-in system components obtained through querying cannot be attached to this component. > > This component does not work with the [attribute modifier](./ts-universal-attributes-attribute-modifier.md). +> +> During the construction of the node tree under this component, the UI instance UIContext](../js-apis-arkui-UIContext.md) is used. Switching between different UI instances might cause issues due to instance mismatches. As a result, this component currently does not support reusing nodes across multiple instances. ## Child Components Not supported @@ -18,7 +20,7 @@ Not supported ### NodeContainer -NodeContainer(controller: import('../api/@ohos.arkui.node').NodeController) +NodeContainer(controller: NodeController) **Atomic service API**: This API can be used in atomic services since API version 12. @@ -31,11 +33,11 @@ NodeContainer(controller: import('../api/@ohos.arkui.node').NodeController) | controller | [NodeController](../js-apis-arkui-nodeController.md) | Yes | **NodeController** instance used to control the upper and lower tree nodes in the **NodeContainer**. It represents the lifecycle of the **NodeContainer**.| ## Attributes -The [universal attributes](ts-universal-attributes-size.md) are supported. +The [universal attributes](ts-component-general-attributes.md) are supported. ## Events -The [universal events](ts-universal-events-click.md) are supported. +The [universal events](ts-component-general-events.md) are supported. ## Example diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-patternlock.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-patternlock.md index cbf17bc335ab246376d74d88ef3a9d3345afb4f4..ea3ff180daf04e136162413d6260a119fec03bd6 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-patternlock.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-patternlock.md @@ -295,10 +295,10 @@ Sets the authentication challenge result for the pattern password. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Description | -| ------- | -------------- | -| CORRECT | The pattern password is correct.| -| WRONG | The pattern password is incorrect.| +| Name | Value | Description | +| ------- | ----- | -------------- | +| CORRECT | 1 | The pattern password is correct.| +| WRONG | 2 | The pattern password is incorrect.| ## Example @@ -415,4 +415,3 @@ struct PatternLockExample { ``` ![patternlock](figures/patternlock.gif) - \ No newline at end of file diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-plugincomponent-sys.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-plugincomponent-sys.md index a023f9158db704c38022e365b0257efaf50e1400..5084ee2f157215df1e6f9fffb9f1c8c61fe1209e 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-plugincomponent-sys.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-plugincomponent-sys.md @@ -16,17 +16,26 @@ Not supported ## APIs -PluginComponent(value: { template: PluginComponentTemplate, data: KVObject}) +PluginComponent(options: PluginComponentOptions) Creates a **PluginComponent** to display the UI provided by an external application. **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| value | {
template: [PluginComponentTemplate](#plugincomponenttemplate),
data: [KVObject](../js-apis-plugincomponent.md#kvobject)
} | Yes | **template**: template of the **PluginComponent**, which is bound to the component defined by the provider.
**data**: data passed to the **PluginComponent** provider.| +| Name | Type | Mandatory| Description | +| ------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| options | [PluginComponentOptions](#plugincomponentoptions14) | Yes | Configuration options of the **PluginComponent**.| -## PluginComponentTemplate +## PluginComponentOptions14+ + +Defines options for constructing a **PluginComponent**. + +| Name | Type | Description | +| ---------- | ------ | --------------------------- | +| template | [PluginComponentTemplate](#plugincomponenttemplate9) | Template of the **PluginComponent**, which is bound to the component defined by the provider. | +| data | any | Data passed to the **PluginComponent** provider.| + +## PluginComponentTemplate9+ | Name | Type | Description | | ---------- | ------ | --------------------------- | @@ -38,26 +47,25 @@ The width and height of the component must be explicitly set to non-zero valid v **NOTE** The template can be provided in either of the following modes: -* Use an absolute path. In this case, set **source** to the absolute path of the template and leave **bundleName** blank. This mode is not recommended as it is applicable only to standalone templates that do not need to load resources. - -* Use an application package. In this case, set **bundleName** to the application bundle name and **source** to the relative path of the HAP file template. In the multi-HAP scenario, a HAP file is identified based on its relative path and name. +* 1. Use an absolute path. In this case, set **source** to the absolute path of the template and leave **bundleName** blank. This mode is not recommended as it is applicable only to standalone templates that do not need to load resources. +* 2. Use an application package. In this case, set **bundleName** to the application bundle name and **source** to the relative path of the HAP file template. In the multi-HAP scenario, a HAP file is identified based on its relative path and name. Example: **{source: 'pages/PluginProviderExample.ets&entry', bundleName:'com.example.provider'}** - The template is provided only when **source** can be set to an ability name in the FA model. + The template is provided only when **source** can be set to an ability name or bundle name in the FA model. Example: **{source:'plugin', bundleName:'com.example.provider'}** ## Events -Only the [gesture event](ts-gesture-settings.md) can be distributed to and processed inside the provider page. +[Gesture events](ts-gesture-settings.md) can be distributed to and processed inside the provider page. -In addition to the [universal events](ts-universal-events-click.md), the following events are supported. +In addition to the [universal events](ts-component-general-events.md), the following events are supported. ### onComplete -onComplete(callback: () => void) +onComplete(callback: VoidCallback) Triggered when the component loading is complete. @@ -67,7 +75,7 @@ Triggered when the component loading is complete. ### onError -onError(callback: (info: { errcode: number, msg: string }) => void) +onError(callback: {info: PluginErrorCallback}) Triggered when an error occurs during component loading. @@ -77,262 +85,318 @@ Triggered when an error occurs during component loading. **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------------------------------------------ | ---- | ----------------------------------------------- | -| info | { errcode: number, msg: string } | Yes | **errcode**: error code.
**msg**: error information.| +| Name | Type | Mandatory| Description | +| --------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | +| callback | [PluginErrorCallback](#pluginerrorcallback14) | Yes | Callback invoked when an error occurs.| + +## PluginErrorCallback14+ + +Defines the callback invoked when an error occurs. + +| Name | Type | Description | +| -------- | ------------------ | --------------------------- | +| info | [PluginErrorData](#pluginerrordata14) | Data provided when the error occurs.| + +## PluginErrorData14+ + +Defines the data provided when an error occurs during component loading. + +| Name | Type | Description | +| ---------- | ------ | -------------------------- | +| errcode | number | Error code. | +| msg | string | Error message. | -## Example +## Example: Loading a PluginComponent +This example demonstrates the basic usage of the **PluginComponent**. Specifically, you need to create an application acting as the **PluginComponent** [user](#plugincomponent-user) with the bundle name of **"com.example.user"** and an application acting as the **PluginComponent** [provider](#plugincomponent-provider) with the bundle name of **"com.example.provider"**. After building the application projects, perform the following steps for testing: +1. Install the HAP packages of both applications on the device. +2. Open the user application page. Both user and provider content should be displayed correctly. +3. Register listeners by clicking the **Register Push Listener** button on the user side and the **Register Request Listener** button on the provider side. +4. Send a request from the user to the provider by clicking the **Request** button. The log should print information related to **onRequestListener**. +5. Send a push event from the provider to the user by clicking the **Push** button. The log should print information related to **onPushListener**. ### PluginComponent User -```ts -//PluginUserExample.ets -import plugin from "./plugin_component" -interface Info{ - errcode:number, - msg:string -} -@Entry -@Component -struct PluginUserExample { - - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Text('Hello World') - .fontSize(50) - .fontWeight(FontWeight.Bold) - Button('Register Request Listener') - .fontSize(30) - .width(400) - .height(100) - .margin({top:20}) - .onClick(()=>{ - plugin.onListener() - console.log("Button('Register Request Listener')") - }) - Button('Request') - .fontSize(50) - .width(400) - .height(100) - .margin({ top: 20 }) - .onClick(() => { - plugin.Request() - console.log("Button('Request')") - }) - PluginComponent({ - template: { source: 'pages/PluginProviderExample.ets&entry', bundleName: 'com.example.plugin' }, - data: { 'countDownStartValue': 'new countDownStartValue' } - }).size({ width: 500, height: 350 }) - .onComplete(() => { - console.log("onComplete") - }) - .onError((info:Info) => { - console.log("onComplete" + info.errcode + ":" + info.msg) - }) +The user application has a bundle name of **"com.example.user"** and contains one page. +- The EntryAbility (UIAbility) loads the entry page file **ets/pages/Index.ets**, which contains the following code: + ```ts + import plugin from "./plugin_component" + + interface Info { + errcode: number, + msg: string + } + + @Entry + @Component + struct PluginUserExample { + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text('Hello World') + .fontSize(50) + .fontWeight(FontWeight.Bold) + Button('Register Push Listener') + .fontSize(30) + .width(400) + .height(100) + .margin({ top: 20 }) + .onClick(() => { + plugin.onListener() + console.log("Button('Register Push Listener')") + }) + Button('Request') + .fontSize(50) + .width(400) + .height(100) + .margin({ top: 20 }) + .onClick(() => { + plugin.Request() + console.log("Button('Request')") + }) + PluginComponent({ + // Provider + template: { source: 'pages/Index.ets&entry', bundleName: 'com.example.provider' }, + data: { 'countDownStartValue': 'new countDownStartValue' } + }).size({ width: 500, height: 350 }) + .onComplete(() => { + console.log("onComplete") + }) + .onError((info: Info) => { + console.log("onComplete" + info.errcode + ":" + info.msg) + }) + } + .width('100%') + .height('100%') } - .width('100%') - .height('100%') } -} -``` + ``` +- Copy the [PluginComponent manager code](#plugincomponent-manager) corresponding to your project model type to the **ets/pages/plugin_component.js** file. +- Add the **requestPermissions** tag in the **module.json5** file to allow the user application to query information from other applications: + ```json + "requestPermissions": [ + { + "name": "ohos.permission.GET_BUNDLE_INFO_PRIVILEGED", + "usedScene": { + "abilities": [ + "EntryAbility" + ], + "when": "inuse" + } + } + ] + ``` ### PluginComponent Provider -```ts -//PluginProviderExample.ets -import plugin from "./plugin_component" - -@Entry -@Component -struct PluginProviderExample { - @State message: string = 'no click!' - - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Button('Register Push Listener') - .fontSize(30) - .width(400) - .height(100) - .margin({top:20}) - .onClick(()=>{ - plugin.onListener() - console.log("Button('Register Push Listener')") - }) - Button('Push') - .fontSize(30) - .width(400) - .height(100) - .margin({top:20}) - .onClick(()=>{ - plugin.Push() - this.message = "Button('Push')" - console.log("Button('Push')") - }) - Text(this.message) - .height(150) - .fontSize(30) - .padding(5) - .margin(5) - }.width('100%').height('100%').backgroundColor(0xDCDCDC).padding({ top: 5 }) +The provider application has a bundle name of **"com.example.provider"** and contains one page. +- The EntryAbility (UIAbility) loads the entry page file **ets/pages/Index.ets**, which contains the following code: + ```ts + import plugin from "./plugin_component" + + @Entry + @Component + struct PluginProviderExample { + @State message: string = 'no click!' + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Button('Register Request Listener') + .fontSize(30) + .width(400) + .height(100) + .margin({ top: 20 }) + .onClick(() => { + plugin.onListener() + console.log("Button('Register Request Listener')") + }) + Button('Push') + .fontSize(30) + .width(400) + .height(100) + .margin({ top: 20 }) + .onClick(() => { + plugin.Push() + this.message = "Button('Push')" + console.log("Button('Push')") + }) + Text(this.message) + .height(150) + .fontSize(30) + .padding(5) + .margin(5) + }.width('100%').height('100%').backgroundColor(0xDCDCDC).padding({ top: 5 }) + } } -} -``` + ``` +- Copy the [PluginComponent manager code](#plugincomponent-manager) corresponding to your project model type to the **ets/pages/plugin_component.js** file. -### PluginComponent Tools +### PluginComponent Manager + +The **PluginComponent** manager is used for communication between the user and provider. You need to select the corresponding code based on the model type and copy it into your project. #### FA Model ```js -// The sample code applies only to JS source files. -//plugin_component.js +// This example code is only applicable to the FA model. import pluginComponentManager from '@ohos.pluginComponent' +var providerBundleName = 'com.example.provider' +var providerAbilityName = 'com.example.provider.EntryAbility' +var providerName = 'Index' + +// Push event listener function onPushListener(source, template, data, extraData) { - console.log("onPushListener template.source=" + template.source) - console.log("onPushListener template.ability=" + template.ability) - console.log("onPushListener data=" + JSON.stringify(data)) - console.log("onPushListener extraData=" + JSON.stringify(extraData)) + console.log("onPushListener template.source=" + template.source) + console.log("onPushListener template.ability=" + template.ability) + console.log("onPushListener data=" + JSON.stringify(data)) + console.log("onPushListener extraData=" + JSON.stringify(extraData)) } +// Request event listener function onRequestListener(source, name, data) { console.log("onRequestListener name=" + name); console.log("onRequestListener data=" + JSON.stringify(data)); - return {template:"plugintemplate", data:data}; + return {template:"pluginTemplate", data:data}; } export default { - //register listener - onListener() { - pluginComponentManager.on("push", onPushListener) - pluginComponentManager.on("request", onRequestListener) - }, - Push() { - // The component provider proactively sends data. - pluginComponentManager.push( - { - want: { - bundleName: "com.example.plugin", - abilityName: "com.example.myapplication.PluginProviderExample", - }, - name: "PluginProviderExample", - data: { - "key_1": "plugin component test", - "key_2": 34234 - }, - extraData: { - "extra_str": "this is push event" - }, - jsonPath: "", - }, - (err, data) => { - console.log("push_callback: push ok!"); - } - ) - }, - Request() { - // The component user proactively sends data. - pluginComponentManager.request({ - want: { - bundleName: "com.example.plugin", - abilityName: "com.example.myapplication.PluginProviderExample", - }, - name: "PluginProviderExample", - data: { - "key_1": "plugin component test", - "key_2": 34234 + // Register event listeners. + onListener() { + pluginComponentManager.on("push", onPushListener) + pluginComponentManager.on("request", onRequestListener) + }, + Push() { + // The provider proactively sends an event, want: provider information. + pluginComponentManager.push( + { + want: { + bundleName: providerBundleName, + abilityName: providerAbilityName, + }, + name: providerName, + data: { + "key_1": "plugin component push data", + "key_2": 12345 + }, + extraData: { + "extra_str": "this is push event" + }, + jsonPath: "", + }, + (err, data) => { + console.log("push_callback: push ok!"); + } + ) + }, + Request() { + // The user proactively sends an event, want: provider information. + pluginComponentManager.request({ + want: { + bundleName: providerBundleName, + abilityName: providerAbilityName, + }, + name: providerName, + data: { + "key_1": "plugin component request data", + "key_2": 67890 + }, + jsonPath: "", }, - jsonPath: "", - }, - (err, data) => { - console.log("request_callback: componentTemplate.ability=" + data.componentTemplate.ability) - console.log("request_callback: componentTemplate.source=" + data.componentTemplate.source) - console.log("request_callback: data=" + JSON.stringify(data.data)) - console.log("request_callback: extraData=" + JSON.stringify(data.extraData)) - } - ) - } + (err, data) => { + console.log("request_callback: componentTemplate.ability=" + data.componentTemplate.ability) + console.log("request_callback: componentTemplate.source=" + data.componentTemplate.source) + console.log("request_callback: data=" + JSON.stringify(data.data)) + console.log("request_callback: extraData=" + JSON.stringify(data.extraData)) + } + ) + } } ``` #### Stage Model ```js -// The sample code applies only to JS source files. -//plugin_component.js +// This example code is only applicable to the stage model. import pluginComponentManager from '@ohos.pluginComponent' +var userBundleName = 'com.example.user' +var userAbilityName = 'com.example.user.EntryAbility' +var providerBundleName = 'com.example.provider' +var providerAbilityName = 'com.example.provider.EntryAbility' +var providerName = 'Index' + +// Push event listener function onPushListener(source, template, data, extraData) { - console.log("onPushListener template.source=" + template.source) - console.log("onPushListener template.ability=" + template.ability) - console.log("onPushListener data=" + JSON.stringify(data)) - console.log("onPushListener extraData=" + JSON.stringify(extraData)) + console.log("onPushListener template.source=" + template.source) + console.log("onPushListener template.ability=" + template.ability) + console.log("onPushListener data=" + JSON.stringify(data)) + console.log("onPushListener extraData=" + JSON.stringify(extraData)) } -function onRequestListener(source, name, data) -{ - console.log("onRequestListener name=" + name); - console.log("onRequestListener data=" + JSON.stringify(data)); - return {template:"plugintemplate", data:data}; +// Request event listener +function onRequestListener(source, name, data) { + console.log("onRequestListener name=" + name) + console.log("onRequestListener data=" + JSON.stringify(data)) + return { template: "pluginTemplate", data: data } } export default { - //register listener - onListener() { - pluginComponentManager.on("push", onPushListener) - pluginComponentManager.on("request", onRequestListener) - }, - Push() { - // The component provider proactively sends data. - pluginComponentManager.push( - { - owner: { - bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", - }, - target: { - bundleName: "com.example.plugin", - abilityName: "com.example.myapplication.PluginProviderExample", - }, - name: "PluginProviderExample", - data: { - "key_1": "plugin component test", - "key_2": 34234 - }, - extraData: { - "extra_str": "this is push event" - }, - jsonPath: "", - }, - (err, data) => { - console.log("push_callback: push ok!"); - } - ) - }, - Request() { - // The component user proactively sends data. - pluginComponentManager.request({ - owner: { - bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", - }, - target: { - bundleName: "com.example.plugin", - abilityName: "com.example.myapplication.PluginProviderExample", - }, - name: "PluginProviderExample", - data: { - "key_1": "plugin component test", - "key_2": 34234 + // Register event listeners. + onListener() { + pluginComponentManager.on("push", onPushListener) + pluginComponentManager.on("request", onRequestListener) + }, + Push() { + // The provider proactively sends an event, owner: user, target: provider. + pluginComponentManager.push( + { + owner: { + bundleName: userBundleName, + abilityName: userAbilityName, + }, + target: { + bundleName: providerBundleName, + abilityName: providerAbilityName, + }, + name: providerName, + data: { + "key_1": "plugin component push data", + "key_2": 12345 + }, + extraData: { + "extra_str": "this is push event" + }, + jsonPath: "", + }, + (err, data) => { + console.log("push_callback: push ok!"); + } + ) + }, + Request() { + // The user proactively sends an event, owner: user, target: provider. + pluginComponentManager.request({ + owner: { + bundleName: userBundleName, + abilityName: userAbilityName, + }, + target: { + bundleName: providerBundleName, + abilityName: providerAbilityName, + }, + name: providerName, + data: { + "key_1": "plugin component request data", + "key_2": 67890 + }, + jsonPath: "", }, - jsonPath: "", - }, - (err, data) => { - console.log("request_callback: componentTemplate.ability=" + data.componentTemplate.ability) - console.log("request_callback: componentTemplate.source=" + data.componentTemplate.source) - console.log("request_callback: data=" + JSON.stringify(data.data)) - console.log("request_callback: extraData=" + JSON.stringify(data.extraData)) - } - ) - } + (err, data) => { + console.log("request_callback: componentTemplate.ability=" + data.componentTemplate.ability) + console.log("request_callback: componentTemplate.source=" + data.componentTemplate.source) + console.log("request_callback: data=" + JSON.stringify(data.data)) + console.log("request_callback: extraData=" + JSON.stringify(data.extraData)) + } + ) + } } ``` diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-progress.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-progress.md index 1ca9ec2c304f9ecfd7bccdedb2ead88a379ff1fd..36335ca336271d73ccb3b11e4f585c37906b8ec1 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-progress.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-progress.md @@ -90,7 +90,7 @@ ProgressType.Capsule | [CapsuleStyleOptions10+](#capsulestyleoptions1 ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. > **NOTE** > @@ -178,7 +178,7 @@ Sets whether to enable privacy mode. | Name| Type | Mandatory| Description | | ------ | --------------------------------------------------------- | ---- | ----------------------------------------------------- | -| isPrivacySensitiveMode | [Optional\] | Yes | Whether to enable privacy mode, in which the progress is cleared and the text is obscured.
**NOTE**
If this parameter is set to **null**, privacy mode is disabled.
[Enabling privacy mode requires widget framework support.](./ts-universal-attributes-obscured.md) | +| isPrivacySensitiveMode | [Optional\] | Yes | Whether to enable privacy mode, in which the progress is cleared and the text is obscured. The value **true** means to enable privacy mode, and **false** means the opposite.
**NOTE**
If this parameter is set to **null**, privacy mode is disabled.
[Enabling privacy mode requires widget framework support.](./ts-universal-attributes-obscured.md) | ## ProgressConfiguration12+ @@ -188,8 +188,8 @@ Sets whether to enable privacy mode. | Name| Type | Mandatory|Description | | ------ | ------ | ------- |------------| -| value | number | Yes| Current progress.| -| total | number | Yes| Indicates the total progress. | +| value | number | Yes| Current progress. Values less than 0 are adjusted to **0**. Values greater than the value of **total** are capped at the value of **total**.
Default value: **0**
Value range: [0, total]| +| total | number | Yes| Indicates the total progress.
Value range: [0, +∞] | ## CommonProgressStyleOptions10+ @@ -199,7 +199,7 @@ Sets whether to enable privacy mode. | Name | Type | Mandatory| Description | | ------------ | ---------------------------- | ---- | ------------------------------------------------------------------------------------------ | -| enableSmoothEffect | boolean | No| Whether to enable the smooth effect. When this effect is enabled, the progress changes smoothly from the current value to the target value. When this effect is disabled, the progress changes abruptly to the target value.
Default value: **true**| +| enableSmoothEffect | boolean | No| Whether to enable the smooth effect. When this effect is enabled, the progress changes smoothly from the current value to the target value. When this effect is disabled, the progress changes abruptly to the target value.
Default value: **true**
**true**: Enable the smooth effect.
**false**: Disable the smooth effect.| ## ScanEffectOptions10+ @@ -209,7 +209,7 @@ Sets whether to enable privacy mode. | Name | Type| Mandatory| Description| | ------------- | ------- | ---- | -------- | -| enableScanEffect | boolean | No| Whether to enable the scan effect.
Default value: **false**| +| enableScanEffect | boolean | No| Whether to enable the scan effect.
Default value: **false**
**true**: Enable the scan effect.
**false**: Disable the scan effect.| ## ProgressStyleOptions8+ @@ -224,7 +224,7 @@ Inherits [CommonProgressStyleOptions](#commonprogressstyleoptions10). | Name | Type | Mandatory| Description | | ------------ | ---------------------------- | ---- | ------------------------------------------------------------------------------------------ | | strokeWidth | [Length](ts-types.md#length) | No | Stroke width of the progress indicator. It cannot be set in percentage.
Default value: **4.0vp** | -| scaleCount | number | No | Number of divisions on the ring-style process indicator.
Default value: **120** | +| scaleCount | number | No | Number of divisions on the ring-style process indicator.
Default value: **120**
Value range: [2, min(width, height)/scaleWidth/2/π]. If the value is outside this range, the progress indicator is displayed in the indeterminate ring style. | | scaleWidth | [Length](ts-types.md#length) | No | Scale width of the ring-style progress bar. It cannot be set in percentage. If it is greater than the value of **strokeWidth**, the default scale width is used.
Default value: **2.0vp**| ## CapsuleStyleOptions10+ @@ -242,12 +242,12 @@ Inherits [ScanEffectOptions](#scaneffectoptions10) and [CommonProgressStyleOptio | content | string | No| Text content, which can be customized .| | font | [Font](ts-types.md#font) | No| Text style.
Default value:
- Font size (cannot be set in percentage): **12fp**
- Other attributes: following the settings of the **Text** component.| | fontColor | [ResourceColor](ts-types.md#resourcecolor) | No| Font color.
Default value: **'\#ff182431'**| -| showDefaultPercentage | boolean | No| Whether to show the percentage of the current progress. This attribute does not take effect when the **content** attribute is set.
Default value: **false**| -| borderRadius16+ | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | No| Corner radius. The value cannot be set in percentage.
Value range: [0, height/2]
Default value: height/2
If an invalid value is set, the default value is used.| +| showDefaultPercentage | boolean | No| Whether to show the percentage of the current progress. This attribute does not take effect when the **content** attribute is set.
Default value: **false**.
**true**: Show the percentage of the current progress.
**false**: Do not show the percentage of the current progress.| +| borderRadius18+ | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | No| Corner radius. The value cannot be set in percentage.
Value range: [0, height/2]
Default value: height/2
If an invalid value is set, the default value is used.| ## RingStyleOptions10+ -Inherits [ScanEffectOptions](#scaneffectoptions10) and [CommonProgressStyleOptions](#commonprogressstyleoptions10). +Inherits from [ScanEffectOptions](#scaneffectoptions10) and [CommonProgressStyleOptions](#commonprogressstyleoptions10). **Atomic service API**: This API can be used in atomic services since API version 11. @@ -256,7 +256,7 @@ Inherits [ScanEffectOptions](#scaneffectoptions10) and [CommonProgressStyleOptio | Name | Type | Mandatory| Description | | ------------- | ---------------------------- | ---- | ------------------------------------------------------------------------------------------ | | strokeWidth | [Length](ts-types.md#length) | No | Stroke width of the progress indicator. It cannot be set in percentage. A value greater than or equal to the radius evaluates to half of the radius.
Default value: **4.0vp**| -| shadow | boolean | No | Whether to enable the shadow effect.
Default value: **false** | +| shadow | boolean | No | Whether to enable the shadow effect.
Default value: **false**.
**true**: Enable the shadow effect.
**false**: Disable the shadow effect. | | status | [ProgressStatus10+](#progressstatus10) | No| Status of the progress indicator. When this parameter is set to **LOADING**, the check update animation is played, and the **value** settings do not take effect. When the value changes from **LOADING** to **PROGRESSING**, the check update animation stops when it has reached the end state.
Default value: **ProgressStatus.PROGRESSING**| ## LinearStyleOptions10+ @@ -283,7 +283,7 @@ Inherits [CommonProgressStyleOptions](#commonprogressstyleoptions10). | Name | Type | Mandatory| Description | | ------------ | ---------------------------- | ---- | ------------------------------------------------------------------------------------------ | | strokeWidth | [Length](ts-types.md#length) | No | Stroke width of the progress indicator. It cannot be set in percentage.
Default value: **4.0vp** | -| scaleCount | number | No | Number of divisions on the ring-style process indicator.
Default value: **120** | +| scaleCount | number | No | Number of divisions on the ring-style process indicator.
Default value: **120**
Value range: [2, min(width, height)/scaleWidth/2/π]. If the value is outside this range, the progress indicator is displayed in the indeterminate ring style. | | scaleWidth | [Length](ts-types.md#length) | No | Scale width of the ring-style progress bar. It cannot be set in percentage. If it is greater than the value of **strokeWidth**, the default scale width is used.
Default value: **2.0vp**| ## EclipseStyleOptions10+ @@ -307,7 +307,7 @@ Inherits [CommonProgressStyleOptions](#commonprogressstyleoptions10). ## Events -The [universal events](ts-universal-events-click.md) are supported. +The [universal events](ts-component-general-events.md) are supported. ## Example diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-qrcode.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-qrcode.md index f593b6cdc98a72d0e34b0064261e8815700bff40..1882e49e4436f016d86c51484eaa3bc627e98968 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-qrcode.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-qrcode.md @@ -32,7 +32,7 @@ QRCode(value: string) ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### color @@ -84,7 +84,7 @@ Sets the opacity of the QR code content. The minimum value is 0, and the maximum | Name| Type | Mandatory| Description | | ------ | ---------------------------------------------------- | ---- | ---------------------------------------- | -| value | number \| [Resource](ts-types.md#resource) | Yes | Opacity of the QR code content.
Default value: **1**| +| value | number \| [Resource](ts-types.md#resource) | Yes | Opacity of the QR code content.
Default value: **1**
Value range: [0, 1]. If the value is out of the range, the default value is used.| ## Events @@ -102,6 +102,7 @@ This example demonstrates the basic usage of the **QRCode** component. It shows @Component struct QRCodeExample { private value: string = 'hello world' + build() { Column({ space: 5 }) { Text('normal').fontSize(9).width('90%').fontColor(0xCCCCCC).fontSize(30) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-radio.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-radio.md index a16b3e78d2c9a8d395b0d0619a0f501e8e7143e3..bf8e50a13b54282a95f6cbd3ae7c5af30a3ac469 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-radio.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-radio.md @@ -51,15 +51,15 @@ Creates a radio button. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Description | -| --------------- | -------------------------------- | -| TICK | Default tick icon. | -| DOT | Default dot icon. | -| CUSTOM | Custom component.| +| Name | Value | Description | +| --------------- | -------------------------------- | -------------------------------- | +| TICK | 0 | Default tick icon. | +| DOT | 1 | Default dot icon. | +| CUSTOM | 2 | Custom component.| ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### checked @@ -68,6 +68,7 @@ checked(value: boolean) Sets whether the radio button is selected. Since API version 10, this attribute supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md). +Since API version 18, this attribute supports two-way binding through [!!](../../../quick-start/arkts-new-binding.md#two-way-binding-between-built-in-component-parameters). **Widget capability**: This API can be used in ArkTS widgets since API version 9. @@ -77,9 +78,30 @@ Since API version 10, this attribute supports two-way binding through [$$](../.. **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------- | ---- | ------------------------------------ | -| value | boolean | Yes | Whether the radio button is selected.
Default value: **false**| +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------------------------------------ | +| value | boolean | Yes | Whether the radio button is selected.
Default value: **false**
**true**: The radio button is selected. **false**: The radio button is not selected.| + +### checked18+ + +checked(isChecked: Optional\) + +Sets whether the radio button is selected. Compared to [checked](#checked), this API supports the **undefined** type for the **isChecked** parameter. + +This attribute supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md). +Since API version 18, this attribute supports two-way binding through [!!](../../../quick-start/arkts-new-binding.md#two-way-binding-between-built-in-component-parameters). + +**Widget capability**: This API can be used in ArkTS widgets since API version 18. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| isChecked | [Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Whether the radio button is selected.
If **isChecked** is set to **undefined**, the default value **false** is used.
**true**: The radio button is selected. **false**: The radio button is not selected.| ### radioStyle10+ @@ -99,7 +121,7 @@ Since API version 10, this API is supported in ArkTS widgets. | ------ | ----------------------------------- | ---- | ---------------------------------- | | value | [RadioStyle](#radiostyle10) | No | Style of the radio button in selected or deselected state.| -## contentModifier12+ +### contentModifier12+ contentModifier(modifier: ContentModifier\) @@ -115,9 +137,25 @@ Creates a content modifier. | ------ | --------------------------------------------- | ---- | ------------------------------------------------ | | modifier | [ContentModifier\](#radioconfiguration12) | Yes | Content modifier to apply to the current component.
**modifier**: content modifier. You need a custom class to implement the **ContentModifier** API.| +### contentModifier18+ + +contentModifier(modifier: Optional>) + +Creates a content modifier. Compared to [contentModifier](#contentmodifier12)12+, this API supports the **undefined** type for the **modifier** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| modifier | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[ContentModifier\](#radioconfiguration12)> | Yes | Content modifier to apply to the current component.
**modifier**: content modifier. You need a custom class to implement the **ContentModifier** API.
If **modifier** is set to **undefined**, no content modifier is used.| + ## Events -In addition to the [universal events](ts-universal-events-click.md), the following events are supported. +In addition to the [universal events](ts-component-general-events.md), the following events are supported. ### onChange @@ -133,6 +171,40 @@ Triggered when the selected state of the radio button changes. **Parameters** +| Name | Type | Mandatory| Description | +| --------- | ------- | ---- | -------------------------------- | +| isChecked | boolean | Yes | Selected state of the radio button.| + +### onChange18+ + +onChange(callback: Optional\) + +Triggered when the selected state of the radio button changes. Compared to [onChange](#onchange), this API supports the **undefined** type for the **callback** parameter. + +**Widget capability**: This API can be used in ArkTS widgets since API version 18. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| callback | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[OnRadioChangeCallback](#onradiochangecallback18)> | Yes | Called invoked when the selected state of the radio button changes.
If **callback** is set to **undefined**, the callback function is not used.| + +## OnRadioChangeCallback18+ + +type OnRadioChangeCallback = (isChecked: boolean) => void + +Triggered when the selected state of the radio button changes. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + | Name | Type | Mandatory| Description | | --------- | ------- | ---- | ------------------------------------------------------------ | | isChecked | boolean | Yes | Selected state of the radio button.
The value **true** means that the radio button changes from unselected to selected, and **false** means that the radio button changes from selected to unselected.| @@ -145,9 +217,9 @@ Triggered when the selected state of the radio button changes. | Name | Type | Mandatory| Description | | ---------------------- | ------------------------------------------ | ---- | ------------------------------------------------------------ | -| checkedBackgroundColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the background when the radio button is selected.
Default value: **#007DFF** | -| uncheckedBorderColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the border when the radio button is deselected.
Default value: **#182431** | -| indicatorColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the indicator when the radio button is selected. Since API version 12, this parameter takes effect only when **indicatorType** is set to **RadioIndicatorType.TICK** or **RadioIndicatorType.DOT**.
Default value: **#FFFFFF**| +| checkedBackgroundColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the background when the radio button is selected.
Default value: **$r('sys.color.ohos_id_color_text_primary_activated')** | +| uncheckedBorderColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the border when the radio button is deselected.
Default value: **$r('sys.color.ohos_id_color_switch_outline_off')** | +| indicatorColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the indicator when the radio button is selected. Since API version 12, this parameter takes effect only when **indicatorType** is set to **RadioIndicatorType.TICK** or **RadioIndicatorType.DOT**.
Default value: **$r('sys.color.ohos_id_color_foreground_contrary')**| ## RadioConfiguration12+ @@ -160,8 +232,8 @@ You need a custom class to implement the **ContentModifier** API. | Name | Type | Read Only| Optional | Description | | ------ | ------ |-------------------------------- |-------------------------------- |-------------------------------- | | value | string | No| No|Current value of the radio button.| -| checked | boolean| No| No| Whether the radio button is selected.
Default value: **false**| -| triggerChange |Callback\|No|No|Changes the selected state of the radio button.| +| checked | boolean| No| No| Whether the radio button is selected.
Default value: **false**
**true**: The radio button is selected. **false**: The radio button is not selected.| +| triggerChange |Callback\|No|No|Changes the selected state of the radio button.
The value **true** means that the radio button changes from unselected to selected, and **false** means that the radio button changes from selected to unselected.| ## Example diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-rating.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-rating.md index b9f1fc3d6d619e565e1a229ccf2f7357f7312b5f..b9efc361c2185cbf8fa39f13eeaa326b98846357 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-rating.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-rating.md @@ -24,9 +24,9 @@ Rating(options?: RatingOptions) **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ----------------------------------------- | ---- | -------------- | -| rating | [RatingOptions](#ratingoptions13) | No | Rating bar options.| +| Name | Type | Mandatory| Description | +| ------- | ----------------------------------------- | ---- | -------------- | +| options | [RatingOptions](#ratingoptions18) | No | Rating bar options.| ## Attributes @@ -48,6 +48,24 @@ Sets the total number of ratings (stars). If the value set is less than or equal | ------ | ------ | ---- | ---------------------------- | | value | number | Yes | Total number of ratings.
Default value: **5**| +### stars18+ + +stars(starCount: Optional\) + +Sets the total number of ratings (stars). If the value set is less than or equal to 0, the default value is used. Compared to [stars](#stars), this API supports the **undefined** type for the **starCount** parameter. + +**Widget capability**: This API can be used in ArkTS widgets since API version 18. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------------------------------------ | ---- | ---------------------------------------------------------- | +| starCount | [Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Total number of ratings.
If **starCount** is set to **undefined**, the default value **5** is used.| + ### stepSize stepSize(value: number) @@ -66,6 +84,24 @@ Sets the step for rating. A value less than 0.1 evaluates to the default value. | ------ | ------ | ---- | ----------------------------------------------------------- | | value | number | Yes | Step for rating.
Default value: **0.5**
Value range: [0.1, stars]| +### stepSize18+ + +stepSize(size: Optional\) + +Sets the step for rating. A value less than 0.1 evaluates to the default value. Compared to [stepSize](#stepsize), this API supports the **undefined** type for the **size** parameter. + +**Widget capability**: This API can be used in ArkTS widgets since API version 18. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| size | [Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Step for rating.
If **size** is set to **undefined**, the default value **0.5** is used.
Value range: [0.1, stars]| + ### starStyle starStyle(options: StarStyleOptions) @@ -86,7 +122,31 @@ By default, the image is loaded in asynchronous mode. Synchronous loading is not | Name | Type | Mandatory| Description | | ------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | -| options | [StarStyleOptions](#starstyleoptions13) | Yes | Star style.
**NOTE**
If the path specified for **backgroundUri**, **foregroundUri**, or **secondaryUri** is incorrect, no image is displayed.
If **backgroundUri** or **foregroundUri** is set to **undefined** or an empty string, the **Rating** component loads the default star image source.
If **secondaryUri** is set to **undefined** or an empty string or is not set, **backgroundUri** is prioritized, which is equivalent to where only **foregroundUri** and **backgroundUri** are set.| +| options | [StarStyleOptions](#starstyleoptions18) | Yes | Star style.
**NOTE**
If the path specified for **backgroundUri**, **foregroundUri**, or **secondaryUri** is incorrect, no image is displayed.
If **backgroundUri** or **foregroundUri** is set to **undefined** or an empty string, the **Rating** component loads the default star image source.
If **secondaryUri** is set to **undefined** or an empty string or is not set, **backgroundUri** is prioritized, which is equivalent to where only **foregroundUri** and **backgroundUri** are set.| + +### starStyle18+ + +starStyle(options: Optional\) + +Sets the star style. For details about the supported image types, see [Image](ts-basic-components-image.md). + +Local and online images are supported, but not **PixelMap** and **Resource** objects. + +By default, the image is loaded in asynchronous mode. Synchronous loading is not supported. + +Compared to [starStyle](#starstyle), this API supports the **undefined** type for the **options** parameter. + +**Widget capability**: This API can be used in ArkTS widgets since API version 18. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| options | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[StarStyleOptions](#starstyleoptions18)> | Yes | Star style.
**NOTE**
If the path specified for **backgroundUri**, **foregroundUri**, or **secondaryUri** is incorrect, no image is displayed.
If **backgroundUri** or **foregroundUri** is set to **undefined** or an empty string, the **Rating** component loads the default star image source.
If **secondaryUri** is set to **undefined** or an empty string or is not set, **backgroundUri** is prioritized, which is equivalent to where only **foregroundUri** and **backgroundUri** are set.| > **NOTE** > @@ -110,6 +170,21 @@ Creates a content modifier. | ------ | --------------------------------------------- | ---- | ------------------------------------------------ | | modifier | [ContentModifier\](#ratingconfiguration12) | Yes | Content modifier to apply to the current component.
**modifier**: content modifier. You need a custom class to implement the **ContentModifier** API.| +### contentModifier18+ + +contentModifier(modifier: Optional>) + +Creates a content modifier. Compared to [contentModifier](#contentmodifier12), this API supports the **undefined** type for the **modifier** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| modifier | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[ContentModifier\](#ratingconfiguration12)> | Yes | Content modifier to apply to the current component.
**modifier**: content modifier. You need a custom class to implement the **ContentModifier** API.
If **modifier** is set to **undefined**, no content modifier is used.| ## Events @@ -131,6 +206,40 @@ Triggered when the rating value changes. | ------ | ------ | ---- | -------------- | | value | number | Yes | Rating value.| +### onChange18+ + +onChange(callback:Optional\) + +Triggered when the rating value changes. Compared to [onChange](#onchange), this API supports the **undefined** type for the **callback** parameter. + +**Widget capability**: This API can be used in ArkTS widgets since API version 18. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| callback | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[OnRatingChangeCallback](#onratingchangecallback18)> | Yes | Triggered when the rating value changes.
If **callback** is set to **undefined**, the callback function is not used.| + +## OnRatingChangeCallback18+ + +type OnRatingChangeCallback = (rating: number) => void + +Triggered when the rating value changes. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------- | +| rating | number | Yes | Rating value.| + ## Sequential Keyboard Navigation Specifications | Key | Description | |------------|-----------------------------| @@ -150,42 +259,44 @@ You need a custom class to implement the **ContentModifier** API. | Name | Type | Read Only | Optional | Description | | ------ | ------ | ------ |-------------------------------- |-------------------------------- | -| rating | number | No| No|Value to rate.
Default value: **0**| -| indicator | boolean | No| No| Whether the component is used only as an indicator.
Default value: **false**| +| rating | number | No| No| Value to rate.
Default value: **0**
Value range: [0, stars]
Values less than 0 are treated as **0**, and values greater than the value of [stars](#stars) are treated as the value of **stars**.
This parameter supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md).
This parameter supports two-way binding through [!!](../../../quick-start/arkts-new-binding.md).| +| indicator | boolean | No| No| Whether the rating bar is used as an indicator.
**true**: The rating bar is used as an indicator.
**false**: The rating bar is not used as an indicator.
Default value: **false**| | stars | number | No| No|Total number of ratings.
Default value: **5**| | stepSize | number | No| No|Step of an operation.
Default value: **0.5**| | triggerChange | Callback\ | No| No|Callback triggered when the rating value changes.| -## RatingOptions13+ +## RatingOptions18+ -**Widget capability**: This API can be used in ArkTS widgets since API version 13. +**Widget capability**: This API can be used in ArkTS widgets since API version 18. -**Atomic service API**: This API can be used in atomic services since API version 13. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory| Description | -| --------- | ------- | ---- | ------------------------------------------------------------ | -| rating | number | Yes | Value to rate.
Default value: **0**
Value range: [0, stars]
Values less than 0 are treated as **0**, and values greater than the value of **stars** are treated as the value of **stars**.
This parameter supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md).| -| indicator | boolean | No | Whether the component is used only as an indicator.
Default value: **false**
**NOTE**
When **indicator** is set to **true**, the default component height is 12.0 vp, and the component width is calculated as follows: Height x Value of **stars**.
When **indicator** is set to **false**, the default component height is 28.0 vp, and the component width is calculated as follows: Height x Value of **stars**.| +| Name | Type | Mandatory| Description | +| ---------------------- | ------- | ---- | ------------------------------------------------------------ | +| rating7+ | number | Yes | Value to rate.
Default value: **0**
Value range: [0, stars]
Values less than 0 are treated as **0**, and values greater than the value of [stars](#stars) are treated as the value of **stars**.
This parameter supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md).
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| indicator7+ | boolean | No | Whether the component is used only as an indicator.
Default value: **false**
**NOTE**
When **indicator** is set to **true**, the default component height is 12.0 vp, and the component width is calculated as follows: Height x Value of **stars**.
When **indicator** is set to **false**, the default component height is 28.0 vp, and the component width is calculated as follows: Height x Value of **stars**.
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11.| -## StarStyleOptions13+ +## StarStyleOptions18+ -**Widget capability**: This API can be used in ArkTS widgets since API version 13. +**Widget capability**: This API can be used in ArkTS widgets since API version 18. -**Atomic service API**: This API can be used in atomic services since API version 13. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory| Description | -| ------------- | ------ | ---- | ------------------------------------------------------------ | -| backgroundUri | string | Yes | Image path for the unselected star. You can use the default system image or a custom image. | -| foregroundUri | string | Yes | Image path for the selected star. You can use the default system image or a custom image. | -| secondaryUri | string | No | Image path for the partially selected star. You can use the default system image or a custom image.| +| Name | Type | Mandatory| Description | +| -------------------------- | ------ | ---- | ------------------------------------------------------------ | +| backgroundUri7+ | string | Yes | Image path for the unselected star. You can use the default system image or a custom image.
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| foregroundUri7+ | string | Yes | Image path for the selected star. You can use the default system image or a custom image.
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| secondaryUri7+ | string | No | Image path for the partially selected star. You can use the default system image or a custom image.
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11.| ## Example -### Example 1 +### Example 1: Setting the Default Rating Style + +This example demonstrates how to set the default star rating style. ```ts // xxx.ets @@ -241,7 +352,9 @@ struct RatingExample { ![rating](figures/rating.gif) -### Example 2 +### Example 2: Customizing the Rating Style + +This example demonstrates how to configure **starStyle** to use custom image links for stars. ```ts // xxx.ets @@ -275,7 +388,7 @@ struct RatingExample { ![rating1](figures/rating1.gif) -### Example 3 +### Example 3: Implementing a Custom Rating Bar This example implements a custom rating bar, with each circle representing 0.5 point. If **ratingIndicator** is set to **true**, the rating bar is used only as an indicator, and the rating cannot be changed. if it is set to **false**, the rating can be changed. **ratingStars** sets the rating value. **ratingStepsize** sets the step for rating. diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-remotewindow-sys.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-remotewindow-sys.md index c347998f82800f6bc3e4072b54ffb876389d90ba..9303833b79dd0d62f0d4a97a7ae87b29d5b515c1 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-remotewindow-sys.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-remotewindow-sys.md @@ -49,11 +49,11 @@ Implements a rounded rectangle. ## Attributes -The [universal attributes](ts-universal-attributes-size.md) are supported. +The [universal attributes](ts-component-general-attributes.md) are supported. ## Events -The [universal events](ts-universal-events-click.md) are supported. +The [universal events](ts-component-general-events.md) are supported. ## Example The **RemoteWindow** component needs to receive the **WindowAnimationTarget** object from the **WindowAnimationController** object set by [windowAnimationManager](../js-apis-windowAnimationManager-sys.md). You can create a **RemoteWindowExample.ets** file as an example to encapsulate the **RemoteWindow** component and the passed **WindowAnimationTarget** object. diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-richeditor-sys.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-richeditor-sys.md new file mode 100644 index 0000000000000000000000000000000000000000..203146c06c1daa03a8730312835a706af7a9c9ed --- /dev/null +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-richeditor-sys.md @@ -0,0 +1,37 @@ +# RichEditor (System API) + +**RichEditor** is a component that supports interactive text editing and mixture of text and imagery. + +> **NOTE** +> +> This component is supported since API version 10. Updates will be marked with a superscript to indicate their earliest API version. +> +> This topic describes only system APIs provided by the module. For details about its public APIs, see [RichEditor](ts-basic-components-richeditor.md). +> +## RichEditorBuilderSpanOptions11+ + +Defines the options for adding a builder span. + +**Atomic service API**: This API can be used in atomic services since API version 12. + +**System API**: This is a system API. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ------------------------------------- | +| dragBackgroundColor18+ | [ColorMetrics](../js-apis-arkui-graphics.md#colormetrics12) | No | Background color of the builder when it is dragged independently. If no valid value is specified, the default color is used. | +| isDragShadowNeeded18+ | boolean | No | Whether to apply a shadow when the builder is dragged independently. If no valid value is specified, a shadow is applied.| + +## RichEditorGesture11+ + +Defines the callback for user interactions. + +**System API**: This is a system API. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ----------- | ---------- | ---- | ------------- | +| onDoubleClick14+ | Callback\<[GestureEvent](ts-gesture-settings.md#gestureevent)\> | No | Callback for double-click events.
**Atomic service API**: This API can be used in atomic services since API version 14. | + diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-richeditor.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-richeditor.md index bc0e021aefdcddd5d1b46a11bf3534747b4a2e75..81021679ffc3b0ee9081514a854aea3db4bfa185 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-richeditor.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-richeditor.md @@ -37,7 +37,7 @@ RichEditor(options: RichEditorStyledStringOptions)12+ ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. > **NOTE** > @@ -315,13 +315,13 @@ Sets the scrollbar display mode when the **RichEditor** text box is editable. | ------ | ----------------------------------------- | ---- | ------------------------------------------------------ | | state | [BarState](ts-appendix-enums.md#barstate) | Yes | Scrollbar display mode when the text box is editable.
Default value: **BarState.Auto**| -### maxLength16+ +### maxLength18+ -maxLength(value: Optional\) +maxLength(maxLength: Optional\) Sets the maximum number of characters for text input. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -329,15 +329,15 @@ Sets the maximum number of characters for text input. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| value | [Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Maximum number of characters for text input.
Default value: **Infinity**, which means unlimited input. The **undefined** type is supported.
**NOTE**
If this attribute is not set or is set to an invalid value, the default value is used. If a decimal number is specified, the integer part is used.| +| maxLength | [Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Maximum number of characters for text input.
Default value: **Infinity**, which means unlimited input. The **undefined** type is supported.
**NOTE**
If this attribute is not set or is set to an invalid value, the default value is used. If a decimal number is specified, the integer part is used.| -### maxLines16+ +### maxLines18+ -maxLines(value: Optional\) +maxLines(maxLines: Optional\) -Sets the maximum number of lines that the text can display. +Sets the maximum number of lines that the rich text can display. When **maxLines** is set, content that exceeds the specified number of lines can be scrolled to display. If both the component height and **maxLines** are set, the component height takes precedence. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -345,7 +345,7 @@ Sets the maximum number of lines that the text can display. | Name| Type | Mandatory| Description | | ------ | ----------------------------------------- | ---- | ------------------------------------------------------------ | -| value | [Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Maximum number of lines that the text can display.
Default value: **Infinity**, which means unlimited lines. The **undefined** type is supported.
Value range: (0, +∞)| +| maxLines | [Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Maximum number of lines that the rich text can display. When it is set, content that exceeds the specified number of lines can be scrolled to display. If both the component height and **maxLines** are set, the component height takes precedence.
Default value: **Infinity**, which means unlimited lines. The **undefined** type is supported.
Value range: (0, +∞)| ### enableHapticFeedback13+ @@ -361,13 +361,13 @@ Sets whether haptic feedback is enabled. | ------ | --------------------------------------------- |-----|-------------------------------------------------------------------------------------| | isEnabled | boolean | Yes | Whether haptic feedback is enabled.
**true** (default): Haptic feedback is enabled.
**false**: Haptic feedback is disabled.
Whether this parameter takes effect after being set to true depends on hardware support.| -### keyboardAppearance16+ +### keyboardAppearance15+ -keyboardAppearance(appearance: KeyboardAppearance) +keyboardAppearance(appearance: Optional\) Sets the keyboard appearance. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 15. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -375,11 +375,25 @@ Sets the keyboard appearance. | Name| Type| Mandatory| Description| | ------ | ----------------------------------------- | ---- | ------------------------------------------------------ | -| appearance | [KeyboardAppearance](ts-text-common.md#keyboardappearance16) | Yes | Keyboard appearance.
Default value: **KeyboardAppearance.NONE_IMMERSIVE**| +| appearance | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[KeyboardAppearance](ts-text-common.md#keyboardappearance15)\> | Yes | Keyboard appearance.
Default value: **KeyboardAppearance.NONE_IMMERSIVE**| + +### stopBackPress18+ + +stopBackPress(isStopped: Optional<boolean>) + +Sets whether to prevent the back button press from being propagated to other components or applications. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name| Type | Mandatory | Description | +| ------ | --------------------------------------------- |-----|-------------------------------------------------------------------------------------| +| isStopped | Optional<boolean> | No | Whether to prevent the back button press from being propagated to other components or applications. Default value: **true**| ## Events -In addition to the [universal events](ts-universal-events-click.md), [OnDidChangeCallback](ts-text-common.md#ondidchangecallback12), [StyledStringChangedListener](ts-text-common.md#styledstringchangedlistener12), [StyledStringChangeValue](ts-text-common.md#styledstringchangevalue12), and the following events are supported. +In addition to the [universal events](ts-component-general-events.md), [OnDidChangeCallback](ts-text-common.md#ondidchangecallback12), [StyledStringChangedListener](ts-text-common.md#styledstringchangedlistener12), [StyledStringChangeValue](ts-text-common.md#styledstringchangevalue12), and the following events are supported. ### onReady @@ -699,6 +713,7 @@ Provides the text span information. | symbolSpanStyle11+ | [RichEditorSymbolSpanStyle](#richeditorsymbolspanstyle11) | No | Style of the **SymbolSpan** component.
**Atomic service API**: This API can be used in atomic services since API version 12.| | paragraphStyle12+ | [RichEditorParagraphStyle](#richeditorparagraphstyle11) | No | Paragraph style.
**Atomic service API**: This API can be used in atomic services since API version 12.| | previewText12+ | string | No | Content of the preview text.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| urlStyle18+ | [RichEditorUrlStyle](#richeditorurlstyle18) | No | URL information.
Default value: **undefined**
**Atomic service API**: This API can be used in atomic services since API version 18.| ## RichEditorSpanPosition @@ -726,22 +741,20 @@ Provides the span type information. | IMAGE | 1 | Image span.
**Atomic service API**: This API can be used in atomic services since API version 11. | | MIXED | 2 | Mixed span, which contains both text and imagery.
**Atomic service API**: This API can be used in atomic services since API version 11. | | BUILDER12+ | 3 | Builder span.
**Atomic service API**: This API can be used in atomic services since API version 12. | -| DEFAULT16+ | 4 | Default type, used when no specific span type is specified.
**Atomic service API**: This API can be used in atomic services since API version 16.| +| DEFAULT15+ | 4 | Default type, used when no specific span type is specified.
**Atomic service API**: This API can be used in atomic services since API version 15.| ## RichEditorResponseType11+ Provides the response type of the menu. -**Atomic service API**: This API can be used in atomic services since API version 12. - **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Description | -| ---------- | ------------- | -| LONG_PRESS | The menu is displayed when the component is long-pressed. | -| RIGHT_CLICK | The menu is displayed when the component is right-clicked.| -| SELECT | The menu is displayed when the component is selected.| -| DEFAULT16+ | Default type, used when no specific response type is specified.| +| Name | Value | Description | +| ----- | ---- | ------------ | +| RIGHT_CLICK | 0 | The menu is displayed when the component is right-clicked.
**Atomic service API**: This API can be used in atomic services since API version 12. | +| LONG_PRESS | 1 | The menu is displayed when the component is long-pressed.
**Atomic service API**: This API can be used in atomic services since API version 12. | +| SELECT | 2 | The menu is displayed when the component is selected.
**Atomic service API**: This API can be used in atomic services since API version 12. | +| DEFAULT15+ | 3 | Default type, used when no specific response type is specified.
**Atomic service API**: This API can be used in atomic services since API version 15. | ## RichEditorTextStyleResult @@ -761,15 +774,15 @@ Provides the text span style information returned by the backend. | lineHeight12+ | number | No | Line height. The default unit is fp.
**Atomic service API**: This API can be used in atomic services since API version 12.| | letterSpacing12+| number | No | Letter spacing. The default unit is fp.
**Atomic service API**: This API can be used in atomic services since API version 12.| | fontFeature12+ | string | No| Font feature.
**Atomic service API**: This API can be used in atomic services since API version 12.| -| halfLeading16+ | boolean | No| Whether half leading is enabled.
Whether half leading is enabled. Half leading is the leading split in half and applied equally to the top and bottom edges. The value **true** means that half leading is enabled, and **false** means the opposite.
Default value: **false**
**Atomic service API**: This API can be used in atomic services since API version 16.| -| textBackgroundStyle16+ | [TextBackgroundStyle](ts-basic-components-span.md#textbackgroundstyle11) | No | Text background style.| +| halfLeading18+ | boolean | No| Whether half leading is enabled.
Half leading is the leading split in half and applied equally to the top and bottom edges. The value **true** means that half leading is enabled, and **false** means the opposite.
Default value: **false**
**Atomic service API**: This API can be used in atomic services since API version 18.| +| textBackgroundStyle18+ | [TextBackgroundStyle](ts-basic-components-span.md#textbackgroundstyle11) | No | Text background style.| > **NOTE** > > While **fontWeight** in **RichEditorTextStyle** sets the font weight, **fontWeight** in **RichEditorTextStyleResult** returns the set font weight after conversion to digits. > > The table below lists the conversion mappings. -> +> > | fontWeight in RichEditorTextStyle | fontWeight in RichEditorTextStyleResult | > | ---- | ----------------------------------- | > | 100 | 0 | @@ -787,7 +800,7 @@ Provides the text span style information returned by the backend. > | Medium | 13 | > | Bold | 9 | > | Bolder | 11 | -> +> > The conversion mappings between the **fontWeight** parameters in **RichEditorSymbolSpanStyle** and **RichEditorSymbolSpanStyleResult** are the same as those between the **fontWeight** parameters in **RichEditorTextStyle** and **RichEditorTextStyleResult**. ## RichEditorSymbolSpanStyleResult11+ @@ -803,8 +816,8 @@ Provides the symbol span style information returned by the backend. | fontColor | Array\<[ResourceColor](ts-types.md#resourcecolor)\> | Yes| Color of the symbol span.
Default value: depending on the rendering strategy| | fontSize | number \| string \| [Resource](ts-types.md#resource) | Yes| Size of the symbol span. The default unit is fp.
The default value follows the theme.| | fontWeight | number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string | Yes| Weight of the symbol span.
For the number type, the value ranges from 100 to 900, at an interval of 100. A larger value indicates a heavier font weight. The default value is **400**.
For the string type, only strings of the number type are supported, for example, **"400"**, **"bold"**, **"bolder"**, **"lighter"**, **"regular"**, and **"medium"**, which correspond to the enumerated values in **FontWeight**.
Default value: **FontWeight.Normal**| -| renderingStrategy | [SymbolRenderingStrategy](ts-basic-components-symbolGlyph.md#symbolrenderingstrategy11) | Yes| Rendering strategy of the symbol span.
Default value: **SymbolRenderingStrategy.SINGLE**| -| effectStrategy | [SymbolEffectStrategy](ts-basic-components-symbolGlyph.md#symboleffectstrategy11) | Yes| Effect strategy of the symbol span.
Default value: **SymbolEffectStrategy.NONE**| +| renderingStrategy | [SymbolRenderingStrategy](ts-basic-components-symbolGlyph.md#symbolrenderingstrategy11) | Yes| Rendering strategy of the symbol span.
Default value: **SymbolRenderingStrategy.SINGLE**
+| effectStrategy | [SymbolEffectStrategy](ts-basic-components-symbolGlyph.md#symboleffectstrategy11) | Yes| Effect strategy of the symbol span.
Default value: **SymbolEffectStrategy.NONE**
## RichEditorImageSpanResult @@ -831,7 +844,7 @@ Provides the image span style information returned by the backend. | Name | Type | Mandatory | Description | | ------------- | ---------------------------------------- | ---- | --------- | | size | [number, number] | Yes | Width and height of the image, in px. Default value: varies by the value of **objectFit**. If the value of **objectFit** is **Cover**, the image height is the component height minus the top and bottom paddings, and the image width is the component width minus the left and right paddings.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| verticalAlign | [ImageSpanAlignment](ts-basic-components-imagespan.md#imagespanalignment) | Yes | Vertical alignment mode of the image.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| verticalAlign | [ImageSpanAlignment](ts-appendix-enums.md#imagespanalignment10) | Yes | Vertical alignment mode of the image.
**Atomic service API**: This API can be used in atomic services since API version 11.| | objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | Yes | Scale mode of the image.
**Atomic service API**: This API can be used in atomic services since API version 11.| | layoutStyle12+ | [RichEditorLayoutStyle](#richeditorlayoutstyle11) | No | Image layout style.
**Atomic service API**: This API can be used in atomic services since API version 12.| @@ -1057,13 +1070,13 @@ Obtains the preview text. | ---------------------------------------- | ------- | | [PreviewText](ts-text-common.md#previewtext12) | Preview text.| -### getCaretRect16+ +### getCaretRect18+ getCaretRect(): RectResult | undefined Obtains the relative position of the cursor in the **RichEditor** component. If the cursor is not blinking, the API returns **undefined**. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -1151,7 +1164,7 @@ Adds a custom builder span. > - If the cursor in the component is blinking, the cursor position is updated to be after the inserted image span. The following universal attributes are supported: [size](ts-universal-attributes-size.md#size), [padding](ts-universal-attributes-size.md#padding), [margin](ts-universal-attributes-size.md#margin), [aspectRatio](ts-universal-attributes-layout-constraints.md#aspectratio), [borderStyle](ts-universal-attributes-border.md#borderstyle), [borderWidth](ts-universal-attributes-border.md#borderwidth), [borderColor](ts-universal-attributes-border.md#bordercolor), [borderRadius](ts-universal-attributes-border.md#borderradius), [backgroundColor](ts-universal-attributes-background.md#backgroundcolor), [backgroundBlurStyle](ts-universal-attributes-background.md#backgroundblurstyle9), [opacity](ts-universal-attributes-opacity.md), [blur](ts-universal-attributes-image-effect.md#blur), [backdropBlur](ts-universal-attributes-background.md#backdropblur), [shadow](ts-universal-attributes-image-effect.md#shadow), [grayscale](ts-universal-attributes-image-effect.md#grayscale), [brightness](ts-universal-attributes-image-effect.md#brightness), [saturate](ts-universal-attributes-image-effect.md#saturate), -[contrast](ts-universal-attributes-image-effect.md#contrast), [invert](ts-universal-attributes-image-effect.md#invert), [sepia](ts-universal-attributes-image-effect.md#sepia), [hueRotate](ts-universal-attributes-image-effect.md#huerotate), [colorBlend](ts-universal-attributes-image-effect.md#colorblend7), [linearGradientBlur](ts-universal-attributes-image-effect.md#lineargradientblur12), [clip](ts-universal-attributes-sharp-clipping.md#clip), [mask](ts-universal-attributes-sharp-clipping.md#mask), [foregroundBlurStyle](ts-universal-attributes-foreground-blur-style.md#foregroundblurstyle), [accessibilityGroup](ts-universal-attributes-accessibility.md#accessibilitygroup), [accessibilityText](ts-universal-attributes-accessibility.md#accessibilitytext), [accessibilityDescription](ts-universal-attributes-accessibility.md#accessibilitydescription), [accessibilityLevel](ts-universal-attributes-accessibility.md#accessibilitylevel), [sphericalEffect](ts-universal-attributes-image-effect.md#sphericaleffect12), [lightUpEffect](ts-universal-attributes-image-effect.md#lightupeffect12), [pixelStretchEffect](ts-universal-attributes-image-effect.md#pixelstretcheffect12) +[contrast](ts-universal-attributes-image-effect.md#contrast), [invert](ts-universal-attributes-image-effect.md#invert), [sepia](ts-universal-attributes-image-effect.md#sepia), [hueRotate](ts-universal-attributes-image-effect.md#huerotate), [colorBlend](ts-universal-attributes-image-effect.md#colorblend7), [linearGradientBlur](ts-universal-attributes-image-effect.md#lineargradientblur12), [clip](ts-universal-attributes-sharp-clipping.md#clip12), [mask](ts-universal-attributes-sharp-clipping.md#mask12), [foregroundBlurStyle](ts-universal-attributes-foreground-blur-style.md#foregroundblurstyle), [accessibilityGroup](ts-universal-attributes-accessibility.md#accessibilitygroup), [accessibilityText](ts-universal-attributes-accessibility.md#accessibilitytext), [accessibilityDescription](ts-universal-attributes-accessibility.md#accessibilitydescription), [accessibilityLevel](ts-universal-attributes-accessibility.md#accessibilitylevel), [sphericalEffect](ts-universal-attributes-image-effect.md#sphericaleffect12), [lightUpEffect](ts-universal-attributes-image-effect.md#lightupeffect12), [pixelStretchEffect](ts-universal-attributes-image-effect.md#pixelstretcheffect12) **Atomic service API**: This API can be used in atomic services since API version 12. @@ -1432,7 +1445,7 @@ Obtains the styled string displayed in the **RichEditor** component. onContentChanged(listener: StyledStringChangedListener): void -Register a callback for text content changes, which will be invoked when the text content is changed by the backend program. +Triggered when text content changes. This callback is invoked when the text content is changed by the backend program. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -1461,8 +1474,6 @@ Provides information about the selected content. Defines the range of the **RichEditor**. -Inherits [RichEditorRange](#richeditorrange). - **Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -1489,13 +1500,12 @@ Defines the text span style options. Inherits [RichEditorSpanStyleOptions](#richeditorspanstyleoptions). -**Atomic service API**: This API can be used in atomic services since API version 11. - **System capability**: SystemCapability.ArkUI.ArkUI.Full | Name | Type | Mandatory| Description | | --------- | ------------------------------------------- | ---- | ---------- | -| textStyle | [RichEditorTextStyle](#richeditortextstyle) | Yes | Text style.| +| textStyle | [RichEditorTextStyle](#richeditortextstyle) | Yes | Text style.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| urlStyle18+ | [RichEditorUrlStyle](#richeditorurlstyle18) | No | URL information.
Default value: **undefined**
**Atomic service API**: This API can be used in atomic services since API version 18.| ## RichEditorUpdateImageSpanStyleOptions @@ -1548,16 +1558,15 @@ Inherits [RichEditorSpanStyleOptions](#richeditorspanstyleoptions). Describes the paragraph style. -**Atomic service API**: This API can be used in atomic services since API version 12. - **System capability**: SystemCapability.ArkUI.ArkUI.Full | Name | Type | Mandatory | Description | | ------------- | ---------------------------------------- | ---- | ------------------ | | textAlign | [TextAlign](ts-appendix-enums.md#textalign) | No | Horizontal alignment mode of the text.
Default value: **TextAlign.START**
**Atomic service API**: This API can be used in atomic services since API version 12.| | leadingMargin | [Dimension](ts-types.md#dimension10) \| [LeadingMarginPlaceholder](#leadingmarginplaceholder11) | No | Indent of the paragraph. It has no effect if the paragraph starts with an image or builder span. If of the **Dimension** type, this parameter cannot be set in percentage. Default value: **{"size":["0.00px","0.00px"]}**
**Atomic service API**: This API can be used in atomic services since API version 12.| -| wordBreak12+ | [WordBreak](ts-appendix-enums.md#wordbreak11) | No | Word break rule.
Default value: **WordBreak.BREAK_WORD** | -| lineBreakStrategy12+ | [LineBreakStrategy](ts-appendix-enums.md#linebreakstrategy12) | No| Line break rule.
Default value: **LineBreakStrategy.GREEDY**
This parameter takes effect when **wordBreak** is not set to **breakAll**. Hyphens are not supported.| +| wordBreak12+ | [WordBreak](ts-appendix-enums.md#wordbreak11) | No | Word break rule.
Default value: **WordBreak.BREAK_WORD**
**Atomic service API**: This API can be used in atomic services since API version 12.| +| lineBreakStrategy12+ | [LineBreakStrategy](ts-appendix-enums.md#linebreakstrategy12) | No| Line break rule.
Default value: **LineBreakStrategy.GREEDY**
This parameter takes effect when **wordBreak** is not set to **breakAll**. Hyphens are not supported.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| paragraphSpacing18+ | number | No | Spacing between paragraphs.
Unit: fp
Default value: **0**
**Atomic service API**: This API can be used in atomic services since API version 18.| ## LeadingMarginPlaceholder11+ @@ -1595,6 +1604,7 @@ Describes the options for adding a text span. | style | [RichEditorTextStyle](#richeditortextstyle) | No | Style of the text span to be added. If this parameter is left empty, the default text style will be used.
**Atomic service API**: This API can be used in atomic services since API version 11.| | paragraphStyle11+ | [RichEditorParagraphStyle](#richeditorparagraphstyle11) | No | Paragraph style.
**Atomic service API**: This API can be used in atomic services since API version 12.| | gesture11+ | [RichEditorGesture](#richeditorgesture11) | No | Behavior-triggered callback. If this parameter is left empty, only the default system behavior is supported.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| urlStyle18+ | [RichEditorUrlStyle](#richeditorurlstyle18) | No | URL information.
Default value: **undefined**
**Atomic service API**: This API can be used in atomic services since API version 18.| ## RichEditorTextStyle @@ -1614,8 +1624,8 @@ Provides the text style information. | lineHeight12+ | number \| string \| [Resource](ts-types.md#resource) | No |Text line height. If the value is less than or equal to 0, the line height is not limited and the font size is adaptive. If the value is of the number type, the unit fp is used. The value cannot be a percentage.
**Atomic service API**: This API can be used in atomic services since API version 12.| | letterSpacing12+ | number \| string | No | Letter spacing. If the value is negative, the text is compressed. A negative value too small may result in the text being compressed to 0 and no content being displayed. If the value is of the number type, the unit fp is used. The value cannot be a percentage.
**Atomic service API**: This API can be used in atomic services since API version 12.| | fontFeature12+ | string | No| Font feature, for example, monospaced digits. If this parameter is not set, monospaced digits are used as the default value. If invalid characters are set, the default value is retrained.
Format: normal \| \
Syntax for \: \ \[ \ \| on \| off ]
There can be multiple **\** values, which are separated by commas (,).
For example, the input format for monospaced clock fonts is "ss01" on.
For details about the supported font features, see [Font Feature List](ts-basic-components-text.md#fontfeature12).
Font features are advanced typographic features, such as ligatures and monospace, for OpenType fonts. They are typically used in custom fonts and require the support of the font itself.
For more information about the font features, see [Low-level font feature settings control: the font-feature-settings property](https://www.w3.org/TR/css-fonts-3/#font-feature-settings-prop) and [The Complete CSS Demo for OpenType Features](https://sparanoid.com/lab/opentype-features/).
**Atomic service API**: This API can be used in atomic services since API version 12.| -| halfLeading16+ | boolean | No | Whether half leading is enabled.
Whether half leading is enabled. Half leading is the leading split in half and applied equally to the top and bottom edges. The value **true** means that half leading is enabled, and **false** means the opposite.
Default value: **false**
**Atomic service API**: This API can be used in atomic services since API version 16.| -| textBackgroundStyle16+ | [TextBackgroundStyle](ts-basic-components-span.md#textbackgroundstyle11) | No | Text background style.
Default value:
{
color: Color.Transparent,
radius: 0
} | +| halfLeading18+ | boolean | No | Whether half leading is enabled.
Half leading is the leading split in half and applied equally to the top and bottom edges. The value **true** means that half leading is enabled, and **false** means the opposite.
Default value: **false**
**Atomic service API**: This API can be used in atomic services since API version 18.| +| textBackgroundStyle18+ | [TextBackgroundStyle](ts-basic-components-span.md#textbackgroundstyle11) | No | Text background style.
Default value:
{
color: Color.Transparent,
radius: 0
} | ## PlaceholderStyle12+ @@ -1652,7 +1662,7 @@ Provides the image span style information. | Name | Type | Mandatory | Description | | ------------------------- | ---------------------------------------- | ---- | ---------------------------------------- | | size | [[Dimension](ts-types.md#dimension10), [Dimension](ts-types.md#dimension10)] | No | Width and height of the image. Default value: varies by the value of **objectFit**. If the value of **objectFit** is **Cover**, the image height is the component height minus the top and bottom paddings, and the image width is the component width minus the left and right paddings. Values using percentage notation are not supported.
**Atomic service API**: This API can be used in atomic services since API version 11. | -| verticalAlign | [ImageSpanAlignment](ts-basic-components-imagespan.md#imagespanalignment) | No | Vertical alignment mode of the image.
Default value: **ImageSpanAlignment.BOTTOM**
**Atomic service API**: This API can be used in atomic services since API version 11.| +| verticalAlign | [ImageSpanAlignment](ts-appendix-enums.md#imagespanalignment10)| No | Vertical alignment mode of the image.
Default value: **ImageSpanAlignment.BOTTOM**
**Atomic service API**: This API can be used in atomic services since API version 11.| | objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | No | Scale mode of the image.
Default value: **ImageFit.Cover**
**Atomic service API**: This API can be used in atomic services since API version 11. | | layoutStyle11+ | [RichEditorLayoutStyle](#richeditorlayoutstyle11) | No | Image layout style. Default value: **{"borderRadius":"","margin":""}**

**Atomic service API**: This API can be used in atomic services since API version 12. | @@ -1723,8 +1733,21 @@ Provides the options of the custom context menu on selection. | onAppear | [MenuOnAppearCallback](#menuonappearcallback12) | No | Callback invoked when the custom context menu on selection appears.
**Atomic service API**: This API can be used in atomic services since API version 11.| | onDisappear | Callback\ | No | Callback invoked when the custom context menu on selection disappears.
**Atomic service API**: This API can be used in atomic services since API version 11.| | menuType13+ | [MenuType](ts-text-common.md#menutype13) | No| Type of the custom context menu on selection.
**Atomic service API**: This API can be used in atomic services since API version 13.
Default value: **MenuType.SELECTION_MENU**| -| onMenuShow16+ | [MenuType](#menucallback16) | No| Callback invoked when the custom context menu on selection is shown.
**Atomic service API**: This API can be used in atomic services since API version 16.| -| onMenuHide16+ | [MenuType](#menucallback16) | No| Callback invoked when the custom context menu on selection is hidden.
**Atomic service API**: This API can be used in atomic services since API version 16.| +| onMenuShow15+ | [MenuCallback](#menucallback15) | No| Callback invoked when the custom context menu on selection is shown.
**Atomic service API**: This API can be used in atomic services since API version 15.| +| onMenuHide15+ | [MenuCallback](#menucallback15) | No| Callback invoked when the custom context menu on selection is hidden.
**Atomic service API**: This API can be used in atomic services since API version 15.| +| previewMenuOptions18+ | [PreviewMenuOptions](#previewmenuoptions18) | No| Options of the preview menu.
**Atomic service API**: This API can be used in atomic services since API version 18.| + +## PreviewMenuOptions18+ + +Defines the options of the preview menu. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ----------- | ---------- | ---- | ------------- | +| hapticFeedbackMode | [HapticFeedbackMode](ts-universal-attributes-menu.md#hapticfeedbackmode18)| No| Vibration effect when the menu is displayed.
Default value: **HapticFeedbackMode.DISABLED** (no vibration when the menu is displayed)| ## PasteEvent11+ @@ -1821,13 +1844,13 @@ Represents the callback invoked when the custom context menu on selection appear | start | number | Yes | Start position of the selected content.| | end | number | Yes | End position of the selected content. | -## MenuCallback16+ +## MenuCallback15+ type MenuCallback = (start: number, end: number) => void Represents the callback invoked when the custom context menu on selection is shown or hidden. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 15. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -1869,7 +1892,7 @@ Represents the callback invoked on mouse hover. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------ | ---- | -------------------------------------------------------- | | status | boolean | Yes | Whether the mouse pointer is hovering over the component. The value **true** means that the mouse pointer enters the component, and **false** means that the mouse pointer leaves the component.| -| event | [HoverEvent](ts-universal-events-hover.md#hoverevent11) | Yes | Event bubbling.| +| event | [HoverEvent](ts-universal-events-hover.md#hoverevent10) | Yes | Event bubbling.| ## RichEditorTextSpan @@ -1883,7 +1906,7 @@ Provides the text span information. | ----------------------------- | ---------------------------------------- | ---- | ---------------------- | | spanPosition | [RichEditorSpanPosition](#richeditorspanposition) | Yes | Span position.| | value | string | Yes | Text span content.| -| textStyle | [RichEditorTextStyle](#richeditortextstyle) | Yes | Text span style.| +| textStyle | [RichEditorTextStyle](#richeditortextstyle) | No | Text span style.| ## RichEditorImageSpan @@ -1896,9 +1919,21 @@ Image span information. | Name | Type | Mandatory | Description | |------------------|-------------------------------------------------------------------|-----|------------------| | spanPosition | [RichEditorSpanPosition](#richeditorspanposition) | Yes | Span position.| -| valuePixelMap | [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7)\|[ResourceStr](ts-types.md#resourcestr) | Yes | Image content.| +| value | [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7)\|[ResourceStr](ts-types.md#resourcestr) | Yes | Image content.| | imageStyle | [RichEditorImageSpanStyle](#richeditorimagespanstyle) | No| Image style.| +## RichEditorUrlStyle18+ + +URL information. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory| Description | +|---------|---------------------------------------------|------|---------| +| url | [ResourceStr](ts-types.md#resourcestr) | No | URL.
Default value: **undefined**| + ## Example ### Example 1: Updating the Text Style @@ -3026,6 +3061,14 @@ struct Index { } }) }) + + Button("Set Paragraph Spacing to 50").onClick (() => { + this.controller.updateParagraphStyle({ start: -1, end: -1, + style: { + paragraphSpacing: 50, + } + }) + }) Divider() Button("getParagraphs").onClick(() => { this.spanParagraphs = this.controller.getParagraphs({ start: -1, end: -1 }) @@ -4475,6 +4518,9 @@ struct Index { let richEditorSelection = this.controller.getSelection(); let start = richEditorSelection.start ? richEditorSelection.start : 0; let end = richEditorSelection.end ? richEditorSelection.end : 0; + if (start < 0 || end <= start) { + return; + } // Obtain the styled string displayed in the component. this.richEditorStyledString = this.controller.getStyledString(); this.richEditorStyledString.removeString(start, end - start); @@ -4502,6 +4548,9 @@ struct Index { let richEditorSelection = this.controller.getSelection(); let start = richEditorSelection.start ? richEditorSelection.start : 0; let end = richEditorSelection.end ? richEditorSelection.end : 0; + if (start < 0 || end <= start) { + return; + } // Obtain the styled string displayed in the component. this.richEditorStyledString = this.controller.getStyledString(); this.richEditorStyledString.setStyle({ @@ -4529,7 +4578,7 @@ struct Index { } ``` -![StyledString](figures/StyledString(example20).gif) + ### Example 21: Obtaining Layout Information This example shows how to obtain layout information using the [getLayoutManager](#getlayoutmanager12) API. It includes obtaining the total number of lines using [getLineCount](ts-text-common.md#getlinecount), the glyph position closest to a given coordinate using [getGlyphPositionAtCoordinate](ts-text-common.md#getglyphpositionatcoordinate), and line metrics, text style information, and font properties using [getLineMetrics](ts-text-common.md#getlinemetrics). @@ -4666,7 +4715,12 @@ struct RichEditorExample { ![RichEditorSelectionMenuOptions](figures/richEditorSelectionMenuOptions.png) ### Example 23: Setting Common Component Attributes -This example shows how to set common attributes for the component, including:
Setting the scrollbar display mode during editing using [barState](#barstate13)
Configuring whether the soft keyboard is automatically displayed when the component gains focus through means other than clicking, using [enableKeyboardOnFocus](#enablekeyboardonfocus12)
Enabling or disabling haptic feedback for the component using [enableHapticFeedback](#enablehapticfeedback13)
ObtainIng preview text information using [getPreviewText](#getpreviewtext12) +This example shows how to set common attributes for the component, including: + +- Setting the scrollbar display mode during editing using [barState](#barstate13) +- Configuring whether the soft keyboard is automatically displayed when the component gains focus through means other than clicking, using [enableKeyboardOnFocus](#enablekeyboardonfocus12) +- Enabling or disabling haptic feedback for the component using [enableHapticFeedback](#enablehapticfeedback13) +- Obtaining preview text information using [getPreviewText](#getpreviewtext12) Specifying whether to prevent the back button press from being propagated to other components or applications, using [stopBackPress](#stopbackpress18) ```ts // xxx.ets @@ -4719,6 +4773,7 @@ struct RichEditor_example { .barState(this.bs[this.bs_num]) .enableKeyboardOnFocus(this.e) .enableHapticFeedback(true) + .stopBackPress(false); RichEditor(this.options1).width(300) @@ -4751,10 +4806,10 @@ struct RichEditor_example { ``` -![StyledString](figures/example23.gif) + ### Example 24: Obtaining the Relative Position of the Cursor in the Component -This example demonstrates how to obtain the relative position of the current cursor in the component using the [getCaretRect](#getcaretrect16) API in **RichEditorBaseController**. +This example demonstrates how to obtain the relative position of the current cursor in the component using the [getCaretRect](#getcaretrect18) API in **RichEditorBaseController**. ```ts // xxx.ets @@ -4805,7 +4860,7 @@ struct Index { ``` -![StyledString](figures/example24.gif) + ### Example 25: Setting the Maximum Number of Lines and Maximum Number of Characters This example shows how to set the maximum number of characters using **maxLength** and the maximum number of lines using **maxLines**. @@ -4814,8 +4869,8 @@ This example shows how to set the maximum number of characters using **maxLength @Entry @Component struct RichEditorExample { - @State text: string = "As the sun begins to set, casting a warm golden hue across the sky,"+ - "the world seems to slow down and breathe a sigh of relief. The sky is painted with hues of orange, "+ + @State text: string = "As the sun begins to set, casting a warm golden hue across the sky," + + "the world seems to slow down and breathe a sigh of relief. The sky is painted with hues of orange, " + " pink, and lavender, creating a breathtaking tapestry that stretches as far as the eye can see." + "The air is filled with the sweet scent of blooming flowers, mingling with the earthy aroma of freshly turned soil." + "it casts a warm," + @@ -4832,7 +4887,7 @@ struct RichEditorExample { "it casts a warm," + "golden hue that spreads like liquid amber across the vast expanse of the sky." + "The once-blue heavens gradually transform, " - @State maxLineList: (number | undefined)[] = [ 2, 6, undefined] + @State maxLineList: (number | undefined)[] = [2, 6, undefined] @State maxLineIndex: number = 0 @State maxLineStringList: (string)[] = ["2", "6", "undefined"] richEditorStyledString: MutableStyledString = new MutableStyledString(""); @@ -4869,21 +4924,23 @@ struct RichEditorExample { } }) }) - .margin({left:20}) + .margin({ left: 20 }) } - RichEditor({ controller: this.controller1 }) - .width('95%') - .margin(10) - .maxLength(7) - .backgroundColor('rgb(240,250,255)') - Text("Current maxLine value: " + this.maxLineStringList[this.maxLineIndex]).margin(10) - .fontSize(25) - Button("Change maxLines").onClick(() => { - this.maxLineIndex++ - if (this.maxLineIndex > this.maxLineList.length - 1) { - this.maxLineIndex = 0 - } - }) + + RichEditor({ controller: this.controller1 }) + .width('95%') + .margin(10) + .height(60) + .maxLength(7) + .backgroundColor('rgb(240,250,255)') + Text("Current maxLine value: " + this.maxLineStringList[this.maxLineIndex]).margin(10) + .fontSize(25) + Button("Change maxLines").onClick(() => { + this.maxLineIndex++ + if (this.maxLineIndex > this.maxLineList.length - 1) { + this.maxLineIndex = 0 + } + }) RichEditor({ controller: this.controller3 }) .onReady(() => { this.controller3.addTextSpan(this.text, @@ -4897,11 +4954,114 @@ struct RichEditorExample { .margin(10) .width('95%') .maxLines(this.maxLineList[this.maxLineIndex]) - .height(105) .backgroundColor('rgb(240,250,255)') } } } ``` -![StyledString](figures/maxLengthmaxLines.gif) - + + +### Example 26: Setting the Drag Preview and Drag Shadow for a Custom Layout +This example shows how to use **addBuilderSpan** to configure the drag preview and drag shadow for a custom layout in drag-and-drop scenarios. + +```ts +// xxx.ets +import { ColorMetrics } from '@kit.ArkUI'; + +@Entry +@Component +struct richEditorNew03 { + controller: RichEditorController = new RichEditorController(); + options: RichEditorOptions = { controller: this.controller } + build() { + Column({ space: 10 }) { + Column() { + RichEditor(this.options) + .onReady(() => { + this.controller.addBuilderSpan(() => { + this.placeholderBuilder() + }, { + offset: -1, + dragBackgroundColor: ColorMetrics.rgba(0xff, 0x80, 0, 0xff), + isDragShadowNeeded: false + }) + this.controller.addBuilderSpan(() => { + this.placeholderBuilder() + }, { + offset: -1, + dragBackgroundColor: ColorMetrics.resourceColor("#ffff0000") + .blendColor(ColorMetrics.resourceColor("#ff00ff00")), + isDragShadowNeeded: true + }) + this.controller.addBuilderSpan(() => { + this.placeholderBuilder() + }, { offset: -1 }) + }) + .borderWidth(1) + .width("100%") + .height("50%") + .margin(50) + } + .width('100%') + .margin({top:100}) + } + } + + @Builder + placeholderBuilder() { + Row() { + Text('This is a BuilderSpan, not plain text content') + .fontSize(22) + .copyOption(CopyOptions.InApp) + } + } +} +``` + + +### Example 27: Setting the URL Style for Text +This example demonstrates how to add **UrlStyle** in the **addTextSpan** and **updateSpanStyle** APIs to enable text to be clickable and link to a URL. + +```ts +// xxx.ets + +@Entry +@Component +struct RichEditorExample { + controller: RichEditorController = new RichEditorController(); + options: RichEditorOptions = { controller: this.controller }; + styledStringController: RichEditorStyledStringController = new RichEditorStyledStringController(); + styledStringOptions: RichEditorStyledStringOptions = { controller: this.styledStringController }; + + build() { + Column() { + Row() { + Button("Add Example Url").onClick(() => { + this.controller.addTextSpan("Example URL", { + urlStyle: { url: "https://www.example.com" } + }) + }) + Button("Clear Url").onClick(() => { + this.controller.updateSpanStyle({ + start: 0, + textStyle: {}, + urlStyle: { url: "" } + }) + }) + } + + Row() { + RichEditor(this.options) + .height('35%') + .border({ width: 1, color: Color.Blue }) + } + + Row() { + RichEditor(this.styledStringOptions) + .height('35%') + .border({ width: 1, color: Color.Red }) + } + } + } +} +``` diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-richtext.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-richtext.md index cc90bcc7ff637bb1500d6b52ea1fe9749256dc7f..9738b3ceb5b5e46fd057ab9a50e05d34a28f0f63 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-richtext.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-richtext.md @@ -63,7 +63,7 @@ Triggered when web page loading is completed. ## Attributes -Among the [universal attributes](ts-universal-attributes-size.md), only the **width**, **height**, **size**, and **layoutWeight** attributes are supported. +Among the [universal attributes](ts-component-general-attributes.md), only the **width**, **height**, **size**, and **layoutWeight** attributes are supported. ## Supported Tags diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-scrollbar.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-scrollbar.md index 0c5c284a0b88f9b0bcf9c6efd4499113f46f8912..597874d93d1624d8864ed483508e93d25623c7f9 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-scrollbar.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-scrollbar.md @@ -1,6 +1,6 @@ # ScrollBar -The **ScrollBar** is used together with scrollable components, such as **List**, **Grid**, and **Scroll**. +The **ScrollBar** component is designed to be used together with scrollable components such as [ArcList](ts-container-arclist.md), [List](ts-container-list.md), [Grid](ts-container-grid.md), [Scroll](ts-container-scroll.md), and [WaterFlow](ts-container-waterflow.md). > **NOTE** > @@ -28,11 +28,11 @@ ScrollBar(value: ScrollBarOptions) ## Properties -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. -## enableNestedScroll14+ +### enableNestedScroll14+ -enableNestedScroll(value: boolean) +enableNestedScroll(enabled: Optional\) Sets whether nested scrolling is enabled. @@ -44,7 +44,7 @@ Sets whether nested scrolling is enabled. | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------------- | -| value | boolean | Yes | Whether nested scrolling is enabled. The value **true** means that nested scrolling is enabled, and **false** means the opposite.
Default value: **false**| +| enabled | Optional\ | Yes | Whether nested scrolling is enabled. The value **true** means that nested scrolling is enabled, and **false** means the opposite.
Default value: **false**| > **NOTE** > diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-search.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-search.md index 03b14df03ae4814795281fe4b65f244a4c8ebc09..0093f9210e6a1fae675af990526c5cbad4f23179 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-search.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-search.md @@ -22,26 +22,26 @@ Search(options?: SearchOptions) | Name | Type | Mandatory| Description | | ----------- | ------------- | ---- | ------------- | -| options | [SearchOptions](#searchoptions14)| No | Initialization options of the **Search** component.| +| options | [SearchOptions](#searchoptions18)| No | Initialization options of the **Search** component.| -## SearchOptions14+ +## SearchOptions18+ Describes the initialization options of the **Search** component. -**Atomic service API**: This API can be used in atomic services since API version 14. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full | Name | Type | Mandatory| Description | | ----------- | ------------- | ---- | ------------- | -| value | string | No | Text input in the search text box.
Since API version 10, this parameter supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md).
Since API version 16, this parameter supports two-way binding through [!!](../../../quick-start/arkts-new-binding.md#two-way-binding-between-built-in-component-parameters).| -| placeholder | [ResourceStr](ts-types.md#resourcestr) | No | Text displayed when there is no input. | -| icon | string | No | Path to the search icon. By default, the system search icon is used.
**NOTE**
The icon data source can be a local or online image.
- The supported formats include PNG, JPG, BMP, SVG, GIF, pixelmap, and HEIF.
- The Base64 string is supported in the following format: data:image/[png\|jpeg\|bmp\|webp\|heif];base64,[base64 data], where *[base64 data]* is a Base64 string.
If this attribute and the **searchIcon** attribute are both set, the **searchIcon** attribute takes precedence.| -| controller | [SearchController](#searchcontroller) | No | Controller of the **Search** component. | +| value8+ | string | No | Text input in the search text box.
Since API version 10, this parameter supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md).
Since API version 18, this parameter supports two-way binding through [!!](../../../quick-start/arkts-new-binding.md#two-way-binding-between-built-in-component-parameters).
**Atomic service API**: This API can be used in atomic services since API version 11.| +| placeholder8+ | [ResourceStr](ts-types.md#resourcestr) | No | Text displayed when there is no input.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| icon8+ | string | No | Path to the search icon. By default, the system search icon is used.
**NOTE**
The icon data source can be a local or online image.
- The supported formats include PNG, JPG, BMP, SVG, GIF, pixelmap, and HEIF.
- The Base64 string is supported in the following format: data:image/[png\|jpeg\|bmp\|webp\|heif];base64,[base64 data], where *[base64 data]* is a Base64 string.
If this attribute and the **searchIcon** attribute are both set, the **searchIcon** attribute takes precedence.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| controller8+ | [SearchController](#searchcontroller) | No | Controller of the **Search** component.
**Atomic service API**: This API can be used in atomic services since API version 11. | ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### searchButton @@ -51,6 +51,8 @@ Sets the text on the search button located next to the search text box. Clicking the search button triggers both **onSubmit** and **onClick** callbacks. +The default font size on wearable devices is 18 fp. + **Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -66,7 +68,7 @@ Clicking the search button triggers both **onSubmit** and **onClick** callbacks. placeholderColor(value: ResourceColor) -Sets the placeholder text color. +Sets the placeholder text color. The default value on wearable devices is **#99ffffff.** **Atomic service API**: This API can be used in atomic services since API version 11. @@ -84,6 +86,8 @@ placeholderFont(value?: Font) Sets the placeholder text style, including the font size, font width, font family, and font style. The 'HarmonyOS Sans' font and [registered custom fonts](../js-apis-font.md) are supported. +The default font size on wearable devices is 18 px. + **Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -100,6 +104,8 @@ textFont(value?: Font) Sets the style of the text entered in the search box, including the font size, font width, font family, and font style. Currently, only the default font family is supported. +The default font size on wearable devices is 18 fp. + **Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -130,7 +136,7 @@ Sets the text alignment mode in the search text box. Currently, the following al copyOption(value: CopyOptions) -Sets whether copy and paste is allowed. If this attribute is set to **CopyOptions.None**, the text can be pasted, but copy, cut, or AI-powered writing is not allowed. +Sets whether copy and paste is allowed. If this attribute is set to **CopyOptions.None**, the text can only be pasted; all other actions, such as copying, cutting, and sharing, are disabled. Dragging is not allowed when **CopyOptions.None** is set. @@ -150,6 +156,8 @@ searchIcon(value: IconOptions | SymbolGlyphModifier) Sets the style of the search icon on the left. +The default icon size on wearable devices is 16 vp. + **Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -166,6 +174,8 @@ cancelButton(value: CancelButtonOptions | CancelButtonSymbolOptions) Sets the style of the Cancel button on the right. +The default icon size on wearable devices is 18 vp. + **Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -182,6 +192,8 @@ fontColor(value: ResourceColor) Sets the font color of the input text. [Universal text attributes](ts-universal-attributes-text-style.md) **fontSize**, **fontStyle**, **fontWeight**, and **fontFamily** are set in the [textFont](#textfont) attribute. +The default value on wearable devices is **'#dbffffff'**. + **Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -217,7 +229,7 @@ enableKeyboardOnFocus(value: boolean) Sets whether to enable the input method when the **Search** component obtains focus in a way other than clicking. - +Since API version 10, the **Search** component brings up the keyboard by default when it obtains focus. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -282,7 +294,7 @@ type(value: SearchType) Sets the text box type. -
**Atomic service API**: This API can be used in atomic services since API version 12. +**Atomic service API**: This API can be used in atomic services since API version 12. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -360,7 +372,7 @@ Sets the color, type, and style of the text decorative line. letterSpacing(value: number | string | Resource) -Sets the letter spacing for a text style. If the value specified is a percentage or 0, the default value is used. +Sets the letter spacing for a text style. If the value specified is a percentage or 0, the default value is used. For the string type, numeric string values with optional units, for example, **"10"** or **"10fp"**, are supported. If the value specified is a negative value, the text is compressed. A negative value too small may result in the text being compressed to 0 and no content being displayed. @@ -372,7 +384,7 @@ If the value specified is a negative value, the text is compressed. A negative v | Name| Type | Mandatory| Description | | ------ | -------------------------- | ---- | -------------- | -| value | number \| string \| [Resource](ts-types.md#resource) | Yes | Letter spacing.| +| value | number \| string \| [Resource](ts-types.md#resource) | Yes | Letter spacing.
Unit: fp| ### fontFeature12+ @@ -457,7 +469,7 @@ Sets the indent of the first line text. minFontSize(value: number | string | Resource) -Sets the minimum font size. +Sets the minimum font size. For the string type, numeric string values with optional units, for example, **"10"** or **"10fp"**, are supported. For the setting to take effect, this attribute must be used together with [maxFontSize](#maxfontsize12) or layout constraint settings. @@ -471,13 +483,13 @@ When the adaptive font size is used, the **fontSize** settings do not take effec | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------ | -| value | number \| string \| [Resource](ts-types.md#resource) | Yes | Minimum font size.| +| value | number \| string \| [Resource](ts-types.md#resource) | Yes | Minimum font size.
Unit: fp| ### maxFontSize12+ maxFontSize(value: number | string | Resource) -Sets the maximum font size. +Sets the maximum font size. For the string type, numeric string values with optional units, for example, **"10"** or **"10fp"**, are supported. For the setting to take effect, this attribute must be used together with [minFontSize](#minfontsize12) or layout constraint settings. @@ -491,15 +503,15 @@ When the adaptive font size is used, the **fontSize** settings do not take effec | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------ | -| value | number \| string \| [Resource](ts-types.md#resource) | Yes | Maximum font size.| +| value | number \| string \| [Resource](ts-types.md#resource) | Yes | Maximum font size.
Unit: fp| -### halfLeading16+ +### halfLeading18+ -halfLeading(halfLeading: boolean) +halfLeading(halfLeading: Optional\) Sets whether half leading is enabled. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -507,15 +519,15 @@ Sets whether half leading is enabled. | Name| Type | Mandatory| Description | | ------ | --------------------------------------------- | ---- | --------------------------------------------- | -| halfLeading | boolean | Yes | Whether half leading is enabled.
Whether half leading is enabled. Half leading is the leading split in half and applied equally to the top and bottom edges. The value **true** means that half leading is enabled, and **false** means the opposite.
Default value: **false**| +| halfLeading | [Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Whether half leading is enabled.
Half leading is the leading split in half and applied equally to the top and bottom edges. The value **true** means that half leading is enabled, and **false** means the opposite.
Default value: **false**| -### minFontScale16+ +### minFontScale18+ -minFontScale(scale: number | Resource) +minFontScale(scale: Optional\) Sets the minimum font scale factor for text. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -523,15 +535,15 @@ Sets the minimum font scale factor for text. | Name| Type | Mandatory| Description | | ------ | --------------------------------------------- | ---- | --------------------------------------------- | -| scale | number \| [Resource](ts-types.md#resource) | Yes | Minimum font scale factor for text.
Value range: [0, 1]
**NOTE**
A value less than 0 is handled as 0. A value greater than 1 is handled as 1. Abnormal values are ineffective by default.| +| scale | [Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Minimum font scale factor for text. The **undefined** type is supported.
Value range: [0, 1]
**NOTE**
A value less than 0 is handled as 0. A value greater than 1 is handled as 1. Abnormal values are ineffective by default.| -### maxFontScale16+ +### maxFontScale18+ -maxFontScale(scale: number | Resource) +maxFontScale(scale: Optional\) Sets the maximum font scale factor for text. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -539,7 +551,7 @@ Sets the maximum font scale factor for text. | Name| Type | Mandatory| Description | | ------ | --------------------------------------------- | ---- | --------------------------------------------- | -| scale | number \| [Resource](ts-types.md#resource) | Yes | Maximum font scale factor for text.
Value range: [1, +∞)
**NOTE**
A value less than 1 is handled as 1. Abnormal values are ineffective by default.| +| scale | [Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Maximum font scale factor for text. The **undefined** type is supported.
Value range: [1, +∞)
**NOTE**
A value less than 1 is handled as 1. Abnormal values are ineffective by default.| ### editMenuOptions12+ @@ -575,18 +587,6 @@ Preview text is in a temporary state and does not support text interception. As | ------ | ------- | ---- | ---------------------------------- | | enable | boolean | Yes | Whether to enable preview text.
Default value: **true**| -> **NOTE** -> -> This API is disabled by default in C API scenarios. To enable preview text in such scenarios, set [metadata](../../../../application-dev/quick-start/module-structure.md#internal-structure-of-the-metadata-attribute) in the **module.json5** file of the project as follows: -> ```json -> "metadata": [ -> { -> "name": "can_preview_text", -> "value": "true", -> } -> ] -> ``` - ### enableHapticFeedback13+ enableHapticFeedback(isEnabled: boolean) @@ -614,13 +614,29 @@ Specifies whether to enable haptic feedback. > ] > ``` -### stopBackPress16+ +### keyboardAppearance15+ + +keyboardAppearance(appearance: Optional\) + +Sets the appearance of the keyboard when the text box is focused. + +**Atomic service API**: This API can be used in atomic services since API version 15. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------ | ----------------------------------------- | ---- | ------------------------------------------------------ | +| appearance | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[KeyboardAppearance](ts-text-common.md#keyboardappearance15)> | Yes | Appearance of the keyboard.
Default value: **KeyboardAppearance.NONE_IMMERSIVE**| -stopBackPress(isStopped: boolean) +### stopBackPress15+ + +stopBackPress(isStopped: Optional\) Sets whether to prevent the back button press from being propagated to other components or applications. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 15. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -628,7 +644,7 @@ Sets whether to prevent the back button press from being propagated to other com | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ---------------------------------- | -| isStopped | boolean | Yes | Whether to consume the back button press.
Default value: **true**| +| isStopped | [Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Whether to consume the back button press.
Default value: **true**| ## IconOptions10+ @@ -644,15 +660,13 @@ Sets whether to prevent the back button press from being propagated to other com ## SearchButtonOptions10+ -**Atomic service API**: This API can be used in atomic services since API version 11. - **System capability**: SystemCapability.ArkUI.ArkUI.Full | Name | Type | Mandatory| Description | | --------- | ------------------------------------------ | ---- | ---------------- | -| fontSize | [Length](ts-types.md#length) | No | Font size of the button. It cannot be set in percentage.| -| fontColor | [ResourceColor](ts-types.md#resourcecolor) | No | Font color of the button.| -| autoDisable16+ | boolean | No | Whether the search button is disabled and grayed out when there is no text content.| +| fontSize | [Length](ts-types.md#length) | No | Font size of the button. It cannot be set in percentage. **Atomic service API**: This API can be used in atomic services since API version 11.| +| fontColor | [ResourceColor](ts-types.md#resourcecolor) | No | Font color of the button. **Atomic service API**: This API can be used in atomic services since API version 11.| +| autoDisable18+ | Boolean | No | Whether to disable the search button when there is no text input.
Default value: **false**
**true**: The search button is disabled when there is no text input.
**false**: The search button remains enabled regardless of the text input.
**Atomic service API**: This API can be used in atomic services since API version 18.| ## CancelButtonStyle10+ @@ -705,7 +719,7 @@ Sets whether to prevent the back button press from being propagated to other com ## Events -In addition to the [universal events](ts-universal-events-click.md), the following events are supported. +In addition to the [universal events](ts-component-general-events.md), the following events are supported. ### onSubmit @@ -802,7 +816,7 @@ Invoked when a paste operation is performed. **Parameters** | Name | Type | Mandatory| Description | | ------------------- | ------------------------------------------------------------ | ---- | ---------------------- | -| callback | [OnPasteCallback](ts-basic-components-textinput#onpastecallback14) | Yes | Callback used to return the pasted text content.| +| callback | [OnPasteCallback](ts-basic-components-textinput.md#onpastecallback18) | Yes | Callback used to return the pasted text content.| ### onTextSelectionChange10+ @@ -818,7 +832,7 @@ Invoked when the position of the text selection changes or when the cursor posit | Name | Type | Mandatory| Description | | -------------- | ------ | ---- | ------------------------------------------------- | -| callback | [OnTextSelectionChangeCallback](ts-basic-components-textinput#ontextselectionchangecallback14) | Yes | Callback for text selection changes or cursor position changes.| +| callback | [OnTextSelectionChangeCallback](ts-basic-components-textinput.md#ontextselectionchangecallback18) | Yes | Callback for text selection changes or cursor position changes.| ### onContentScroll10+ @@ -834,7 +848,7 @@ Invoked when the text content is scrolled. | Name | Type | Mandatory| Description | | ------------ | ------ | ---- | ---------------------------------- | -| callback | [OnContentScrollCallback](ts-basic-components-textinput#oncontentscrollcallback14) | Yes | Callback for text content scrolling.| +| callback | [OnContentScrollCallback](ts-basic-components-textinput.md#oncontentscrollcallback18) | Yes | Callback for text content scrolling.| ### onEditChange12+ @@ -866,7 +880,7 @@ Invoked when text is about to be inserted. | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------ | -| callback | Callback\<[InsertValue](ts-text-common.md#insertvalue12), boolean> | Yes | Callback invoked when text is about to be inserted.
It returns **true** if the text is inserted; returns **false** otherwise.
This callback is not invoked for text preview.
It is available only for system input methods.| +| callback | Callback\<[InsertValue](ts-text-common.md#insertvalue12), boolean> | Yes | Callback invoked when text is about to be inserted.
It returns **true** if the text is inserted; returns **false** otherwise.
This callback is not triggered for pre-edit or candidate word operations.
It is available only for system input methods.| ### onDidInsert12+ @@ -916,6 +930,24 @@ Called when text is deleted. | ------ | ------------------------------------------------------------ | ---- | ------------------ | | callback | Callback\<[DeleteValue](ts-text-common.md#deletevalue12)> | Yes | Callback invoked when text is deleted.
It is available only for system input methods.| +### onWillChange15+ + +onWillChange(callback: Callback\) + +Called when the text content is about to change. + +This callback is triggered after **onWillInsert** and **onWillDelete**, but before **onDidInsert** and **onDidDelete**. + +**Atomic service API**: This API can be used in atomic services since API version 15. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------ | +| callback | Callback\<[EditableTextChangeValue](ts-text-common.md#editabletextchangevalue15), boolean> | Yes | Callback triggered when the text content is about to change.
Returning **true** allows the change to proceed, while returning **false** cancels the change.| + ## SearchController Inherits from [TextContentControllerBase](ts-types.md#textcontentcontrollerbase10). @@ -1073,12 +1105,12 @@ struct SearchExample { Search({ value: this.changeValue, placeholder: 'Type to search...' }) .searchButton('SEARCH') .searchIcon({ - src: $r('app.media.search') + src: $r('sys.media.ohos_ic_public_search_filled') }) .cancelButton({ style: CancelButtonStyle.CONSTANT, icon: { - src: $r('app.media.cancel') + src: $r('sys.media.ohos_ic_public_cancel_filled') } }) .width('90%') @@ -1514,3 +1546,320 @@ struct SearchExample { ``` ![searchSymbolGlyphModifierIcon](figures/searchSymbolGlyphModifierIcon.png) + +### Example 12: Setting Whether Text is Copyable + +This example demonstrates how to set whether text is copyable using **copyOption**. + +```ts +// xxx.ets + +@Entry +@Component +struct SearchExample { + controller: SearchController = new SearchController() + @State copyValue: string = '' + @State cutValue: string = '' + + build() { + Column({ space: 3 }) { + Text("copy: " + this.copyValue) + Text("cut:" + this.cutValue) + Search({ value: 'Search CopyOption:None', controller: this.controller }) + .width('95%') + .height(40) + .copyOption(CopyOptions.None) + .onCopy((value: string) => { + this.copyValue = value; + }) + .onCut((value: string) => { + this.cutValue = value; + }) + Search({ value: 'Search CopyOption:InApp', controller: this.controller }) + .width('95%') + .height(40) + .copyOption(CopyOptions.InApp) + .onCopy((value: string) => { + this.copyValue = value; + }) + .onCut((value: string) => { + this.cutValue = value; + }) + Search({ value: 'Search CopyOption:LocalDevice', controller: this.controller }) + .width('95%') + .height(40) + .copyOption(CopyOptions.LocalDevice) + .onCopy((value: string) => { + this.copyValue = value; + }) + .onCut((value: string) => { + this.cutValue = value; + }) + } + .width('100%') + .height('100%') + } +} +``` + +![searchCopyOption](figures/searchCopyOption.gif) + +### Example 13: Setting the Horizontal Alignment, Caret Style, and Background Color of the Selected Text + +This example shows how to set the horizontal alignment, caret style, and background color of the selected text using **textAlign**, **caretStyle**, and **selectedBackgroundColor**. + +```ts +// xxx.ets + +@Entry +@Component +struct SearchExample { + controller: SearchController = new SearchController() + + build() { + Column({ space: 3 }) { + Search({ value: 'Search textAlign sample', controller: this.controller }) + .width('95%') + .height(40) + .stopBackPress(true) + .textAlign(TextAlign.Center) + .caretStyle({ width: 3, color: Color.Green }) + .selectedBackgroundColor(Color.Gray) + } + .width('100%') + .height('100%') + } +} +``` + +![searchTextAlign](figures/searchTextAlign.gif) + +### Example 14: Configuring the Text Box to Receive Default Focus and Bring Up the Soft Keyboard + +This example illustrates how to configure the text box to receive default focus and bring up the soft keyboard using **defaultFocus** and **enableKeyboardOnFocus**. + +```ts +// xxx.ets + +@Entry +@Component +struct SearchExample { + controller: SearchController = new SearchController() + @State value: string = 'false' + + build() { + Column({ space: 3 }) { + Text('editing: ' + this.value) + Search({ placeholder: 'please enter...', controller: this.controller }) + .width('95%') + .height(40) + .defaultFocus(true) + .enableKeyboardOnFocus(true) + .enablePreviewText(true) + .enableHapticFeedback(true) + .onEditChange((data: boolean) => { + this.value = data ? 'true' : 'false' + }) + } + .width('100%') + .height('100%') + } +} +``` + +![searchEnableKeyboardOnFocus](figures/searchEnableKeyboardOnFocus.gif) + +### Example 15: Disabling the System Context Menu on Selection + +This example shows how to disable the system context menu on selection using **defaultFocus** and **enableKeyboardOnFocus**. + +```ts +// xxx.ets + +@Entry +@Component +struct SearchExample { + controller: SearchController = new SearchController() + + build() { + Column({ space: 3 }) { + Search({ value: '123456', controller: this.controller }) + .width('95%') + .height(40) + .type(SearchType.NUMBER) + .selectionMenuHidden(true) + } + .width('100%') + .height('100%') + } +} +``` + +![searchSelectionMenuHidden](figures/searchSelectionMenuHidden.gif) + +### Example 16: Setting Input Filtering + +This example shows how to set input filtering using **inputFilter**. + +```ts +// xxx.ets + +@Entry +@Component +struct SearchExample { + controller: SearchController = new SearchController() + @State filterValue: string = '' + + build() { + Column({ space: 3 }) { + Text('Filter:' + this.filterValue) + Search({ placeholder: 'please enter...', controller: this.controller }) + .width('95%') + .height(40) + .textIndent(5) + .halfLeading(true) + .inputFilter('[a-z]', (filterValue: string) => { + this.filterValue = filterValue + }) + } + .width('100%') + .height('100%') + } +} +``` + +![searchInputFilter](figures/searchInputFilter.gif) + +### Example 17: Selecting a Specific Text Range + +This example illustrates how to select a specific range of text content using **setTextSelection**. + +```ts +// xxx.ets + +@Entry +@Component +struct SearchExample { + controller: SearchController = new SearchController() + @State startIndex: number = 0 + @State endIndex: number = 0 + + build() { + Column({ space: 3 }) { + Text('Selection start:' + this.startIndex + ' end:' + this.endIndex) + Search({ value: 'Hello World', controller: this.controller }) + .width('95%') + .height(40) + .minFontScale(1) + .maxFontScale(1.5) + .defaultFocus(true) + .onTextSelectionChange((selectionStart: number, selectionEnd: number) => { + this.startIndex = selectionStart + this.endIndex = selectionEnd + }) + + Button('Selection [0,3]') + .onClick(() => { + this.controller.setTextSelection(0, 3) + }) + } + .width('100%') + .height('100%') + } +} +``` + +![searchSetTextSelection](figures/searchSetTextSelection.gif) + +### Example 18: Handling Text Scrolling Events + +This example demonstrates how to set a callback for text scrolling events using **onContentScroll**. + +```ts +// xxx.ets + +@Entry +@Component +struct SearchExample { + controller: SearchController = new SearchController() + @State offsetX: number = 0 + @State offsetY: number = 0 + + build() { + Column({ space: 3 }) { + Text('offset x:' + this.offsetX + ' y:' + this.offsetY) + Search({ value: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', controller: this.controller }) + .width(200) + .height(40) + .onContentScroll((totalOffsetX: number, totalOffsetY: number) => { + this.offsetX = totalOffsetX + this.offsetY = totalOffsetY + }) + } + .width('100%') + .height('100%') + } +} +``` + +![searchOnContentScroll](figures/searchOnContentScroll.gif) + +### Example 19: Setting the Minimum and Maximum Font Scale Factor + +This example demonstrates how to set the minimum and maximum font scale factor using **minFontScale** and **maxFontScale**. + +```ts +import { abilityManager, Configuration } from '@kit.AbilityKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +// xxx.ets +@Entry +@Component +export struct TextAreaExample11 { + @State minFontScale: number = 0.85; + @State maxFontScale: number = 2; + @State changeValue: string = 'abcde'; + + build() { + Column() { + Column({ space: 30 }) { + Text("System font size changes: small and large, small and large") + TextArea({ + placeholder: 'The text area can hold an unlimited amount of text. input your word...', + }) + // Set the minimum font scale factor; if the value is undefined, the text follows the default font scale factor. + .minFontScale(0.85) + // Set the maximum font scale factor; if the value is undefined, the text follows the default font scale factor. + .maxFontScale(2) + }.width('100%') + } + } +} +``` + +```ts +Create a new directory named profile in the following path: AppScope/resources/base. +Inside the newly created profile directory, create a file named configuration.json. +Add the following JSON code to the configuration.json file: +{ + "configuration":{ + "fontSizeScale": "followSystem", + "fontSizeMaxScale": "3.2" +} +} +``` + +```ts +Modify the app.json5 file in AppScope as follows: +{ + "app": { + "bundleName": "com.example.myapplication", + "vendor": "example", + "versionCode": 1000000, + "versionName": "1.0.0", + "icon": "$media:app_icon", + "label": "$string:app_name", + "configuration": "$profile:configuration" + } +} +``` diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-select.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-select.md index f8e93203a215df3506c2bb635c6b67357b9b9e40..11e658263af10193b100616e6ae99772481ce2ff 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-select.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-select.md @@ -12,7 +12,7 @@ Not supported ## APIs -Select(options: Array\<[SelectOption](#selectoption)\>) +Select(options: Array\) **Atomic service API**: This API can be used in atomic services since API version 11. @@ -36,7 +36,7 @@ Select(options: Array\<[SelectOption](#selectoption)\>) ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### selected @@ -45,6 +45,7 @@ selected(value: number | Resource) Sets the index of the initial selected option in the drop-down list box. The index of the first option is **0**. If this attribute is set to an invalid value or is not set, the default value **-1** will be used, which means that no option will be selected. If this attribute is set to **undefined** or **null**, the first option will be selected. Since API version 10, this attribute supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md). +Since API version 18, this attribute supports two-way binding through [!!](../../../quick-start/arkts-new-binding.md#two-way-binding-between-built-in-component-parameters). **Atomic service API**: This API can be used in atomic services since API version 11. @@ -54,7 +55,26 @@ Since API version 10, this attribute supports two-way binding through [$$](../.. | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------ | -| value | number \| [Resource](ts-types.md#resource)11+ | Yes | Index of the initial selected option in the drop-down list box.| +| value | number \| [Resource](ts-types.md#resource)11+ | Yes | Index of the default option in the drop-down list box. The index is zero-based.| + +### selected18+ + +selected(numCount: Optional) + +Sets the index of the initial selected option in the drop-down list box. The index of the first option is **0**. If this attribute is set to an invalid value or is not set, the default value **-1** will be used, which means that no option will be selected. If this attribute is set to **undefined** or **null**, the first option will be selected. + +This attribute supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md). +This attribute supports two-way binding through [!!](../../../quick-start/arkts-new-binding.md). + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| numCount | [Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Index of the initial selected option in the drop-down list box.
If **numCount** is set to **undefined**, the first item is selected by default.| ### value @@ -63,6 +83,7 @@ value(value: ResourceStr) Sets the text of the drop-down button. By default, it will be replaced by the content of the selected option, if any. Since API version 10, this attribute supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md). +Since API version 18, this attribute supports two-way binding through [!!](../../../quick-start/arkts-new-binding.md#two-way-binding-between-built-in-component-parameters). **Atomic service API**: This API can be used in atomic services since API version 11. @@ -72,7 +93,25 @@ Since API version 10, this attribute supports two-way binding through [$$](../.. | Name| Type | Mandatory| Description | | ------ | ---------------------------------------------------- | ---- | ------------------------ | -| value | [ResourceStr](ts-types.md#resourcestr)11+ | Yes | Text of the drop-down button.| +| value | [ResourceStr](ts-types.md#resourcestr)11+ | Yes | Text of the drop-down button.
**NOTE**
If the text is longer than the column width, it will be truncated.| + +### value18+ + +value(resStr: Optional\) + +Sets the text of the drop-down button. By default, it will be replaced by the content of the selected option, if any. Compared to [value](#value), this API supports the **undefined** type for the **resStr** parameter. + +This attribute supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md) or [!!](../../../quick-start/arkts-new-binding.md). + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| resStr | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[ResourceStr](ts-types.md#resourcestr)> | Yes | Text of the drop-down button.
If **resStr** is set to **undefined**, the previous value is retained.| ### controlSize12+ @@ -86,10 +125,34 @@ Sets the size of the **Select** component. **Parameters** -| Name| Type | Mandatory| Description | -| ------ | --------------------------------------------- | ---- | ------------------------------------------------ | +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------ | | value | [ControlSize](ts-basic-components-button.md#controlsize11)11+ | Yes | Size of the **Select** component.
Default value: **ControlSize.NORMAL**| +The priorities of **controlSize**, **width**, and **height** are as follows: + + 1. If only **width** and **height** are set and the text is too large to fit in the component the text exceeds the component size and is displayed as an ellipsis (...). + + 2. If only controlSize is set but width and height are not set, the width and height of the component adapt to the text. The text cannot exceed the component, and minWidth and minHeight are set. + + 3) If controlSize, width, and height are set, the values of width and height take effect. If the values of width and height are less than the values of minWidth and minHeight set by controlSize, the values of width and height do not take effect, the width and height are the same as the minimum width minWidth and minimum height minHeight configured by controlSize. + +### controlSize18+ + +controlSize(size: Optional\) + +Sets the size of the **Select** component. Compared to [controlSize](#controlsize12)12+, this API supports the **undefined** type for the **size** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| size | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[ControlSize](ts-basic-components-button.md#controlsize11)> | Yes | Size of the **Select** component.
If **size** is set to **undefined**, the default value **ControlSize.NORMAL** is used.| + The priorities of **controlSize**, **width**, and **height** are as follows: 1. If only **width** and **height** are set and the text is too large to fit in the component the text exceeds the component size and is displayed as an ellipsis (...). @@ -114,6 +177,22 @@ Creates a content modifier for the drop-down list box. | ------ | --------------------------------------------- | ---- | ------------------------------------------------ | | modifier | [ContentModifier\](#menuitemconfiguration12) | Yes | Content modifier to apply to the drop-down list box.
**modifier**: content modifier. You need a custom class to implement the **ContentModifier** API.| +### menuItemContentModifier18+ + +menuItemContentModifier(modifier: Optional\>) + +Creates a content modifier for the drop-down list box. Compared to [menuItemContentModifier](#menuitemcontentmodifier12)12+, this API supports the **undefined** type for the **modifier** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| modifier | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[ContentModifier\](#menuitemconfiguration12)> | Yes | Content modifier to apply to the drop-down list box.
**modifier**: content modifier. You need a custom class to implement the **ContentModifier** API.
If **modifier** is set to **undefined**, no content modifier is used.| + ### divider12+ divider(options: Optional\ | null) @@ -129,6 +208,20 @@ Sets the divider style. If this attribute is not set, the divider is displayed b | ------ | ------- | ---- | --------------------------------------------------------------------- | | options | Optional\<[DividerOptions](ts-basic-components-textpicker.md#divideroptions12)> \| null | Yes | Divider options.
1. If **DividerOptions** is set, the divider is displayed in the configured style.
Default value:
{
strokeWidth: '1px' ,
color: '#33182431'
}
2. If this parameter is set to **null**, the divider is not displayed.
3. If the value of **strokeWidth** is too larger, the divider may overlap the text. The divider extends both upwards and downwards from the bottom of each item.
4. The default values for **startMargin** and **endMargin** are consistent with the style of the divider when the **divider** attribute is not set. If the sum of **startMargin** and **endMargin** is equal to the value of **optionWidth**, the divider is not displayed. If the sum of **startMargin** and **endMargin** exceeds the value of **optionWidth**, the divider line is displayed in the default style.| +### dividerStyle18+ + +Sets the divider style. If this attribute is not set, the divider is displayed based on the default value. This attribute cannot be used together with the **divider** attribute. The last one called will take effect. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | --------------------------------------------------------------------- | +| options | Optional\<[DividerStyleOptions](ts-types.md#dividerstyleoptions12)> \| null | Yes | Divider options.
1. If **DividerOptions** is set, the divider is displayed in the configured style.
Default value:
{
strokeWidth: '1px' ,
color: '#33182431'
}
2. If this parameter is set to **null** or **undefined**, the default divider is displayed.
3. When **mode** is set to **FLOAT_ABOVE_MENU**, be careful with the **strokeWidth** settings to avoid covering text. The divider extends both upwards and downwards from the bottom of each item. When **mode** is **EMBEDDED_IN_MENU**, the divider expands to fill its own space within the menu.
4. The default values for **startMargin** and **endMargin** are consistent with the style of the divider when the **divider** attribute is not set. If the sum of **startMargin** and **endMargin** is equal to the value of **optionWidth**, the divider is not displayed. If the sum of **startMargin** and **endMargin** exceeds the value of **optionWidth**, the divider line is displayed in the default style.| + ### font font(value: Font) @@ -143,7 +236,23 @@ Sets the text font of the drop-down button. If **size** is set to **0**, the tex | Name| Type | Mandatory| Description | | ------ | ------------------------ | ---- | ------------------------------------------------------------ | -| value | [Font](ts-types.md#font) | Yes | Text font of the drop-down button.
Default value:
API version 11 and earlier versions:
{
size: $r('sys.float.ohos_id_text_size_button1'),
weight: FontWeight.Medium
}
Since API version 12: The default value of **size** is **$r('sys.float.ohos_id_text_size_button2')** in the case of **controlSize.SMALL** and **$r('sys.float.ohos_id_text_size_button1')** in other cases.| +| value | [Font](ts-types.md#font) | Yes | Text font of the drop-down button.
Default value:
API version 11 and earlier versions:
{
size: `$r('sys.float.ohos_id_text_size_button1')`,
weight: FontWeight.Medium
}
Since API version 12: The default value of **size** is **$r('sys.float.ohos_id_text_size_button2')** in the case of **controlSize.SMALL** and **$r('sys.float.ohos_id_text_size_button1')** in other cases.| + +### font18+ + +font(selectFont: Optional\) + +Sets the font style of the drop-down button. If **size** is set to **0**, the text is not displayed. If **size** is set to a negative value, the text is displayed at its default size. Compared to [font](#font), this API supports the **undefined** type for the **selectFont** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| selectFont | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[Font](ts-types.md#font)> | Yes | Font style of the drop-down button.
If c**ontrolSize** is set to **controlSize.SMALL**, the default value of **size** is **$r('sys.float.ohos_id_text_size_button2')**. Otherwise, the default value is **$r('sys.float.ohos_id_text_size_button1')**.
If **selectFont** is set to **undefined**, the default font style is used.| ### fontColor @@ -161,6 +270,22 @@ Sets the font color of the drop-down button. | ------ | ------------------------------------------ | ---- | ------------------------------------------------------------ | | value | [ResourceColor](ts-types.md#resourcecolor) | Yes | Font color of the drop-down button.
Default value: **$r('sys.color.ohos_id_color_text_primary')** with the opacity of **$r('sys.color.ohos_id_alpha_content_primary')**| +### fontColor18+ + +fontColor(resColor: Optional\) + +Sets the font color of the drop-down button. Compared to [fontColor](#fontcolor), this API supports the **undefined** type for the **resColor** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| resColor | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[ResourceColor](ts-types.md#resourcecolor)> | Yes | Font color of the drop-down button.
When **resColor** is set to **undefined**, the default value is a blend of **$r('sys.color.ohos_id_color_text_primary')** with the opacity of **$r('sys.color.ohos_id_alpha_content_primary')**.
If **value** is set to **undefined**, the previous value is retained.| + ### selectedOptionBgColor selectedOptionBgColor(value: ResourceColor) @@ -177,6 +302,22 @@ Sets the background color of the selected option in the drop-down list box. | ------ | ------------------------------------------ | ---- | ------------------------------------------------------------ | | value | [ResourceColor](ts-types.md#resourcecolor) | Yes | Background color of the selected option in the drop-down list box.
Default value: **$r('sys.color.ohos_id_color_component_activated')** with the opacity of **$r('sys.color.ohos_id_alpha_highlight_bg')**| +### selectedOptionBgColor18+ + +selectedOptionBgColor(resColor: Optional\) + +Sets the background color of the selected option in the drop-down list box. Compared to [selectedOptionBgColor](#selectedoptionbgcolor), this API supports the **undefined** type for the **resColor** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| resColor | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[ResourceColor](ts-types.md#resourcecolor)> | Yes | Background color of the selected option in the drop-down list box.
When **resColor** is set to **undefined**, the default value is a blend of **$r('sys.color.ohos_id_color_component_activated')** with the opacity of **$r('sys.color.ohos_id_alpha_highlight_bg')**.| + ### selectedOptionFont selectedOptionFont(value: Font) @@ -193,6 +334,22 @@ Sets the text font of the selected option in the drop-down list box. When **size | ------ | ------------------------ | ---- | ------------------------------------------------------------ | | value | [Font](ts-types.md#font) | Yes | Text font of the selected option in the drop-down list box.
Default value:
{
size: $r('sys.color.ohos_id_text_size_body1'),
weight: FontWeight.Regular
} | +### selectedOptionFont18+ + +selectedOptionFont(selectFont: Optional\) + +Sets the text font of the selected option in the drop-down list box. When **size** is set to **0**, the text is not displayed. When **size** is set to a negative value, the text is displayed at its default size. Compared to [selectedOptionFont](#selectedoptionfont), this API supports the **undefined** type for the **selectFont** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| selectFont | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[Font](ts-types.md#font)> | Yes | Text font of the selected option in the drop-down list box.
If **selectFont** is set to **undefined**, the default value is used:
{
size: $r('sys.color.ohos_id_text_size_body1'),
weight: FontWeight.Regular
} | + ### selectedOptionFontColor selectedOptionFontColor(value: ResourceColor) @@ -209,6 +366,22 @@ Sets the font color of the selected option in the drop-down list box. | ------ | ------------------------------------------ | ---- | ------------------------------------------------------------ | | value | [ResourceColor](ts-types.md#resourcecolor) | Yes | Font color of the selected option in the drop-down list box.
Default value: **$r('sys.color.ohos_id_color_text_primary_activated')**| +### selectedOptionFontColor18+ + +selectedOptionFontColor(resColor: Optional\) + +Sets the font color of the selected option in the drop-down list box. Compared to [selectedOptionFontColor](#selectedoptionfontcolor), this API supports the **undefined** type for the **resColor** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| resColor | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[ResourceColor](ts-types.md#resourcecolor)> | Yes | Font color of the selected option in the drop-down list box.
If **resColor** is set to **undefined**, the default value **$r('sys.color.ohos_id_color_text_primary_activated')** is used.| + ### optionBgColor optionBgColor(value: ResourceColor) @@ -225,6 +398,22 @@ Sets the background color of options in the drop-down list box. | ------ | ------------------------------------------ | ---- | ------------------------------------------------------------ | | value | [ResourceColor](ts-types.md#resourcecolor) | Yes | Background color of an option in the drop-down list box.
Default value:
Versions earlier than API version 11: **Color.White**
Since API version 11: **Color.Transparent**| +### optionBgColor18+ + +optionBgColor(resColor: Optional\) + +Sets the background color of options in the drop-down list box. Compared to [optionBgColor](#optionbgcolor), this API supports the **undefined** type for the **resColor** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| resColor | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[ResourceColor](ts-types.md#resourcecolor)> | Yes | Background color of an option in the drop-down list box.
If **resColor** is set to **undefined**, the default value **Color.Transparent** is used.| + ### optionFont optionFont(value: Font) @@ -241,6 +430,24 @@ Sets the text font of options in the drop-down list box. When **size** is set to | ------ | ------------------------ | ---- | ------------------------------------------------------------ | | value | [Font](ts-types.md#font) | Yes | Text font of options in the drop-down list box.
Default value:
{
size: $r('sys.float.ohos_id_text_size_body1'),
weight: FontWeight.Regular
} | +### optionFont18+ + +optionFont(selectFont: Optional\) + +Sets the text font of options in the drop-down list box. When **size** is set to **0**, the text is not displayed. When **size** is set to a negative value, the text is displayed at its default size. + +Compared to [optionFont](#optionfont), this API supports the **undefined** type for the **selectFont** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| selectFont | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[Font](ts-types.md#font)> | Yes | Text font of options in the drop-down list box.
If **selectFont** is set to **undefined**, the default value is used:
{
size: $r('sys.float.ohos_id_text_size_body1'),
weight: FontWeight.Regular
} | + ### optionFontColor optionFontColor(value: ResourceColor) @@ -257,6 +464,22 @@ Sets the font color of options in the drop-down list box. | ------ | ------------------------------------------ | ---- | ------------------------------------------------------------ | | value | [ResourceColor](ts-types.md#resourcecolor) | Yes | Font color of options in the drop-down list box.
Default value: **$r('sys.color.ohos_id_color_text_primary')**| +### optionFontColor18+ + +optionFontColor(resColor: Optional\) + +Sets the font color of options in the drop-down list box. Compared to [optionFontColor](#optionfontcolor), this API supports the **undefined** type for the **resColor** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| resColor | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[ResourceColor](ts-types.md#resourcecolor)> | Yes | Font color of options in the drop-down list box.
If **resColor** is set to **undefined**, the default value **$r('sys.color.ohos_id_color_text_primary')** is used.| + ### space10+ space(value: Length) @@ -271,7 +494,23 @@ Sets the spacing between the text and arrow of an option. This attribute cannot | Name| Type | Mandatory| Description | | ------ | ---------------------------- | ---- | ------------------------------------------------ | -| value | [Length](ts-types.md#length) | Yes | Spacing between the text and arrow of an option.
Default value: **8**| +| value | [Length](ts-types.md#length) | Yes | Spacing between the text and arrow of an option.
Default value: **8**
**NOTE**
For the string type, percentage values are not supported.| + +### space18+ + +space(spaceLength: Optional\) + +Sets the spacing between the text and arrow of an option. This attribute cannot be set in percentage. If the value specified is **null**, **undefined**, or a value less than or equal to 8, the default value is used. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| spaceLength | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[Length](ts-types.md#length)> | Yes | Spacing between the text and arrow of an option.
If **spaceLength** is set to **undefined**, the default value **8** is used.| ### arrowPosition10+ @@ -289,6 +528,22 @@ Sets the alignment between the text and arrow of an option. | ------ | ----------------------------------------- | ---- | ------------------------------------------------------------ | | value | [ArrowPosition](#arrowposition10) | Yes | Alignment between the text and arrow of an option.
Default value: **ArrowPosition.END**| +### arrowPosition18+ + +arrowPosition(position: Optional\) + +Sets the alignment between the text and arrow of an option. Compared to [arrowPosition](#arrowposition10), this API supports the **undefined** type for the **position** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| position | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[ArrowPosition](#arrowposition10)> | Yes | Alignment between the text and arrow of an option.
If **position** is set to **undefined**, the default value **ArrowPosition.END** is used.| + ### menuAlign10+ menuAlign(alignType: MenuAlignType, offset?: Offset) @@ -306,6 +561,23 @@ Sets the alignment between the drop-down button and the drop-down menu. | alignType | [MenuAlignType](#menualigntype10) | Yes | Alignment type.
Default value: **MenuAlignType.START** | | offset | [Offset](ts-types.md#offset) | No | Offset of the drop-down menu relative to the drop-down button after alignment based on the alignment type.
Default value: **{dx: 0, dy: 0}**| +### menuAlign18+ + +menuAlign(alignType: Optional\, offset?: Offset) + +Sets the alignment between the drop-down button and the drop-down menu. Compared to [menuAlign](#menualign10)10+, this API supports the **undefined** type for the **alignType** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| alignType | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[MenuAlignType](#menualigntype10)> | Yes | Alignment type.
If **alignType** is set to **undefined**, the default value **MenuAlignType.START** is used.| +| offset | [Offset](ts-types.md#offset) | No | Offset of the drop-down menu relative to the drop-down button after alignment based on the alignment type.
Default value: **{dx: 0, dy: 0}**| + ### optionWidth11+ optionWidth(value: Dimension | OptionWidthMode ) @@ -324,13 +596,31 @@ If an invalid value or a value less than the minimum width of 56 vp is set, the | ------ | ------------------------------------------------------------ | ---- | ------------------ | | value | [Dimension](ts-types.md#dimension10) \| [OptionWidthMode](ts-appendix-enums.md#optionwidthmode11) | Yes | Width of the option in the drop-down list box.| +### optionWidth18+ + +optionWidth(width: Optional\ ) + +Sets the width for the option in the drop-down list box. This attribute cannot be set in percentage. **OptionWidthMode** specifies whether to inherit the width of the drop-down list button. Compared to [optionWidth](#optionwidth11)11+, this API supports the **undefined** type for the **width** parameter. + +If an invalid value or a value less than the minimum width of 56 vp is set, the attribute does not take effect, and the option width uses the default value, which is two columns. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| width | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[Dimension](ts-types.md#dimension10) \| [OptionWidthMode](ts-appendix-enums.md#optionwidthmode11)> | Yes | Width of the option in the drop-down list box.
If set to **undefined**, this attribute does not take effect. In this case, the default width of two columns is used.| + ### optionHeight11+ optionHeight(value: Dimension) Sets the maximum height for the option in the drop-down list box. This attribute cannot be set in percentage. The default and maximum value is 80% of the available height of the screen. -If set to an invalid value or 0, this attribute does not take effect. In this case, the default value is used. +If set to an invalid value, **0**, or **undefined**, this attribute does not take effect. In this case, the default value is used. If the actual height of all options in the drop-down list box is less than the preset height, the options are displayed at their actual height. @@ -344,6 +634,26 @@ If the actual height of all options in the drop-down list box is less than the p | ------ | ------------------------------------ | ---- | ------------------------ | | value | [Dimension](ts-types.md#dimension10) | Yes | Maximum height of the option in the drop-down list box.| +### optionHeight18+ + +optionHeight(height: Optional\) + +Sets the maximum height for the option in the drop-down list box. This attribute cannot be set in percentage. The default and maximum value is 80% of the available height of the screen. Compared to [optionHeight](#optionheight11)11+, this API supports the **undefined** type for the **height** parameter. + +If set to an invalid value or 0, this attribute does not take effect. In this case, the default value is used. + +If the actual height of all options in the drop-down list box is less than the preset height, the options are displayed at their actual height. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| height | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[Dimension](ts-types.md#dimension10)> | Yes | Maximum height of the option in the drop-down list box. | + ### menuBackgroundColor11+ menuBackgroundColor(value: ResourceColor) @@ -360,6 +670,22 @@ Sets the background color of the drop-down list box. | ------ | ------------------------------------------ | ---- | ------------------------------------------------------------ | | value | [ResourceColor](ts-types.md#resourcecolor) | Yes | Background color of the drop-down list box.
Default value:
Versions earlier than API version 11: **$r('sys.color.ohos_id_color_card_bg')**
Since API version 11: **Color.Transparent**| +### menuBackgroundColor18+ + +menuBackgroundColor(resColor: Optional\) + +Sets the background color of the drop-down list box. Compared to [menuBackgroundColor](#menubackgroundcolor11)11+, this API supports the **undefined** type for the **resColor** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| resColor | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[ResourceColor](ts-types.md#resourcecolor)> | Yes | Background color of the drop-down list box.
If **resColor** is set to **undefined**, the default value **Color.Transparent** is used.| + ### menuBackgroundBlurStyle11+ menuBackgroundBlurStyle(value: BlurStyle) @@ -372,20 +698,70 @@ Sets the background blur style of the drop-down list box. **Parameters** -| Name| Type | Mandatory| Description | -| ------ | -------------------------------------------- | ---- | ------------------------------------------------------------ | +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | value | [BlurStyle](ts-universal-attributes-background.md#blurstyle9) | Yes | Background blur style of the drop-down list box.
Default value: **BlurStyle.COMPONENT_ULTRA_THICK**| +### menuBackgroundBlurStyle18+ + +menuBackgroundBlurStyle(style: Optional\) + +Sets the background blur style of the drop-down list box. Compared to [menuBackgroundBlurStyle](#menubackgroundblurstyle11)11+, this API supports the **undefined** type for the **style** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| style | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[BlurStyle](ts-universal-attributes-background.md#blurstyle9)> | Yes | Background blur style of the drop-down list box.
If **style** is set to **undefined**, the default value **BlurStyle.COMPONENT_ULTRA_THICK** is used.| + +### avoidance18+ + +avoidance(mode: AvoidanceMode) + +Sets the avoidance mode for the drop-down list box. + +**Widget capability**: This API can be used in ArkTS widgets since API version 18. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | +| mode | [AvoidanceMode](#avoidancemode18) | Yes | Avoidance mode of the drop-down list box.
Default value: **AvoidanceMode.COVER_TARGET**| + +### menuOutline18+ + +menuOutline(value: MenuOutlineOptions) + +Sets the outline style for the drop-down list box. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| value | [MenuOutlineOptions](#menuoutlineoptions18) | Yes | Outline style of the drop-down list box.| + ## ArrowPosition10+ **Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Description | -| ------------------- | ------------------ | -| END10+ | The text is in front of the arrow.| -| START10+ | The arrow is in front of the text.| +| Name | Value | Description | +| ------------------- | ------------------ | ------------------ | +| END | 0 | The text is in front of the arrow.| +| START | 1 | The arrow is in front of the text.| ## MenuAlignType10+ @@ -393,11 +769,26 @@ Sets the background blur style of the drop-down list box. **System capability**: SystemCapability.ArkUI.ArkUI.Full +| Name | Value| Description | +| ------------------- | --- | ------------------ | +| START | 0 |Aligned with the start edge in the same direction as the language in use.| +| CENTER | 1 |Aligned with the center.| +| END | 2 |Aligned with the end edge in the same direction as the language in use.| + +## AvoidanceMode18+ + +Enumerates the avoidance modes of the drop-down list box. + +**Widget capability**: This API can be used in ArkTS widgets since API version 18. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + | Name | Description | | ------------------- | ------------------ | -| START | Aligned with the start edge in the same direction as the language in use.| -| CENTER | Aligned with the center.| -| END | Aligned with the end edge in the same direction as the language in use.| +| COVER_TARGET | If there is not enough space below the target component, cover the target component.| +| AVOID_AROUND_TARGET | If there is not enough space around the target component, compress and display in the largest available space (scrollable).| ## MenuItemConfiguration12+ @@ -407,13 +798,26 @@ Sets the background blur style of the drop-down list box. | Name| Type | Mandatory| Description | | ------ | -------------------------------------------- | ---- | ------------------------------------------------------------ | -| value | [ResourceStr](ts-types.md#resourcestr) | Yes | Text content of the option in the drop-down list box.| -| icon | [ResourceStr](ts-types.md#resourcestr) | No | Icon of the option in the drop-down list box.| +| value | [ResourceStr](ts-types.md#resourcestr) | Yes | Text content of the option in the drop-down list box.
**NOTE**
If the text is longer than the width of the menu text area, it is truncated.| +| icon | [ResourceStr](ts-types.md#resourcestr) | No | Icon of the option in the drop-down list box.
**NOTE**
The string type can be used to load network images and local images.| | symbolIcon12+ | [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) | No | Symbol icon of the option in the drop-down list box.| | selected | boolean | Yes | Whether the option in the drop-down list box is selected.
Default value: **false**| -| index | number | Yes | Index of the option in the drop-down list box.| +| index | number | Yes | Index of the option in the drop-down list box. The index is zero-based.| | triggerSelect | (index: number, value: string) :void | Yes | Invoked when an option in the drop-down list box is selected.
**index**: index of the selected option.
**value**: text of the selected option.
**NOTE**
The value of **index** will be assigned to the **index** parameter in the [onSelect](#onselect) callback; the value of **value** will be returned to the **Select** component for display and will also be assigned to the **value** parameter in the [onSelect](#onselect) callback.| +## MenuOutlineOptions18+ + +Defines the outline options for the drop-down list box. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type |Mandatory | Description | +| ------ | ----------------------|-------------------------------------- | ------------------------------------------------------------ | +| width | [Dimension](ts-types.md#dimension10) \| [EdgeOutlineWidths](ts-universal-attributes-outline.md#edgeoutlinewidths)| No| Width of the outline. Percentage values are not supported.
Default value: **0**| +| color | [ResourceColor](ts-types.md#resourcecolor) \| [EdgeColors](ts-universal-attributes-outline.md#edgecolors)|No| Color of the outline.
Default value: **#19ffffff**| + ## Events ### onSelect @@ -428,12 +832,47 @@ Invoked when an option in the drop-down list box is selected. **Parameters** +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ----------------------------- | +| index | number | Yes | Index of the selected option. The index is zero-based.| +| value | string | Yes | Value of the selected option. | + +### onSelect18+ + +onSelect(callback: Optional\ ) + +Invoked when an option in the drop-down list box is selected. Compared to [onSelect](#onselect), this API supports the **undefined** type for the **callback** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| callback | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[OnSelectCallback](#onselectcallback18)> | Yes | Invoked when an option in the drop-down list box is selected.
If **callback** is set to **undefined**, the callback function is not used.| + +## OnSelectCallback18+ + +type OnSelectCallback = (index: number, selectStr: string) => void + +Invoked when an option in the drop-down list box is selected. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------- | -| index | number | Yes | Index of the selected option.| -| value | string | Yes | Value of the selected option. | +| index | number | Yes | Index of the selected option. The index is zero-based.| +| selectStr | string | Yes | Value of the selected option. | + +## Example 1: Creating a Drop-down List Box -## Example 1 +This example demonstrates how to create a drop-down list box by configuring **SelectOptions**. ```ts // xxx.ets @@ -444,6 +883,7 @@ struct SelectExample { @State index: number = 2 @State space: number = 8 @State arrowPosition: ArrowPosition = ArrowPosition.END + build() { Column() { Select([{ value: 'aaa', icon: $r("app.media.selection") }, @@ -458,16 +898,17 @@ struct SelectExample { .optionFont({ size: 16, weight: 400 }) .space(this.space) .arrowPosition(this.arrowPosition) - .menuAlign(MenuAlignType.START, {dx:0, dy:0}) + .menuAlign(MenuAlignType.START, { dx: 0, dy: 0 }) .optionWidth(200) .optionHeight(300) - .onSelect((index:number, text?: string | undefined)=>{ + .onSelect((index: number, text?: string | undefined) => { console.info('Select:' + index) this.index = index; - if(text){ + if (text) { this.text = text; } }) + .avoidance(AvoidanceMode.COVER_TARGET); }.width('100%') } } @@ -475,67 +916,9 @@ struct SelectExample { ![](figures/selectExample.png) -## Example 2 -This example implements a custom drop-down list box, each option of which consists of text + image + blank area + text + drawn triangle. After a menu option is clicked, the text content of the menu option is displayed. - -```ts -import { MenuItemModifier } from '@kit.ArkUI' -class MyMenuItemContentModifier implements ContentModifier { - modifierText: string = "" - constructor(text: string) { - this.modifierText = text; - } - applyContent(): WrappedBuilder<[MenuItemConfiguration]> { - return wrapBuilder(MenuItemBuilder) - } -} -@Builder -function MenuItemBuilder(configuration: MenuItemConfiguration) { - Row() { - Text(configuration.value) - Blank() - Image(configuration.icon).size({ width: 40, height: 40 }) - Blank(30) - Text((configuration.contentModifier as MyMenuItemContentModifier).modifierText) - Path() - .width('100px') - .height('150px') - .commands('M40 0 L80 100 L0 100 Z') - .fillOpacity(0) - .stroke(Color.Black) - .strokeWidth(3) - } - .onClick(() => { - configuration.triggerSelect(configuration.index, configuration.value.valueOf().toString()) - }) -} - -@Entry -@Component -struct SelectExample { - @State text: string = "With modifier" - build() { - Column() { - Row() { - Select([{ value: 'item1', icon: $r("app.media.icon") }, - { value: 'item2', icon: $r("app.media.icon") }]) - .value(this.text) - .onSelect((index:number, text?: string)=>{ - console.info('Select index:' + index) - console.info('Select text:' + text) - }) - .menuItemContentModifier(new MyMenuItemContentModifier("I'm from Modifier")) - - }.alignItems(VerticalAlign.Center).height("50%") - } - } -} -``` -![](figures/selectBuilderExample.png) - -## Example 3 +## Example 2: Setting the Symbol Icon This example implements a drop-down list box, each option of which uses a symbol as its image. ```ts @@ -549,10 +932,15 @@ struct SelectExample { @State index: number = 2 @State space: number = 8 @State arrowPosition: ArrowPosition = ArrowPosition.END - @State symbolModifier1: SymbolGlyphModifier = new SymbolGlyphModifier($r('sys.symbol.ohos_wifi')).fontColor([Color.Green]); - @State symbolModifier2: SymbolGlyphModifier = new SymbolGlyphModifier($r('sys.symbol.ohos_star')).fontColor([Color.Red]); - @State symbolModifier3: SymbolGlyphModifier = new SymbolGlyphModifier($r('sys.symbol.ohos_trash')).fontColor([Color.Gray]); - @State symbolModifier4: SymbolGlyphModifier = new SymbolGlyphModifier($r('sys.symbol.exposure')).fontColor([Color.Gray]); + @State symbolModifier1: SymbolGlyphModifier = + new SymbolGlyphModifier($r('sys.symbol.ohos_wifi')).fontColor([Color.Green]); + @State symbolModifier2: SymbolGlyphModifier = + new SymbolGlyphModifier($r('sys.symbol.ohos_star')).fontColor([Color.Red]); + @State symbolModifier3: SymbolGlyphModifier = + new SymbolGlyphModifier($r('sys.symbol.ohos_trash')).fontColor([Color.Gray]); + @State symbolModifier4: SymbolGlyphModifier = + new SymbolGlyphModifier($r('sys.symbol.exposure')).fontColor([Color.Gray]); + build() { Column() { Select([{ value: 'aaa', symbolIcon: this.symbolModifier1 }, @@ -567,14 +955,15 @@ struct SelectExample { .optionFont({ size: 16, weight: 400 }) .space(this.space) .arrowPosition(this.arrowPosition) - .menuAlign(MenuAlignType.START, {dx:0, dy:0}) - .onSelect((index:number, text?: string | undefined)=>{ + .menuAlign(MenuAlignType.START, { dx: 0, dy: 0 }) + .onSelect((index: number, text?: string | undefined) => { console.info('Select:' + index) this.index = index; - if(text){ + if (text) { this.text = text; } }) + .avoidance(AvoidanceMode.COVER_TARGET); }.width('100%') } } @@ -582,17 +971,19 @@ struct SelectExample { ![](figures/SelectSymbol.png) -## Example 4 +## Example 3: Implementing a Custom Drop-down List Box This example implements a custom drop-down list box, each option of which consists of text + symbol + blank area + text + drawn triangle. After a menu option is clicked, the text content of the menu option is displayed. ```ts -import { MenuItemModifier, SymbolGlyphModifier } from '@kit.ArkUI' +import { SymbolGlyphModifier } from '@kit.ArkUI' class MyMenuItemContentModifier implements ContentModifier { modifierText: string = "" + constructor(text: string) { this.modifierText = text; } + applyContent(): WrappedBuilder<[MenuItemConfiguration]> { return wrapBuilder(MenuItemBuilder) } @@ -628,15 +1019,18 @@ function MenuItemBuilder(configuration: MenuItemConfiguration) { @Component struct SelectExample { @State text: string = "Content Modifier Select" - @State symbolModifier1: SymbolGlyphModifier = new SymbolGlyphModifier($r('sys.symbol.ohos_trash')).fontColor([Color.Gray]); - @State symbolModifier2: SymbolGlyphModifier = new SymbolGlyphModifier($r('sys.symbol.exposure')).fontColor([Color.Gray]); + @State symbolModifier1: SymbolGlyphModifier = + new SymbolGlyphModifier($r('sys.symbol.ohos_trash')).fontColor([Color.Gray]); + @State symbolModifier2: SymbolGlyphModifier = + new SymbolGlyphModifier($r('sys.symbol.exposure')).fontColor([Color.Gray]); + build() { Column() { Row() { Select([{ value: 'item1', icon: $r('app.media.icon'), symbolIcon: this.symbolModifier1 }, { value: 'item1', icon: $r('app.media.icon'), symbolIcon: this.symbolModifier2 }]) .value(this.text) - .onSelect((index:number, text?: string)=>{ + .onSelect((index: number, text?: string) => { console.info('Select index:' + index) console.info('Select text:' + text) }) @@ -649,8 +1043,8 @@ struct SelectExample { ``` ![](figures/SelectBuilderSymbol.png) -## Example 5 -This example implements a drop-down list box with custom dividers. +## Example 4: Using the Divider Style +This example demonstrates how to configure a drop-down list box with a custom divider style by setting **divider** with **DividerOptions**. ```ts // xxx.ets @@ -660,6 +1054,7 @@ struct SelectExample { @State text: string = "TTTTT" @State index: number = -1 @State arrowPosition: ArrowPosition = ArrowPosition.END + build() { Column() { Select([{ value: 'aaa', icon: $r("app.media.icon") }, @@ -673,25 +1068,31 @@ struct SelectExample { .selectedOptionFont({ size: 16, weight: 400 }) .optionFont({ size: 16, weight: 400 }) .arrowPosition(this.arrowPosition) - .menuAlign(MenuAlignType.START, {dx:0, dy:0}) + .menuAlign(MenuAlignType.START, { dx: 0, dy: 0 }) .optionWidth(200) .optionHeight(300) - .divider( { strokeWidth: 5, color: Color.Blue, startMargin: 10, endMargin: 10 }) - .onSelect((index:number, text?: string | undefined)=>{ + .divider({ + strokeWidth: 5, + color: Color.Blue, + startMargin: 10, + endMargin: 10 + }) + .onSelect((index: number, text?: string | undefined) => { console.info('Select:' + index) this.index = index; - if(text){ + if (text) { this.text = text; } }) + .avoidance(AvoidanceMode.COVER_TARGET); }.width('100%') } } ``` ![](figures/SelectCustomDivider.png) -## Example 6 -This example implements a drop-down list box where the dividers are hidden. +## Example 5: Using the No-Divider Style +This example demonstrates how to create a drop-down list box with no divider by setting **divider** to **null**. ```ts // xxx.ets @@ -701,6 +1102,7 @@ struct SelectExample { @State text: string = "TTTTT" @State index: number = -1 @State arrowPosition: ArrowPosition = ArrowPosition.END + build() { Column() { Select([{ value: 'aaa', icon: $r("app.media.icon") }, @@ -714,17 +1116,18 @@ struct SelectExample { .selectedOptionFont({ size: 16, weight: 400 }) .optionFont({ size: 16, weight: 400 }) .arrowPosition(this.arrowPosition) - .menuAlign(MenuAlignType.START, {dx:0, dy:0}) + .menuAlign(MenuAlignType.START, { dx: 0, dy: 0 }) .optionWidth(200) .optionHeight(300) - .divider( null ) - .onSelect((index:number, text?: string | undefined)=>{ + .divider(null) + .onSelect((index: number, text?: string | undefined) => { console.info('Select:' + index) this.index = index; - if(text){ + if (text) { this.text = text; } }) + .avoidance(AvoidanceMode.COVER_TARGET); }.width('100%') } } diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-slider.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-slider.md index dbba2da02129ea2cd4b5cb8476444979ea37ce67..81be33abe545810422627ee00d07fb1fc53dfc55 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-slider.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-slider.md @@ -38,13 +38,13 @@ Slider(options?: SliderOptions) | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | number | No| Current progress.
Default value: same as the value of **min**
Since API version 10, this parameter supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md).| +| value | number | No| Current progress.
Default value: same as the value of **min**
Since API version 10, this parameter supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md).
This parameter supports two-way binding through [!!](../../../quick-start/arkts-new-binding.md).
Value range: [min, max]
Values less than the value of **min** are adjusted to the value of **min**, and values greater than the value of **max** are capped at the value of **max**.| | min | number | No| Minimum value.
Default value: **0**| | max | number | No| Maximum value.
Default value: **100**
**NOTE**
If the value of **min** is greater than or equal to the value of **max**, the **min** value defaults to **0**, and the **max** value defaults to **100**.
If the value is not within the [min, max] range, the value of **min** or **max** is used, whichever is closer.| | step | number | No| Step of the slider.
Default value: **1**
Value range: [0.01, max - min]
**NOTE**
If this parameter is set to a value less than 0 or greater than the value of **max**, the default value is used.| | style | [SliderStyle](#sliderstyle) | No| Style of the slider thumb and track.
Default value: **SliderStyle.OutSet**| | direction8+ | [Axis](ts-appendix-enums.md#axis) | No| Whether the slider moves horizontally or vertically.
Default value: **Axis.Horizontal**| -| reverse8+ | boolean | No| Whether the slider values are reversed. By default, the values increase from left to right for a horizontal slider and from top to bottom for a vertical slider.
Default value: **false**| +| reverse8+ | boolean | No| Whether the slider values are reversed.
Default value: **false**
**true**: Horizontal sliders slide from right to left, while vertical sliders slide from bottom to top. **false**: Horizontal sliders slide from left to right, while vertical sliders slide from top to bottom.| ## SliderStyle @@ -58,7 +58,7 @@ Slider(options?: SliderOptions) ## Attributes -All the [universal attributes](ts-universal-attributes-size.md) except **responseRegion** are supported +All the [universal attributes](ts-component-general-attributes.md) except **responseRegion** are supported. ### blockColor @@ -106,12 +106,10 @@ Since API version 12, **LinearGradient** can be used to create a gradient effect ### selectedColor -selectedColor(value: ResourceColor | LinearGradient) +selectedColor(value: ResourceColor) Sets the color of the portion of the track between the minimum value and the thumb, representing the selected portion. -Since API version 16, **LinearGradient** can be used to create a gradient effect for the selected portion. - **Widget capability**: This API can be used in ArkTS widgets since API version 9. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -120,9 +118,29 @@ Since API version 16, **LinearGradient** can be used to create a gradient effect **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| value | [ResourceColor](ts-types.md#resourcecolor) \| [LinearGradient16+](ts-basic-components-datapanel.md#lineargradient10) | Yes | Color of the portion of the track between the minimum value and the thumb.
**NOTE**
With gradient color settings, if the color stop values are invalid or if the color stops are empty, the gradient effect will not be applied.
Default value: **$r('sys.color.ohos_id_color_emphasize')**| +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------ | ---- | ------------------------------------------------------------ | +| value | [ResourceColor](ts-types.md#resourcecolor) | Yes | Color of the portion of the track between the minimum value and the thumb.
**NOTE**
With gradient color settings, if the color stop values are invalid or if the color stops are empty, the gradient effect will not be applied.
Default value: **$r('sys.color.ohos_id_color_emphasize')**| + +### selectedColor18+ + +selectedColor(selectedColor: ResourceColor | LinearGradient) + +Sets the color of the portion of the track between the minimum value and the thumb, representing the selected portion. Compared to [selectedColor](#selectedcolor), this API supports the **LinearGradient** type. + +Since API version 16, **LinearGradient** can be used to create a gradient effect for the selected portion. + +**Widget capability**: This API can be used in ArkTS widgets since API version 18. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| selectedColor | [ResourceColor](ts-types.md#resourcecolor) \| [LinearGradient18+](ts-basic-components-datapanel.md#lineargradient10) | Yes | Color of the portion of the track between the minimum value and the thumb.
**NOTE**
With gradient color settings, if the color stop values are invalid or if the color stops are empty, the gradient effect will not be applied.
Default value: **$r('sys.color.ohos_id_color_emphasize')**| ### showSteps @@ -140,7 +158,7 @@ Sets whether to display the current step. | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------------------ | -| value | boolean | Yes | Whether to display the current step.
Default value: **false**| +| value | boolean | Yes | Whether to display the current step.
**true**: Display the current step.
**false**: Do not display the current step.
Default value: **false**| ### showTips @@ -231,7 +249,7 @@ When **SliderBlockType.SHAPE** is used, **blockBorderWidth** sets the border wid | Name| Type | Mandatory| Description | | ------ | ---------------------------- | ---- | -------------- | -| value | [Length](ts-types.md#length) | Yes | Border width of the slider in the block direction.| +| value | [Length](ts-types.md#length) | Yes | Border width of the slider in the block direction.
**NOTE**
For the string type, percentage values are not supported.| ### stepColor10+ @@ -263,7 +281,7 @@ Sets the radius of the rounded corner of the track. | Name| Type | Mandatory| Description | | ------ | ---------------------------- | ---- | -------------------------------- | -| value | [Length](ts-types.md#length) | Yes | Radius of the rounded corner of the track.
Default value:
**'2vp'** when **style** is **SliderStyle.OutSet**
**'10vp'** when **style** is **SliderStyle.InSet**| +| value | [Length](ts-types.md#length) | Yes | Radius of the rounded corner of the track.
Default value:
**'2vp'** when **style** is **SliderStyle.OutSet**
**'10vp'** when **style** is **SliderStyle.InSet**
**NOTE**
For the string type, percentage values are not supported. If the value is less than 0, the default value is used.| ### selectedBorderRadius12+ @@ -279,7 +297,7 @@ Set the corner radius of the selected (highlighted) part of the slider. | Name| Type | Mandatory| Description | | ------ | ---------------------------- | ---- | -------------------------------- | -| value | [Dimension](ts-types.md#dimension10)| Yes | Corner radius of the selected part of the slider.
Default value:
- For **SliderStyle.InSet** or **SliderStyle.OutSet**: same as the corner radius of the background
- **SliderStyle.NONE**: **0**| +| value | [Dimension](ts-types.md#dimension10)| Yes | Corner radius of the selected part of the slider.
Default value:
- For **SliderStyle.InSet** or **SliderStyle.OutSet**: same as the corner radius of the background
- **SliderStyle.NONE**: **0**
**NOTE**
Percentage values are not supported. If the value is less than 0, the default value is used.| ### blockSize10+ @@ -301,7 +319,7 @@ When the slider type is set to **SliderBlockType.SHAPE**, this API sets the size | Name| Type | Mandatory| Description | | ------ | -------------------------------------- | ---- | ------------------------------------------------------------ | -| value | [SizeOptions](ts-types.md#sizeoptions) | Yes | Size of the slider in the block direction.
Default value:
For [SliderStyle](#sliderstyle).OutSet: **{width: 16, height: 16}**
- For [SliderStyle](#sliderstyle).InSet: **{width: 12, height: 12}**
- For [SliderStyle](#sliderstyle).NONE: This parameter is not effective.
If the set **blockSize** has different width and height values, the smaller value is taken. If one or both of the width and height values are less than or equal to 0, the default value is used instead.| +| value | [SizeOptions](ts-types.md#sizeoptions) | Yes | Size of the slider in the block direction.
Default value:
For [SliderStyle](#sliderstyle).OutSet: **{width: 18, height: 18}**
- For [SliderStyle](#sliderstyle).InSet: **{width: 12, height: 12}**
- For [SliderStyle](#sliderstyle).NONE: This parameter is not effective.
If the set **blockSize** has different width and height values, the smaller value is taken. If one or both of the width and height values are less than or equal to 0, the default value is used instead.| ### blockStyle10+ @@ -333,7 +351,7 @@ Sets the step size (diameter). If the value is 0, the step size is not displayed | Name| Type | Mandatory| Description | | ------ | ---------------------------- | ---- | ------------------------------------- | -| value | [Length](ts-types.md#length) | Yes | Step size (diameter).
Default value: **'4vp'**
Value range: [0, trackThickness)| +| value | [Length](ts-types.md#length) | Yes | Step size (diameter).
Default value: **'4vp'**
Value range: [0, [trackThickness](#trackthickness8))| ### minLabel(deprecated) @@ -403,7 +421,7 @@ Sets the minimum distance required for the slider to respond. | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------------------ | -| value | number | Yes | Minimum distance required for the slider to respond. The slider will only respond and move when the sliding distance exceeds this threshold.
**NOTE**
The unit is the same as that of **min** and **max**.
If the value is less than 0, greater than the result of (max - min), or invalid, the default value is used.
Default value: **0**| +| value | number | Yes | Minimum distance required for the slider to respond. The slider will only respond and move when the sliding distance exceeds this threshold.
**NOTE**
The unit is the same as that of [min](#slideroptions) and [max](#slideroptions).
If the value is less than 0, greater than the result of (max - min), or invalid, the default value is used.
Default value: **0** | ### contentModifier12+ @@ -442,7 +460,7 @@ Sets the slide range. | ------ | ----------------------------------- | ---- | ---------------- | | value | [SlideRange](#sliderange12) | Yes | Slide range.| -### enableHapticFeedback16+ +### enableHapticFeedback18+ enableHapticFeedback(enabled: boolean) @@ -458,7 +476,7 @@ To enable haptic feedback, you must declare the ohos.permission.VIBRATE permissi ] ``` -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -466,13 +484,13 @@ To enable haptic feedback, you must declare the ohos.permission.VIBRATE permissi | ------ | --------------------------------------------- |-----|-------------------------------------------------------------------------------------| | enabled | boolean | Yes | Whether to enable haptic feedback.
**true** (default): Haptic feedback is enabled.
**false**: Haptic feedback is disabled.| -### digitalCrownSensitivity16+ +### digitalCrownSensitivity18+ digitalCrownSensitivity(sensitivity: Optional\) Sets the sensitivity to the digital crown rotation. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -480,7 +498,7 @@ Sets the sensitivity to the digital crown rotation. | Name | Type | Mandatory| Description | | ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------- | -| sensitivity | [Optional\](ts-appendix-enums.md#crownsensitivity16) | Yes | Sensitivity to the digital crown rotation.
Default value: **CrownSensitivity.MEDIUM**| +| sensitivity | [Optional\](ts-appendix-enums.md#crownsensitivity18) | Yes | Sensitivity to the digital crown rotation.
Default value: **CrownSensitivity.MEDIUM**| ## SliderBlockStyle10+ @@ -547,7 +565,7 @@ Defines the callback type used in **SlideRange**. ## Events -In addition to the [universal events](ts-universal-events-click.md), the following attributes are supported. +In addition to the [universal events](ts-component-general-events.md), the following events are supported. ### onChange @@ -617,7 +635,7 @@ Defines the callback type used in **SliderConfiguration**. | Name| Type | Mandatory| Description | | ------ | ------ | ---------------- | ---------------- | -| value | number | Yes| Current progress.| +| value | number | Yes| Current progress.
Value range: [[min](#slideroptions), [max](#slideroptions)]| | mode | [SliderChangeMode](#sliderchangemode)| Yes| State triggered by the event.| ## Example @@ -914,7 +932,7 @@ This example demonstrates how to customize the **Slider** component using a styl .fontSize(10) Text('Max: ' + config.max) .fontSize(10) - Text ('Step: ' + config.step) + Text('Step: ' + config.step) .fontSize(10) } .width('80%') diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-span.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-span.md index 7f7c5391743b8ac244886cc54bf9f0ca1e844314..4874e4c2e06f1d5ebbc440f012a3d95a521257a4 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-span.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-span.md @@ -57,7 +57,7 @@ Style and color of the text decorative line. letterSpacing(value: number | string) -Letter spacing. A negative value tightens the spacing; a positive value loosens the spacing, and the letters are spread farther apart with the value. +Letter spacing. A negative value tightens the spacing; a positive value loosens the spacing, and the letters are spread farther apart with the value. For the string type, numeric string values with optional units, for example, **"10"** or **"10fp"**, are supported. **Widget capability**: This API can be used in ArkTS widgets since API version 9. @@ -69,7 +69,7 @@ Letter spacing. A negative value tightens the spacing; a positive value loosens | Name| Type | Mandatory| Description | | ------ | ------- | ---- | -------------- | -| value | number \| string | Yes | Letter spacing.| +| value | number \| string | Yes | Letter spacing.
Unit: fp| ### textCase @@ -123,7 +123,7 @@ Sets the font size. | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| value | number \| string\| [Resource](ts-types.md#resource) | Yes | Font size. If **fontSize** is of the number type, the unit fp is used. The default font size is 16 fp. The value cannot be a percentage.| +| value | number \| string \| [Resource](ts-types.md#resource) | Yes | Font size. If **fontSize** is of the number type, the unit fp is used. The default font size is 16 fp. For the string type, numeric string values with optional units, for example, **"10"** or **"10fp"**, are supported. Percentage values are not supported.| ### fontStyle @@ -183,7 +183,7 @@ Sets the font family. lineHeight(value: Length) -Sets the line height for the text. +Sets the line height for the text. When using the string type, numeric string values with optional units, for example, **"10"** or **"10fp"**, are supported. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -301,7 +301,7 @@ Sets the offset of the baseline. This attribute coexists with the **baselineOffs ## Example ### Example 1: Setting the Text Style -This example showcases various text styles by using the **decoration**, **letterSpacing**, and **textCase** attributes. +This example demonstrates how to apply different text styles and configure click events for the **Span** component. ```ts // xxx.ets @@ -309,7 +309,7 @@ This example showcases various text styles by using the **decoration**, **letter @Component struct SpanExample { build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) { Text('Basic Usage').fontSize(9).fontColor(0xCCCCCC) Text() { Span('In Line') @@ -320,12 +320,15 @@ struct SpanExample { Text() { Span('This is the Span component').fontSize(12).textCase(TextCase.Normal) .decoration({ type: TextDecorationType.None, color: Color.Red }) - } + .fontFamily('HarmonyOS Sans') + }.margin({ top: 12 }) // Add a line under the text. - Text('Text Decoration').fontSize(9).fontColor(0xCCCCCC) + Text('Text Decoration').fontSize(9).fontColor(0xCCCCCC).margin({ top: 12 }) Text() { - Span('I am Underline-WAVY-span').decoration({ type: TextDecorationType.Underline, color: Color.Red, style: TextDecorationStyle.WAVY }).fontSize(12) + Span('I am Underline-WAVY-span') + .decoration({ type: TextDecorationType.Underline, color: Color.Red, style: TextDecorationStyle.WAVY }) + .fontSize(12) } Text() { @@ -335,11 +338,13 @@ struct SpanExample { } Text() { - Span('I am Overline-DASHED-span').decoration({ type: TextDecorationType.Overline, color: Color.Red, style: TextDecorationStyle.DASHED }).fontSize(12) + Span('I am Overline-DASHED-span') + .decoration({ type: TextDecorationType.Overline, color: Color.Red, style: TextDecorationStyle.DASHED }) + .fontSize(12) } // Set the letter spacing. - Text('LetterSpacing').fontSize(9).fontColor(0xCCCCCC) + Text('LetterSpacing').fontSize(9).fontColor(0xCCCCCC).margin({ top: 12 }) Text() { Span('span letter spacing') .letterSpacing(0) @@ -358,9 +363,8 @@ struct SpanExample { .fontSize(12) } - // Set the text case. - Text('Text Case').fontSize(9).fontColor(0xCCCCCC) + Text('Text Case').fontSize(9).fontColor(0xCCCCCC).margin({ top: 12 }) Text() { Span('I am Lower-span').fontSize(12) .textCase(TextCase.LowerCase) @@ -372,7 +376,63 @@ struct SpanExample { .textCase(TextCase.UpperCase) .decoration({ type: TextDecorationType.None }) } - }.width('100%').height(250).padding({ left: 35, right: 35, top: 35 }) + + // Set the text font style. + Text('FontStyle').fontSize(9).fontColor(0xCCCCCC).margin({ top: 12 }) + Text() { + Span('I am FontStyle-Normal').fontSize(12) + .fontStyle(FontStyle.Normal) + } + + Text() { + Span('I am FontStyle-Italic').fontSize(12) + .fontStyle(FontStyle.Italic) + } + + // Set the text font weight. + Text('FontWeight').fontSize(9).fontColor(0xCCCCCC).margin({ top: 12 }) + Text() { + Span('I am FontWeight-Lighter').fontSize(12) + .fontWeight(FontWeight.Lighter) + } + + Text() { + Span('I am FontWeight-Bold').fontSize(12) + .fontWeight(FontWeight.Bold) + } + + // Set the text line height. + Text('LineHeight').fontSize(9).fontColor(0xCCCCCC).margin({ top: 12 }) + Text() { + Span('I am lineHeight default\n').fontSize(12) + .fontWeight(FontWeight.Lighter) + Span('I am lineHeight 30').fontSize(12) + .lineHeight(30) + } + .backgroundColor(Color.Gray) + + // Set the text style. + Text('Font').fontSize(9).fontColor(0xCCCCCC).margin({ top: 12 }) + Text() { + Span('span font 12 Bolder Italic') + .font({ + size: 12, + weight: FontWeight.Bolder, + style: FontStyle.Italic, + family: "HarmonyOS Sans" + }) + } + + // Set the click event. + Text('span click event').fontSize(9).fontColor(0xCCCCCC).margin({ top: 12 }) + Text() { + Span('Span default ').fontSize(12) + Span('Span click') + .onClick((event) => { + console.log("span onClick") + }) + } + }.width('100%').padding({ left: 35, right: 35, top: 35 }) } } ``` @@ -388,18 +448,44 @@ This example demonstrates the effect of setting a shadow for text using the **te @Entry @Component struct SpanExample { - @State textShadows : ShadowOptions | Array = [{ radius: 10, color: Color.Red, offsetX: 10, offsetY: 0 },{ radius: 10, color: Color.Black, offsetX: 20, offsetY: 0 }, - { radius: 10, color: Color.Brown, offsetX: 30, offsetY: 0 },{ radius: 10, color: Color.Green, offsetX: 40, offsetY: 0 }, - { radius: 10, color: Color.Yellow, offsetX: 100, offsetY: 0 }] + @State textShadows: ShadowOptions | Array = [{ + radius: 10, + color: Color.Red, + offsetX: 10, + offsetY: 0 + }, { + radius: 10, + color: Color.Orange, + offsetX: 20, + offsetY: 0 + }, + { + radius: 10, + color: Color.Yellow, + offsetX: 30, + offsetY: 0 + }, { + radius: 10, + color: Color.Green, + offsetX: 40, + offsetY: 0 + }, + { + radius: 10, + color: Color.Blue, + offsetX: 100, + offsetY: 0 + }] build() { Column({ space: 8 }) { Text() { - Span('123456789').fontSize(50).textShadow(this.textShadows) + Span('123456789').fontSize(50).textShadow(this.textShadows).fontColor(Color.Pink) } + Text() { Span('123456789') // span can inherit text shadow & font size from outer text - }.fontSize(50).textShadow(this.textShadows) + }.fontSize(50).textShadow(this.textShadows).fontColor(Color.Pink) } } } @@ -420,10 +506,10 @@ struct SpanExample { Text() { Span(' Hello World ! ') .fontSize('20fp') - .textBackgroundStyle({color: "#7F007DFF", radius: "5vp"}) + .textBackgroundStyle({ color: "#7F007DFF", radius: "5vp" }) .fontColor(Color.White) } - }.width('100%').margin({bottom: '5vp'}).alignItems(HorizontalAlign.Center) + }.width('100%').margin({ bottom: '5vp' }).alignItems(HorizontalAlign.Center) } } ``` @@ -434,6 +520,7 @@ struct SpanExample { This example demonstrates the effect of setting different baseline offsets for text using the **baselineOffset** attribute. ```ts +// xxx.ets import { LengthUnit, LengthMetrics } from '@kit.ArkUI'; @Entry @@ -442,16 +529,18 @@ struct SpanExample { build() { Row() { Column() { - Text(){ - Span('word1') - .baselineOffset(new LengthMetrics(20,LengthUnit.VP)) - Span('word2') - .baselineOffset(new LengthMetrics(0,LengthUnit.VP)) - ImageSpan($r("app.media.icon")) - .width('45px') - .baselineOffset(new LengthMetrics(-20,LengthUnit.VP)) + Text() { + Span('SpanOne') + .fontSize(10) + .baselineOffset(new LengthMetrics(20, LengthUnit.VP)) + Span('SpanTwo') + .fontSize(10) + .baselineOffset(new LengthMetrics(0, LengthUnit.VP)) + ImageSpan($r("app.media.sky"))// You are advised to use a custom local image. + .width('80px') + .baselineOffset(new LengthMetrics(-20, LengthUnit.VP)) } - .backgroundColor(Color.Gray) + .backgroundColor('#7F007DFF') } .width('100%') } diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-stepper.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-stepper.md index 65246d544e45e33414b00a99ec0d22a895cad5e5..ca90a5789ece33b0fe78ebcc42e38407f2ee8acf 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-stepper.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-stepper.md @@ -68,8 +68,8 @@ Invoked when the **prevLabel** of the current **StepperItem** is clicked to swit | Name | Type | Mandatory| Description | | --------- | ------ | ---- | ------------------------------------------ | -| prevIndex | number | Yes | Index of the step page before the switching. | -| index | number | Yes | Index of the step page after the switching, that is, index of the previous or next page.| +| prevIndex | number | Yes | Index of the step page before the switching.
Value range: [0, +∞)| +| index | number | Yes | Index of the step page after the switching, that is, index of the previous or next page.
Value range: [0, +∞)| ### onNext @@ -108,6 +108,8 @@ Invoked when the **prevLabel** of the current **StepperItem** is clicked to swit ## Example +This example demonstrates how to use the **Stepper** component. + ```ts // xxx.ets @Styles function itemStyle () { diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-stepperitem.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-stepperitem.md index ce5555f1675361a991ea8310c5f578914caa58d8..392ba796b41711af8f1f9193aea541e40fa0d9b2 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-stepperitem.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-stepperitem.md @@ -37,7 +37,7 @@ Sets the text label of the button on the left, which is not displayed on the fir | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | string | Yes| Text label of the button on the left.| +| value | string | Yes| Text label of the button on the left. When the string is too long, it is scaled down, wrapped in two lines, and then clipped.| ### nextLabel @@ -53,7 +53,7 @@ Sets the text label of the button on the right. The default value is **Start** f | Name| Type | Mandatory| Description | | ------ | ------------------------------- | ---- | ------------------------------------------------------------ | -| value | string | Yes | Text label of the button on the right. | +| value | string | Yes | Text label of the button on the right. When the string is too long, it is scaled down, wrapped in two lines, and then clipped. | ### status diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-symbolGlyph.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-symbolGlyph.md index d6d931cdc06da9a4c1ab8cc752c6fdddc04d78bd..bebad0e5bf7c060dd11cad296fbe2389129366cd 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-symbolGlyph.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-symbolGlyph.md @@ -32,7 +32,7 @@ SymbolGlyph(value?: Resource) ## Attributes -The [universal attributes](ts-universal-attributes-size.md) are supported. With regard to text attributes, only the following attributes are supported. +The [universal attributes](ts-component-general-attributes.md) are supported. With regard to text attributes, only the following attributes are supported. ### fontColor @@ -56,7 +56,7 @@ Sets the color of the **SymbolGlyph** component. fontSize(value: number | string | Resource) -Sets the size of the **SymbolGlyph** component. +Sets the size of the **SymbolGlyph** component. When using the string type, numeric string values with optional units, for example, **"10"** or **"10fp"**, are supported. The display size of the symbol glyph is controlled by the **fontSize** setting. Once **width** or **height** is specified, other universal attributes will only affect the size of the component's placeholder, not the symbol glyph itself. @@ -70,7 +70,7 @@ The display size of the symbol glyph is controlled by the **fontSize** setting. | Name| Type| Mandatory| Description | | ------ | ---- | ---- | ----- | -| value | number \| string \| [Resource](ts-types.md#resource) | Yes | Size of the **SymbolGlyph** component.
Default value: system default value| +| value | number \| string \| [Resource](ts-types.md#resource) | Yes | Size of the **SymbolGlyph** component.
Default value: **16fp**
Unit: fp
Percentage strings are not supported.| ### fontWeight @@ -174,16 +174,38 @@ Sets the symbol effect and effect trigger for the **SymbolGlyph** component. > > When configuring the symbol effect, use the **effectStrategy** attribute or a single **symbolEffect** attribute. Mixing multiple effect attributes is not allowed. -## SymbolEffect12+ +### minFontScale18+ -Defines the **SymbolEffect** class. +minFontScale(scale: Optional\) -**Widget capability**: This API can be used in ArkTS widgets since API version 12. +Sets the minimum font scale factor for the **SymbolGlyph** component. -**Atomic service API**: This API can be used in atomic services since API version 12. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ----- | +| scale |[Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Minimum font scale factor for the **SymbolGlyph** component.
Value range: [0, 1]
The value **0** results in the minimum scaling.
**NOTE**
A value less than 0 is handled as 0. A value greater than 1 is handled as 1. Abnormal values are ineffective by default. | + +### maxFontScale18+ + +maxFontScale(scale: Optional\) + +Sets the maximum font scale factor for the **SymbolGlyph** component. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ----- | +| scale |[Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Maximum font scale factor for the **SymbolGlyph** component.
Value range: [1, +∞)
**NOTE**
A value less than 1 is handled as **1**. Abnormal values are ineffective by default.| + ## ScaleSymbolEffect12+ Inherits from **SymbolEffect**. @@ -194,7 +216,7 @@ Inherits from **SymbolEffect**. **System capability**: SystemCapability.ArkUI.ArkUI.Full -### Attributes +### Properties | Name| Type| Mandatory| Description | | ---- | ---- | ---- | ---- | @@ -230,7 +252,7 @@ Inherits from **SymbolEffect**. **System capability**: SystemCapability.ArkUI.ArkUI.Full -### Attributes +### Properties | Name| Type| Mandatory| Description | | ---- | ---- | ---- | ---- | @@ -264,7 +286,7 @@ Inherits from **SymbolEffect**. **System capability**: SystemCapability.ArkUI.ArkUI.Full -### Attributes +### Properties | Name| Type| Mandatory| Description | | ---- | ---- | ---- | ---- | @@ -298,7 +320,7 @@ Inherits from **SymbolEffect**. **System capability**: SystemCapability.ArkUI.ArkUI.Full -### Attributes +### Properties | Name| Type| Mandatory| Description | | ---- | ---- | ---- | ---- | @@ -332,7 +354,7 @@ Inherits from **SymbolEffect**. **System capability**: SystemCapability.ArkUI.ArkUI.Full -### Attributes +### Properties | Name| Type| Mandatory| Description | | ---- | ---- | ---- | ---- | @@ -368,7 +390,7 @@ Inherits from **SymbolEffect**. **System capability**: SystemCapability.ArkUI.ArkUI.Full -### Attributes +### Properties | Name| Type| Mandatory| Description | | ---- | ---- | ---- | ---- | @@ -392,9 +414,9 @@ A constructor used to create a **ReplaceSymbolEffect** instance, which comes wit | ---- | ---- | ---- | ---- | | scope | [EffectScope](#effectscope12) | No | Effect scope.
Default value: **EffectScope.LAYER**| -## PulseSymbolEffect12+ +## SymbolEffectStrategy11+ -A constructor used to create a **PulseSymbolEffect** instance, which comes with a pulse animation effect. +Enumerates symbol effect types. Once applied, the symbol effect becomes active instantly, eliminating the need for triggering. **Widget capability**: This API can be used in ArkTS widgets since API version 12. @@ -402,7 +424,15 @@ A constructor used to create a **PulseSymbolEffect** instance, which comes with **System capability**: SystemCapability.ArkUI.ArkUI.Full -## EffectDirection12+ +| Name | Value| Description | +| ------ | --- | ----------------------------- | +| NONE | 0 | No effect (default value).| +| SCALE | 1 | Scale effect as a whole. | +| HIERARCHICAL | 2 | Hierarchical effect. | + +## SymbolRenderingStrategy11+ + +Enumerates the rendering modes. **Widget capability**: This API can be used in ArkTS widgets since API version 12. @@ -410,12 +440,15 @@ A constructor used to create a **PulseSymbolEffect** instance, which comes with **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name| Value | Description | -| ---- | ---- | ---------------- | -| DOWN | 0 | The symbol scales down and then returns to its original size.| -| UP | 1 | The symbol scales up and then returns to its original size.| +| Name | Value| Description | +| ------ | --- | ----------------------------- | +| SINGLE | 0 | Single-color mode (default value).
The default color is black.
You can set one or multiple colors, but only the first color will be applied.| +| MULTIPLE_COLOR | 1 | Multi-color mode.
A maximum of three colors can be set. If only one color is set, it updates the color of the first layer, leaving other colors at their default values.
The sequence of color settings matches the layering order of the symbol; any colors beyond the number of symbol layers will not take effect.
Only color values are accepted. Opacity settings do not take effect.| +| MULTIPLE_OPACITY | 2 | Layered mode.
The default color is black. You can set one or multiple colors, but only the first color will be applied.
Opacity is predefined for the layers: 100% for the first layer, 50% for the second layer, and 20% for the third layer. | -## EffectScope12+ +## SymbolEffect12+ + +Defines the **SymbolEffect** class. **Widget capability**: This API can be used in ArkTS widgets since API version 12. @@ -423,12 +456,9 @@ A constructor used to create a **PulseSymbolEffect** instance, which comes with **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Value | Description | -| ----- | ---- | ---------- | -| LAYER | 0 | Layered mode.| -| WHOLE | 1 | Whole mode.| +## PulseSymbolEffect12+ -## EffectFillStyle12+ +A constructor used to create a **PulseSymbolEffect** instance, which comes with a pulse animation effect. **Widget capability**: This API can be used in ArkTS widgets since API version 12. @@ -436,14 +466,20 @@ A constructor used to create a **PulseSymbolEffect** instance, which comes with **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Value | Description | -| ---------- | ---- | ---------- | -| CUMULATIVE | 0 | Cumulative style.| -| ITERATIVE | 1 | Iterative style.| +## EffectDirection12+ -## SymbolEffectStrategy11+ +**Widget capability**: This API can be used in ArkTS widgets since API version 12. -Enumerates symbol effect types. Once applied, the symbol effect becomes active instantly, eliminating the need for triggering. +**Atomic service API**: This API can be used in atomic services since API version 12. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name| Value | Description | +| ---- | ---- | ---------------- | +| DOWN | 0 | The symbol scales down and then returns to its original size.| +| UP | 1 | The symbol scales up and then returns to its original size.| + +## EffectScope12+ **Widget capability**: This API can be used in ArkTS widgets since API version 12. @@ -451,15 +487,12 @@ Enumerates symbol effect types. Once applied, the symbol effect becomes active i **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Description | -| ------ | ----------------------------- | -| NONE | No effect (default value).| -| SCALE | Scale effect as a whole. | -| HIERARCHICAL | Hierarchical effect. | - -## SymbolRenderingStrategy11+ +| Name | Value | Description | +| ----- | ---- | ---------- | +| LAYER | 0 | Layered mode.| +| WHOLE | 1 | Whole mode.| -Enumerates the rendering modes. +## EffectFillStyle12+ **Widget capability**: This API can be used in ArkTS widgets since API version 12. @@ -467,19 +500,20 @@ Enumerates the rendering modes. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Description | -| ------ | ----------------------------- | -| SINGLE | Single-color mode (default).
The default color is black, and one color can be set.
If multiple colors are set, only the first color takes effect.| -| MULTIPLE_COLOR | Multi-color mode.
A maximum of three colors can be set. If only one color is set, it updates the color of the first layer, leaving other colors at their default values.
The sequence of color settings matches the layering order of the symbol; any colors beyond the number of symbol layers will not take effect.
Only color values are accepted. Opacity settings do not take effect.| -| MULTIPLE_OPACITY | Layered mode.
The default color is black, and one color can be set. If multiple colors are set, only the first color takes effect.
Opacity is related to the layer, with the first layer at 100%, the second layer at 50%, and the third layer at 20%. | +| Name | Value | Description | +| ---------- | ---- | ---------- | +| CUMULATIVE | 0 | Cumulative style.| +| ITERATIVE | 1 | Iterative style.| ## Events -The [universal events](ts-universal-events-click.md) are supported. +The [universal events](ts-component-general-events.md) are supported. ## Example -### Example 1 +### Example 1: Setting Rendering and Effect Strategies + +This example demonstrates different rendering and effect strategies using **renderingStrategy** and **effectStrategy**. ```ts // xxx.ets @@ -529,7 +563,7 @@ struct Index { } Column() { - Text("Layered mode") + Text ("Layered mode") SymbolGlyph($r('sys.symbol.ohos_folder_badge_plus')) .fontSize(96) .renderingStrategy(SymbolRenderingStrategy.MULTIPLE_OPACITY) @@ -565,9 +599,9 @@ struct Index { ``` ![symbol](figures/symbolGlyph.gif) -### Example 2 +### Example 2: Setting Effects -This example demonstrates the use of the s**ymbolEffec**t attribute in the **SymbolGlyph** component to achieve variable color and replace animation effects. +This example demonstrates the effects of variable color animation and replacement animation using **symbolEffect**. ```ts // xxx.ets @@ -582,29 +616,29 @@ struct Index { Column() { Row() { Column() { - Text("Variable Color Animation") + Text("Variable color animation") SymbolGlyph($r('sys.symbol.ohos_wifi')) .fontSize(96) .symbolEffect(new HierarchicalSymbolEffect(EffectFillStyle.ITERATIVE), this.isActive) Button(this.isActive ? 'Off' : 'Play').onClick(() => { this.isActive = !this.isActive; }) - }.margin({right:20}) + }.margin({ right: 20 }) Column() { - Text("Replace Animation") + Text("Replacement animation") SymbolGlyph(this.replaceFlag ? $r('sys.symbol.checkmark_circle') : $r('sys.symbol.repeat_1')) .fontSize(96) .symbolEffect(new ReplaceSymbolEffect(EffectScope.WHOLE), this.triggerValueReplace) - Button('trigger').onClick(() => { + Button('Trigger').onClick(() => { this.replaceFlag = !this.replaceFlag; this.triggerValueReplace = this.triggerValueReplace + 1; }) } } }.margin({ - left:30, - top:50 + left: 30, + top: 50 }) } } diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-text.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-text.md index 2f1e3f7fe5ddc505ca05690d32bee23e3ea842c0..88be1f4120fa4ae7541b8ec477af246721fa453e 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-text.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-text.md @@ -30,7 +30,7 @@ Text(content?: string | Resource , value?: TextOptions) ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### textAlign @@ -54,7 +54,7 @@ When **textAlign** is set to **TextAlign.JUSTIFY**, you must set the [wordBreak] | Name| Type | Mandatory| Description | | ------ | ------------------------------------------- | ---- | ---------------------------------------------------------- | -| value | [TextAlign](ts-appendix-enums.md#textalign) | Yes | Horizontal alignment of the text.
Default value: **TextAlign.Start**| +| value | [TextAlign](ts-appendix-enums.md#textalign) | Yes | Horizontal alignment of the text.
Default value: **TextAlign.Start** on non-wearable devices and **TextAlign.Center** on wearable devices| ### textOverflow @@ -80,7 +80,7 @@ Since API version 12, **TextOverflow.MARQUEE** is available for the **ImageSpan* | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| options | [TextOverflowOptions](#textoverflowoptions14) | Yes | Display mode when the text is too long.| +| options | [TextOverflowOptions](#textoverflowoptions18) | Yes | Display mode when the text is too long.| ### maxLines @@ -104,7 +104,7 @@ Sets the maximum number of lines in the text. By default, text is automatically lineHeight(value: number | string | Resource) -Sets the text line height. If the value is less than or equal to **0**, the line height is not limited and the font size is adaptive. If the value is of the number type, the unit fp is used. +Sets the text line height. If the value is less than or equal to **0**, the line height is not limited and the font size is adaptive. If the value is of the number type, the unit fp is used. For the string type, numeric string values with optional units, for example, **"10"** or **"10fp"**, are supported. **Widget capability**: This API can be used in ArkTS widgets since API version 9. @@ -160,7 +160,7 @@ Positive values shift the content upwards, while negative values shift it downwa letterSpacing(value: number | string) -Sets the letter spacing for a text style. If the value specified is a percentage or 0, the default value is used. +Sets the letter spacing for a text style. If the value specified is a percentage or 0, the default value is used. For the string type, numeric string values with optional units, for example, **"10"** or **"10fp"**, are supported. If the value specified is a negative value, the text is compressed. A negative value too small may result in the text being compressed to 0 and no content being displayed. @@ -174,21 +174,21 @@ If the value specified is a negative value, the text is compressed. A negative v | Name| Type | Mandatory| Description | | ------ | -------------------------- | ---- | -------------- | -| value | number \| string | Yes | Letter spacing.| +| value | number \| string | Yes | Letter spacing.
Unit: fp| ### minFontSize minFontSize(value: number | string | Resource) -Sets the minimum font size. +Sets the minimum font size. For the string type, numeric string values with optional units, for example, **"10"** or **"10fp"**, are supported. For the setting to take effect, this attribute must be used together with [maxFontSize](#maxfontsize) and [maxLines](#maxlines), or layout constraint settings. When the adaptive font size is used, the **fontSize** settings do not take effect. -If the value of **minFontSize** is less than or equal to 0, the adaptive font size does not take effect. +If the value of **minFontSize** is less than or equal to 0, font size adaptation does not take effect. In this case, the actual font size is determined by the value of [fontSize](#fontsize). If [fontSize](#fontsize) is not specified, the default value is used. -Since API version 16, this attribute takes effect on child components and styled strings, and the adaptive font size is applied to parts where the font size is not set. +Since API version 18, this attribute takes effect on child components and styled strings, and the adaptive font size is applied to parts where the font size is not set. **Widget capability**: This API can be used in ArkTS widgets since API version 9. @@ -200,19 +200,21 @@ Since API version 16, this attribute takes effect on child components and styled | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------ | -| value | number \| string \| [Resource](ts-types.md#resource) | Yes | Minimum font size.| +| value | number \| string \| [Resource](ts-types.md#resource) | Yes | Minimum font size.
Unit: fp| ### maxFontSize maxFontSize(value: number | string | Resource) -Sets the maximum font size. +Sets the maximum font size. For the string type, numeric string values with optional units, for example, **"10"** or **"10fp"**, are supported. For the setting to take effect, this attribute must be used together with [minFontSize](#minfontsize) and [maxLines](#maxlines), or layout constraint settings. When the adaptive font size is used, the **fontSize** settings do not take effect. -Since API version 16, this attribute takes effect on child components and styled strings, and the adaptive font size is applied to parts where the font size is not set. +If the value of **maxFontSize** is less than or equal to 0, font size adaptation does not take effect. In this case, the actual font size is determined by the value of [fontSize](#fontsize). If [fontSize](#fontsize) is not specified, the default value is used. + +Since API version 18, this attribute takes effect on child components and styled strings, and the adaptive font size is applied to parts where the font size is not set. **Widget capability**: This API can be used in ArkTS widgets since API version 9. @@ -224,7 +226,7 @@ Since API version 16, this attribute takes effect on child components and styled | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------ | -| value | number \| string \| [Resource](ts-types.md#resource) | Yes | Maximum font size.| +| value | number \| string \| [Resource](ts-types.md#resource) | Yes | Maximum font size.
Unit: fp| ### textCase @@ -248,7 +250,7 @@ Sets the text case. fontColor(value: ResourceColor) -Sets the font color. +Sets the font color. The default value on wearable devices is **'#dbffffff'**. **Widget capability**: This API can be used in ArkTS widgets since API version 9. @@ -266,7 +268,7 @@ Sets the font color. fontSize(value: number | string | Resource) -Sets the text size. +Sets the text size. The default value on wearable devices is **5fp**. **Widget capability**: This API can be used in ArkTS widgets since API version 9. @@ -314,7 +316,7 @@ Sets the font weight. If the value is too large, the text may be clipped dependi | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| value | number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string | Yes | Font weight. For the number type, the value range is [100, 900], at an interval of 100. The default value is **400**. A larger value indicates a heavier font weight. For the string type, only strings that represent a number, for example, **"400"**, and the following enumerated values of **FontWeight** are supported: **"bold"**, **"bolder"**, **"lighter"**, **"regular"**, and **"medium"**.
Default value: **FontWeight.Normal**| +| value | number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string | Yes | Font weight. For the number type, the value range is [100, 900], at an interval of 100. The default value is **400**. A larger value indicates a heavier font weight. For the string type, only strings that represent a number, for example, **"400"**, and the following enumerated values of **FontWeight** are supported: **"bold"**, **"bolder"**, **"lighter"**, **"regular"**, and **"medium"**.
Default value: **FontWeight.Normal** on non-wearable devices and **FontWeight.Regular** on wearable devices| ### fontFamily @@ -416,11 +418,11 @@ Since API version 11, this API supports input parameters in an array to implemen heightAdaptivePolicy(value: TextHeightAdaptivePolicy) -Sets how the adaptive height is determined for the text. +Sets how the font size of text adapts to layout constraints. When this attribute is set to **TextHeightAdaptivePolicy.MAX_LINES_FIRST**, the [maxLines](#maxlines) attribute takes precedence for adjusting the text height. If the **maxLines** setting results in a layout beyond the layout constraints, the text will shrink to a font size between [minFontSize](#minfontsize) and [maxFontSize](#maxfontsize) to allow for more content to be shown. -If this attribute is set to **TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST**, the **minFontSize** attribute takes precedence for adjusting the text height. If the text can fit in one line with the **minFontSize** setting, the text will enlarge to the largest possible font size between **minFontSize** and **maxFontSize**. +If this attribute is set to **TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST**, the **minFontSize** attribute takes precedence for adjusting the text height. If the text fits on one line at **minFontSize**, the system attempts to increase the font size within the range of **minFontSize** and **maxFontSize** to display the text as large as possible on one line. If the text cannot fit into a single line even at **minFontSize**, it sticks with **minFontSize**. If this attribute is set to **TextHeightAdaptivePolicy.LAYOUT_CONSTRAINT_FIRST**, the layout constraints take precedence for adjusting the text height. If the resultant layout is beyond the layout constraints, the text will shrink to a font size between **minFontSize** and **maxFontSize** to respect the layout constraints. If the text still extends beyond the layout constraints after shrinking to **minFontSize**, the lines that exceed the constraints are deleted. @@ -532,7 +534,7 @@ Touching and right-clicking an entity with the mouse will pop up the correspondi This API does not work when **overflow** is set to **TextOverflow.MARQUEE**. -When **copyOption** is set to **CopyOptions.None**, the menu displayed after an entity is clicked does not provide the text selection or copy functionality. When **copyOption** is not set to **CopyOptions.None**, and **textSelectable** is set to **TextSelectableMode.UNSELECTABLE**, the entity still has the copy functionality but does not have the text selection feature. +When **copyOption** is set to **CopyOptions.None**, the menu displayed after an entity is clicked does not provide the text selection, copy, translation, or sharing functionality. When **copyOption** is not set to **CopyOptions.None**, and **textSelectable** is set to **TextSelectableMode.UNSELECTABLE**, the entity still has the copy functionality but does not have the text selection feature. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -803,7 +805,7 @@ It is only effective for the **Text** component, not for its child components. | Name| Type | Mandatory| Description | | ------ | --------------------------------------------- | ---- | --------------------------------------------- | -| weight | number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string | Yes | Font weight.| +| weight | number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string | Yes | Font weight. For the number type, the value ranges from 100 to 900, at an interval of 100. A larger value indicates a heavier font weight. The default value is **400**. For the string type, only strings that represent a number, for example, **"400"**, and the following enumerated values of **FontWeight** are supported: **"bold"**, **"bolder"**, **"lighter"**, **"regular"**, and **"medium"**.| | options | [FontSettingOptions](ts-text-common.md#fontsettingoptions12) | No | Font settings.| ### enableHapticFeedback13+ @@ -865,39 +867,71 @@ Sets the background color of the selected text. If the opacity is not set, a 20% | ------ | ------------------------------------------ | ---- | ------------------------------------------ | | color | [ResourceColor](ts-types.md#resourcecolor) | Yes | Background color of the selected text.
By default, a 20% opacity is applied.
Default value: **'#007DFF'**| +### marqueeOptions18+ + +marqueeOptions(options: Optional\) + +Sets the marquee effect for text. + +The **marqueeOptions** settings take effect only when **textOverflow** is set to **TextOverflow.MARQUEE**. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------ | ---- | ------------------------------------------ | +| options | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[TextMarqueeOptions](#textmarqueeoptions18)> | Yes| Marquee settings, including the switch, step length, number of loops, and direction.| + ## TextSpanType11+ Provides the [span](ts-basic-components-span.md) type information. -**Atomic service API**: This API can be used in atomic services since API version 12. - **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name| Description| -| -------- | -------- | -| TEXT | Text span.| -| IMAGE | Image span.| -| MIXED | Mixed span, which contains both text and imagery.| +| Name| Value| Description| +| -------- | ---- | -------- | +| TEXT | 0 | Text span.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| IMAGE | 1 | Image span.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| MIXED | 2 | Mixed span, which contains both text and imagery.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| DEFAULT15+ | 3 | When this type is registered but **TEXT**, **IMAGE**, or **MIXED** types are not registered, this type will be triggered and displayed for those registered types.
**Atomic service API**: This API can be used in atomic services since API version 15.| -## TextResponseType11+ +> **NOTE** +> +> The order for menu type matching is as follows. When the user interacts with text, the system follows this order to decides which type of menu to display. +> 1. Check whether a menu is registered for **TextSpanType.TEXT** and **TextResponseType.LONG_PRESS**. +> 2. Check whether a menu is registered for **TextSpanType.TEXT** and **TextResponseType.DEFAULT**. +> 3. Check whether a menu is registered for **TextSpanType.DEFAULT** and **TextResponseType.LONG_PRESS**. +> 4. Check whether a menu is registered for **TextSpanType.DEFAULT** and **TextResponseType.DEFAULT**. -**Atomic service API**: This API can be used in atomic services since API version 12. +## TextResponseType11+ **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Description | -| ---------- | ------------- | -| RIGHT_CLICK | The menu is displayed when the component is right-clicked.| -| LONG_PRESS | The menu is displayed when the component is long-pressed. | -| SELECT | The menu is displayed when the component is selected.| +| Name | Value| Description | +| ---------- | --- | ------------- | +| RIGHT_CLICK | 0 | The menu is displayed when the component is right-clicked.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| LONG_PRESS | 1 | The menu is displayed when the component is long-pressed.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| SELECT | 2 | The menu is displayed when the component is selected.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| DEFAULT15+ | 3 | When this type is registered but **RIGHT_CLICK**, **LONG_PRESS**, or **SELECT** types are not registered, this type will be triggered and displayed for right-click, long press, and mouse selection actions.
**Atomic service API**: This API can be used in atomic services since API version 15.| + +> **NOTE** +> +> The order for menu type matching is as follows. When the user interacts with text, the system follows this order to decides which type of menu to display. +> 1. Check whether a menu is registered for **TextSpanType.TEXT** and **TextResponseType.LONG_PRESS**. +> 2. Check whether a menu is registered for **TextSpanType.TEXT** and **TextResponseType.DEFAULT**. +> 3. Check whether a menu is registered for **TextSpanType.DEFAULT** and **TextResponseType.LONG_PRESS**. +> 4. Check whether a menu is registered for **TextSpanType.DEFAULT** and **TextResponseType.DEFAULT**. -## TextOverflowOptions14+ +## TextOverflowOptions18+ Describes the display mode when the text is too long. -**Widget capability**: This API can be used in ArkTS widgets since API version 14. +**Widget capability**: This API can be used in ArkTS widgets since API version 18. -**Atomic service API**: This API can be used in atomic services since API version 14. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -905,11 +939,11 @@ Describes the display mode when the text is too long. | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| overflow | [TextOverflow](ts-appendix-enums.md#textoverflow) | Yes | Display mode when the text is too long.
Default value: **TextOverflow.Clip**| +| overflow7+ | [TextOverflow](ts-appendix-enums.md#textoverflow) | Yes | Display mode when the text is too long.
Default value: **TextOverflow.Clip**
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11.| ## Events -In addition to the [universal events](ts-universal-events-click.md), the following events are supported. +In addition to the [universal events](ts-component-general-events.md), the following events are supported. ### onCopy11+ @@ -944,13 +978,13 @@ Called when the text selection position changes. | selectionStart | number | Yes | Start position of the selected text.| | selectionEnd | number | Yes | End position of the selected text.| -### onMarqueeStateChange16+ +### onMarqueeStateChange18+ onMarqueeStateChange(callback: Callback\) Called when the marquee animation reaches the specified state. -**Widget capability**: This API can be used in ArkTS widgets since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -958,7 +992,7 @@ Called when the marquee animation reaches the specified state. | Name | Type | Mandatory | Description | |--------|---------------------------------------------------|-----|--------------------------| -| state | [Callback\](#marqueestate16) | Yes | Callback that receives a **MarqueeState** enum value, which indicates the current state of the marquee animation.| +| callback | Callback\<[MarqueeState](#marqueestate18)\> | Yes | Callback that receives a **MarqueeState** enum value, which indicates the current state of the marquee animation.| ## TextOptions11+ @@ -1028,18 +1062,12 @@ Obtains the **LayoutManager** object. | ---------------------------------------- | ------- | | [LayoutManager](ts-text-common.md#layoutmanager12) | **LayoutManager** object.| -## marqueeOptions16+ - -The **marqueeOptions** settings take effect only when **textOverflow** is set to **TextOverflow.MARQUEE**. - -| Name | Type | Mandatory| Description | -|----------------|------------------------------------------------| -------- |---------------| -| marqueeOptions | [TextMarqueeOptions](#marqueeoptions16) | Yes| Marquee settings, including the switch, step length, number of loops, and direction.| - -## TextMarqueeOptions16+ +## TextMarqueeOptions18+ Describes the initialization options of the **Marquee** component. +**Atomic service API**: This API can be used in atomic services since API version 18. + **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** @@ -1052,26 +1080,34 @@ Describes the initialization options of the **Marquee** component. | fromStart | boolean | No | Whether the text scrolls from the start.
Default value: **true** | | delay | number | No | Time interval between scroll movements.
Default value: **0** | | fadeout | boolean | No | Whether to apply a fade-out effect when the text is too long. With this parameter set to **true**: When the text content exceeds the display range, the edges of the partially visible text will have a fade-out effect applied; If both ends have partially visible text, both ends will have the fade-out effect applied; The **clip** attribute is automatically locked to **true** and cannot be set to **false**.
Default value: **false** | -| marqueeStartPolicy | [MarqueeStartPolicy](#marqueestartpolicy16) | No | Start policy of the marquee.
Default value: **MarqueeStartPolicy.DEFAULT** | +| marqueeStartPolicy | [MarqueeStartPolicy](#marqueestartpolicy18) | No | Start policy of the marquee.
Default value: **MarqueeStartPolicy.DEFAULT** | -## MarqueeStartPolicy16+ +## MarqueeStartPolicy18+ Enumerates the marquee scrolling modes. +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + | Name | Value| Description | |----------|----|---------------| -| DEFAULT | 0 |The marquee scrolls continuously. Default value. | -| ON_FOCUS | 1 |The marquee starts scrolling when it has focus or when the mouse hovers over it.| +| DEFAULT | 0 | The marquee scrolls continuously. Default value. | +| ON_FOCUS | 1 | The marquee starts scrolling when it has focus or when the mouse hovers over it.| -## MarqueeState16+ +## MarqueeState18+ Enumerates the return values of the marquee state callback. -| Name | Value|Description | +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Value| Description | |--------|----|-------------------------------| -| START |0 |The marquee starts scrolling. | -| BOUNCE |1 |The marquee completes one scroll movement. If the number of **loops** is not 1, this value will be returned multiple times.| -| FINISH |2 |All loops of the marquee are completed. | +| START | 0 | The marquee starts scrolling. | +| BOUNCE | 1 | The marquee completes one scroll movement. If the number of **loops** is not 1, this value will be returned multiple times.| +| FINISH | 2 | All loops of the marquee are completed. | ## Example @@ -1092,16 +1128,16 @@ function style(TextAlign: TextAlign) { @Entry @Component struct TextExample1 { - @State changeTextAlignIndex: number = 0 - @State changeDecorationIndex: number = 0 - @State TextAlign: TextAlign[] = [TextAlign.Start, TextAlign.Center, TextAlign.End] - @State TextAlignStr: string[] = ['Start', 'Center', 'End'] + @State changeTextAlignIndex: number = 0; + @State changeDecorationIndex: number = 0; + @State TextAlign: TextAlign[] = [TextAlign.Start, TextAlign.Center, TextAlign.End]; + @State TextAlignStr: string[] = ['Start', 'Center', 'End']; @State TextDecorationType: TextDecorationType[] = - [TextDecorationType.LineThrough, TextDecorationType.Overline, TextDecorationType.Underline] - @State TextDecorationTypeStr: string[] = ['LineThrough', 'Overline', 'Underline'] + [TextDecorationType.LineThrough, TextDecorationType.Overline, TextDecorationType.Underline]; + @State TextDecorationTypeStr: string[] = ['LineThrough', 'Overline', 'Underline']; @State TextDecorationStyle: TextDecorationStyle[] = - [TextDecorationStyle.SOLID, TextDecorationStyle.DOTTED, TextDecorationStyle.WAVY] - @State TextDecorationStyleStr: string[] = ['SOLID', 'DOTTED', 'WAVY'] + [TextDecorationStyle.SOLID, TextDecorationStyle.DOTTED, TextDecorationStyle.WAVY]; + @State TextDecorationStyleStr: string[] = ['SOLID', 'DOTTED', 'WAVY']; build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) { @@ -1118,9 +1154,9 @@ struct TextExample1 { Row() { Button('TextAlign Value: ' + this.TextAlignStr[this.changeTextAlignIndex]).onClick(() => { - this.changeTextAlignIndex++ + this.changeTextAlignIndex++; if (this.changeTextAlignIndex > (this.TextAlignStr.length - 1)) { - this.changeTextAlignIndex = 0 + this.changeTextAlignIndex = 0; } }) }.justifyContent(FlexAlign.Center).width('100%') @@ -1163,12 +1199,12 @@ struct TextExample1 { ### Example 2: Setting the Text Style -This example showcases various text styles by using the **decoration**, **letterSpacing**, **textCase**, and **textShadow** attributes. +This example shows how to set various text styles using **decoration**, **letterSpacing**, and **textCase**, **fontFamily**, **textShadow**, **fontStyle**, **textIndent**, and **fontWeight** attributes. ```ts @Extend(Text) function style() { - .fontSize(12) + .font({ size: 12 }) .border({ width: 1 }) .padding(10) .width('100%') @@ -1178,13 +1214,13 @@ function style() { @Entry @Component struct TextExample2 { - @State changeDecorationIndex: number = 0 + @State changeDecorationIndex: number = 0; @State TextDecorationType: TextDecorationType[] = - [TextDecorationType.LineThrough, TextDecorationType.Overline, TextDecorationType.Underline] - @State TextDecorationTypeStr: string[] = ['LineThrough', 'Overline', 'Underline'] + [TextDecorationType.LineThrough, TextDecorationType.Overline, TextDecorationType.Underline]; + @State TextDecorationTypeStr: string[] = ['LineThrough', 'Overline', 'Underline']; @State TextDecorationStyle: TextDecorationStyle[] = - [TextDecorationStyle.SOLID, TextDecorationStyle.DOTTED, TextDecorationStyle.WAVY] - @State TextDecorationStyleStr: string[] = ['SOLID', 'DOTTED', 'WAVY'] + [TextDecorationStyle.SOLID, TextDecorationStyle.DOTTED, TextDecorationStyle.WAVY]; + @State TextDecorationStyleStr: string[] = ['SOLID', 'DOTTED', 'WAVY']; build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) { @@ -1201,9 +1237,9 @@ struct TextExample2 { Row() { Button('Decoration Type: ' + this.TextDecorationTypeStr[this.changeDecorationIndex] + ' & ' + this.TextDecorationStyleStr[this.changeDecorationIndex]).onClick(() => { - this.changeDecorationIndex++ + this.changeDecorationIndex++; if (this.changeDecorationIndex > (this.TextDecorationTypeStr.length - 1)) { - this.changeDecorationIndex = 0 + this.changeDecorationIndex = 0; } }) }.justifyContent(FlexAlign.Center).width('100%') @@ -1233,6 +1269,12 @@ struct TextExample2 { .textCase(TextCase.UpperCase) .style() + Text('fontFamily').fontSize(9).fontColor(0xCCCCCC) + // Set the font family. + Text('This is the text content with fontFamily') + .style() + .fontFamily('HarmonyOS Sans') + Text('textShadow').fontSize(9).fontColor(0xCCCCCC) // Set the text shadow. Text('textShadow') @@ -1246,7 +1288,28 @@ struct TextExample2 { offsetY: 0 }) - }.height(600).width('100%').padding({ left: 35, right: 35, top: 35 }) + Text('fontStyle').fontSize(9).fontColor(0xCCCCCC) + // Set the font style. + Text('This is the text content with fontStyle set to Italic') + .style() + .fontStyle(FontStyle.Italic) + Text('This is the text content with fontStyle set to Normal') + .style() + .fontStyle(FontStyle.Normal) + + Text('textIndent').fontSize(9).fontColor(0xCCCCCC) + // Set the text indentation. + Text('This is the text content with textIndent 30') + .style() + .textIndent(30) + + Text('fontWeight').fontSize(9).fontColor(0xCCCCCC) + // Set the font weight. + Text('This is the text content with fontWeight 800') + .style() + .fontWeight('800', { enableVariableFontWeight: true }) + + }.width('100%').padding({ left: 35, right: 35 }) } } ``` @@ -1271,10 +1334,10 @@ function style() { @Component struct TextExample3 { @State text: string = - 'The text component is used to display a piece of textual information.Support universal attributes and universal text attributes.' - @State ellipsisModeIndex: number = 0 - @State ellipsisMode: EllipsisMode[] = [EllipsisMode.START, EllipsisMode.CENTER, EllipsisMode.END] - @State ellipsisModeStr: string[] = ['START', 'CENTER', 'END'] + 'The text component is used to display a piece of textual information.Support universal attributes and universal text attributes.'; + @State ellipsisModeIndex: number = 0; + @State ellipsisMode: EllipsisMode[] = [EllipsisMode.START, EllipsisMode.CENTER, EllipsisMode.END]; + @State ellipsisModeStr: string[] = ['START', 'CENTER', 'END']; build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) { @@ -1298,23 +1361,23 @@ struct TextExample3 { .textOverflow({ overflow: TextOverflow.MARQUEE }) .style() .marqueeOptions({ - start: true, - fromStart: true, - step: 6, - loop: -1, - delay: 0, - fadeout: false, - marqueeStartPolicy: MarqueeStartPolicy.DEFAULT - }) - .onMarqueeStateChange((state:MarqueeState) => { - if (state == MarqueeState.START) { - // "Received state: START"; - } else if(state == MarqueeState.BOUNCE){ - // "Received state: BOUNCE"; - } else if(state == MarqueeState.FINISH){ - // "Received state: FINISH"; - } - }) + start: true, + fromStart: true, + step: 6, + loop: -1, + delay: 0, + fadeout: false, + marqueeStartPolicy: MarqueeStartPolicy.DEFAULT + }) + .onMarqueeStateChange((state: MarqueeState) => { + if (state == MarqueeState.START) { + // "Received state: START"; + } else if (state == MarqueeState.BOUNCE) { + // "Received state: BOUNCE"; + } else if (state == MarqueeState.FINISH) { + // "Received state: FINISH"; + } + }) Text('ellipsisMode').fontSize(9).fontColor(0xCCCCCC) // Set the position of the ellipsis (...) for text truncation. @@ -1326,9 +1389,9 @@ struct TextExample3 { Row() { Button('Ellipsis Position: ' + this.ellipsisModeStr[this.ellipsisModeIndex]).onClick(() => { - this.ellipsisModeIndex++ + this.ellipsisModeIndex++; if (this.ellipsisModeIndex > (this.ellipsisModeStr.length - 1)) { - this.ellipsisModeIndex = 0 + this.ellipsisModeIndex = 0; } }) } @@ -1358,19 +1421,19 @@ function style() { @Component struct TextExample4 { @State text: string = - 'The text component is used to display a piece of textual information.Support universal attributes and universal text attributes.' + 'The text component is used to display a piece of textual information.Support universal attributes and universal text attributes.'; @State text2: string = "They can be classified as built-in components–those directly provided by the ArkUI framework and custom components – those defined by developers" + "The built-in components include buttons radio buttons progress indicators and text You can set the rendering effect of these components in method chaining mode," + - "page components are divided into independent UI units to implement independent creation development and reuse of different units on pages making pages more engineering-oriented." - @State textClip: boolean = false - @State wordBreakIndex: number = 0 - @State wordBreak: WordBreak[] = [WordBreak.NORMAL, WordBreak.BREAK_ALL, WordBreak.BREAK_WORD] - @State wordBreakStr: string[] = ['NORMAL', 'BREAK_ALL', 'BREAK_WORD'] - @State lineBreakStrategyIndex: number = 0 + "page components are divided into independent UI units to implement independent creation development and reuse of different units on pages making pages more engineering-oriented."; + @State textClip: boolean = false; + @State wordBreakIndex: number = 0; + @State wordBreak: WordBreak[] = [WordBreak.NORMAL, WordBreak.BREAK_ALL, WordBreak.BREAK_WORD]; + @State wordBreakStr: string[] = ['NORMAL', 'BREAK_ALL', 'BREAK_WORD']; + @State lineBreakStrategyIndex: number = 0; @State lineBreakStrategy: LineBreakStrategy[] = - [LineBreakStrategy.GREEDY, LineBreakStrategy.HIGH_QUALITY, LineBreakStrategy.BALANCED] - @State lineBreakStrategyStr: string[] = ['GREEDY', 'HIGH_QUALITY', 'BALANCED'] + [LineBreakStrategy.GREEDY, LineBreakStrategy.HIGH_QUALITY, LineBreakStrategy.BALANCED]; + @State lineBreakStrategyStr: string[] = ['GREEDY', 'HIGH_QUALITY', 'BALANCED']; build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) { @@ -1384,9 +1447,9 @@ struct TextExample4 { Row() { Button('wordBreak Value: ' + this.wordBreakStr[this.wordBreakIndex]).onClick(() => { - this.wordBreakIndex++ + this.wordBreakIndex++; if (this.wordBreakIndex > (this.wordBreakStr.length - 1)) { - this.wordBreakIndex = 0 + this.wordBreakIndex = 0; } }) } @@ -1400,7 +1463,7 @@ struct TextExample4 { .style() Row() { Button('Clip Mode: ' + this.textClip).onClick(() => { - this.textClip = !this.textClip + this.textClip = !this.textClip; }) } @@ -1411,9 +1474,9 @@ struct TextExample4 { .style() Row() { Button('lineBreakStrategy Value: ' + this.lineBreakStrategyStr[this.lineBreakStrategyIndex]).onClick(() => { - this.lineBreakStrategyIndex++ + this.lineBreakStrategyIndex++; if (this.lineBreakStrategyIndex > (this.lineBreakStrategyStr.length - 1)) { - this.lineBreakStrategyIndex = 0 + this.lineBreakStrategyIndex = 0; } }) } @@ -1426,17 +1489,18 @@ struct TextExample4 { ### Example 5: Setting Text Selection and Copy -This example demonstrates the effects of text selection and triggering a copy callback using the **selection** and **onCopy** APIs. +This example demonstrates how to set text selection, trigger a copy callback, make text selection draggable, and modify the caret and selection background colors using **selection**, **onCopy**, **draggable**, **caretColor**, and **selectedBackgroundColor**. ```ts // xxx.ets @Entry @Component struct TextExample5 { - @State onCopy: string = '' - @State text: string = 'This is set selection to Selection text content This is set selection to Selection text content.' - @State start: number = 0 - @State end: number = 20 + @State onCopy: string = ''; + @State text: string = + 'This is set selection to Selection text content This is set selection to Selection text content.'; + @State start: number = 0; + @State end: number = 20; build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.Start }) { @@ -1448,14 +1512,18 @@ struct TextExample5 { .copyOption(CopyOptions.InApp) .selection(this.start, this.end) .onCopy((value: string) => { - this.onCopy = value + this.onCopy = value; }) + .draggable(true) + .caretColor(Color.Red) + .selectedBackgroundColor(Color.Grey) + .enableHapticFeedback(true) Button('Set text selection') - .margin({left:20}) + .margin({ left: 20 }) .onClick(() => { // Change the start point and end point of the text selection. - this.start = 10 - this.end = 30 + this.start = 10; + this.end = 30; }) Text(this.onCopy).fontSize(12).margin(10).key('copy') }.height(600).width(335).padding({ left: 35, right: 35, top: 35 }) @@ -1464,9 +1532,9 @@ struct TextExample5 { ``` ![](figures/textExample5.png) -### Example 6: Setting Text Auto-Adaptation +### Example 6: Setting Text Adaptation and Font Scale Factor Limits -This example showcases the implementation of text auto-adaptation features using the **heightAdaptivePolicy** attribute. +This example demonstrates how to implement text adaptation using **heightAdaptivePolicy** and to set font scale factor limits using **minFontScale** and **maxFontScale**. ```ts // xxx.ets @@ -1496,6 +1564,12 @@ struct TextExample6 { .style(TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST) Text('This is the text with the height adaptive policy set.') .style(TextHeightAdaptivePolicy.LAYOUT_CONSTRAINT_FIRST) + + Text('fontScale').fontSize(9).fontColor(0xCCCCCC) + Text('This is the text content with minFontScale set to 1 and maxFontScale set to 1.2') + .style(TextHeightAdaptivePolicy.MAX_LINES_FIRST) + .minFontScale(1) + .maxFontScale(1.2) }.height(600).width('100%').padding({ left: 35, right: 35, top: 35 }) } } @@ -1512,28 +1586,31 @@ This example demonstrates how to implement text recognition features using the * @Entry @Component struct TextExample7 { - @State phoneNumber: string = '(86) (755) ********' - @State url: string = 'www.********.com' - @State email: string = '***@example.com' - @State address: string = 'XX (province) XX (city) XX (county) XXXX' - @State datetime: string = 'XX-XX-XX XXXX' - @State enableDataDetector: boolean = true - @State types: TextDataDetectorType[] = [] + @State phoneNumber: string = '(86) (755) ********'; + @State url: string = 'www.********.com'; + @State email: string = '***@example.com'; + @State address: string = 'XX (province) XX (city) XX (county) XXXX'; + @State datetime: string = 'XX-XX-XX XXXX'; + @State enableDataDetector: boolean = true; + @State types: TextDataDetectorType[] = []; build() { Row() { Column() { Text( 'Phone number:' + this.phoneNumber + '\n' + - 'URL:' + this.url + '\n' + - 'Email:' + this.email + '\n' + - 'Address:' + this.address + '\n' + - 'Time:' + this.datetime + 'URL:' + this.url + '\n' + + 'Email:' + this.email + '\n' + + 'Address:' + this.address + '\n' + + 'Time:' + this.datetime ) .fontSize(16) .copyOption(CopyOptions.InApp) .enableDataDetector(this.enableDataDetector) - .dataDetectorConfig({types : this.types, onDetectResultUpdate: (result: string)=>{}}) + .dataDetectorConfig({ + types: this.types, onDetectResultUpdate: (result: string) => { + } + }) .textAlign(TextAlign.Center) .borderWidth(1) .padding(10) @@ -1557,8 +1634,8 @@ This example showcases how to bind text to a custom menu using the **bindSelecti @Entry @Component struct TextExample8 { - controller: TextController = new TextController() - options: TextOptions = { controller: this.controller } + controller: TextController = new TextController(); + options: TextOptions = { controller: this.controller }; build() { Column() { @@ -1605,7 +1682,7 @@ struct TextExample8 { MenuItemGroup() { MenuItem({ startIcon: $r('app.media.app_icon'), content: "Right Click Menu 1", labelInfo: "" }) .onClick((event) => { - this.controller.closeSelectionMenu() + this.controller.closeSelectionMenu(); }) MenuItem({ startIcon: $r('app.media.app_icon'), content: "Right Click Menu 2", labelInfo: "" }) MenuItem({ startIcon: $r('app.media.app_icon'), content: "Right Click Menu 3", labelInfo: "" }) @@ -1622,7 +1699,7 @@ struct TextExample8 { MenuItemGroup() { MenuItem({ startIcon: $r('app.media.app_icon'), content: "Long Press Image Menu 1", labelInfo: "" }) .onClick((event) => { - this.controller.closeSelectionMenu() + this.controller.closeSelectionMenu(); }) MenuItem({ startIcon: $r('app.media.app_icon'), content: "Long Press Image Menu 2", labelInfo: "" }) MenuItem({ startIcon: $r('app.media.app_icon'), content: "Long Press Image Menu 3", labelInfo: "" }) @@ -1639,7 +1716,7 @@ struct TextExample8 { MenuItemGroup() { MenuItem({ startIcon: $r('app.media.app_icon'), content: "Select Mixed Menu 1", labelInfo: "" }) .onClick((event) => { - this.controller.closeSelectionMenu() + this.controller.closeSelectionMenu(); }) MenuItem({ startIcon: $r('app.media.app_icon'), content: "Select Mixed Menu 2", labelInfo: "" }) MenuItem({ startIcon: $r('app.media.app_icon'), content: "Select Mixed Menu 3", labelInfo: "" }) @@ -1673,7 +1750,6 @@ function style() { .fontSize(12) .border({ width: 1 }) .width('100%') - // .margin(5) } @Entry @@ -1728,13 +1804,13 @@ import { text } from '@kit.ArkGraphics2D' @Entry @Component struct TextExample10 { - @State lineCount: string = "" - @State glyphPositionAtCoordinate: string = "" - @State lineMetrics: string = "" - @State rectsForRangeStr: string = "" - controller: TextController = new TextController() + @State lineCount: string = ""; + @State glyphPositionAtCoordinate: string = ""; + @State lineMetrics: string = ""; + @State rectsForRangeStr: string = ""; + controller: TextController = new TextController(); @State textStr: string = - 'Hello World!' + 'Hello World!'; build() { Scroll() { @@ -1748,8 +1824,8 @@ struct TextExample10 { .fontSize(25) .borderWidth(1) .onAreaChange(() => { - let layoutManager: LayoutManager = this.controller.getLayoutManager() - this.lineCount = "LineCount: " + layoutManager.getLineCount() + let layoutManager: LayoutManager = this.controller.getLayoutManager(); + this.lineCount = "LineCount: " + layoutManager.getLineCount(); }) Text('LineCount').fontSize(15).fontColor(0xCCCCCC).width('90%').padding(10) @@ -1758,11 +1834,11 @@ struct TextExample10 { Text('GlyphPositionAtCoordinate').fontSize(15).fontColor(0xCCCCCC).width('90%').padding(10) Button("Relative Component Coordinates [150,50]") .onClick(() => { - let layoutManager: LayoutManager = this.controller.getLayoutManager() - let position: PositionWithAffinity = layoutManager.getGlyphPositionAtCoordinate(150, 50) + let layoutManager: LayoutManager = this.controller.getLayoutManager(); + let position: PositionWithAffinity = layoutManager.getGlyphPositionAtCoordinate(150, 50); this.glyphPositionAtCoordinate = - "Relative coordinates [150,50] glyphPositionAtCoordinate position: " + position.position + " affinity: " + - position.affinity + "Relative component coordinates [150,50] glyphPositionAtCoordinate position: " + position.position + " affinity: " + + position.affinity; }) .margin({ bottom: 20, top: 10 }) Text(this.glyphPositionAtCoordinate) @@ -1770,12 +1846,12 @@ struct TextExample10 { Text('LineMetrics').fontSize(15).fontColor(0xCCCCCC).width('90%').padding(10) Button("Line Metrics") .onClick(() => { - let layoutManager: LayoutManager = this.controller.getLayoutManager() - let lineMetrics: LineMetrics = layoutManager.getLineMetrics(0) - this.lineMetrics = "lineMetrics is " + JSON.stringify(lineMetrics) + "\n\n" - let runMetrics = lineMetrics.runMetrics + let layoutManager: LayoutManager = this.controller.getLayoutManager(); + let lineMetrics: LineMetrics = layoutManager.getLineMetrics(0); + this.lineMetrics = "lineMetrics is " + JSON.stringify(lineMetrics) + "\n\n"; + let runMetrics = lineMetrics.runMetrics; runMetrics.forEach((value, key) => { - this.lineMetrics += "runMetrics key is " + key + " " + JSON.stringify(value) + "\n\n" + this.lineMetrics += "runMetrics key is " + key + " " + JSON.stringify(value) + "\n\n"; }) }) .margin({ bottom: 20, top: 10 }) @@ -1784,13 +1860,13 @@ struct TextExample10 { Text('getRectsForRange').fontSize(15).fontColor(0xCCCCCC).width('90%').padding(10) Button("Drawing Area Info for Characters/Placeholders within Specified Text Range") .onClick(() => { - let layoutManager: LayoutManager = this.controller.getLayoutManager() - let range: TextRange = { start: 0, end: 1 } + let layoutManager: LayoutManager = this.controller.getLayoutManager(); + let range: TextRange = { start: 0, end: 1 }; let rectsForRangeInfo: text.TextBox[] = - layoutManager.getRectsForRange(range, text.RectWidthStyle.TIGHT, text.RectHeightStyle.TIGHT) - this.rectsForRangeStr = "getRectsForRange result is " + "\n\n" + layoutManager.getRectsForRange(range, text.RectWidthStyle.TIGHT, text.RectHeightStyle.TIGHT); + this.rectsForRangeStr = "getRectsForRange result is " + "\n\n"; rectsForRangeInfo.forEach((value, key) => { - this.rectsForRangeStr += "rectsForRange key is " + key + " " + JSON.stringify(value) + "\n\n" + this.rectsForRangeStr += "rectsForRange key is " + key + " " + JSON.stringify(value) + "\n\n"; }) }) .margin({ bottom: 20, top: 10 }) @@ -1813,8 +1889,9 @@ This example demonstrates how to implement the feature to select text using the @Entry @Component struct TextExample11 { - @State message: string = 'TextTextTextTextTextTextTextText' + 'TextTextTextTextTextTextTextTextTextTextTextTextTextTextTextText' - + @State message: string = + 'TextTextTextTextTextTextTextText' + 'TextTextTextTextTextTextTextTextTextTextTextTextTextTextTextText'; + build() { Column() { Text(this.message) @@ -1847,34 +1924,34 @@ struct TextExample12 { content: 'Custom 1', icon: $r('app.media.startIcon'), id: TextMenuItemId.of('custom1'), - } + }; let item2: TextMenuItem = { content: 'Custom 2', id: TextMenuItemId.of('custom2'), icon: $r('app.media.startIcon'), - } - menuItems.push(item1) - menuItems.unshift(item2) - return menuItems + }; + menuItems.push(item1); + menuItems.unshift(item2); + return menuItems; } onMenuItemClick = (menuItem: TextMenuItem, textRange: TextRange) => { if (menuItem.id.equals(TextMenuItemId.of("custom2"))) { - console.log("Intercept id: custom2 start:" + textRange.start + "; end:" + textRange.end) - return true + console.log("Intercept id: custom2 start:" + textRange.start + "; end:" + textRange.end); + return true; } if (menuItem.id.equals(TextMenuItemId.COPY)) { - console.log("Intercept COPY start:" + textRange.start + "; end:" + textRange.end) - return true + console.log("Intercept COPY start:" + textRange.start + "; end:" + textRange.end); + return true; } if (menuItem.id.equals(TextMenuItemId.SELECT_ALL)) { - console.log("Do not intercept SELECT_ALL start:" + textRange.start + "; end:" + textRange.end) - return false + console.log("Do not intercept SELECT_ALL start:" + textRange.start + "; end:" + textRange.end); + return false; } - return false - } + return false; + }; @State editMenuOptions: EditMenuOptions = { onCreateMenu: this.onCreateMenu, onMenuItemClick: this.onMenuItemClick - } + }; build() { Column() { @@ -1905,7 +1982,7 @@ struct TextExample13 { Column({ space: 10 }) { Text("privacySensitive") .privacySensitive(true) - .margin({top :30}) + .margin({ top: 30 }) } .alignItems(HorizontalAlign.Center) .width("100%") diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-textarea.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-textarea.md index 809f9f82b5173513a799d6cce3d8a7dba4796271..a571ab3f1750e04e352b6826ec73e307f333ec98 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-textarea.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-textarea.md @@ -37,13 +37,13 @@ TextArea(value?: TextAreaOptions) | Name| Type | Mandatory | Description| | ---- | ----- | ---- | ---- | | placeholder | [ResourceStr](ts-types.md#resourcestr) | No | Text displayed when there is no input.
When only the **placeholder** attribute is set, the text selection handle is still available; the caret stays at the beginning of the placeholder text when the handle is released. | -| text | [ResourceStr](ts-types.md#resourcestr) | No | Current text input.
You are advised to bind the state variable to the text in real time through the **onChange** event,
so as to prevent display errors when the component is updated.
Since API version 10, this parameter supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md).
Since API version 16, this parameter supports two-way binding through [!!](../../../quick-start/arkts-new-binding.md#two-way-binding-between-built-in-component-parameters).| +| text | [ResourceStr](ts-types.md#resourcestr) | No | Current text input.
You are advised to bind the state variable to the text in real time through the **onChange** event,
so as to prevent display errors when the component is updated.
Since API version 10, this parameter supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md).
Since API version 18, this parameter supports two-way binding through [!!](../../../quick-start/arkts-new-binding.md#two-way-binding-between-built-in-component-parameters).| | controller8+ | [TextAreaController](#textareacontroller8) | No | Text area controller.| ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. > **NOTE** > @@ -156,7 +156,7 @@ Sets the text size. | Name| Type | Mandatory| Description | | ------ | ---------------------------- | ---- | ------------------------------------------------------------ | -| value | [Length](ts-types.md#length) | Yes | Font size. If **fontSize** is of the number type, the unit fp is used. The default font size is 16 fp. This parameter cannot be set in percentage.| +| value | [Length](ts-types.md#length) | Yes | Font size. If **fontSize** is of the number type, the unit fp is used. The default font size is 16 fp on non-wearable devices and 18 fp on wearable devices. This parameter cannot be set in percentage.| ### fontStyle @@ -227,7 +227,7 @@ Sets the regular expression for input filtering. Only inputs that comply with th copyOption(value: CopyOptions) -Sets whether copy and paste is allowed. If this attribute is set to **CopyOptions.None**, the text can be pasted, but copy, cut, and AI-powered writing is not allowed. +Sets whether copy and paste is allowed. If this attribute is set to **CopyOptions.None**, the text can only be pasted; all other actions, such as copying, cutting, and sharing, are disabled. Dragging is not allowed when **CopyOptions.None** is set. @@ -298,9 +298,9 @@ Sets the polymorphic style of the text box. The inline input style is only avail enableKeyboardOnFocus(value: boolean) -Sets whether to enable the input method when the **TextArea** component obtains focus in a way other than clicking. +Sets whether to bring up the keyboard when the **TextArea** component obtains focus in a way other than clicking. - +Since API version 10, the **TextArea** component brings up the keyboard by default when it obtains focus. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -310,7 +310,7 @@ Sets whether to enable the input method when the **TextArea** component obtains | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ----------------------------------------------------------- | -| value | boolean | Yes | Whether to enable the input method when the **TextArea** component obtains focus in a way other than clicking.
Default value: **true**| +| value | boolean | Yes | Whether to bring up the keyboard when the **TextArea** component obtains focus in a way other than clicking.
Default value: **true**| ### selectionMenuHidden10+ @@ -453,7 +453,7 @@ Sets the content type for autofill. | Name | Type | Mandatory| Description | | ----------- | ------------------------------------- | ---- | -------------- | -| contentType | [ContentType](#contenttype12) | Yes | Content type for autofill.| +| contentType | [ContentType](ts-basic-components-textinput.md#contenttype12) | Yes | Content type for autofill.| ### lineHeight12+ @@ -491,7 +491,7 @@ Sets the color, type, and style of the text decorative line. letterSpacing(value: number | string | Resource) -Sets the letter spacing for a text style. If the value specified is a percentage or 0, the default value is used. +Sets the letter spacing for a text style. If the value specified is a percentage or 0, the default value is used. For the string type, numeric string values with optional units, for example, **"10"** or **"10fp"**, are supported. If the value specified is a negative value, the text is compressed. A negative value too small may result in the text being compressed to 0 and no content being displayed. @@ -503,7 +503,7 @@ If the value specified is a negative value, the text is compressed. A negative v | Name| Type | Mandatory| Description | | ------ | -------------------------- | ---- | -------------- | -| value | number \| string \| [Resource](ts-types.md#resource) | Yes | Letter spacing.| +| value | number \| string \| [Resource](ts-types.md#resource) | Yes | Letter spacing.
Unit: fp| ### fontFeature12+ @@ -631,7 +631,7 @@ If **overflow** is set to **TextOverflow.None**, **TextOverflow.Clip**, or **Tex minFontSize(value: number | string | Resource) -Sets the minimum font size. +Sets the minimum font size. For the string type, numeric string values with optional units, for example, **"10"** or **"10fp"**, are supported. For the setting to take effect, this attribute must be used together with [maxFontSize](#maxfontsize12) and [maxLines](#maxlines10), or layout constraint settings. @@ -645,13 +645,13 @@ When the adaptive font size is used, the **fontSize** settings do not take effec | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------ | -| value | number \| string \| [Resource](ts-types.md#resource) | Yes | Minimum font size.| +| value | number \| string \| [Resource](ts-types.md#resource) | Yes | Minimum font size.
Unit: fp| ### maxFontSize12+ maxFontSize(value: number | string | Resource) -Sets the maximum font size. +Sets the maximum font size. For the string type, numeric string values with optional units, for example, **"10"** or **"10fp"**, are supported. For the setting to take effect, this attribute must be used together with [minFontSize](#minfontsize12) and [maxLines](#maxlines10), or layout constraint settings. @@ -665,55 +665,7 @@ When the adaptive font size is used, the **fontSize** settings do not take effec | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------ | -| value | number \| string \| [Resource](ts-types.md#resource) | Yes | Maximum font size.| - -### halfLeading16+ - -halfLeading(halfLeading: boolean) - -Sets whether half leading is enabled. - -**Atomic service API**: This API can be used in atomic services since API version 16. - -**System capability**: SystemCapability.ArkUI.ArkUI.Full - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | --------------------------------------------- | ---- | --------------------------------------------- | -| halfLeading | boolean | Yes | Whether half leading is enabled.
Whether half leading is enabled. Half leading is the leading split in half and applied equally to the top and bottom edges. The value **true** means that half leading is enabled, and **false** means the opposite.
Default value: **false**| - -### minFontScale16+ - -minFontScale(scale: number | Resource) - -Sets the minimum font scale factor for text. - -**Atomic service API**: This API can be used in atomic services since API version 16. - -**System capability**: SystemCapability.ArkUI.ArkUI.Full - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | --------------------------------------------- | ---- | --------------------------------------------- | -| scale | number \| [Resource](ts-types.md#resource) | Yes | Minimum font scale factor for text.
Value range: [0, 1]
**NOTE**
A value less than 0 is handled as 0. A value greater than 1 is handled as 1. Abnormal values are ineffective by default.| - -### maxFontScale16+ - -maxFontScale(scale: number | Resource) - -Sets the maximum font scale factor for text. - -**Atomic service API**: This API can be used in atomic services since API version 16. - -**System capability**: SystemCapability.ArkUI.ArkUI.Full - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | --------------------------------------------- | ---- | --------------------------------------------- | -| scale | number \| [Resource](ts-types.md#resource) | Yes | Maximum font scale factor for text.
Value range: [1, +∞)
**NOTE**
A value less than 1 is handled as 1. Abnormal values are ineffective by default.| +| value | number \| string \| [Resource](ts-types.md#resource) | Yes | Maximum font size.
Unit: fp| ### heightAdaptivePolicy12+ @@ -804,18 +756,6 @@ Preview text is in a temporary state and does not support text interception. As | ------ | ------- | ---- | ---------------------------------- | | enable | boolean | Yes | Whether to enable preview text.
Default value: **true**| -> **NOTE** -> -> This API is disabled by default in C API scenarios. To enable preview text in such scenarios, set [metadata](../../../../application-dev/quick-start/module-structure.md#internal-structure-of-the-metadata-attribute) in the **module.json5** file of the project as follows: -> ```json -> "metadata": [ -> { -> "name": "can_preview_text", -> "value": "true", -> } -> ] -> ``` - ### enableHapticFeedback13+ enableHapticFeedback(isEnabled: boolean) @@ -843,15 +783,29 @@ Specifies whether to enable haptic feedback. > ] > ``` -### ellipsisMode16+ +### keyboardAppearance15+ -ellipsisMode(value: EllipsisMode) +keyboardAppearance(appearance: Optional\) -Sets the ellipsis position. For the settings to work, **overflow** must be set to **TextOverflow.Ellipsis** and **maxLines** must be specified. Setting **ellipsisMode** alone does not take effect. +Sets the appearance of the keyboard when the text box is focused. -**EllipsisMode.START** and **EllipsisMode.CENTER** take effect only when **maxLines** is set to **1**. +**Atomic service API**: This API can be used in atomic services since API version 15. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full -**Atomic service API**: This API can be used in atomic services since API version 16. +**Parameters** + +| Name| Type| Mandatory| Description| +| ------ | ----------------------------------------- | ---- | ------------------------------------------------------ | +| appearance | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[KeyboardAppearance](ts-text-common.md#keyboardappearance15)> | Yes | Appearance of the keyboard.
Default value: **KeyboardAppearance.NONE_IMMERSIVE**| + +### stopBackPress15+ + +stopBackPress(isStopped: Optional\) + +Sets whether to prevent the back button press from being propagated to other components or applications. + +**Atomic service API**: This API can be used in atomic services since API version 15. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -859,15 +813,65 @@ Sets the ellipsis position. For the settings to work, **overflow** must be set t | Name| Type | Mandatory| Description | | ------ | --------------------------------------------------- | ---- | ----------------------------------------- | -| value | [EllipsisMode](ts-appendix-enums.md#ellipsismode11) | Yes | Ellipsis position.
Default value: **EllipsisMode.END**| +| isStopped | [Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Whether to consume the back button press.
Default value: **true**| -### stopBackPress16+ +### halfLeading18+ -stopBackPress(isStopped: boolean) +halfLeading(halfLeading: Optional\) -Sets whether to prevent the back button press from being propagated to other components or applications. +Sets whether half leading is enabled. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | --------------------------------------------- | ---- | --------------------------------------------- | +| halfLeading | [Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Whether half leading is enabled.
Half leading is the leading split in half and applied equally to the top and bottom edges. The value **true** means that half leading is enabled, and **false** means the opposite.
Default value: **false**| + +### minFontScale18+ + +minFontScale(scale: Optional\) + +Sets the minimum font scale factor for text. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | --------------------------------------------- | ---- | --------------------------------------------- | +| scale | [Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Minimum font scale factor for text. The **undefined** type is supported.
Value range: [0, 1]
**NOTE**
A value less than 0 is handled as 0. A value greater than 1 is handled as 1. Abnormal values are ineffective by default.| + +### maxFontScale18+ + +maxFontScale(scale: Optional\) + +Sets the maximum font scale factor for text. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | --------------------------------------------- | ---- | --------------------------------------------- | +| scale | [Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Maximum font scale factor for text. The **undefined** type is supported.
Value range: [1, +∞)
**NOTE**
A value less than 1 is handled as 1. Abnormal values are ineffective by default.| + +### ellipsisMode18+ + +ellipsisMode(mode: Optional\) + +Sets the ellipsis position. For the settings to work, **overflow** must be set to **TextOverflow.Ellipsis** and **maxLines** must be specified. Setting **ellipsisMode** alone does not take effect. + +**EllipsisMode.START** and **EllipsisMode.CENTER** take effect only when **maxLines** is set to **1**. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -875,11 +879,11 @@ Sets whether to prevent the back button press from being propagated to other com | Name| Type | Mandatory| Description | | ------ | --------------------------------------------------- | ---- | ----------------------------------------- | -| isStopped | boolean | Yes | Whether to consume the back button press.
Default value: **true**| +| mode | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[EllipsisMode](ts-appendix-enums.md#ellipsismode11)> | Yes | Ellipsis position.
Default value: **EllipsisMode.END**| ## Events -In addition to the [universal events](ts-universal-events-click.md), the following events are supported. +In addition to the [universal events](ts-component-general-events.md), the following events are supported. ### onChange @@ -887,7 +891,7 @@ onChange(callback: EditableTextOnChangeCallback) Called when the input in the text box changes. -In this callback, if cursor operations are performed, developers need to adjust the cursor logic based on the **previewText** parameter to ensure it works seamlessly within the preview display scenario. +In this callback, if cursor operations are performed, you need to adjust the cursor logic based on the **previewText** parameter to make sure it works seamlessly under the preview display scenario. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -1044,7 +1048,7 @@ Triggered when text is about to be inserted. | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------ | -| callback | Callback\<[InsertValue](ts-text-common.md#insertvalue12), boolean> | Yes | Callback triggered when text is about to be inserted.
It returns **true** if the text is inserted; returns **false** otherwise.
This callback is not called for text preview.
It is available only for system input methods.| +| callback | Callback\<[InsertValue](ts-text-common.md#insertvalue12), boolean> | Yes | Callback triggered when text is about to be inserted.
It returns **true** if the text is inserted; returns **false** otherwise.
This callback is not triggered for pre-edit or candidate word operations.
It is available only for system input methods.| ### onDidInsert12+ @@ -1094,6 +1098,24 @@ Triggered when text is deleted. | ------ | ------------------------------------------------------------ | ---- | ------------------ | | callback | Callback\<[DeleteValue](ts-text-common.md#deletevalue12)> | Yes | Callback triggered when text is deleted.
It is available only for system input methods.| +### onWillChange15+ + +onWillChange(callback: Callback\) + +Called when the text content is about to change. + +This callback is triggered after **onWillInsert** and **onWillDelete**, but before **onDidInsert** and **onDidDelete**. + +**Atomic service API**: This API can be used in atomic services since API version 15. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------ | +| callback | Callback\<[EditableTextChangeValue](ts-text-common.md#editabletextchangevalue15), boolean> | Yes | Callback triggered when the text content is about to change.
Returning **true** allows the change to proceed, while returning **false** cancels the change.| + ## TextAreaController8+ Inherits from [TextContentControllerBase](ts-types.md#textcontentcontrollerbase10). @@ -1183,38 +1205,6 @@ Exits the editing state. | NUMBER_DECIMAL12+ | 12 | Number input mode with a decimal point.
The value can contain digits and one decimal point.| | URL12+ | 13 | URL input mode.| -## ContentType12+ - -Enumerates the content types for autofill. - -**Atomic service API**: This API can be used in atomic services since API version 12. - -**System capability**: SystemCapability.ArkUI.ArkUI.Full - -| Name | Value | Description | -| -------------------------- | ---- | ------------------------------------------------------------ | -| USER_NAME | 0 | Username. Password Vault, when enabled, can automatically save and fill in usernames.| -| PASSWORD | 1 | Password. Password Vault, when enabled, can automatically save and fill in passwords.| -| NEW_PASSWORD | 2 | New password. Password Vault, when enabled, can automatically generate a new password. | -| FULL_STREET_ADDRESS | 3 | Full street address. The scenario-based autofill feature, when enabled, can automatically save and fill in full street addresses.| -| HOUSE_NUMBER | 4 | House number. The scenario-based autofill feature, when enabled, can automatically save and fill in house numbers.| -| DISTRICT_ADDRESS | 5 | District and county. The scenario-based autofill feature, when enabled, can automatically save and fill in districts and counties.| -| CITY_ADDRESS | 6 | City. The scenario-based autofill feature, when enabled, can automatically save and fill in cities.| -| PROVINCE_ADDRESS | 7 | Province. The scenario-based autofill feature, when enabled, can automatically save and fill in provinces.| -| COUNTRY_ADDRESS | 8 | Country. The scenario-based autofill feature, when enabled, can automatically save and fill in countries.| -| PERSON_FULL_NAME | 9 | Full name. The scenario-based autofill feature, when enabled, can automatically save and fill in full names.| -| PERSON_LAST_NAME | 10 | Last name. The scenario-based autofill feature, when enabled, can automatically save and fill in last names.| -| PERSON_FIRST_NAME | 11 | First name. The scenario-based autofill feature, when enabled, can automatically save and fill in first names.| -| PHONE_NUMBER | 12 | Phone number. The scenario-based autofill feature, when enabled, can automatically save and fill in phone numbers.| -| PHONE_COUNTRY_CODE | 13 | Country code. The scenario-based autofill feature, when enabled, can automatically save and fill in country codes.| -| FULL_PHONE_NUMBER | 14 | Phone number with country code. The scenario-based autofill feature, when enabled, can automatically save and fill in phone numbers with country codes.| -| EMAIL_ADDRESS | 15 | Email address. The scenario-based autofill feature, when enabled, can automatically save and fill in email addresses.| -| BANK_CARD_NUMBER | 16 | Bank card number. The scenario-based autofill feature, when enabled, can automatically save and fill in bank card numbers.| -| ID_CARD_NUMBER | 17 | ID card number. The scenario-based autofill feature, when enabled, can automatically save and fill in ID card numbers.| -| NICKNAME | 23 | Nickname. The scenario-based autofill feature, when enabled, can automatically save and fill in nicknames.| -| DETAIL_INFO_WITHOUT_STREET | 24 | Address information without street address. The scenario-based autofill feature, when enabled, can automatically save and fill in address information without street addresses.| -| FORMAT_ADDRESS | 25 | Standard address. The scenario-based autofill feature, when enabled, can automatically save and fill in standard addresses.| - ## TextAreaSubmitCallback14+ type TextAreaSubmitCallback = (enterKeyType: EnterKeyType, event?: SubmitEvent) => void @@ -1469,31 +1459,31 @@ struct TextAreaExample { Row() { Column() { Text('lineHeight').fontSize(9).fontColor(0xCCCCCC) - TextArea({text: 'lineHeight unset'}) + TextArea({ text: 'lineHeight unset' }) .border({ width: 1 }).padding(10).margin(5) - TextArea({text: 'lineHeight 15'}) + TextArea({ text: 'lineHeight 15' }) .border({ width: 1 }).padding(10).margin(5).lineHeight(15) - TextArea({text: 'lineHeight 30'}) + TextArea({ text: 'lineHeight 30' }) .border({ width: 1 }).padding(10).margin(5).lineHeight(30) Text('letterSpacing').fontSize(9).fontColor(0xCCCCCC) - TextArea({text: 'letterSpacing 0'}) + TextArea({ text: 'letterSpacing 0' }) .border({ width: 1 }).padding(5).margin(5).letterSpacing(0) - TextArea({text: 'letterSpacing 3'}) + TextArea({ text: 'letterSpacing 3' }) .border({ width: 1 }).padding(5).margin(5).letterSpacing(3) - TextArea({text: 'letterSpacing -1'}) + TextArea({ text: 'letterSpacing -1' }) .border({ width: 1 }).padding(5).margin(5).letterSpacing(-1) Text('decoration').fontSize(9).fontColor(0xCCCCCC) - TextArea({text: 'LineThrough, Red\nsecond line'}) + TextArea({ text: 'LineThrough, Red\nsecond line' }) .border({ width: 1 }).padding(5).margin(5) - .decoration({type: TextDecorationType.LineThrough, color: Color.Red}) - TextArea({text: 'Overline, Red, DOTTED\nsecond line'}) + .decoration({ type: TextDecorationType.LineThrough, color: Color.Red }) + TextArea({ text: 'Overline, Red, DOTTED\nsecond line' }) .border({ width: 1 }).padding(5).margin(5) - .decoration({type: TextDecorationType.Overline, color: Color.Red, style: TextDecorationStyle.DOTTED}) - TextArea({text: 'Underline, Red, WAVY\nsecond line'}) + .decoration({ type: TextDecorationType.Overline, color: Color.Red, style: TextDecorationStyle.DOTTED }) + TextArea({ text: 'Underline, Red, WAVY\nsecond line' }) .border({ width: 1 }).padding(5).margin(5) - .decoration({type: TextDecorationType.Underline, color: Color.Red, style: TextDecorationStyle.WAVY}) + .decoration({ type: TextDecorationType.Underline, color: Color.Red, style: TextDecorationStyle.WAVY }) }.height('90%') } .width('90%') @@ -1517,13 +1507,13 @@ struct TextAreaExample { @State text2: string = 'This is ss01 off: 0123456789' build() { - Column(){ - TextArea({text: this.text1}) + Column() { + TextArea({ text: this.text1 }) .fontSize(20) - .margin({top:200}) + .margin({ top: 200 }) .fontFeature("\"ss01\" on") - TextArea({text : this.text2}) - .margin({top:10}) + TextArea({ text: this.text2 }) + .margin({ top: 10 }) .fontSize(20) .fontFeature("\"ss01\" off") } @@ -1545,19 +1535,21 @@ This example illustrates the implementation of a custom keyboard that automatica struct TextAreaExample { controller: TextAreaController = new TextAreaController() @State inputValue: string = "" - @State height1:string|number = '80%' - @State height2:number = 100 - @State supportAvoidance:boolean = true; + @State height1: string | number = '80%' + @State height2: number = 100 + @State supportAvoidance: boolean = true; // Create a custom keyboard component. - @Builder CustomKeyboardBuilder() { + @Builder + CustomKeyboardBuilder() { Column() { - Row(){ + Row() { Button('x').onClick(() => { // Disable the custom keyboard. this.controller.stopEditing() }).margin(10) } + Grid() { ForEach([1, 2, 3, 4, 5, 6, 7, 8, 9, '*', 0, '#'], (item: number | string) => { GridItem() { @@ -1573,16 +1565,16 @@ struct TextAreaExample { build() { Column() { - Row(){ + Row() { Button("20%") .fontSize(24) - .onClick(()=>{ + .onClick(() => { this.height1 = "20%" }) Button("80%") .fontSize(24) - .margin({left:20}) - .onClick(()=>{ + .margin({ left: 20 }) + .onClick(() => { this.height1 = "80%" }) } @@ -1590,12 +1582,13 @@ struct TextAreaExample { .alignItems(VerticalAlign.Bottom) .height(this.height1) .width("100%") - .padding({bottom:50}) - TextArea({ controller: this.controller, text: this.inputValue}) + .padding({ bottom: 50 }) + + TextArea({ controller: this.controller, text: this.inputValue }) .height(100) - // Bind the custom keyboard. - .customKeyboard(this.CustomKeyboardBuilder(),{ supportAvoidance: this.supportAvoidance }).margin(10).border({ width: 1 }) - // .height(200) + .customKeyboard(this.CustomKeyboardBuilder(), { supportAvoidance: this.supportAvoidance })// Bind a custom keyboard. + .margin(10) + .border({ width: 1 }) } } } @@ -1655,26 +1648,26 @@ import { LengthMetrics } from '@kit.ArkUI' @Component struct TextAreaExample { build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) { - Text('TextArea lineSpacing.').fontSize(9).fontColor(0xCCCCCC) - TextArea({ placeholder: 'This is the TextArea with no lineSpacing set.' }) - .fontSize(12) - TextArea({ placeholder: 'This is the TextArea with lineSpacing set to 20_px.' }) - .fontSize(12) - .lineSpacing(LengthMetrics.px(20)) - TextArea({ placeholder: 'This is the TextArea with lineSpacing set to 20_vp.' }) - .fontSize(12) - .lineSpacing(LengthMetrics.vp(20)) - TextArea({ placeholder: 'This is the TextArea with lineSpacing set to 20_fp.' }) - .fontSize(12) - .lineSpacing(LengthMetrics.fp(20)) - TextArea({ placeholder: 'This is the TextArea with lineSpacing set to 20_lpx.' }) - .fontSize(12) - .lineSpacing(LengthMetrics.lpx(20)) - TextArea({ placeholder: 'This is the TextArea with lineSpacing set to 100%.' }) - .fontSize(12) - .lineSpacing(LengthMetrics.percent(1)) - }.height(600).width(350).padding({ left: 35, right: 35, top: 35 }) + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) { + Text('TextArea lineSpacing.').fontSize(9).fontColor(0xCCCCCC) + TextArea({ text: 'This is the TextArea with no lineSpacing set.' }) + .fontSize(12) + TextArea({ text: 'This is the TextArea with lineSpacing set to 20_px.' }) + .fontSize(12) + .lineSpacing(LengthMetrics.px(20)) + TextArea({ text: 'This is the TextArea with lineSpacing set to 20_vp.' }) + .fontSize(12) + .lineSpacing(LengthMetrics.vp(20)) + TextArea({ text: 'This is the TextArea with lineSpacing set to 20_fp.' }) + .fontSize(12) + .lineSpacing(LengthMetrics.fp(20)) + TextArea({ text: 'This is the TextArea with lineSpacing set to 20_lpx.' }) + .fontSize(12) + .lineSpacing(LengthMetrics.lpx(20)) + TextArea({ text: 'This is the TextArea with lineSpacing set to 100%.' }) + .fontSize(12) + .lineSpacing(LengthMetrics.percent(1)) + }.height(600).width(350).padding({ left: 35, right: 35, top: 35 }) } } ``` @@ -1944,3 +1937,138 @@ struct EllipsisModeExample { ``` ![textAreaEllipsisMode](figures/textAreaEllipsisMode.png) + +### Example 16: Implementing Custom Copy, Cut, and Paste Behavior + +This example demonstrates how to listen for the copy, cut, and paste buttons in the text selection menu, how to disable the system paste functionality, and how to implement custom paste behavior. + +```ts +// xxx.ets +@Entry +@Component +struct TextAreaExample { + @State text: string = '' + controller: TextAreaController = new TextAreaController() + + build() { + Column() { + TextArea({ + text: this.text, + placeholder: 'placeholder', + controller: this.controller + }) + .placeholderColor(Color.Red) + .textAlign(TextAlign.Center) + .caretColor(Color.Green) + .caretStyle({ width: '2vp' }) + .fontStyle(FontStyle.Italic) + .fontWeight(FontWeight.Bold) + .fontFamily('HarmonyOS Sans') + .inputFilter('[a-zA-Z]+', (value) => { // Only alphabetic input is allowed. + console.error(`unsupport char ${value}`) + }) + .copyOption(CopyOptions.LocalDevice) + .enableKeyboardOnFocus(false) + .selectionMenuHidden(false) + .barState(BarState.On) + .type(TextAreaType.NORMAL) + .selectedBackgroundColor(Color.Orange) + .textIndent(2) + .halfLeading(true) + .minFontScale(1) + .maxFontScale(2) + .enablePreviewText(true) + .enableHapticFeedback(true) + .stopBackPress(false)// Delegate back press to other components. + .width(336) + .height(56) + .margin(20) + .fontSize(16) + .onEditChange((isEditing: boolean) => { + console.log(`isEditing ${isEditing}`) + }) + .onCopy((value) => { + console.log(`copy ${value}`) + }) + .onCut((value) => { + console.log(`cut ${value}`) + }) + .onPaste((value, event) => { + // Prevent the default system paste behavior and implement custom logic. + if (event.preventDefault) { + event.preventDefault() + } + console.log(`paste:${value}`) + this.text = value + }) + .onTextSelectionChange((start: number, end: number) => { + console.log(`onTextSelectionChange start ${start}, end ${end}`) + }) + .onContentScroll((totalOffsetX: number, totalOffsetY: number) => { + console.log(`onContentScroll offsetX ${totalOffsetX}, offsetY ${totalOffsetY}`) + }) + }.width('100%').height('100%').backgroundColor('#F1F3F5') + } +} +``` +![textCustomPaste](figures/textarea_custom_paste.PNG) + +### Example 17: Setting the Minimum and Maximum Font Scale Factor + +This example demonstrates how to set the minimum and maximum font scale factor using **minFontScale** and **maxFontScale**. + +```ts +import { abilityManager, Configuration } from '@kit.AbilityKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +// xxx.ets +@Entry +@Component +export struct TextAreaExample11 { + @State minFontScale: number = 0.85; + @State maxFontScale: number = 2; + @State changeValue: string = 'abcde'; + + build() { + Column() { + Column({ space: 30 }) { + Text("System font size changes: small and large, small and large") + TextArea({ + placeholder: 'The text area can hold an unlimited amount of text. input your word...', + }) + // Set the minimum font scale factor; if the value is undefined, the text follows the default font scale factor. + .minFontScale(0.85) + // Set the maximum font scale factor; if the value is undefined, the text follows the default font scale factor. + .maxFontScale(2) + }.width('100%') + } + } +} +``` + +```ts +Create a new directory named profile in the following path: AppScope/resources/base. +Inside the newly created profile directory, create a file named configuration.json. +Add the following JSON code to the configuration.json file: +{ + "configuration":{ + "fontSizeScale": "followSystem", + "fontSizeMaxScale": "3.2" +} +} +``` + +```ts +Modify the app.json5 file in AppScope as follows: +{ + "app": { + "bundleName": "com.example.myapplication", + "vendor": "example", + "versionCode": 1000000, + "versionName": "1.0.0", + "icon": "$media:app_icon", + "label": "$string:app_name", + "configuration": "$profile:configuration" + } +} +``` diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-textinput-sys.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-textinput-sys.md index 67c3be9d52ab8168e5f282fbaf084cdfad4c2268..8079a2e6d9ab81a1b7e3b4c8f66a06804c064ad4 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-textinput-sys.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-textinput-sys.md @@ -10,6 +10,8 @@ The **TextInput** component provides single-line text input. ## InputType +**System capability**: SystemCapability.ArkUI.ArkUI.Full + | Name | Description | | ---------------------------------- | ---------------------------------------- | | SCREEN_LOCK_PASSWORD11+ | Lock screen password input mode. This mode accepts only digits, letters, underscores (_), spaces, and special characters. An eye icon is used to show or hide the password, and the entered text is hidden behind dots by default. Since API version 12, on specific devices, the entered text is displayed directly as dots. The password input mode does not support underlines.
**System API**: This is a system API.| diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-textinput.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-textinput.md index 1df8300ef59163abcbc00f7c153c546bb367288c..0df0800cb8ec04c4aee071e352c66503f2b033af 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-textinput.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-textinput.md @@ -35,12 +35,12 @@ TextInput(value?: TextInputOptions) | Name| Type | Mandatory | Description| | ---- | ----- | ---- | ---- | | placeholder | [ResourceStr](ts-types.md#resourcestr) | No | Text displayed when there is no input. | -| text | [ResourceStr](ts-types.md#resourcestr) | No | Current text input.
You are advised to bind the state variable to the text in real time through the **onChange** event,
so as to prevent display errors when the component is updated.
Since API version 10, this parameter supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md).
Since API version 16, this parameter supports two-way binding through [!!](../../../quick-start/arkts-new-binding.md#two-way-binding-between-built-in-component-parameters).| +| text | [ResourceStr](ts-types.md#resourcestr) | No | Current text input.
You are advised to bind the state variable to the text in real time through the **onChange** event,
so as to prevent display errors when the component is updated.
Since API version 10, this parameter supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md).
Since API version 18, this parameter supports two-way binding through [!!](../../../quick-start/arkts-new-binding.md#two-way-binding-between-built-in-component-parameters).| | controller8+ | [TextInputController](#textinputcontroller8) | No | Text input controller. | ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. > **NOTE** > @@ -74,6 +74,8 @@ placeholderColor(value: ResourceColor) Sets the placeholder text color. +The default value on wearable devices is **'#99ffffff'**. + **Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -90,6 +92,8 @@ placeholderFont(value?: Font) Sets the placeholder text style, including the font size, font width, font family, and font style. The 'HarmonyOS Sans' font and [registered custom fonts](../js-apis-font.md) are supported. +The default value on wearable devices is **18fp**. + **Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -158,6 +162,8 @@ fontColor(value: ResourceColor) Sets the font color. +The default value on wearable devices is **'#dbffffff'**. + **Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -174,6 +180,8 @@ fontSize(value: Length) Sets the font size. +The default value on wearable devices is **18fp**. + **Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -255,7 +263,7 @@ Since API version 11, if **inputFilter** is set and the entered characters are n copyOption(value: CopyOptions) -Sets whether copy and paste is allowed. If this attribute is set to **CopyOptions.None**, the text can be pasted, but copy, cut, and AI-powered writing is not allowed. +Sets whether copy and paste is allowed. If this attribute is set to **CopyOptions.None**, the text can only be pasted; all other actions, such as copying, cutting, and sharing, are disabled. Dragging is not allowed when **CopyOptions.None** is set. @@ -391,6 +399,8 @@ showError(value?: ResourceStr | undefined) Sets the error message displayed when an error occurs. +On wearable devices, the error message is displayed at a font size of 13 fp and center-aligned. + If the data type is **ResourceStr** and the input content does not comply with specifications, the error message is displayed. If the error message does not fit in one line, an ellipsis (…) is displayed to represent clipped text. If the data type is **undefined**, no error message is displayed. For details, see [Example 2](#example-2-setting-underlines). **Atomic service API**: This API can be used in atomic services since API version 11. @@ -427,7 +437,7 @@ Sets the password icon to display at the end of the password text box. Images in JPG, PNG, BMP, HEIC, and WEBP formats are supported. -The icon size is fixed at 24 vp, regardless of the source image size. +The icon size is fixed at 24 vp (or 28 vp on wearable devices), regardless of the source image size. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -445,7 +455,7 @@ enableKeyboardOnFocus(value: boolean) Sets whether to enable the input method when the **TextInput** component obtains focus in a way other than clicking. - +Since API version 10, the **TextInput** component brings up the keyboard by default when it obtains focus. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -574,6 +584,8 @@ cancelButton(options: CancelButtonOptions) Sets the style of the cancel button on the right. This attribute is not available for the inline input style. +The default value is **28fp** on wearable devices. + **Atomic service API**: This API can be used in atomic services since API version 12. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -637,7 +649,7 @@ Sets the content type for autofill. | Name| Type | Mandatory| Description | | ------ | ------------------------------------- | ---- | -------------- | -| value | [ContentType](#contenttype12) | Yes | Content type for autofill.| +| value | [ContentType](#contenttype12-1) | Yes | Content type for autofill.| ### underlineColor12+ @@ -657,7 +669,7 @@ Sets the color of the underline when it is shown. lineHeight(value: number | string | Resource) -Sets the text line height. If the value is less than or equal to **0**, the line height is not limited and the font size is adaptive. If the value is of the number type, the unit fp is used. +Sets the text line height. If the value is less than or equal to **0**, the line height is not limited and the font size is adaptive. If the value is of the number type, the unit fp is used. For the string type, numeric string values with optional units, for example, **"10"** or **"10fp"**, are supported. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -689,7 +701,7 @@ Sets the color, type, and style of the text decorative line. This attribute does letterSpacing(value: number | string | Resource) -Sets the letter spacing for a text style. If the value specified is a percentage or 0, the default value is used. +Sets the letter spacing for a text style. If the value specified is a percentage or 0, the default value is used. For the string type, numeric string values with optional units, for example, **"10"** or **"10fp"**, are supported. If the value specified is a negative value, the text is compressed. A negative value too small may result in the text being compressed to 0 and no content being displayed. @@ -701,7 +713,7 @@ If the value specified is a negative value, the text is compressed. A negative v | Name| Type | Mandatory| Description | | ------ | -------------------------- | ---- | -------------- | -| value | number \| string \| [Resource](ts-types.md#resource) | Yes | Letter spacing.| +| value | number \| string \| [Resource](ts-types.md#resource) | Yes | Letter spacing.
Unit: fp| ### fontFeature12+ @@ -799,7 +811,7 @@ Sets the indent of the first line text. minFontSize(value: number | string | Resource) -Sets the minimum font size. +Sets the minimum font size. For the string type, numeric string values with optional units, for example, **"10"** or **"10fp"**, are supported. For the setting to take effect, this attribute must be used together with [maxFontSize](#maxfontsize12) and [maxLines](#maxlines10) (when the component is in editing state in the inline input style), or layout constraint settings. @@ -813,13 +825,13 @@ When the adaptive font size is used, the **fontSize** settings do not take effec | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------ | -| value | number \| string \| [Resource](ts-types.md#resource) | Yes | Minimum font size.| +| value | number \| string \| [Resource](ts-types.md#resource) | Yes | Minimum font size.
Unit: fp| ### maxFontSize12+ maxFontSize(value: number | string | Resource) -Sets the maximum font size. +Sets the maximum font size. For the string type, numeric string values with optional units, for example, **"10"** or **"10fp"**, are supported. For the setting to take effect, this attribute must be used together with [minFontSize](#minfontsize12) and [maxLines](#maxlines10) (when the component is in editing state in the inline input style), or layout constraint settings. @@ -833,55 +845,7 @@ When the adaptive font size is used, the **fontSize** settings do not take effec | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------ | -| value | number \| string \| [Resource](ts-types.md#resource) | Yes | Maximum font size.| - -### halfLeading16+ - -halfLeading(halfLeading: boolean) - -Sets whether half leading is enabled. - -**Atomic service API**: This API can be used in atomic services since API version 16. - -**System capability**: SystemCapability.ArkUI.ArkUI.Full - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | --------------------------------------------- | ---- | --------------------------------------------- | -| halfLeading | boolean | Yes | Whether half leading is enabled.
Whether half leading is enabled. Half leading is the leading split in half and applied equally to the top and bottom edges. The value **true** means that half leading is enabled, and **false** means the opposite.
Default value: **false**| - -### minFontScale16+ - -minFontScale(scale: number | Resource) - -Sets the minimum font scale factor for text. - -**Atomic service API**: This API can be used in atomic services since API version 16. - -**System capability**: SystemCapability.ArkUI.ArkUI.Full - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | --------------------------------------------- | ---- | --------------------------------------------- | -| scale | number \| [Resource](ts-types.md#resource) | Yes | Minimum font scale factor for text.
Value range: [0, 1]
**NOTE**
A value less than 0 is handled as 0. A value greater than 1 is handled as 1. Abnormal values are ineffective by default.| - -### maxFontScale16+ - -maxFontScale(scale: number | Resource) - -Sets the maximum font scale factor for text. - -**Atomic service API**: This API can be used in atomic services since API version 16. - -**System capability**: SystemCapability.ArkUI.ArkUI.Full - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | --------------------------------------------- | ---- | --------------------------------------------- | -| scale | number \| [Resource](ts-types.md#resource) | Yes | Maximum font scale factor for text.
Value range: [1, +∞)
**NOTE**
A value less than 1 is handled as 1. Abnormal values are ineffective by default.| +| value | number \| string \| [Resource](ts-types.md#resource) | Yes | Maximum font size.
Unit: fp| ### heightAdaptivePolicy12+ @@ -917,9 +881,9 @@ showPassword(visible: boolean) Sets whether to show the password. -This attribute takes effect only in password input mode. +This API has effect only when the [input type](#inputtype) is set to **Password**, **NEWPASSWORD**, or **NUMBERPASSWORD** mode. It does not work in other modes. -In password input mode, the icon at the end of the text box serves as a toggle for password visibility. As such, you are advised to implement status synchronization with [onSecurityStateChange](#onsecuritystatechange12) to ensure that the password visibility status is accurately reflected. +When in password mode, there may be inconsistency between the backend state of the text box and the frontend application's state management variables. This can cause issues with the icon at the end of the password text box. To avoid such issues, use the [onSecurityStateChange](#onsecuritystatechange12) callback to sync the states. For details, see [Example 1](#example-1-setting-and-obtaining-the-cursor-position). **Atomic service API**: This API can be used in atomic services since API version 12. @@ -981,18 +945,6 @@ Preview text is in a temporary state and does not support text interception. As | ------ | ------- | ---- | ---------------------------------- | | enable | boolean | Yes | Whether to enable preview text.
Default value: **true**| -> **NOTE** -> -> This API is disabled by default in C API scenarios. To enable preview text in such scenarios, set [metadata](../../../../application-dev/quick-start/module-structure.md#internal-structure-of-the-metadata-attribute) in the **module.json5** file of the project as follows: -> ```json -> "metadata": [ -> { -> "name": "can_preview_text", -> "value": "true", -> } -> ] -> ``` - ### enableHapticFeedback13+ enableHapticFeedback(isEnabled: boolean) @@ -1020,31 +972,29 @@ Specifies whether to enable haptic feedback. > ] > ``` -### cancelButton16+ +### keyboardAppearance15+ -cancelButton(value: CancelButtonSymbolOptions) +keyboardAppearance(appearance: Optional\) -Sets the style of the cancel button on the right. This attribute is not available for the inline input style. +Sets the appearance of the keyboard when the text box is focused. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 15. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| value | [CancelButtonSymbolOptions](ts-basic-components-search.md#cancelbuttonsymboloptions12) | Yes | Style of the cancel button on the right.
Default value:
{
style: CancelButtonStyle.INPUT
} | - -### ellipsisMode16+ +| Name| Type| Mandatory| Description| +| ------ | ----------------------------------------- | ---- | ------------------------------------------------------ | +| appearance | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[KeyboardAppearance](ts-text-common.md#keyboardappearance15)> | Yes | Appearance of the keyboard.
Default value: **KeyboardAppearance.NONE_IMMERSIVE**| -ellipsisMode(value: EllipsisMode) +### stopBackPress15+ -Sets the ellipsis position. For the settings to work, **overflow** must be set to **TextOverflow.Ellipsis**. Setting **ellipsisMode** alone does not take effect. +stopBackPress(isStopped: Optional\) -**ellipsisMode** is effective only in inline mode. +Sets whether to prevent the back button press from being propagated to other components or applications. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 15. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -1052,15 +1002,81 @@ Sets the ellipsis position. For the settings to work, **overflow** must be set t | Name| Type | Mandatory| Description | | ------ | --------------------------------------------------- | ---- | ----------------------------------------- | -| value | [EllipsisMode](ts-basic-components-richeditor#ellipsismode16) | Yes | Ellipsis position.
Default value: **EllipsisMode.END**| +| isStopped | [Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Whether to consume the back button press.
Default value: **true**| -### stopBackPress16+ +### halfLeading18+ -stopBackPress(isStopped: boolean) +halfLeading(halfLeading: Optional\) -Sets whether to prevent the back button press from being propagated to other components or applications. +Sets whether half leading is enabled. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | --------------------------------------------- | ---- | --------------------------------------------- | +| halfLeading | [Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Whether half leading is enabled.
Half leading is the leading split in half and applied equally to the top and bottom edges. The value **true** means that half leading is enabled, and **false** means the opposite.
Default value: **false**| + +### minFontScale18+ + +minFontScale(scale: Optional\) + +Sets the minimum font scale factor for text. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | --------------------------------------------- | ---- | --------------------------------------------- | +| scale | [Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Minimum font scale factor for text. The **undefined** type is supported.
Value range: [0, 1]
**NOTE**
A value less than 0 is handled as 0. A value greater than 1 is handled as 1. Abnormal values are ineffective by default.| + +### maxFontScale18+ + +maxFontScale(scale: Optional\) + +Sets the maximum font scale factor for text. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | --------------------------------------------- | ---- | --------------------------------------------- | +| scale | [Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Maximum font scale factor for text. The **undefined** type is supported.
Value range: [1, +∞)
**NOTE**
A value less than 1 is handled as 1. Abnormal values are ineffective by default.| + +### cancelButton18+ + +cancelButton(symbolOptions: CancelButtonSymbolOptions) + +Sets the style of the cancel button on the right. This attribute is not available for the inline input style. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| symbolOptions | [CancelButtonSymbolOptions](ts-basic-components-search.md#cancelbuttonsymboloptions12) | Yes | Style of the cancel button on the right.
Default value:
{
style: CancelButtonStyle.INPUT
} | + +### ellipsisMode18+ + +ellipsisMode(mode: Optional\) + +Sets the ellipsis position. For the settings to work, **overflow** must be set to **TextOverflow.Ellipsis**. Setting **ellipsisMode** alone does not take effect. + +**EllipsisMode.START** and **EllipsisMode.CENTER** take effect only when **maxLines** is set to **1** in inline style. + +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -1068,7 +1084,7 @@ Sets whether to prevent the back button press from being propagated to other com | Name| Type | Mandatory| Description | | ------ | --------------------------------------------------- | ---- | ----------------------------------------- | -| isStopped | boolean | Yes | Whether to consume the back button press.
Default value: **true**| +| mode | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[EllipsisMode](ts-appendix-enums.md#ellipsismode11)> | Yes | Ellipsis position.
Default value: **EllipsisMode.END**| ## InputType @@ -1078,7 +1094,7 @@ Sets whether to prevent the back button press from being propagated to other com | ----------------------------- | ------------------------------------------------------------ | | Normal | Normal input mode. In this mode, there is no special restriction on the input characters.
**Atomic service API**: This API can be used in atomic services since API version 11.| | Password | Password input mode.
An eye icon is used to show or hide the password. By default, the entered characters are temporarily shown before being obscured by dots; they are directly obscured by dots since API version 12 on certain devices. The password input mode does not support underlines. If Password Vault is enabled, autofill is available for the username and password.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| Email | Email address input mode.
This mode accepts only digits, letters, underscores (_), dots (.), and the following special characters: ! # $ % & ' * + - / = ? ^ ` \{ \| \} ~ @ (which can only appear once)
**Atomic service API**: This API can be used in atomic services since API version 11.| +| Email | Email address input mode.
This mode accepts only digits, letters, underscores (_), dots (.), and the following special characters: ! # $ % & ' " * + - / = ? ^ ` \{ \| \} ~ @ (which can only appear once)
**Atomic service API**: This API can be used in atomic services since API version 11.| | Number | Digit input mode.
**Atomic service API**: This API can be used in atomic services since API version 11.| | PhoneNumber9+ | Phone number input mode.
In this mode, the following are allowed: digits, spaces, plus signs (+), hyphens (-), asterisks (*), and number signs (#); the length is not limited.
**Atomic service API**: This API can be used in atomic services since API version 11.| | USER_NAME11+ | Username input mode.
If Password Vault is enabled, autofill is available for the username and password.
**Atomic service API**: This API can be used in atomic services since API version 12.| @@ -1091,33 +1107,43 @@ Sets whether to prevent the back button press from being propagated to other com Enumerates the content types for autofill. -**Atomic service API**: This API can be used in atomic services since API version 12. - **System capability**: SystemCapability.ArkUI.ArkUI.Full | Name | Value | Description | | -------------------------- | ---- | ------------------------------------------------------------ | -| USER_NAME | 0 | Username. Password Vault, when enabled, can automatically save and fill in usernames.| -| PASSWORD | 1 | Password. Password Vault, when enabled, can automatically save and fill in passwords.| -| NEW_PASSWORD | 2 | New password. Password Vault, when enabled, can automatically generate a new password. | -| FULL_STREET_ADDRESS | 3 | Full street address. The scenario-based autofill feature, when enabled, can automatically save and fill in full street addresses.| -| HOUSE_NUMBER | 4 | House number. The scenario-based autofill feature, when enabled, can automatically save and fill in house numbers.| -| DISTRICT_ADDRESS | 5 | District and county. The scenario-based autofill feature, when enabled, can automatically save and fill in districts and counties.| -| CITY_ADDRESS | 6 | City. The scenario-based autofill feature, when enabled, can automatically save and fill in cities.| -| PROVINCE_ADDRESS | 7 | Province. The scenario-based autofill feature, when enabled, can automatically save and fill in provinces.| -| COUNTRY_ADDRESS | 8 | Country. The scenario-based autofill feature, when enabled, can automatically save and fill in countries.| -| PERSON_FULL_NAME | 9 | Full name. The scenario-based autofill feature, when enabled, can automatically save and fill in full names.| -| PERSON_LAST_NAME | 10 | Last name. The scenario-based autofill feature, when enabled, can automatically save and fill in last names.| -| PERSON_FIRST_NAME | 11 | First name. The scenario-based autofill feature, when enabled, can automatically save and fill in first names.| -| PHONE_NUMBER | 12 | Phone number. The scenario-based autofill feature, when enabled, can automatically save and fill in phone numbers.| -| PHONE_COUNTRY_CODE | 13 | Country code. The scenario-based autofill feature, when enabled, can automatically save and fill in country codes.| -| FULL_PHONE_NUMBER | 14 | Phone number with country code. The scenario-based autofill feature, when enabled, can automatically save and fill in phone numbers with country codes.| -| EMAIL_ADDRESS | 15 | Email address. The scenario-based autofill feature, when enabled, can automatically save and fill in email addresses.| -| BANK_CARD_NUMBER | 16 | Bank card number. The scenario-based autofill feature, when enabled, can automatically save and fill in bank card numbers.| -| ID_CARD_NUMBER | 17 | ID card number. The scenario-based autofill feature, when enabled, can automatically save and fill in ID card numbers.| -| NICKNAME | 23 | Nickname. The scenario-based autofill feature, when enabled, can automatically save and fill in nicknames.| -| DETAIL_INFO_WITHOUT_STREET | 24 | Address information without street address. The scenario-based autofill feature, when enabled, can automatically save and fill in address information without street addresses.| -| FORMAT_ADDRESS | 25 | Standard address. The scenario-based autofill feature, when enabled, can automatically save and fill in standard addresses.| +| USER_NAME | 0 | Username. Password Vault, when enabled, can automatically save and fill in usernames.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| PASSWORD | 1 | Password. Password Vault, when enabled, can automatically save and fill in passwords.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| NEW_PASSWORD | 2 | New password. Password Vault, when enabled, can automatically generate a new password.
**Atomic service API**: This API can be used in atomic services since API version 12. | +| FULL_STREET_ADDRESS | 3 | Full street address. The scenario-based autofill feature, when enabled, can automatically save and fill in full street addresses.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| HOUSE_NUMBER | 4 | House number. The scenario-based autofill feature, when enabled, can automatically save and fill in house numbers.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| DISTRICT_ADDRESS | 5 | District and county. The scenario-based autofill feature, when enabled, can automatically save and fill in districts and counties.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| CITY_ADDRESS | 6 | City. The scenario-based autofill feature, when enabled, can automatically save and fill in cities.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| PROVINCE_ADDRESS | 7 | Province. The scenario-based autofill feature, when enabled, can automatically save and fill in provinces.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| COUNTRY_ADDRESS | 8 | Country. The scenario-based autofill feature, when enabled, can automatically save and fill in countries.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| PERSON_FULL_NAME | 9 | Full name. The scenario-based autofill feature, when enabled, can automatically save and fill in full names.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| PERSON_LAST_NAME | 10 | Last name. The scenario-based autofill feature, when enabled, can automatically save and fill in last names.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| PERSON_FIRST_NAME | 11 | First name. The scenario-based autofill feature, when enabled, can automatically save and fill in first names.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| PHONE_NUMBER | 12 | Phone number. The scenario-based autofill feature, when enabled, can automatically save and fill in phone numbers.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| PHONE_COUNTRY_CODE | 13 | Country code. The scenario-based autofill feature, when enabled, can automatically save and fill in country codes.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| FULL_PHONE_NUMBER | 14 | Phone number with country code. The scenario-based autofill feature, when enabled, can automatically save and fill in phone numbers with country codes.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| EMAIL_ADDRESS | 15 | Email address. The scenario-based autofill feature, when enabled, can automatically save and fill in email addresses.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| BANK_CARD_NUMBER | 16 | Bank card number. The scenario-based autofill feature, when enabled, can automatically save and fill in bank card numbers.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| ID_CARD_NUMBER | 17 | ID card number. The scenario-based autofill feature, when enabled, can automatically save and fill in ID card numbers.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| NICKNAME | 23 | Nickname. The scenario-based autofill feature, when enabled, can automatically save and fill in nicknames.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| DETAIL_INFO_WITHOUT_STREET | 24 | Address information without street address. The scenario-based autofill feature, when enabled, can automatically save and fill in address information without street addresses.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| FORMAT_ADDRESS | 25 | Standard address. The scenario-based autofill feature, when enabled, can automatically save and fill in standard addresses.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| PASSPORT_NUMBER18+ | 26 | Passport number. The scenario-based autofill feature, when enabled, can automatically save and fill in passport numbers.
**Atomic service API**: This API can be used in atomic services since API version 18.| +| VALIDITY18+ | 27 | Passport validity period. The scenario-based autofill feature, when enabled, can automatically save and fill in passport validity periods.
**Atomic service API**: This API can be used in atomic services since API version 18.| +| ISSUE_AT18+ | 28 | Passport place of issue. The scenario-based autofill feature, when enabled, can automatically save and fill in the place of issue for passports.
**Atomic service API**: This API can be used in atomic services since API version 18.| +| ORGANIZATION18+ | 29 | Invoice title. The scenario-based autofill feature, when enabled, can automatically save and fill in invoice titles.
**Atomic service API**: This API can be used in atomic services since API version 18.| +| TAX_ID18+ | 30 | Tax ID. The scenario-based autofill feature, when enabled, can automatically save and fill in tax IDs.
**Atomic service API**: This API can be used in atomic services since API version 18.| +| ADDRESS_CITY_AND_STATE18+ | 31 | Location. The scenario-based autofill feature, when enabled, can automatically save and fill in locations.
**Atomic service API**: This API can be used in atomic services since API version 18.| +| FLIGHT_NUMBER18+ | 32 | Flight number. Currently not supported for automatic saving and auto-filling.
**Atomic service API**: This API can be used in atomic services since API version 18.| +| LICENSE_NUMBER18+ | 33 | Driver's license number. Currently not supported for automatic saving and auto-filling.
**Atomic service API**: This API can be used in atomic services since API version 18.| +| LICENSE_FILE_NUMBER18+ | 34 | Driver's license file number. Currently not supported for automatic saving and auto-filling.
**Atomic service API**: This API can be used in atomic services since API version 18.| +| LICENSE_PLATE18+ | 35 | License plate number. The scenario-based autofill feature, when enabled, can automatically save and fill in license plate numbers.
**Atomic service API**: This API can be used in atomic services since API version 18.| +| ENGINE_NUMBER18+ | 36 | Vehicle registration engine number. Currently not supported for automatic saving and auto-filling.
**Atomic service API**: This API can be used in atomic services since API version 18.| +| LICENSE_CHASSIS_NUMBER18+ | 37 | Chassis number. Currently not supported for automatic saving and auto-filling.
**Atomic service API**: This API can be used in atomic services since API version 18.| ## TextInputStyle9+ @@ -1138,8 +1164,8 @@ Enumerates the content types for autofill. | Name| Type | Mandatory | Description| | ---- | ----- | ---- | ---- | -| onIconSrc | string \| [Resource](ts-types.md#resource) | No | Icon that can be used to hide the password in password input mode.| -| offIconSrc | string \| [Resource](ts-types.md#resource) | No | Icon that can be used to show the password in password input mode.| +| onIconSrc | string \| [Resource](ts-types.md#resource) | No | Icon that can be used to hide the password in password input mode.
The string type can be used to load network images and local images.| +| offIconSrc | string \| [Resource](ts-types.md#resource) | No | Icon that can be used to show the password in password input mode.
The string type can be used to load network images and local images.| ## EnterKeyType @@ -1147,20 +1173,20 @@ Enumerates the Enter key types. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Description | -| ---------------------- | ------------------ | -| Go | The Enter key is labeled "Go."
**Atomic service API**: This API can be used in atomic services since API version 11. | -| Search | The Enter key is labeled "Search."
**Atomic service API**: This API can be used in atomic services since API version 11. | -| Send | The Enter key is labeled "Send."
**Atomic service API**: This API can be used in atomic services since API version 11. | -| Next | The Enter key is labeled "Next."
**Atomic service API**: This API can be used in atomic services since API version 11.| -| Done | The Enter key is labeled "Done."
**Atomic service API**: This API can be used in atomic services since API version 11. | -| PREVIOUS11+ | The Enter key is labeled "Previous."
**Atomic service API**: This API can be used in atomic services since API version 12.| -| NEW_LINE11+ | The Enter key is labeled "New Line."
**Atomic service API**: This API can be used in atomic services since API version 12. | +| Name | Value| Description | +| ---------------------- | --- | ------------------ | +| Go | 2 | The Enter key is labeled "Go."
**Atomic service API**: This API can be used in atomic services since API version 11. | +| Search | 3 | The Enter key is labeled "Search."
**Atomic service API**: This API can be used in atomic services since API version 11. | +| Send | 4 | The Enter key is labeled "Send."
**Atomic service API**: This API can be used in atomic services since API version 11. | +| Next | 5 | The Enter key is labeled "Next."
**Atomic service API**: This API can be used in atomic services since API version 11.| +| Done | 6 | The Enter key is labeled "Done."
**Atomic service API**: This API can be used in atomic services since API version 11. | +| PREVIOUS11+ | 7 | The Enter key is labeled "Previous."
**Atomic service API**: This API can be used in atomic services since API version 12.| +| NEW_LINE11+ | 8 | The Enter key is labeled "New Line."
**Atomic service API**: This API can be used in atomic services since API version 12. | ## Events -In addition to the [universal events](ts-universal-events-click.md), the following events are supported. +In addition to the [universal events](ts-component-general-events.md), the following events are supported. ### onChange @@ -1182,7 +1208,7 @@ In this callback, if cursor operations are performed, you need to adjust the cur ### onSubmit -onSubmit(callback:OnSubmitCallback) +onSubmit(callback: OnSubmitCallback) Triggered when the Enter key on the keyboard is pressed for submission. @@ -1194,7 +1220,7 @@ Triggered when the Enter key on the keyboard is pressed for submission. | Name | Type | Mandatory| Description | | ------------------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ | -| callback | [OnSubmitCallback](#onsubmitcallback14) | Yes | Callback for submission.| +| callback | [OnSubmitCallback](#onsubmitcallback18) | Yes | Callback for submission.| ### onEditChanged(deprecated) @@ -1214,7 +1240,7 @@ This API is deprecated since API version 8. You are advised to use **onEditChang ### onEditChange8+ -onEditChange(callback:Callback\) +onEditChange(callback: Callback\) Triggered when the input status changes. The text box is in the editing state when it has the caret placed in it, and is in the non-editing state otherwise. @@ -1230,7 +1256,7 @@ Triggered when the input status changes. The text box is in the editing state wh ### onCopy8+ -onCopy(callback:Callback\) +onCopy(callback: Callback\) Triggered when a copy operation is performed. @@ -1246,7 +1272,7 @@ Triggered when a copy operation is performed. ### onCut8+ -onCut(callback:Callback\) +onCut(callback: Callback\) Triggered when a cut operation is performed. @@ -1262,7 +1288,7 @@ Triggered when a cut operation is performed. ### onPaste8+ -onPaste(callback:OnPasteCallback ) +onPaste(callback: OnPasteCallback) Triggered when a paste operation is performed. @@ -1273,7 +1299,7 @@ Triggered when a paste operation is performed. **Parameters** | Name | Type | Mandatory| Description | | ------------------- | ------------------------------------------------------------ | ---- | ---------------------- | -| callback | [OnPasteCallback](#onpastecallback14) | Yes | Callback used to return the pasted text content.| +| callback | [OnPasteCallback](#onpastecallback18) | Yes | Callback used to return the pasted text content.| ### onTextSelectionChange10+ @@ -1289,7 +1315,7 @@ Triggered when the position of the text selection changes or when the cursor pos | Name | Type | Mandatory| Description | | -------------- | ------ | ---- | --------------------------------------- | -| callback | [OnTextSelectionChangeCallback](#ontextselectionchangecallback14) | Yes | Callback for text selection changes or cursor position changes.| +| callback | [OnTextSelectionChangeCallback](#ontextselectionchangecallback18) | Yes | Callback for text selection changes or cursor position changes.| ### onContentScroll10+ @@ -1305,7 +1331,7 @@ Triggered when the text content is scrolled. | Name | Type | Mandatory| Description | | ------------ | ------ | ---- | ---------------------------------- | -| callback | [OnContentScrollCallback](#oncontentscrollcallback14) | Yes | Callback for text content scrolling.| +| callback | [OnContentScrollCallback](#oncontentscrollcallback18) | Yes | Callback for text content scrolling.| ### onSecurityStateChange12+ @@ -1337,7 +1363,7 @@ Triggered when text is about to be inserted. | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------ | -| callback | Callback\<[InsertValue](ts-text-common.md#insertvalue12), boolean> | Yes | Callback triggered when text is about to be inserted.
It returns **true** if the text is inserted; returns **false** otherwise.
This callback is not called for text preview.
It is available only for system input methods.| +| callback | Callback\<[InsertValue](ts-text-common.md#insertvalue12), boolean> | Yes | Callback triggered when text is about to be inserted.
It returns **true** if the text is inserted; returns **false** otherwise.
This callback is not triggered for pre-edit or candidate word operations.
It is available only for system input methods.| ### onDidInsert12+ @@ -1387,6 +1413,24 @@ Triggered when text is deleted. | ------ | ------------------------------------------------------------ | ---- | ------------------ | | callback | Callback\<[DeleteValue](ts-text-common.md#deletevalue12)> | Yes | Callback triggered when text is deleted.
It is available only for system input methods.| +### onWillChange15+ + +onWillChange(callback: Callback\) + +Called when the text content is about to change. + +This callback is triggered after **onWillInsert** and **onWillDelete**, but before **onDidInsert** and **onDidDelete**. + +**Atomic service API**: This API can be used in atomic services since API version 15. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------ | +| callback | Callback\<[EditableTextChangeValue](ts-text-common.md#editabletextchangevalue15), boolean> | Yes | Callback triggered when the text content is about to change.
Returning **true** allows the change to proceed, while returning **false** cancels the change.| + ## TextInputController8+ Inherits from [TextContentControllerBase](ts-types.md#textcontentcontrollerbase10). @@ -1414,7 +1458,7 @@ A constructor used to create a **TextInputController** object. caretPosition(value: number): void -Sets the position of the caret. +Sets the position of the caret. If the value is less than 0, the value **0** is used. If the value exceeds the text length, the caret is placed at the end of the text. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -1482,7 +1526,7 @@ Defines the user submission event. **System capability**: SystemCapability.ArkUI.ArkUI.Full -### Attributes +### Properties **Atomic service API**: This API can be used in atomic services since API version 11. @@ -1502,13 +1546,13 @@ Maintains the editable state of the text box when called. **System capability**: SystemCapability.ArkUI.ArkUI.Full -## OnPasteCallback14+ +## OnPasteCallback18+ type OnPasteCallback = (content: string, event: PasteEvent) => void Defines the callback used to return the pasted text content. -**Atomic service API**: This API can be used in atomic services since API version 14. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -1519,13 +1563,13 @@ Defines the callback used to return the pasted text content. | content | string | Yes | Text to be pasted. | | event | [PasteEvent](ts-basic-components-richeditor.md#pasteevent11) | Yes | Custom paste event.| -## OnSubmitCallback14+ +## OnSubmitCallback18+ type OnSubmitCallback = (enterKey: EnterKeyType, event: SubmitEvent) => void Defines the callback for submission. -**Atomic service API**: This API can be used in atomic services since API version 14. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -1536,13 +1580,13 @@ Defines the callback for submission. | enterKey | [EnterKeyType](#enterkeytype) | Yes | Type of the Enter key.| | event | [SubmitEvent](#submitevent11) | Yes | Submit event. | -## OnTextSelectionChangeCallback14+ +## OnTextSelectionChangeCallback18+ type OnTextSelectionChangeCallback = (selectionStart: number, selectionEnd: number) => void Defines the callback for text selection changes or cursor position changes. -**Atomic service API**: This API can be used in atomic services since API version 14. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -1553,13 +1597,13 @@ Defines the callback for text selection changes or cursor position changes. | selectionStart | number | Yes | Start position of the selected text. The start position of text is **0**.| | selectionEnd | number | Yes | End position of the selected text. | -## OnContentScrollCallback14+ +## OnContentScrollCallback18+ type OnContentScrollCallback = (totalOffsetX: number, totalOffsetY: number) => void Defines the callback for text content scrolling. -**Atomic service API**: This API can be used in atomic services since API version 14. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -1588,7 +1632,8 @@ struct TextInputExample { build() { Column() { - TextInput({ text: this.text, placeholder: 'input your word...', controller: this.controller }) + // Use !! to implement two-way binding of the text parameter. + TextInput({ text: this.text!!, placeholder: 'input your word...', controller: this.controller }) .placeholderColor(Color.Grey) .placeholderFont({ size: 14, weight: 400 }) .caretColor(Color.Blue) @@ -1600,9 +1645,6 @@ struct TextInputExample { .inputFilter('[a-z]', (e) => { console.log(JSON.stringify(e)) }) - .onChange((value: string) => { - this.text = value - }) Text(this.text) Button('Set caretPosition 1') .margin(15) @@ -1626,7 +1668,7 @@ struct TextInputExample { .showPassword(this.passwordState) .onSecurityStateChange(((isShowPassword: boolean) => { // Update the password visibility. - console.info('isShowPassword',isShowPassword) + console.info('isShowPassword', isShowPassword) this.passwordState = isShowPassword })) // Email address autofill. @@ -1648,23 +1690,25 @@ struct TextInputExample { } ``` -![TextInput](figures/TextInput.png) +![TextInput](figures/TextInput.gif) ### Example 2: Setting Underlines This example showcases the effects of underlines in different scenarios using the **showUnderline**, **showError**, **showUnit**, and **passwordIcon** attributes. ```ts +// xxx.ets @Entry @Component struct TextInputExample { - @State passWordSrc1: Resource = $r('app.media.ImageOne') - @State passWordSrc2: Resource = $r('app.media.ImageTwo') - @State textError: string = '' - @State text: string = '' - @State nameText: string = 'test' + @State passWordSrc1: Resource = $r('app.media.ImageOne'); + @State passWordSrc2: Resource = $r('app.media.ImageTwo'); + @State textError: string = ''; + @State text: string = ''; + @State nameText: string = 'test'; - @Builder itemEnd() { + @Builder + itemEnd() { Select([{ value: 'KB' }, { value: 'MB' }, { value: 'GB' }, @@ -1679,9 +1723,14 @@ struct TextInputExample { .selectedOptionFont({ size: 20, weight: 400 }) .optionFont({ size: 20, weight: 400 }) .backgroundColor(Color.Transparent) - .responseRegion({ height: "40vp", width: "80%", x: '10%', y: '6vp' }) + .responseRegion({ + height: "40vp", + width: "80%", + x: '10%', + y: '6vp' + }) .onSelect((index: number) => { - console.info('Select:' + index) + console.info('Select:' + index); }) } @@ -1713,12 +1762,12 @@ struct TextInputExample { .onSubmit((enterKey: EnterKeyType, event: SubmitEvent) => { // If the entered user name is incorrect, clear the text box and display an error message. if (this.text == this.nameText) { - this.textError = '' + this.textError = ''; } else { - this.textError = 'Incorrect user name.' - this.text = '' + this.textError = 'Incorrect user name.'; + this.text = ''; // Call keepEditableState to maintain the editable state of the text box. - event.keepEditableState() + event.keepEditableState(); } }) // Set the color of the underline. @@ -1752,22 +1801,23 @@ This example demonstrates how to implement a custom keyboard using the **customK @Entry @Component struct TextInputExample { - controller: TextInputController = new TextInputController() - @State inputValue: string = "" + controller: TextInputController = new TextInputController(); + @State inputValue: string = ""; // Create a custom keyboard component. - @Builder CustomKeyboardBuilder() { + @Builder + CustomKeyboardBuilder() { Column() { Button('x').onClick(() => { // Disable the custom keyboard. - this.controller.stopEditing() + this.controller.stopEditing(); }) Grid() { - ForEach([1, 2, 3, 4, 5, 6, 7, 8, 9, '*', 0, '#'], (item:number|string) => { + ForEach([1, 2, 3, 4, 5, 6, 7, 8, 9, '*', 0, '#'], (item: number | string) => { GridItem() { Button(item + "") .width(110).onClick(() => { - this.inputValue += item + this.inputValue += item; }) } }) @@ -1777,8 +1827,7 @@ struct TextInputExample { build() { Column() { - TextInput({ controller: this.controller, text: this.inputValue }) - // Bind the custom keyboard. + TextInput({ controller: this.controller, text: this.inputValue })// Bind a custom keyboard. .customKeyboard(this.CustomKeyboardBuilder()).margin(10).border({ width: 1 }).height('48vp') } } @@ -1796,8 +1845,8 @@ This example demonstrates how to use the **cancelButton** attribute to customize @Entry @Component struct TextInputExample { - @State text: string = '' - controller: TextInputController = new TextInputController() + @State text: string = ''; + controller: TextInputController = new TextInputController(); build() { Column() { @@ -1808,12 +1857,12 @@ struct TextInputExample { style: CancelButtonStyle.CONSTANT, icon: { size: 45, - src: $r('app.media.icon'), + src: $r('app.media.app_icon'), color: Color.Blue } }) .onChange((value: string) => { - this.text = value + this.text = value; }) } } @@ -1831,8 +1880,8 @@ This example showcases the implementation of a counter feature using the **maxLe @Entry @Component struct TextInputExample { - @State text: string = '' - controller: TextInputController = new TextInputController() + @State text: string = ''; + controller: TextInputController = new TextInputController(); build() { Column() { @@ -1842,12 +1891,12 @@ struct TextInputExample { .height(56) .maxLength(6) .showUnderline(true) - .showCounter(true, { thresholdPercentage: 50, highlightBorder: true }) - // The character counter is in this format: Number of characters that have been entered/Maximum number of characters allowed, which is specified by maxLength(). - // The character counter is displayed when the number of characters that have been entered is greater than the maximum number of characters multiplied by 50% (threshold percentage). - // When highlightBorder is set to false, the text box border turns red when the number of entered characters reaches the maximum. The default value is true. + .showCounter(true, + { thresholdPercentage: 50, highlightBorder: true })// The character counter is in this format: Number of characters that have been entered/Maximum number of characters allowed, which is specified by maxLength(). + // The character counter is displayed when the number of characters that have been entered is greater than the maximum number of characters multiplied by 50% (threshold percentage). + // When highlightBorder is set to false, the text box border turns red when the number of entered characters reaches the maximum. The default value is true. .onChange((value: string) => { - this.text = value + this.text = value; }) }.width('100%').height('100%').backgroundColor('#F1F3F5') } @@ -1862,33 +1911,34 @@ struct TextInputExample { This example illustrates how to format phone numbers using the **onChange callback** API. ```ts +// xxx.ets @Entry @Component struct TextInputExample { - @State submitValue: string = '' - @State text: string = '' - public readonly NUM_TEXT_MAXSIZE_LENGTH = 13 - @State teleNumberNoSpace: string = "" - @State nextCaret: number = -1 // Used to record the position for the next caret setting - @State actualCh: number = -1 // Used to record the insertion or deletion position relative to the i-th digit of the caret - @State lastCaretPosition: number = 0 - @State lastCaretPositionEnd: number = 0 - controller: TextInputController = new TextInputController() + @State submitValue: string = ''; + @State text: string = ''; + public readonly NUM_TEXT_MAXSIZE_LENGTH = 13; + @State teleNumberNoSpace: string = ""; + @State nextCaret: number = -1; // Used to record the position for the next caret setting. + @State actualCh: number = -1; // Used to record the insertion or deletion position relative to the i-th digit of the caret. + @State lastCaretPosition: number = 0; + @State lastCaretPositionEnd: number = 0; + controller: TextInputController = new TextInputController(); isEmpty(str?: string): boolean { - return str == 'undefined' || !str || !new RegExp("[^\\s]").test(str) + return str == 'undefined' || !str || !new RegExp("[^\\s]").test(str); } checkNeedNumberSpace(numText: string) { - let isSpace: RegExp = new RegExp('[\\+;,#\\*]', 'g') - let isRule: RegExp = new RegExp('^\\+.*') + let isSpace: RegExp = new RegExp('[\\+;,#\\*]', 'g'); + let isRule: RegExp = new RegExp('^\\+.*'); if (isSpace.test(numText)) { // If the phone number contains special characters, no space is added. if (isRule.test(numText)) { - return true + return true; } else { - return false + return false; } } return true; @@ -1896,61 +1946,61 @@ struct TextInputExample { removeSpace(str: string): string { if (this.isEmpty(str)) { - return '' + return ''; } - return str.replace(new RegExp("[\\s]", "g"), '') + return str.replace(new RegExp("[\\s]", "g"), ''); } setCaret() { if (this.nextCaret != -1) { - console.log("to keep caret position right, change caret to", this.nextCaret) - this.controller.caretPosition(this.nextCaret) - this.nextCaret = -1 + console.log("to keep caret position right, change caret to", this.nextCaret); + this.controller.caretPosition(this.nextCaret); + this.nextCaret = -1; } } calcCaretPosition(nextText: string) { - let befNumberNoSpace: string = this.removeSpace(this.text) - this.actualCh = 0 + let befNumberNoSpace: string = this.removeSpace(this.text); + this.actualCh = 0; if (befNumberNoSpace.length < this.teleNumberNoSpace.length) { // Insertion scenario for (let i = 0; i < this.lastCaretPosition; i++) { if (this.text[i] != ' ') { - this.actualCh += 1 + this.actualCh += 1; } } - this.actualCh += this.teleNumberNoSpace.length - befNumberNoSpace.length - console.log("actualCh: " + this.actualCh) + this.actualCh += this.teleNumberNoSpace.length - befNumberNoSpace.length; + console.log("actualCh: " + this.actualCh); for (let i = 0; i < nextText.length; i++) { if (nextText[i] != ' ') { - this.actualCh -= 1 + this.actualCh -= 1; if (this.actualCh <= 0) { - this.nextCaret = i + 1 + this.nextCaret = i + 1; break; } } } } else if (befNumberNoSpace.length > this.teleNumberNoSpace.length) { // Deletion scenario if (this.lastCaretPosition === this.text.length) { - console.log("Caret at last, no need to change") + console.log("Caret at last, no need to change"); } else if (this.lastCaretPosition === this.lastCaretPositionEnd) { // Scenario where the backspace key on the keyboard is used to delete characters one by one for (let i = this.lastCaretPosition; i < this.text.length; i++) { if (this.text[i] != ' ') { - this.actualCh += 1 + this.actualCh += 1; } } for (let i = nextText.length - 1; i >= 0; i--) { if (nextText[i] != ' ') { - this.actualCh -= 1 + this.actualCh -= 1; if (this.actualCh <= 0) { - this.nextCaret = i + this.nextCaret = i; break; } } } } else { // When cutting or selecting text with a handle to delete multiple characters at once - this.nextCaret = this.lastCaretPosition // Maintain the caret position. + this.nextCaret = this.lastCaretPosition; // Maintain the caret position. } } } @@ -1961,39 +2011,39 @@ struct TextInputExample { TextInput({ text: `${this.text}`, controller: this.controller }).type(InputType.PhoneNumber).height('48vp') .onChange((number: string) => { this.teleNumberNoSpace = this.removeSpace(number); - let nextText: string = "" + let nextText: string = ""; if (this.teleNumberNoSpace.length > this.NUM_TEXT_MAXSIZE_LENGTH - 2) { - nextText = this.teleNumberNoSpace + nextText = this.teleNumberNoSpace; } else if (this.checkNeedNumberSpace(number)) { if (this.teleNumberNoSpace.length <= 3) { - nextText = this.teleNumberNoSpace + nextText = this.teleNumberNoSpace; } else { - let split1: string = this.teleNumberNoSpace.substring(0, 3) - let split2: string = this.teleNumberNoSpace.substring(3) - nextText = split1 + ' ' + split2 + let split1: string = this.teleNumberNoSpace.substring(0, 3); + let split2: string = this.teleNumberNoSpace.substring(3); + nextText = split1 + ' ' + split2; if (this.teleNumberNoSpace.length > 7) { - split2 = this.teleNumberNoSpace.substring(3, 7) - let split3: string = this.teleNumberNoSpace.substring(7) - nextText = split1 + ' ' + split2 + ' ' + split3 + split2 = this.teleNumberNoSpace.substring(3, 7); + let split3: string = this.teleNumberNoSpace.substring(7); + nextText = split1 + ' ' + split2 + ' ' + split3; } } } else { - nextText = number + nextText = number; } - console.log("onChange Triggered:" + this.text + "|" + nextText + "|" + number) + console.log("onChange Triggered:" + this.text + "|" + nextText + "|" + number); if (this.text === nextText && nextText === number) { // The number has been formatted. Changing the caret position at this time will not reset the number. - this.setCaret() + this.setCaret(); } else { - this.calcCaretPosition(nextText) + this.calcCaretPosition(nextText); } - this.text = nextText + this.text = nextText; }) .onTextSelectionChange((selectionStart, selectionEnd) => { // Record the caret position. - console.log("selection change: ", selectionStart, selectionEnd) - this.lastCaretPosition = selectionStart - this.lastCaretPositionEnd = selectionEnd + console.log("selection change: ", selectionStart, selectionEnd); + this.lastCaretPosition = selectionStart; + this.lastCaretPositionEnd = selectionEnd; }) } } @@ -2013,50 +2063,53 @@ This example demonstrates the effects of different text wrapping rules using the @Entry @Component struct TextInputExample { - build() { - Column() { - Text("WordBreakType as NORMAL in the inline input style:").fontSize(16).fontColor(0xFF0000) - TextInput({ - text: 'This is set wordBreak to WordBreak text Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu.' - }) - .fontSize(16) - .style(TextInputStyle.Inline) // Inline input style - .wordBreak(WordBreak.NORMAL) // This attribute does not take effect for the non-inline input style. - - Text("WordBreakType as BREAK_ALL in the inline input style:").fontSize(16).fontColor(0xFF0000) - TextInput({ - text: 'This is set wordBreak to WordBreak text Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu.' - }) - .fontSize(16) - .style(TextInputStyle.Inline) - .wordBreak(WordBreak.BREAK_ALL) + @State textStrEn: string = + 'This is set wordBreak to WordBreak text Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu.'; + @State textStrZn: string = + 'The TextArea component provides multi-line text input and automatically wraps text to ensure that no line extends beyond the component's width.\nWhen the height is not set, the component has no default height and adapts to the content height. When the width is not set, it defaults to the maximum width.';'; - Text("WordBreakType as BREAK_ALL in the inline input style:").fontSize(16).fontColor(0xFF0000) - TextInput({ - text: 'In a multi-line text input component, when the text content entered exceeds the width of the component, it will automatically wrap to display.\nIf the height is not set, the component has no default height and will adapt to the height of the content. If the width is not set, it auto-fills the maximum width available.' - }) - .fontSize(16) - .style(TextInputStyle.Inline) - .wordBreak(WordBreak.BREAK_ALL) - - Text("WordBreakType as BREAK_WORD in the inline input style:").fontSize(16).fontColor(0xFF0000) - TextInput({ - text: 'This is set wordBreak to WordBreak text Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu.' - }) - .fontSize(16) - .style(TextInputStyle.Inline) - .wordBreak(WordBreak.BREAK_WORD) - } + build() { + Row() { + Column() { + Text("WordBreakType as NORMAL in the inline input style:").fontSize(16).fontColor(0xCCCCCC) + TextInput({ + text: this.textStrEn + }) + .margin(10) + .fontSize(16) + .style(TextInputStyle.Inline)// Inline input style + .wordBreak(WordBreak.NORMAL) // This attribute does not take effect for the non-inline input style. + + Text("WordBreakType as BREAK_ALL in the inline input style:").fontSize(16).fontColor(0xCCCCCC) + TextInput({ + text: this.textStrEn + }) + .margin(10) + .fontSize(16) + .style(TextInputStyle.Inline) + .wordBreak(WordBreak.BREAK_ALL) + + Text("WordBreakType as BREAK_WORD in the inline input style:").fontSize(16).fontColor(0xCCCCCC) + TextInput({ + text: this.textStrEn + }) + .margin(10) + .fontSize(16) + .style(TextInputStyle.Inline) + .wordBreak(WordBreak.BREAK_WORD) + }.width('100%') + }.height('100%').margin(10) } } ``` -![TextInputWordBreak](figures/TextInputWordBreak.jpeg) +![TextInputWordBreak](figures/TextInputWordBreak.png) ### Example 8: Setting the Text Style This example showcases various text styles by using the **lineHeight**, **letterSpacing**, and **decoration** attributes. ```ts +// xxx.ets @Entry @Component struct TextInputExample { @@ -2064,31 +2117,31 @@ struct TextInputExample { Row() { Column() { Text('lineHeight').fontSize(9).fontColor(0xCCCCCC) - TextInput({text: 'lineHeight unset'}) + TextInput({ text: 'lineHeight unset' }) .border({ width: 1 }).padding(10).margin(5) - TextInput({text: 'lineHeight 15'}) + TextInput({ text: 'lineHeight 15' }) .border({ width: 1 }).padding(10).margin(5).lineHeight(15) - TextInput({text: 'lineHeight 30'}) + TextInput({ text: 'lineHeight 30' }) .border({ width: 1 }).padding(10).margin(5).lineHeight(30) Text('letterSpacing').fontSize(9).fontColor(0xCCCCCC) - TextInput({text: 'letterSpacing 0'}) + TextInput({ text: 'letterSpacing 0' }) .border({ width: 1 }).padding(5).margin(5).letterSpacing(0) - TextInput({text: 'letterSpacing 3'}) + TextInput({ text: 'letterSpacing 3' }) .border({ width: 1 }).padding(5).margin(5).letterSpacing(3) - TextInput({text: 'letterSpacing -1'}) + TextInput({ text: 'letterSpacing -1' }) .border({ width: 1 }).padding(5).margin(5).letterSpacing(-1) Text('decoration').fontSize(9).fontColor(0xCCCCCC) - TextInput({text: 'LineThrough, Red'}) + TextInput({ text: 'LineThrough, Red' }) .border({ width: 1 }).padding(5).margin(5) - .decoration({type: TextDecorationType.LineThrough, color: Color.Red}) - TextInput({text: 'Overline, Red, DASHED'}) + .decoration({ type: TextDecorationType.LineThrough, color: Color.Red }) + TextInput({ text: 'Overline, Red, DASHED' }) .border({ width: 1 }).padding(5).margin(5) - .decoration({type: TextDecorationType.Overline, color: Color.Red, style: TextDecorationStyle.DASHED}) - TextInput({text: 'Underline, Red, WAVY'}) + .decoration({ type: TextDecorationType.Overline, color: Color.Red, style: TextDecorationStyle.DASHED }) + TextInput({ text: 'Underline, Red, WAVY' }) .border({ width: 1 }).padding(5).margin(5) - .decoration({type: TextDecorationType.Underline, color: Color.Red, style: TextDecorationStyle.WAVY}) + .decoration({ type: TextDecorationType.Underline, color: Color.Red, style: TextDecorationStyle.WAVY }) }.height('90%') } .width('90%') @@ -2104,11 +2157,12 @@ struct TextInputExample { This example demonstrates how to use the **fontFeature** attribute to display text with various typographic features. ```ts +// xxx.ets @Entry @Component struct TextInputExample { - @State text1: string = 'This is ss01 on : 0123456789' - @State text2: string = 'This is ss01 off: 0123456789' + @State text1: string = 'This is ss01 on : 0123456789'; + @State text2: string = 'This is ss01 off: 0123456789'; build() { Column() { @@ -2134,13 +2188,14 @@ struct TextInputExample { This example illustrates the implementation of a custom keyboard that automatically adjusts its position to avoid covering the text box. ```ts +// xxx.ets @Entry @Component struct TextInputExample { - controller: TextInputController = new TextInputController() - @State inputValue: string = "" - @State height1: string | number = '80%' - @State supportAvoidance: boolean = true + controller: TextInputController = new TextInputController(); + @State inputValue: string = ""; + @State height1: string | number = '80%'; + @State supportAvoidance: boolean = true; // Create a custom keyboard component. @Builder @@ -2149,7 +2204,7 @@ struct TextInputExample { Row() { Button('x').onClick(() => { // Disable the custom keyboard. - this.controller.stopEditing() + this.controller.stopEditing(); }).margin(10) } @@ -2158,7 +2213,7 @@ struct TextInputExample { GridItem() { Button(item + "") .width(110).onClick(() => { - this.inputValue += item + this.inputValue += item; }) } }) @@ -2172,13 +2227,13 @@ struct TextInputExample { Button("20%") .fontSize(24) .onClick(() => { - this.height1 = "20%" + this.height1 = "20%"; }) Button("80%") .fontSize(24) .margin({ left: 20 }) .onClick(() => { - this.height1 = "80%" + this.height1 = "80%"; }) } .justifyContent(FlexAlign.Center) @@ -2204,6 +2259,7 @@ struct TextInputExample { This example showcases the implementation of text auto-adaptation features using the **minFontSize**, **maxFontSize**, and **heightAdaptivePolicy** attributes. ```ts +// xxx.ets @Entry @Component struct TextInputExample { @@ -2255,16 +2311,18 @@ struct TextInputExample { This example demonstrates the effects of different line break rules using the **wordBreak** attribute. ```ts +// xxx.ets @Entry @Component struct TextInputExample { @State message1: string = "They can be classified as built-in components–those directly provided by the ArkUI framework and custom components – those defined by developers" + "The built-in components include buttons radio buttonsprogress indicators and text You can set the rendering effectof thesecomponents in method chaining mode," + - "page components are divided into independent UI units to implementindependent creation development and reuse of different units on pages making pages more engineering-oriented." - @State lineBreakStrategyIndex: number = 0 - @State lineBreakStrategy: LineBreakStrategy[] = [LineBreakStrategy.GREEDY, LineBreakStrategy.HIGH_QUALITY, LineBreakStrategy.BALANCED] - @State lineBreakStrategyStr: string[] = ['GREEDY', 'HIGH_QUALITY', 'BALANCED'] + "page components are divided into independent UI units to implement independent creation development and reuse of different units on pages making pages more engineering-oriented."; + @State lineBreakStrategyIndex: number = 0; + @State lineBreakStrategy: LineBreakStrategy[] = + [LineBreakStrategy.GREEDY, LineBreakStrategy.HIGH_QUALITY, LineBreakStrategy.BALANCED]; + @State lineBreakStrategyStr: string[] = ['GREEDY', 'HIGH_QUALITY', 'BALANCED']; build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) { @@ -2278,10 +2336,10 @@ struct TextInputExample { .style(TextInputStyle.Inline) .lineBreakStrategy(this.lineBreakStrategy[this.lineBreakStrategyIndex]) Row() { - Button('Toggle lineBreakStrategy Value: ' + this.lineBreakStrategyStr[this.lineBreakStrategyIndex]).onClick(() => { - this.lineBreakStrategyIndex++ - if(this.lineBreakStrategyIndex > (this.lineBreakStrategyStr.length - 1)) { - this.lineBreakStrategyIndex = 0 + Button('Current lineBreakStrategy value: ' + this.lineBreakStrategyStr[this.lineBreakStrategyIndex]).onClick(() => { + this.lineBreakStrategyIndex++; + if (this.lineBreakStrategyIndex > (this.lineBreakStrategyStr.length - 1)) { + this.lineBreakStrategyIndex = 0; } }) } @@ -2299,11 +2357,11 @@ This example showcases the implementation of insert and delete operations using @Entry @Component struct TextInputExample { - @State insertValue: string = "" - @State deleteValue: string = "" - @State insertOffset: number = 0 - @State deleteOffset: number = 0 - @State deleteDirection: number = 0 + @State insertValue: string = ""; + @State deleteValue: string = ""; + @State insertOffset: number = 0; + @State deleteOffset: number = 0; + @State deleteDirection: number = 0; build() { Row() { @@ -2311,11 +2369,11 @@ struct TextInputExample { TextInput({ text: "Insert callbacks" }) .height(60) .onWillInsert((info: InsertValue) => { - this.insertValue = info.insertValue + this.insertValue = info.insertValue; return true; }) .onDidInsert((info: InsertValue) => { - this.insertOffset = info.insertOffset + this.insertOffset = info.insertOffset; }) Text("insertValue:" + this.insertValue + " insertOffset:" + this.insertOffset).height(30) @@ -2323,13 +2381,13 @@ struct TextInputExample { TextInput({ text: "Delete callbacks" }) .height(60) .onWillDelete((info: DeleteValue) => { - this.deleteValue = info.deleteValue - info.direction + this.deleteValue = info.deleteValue; + info.direction; return true; }) .onDidDelete((info: DeleteValue) => { - this.deleteOffset = info.deleteOffset - this.deleteDirection = info.direction + this.deleteOffset = info.deleteOffset; + this.deleteDirection = info.direction; }) Text("deleteValue:" + this.deleteValue + " deleteOffset:" + this.deleteOffset).height(30) @@ -2356,33 +2414,33 @@ struct TextInputExample { @State text: string = 'TextInput editMenuOptions' onCreateMenu = (menuItems: Array) => { let item1: TextMenuItem = { - content: 'Custom 1', + content: 'custom1', icon: $r('app.media.startIcon'), - id: TextMenuItemId.of('Custom 1'), - } + id: TextMenuItemId.of('custom1'), + }; let item2: TextMenuItem = { - content: 'Custom 2', - id: TextMenuItemId.of('Custom 2'), + content: 'custom2', + id: TextMenuItemId.of('custom2'), icon: $r('app.media.startIcon'), - } - menuItems.push(item1) - menuItems.unshift(item2) - return menuItems + }; + menuItems.push(item1); + menuItems.unshift(item2); + return menuItems; } onMenuItemClick = (menuItem: TextMenuItem, textRange: TextRange) => { if (menuItem.id.equals(TextMenuItemId.of("custom2"))) { - console.log("Intercept id: custom2 start:" + textRange.start + "; end:" + textRange.end) - return true + console.log("Intercept id: custom2 start:" + textRange.start + "; end:" + textRange.end); + return true; } if (menuItem.id.equals(TextMenuItemId.COPY)) { - console.log("Intercept COPY start:" + textRange.start + "; end:" + textRange.end) - return true + console.log("Intercept COPY start:" + textRange.start + "; end:" + textRange.end); + return true; } if (menuItem.id.equals(TextMenuItemId.SELECT_ALL)) { - console.log("Do not intercept SELECT_ALL start:" + textRange.start + "; end:" + textRange.end) - return false + console.log("Do not intercept SELECT_ALL start:" + textRange.start + "; end:" + textRange.end); + return false; } - return false + return false; } @State editMenuOptions: EditMenuOptions = { onCreateMenu: this.onCreateMenu, onMenuItemClick: this.onMenuItemClick @@ -2415,9 +2473,9 @@ import { SymbolGlyphModifier } from '@kit.ArkUI'; @Entry @Component struct TextInputExample { - @State text: string = '' + @State text: string = ''; symbolModifier: SymbolGlyphModifier = - new SymbolGlyphModifier($r('sys.symbol.trash')).fontColor([Color.Red]).fontSize(16).fontWeight(FontWeight.Regular) + new SymbolGlyphModifier($r('sys.symbol.trash')).fontColor([Color.Red]).fontSize(16).fontWeight(FontWeight.Regular); build() { Column() { @@ -2490,3 +2548,172 @@ struct EllipsisModeExample { ``` ![textInputEllipsisMode](figures/textInputEllipsisMode.png) + +### Example 17: Implementing Callbacks for Input Status Changes, Copy, Cut, Paste, and Content Scrolling + +This example demonstrates how to monitor input status changes, copy, cut, paste, and text content scrolling events using the **onEditChange**, **onCopy**, **onCut**, **onPaste**, and **onContentScroll** APIs. + +```ts +// xxx.ets +@Entry +@Component +struct TextInputExample { + @State editStatus: boolean = false; + @State copyValue: string = ""; + @State cutValue: string = ""; + @State pasteValue: string = ""; + @State totalOffsetX: number = 0; + @State totalOffsetY: number = 0; + + build() { + Row() { + Column() { + TextInput({ text: "TextInput supports the callback on input status changes" }) + .height(60) + .fontStyle(FontStyle.Italic) + .fontWeight(FontWeight.Bold) + .fontFamily("HarmonyOS Sans") + .copyOption(CopyOptions.LocalDevice) + .textAlign(TextAlign.Center) + .selectedBackgroundColor(Color.Blue) + .caretStyle({ width: '4vp' }) + .caretPosition(10)// Set the caret position in the TextInput component. + .selectionMenuHidden(true)// Hide the system text selection menu. + .onEditChange((status: boolean) => { + this.editStatus = status; + }) + .defaultFocus (true)// Set the TextInput component as the default focus. + .enableKeyboardOnFocus (false)// Prevent the keyboard from appearing when the TextArea component obtains focus in a way other than clicking. + .selectAll(false) + + Text("editStatus:" + this.editStatus).height(30) + + TextInput({ text: "TextInput supports the callback on copy operations" }) + .height(60) + .fontStyle(FontStyle.Italic) + .fontWeight(FontWeight.Bold) + .fontFamily("HarmonyOS Sans") + .copyOption(CopyOptions.LocalDevice) + .textAlign(TextAlign.Center) + .selectedBackgroundColor(Color.Blue) + .caretStyle({ width: '4vp' }) + .onCopy((copyValue: string) => { + this.copyValue = copyValue; + }) + + Text("copyValue:" + this.copyValue).height(30) + + TextInput({ text: "TextInput supports the callback on cut operations" }) + .height(60) + .fontStyle(FontStyle.Italic) + .fontWeight(FontWeight.Bold) + .fontFamily("HarmonyOS Sans") + .copyOption(CopyOptions.LocalDevice) + .textAlign(TextAlign.Center) + .selectedBackgroundColor(Color.Blue) + .caretStyle({ width: '4vp' }) + .onCut((cutValue: string) => { + this.cutValue = cutValue; + }) + + Text("cutValue:" + this.cutValue).height(30) + + TextInput({ text: "TextInput supports the callback on paste operations" }) + .height(60) + .fontStyle(FontStyle.Italic) + .fontWeight(FontWeight.Bold) + .fontFamily("HarmonyOS Sans") + .copyOption(CopyOptions.LocalDevice) + .textAlign(TextAlign.Center) + .selectedBackgroundColor(Color.Blue) + .caretStyle({ width: '4vp' }) + .onPaste((pasteValue: string) => { + this.pasteValue = pasteValue; + }) + + Text("pasteValue:" + this.pasteValue).height(30) + + TextInput({ text: "TextInput supports the callback on content scrolling: Scroll the text to see offset changes when the text width exceeds the text box width" }) + .height(60) + .fontStyle(FontStyle.Italic) + .fontWeight(FontWeight.Bold) + .fontFamily("HarmonyOS Sans") + .copyOption(CopyOptions.LocalDevice) + .textAlign(TextAlign.Center) + .selectedBackgroundColor(Color.Blue) + .caretStyle({ width: '4vp' }) + .onContentScroll((totalOffsetX: number, totalOffsetY: number) => { + this.totalOffsetX = totalOffsetX; + this.totalOffsetY = totalOffsetY; + }) + + Text("totalOffsetX:" + this.totalOffsetX + " totalOffsetY:" + this.totalOffsetY).height(30) + + }.width('100%') + } + .height('100%') + } +} +``` + +![TextInputEditChange](figures/TextInputEditChange.png) + +### Example 18: Setting the Minimum and Maximum Font Scale Factor + +This example demonstrates how to set the minimum and maximum font scale factor using **minFontScale** and **maxFontScale**. + +```ts +import { abilityManager, Configuration } from '@kit.AbilityKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +// xxx.ets +@Entry +@Component +export struct TextAreaExample11 { + @State minFontScale: number = 0.85; + @State maxFontScale: number = 2; + @State changeValue: string = 'abcde'; + + build() { + Column() { + Column({ space: 30 }) { + Text("System font size changes: small and large, small and large") + TextArea({ + placeholder: 'The text area can hold an unlimited amount of text. input your word...', + }) + // Set the minimum font scale factor; if the value is undefined, the text follows the default font scale factor. + .minFontScale(0.85) + // Set the maximum font scale factor; if the value is undefined, the text follows the default font scale factor. + .maxFontScale(2) + }.width('100%') + } + } +} +``` + +```ts +Create a new directory named profile in the following path: AppScope/resources/base. +Inside the newly created profile directory, create a file named configuration.json. +Add the following JSON code to the **configuration.json** file: +{ + "configuration":{ + "fontSizeScale": "followSystem", + "fontSizeMaxScale": "3.2" +} +} +``` + +```ts +Modify the app.json5 file in AppScope as follows: +{ + "app": { + "bundleName": "com.example.myapplication", + "vendor": "example", + "versionCode": 1000000, + "versionName": "1.0.0", + "icon": "$media:app_icon", + "label": "$string:app_name", + "configuration": "$profile:configuration" + } +} +``` diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-textpicker.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-textpicker.md index 7f7b3a75acb5a7d05fe26ae6c9cdd974c978127f..740e380f0c15f13636c96112d0f79ba9e48501cd 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-textpicker.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-textpicker.md @@ -37,8 +37,9 @@ Creates a text picker based on the selection range specified by **range**. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | range | string[] \| string[] []10+ \| [Resource](ts-types.md#resource) \|
[TextPickerRangeContent](#textpickerrangecontent10)[]10+ \| [TextCascadePickerRangeContent](#textcascadepickerrangecontent10)[]10+ | Yes| Data selection range of the picker. This parameter cannot be set to an empty array. If set to an empty array, it will not be displayed. If it is dynamically changed to an empty array, the current value remains displayed.
**NOTE**
For a single-column picker, use a value of the string[], Resource, or TextPickerRangeContent[] type.
For a multi-column picker, use a value of the string[] type.
For a multi-column linked picker, use a value of the TextCascadePickerRangeContent[] type.
The Resource type supports only [strarray.json](../../../quick-start/resource-categories-and-access.md#resource-group-directories).
The type and number of columns in the range cannot be dynamically modified.| -| selected | number \| number[]10+ | No| Index of the default item in the range.
Default value: **0**
**NOTE**
For a single-column picker, use a value of the number type.
For a multi-column (linked) picker, use a value of the number[] type.
Since API version 10, this attribute supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md).| -| value | string \| string[]10+ | No| Value of the default item in the range. The priority of this parameter is lower than that of **selected**.
Default value: value of the first item
**NOTE**
This parameter works only when the picker contains text only.
For a single-column picker, use a value of the string type.
For a multi-column (linked) picker, use a value of the string[] type.
Since API version 10, this attribute supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md).| +| selected | number \| number[]10+ | No| Index of the default selected item in the array. The index is zero-based.
Default value: **0**
**NOTE**
For a single-column picker, use a value of the number type.
For a multi-column (linked) picker, use a value of the number[] type.
Since API version 10, this attribute supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md).| +| value | string \| string[]10+ | No| Value of the default item in the range. The priority of this parameter is lower than that of **selected**.
Default value: value of the first item
**NOTE**
This parameter works only when the picker contains text only.
For a single-column picker, use a value of the string type.
For a multi-column (linked) picker, use a value of the string[] type.
Since API version 10, this parameter supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md).| +| columnWidths18+ | LengthMetrics[] | No| Width of each column in the picker.
Default value: All columns have equal widths.
**NOTE**
If the text length exceeds the column width, the text will be truncated.| ## TextPickerRangeContent10+ @@ -48,8 +49,8 @@ Creates a text picker based on the selection range specified by **range**. | Name| Type | Mandatory| Description | | ---- | ---------------------------------------------------- | ---- | ---------- | -| icon | string \| [Resource](ts-types.md#resource) | Yes | Image resource.| -| text | string \| [Resource](ts-types.md#resource) | No | Text information.| +| icon | string \| [Resource](ts-types.md#resource) | Yes | Image resource. If the value is a string, such as **"/common/hello.png"**, it represents the path to the image.| +| text | string \| [Resource](ts-types.md#resource) | No | Text information.
An empty character string is used by default.
**NOTE**
If the text length exceeds the column width, the text will be truncated.| ## TextCascadePickerRangeContent10+ @@ -59,7 +60,7 @@ Creates a text picker based on the selection range specified by **range**. | Name| Type | Mandatory| Description | | ------ | -------------------------------------------------------- | ---- | ---------- | -| text | string \| [Resource](ts-types.md#resource) | Yes | Text information.| +| text | string \| [Resource](ts-types.md#resource) | Yes | Text information.
**NOTE**
If the text length exceeds the column width, the text will be truncated.| | children | [TextCascadePickerRangeContent](#textcascadepickerrangecontent10)[] | No | Linkage data.| ## DividerOptions12+ @@ -69,18 +70,18 @@ Creates a text picker based on the selection range specified by **range**. | Name | Type | Mandatory| Description | | ----------- | ------------------------------------ | ---- | ------------------------------------------------------------ | -| strokeWidth | [Dimension](ts-types.md#dimension10) | No | Stroke width of the divider. The unit is vp by default. You can also specify it as px. The percentage type is not supported.| -| startMargin | [Dimension](ts-types.md#dimension10) | No | Distance between the divider and the start edge of the picker. The unit is vp by default. You can also specify it as px. The percentage type is not supported.| -| endMargin | [Dimension](ts-types.md#dimension10) | No | Distance between the divider and the end edge of the picker. The unit is vp by default. You can also specify it as px. The percentage type is not supported.| -| color | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the divider. +| strokeWidth | [Dimension](ts-types.md#dimension10) | No | Stroke width of the divider. The unit is vp by default. You can also specify it as px. The percentage type is not supported.
If the value is less than 0, the default value is used. The maximum value allowed is half the height of the column.
Default value: **2.0px**| +| startMargin | [Dimension](ts-types.md#dimension10) | No | Distance between the divider and the start edge of the picker. The unit is vp by default. You can also specify it as px. The percentage type is not supported.
Values less than 0 are invalid. The maximum value allowed is the width of the column.
Default value: **0**| +| endMargin | [Dimension](ts-types.md#dimension10) | No | Distance between the divider and the end edge of the picker. The unit is vp by default. You can also specify it as px. The percentage type is not supported.
Values less than 0 are invalid. The maximum value allowed is the width of the column.
Default value: **0**| +| color | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the divider.
Default value: **'#33000000'** ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### defaultPickerItemHeight -defaultPickerItemHeight(value: Optional\) +defaultPickerItemHeight(value: number | string) Sets the height of each item in the picker. @@ -92,13 +93,29 @@ Sets the height of each item in the picker. | Name| Type | Mandatory| Description | | ------ | -------------------------- | ---- | ---------------------- | -| value | [Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Height of each item in the picker.| +| value | number \| string | Yes | Height of each item in the picker. For the number type, the value range is [0, +∞]. For the string type, only numeric string values, for example, **"56"**, are supported.
Default value: 56 vp (selected) and 36 vp (unselected).
**NOTE**
The set value applies to both selected and unselected items.| + +### defaultPickerItemHeight18+ + +defaultPickerItemHeight(height: Optional\) + +Sets the height of each item in the picker. Compared to [defaultPickerItemHeight](#defaultpickeritemheight), this API supports the **undefined** type for the **height** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------------------- | ---- | ---------------------- | +| height | [Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Height of each item in the picker. For the number type, the value range is [0, +∞]. For the string type, only numeric string values, for example, **"56"**, are supported.
Default value: 56 vp (selected) and 36 vp (unselected).
**NOTE**
The set value applies to both selected and unselected items.
If **height** is set to **undefined**, the previous value is retained.| ### disappearTextStyle10+ -disappearTextStyle(value: Optional\) +disappearTextStyle(value: PickerTextStyle) -Sets the font color, font size, and font width for the top and bottom items. +Sets the font color, font size, and font weight for the top and bottom items. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -108,13 +125,29 @@ Sets the font color, font size, and font width for the top and bottom items. | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| value | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10)> | Yes | Font color, font size, and font width of the top and bottom items.
Default value:
{
color: '#ff182431',
font: {
size: '14fp',
weight: FontWeight.Regular
}
} | +| value | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | Yes | Font color, font size, and font weight of the top and bottom items.
Default value:
{
color: '#ff182431',
font: {
size: '14fp',
weight: FontWeight.Regular
}
} | + +### disappearTextStyle18+ + +disappearTextStyle(style: Optional\) + +Sets the font color, font size, and font weight for the top and bottom items. Compared to [disappearTextStyle](#disappeartextstyle10)10+, this API supports the **undefined** type for the **style** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| style | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10)> | Yes | Font color, font size, and font weight of the top and bottom items.
If **style** is set to **undefined**, the default value is used:
{
color: '#ff182431',
font: {
size: '14fp',
weight: FontWeight.Regular
}
} | ### textStyle10+ -textStyle(value: Optional\) +textStyle(value: PickerTextStyle) -Sets the font color, font size, and font width for all items except the top, bottom, and selected items. +Sets the font color, font size, and font weight for all items except the top, bottom, and selected items. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -124,13 +157,29 @@ Sets the font color, font size, and font width for all items except the top, bot | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| value | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10)> | Yes | Font color, font size, and font width of all items except the top, bottom, and selected items.
Default value:
{
color: '#ff182431',
font: {
size: '16fp',
weight: FontWeight.Regular
}
} | +| value | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | Yes | Font color, font size, and font weight of all items except the top, bottom, and selected items.
Default value:
{
color: '#ff182431',
font: {
size: '16fp',
weight: FontWeight.Regular
}
} | + +### textStyle18+ + +textStyle(style: Optional\) + +Sets the font color, font size, and font weight for all items except the top, bottom, and selected items. Compared to [textStyle](#textstyle10)10+, this API supports the **undefined** type for the **style** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| style | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10)> | Yes | Font color, font size, and font weight of all items except the top, bottom, and selected items.
If **style** is set to **undefined**, the default value is used:
{
color: '#ff182431',
font: {
size: '16fp',
weight: FontWeight.Regular
}
} | ### selectedTextStyle10+ -selectedTextStyle(value: Optional\) +selectedTextStyle(value: PickerTextStyle) -Sets the font color, font size, and font width for the selected item. +Sets the font color, font size, and font weight for the selected item. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -140,11 +189,27 @@ Sets the font color, font size, and font width for the selected item. | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| value | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10)> | Yes | Font color, font size, and font width of the selected item.
Default value:
{
color: '#ff007dff',
font: {
size: '20vp',
weight: FontWeight.Medium
}
} | +| value | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | Yes | Font color, font size, and font weight of the selected item.
Default value:
{
color: '#ff007dff',
font: {
size: '20vp',
weight: FontWeight.Medium
}
} | + +### selectedTextStyle18+ + +selectedTextStyle(style: Optional\) + +Sets the font color, font size, and font weight for the selected item. Compared to [selectedTextStyle](#selectedtextstyle10)10+, this API supports the **undefined** type for the **style** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| style | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10)> | Yes | Font color, font size, and font weight of the selected item.
If **style** is set to **undefined**, the default value is used:
{
color: '#ff007dff',
font: {
size: '20vp',
weight: FontWeight.Medium
}
} | ### selectedIndex10+ -selectedIndex(value: Optional\) +selectedIndex(value: number | number[]) Sets the index of the default selected item in the array. Its priority is higher than that of the selected value in **options**. For a single-column picker, use a value of the number type. For a multi-column (linked) picker, use a value of the number[] type. @@ -156,11 +221,27 @@ Sets the index of the default selected item in the array. Its priority is higher | Name| Type | Mandatory| Description | | ------ | ---------------------------- | ---- | ---------------------------- | -| value | [Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Index of the default selected item in the array.
Default value: **0**
| +| value | number \| number[] | Yes | Index of the default selected item in the array. The index is zero-based.
Default value: **0**
| + +### selectedIndex18+ + +selectedIndex(index: Optional\) + +Sets the index of the default selected item in the array. Its priority is higher than that of the selected value in **options**. For a single-column picker, use a value of the number type. For a multi-column (linked) picker, use a value of the number[] type. Compared to [selectedIndex](#selectedindex10), this API supports the **undefined** type for the **index** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| index | [Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Index of the default selected item in the array. The index is zero-based.
If **index** is set to **undefined**, the default value **0** is used.
| ### canLoop10+ -canLoop(value: Optional\) +canLoop(value: boolean) Sets whether scrolling is loopable. @@ -172,11 +253,27 @@ Sets whether scrolling is loopable. | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------------------------------------ | -| value | [Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Whether scrolling is loopable.
**true**: loopable
**false**: not loopable
Default value: **true**| +| value | boolean | Yes | Whether scrolling is loopable.
**true**: loopable
**false**: not loopable
Default value: **true**| + +### canLoop18+ + +canLoop(isLoop: Optional\) + +Sets whether scrolling is loopable. Compared to [canLoop](#canloop10)10+, this API supports the **undefined** type for the **isLoop** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------------------------------------ | +| isLoop | [Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Whether scrolling is loopable.
**true**: loopable
**false**: not loopable
If **isLoop** is set to **undefined**, the default value **true** is used.| ### divider12+ -divider(value: Optional\) +divider(value: DividerOptions | null) Sets the divider style. If this attribute is not set, the divider is displayed based on the default value. @@ -189,11 +286,29 @@ If the sum of **startMargin** and **endMargin** exceeds the component width, bot **Parameters** | Name| Type | Mandatory| Description | | ------ | ------- | ---- | --------------------------------------------------------------------- | -| value | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[DividerOptions](#divideroptions12) \| null> | Yes | Divider options.
1. If **DividerOptions** is set, the divider is displayed in the configured style.
Default value:
{
strokeWidth: '2px',
startMargin: 0,
endMargin: 0,
color: '#33000000'
}
2. If this parameter is set to **null**, the divider is not displayed.| +| value | [DividerOptions](#divideroptions12) \| null | Yes | Divider options.
1. If **DividerOptions** is set, the divider is displayed in the configured style.
Default value:
{
strokeWidth: '2px',
startMargin: 0,
endMargin: 0,
color: '#33000000'
}
2. If this parameter is set to **null**, the divider is not displayed.| + +### divider18+ + +divider(textDivider: Optional\) + +Sets the divider style. If this attribute is not set, the divider is displayed based on the default value. Compared to [divider](#divider12)12+, this API supports the **undefined** type for the **textDivider** parameter. + +If the sum of **startMargin** and **endMargin** exceeds the component width, both **startMargin** and **endMargin** will be set to **0**. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | --------------------------------------------------------------------- | +| textDivider | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[DividerOptions](#divideroptions12) \| null> | Yes | Divider options.
1. If **DividerOptions** is set, the divider is displayed in the configured style.
If **textDivider** is set to **undefined**, the default value is used:
{
strokeWidth: '2px',
startMargin: 0,
endMargin: 0,
color: '#33000000'
}
2. If this parameter is set to **null**, the divider is not displayed.| ### gradientHeight12+ -gradientHeight(value: Optional\) +gradientHeight(value: Dimension) Sets the height for the fade effect. If this attribute is not set, the default fade effect is displayed. @@ -205,7 +320,27 @@ Sets the height for the fade effect. If this attribute is not set, the default f | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------------------------------------ | -| value | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[Dimension](ts-types.md#dimension10)> | Yes | Height of the fade effect at the top and bottom edges of the content area. It can be set in percentage, with 100% (the maximum value) being half the height of the picker. Setting it to **0** results in no fade effect, while negative numbers or other invalid values display the default fade effect. Default value: **36vp**| +| value | [Dimension](ts-types.md#dimension10) | Yes | Height of the fade effect at the top and bottom edges of the content area. It can be set in percentage, with 100% (the maximum value) being half the height of the picker. Setting it to **0** results in no fade effect, while negative numbers or other invalid values display the default fade effect. Default value: **36vp**| + +### gradientHeight18+ + +gradientHeight(height: Optional\) + +Sets the height for the fade effect. If this attribute is not set, the default fade effect is displayed. Compared to [gradientHeight](#gradientheight12)12+, this API supports the **undefined** type for the **height** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------------------------------------ | +| height | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[Dimension](ts-types.md#dimension10)> | Yes | Height of the fade effect at the top and bottom edges of the content area. It can be set in percentage, with 100% (the maximum value) being half the height of the picker. Setting it to **0** results in no fade effect, while negative numbers or other invalid values display the default fade effect. Default value: **36vp**
If **height** is set to **undefined**, the default value **36vp** is used.| + +> **NOTE** +> +> Avoid changing the attribute data during the animation process of this component. ### disableTextStyleAnimation15+ @@ -243,15 +378,58 @@ Sets the style of the text items when the text style change animation during the > > Avoid changing the attribute data during the animation process of this component. +### enableHapticFeedback18+ + +enableHapticFeedback(enable: Optional\) + +Specifies whether to enable haptic feedback. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name| Type | Mandatory | Description | +| ------ | --------------------------------------------- |-----|-------------------------------------------------------------------------------------| +| enable | [Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Whether to enable haptic feedback.
**true** (default): Haptic feedback is enabled.
**false**: Haptic feedback is disabled.| + +> **NOTE** +> +> To enable haptic feedback, you must declare the ohos.permission.VIBRATE permission under **requestPermissions** in the **module.json5** file of the project. +> ```json +> "requestPermissions": [ +> { +> "name": "ohos.permission.VIBRATE", +> } +> ] +> `` +> ``` + +### digitalCrownSensitivity18+ +digitalCrownSensitivity(sensitivity: Optional\) + +Sets the sensitivity to the digital crown rotation. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ----- | ---------------------------------------- | ---- | ------------------------- | +| sensitivity | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[CrownSensitivity](ts-appendix-enums.md#crownsensitivity18)> | Yes | Sensitivity to the digital crown rotation.
Default value: **CrownSensitivity.MEDIUM** | + +> **NOTE** +> +> This API is only available to circular screens on wearable devices. The component needs to obtain focus before responding to the [crown event](ts-universal-events-crown.md). + ## Events -In addition to the [universal events](ts-universal-events-click.md), the following events are supported. +In addition to the [universal events](ts-component-general-events.md), the following events are supported. ### onChange -onChange(callback: Optional\) +onChange(callback: (value: string \| string[], index: number \| number[]) => void) -Triggered when the text picker snaps to the selected item. When the picker contains text only or both text and imagery, **value** indicates the text of the selected item. When the picker contains imagery only, **value** is empty. +Triggered when an item in the picker is selected. When the picker contains text only or both text and imagery, **value** indicates the text of the selected item. When the picker contains imagery only, **value** is empty. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -259,20 +437,35 @@ Triggered when the text picker snaps to the selected item. When the picker conta **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------- | ---- | ------------------------------------------ | -| callback | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[OnTextPickerChangeCallback](#ontextpickerchangecallback16)> | Yes | Callback invoked when an item in the picker is selected.| +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------ | ---- | ------------------------------------------------- | +| value | string \| string[]10+ | Yes | Text of the selected item. For a multi-column picker, **value** is of the array type. | +| index | number \| number[]10+ | Yes | Index of the selected item. The index is zero-based. For a multi-column picker, **index** is of the array type.| + +### onChange18+ + +onChange(callback: Optional\) + +Triggered when the text picker snaps to the selected item. Compared to [onChange](#onchange), this API supports the **undefined** type for the **callback** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| callback | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[OnTextPickerChangeCallback](#ontextpickerchangecallback18)> | Yes | Callback invoked when an item in the picker is selected.
If **callback** is set to **undefined**, the callback function is not used.| ### onScrollStop14+ -onScrollStop(callback: (value: string \| string[], index: number \| number[]) => void) +onScrollStop(callback: TextPickerScrollStopCallback) Triggered when the scrolling in the text picker stops. If the scrolling is initiated by a gesture, this event is triggered when the finger is lifted from the screen and the scrolling stops. -When the picker contains text only or a combination of images and text, **value** indicates the text of the selected item. When the picker contains images only, **value** is empty. - **Atomic service API**: This API can be used in atomic services since API version 14. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -281,10 +474,27 @@ When the picker contains text only or a combination of images and text, **value* | Name| Type | Mandatory| Description | | ------ | ------------------------------------------ | ---- | ------------------------------------------------- | -| value | string \| string[] | Yes | Text of the selected item. For a multi-column picker, **value** is of the array type. | -| index | number \| number[] | Yes | Index of the selected item. For a multi-column picker, **index** is of the array type.| +| callback | [TextPickerScrollStopCallback](#textpickerscrollstopcallback14) | Yes | Triggered when the scrolling in the text picker stops.| + +### onScrollStop18+ + +onScrollStop(callback: Optional\) + +Triggered when the scrolling in the text picker stops. Compared to [onScrollStop](#onscrollstop14)14+, this API supports the **undefined** type for the **callback** parameter. + +If the scrolling is initiated by a gesture, this event is triggered when the finger is lifted from the screen and the scrolling stops. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------ | ---- | ------------------------------------------------- | +| callback | [TextPickerScrollStopCallback](#textpickerscrollstopcallback14) | Yes | Triggered when the scrolling in the text picker stops.
If **callback** is set to **undefined**, the callback function is not used.| -### onEnterSelectedArea16+ +### onEnterSelectedArea18+ onEnterSelectedArea(callback: TextPickerEnterSelectedAreaCallback) @@ -294,7 +504,7 @@ Compared to the **onChange** event, this event is triggered earlier, specificall When the picker contains text only or a combination of images and text, **value** indicates the text of the selected item. When the picker contains images only, **value** is empty. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -302,7 +512,7 @@ When the picker contains text only or a combination of images and text, **value* | Name | Type | Mandatory| Description | | -------- | -------------------------- | ---- | ------------------------------------------ | -| callback | [TextPickerEnterSelectedAreaCallback](#textpickerenterselectedareacallback16) | Yes | Triggered during the scrolling of the text picker when an item enters the divider area.| +| callback | [TextPickerEnterSelectedAreaCallback](#textpickerenterselectedareacallback18) | Yes | Triggered during the scrolling of the text picker when an item enters the divider area.| ### onAccept(deprecated) @@ -319,7 +529,7 @@ This API is deprecated since API version 10. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------- | | value | string | Yes | Text of the selected item. | -| index | number | Yes | Index of the selected item.| +| index | number | Yes | Index of the selected item. The index is zero-based.| ### onCancel(deprecated) @@ -345,15 +555,15 @@ Defines the text style options. Inherits [PickerTextStyle](ts-basic-components-d | maxFontSize | number \| string \| [Resource](ts-types.md#resource) | No | Maximum font size. | | overflow | [TextOverflow](ts-appendix-enums.md#textoverflow) | No | Display mode when the text is too long. Ineffective when set to **MARQUEE**. | -## OnTextPickerChangeCallback16+ +## OnTextPickerChangeCallback18+ type OnTextPickerChangeCallback = (value: string | string[], index: number | number[]) => void -Triggered when an item in the picker is selected. +Triggered when an item in the picker is selected. When the picker contains text only or both text and imagery, **value** indicates the text of the selected item. When the picker contains imagery only, **value** is empty. -**Widget capability**: This API can be used in ArkTS widgets since API version 16. +**Widget capability**: This API can be used in ArkTS widgets since API version 18. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -362,9 +572,30 @@ Triggered when an item in the picker is selected. | Name| Type | Mandatory| Description | | ------ | ------------------------------------------ | ---- | ------------------------------------------------- | | value | string \| string[]10+ | Yes | Text of the selected item. For a multi-column picker, **value** is of the array type. | -| index | number \| number[]10+ | Yes | Index of the selected item. For a multi-column picker, **index** is of the array type.| +| index | number \| number[]10+ | Yes | Index of the selected item. The index is zero-based. For a multi-column picker, **index** is of the array type.| -## TextPickerEnterSelectedAreaCallback16+ +## TextPickerScrollStopCallback14+ + +type TextPickerScrollStopCallback = (value: string | string[], index: number | number[]) => void + +Triggered when the scrolling in the text picker stops. + +When the picker contains text only or both text and imagery, **value** indicates the text of the selected item. When the picker contains imagery only, **value** is empty. + +**Widget capability**: This API can be used in ArkTS widgets since API version 14. + +**Atomic service API**: This API can be used in atomic services since API version 14. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------ | ---- | ------------------------------------------------- | +| value | string \| string[] | Yes | Text of the selected item. For a multi-column picker, **value** is of the array type. | +| index | number \| number[] | Yes | Index of the selected item. The index is zero-based. For a multi-column picker, **index** is of the array type.| + +## TextPickerEnterSelectedAreaCallback18+ type TextPickerEnterSelectedAreaCallback = (value: string | string[], index: number | number[]) => void @@ -372,9 +603,9 @@ Represents the callback triggered during the scrolling of the text picker when a In scenarios where the picker contains linked columns, the use of this callback is not recommended. The reason is that it identifies nodes where items enter the divider area during scrolling. However, items that change in response to the scrolling do not themselves scroll. As a result, the callback's return values will only reflect changes for the currently scrolling column, while other non-scrolling columns will remain unchanged. -**Widget capability**: This API can be used in ArkTS widgets since API version 16. +**Widget capability**: This API can be used in ArkTS widgets since API version 18. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -383,16 +614,17 @@ In scenarios where the picker contains linked columns, the use of this callback | Name| Type | Mandatory| Description | | ------ | ------------------------------------------ | ---- | ------------------------------------------------- | | value | string \| string[] | Yes | Text of the selected item. For a multi-column picker, **value** is of the array type. | -| index | number \| number[] | Yes | Index of the selected item. For a multi-column picker, **index** is of the array type.| +| index | number \| number[] | Yes | Index of the selected item. The index is zero-based. For a multi-column picker, **index** is of the array type.| ## Example ### Example 1: Setting the Number of Columns in the Picker -This example demonstrates how to set **range** to implement single-column or multi-column text pickers. +This example demonstrates how to configure a single-column or multi-column text picker by setting **range** and customizing the width of each column using **columnWidths**. ```ts // xxx.ets +import { LengthMetrics } from '@kit.ArkUI' class bottom { bottom:number = 50 } @@ -407,26 +639,40 @@ struct TextPickerExample { private multi: string[][] = [this.apfruits, this.orfruits, this.pefruits] private cascade: TextCascadePickerRangeContent[] = [ { - text: 'Asia', - children: [{ text: 'China', children: [{ text: 'Beijing' }, { text: 'Shanghai' }, { text: 'Chongqing' }] }, - { text: 'Japan', children: [{ text: 'Tokyo' }, { text: 'Hokkaido' }, { text: 'Osaka' }] }] + text: 'Liaoning Province', + children: [{ text: 'Shenyang', children: [{ text: 'Shenhe District' }, { text: 'Heping District' }, { text: 'Hunnan District' }] }, + { text: 'Dalian', children: [{ text: 'Zhongshan District' }, { text: 'Jinzhou District' }, { text: 'Changhai County' }] }] }, { - text: 'Europe', - children: [{ text: 'Germany', children: [{ text: 'Berlin' }, { text: 'Munich' }, { text: 'Nuremberg' }] }, - { text: 'France', children: [{ text: 'Paris' }, { text: 'Lille' }, { text: 'Orleans' }] }] + text: 'Jilin Province', + children: [{ text: 'Changchun', children: [{ text: 'Nanguan District' }, { text: 'Kuancheng District' }, { text: 'Chaoyang District' }] }, + { text: 'Siping', children: [{ text: 'Tiexi District' }, { text: 'Tiedong District' }, { text: 'Lishu County' }] }] }, { - text: 'Africa', - children: [{ text: 'Egypt', children: [{ text: 'Cairo' }, { text: 'Damietta' }, { text: 'Girga' }] }, - { text: 'Algeria', children: [{ text: 'Alger' }, { text: 'Oran' }, { text: 'Adrar' }] }] + text: 'Heilongjiang Province', + children: [{ text: 'Harbin', children: [{ text: 'Daoli District' }, { text: 'Daowai District' }, { text: 'Nangang District' }] }, + { text: 'Mudanjiang', children: [{ text: 'Dong'an District' }, { text: 'Xi'an District' }, { text: 'Aimin District' }] }] } ] + private singleColumnWidths: LengthMetrics[] = [ + LengthMetrics.percent(50) + ] + + private multipleColumnWidths: LengthMetrics[] = [ + LengthMetrics.vp(100), + LengthMetrics.vp(200), + LengthMetrics.vp(100) + ] + private cascadeColumnWidths: LengthMetrics[] = [ + LengthMetrics.percent(20), + LengthMetrics.percent(30), + LengthMetrics.percent(50) + ] build() { Column() { - TextPicker({ range: this.apfruits, selected: this.select }) + TextPicker({ range: this.apfruits, selected: this.select, columnWidths: this.singleColumnWidths }) .onChange((value: string | string[], index: number | number[]) => { console.info('Picker item changed, value: ' + value + ', index: ' + index) }) @@ -437,7 +683,7 @@ struct TextPickerExample { console.info('Picker item enter selected area, value: ' + value + ', index: ' + index) }) - TextPicker({ range: this.multi }) + TextPicker({ range: this.multi, columnWidths: this.multipleColumnWidths }) .onChange((value: string | string[], index: number | number[]) => { console.info('TextPicker multi-column: onChange' + JSON.stringify(value) + ',' + 'index:' + JSON.stringify(index)) }) @@ -448,7 +694,7 @@ struct TextPickerExample { console.info('TextPicker multi-column: onEnterSelectedArea ' + JSON.stringify(value) + ', ' + 'index: ' + JSON.stringify(index)) }) - TextPicker({ range: this.cascade }) + TextPicker({ range: this.cascade, columnWidths: this.cascadeColumnWidths }) .onChange((value: string | string[], index: number | number[]) => { console.info('TextPicker multi-column linkage: onChange' + JSON.stringify(value) + ',' + 'index:' + JSON.stringify(index)) }) @@ -463,7 +709,7 @@ struct TextPickerExample { } ``` -![textpicker](figures/textpicker.gif) + ### Example 2: Setting the Text Style @@ -534,7 +780,7 @@ struct TextPickerExample { ``` ![textpicker](figures/textpicker2.gif) -### Example 3: Using the Divider Style +### Example 4: Using the Divider Style This example demonstrates how to configure a text picker with a custom divider style by setting **divider** with **DividerOptions**. diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-timepicker.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-timepicker.md index 24996c60180e20238038569e7faf5de1eb18a79f..f31877ad3eb02ba89bc30110931c7069acd134d5 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-timepicker.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-timepicker.md @@ -36,6 +36,35 @@ Creates a time picker, which is in 24-hour format by default. | -------------------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | | selected | Date | No | Time of the selected item.
Default value: current system time
Since API version 10, this parameter supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md).
**Atomic service API**: This API can be used in atomic services since API version 11.| | format11+ | [TimePickerFormat](#timepickerformat11)| No | Time format.
Default value: **TimePickerFormat.HOUR_MINUTE**
**Atomic service API**: This API can be used in atomic services since API version 12.| +| start18+ | Date | No | Start time of the time picker.
Default value: **Date(0, 0, 0, 0, 0, 0)**; only the hour and minute settings take effect.
If both start and end are set to non-default values, the loop feature is disabled.
**Atomic service API**: This API can be used in atomic services since API version 18.| +| end18+ | Date | No | End time of the time picker.
Default value: **Date(0, 0, 0, 23, 59, 59)**; only the hour and minute settings take effect.
If both start and end are set to non-default values, the loop feature is disabled.
**Atomic service API**: This API can be used in atomic services since API version 18.| + +> **NOTE** +> +> Modifying the **TimePickerOptions** properties, such as **selected**, **start**, or **end**, during the scrolling process of the **TimePicker** component may not take effect. +> The **Date** object is used to handle dates and time. +> +> **Method 1**: new Date () +> +> Obtains the current system date and time. +> +> **Method 2**: new Date(value: number | string) +> +> | Name | Type | Mandatory | Description | +> | ------- | ------ | ---- | ------ | +> | value | number \| string | Yes | Date format.
**number**: number of milliseconds since 00:00:00 on January 1, 1970.
**string**: date string in formats such as 2025-02 2025-02-20 08:00:00 or 2025-02 2025-02-20T08:00:00.| +> +> **Method 3**: new Date(year: number, monthIndex: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number) +> +> | Name | Type | Mandatory | Description | +> | --------| ------ | ---- | ------ | +> | year | number | Yes | Year. Example: **2025**.| +> | monthIndex | number | Yes | Month index, for example, **2** for March.| +> | date | number | No | Day of the month, for example, **10**. (Required if **hours** is set.) | +> | hours | number | No | Hour, for example, **15**. (Required if **minutes** is set.) | +> | minutes | number | No | Minute, for example, **20**. (Required if **seconds** is set.) | +> | seconds | number | No | Second, for example, **20**. (Required if **ms** is set.) | +> | ms | number | No | Millisecond, for example, **10**.| ## TimePickerFormat11+ @@ -48,9 +77,20 @@ Creates a time picker, which is in 24-hour format by default. | HOUR_MINUTE | Display hours and minutes. | | HOUR_MINUTE_SECOND | Display hours, minutes, and seconds.| +**Handling in the case of exceptions** + +| Exception | Result | +| -------- | ------------------------------------------------------------ | +| The start time is later than the end time. | Both start time and end time are set to their default values. | +| The selected time is earlier than the start time. | The selected time is set to the start time. | +| The selected time is later than the end time. | The selected time is set to the end time. | +| The start time is later than the current system time, and the selected time is not set. | The selected time is set to the start time.| +| The end time is earlier than the current system time, and the selected time is not set. | The selected time is set to the end time. | +| The time format is invalid, such as **'01:61:61'**. | The default value is used. | + ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### useMilitaryTime @@ -68,6 +108,22 @@ Sets whether to display time in 24-hour format. When the display time is in 12-h | ------ | ------- | ---- | ------------------------------------------ | | value | boolean | Yes | Whether the display time is in 24-hour format.
Default value: **false**| +### useMilitaryTime18+ + +useMilitaryTime(isMilitaryTime: Optional\) + +Sets whether to display time in 24-hour format. Compared to [useMilitaryTime](#usemilitarytime), this API supports the **undefined** type for the **isMilitaryTime** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------------------ | +| isMilitaryTime | [Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Whether the display time is in 24-hour format.
If **isMilitaryTime** is set to **undefined**, the default value **false** is used.| + ### disappearTextStyle10+ disappearTextStyle(value: PickerTextStyle) @@ -84,6 +140,22 @@ Sets the font color, font size, and font weight for the top and bottom items. | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | value | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | Yes | Font color, font size, and font weight of the top and bottom items.
Default value:
{
color: '#ff182431',
font: {
size: '14fp',
weight: FontWeight.Regular
}
} | +### disappearTextStyle18+ + +disappearTextStyle(style: Optional\) + +Sets the font color, font size, and font weight for the top and bottom items. Compared to [disappearTextStyle](#disappeartextstyle10)10+, this API supports the **undefined** type for the **style** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| style | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10)> | Yes | Font color, font size, and font weight of the top and bottom items.
If **style** is set to **undefined**, the default value is used:
{
color: '#ff182431',
font: {
size: '14fp',
weight: FontWeight.Regular
}
} | + ### textStyle10+ textStyle(value: PickerTextStyle) @@ -100,6 +172,22 @@ Sets the font color, font size, and font weight for all items except the top, bo | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | value | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | Yes | Font color, font size, and font weight of all items except the top, bottom, and selected items.
Default value:
{
color: '#ff182431',
font: {
size: '16fp',
weight: FontWeight.Regular
}
} | +### textStyle18+ + +textStyle(style: Optional\) + +Sets the font color, font size, and font weight for all items except the top, bottom, and selected items. Compared to [textStyle](#textstyle10)10+, this API supports the **undefined** type for the **style** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| style | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10)> | Yes | Font color, font size, and font weight of all items except the top, bottom, and selected items.
If **style** is set to **undefined**, the default value is used:
{
color: '#ff182431',
font: {
size: '16fp',
weight: FontWeight.Regular
}
} | + ### selectedTextStyle10+ selectedTextStyle(value: PickerTextStyle) @@ -116,6 +204,22 @@ Sets the font color, font size, and font weight for the selected item. | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | value | [PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10) | Yes | Font color, font size, and font weight of the selected item.
Default value:
{
color: '#ff007dff',
font: {
size: '20vp',
weight: FontWeight.Medium
}
} | +### selectedTextStyle18+ + +selectedTextStyle(style: Optional\) + +Sets the font color, font size, and font weight for the selected item. Compared to [selectedTextStyle](#selectedtextstyle10)10+, this API supports the **undefined** type for the **style** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| style | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[PickerTextStyle](ts-basic-components-datepicker.md#pickertextstyle10)> | Yes | Font color, font size, and font weight of the selected item.
If **style** is set to **undefined**, the default value is used:
{
color: '#ff007dff',
font: {
size: '20vp',
weight: FontWeight.Medium
}
} | + ### loop11+ loop(value: boolean) @@ -132,6 +236,22 @@ Sets whether to enable the loop mode. | ------ | ------- | ---- | ------------------------------------------------------------ | | value | boolean | Yes | Whether to enable the loop mode.
Default value: **true**
The value **true** means to enable loop mode, and **false** means the opposite.| +### loop18+ + +loop(isLoop: Optional\) + +Sets whether to enable the loop mode. Compared to [loop](#loop11)11+, this API supports the **undefined** type for the **isLoop** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------------------------------------ | +| isLoop | [Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Whether to enable the loop mode.
If **isLoop** is set to **undefined**, the default value **true** is used. The value **true** means to enable the loop mode, and false means the opposite.| + ### dateTimeOptions12+ dateTimeOptions(value: DateTimeOptions) @@ -148,10 +268,28 @@ Sets whether to display a leading zero for the hours, minutes, and seconds. | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | value | [DateTimeOptions](../../apis-localization-kit/js-apis-intl.md#datetimeoptions) | Yes | Whether to display a leading zero for the hours, minutes, and seconds. Currently only the configuration of the **hour**, **minute**, and **second** parameters is supported.
Default value:
**hour**: In the 24-hour format, it defaults to **2-digit**, which means a leading zero is used; In the 12-hour format, it defaults to **numeric**, which means no leading zero is used.
**minute**: defaults to **2-digit**, which means a leading zero is used.
**second**: defaults to **2-digit**, which means a leading zero is used.
| +### dateTimeOptions18+ + +dateTimeOptions(timeFormat: Optional\) + +Sets whether to display a leading zero for the hours, minutes, and seconds. Compared to [dateTimeOptions](#datetimeoptions12)12+, this API supports the **undefined** type for the **timeFormat** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| timeFormat | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[DateTimeOptions](../../apis-localization-kit/js-apis-intl.md#datetimeoptions)> | Yes | Whether to display a leading zero for the hours, minutes, and seconds. Currently only the configuration of the **hour**, **minute**, and **second** parameters is supported.
Default value:
**hour**: In the 24-hour format, it defaults to **2-digit**, which means a leading zero is used; In the 12-hour format, it defaults to **numeric**, which means no leading zero is used.
**minute**: defaults to **2-digit**, which means a leading zero is used.
**second**: defaults to **2-digit**, which means a leading zero is used.
| + ### enableHapticFeedback12+ enableHapticFeedback(enable: boolean) +Sets whether to enable haptic feedback. + **Atomic service API**: This API can be used in atomic services since API version 12. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -160,9 +298,65 @@ enableHapticFeedback(enable: boolean) | ------ | --------------------------------------------- |-----|-------------------------------------------------------------------------------------| | enable | boolean | Yes | Whether haptic feedback is enabled.
**true** (default): Haptic feedback is enabled.
**false**: Haptic feedback is disabled.
Whether this parameter takes effect after being set to true depends on hardware support.| +### enableHapticFeedback18+ + +enableHapticFeedback(enable: Optional\) + +Sets whether to enable haptic feedback. Compared to [enableHapticFeedback](#enablehapticfeedback12)12+, this API supports the **undefined** type for the **enable** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name| Type | Mandatory | Description | +| ------ | --------------------------------------------- |-----|-------------------------------------------------------------------------------------| +| enable | [Optional](ts-universal-attributes-custom-property.md#optional12)\ | Yes | Whether haptic feedback is enabled.
If **enable** is set to **undefined**, the default value **true** is used. The value **true** means to enable haptic feedback, and **false** means the opposite.
Whether this parameter takes effect after being set to true depends on hardware support.| + +> **NOTE** +> +> To enable haptic feedback, you must declare the ohos.permission.VIBRATE permission under **requestPermissions** in the **module.json5** file of the project. +> ```json +> "requestPermissions": [ +> { +> "name": "ohos.permission.VIBRATE", +> } +> ] +> ``` + +### enableCascade18+ + +enableCascade(enable: boolean) + +Sets whether the AM/PM indicator automatically switches based on the hour in 12-hour format. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name| Type | Mandatory | Description | +| ------ | --------------------------------------------- |-----|-------------------------------------------------------------------------------------| +| enable | boolean | Yes | Whether the AM/PM indicator automatically switches based on the hour in 12-hour format.
Default value: **false**. The value **true** means that the AM/PM indicator automatically switches based on the hour in 12-hour format, and **false** means the opposite.
Setting this parameter to **true** takes effect only when **loop** is also set to **true**.
| + +### digitalCrownSensitivity18+ +digitalCrownSensitivity(sensitivity: Optional\) + +Sets the sensitivity to the digital crown rotation. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ----- | ---------------------------------------- | ---- | ------------------------- | +| sensitivity | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[CrownSensitivity](ts-appendix-enums.md#crownsensitivity18)> | Yes | Sensitivity to the digital crown rotation.
Default value: **CrownSensitivity.MEDIUM** | + +> **NOTE** +> +> This API is only available to circular screens on wearable devices. The component needs to obtain focus before responding to the [crown event](ts-universal-events-crown.md). + ## Events -In addition to the [universal events](ts-universal-events-click.md), the following events are supported. +In addition to the [universal events](ts-component-general-events.md), the following events are supported. ### onChange @@ -180,6 +374,58 @@ Triggered when a time is selected. | ------ | --------------------------------------------- | ---- | -------------- | | value | [TimePickerResult](#timepickerresult)| Yes | Time in 24-hour format.| +### onChange18+ + +onChange(callback: Optional\) + +Triggered when the time options in the TimePicker rest on the selected position after scrolling. Compared to [onChange](#onchange), this API supports the **undefined** type for the **callback** parameter. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| callback | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[OnTimePickerChangeCallback](#ontimepickerchangecallback18)> | Yes | Callback invoked when a time option is selected.
If **callback** is set to **undefined**, the callback function is not used.| + +### onEnterSelectedArea18+ + +onEnterSelectedArea(callback: Callback\) + +Triggered during the scrolling of the time picker when an item enters the divider area. + +Compared to the **onChange** event, this event is triggered earlier, specifically when the scroll distance of the current column exceeds half the height of the selected item, which indicates that the item has entered the divider area. When **enableCascade** is set to **true**, using this callback is not recommended due to the interdependent relationship between the AM/PM and hour columns. This callback indicates the moment an option enters the divider area during scrolling, and only the value of the currently scrolled column will change. The values of other non-scrolled columns will remain unchanged. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------- | ---- | ------------------------------------------ | +| callback | Callback\<[TimePickerResult](#timepickerresult)> | Yes | Callback triggered during the scrolling of the time picker when an item enters the divider area.| + +## OnTimePickerChangeCallback18+ + +type OnTimePickerChangeCallback = (value: TimePickerResult) => void + +Triggered when a time is selected. + +**Widget capability**: This API can be used in ArkTS widgets since API version 18. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | --------------------------------------------- | ---- | -------------- | +| value | [TimePickerResult](#timepickerresult)| Yes | Time in 24-hour format.| + ## TimePickerResult Describes a time in 24-hour format. @@ -194,9 +440,42 @@ Describes a time in 24-hour format. | minute | number | No | No | Minute portion of the selected time.
Value range: [0-59]| | second11+ | number | No | No | Second portion of the selected time.
Value range: [0-59]| - ## Example +### Example 1: Setting the Text Style + +This example demonstrates how to configure **disappearTextStyle**, **textStyle**, and **selectedTextStyle** to customize the text style in a text picker. + +```ts +// xxx.ets +@Entry +@Component +struct TimePickerExample { + private selectedTime: Date = new Date('2022-07-22T08:00:00') + + build() { + TimePicker({ + selected: this.selectedTime + }) + .disappearTextStyle({ color: '#004aaf', font: { size: 24, weight: FontWeight.Lighter } }) + .textStyle({ color: Color.Black, font: { size: 26, weight: FontWeight.Normal } }) + .selectedTextStyle({ color: Color.Blue, font: { size: 30, weight: FontWeight.Bolder } }) + .onChange((value: TimePickerResult) => { + if (value.hour >= 0) { + this.selectedTime.setHours(value.hour, value.minute) + console.info('select current date is: ' + JSON.stringify(value)) + } + }) + } +} +``` + +![timePicker](figures/TimePickerDemo1.png) + +### Example 2: Switching Between 12-Hour and 24-Hour Formats + +This example demonstrates how to switch between 12-hour and 24-hour formats using **useMilitaryTime**. + ```ts // xxx.ets @Entry @@ -212,22 +491,189 @@ struct TimePickerExample { .onClick(() => { this.isMilitaryTime = !this.isMilitaryTime }) + TimePicker({ - selected: this.selectedTime, + selected: this.selectedTime }) .useMilitaryTime(this.isMilitaryTime) .onChange((value: TimePickerResult) => { - if(value.hour >= 0) { + if (value.hour >= 0) { + this.selectedTime.setHours(value.hour, value.minute) + console.info('select current time is: ' + JSON.stringify(value)) + } + }) + .onEnterSelectedArea((value: TimePickerResult) => { + console.info('item enter selected area, time is: ' + JSON.stringify(value)) + }) + }.width('100%') + } +} +``` + + + +### Example 3: Setting the Time Format + +This example shows how to set the time format using **format** and **dateTimeOptions**. + +```ts +// xxx.ets +@Entry +@Component +struct TimePickerExample { + private selectedTime: Date = new Date('2022-07-22T08:00:00') + + build() { + Column() { + TimePicker({ + selected: this.selectedTime, + format: TimePickerFormat.HOUR_MINUTE_SECOND + }) + .dateTimeOptions({ hour: "numeric", minute: "2-digit", second: "2-digit" }) + .onChange((value: TimePickerResult) => { + if (value.hour >= 0) { + this.selectedTime.setHours(value.hour, value.minute) + console.info('select current date is: ' + JSON.stringify(value)) + } + }) + }.width('100%') + } +} +``` + + + +### Example 4: Setting Loopable Scrolling + +This example demonstrates how to set whether scrolling is loopable using **loop**. + +```ts +// xxx.ets +@Entry +@Component +struct TimePickerExample { + @State isLoop: boolean = true + private selectedTime: Date = new Date('2022-07-22T12:00:00') + + build() { + Column() { + TimePicker({ + selected: this.selectedTime + }) + .loop(this.isLoop) + .onChange((value: TimePickerResult) => { + if (value.hour >= 0) { + this.selectedTime.setHours(value.hour, value.minute) + console.info('select current date is: ' + JSON.stringify(value)) + } + }) + + Row() { + Text('Loopable scrolling').fontSize(20) + + Toggle({ type: ToggleType.Switch, isOn: true }) + .onChange((isOn: boolean) => { + this.isLoop = isOn + }) + }.position({ x: '60%', y: '40%' }) + + }.width('100%') + } +} +``` + + + +### Example 5: Setting the Start Time + +This example demonstrates how to set the start time for the time picker. + +```ts +// xxx.ets +@Entry +@Component +struct TimePickerExample { + private selectedTime: Date = new Date('2022-07-22T08:50:00') + + build() { + Column() { + TimePicker({ + selected: this.selectedTime, + format: TimePickerFormat.HOUR_MINUTE_SECOND, + start: new Date('2022-07-22T08:30:00') + }) + .dateTimeOptions({ hour: "numeric", minute: "2-digit", second: "2-digit" }) + .onChange((value: TimePickerResult) => { + if (value.hour >= 0) { + this.selectedTime.setHours(value.hour, value.minute) + console.info('select current date is: ' + JSON.stringify(value)) + } + }) + }.width('100%') + } +} +``` +![timePicker](figures/TimePickerDemo5.png) + +### Example 6: Setting the End Time + +This example demonstrates how to set the end time for the time picker. + +```ts +// xxx.ets +@Entry +@Component +struct TimePickerExample { + private selectedTime: Date = new Date('2022-07-22T08:50:00') + + build() { + Column() { + TimePicker({ + selected: this.selectedTime, + format: TimePickerFormat.HOUR_MINUTE_SECOND, + end: new Date('2022-07-22T15:20:00'), + }) + .dateTimeOptions({ hour: "numeric", minute: "2-digit", second: "2-digit" }) + .onChange((value: TimePickerResult) => { + if (value.hour >= 0) { + this.selectedTime.setHours(value.hour, value.minute) + console.info('select current date is: ' + JSON.stringify(value)) + } + }) + }.width('100%') + } +} +``` + +![timePicker](figures/TimePickerDemo6.png) + +### Example 7: Enabling the AM/PM Indicator to Automatically Switch Based on the Hour in 12-hour Format + +This example demonstrates how to enable AM/PM indicator to automatically switch based on the hour in 12-hour format using **enableCascade** and **loop**. + +```ts +// xxx.ets +@Entry +@Component +struct TimePickerExample { + private selectedTime: Date = new Date('2022-07-22T08:00:00') + + build() { + Column() { + TimePicker({ + selected: this.selectedTime, + }) + .enableCascade(true) + .loop(true) + .onChange((value: TimePickerResult) => { + if (value.hour >= 0) { this.selectedTime.setHours(value.hour, value.minute) console.info('select current date is: ' + JSON.stringify(value)) } }) - .disappearTextStyle({color: Color.Red, font: {size: 15, weight: FontWeight.Lighter}}) - .textStyle({color: Color.Black, font: {size: 20, weight: FontWeight.Normal}}) - .selectedTextStyle({color: Color.Blue, font: {size: 30, weight: FontWeight.Bolder}}) }.width('100%') } } ``` -![timePicker](figures/timePicker.gif) + diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-toggle.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-toggle.md index 16ca4f4da95b37f044d0730af469d7c3907ffb55..83cc8ea14b623acc798413d05db70857ca4b8fa5 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-toggle.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-toggle.md @@ -25,20 +25,20 @@ Toggle(options: ToggleOptions) | Name| Type| Mandatory | Description | | ---- | ---------- | -----| -------------- | -| options | [ToggleOptions](#toggleoptions13) | Yes | Options of the toggle.| +| options | [ToggleOptions](#toggleoptions18) | Yes | Options of the toggle.| -## ToggleOptions13+ +## ToggleOptions18+ -**Widget capability**: This API can be used in ArkTS widgets since API version 13. +**Widget capability**: This API can be used in ArkTS widgets since API version 18. -**Atomic service API**: This API can be used in atomic services since API version 13. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name| Type | Mandatory| Description | -| ---- | --------------------------------- | ---- | ------------------------------------------------------------ | -| type | [ToggleType](#toggletype) | Yes | Type of the toggle.
Default value: **ToggleType.Switch** | -| isOn | boolean | No | Whether the toggle is turned on. The value **true** means that the toggle is turned on, and **false** means the opposite.
Default value: **false**
This parameter supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md).| +| Name | Type | Mandatory| Description | +| ----------------- | --------------------------------- | ---- | ------------------------------------------------------------ | +| type8+ | [ToggleType](#toggletype) | Yes | Type of the toggle.
Default value: **ToggleType.Switch**
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| isOn8+ | boolean | No | Whether the toggle is turned on. The value **true** means that the toggle is turned on, and **false** means the opposite.
Default value: **false**
This parameter supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md).
This attribute supports two-way binding through [!!](../../../quick-start/arkts-new-binding.md).
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11.| ## ToggleType @@ -52,11 +52,11 @@ Toggle(options: ToggleOptions) | -------- | ---------------- | | Checkbox | Check box type.
**NOTE**
Since API version 11, the default style of the **Checkbox** component is changed from rounded square to circle.
The default value of the universal attribute [margin](ts-universal-attributes-size.md#margin) is as follows:
{
top: '14px',
right: '14px',
bottom: '14px',
left: '14px'
}.
Default size:
{width:'20vp', height:'20vp'}| | Button | Button type. The set string, if any, will be displayed inside the button.
The default height is 28 vp, and there is no default width. | -| Switch | Switch type.
**NOTE**
The default value of the universal attribute [margin](ts-universal-attributes-size.md) is as follows:
{
top: '6px',
right: '14px',
bottom: '6px',
left: '14px'
}.
Default size:
{width:'36vp', height:'20vp'}| +| Switch | Switch type.
**NOTE**
The default value of the universal attribute [margin](ts-universal-attributes-size.md#margin) is as follows:
{
top: '6px',
right: '14px',
bottom: '6px',
left: '14px'
}.
Default size:
{width:'36vp', height:'20vp'}| ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### selectedColor @@ -134,14 +134,14 @@ Creates a content modifier. | Name | Type | Mandatory| Description | | ----------------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | -| pointRadius | number \| [Resource](ts-types.md#resource) | No | Radius of the circular slider when the component is of the **Switch** type.
**NOTE**
This parameter cannot be set in percentage. The value specified is used only when it is greater than or equal to 0.
If the value is not specified or the specified one is less than 0, the radius is set using the following formula:
(Component height (in vp)/2) - (2 vp x Component height (in vp)/20 vp)| +| pointRadius | number \| [Resource](ts-types.md#resource) | No | Radius of the circular slider when the component is of the **Switch** type. The unit is vp.
**NOTE**
This parameter cannot be set in percentage. The value specified is used only when it is greater than or equal to 0.
If the value is not specified or the specified one is less than 0, the radius is set using the following formula:
(Component height (in vp)/2) - (2 vp x Component height (in vp)/20 vp)| | unselectedColor | [ResourceColor](ts-types.md#resourcecolor) | No | Background color of the component when it is of the **Switch** type and is disabled.
Default value: **0x337F7F7F**| | pointColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the circular slider when the component is of the **Switch** type.
Default value: **$r('sys.color.ohos_id_color_foreground_contrary')**| -| trackBorderRadius | number \| [Resource](ts-types.md#resource) | No | Radius of the slider track border corners when the component is of the **Switch** type.
**NOTE**
This parameter cannot be set in percentage. If the value specified is less than 0, the radius is set using the default value formula. If the value specified is greater than half of the component height, the latter is used. In other cases, the value specified is used.
If the value is not specified or the specified one is less than 0, the radius is set using the default value formula.
Default value formula: Component height (in vp)/2| +| trackBorderRadius | number \| [Resource](ts-types.md#resource) | No | Radius of the slider track border corners when the component is of the **Switch** type. The unit is vp.
**NOTE**
This parameter cannot be set in percentage. If the value specified is less than 0, the radius is set using the default value formula. If the value specified is greater than half of the component height, the latter is used. In other cases, the value specified is used.
If the value is not specified or the specified one is less than 0, the radius is set using the default value formula.
Default value formula: Component height (in vp)/2| ## Events -In addition to the [universal events](ts-universal-events-click.md), the following events are supported. +In addition to the [universal events](ts-component-general-events.md), the following events are supported. ### onChange @@ -171,14 +171,16 @@ You need a custom class to implement the **ContentModifier** API. | Name | Type | Read-Only | Optional | Description | | ------ | ------ | ------ |-------------------------------- |-------------------------------- | -| isOn | boolean| No | No| Whether the toggle is on.
Default value: **false**| -| enabled | boolean | No| No| Whether the toggle is enabled.| -| triggerChange |Callback\| No| No|Triggers toggle status changes.| +| isOn | boolean| No | No| Whether the toggle is turned on.
Default value: **false**
The value **true** means that the toggle is turned on, and **false** means the opposite.| +| enabled | boolean | No| No| Whether the toggle is enabled. When enabled, the toggle allows state switching.
Default value: **true**
The value **true** means that the toggle is enabled, and **false** means the opposite.| +| triggerChange |Callback\| No| No|Callback invoked when the toggle's state changes.
Whether the toggle is on.
**true**: The toggle is on. The value **true** means the state changes from off to on, and **false** means the state changes from on to off.| ## Example -### Example 1 +### Example 1: Setting the Toggle Style + +This example demonstrates how to configure the style for different types of toggles (checkbox, switch, and button) using **ToggleType**. ```ts // xxx.ets @@ -246,7 +248,7 @@ struct ToggleExample { ![toggle](figures/toggle.gif) -### Example 2 +### Example 2: Customizing the Toggle Style This example implements a toggle of the **Switch** type with custom settings, including the radius and color of the circular slider, background color in the off state, and radius of the slider track border corners. @@ -288,7 +290,7 @@ struct ToggleExample { ![toggle](figures/toggleSwitchStyle.gif) -### Example 3 +### Example 3: Implementing a Custom Toggle Style This example implements a toggle in a custom style. When you click the **Blue** button, the circle background turns blue. When you click the **Yellow** button, the circle background turns yellow. diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-xcomponent-sys.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-xcomponent-sys.md new file mode 100644 index 0000000000000000000000000000000000000000..a30ffd534f383c42ba2a07faf318e44d007ebc49 --- /dev/null +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-components-xcomponent-sys.md @@ -0,0 +1,55 @@ +# XComponent + +**XComponent** provides a surface for graphics rendering and media data input into your view. You can customize the position and size of the surface as needed. + +> **NOTE** +> +> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. +> +> This topic describes only system APIs provided by the module. For details about its public APIs, see [XComponent](ts-basic-components-xcomponent.md). + +## Attributes + +### hdrBrightness14+ + +hdrBrightness(brightness: number) + +Sets the brightness of HDR video playback for the component. + +**System API**: This attribute can be used in system APIs since API version 14. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------- | ---- | ---------------------- | +| brightness | number | Yes | Brightness of HDR video playback.
Value range: 0.0 to 1.0.
Values less than 0 are equivalent to 0, and values greater than 1 are equivalent to 1.
**0** indicates the brightness of the SDR video, and **1** indicates the brightness of the HDR video.| + + > **NOTE** + > + > This attribute is effective only when **type** is set to **SURFACE**. + > + > It is not supported for **XComponent** components created using the [ArkUI NDK API](../../../ui/ndk-build-ui-overview.md). + +### enableTransparentLayer18+ + +enableTransparentLayer(enabled: boolean) + +Sets whether to enable an independent layer for the **XComponent** component when its background is transparent. + +**System API**: This attribute can be used in system APIs since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | ---------------------- | +| enabled | boolean | Yes | Whether to enable an independent layer for the **XComponent** component when its background is transparent.| + + > **NOTE** + > + > This attribute is effective only when **type** is set to **SURFACE**. + > + > It is not supported for **XComponent** components created using the [ArkUI NDK API](../../../ui/ndk-build-ui-overview.md). diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-gestures-longpressgesture.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-gestures-longpressgesture.md index 706ae22640695284868c5938063adc968f2f9b2e..821e1361fc9ffaec9a84b6887869ef7fcbbe6df4 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-gestures-longpressgesture.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-gestures-longpressgesture.md @@ -24,8 +24,9 @@ If the minimum duration of the long press gesture is greater than or equal to 50 | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | fingers | number | No| Minimum number of fingers to trigger a long press gesture. The value ranges from 1 to 10.
Default value: **1**
**NOTE**
If a finger moves more than 15 px after being pressed, the gesture recognition fails.| -| repeat | boolean | No| Whether to continuously trigger the event callback.
Default value: **false**| -| duration | number | No| Minimum hold-down time, in ms.
Default value: **500**
**NOTE**
If the value is less than or equal to 0, the default value **500** will be used.| +| repeat | boolean | No| Whether to continuously trigger the event callback. The value **true** means to continuously trigger the event callback, and **false** means the opposite.
Default value: **false**| +| duration | number | No| Minimum hold-down time, in ms.
Default value: **500**
**NOTE**
Value range: [0, +∞). If the value is less than or equal to 0, the default value **500** is used.| +| isFingerCountLimited15+ | boolean | No| Whether to enforce the exact number of fingers touching the screen. With the value **true**, the gesture recognition fails if the number of fingers touching the screen does not match the configured value of **fingers**.
For gestures that have already been successfully recognized, changes in the number of fingers touching the screen will not trigger the repeat event. However, if the number of fingers touching the screen returns to the configured minimum number, the [onAction](ts-basic-gestures-longpressgesture.md#events) event can be triggered. The [onActionEnd](ts-basic-gestures-longpressgesture.md#events) event can also be triggered regardless of the finger count.
Default value: **false**| ## Events @@ -35,7 +36,7 @@ If the minimum duration of the long press gesture is greater than or equal to 50 | onAction(event:(event: [GestureEvent](ts-gesture-settings.md#gestureevent)) => void) | Invoked when a long press gesture is recognized.
**Atomic service API**: This API can be used in atomic services since API version 11.| | onActionEnd(event:(event: [GestureEvent](ts-gesture-settings.md#gestureevent)) => void) | Invoked when the last finger is lifted after the long press gesture is recognized.
**Atomic service API**: This API can be used in atomic services since API version 11.| | onActionCancel(event: () => void) | Invoked when a tap cancellation event is received after the long press gesture is recognized. No gesture event information is returned.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| onActionCancel(event:(event: [GestureEvent](ts-gesture-settings.md#gestureevent)) => void)16+ | Invoked when a tap cancellation event is received after the long press gesture is recognized. Gesture event information is returned.
**Atomic service API**: This API can be used in atomic services since API version 16.| +| onActionCancel(event:(event: [GestureEvent](ts-gesture-settings.md#gestureevent)) => void)18+ | Invoked when a tap cancellation event is received after the long press gesture is recognized. Gesture event information is returned.
**Atomic service API**: This API can be used in atomic services since API version 18.| ## Attributes @@ -47,7 +48,7 @@ If the minimum duration of the long press gesture is greater than or equal to 50 ## Example -This example demonstrates the recognition of a long press gesture using **TapGesture**. +This example demonstrates the recognition of a long press gesture using **LongPressGesture**. ```ts // xxx.ets diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-gestures-pangesture.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-gestures-pangesture.md index 79413efd20eb555226c80598f3f0d38872315dc3..3893321be5022b1535503862fbab7542d01fadd4 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-gestures-pangesture.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-gestures-pangesture.md @@ -19,7 +19,8 @@ PanGesture(value?: { fingers?: number, direction?: PanDirection, distance?: numb | -------- | -------- | -------- | -------- | | fingers | number | No| Minimum number of fingers to trigger a pan gesture. The value ranges from 1 to 10.
Default value: **1**
Value range: 1 to 10
**NOTE**
If the value is less than 1 or is not set, the default value is used.| | direction | [PanDirection](#pandirection) | No| Pan direction. The value supports the AND (&) and OR (\|) operations.
Default value: **PanDirection.All**| -| distance | number | No| Minimum pan distance to trigger the gesture, in vp.
Default value: **5**
**NOTE**
If a pan gesture and a [tab](ts-container-tabs.md) swipe occur at the same time, set **distance** to **1** to make the gesture more easily recognizable.
If the value specified is less than **0**, the default value **5** is used.| +| distance | number | No| Minimum pan distance to trigger the gesture, in vp.
Value range: [0, +∞)
Default value: **5**
**NOTE**
If a pan gesture and a [tab](ts-container-tabs.md) swipe occur at the same time, set **distance** to **1** to make the gesture more easily recognizable.
If the value specified is less than **0**, the default value **5** is used.| +| isFingerCountLimited15+ | boolean | No| Whether to enforce the exact number of fingers touching the screen. With the value **true**, the gesture recognition fails if the number of fingers touching the screen does not match the configured value of **fingers**. The gesture can only be successfully recognized if the number of fingers touching the screen equals the configured minimum number and the swipe distance meets the threshold.
For gestures that have already been successfully recognized, changing the number of fingers touching the screen will not trigger the [onActionUpdate](ts-basic-gestures-pangesture.md#events) event, but the [onActionEnd](ts-basic-gestures-pangesture.md#events) event can still be triggered.
Default value: **false**| ## PanDirection @@ -59,10 +60,11 @@ PanGestureOptions(value?: { fingers?: number, direction?: PanDirection, distance | Name| Description| | -------- | -------- | -| setDirection(value: [PanDirection](#pandirection)) | Sets the direction.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| setDistance(value: number) | Sets the distance.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| setFingers(value: number) | Sets the number of fingers.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| getDirection()12+: [PanDirection](#pandirection)| Obtains the direction.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| setDirection(value: [PanDirection](#pandirection)) | Sets the pan direction.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| setDistance(value: number) | Sets the minimum pan distance to trigger the gesture, in vp.
Value range: [0, +∞)
**Atomic service API**: This API can be used in atomic services since API version 11.| +| setFingers(value: number) | Sets the minimum number of fingers to trigger the gesture.
Value range: an integer from 1 to 10
**Atomic service API**: This API can be used in atomic services since API version 11.| +| getDirection()12+: [PanDirection](#pandirection)| Obtains the pan direction.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| getDistance()18+: (value: number) | Obtains the minimum pan distance to trigger the gesture.
**Atomic service API**: This API can be used in atomic services since API version 18.| ## Events @@ -73,7 +75,7 @@ PanGestureOptions(value?: { fingers?: number, direction?: PanDirection, distance | onActionUpdate(event: (event: [GestureEvent](ts-gesture-settings.md#gestureevent)) => void) | Invoked when the pan gesture status is updated.
If **fingerList** contains multiple fingers, this callback updates the location information of only one finger each time.
**Atomic service API**: This API can be used in atomic services since API version 11.| | onActionEnd(event: (event: [GestureEvent](ts-gesture-settings.md#gestureevent)) => void) | Invoked when the finger used for a pan gesture is lifted.
**Atomic service API**: This API can be used in atomic services since API version 11.| | onActionCancel(event: () => void) | Invoked when a tap cancellation event is received after a pan gesture is recognized. No gesture event information is returned.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| onActionCancel(event: (event: [GestureEvent](ts-gesture-settings.md#gestureevent)) => void)16+ | Invoked when a tap cancellation event is received after a pan gesture is recognized. Gesture event information is returned.
**Atomic service API**: This API can be used in atomic services since API version 16.| +| onActionCancel(event: (event: [GestureEvent](ts-gesture-settings.md#gestureevent)) => void)18+ | Invoked when a tap cancellation event is received after a pan gesture is recognized. Gesture event information is returned.
**Atomic service API**: This API can be used in atomic services since API version 18.| ## Attributes diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-gestures-pinchgesture.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-gestures-pinchgesture.md index 5ae70627528ee84376e08ee4d7085e35c51735f1..2845e9f2769d11c4775b1ce620d1576deb9a95df 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-gestures-pinchgesture.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-gestures-pinchgesture.md @@ -18,7 +18,8 @@ PinchGesture(value?: { fingers?: number, distance?: number }) | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | fingers | number | No| Minimum number of fingers to trigger a pinch. The value ranges from 2 to 5.
Default value: **2**
While more fingers than the minimum number can be pressed to trigger the gesture, only the first fingers of the minimum number participate in gesture calculation.| -| distance | number | No| Minimum recognition distance, in vp.
Default value: **5**
**NOTE**
If the value is less than or equal to 0, it will be converted to the default value.| +| distance | number | No| Minimum recognition distance, in vp.
Default value: **5**
**NOTE**
Value range: [0, +∞). If the value is less than or equal to 0, the default value is used.| +| isFingerCountLimited15+ | boolean | No| Whether to enforce the exact number of fingers touching the screen. With the value **true**, the gesture recognition fails if the number of fingers touching the screen does not match the configured value of **fingers**. The gesture can only be successfully recognized if the number of fingers equals the configured minimum and the swipe distance meets the threshold. Note that only the first two fingers that touch the screen are considered for the gesture. If one of these fingers is lifted, the gesture recognition fails. For gestures that have already been successfully recognized, changing the number of fingers touching the screen will not trigger the [onActionUpdate](ts-basic-gestures-pinchgesture.md#events) event, but the [onActionEnd](ts-basic-gestures-pinchgesture.md#events) event can still be triggered.
Default value: **false**| ## Events @@ -29,7 +30,7 @@ PinchGesture(value?: { fingers?: number, distance?: number }) | onActionUpdate(event:(event: [GestureEvent](ts-gesture-settings.md#gestureevent)) => void) | Triggered when the user moves the finger in the pinch gesture on the screen.
**Atomic service API**: This API can be used in atomic services since API version 11.| | onActionEnd(event:(event: [GestureEvent](ts-gesture-settings.md#gestureevent)) => void) | Triggered when the fingers used for the pinch gesture are lifted.
**Atomic service API**: This API can be used in atomic services since API version 11.| | onActionCancel(event: () => void) | Triggered when a tap cancellation event is received after the pinch gesture is recognized. No gesture event information is returned.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| onActionCancel(event:(event: [GestureEvent](ts-gesture-settings.md#gestureevent)) => void)16+ | Triggered when a tap cancellation event is received after the pinch gesture is recognized. Gesture event information is returned.
**Atomic service API**: This API can be used in atomic services since API version 16.| +| onActionCancel(event:(event: [GestureEvent](ts-gesture-settings.md#gestureevent)) => void)18+ | Triggered when a tap cancellation event is received after the pinch gesture is recognized. Gesture event information is returned.
**Atomic service API**: This API can be used in atomic services since API version 18.| ## Attributes diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-gestures-rotationgesture.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-gestures-rotationgesture.md index d500b55d6d76205ccdec80afc5a900f67c012d7b..ddb669de80aff6688c3b953ef9c7a099c26242ae 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-gestures-rotationgesture.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-gestures-rotationgesture.md @@ -1,6 +1,6 @@ # RotationGesture -**RotationGesture** is used to trigger a rotation gesture, which requires two to five fingers with a minimum 1-degree rotation angle. +**RotationGesture** is used to trigger a rotation gesture, which requires two to five fingers with a minimum 1-degree rotation angle. This gesture cannot be triggered using a two-finger rotation operation on a trackpad. > **NOTE** > @@ -19,6 +19,7 @@ RotationGesture(value?: { fingers?: number, angle?: number }) | -------- | -------- | -------- | -------- | | fingers | number | No| Minimum number of fingers to trigger a rotation. The value ranges from 2 to 5.
Default value: **2**
While more fingers than the minimum number can be pressed to trigger the gesture, only the first two fingers participate in gesture calculation.| | angle | number | No| Minimum degree that can trigger the rotation gesture.
Default value: **1**
**NOTE**
If the value is less than or equal to 0 or greater than 360, it will be converted to the default value.| +| isFingerCountLimited15+ | boolean | No| Whether to enforce the exact number of fingers touching the screen. With the value **true**, the gesture recognition fails if the number of fingers touching the screen does not match the configured value of **fingers**. The gesture can only be successfully recognized if the number of fingers equals the configured minimum and the swipe distance meets the threshold. Note that only the first two fingers that touch the screen are considered for the gesture. If one of these fingers is lifted, the gesture recognition fails.
For gestures that have already been successfully recognized, changing the number of fingers touching the screen will not trigger the[onActionUpdate](ts-basic-gestures-rotationgesture.md#events) event, but the [onActionEnd](ts-basic-gestures-rotationgesture.md#events) event can still be triggered.
Default value: **false**| ## Events @@ -29,7 +30,7 @@ RotationGesture(value?: { fingers?: number, angle?: number }) | onActionUpdate(event:(event: [GestureEvent](ts-gesture-settings.md#gestureevent)) => void) | Triggered when the user moves the finger in a rotation gesture on the screen.
**Atomic service API**: This API can be used in atomic services since API version 11.| | onActionEnd(event:(event: [GestureEvent](ts-gesture-settings.md#gestureevent)) => void) | Triggered when the finger used for the rotation gesture is lifted.
**Atomic service API**: This API can be used in atomic services since API version 11.| | onActionCancel(event: () => void) | Triggered when a tap cancellation event is received after the rotation gesture is recognized. No gesture event information is returned.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| onActionCancel(event:(event: [GestureEvent](ts-gesture-settings.md#gestureevent)) => void)16+ | Triggered when a tap cancellation event is received after the rotation gesture is recognized. Gesture event information is returned.
**Atomic service API**: This API can be used in atomic services since API version 16.| +| onActionCancel(event:(event: [GestureEvent](ts-gesture-settings.md#gestureevent)) => void)18+ | Triggered when a tap cancellation event is received after the rotation gesture is recognized. Gesture event information is returned.
**Atomic service API**: This API can be used in atomic services since API version 18.| ## Attributes diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-gestures-swipegesture.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-gestures-swipegesture.md index 796423197bd1c44ef8207b3d6ddb936a802a155e..a2287962a2393277b267f4e0c30547e744183a7f 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-gestures-swipegesture.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-gestures-swipegesture.md @@ -20,6 +20,7 @@ SwipeGesture(value?: { fingers?: number, direction?: SwipeDirection, speed?: num | fingers | number | No| Minimum number of fingers to trigger a swipe gesture. The value ranges from 1 to 10.
Default value: **1**| | direction | [swipeDirection](#swipedirection)| No| Swipe direction.
Default value: **SwipeDirection.All**| | speed | number | No| Minimum speed of the swipe gesture.
Default value: 100 vp/s
**NOTE**
If the value is less than or equal to 0, it will be converted to the default value.| +| isFingerCountLimited15+ | boolean | No| Whether to enforce the exact number of fingers touching the screen. With the value **true**, the gesture recognition fails if the number of fingers touching the screen does not match the configured value of **fingers**.
Default value: **false**| ## SwipeDirection diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-gestures-tapgesture.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-gestures-tapgesture.md index eb0d5434a14ca0e3c71104aac4d3645702b55142..b005de4a5719ff36364a867e537480b03fbc4096 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-gestures-tapgesture.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-gestures-tapgesture.md @@ -11,7 +11,9 @@ TapGesture(value?: TapGestureParameters) -**Atomic service API**: This API can be used in atomic services since API version 12. +Triggers a tap gesture with one or more taps. When the gesture is triggered by a keyboard or gamepad, the value of **SourceTool** is **Unknown**. + +**Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -32,6 +34,7 @@ TapGesture(value?: TapGestureParameters) | count | number | No| Number of consecutive taps. If the value is less than 1 or is not set, the default value is used.
Default value: **1**
**NOTE**
1. If multi-tap is configured, the timeout interval between a lift and the next tap is 300 ms.
2. If the distance between the last tapped position and the current tapped position exceeds 60 vp, gesture recognition fails. In multi-finger scenarios, the tapped position is the average position of all fingers involved in the gesture response.| | fingers | number | No| Number of fingers required to trigger a tap. The value ranges from 1 to 10. If the value is less than 1 or is not set, the default value is used.
Default value: **1**
**NOTE**
1. For a multi-finger gesture, recognition fails if the required number of fingers is not pressed within 300 ms after the first finger; when fingers are lifted, if the remaining number of fingers is below the threshold after lifting, all fingers must be lifted within 300 ms for the gesture to be successfully recognized.
2. When the number of fingers touching the screen exceeds the set value, the gesture can be recognized.| | distanceThreshold | number | No| Movement threshold for the tap gesture. If the value is less than or equal to 0 or is not set, the default value is used.
Default value: 2^31-1
**NOTE**
If the finger movement exceeds the preset movement threshold, the tap gesture recognition fails. If the default threshold is used during initialization and the finger moves beyond the component's touch target, the tap gesture recognition fails.| +| isFingerCountLimited15+ | boolean | No| Whether to enforce the exact number of fingers touching the screen. With the value **true**, the gesture recognition fails if the number of fingers touching the screen does not match the configured value of **fingers**.
In multi-tap events (where the **count** parameter is greater than 1), each tap must have the same number of fingers as the configured value; otherwise, the gesture recognition fails.
Default value: **false**| ## Events diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-svg.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-svg.md index 60dafb9d476ca2f0944c710fd01c9cec5092622b..7a35079da56766dd67b801cccba5fa75e7e762dd 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-svg.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-basic-svg.md @@ -15,7 +15,7 @@ The basic shape tags include the following: \, \, \, \ | :-------- | :-------- | :-------- | | \ | Rectangle| **x**: x-axis offset.
**y**: y-axis offset.
**width**: width.
**height**: height.
**rx**: corner radius on the x-axis.
**ry**: corner radius on the y-axis.| | \ | Circle| **cx**: X coordinate of the circle center.
**cy**: Y coordinate of the circle center.
**r**: radius of the circle.| | -| \ | Ellipse| **cx**: X coordinate.
**cy**: Y coordinate.
**rx**: x-axis radius.
**ry**: y-axis radius.
| | +| \ | Ellipse| **cx**: X coordinate.
**cy**: Y coordinate.
**rx**: x-axis radius.
**ry**: y-axis radius.| | | \ | Line| **x1**: X coordinate of the start point.
**y1**: Y coordinate of the start point.
**x2**: X coordinate of the end point.
**y2**: Y coordinate of the end point.| | | \ | Polyline| **points**: vertex coordinates.| | | \ | Polygon| **points**: vertex coordinates.| | @@ -29,20 +29,20 @@ The filter tags include the following: \, \, \ | Defines the filter area.| **x**: x-axis offset of the filter area.
**y**: y-axis offset of the filter area.
**width**: width of the filter area.
**height**: height of the filter area.| +| \ | Defines the filter area.| **x**: x-axis offset of the filter area, with the default value of **0**.
**y**: y-axis offset of the filter area, with the default value of **0**.
**width**: width of the filter area.
**height**: height of the filter area.| | \ | Defines the offset distance along x-axis and y-axis.| **in**: filter input, which can be SourceGraphic, SourceAlpha, or result from other filter effects.
**result**: output after filter processing, which can be used as input for the next filter. The value can include dx and dy.| | \ | Defines the Gaussian blur effect.| **in**: filter input, which can be SourceGraphic, SourceAlpha, or result from other filter effects.
**result**: output after filter processing, which can be used as input for the next filter. The value can include edgemode and stddeviation.| | \ | Defines the blending mode for two input images.| **in**: filter input, which can be SourceGraphic, SourceAlpha, or result from other filter effects.
**result**: output after filter processing, which can be used as input for the next filter.
**in2**: second image source, which can be SourceGraphic, SourceAlpha, or result from other filter effects; mode| -| \ | Defines composition of two input images.
Algorithm: result = k1 * in * in2 + k2 * in + k3 * in2 + k4| **in**: filter input, which can be SourceGraphic, SourceAlpha, or result from other filter effects.
**in2**: second image source, which can be SourceGraphic, SourceAlpha, or result from other filter effects; operator( over \| in \| out \| atop \| xor \| lighter \| arithmetic ), k1, k2, k3, k4| | -| \ | Transforms colors based on a transformation matrix.| **in**: filter input, which can be SourceGraphic, SourceAlpha, or result from other filter effects.
**result**: output after filter processing, which can be used as input for the next filter.
type ( matrix \| saturate \| hueRotate), values| -| \ | Defines the fill color and opacity.| **in**: filter input, which can be SourceGraphic, SourceAlpha, or result from other filter effects.
**result**: output after filter processing, which can be used as input for the next filter; flood-color and flood-opacity| +| \ | Defines composition of two input images.
Algorithm: result = k1 * in * in2 + k2 * in + k3 * in2 + k4| **in**: filter input, which can be SourceGraphic, SourceAlpha, or result from other filter effects.
**in2**: second image source, which can be SourceGraphic, SourceAlpha, or result from other filter effects; operator( over \| in \| out \| atop \| xor \| lighter \| arithmetic ), k1, k2, k3, k4.| +| \ | Transforms colors based on a transformation matrix.| **in**: filter input, which can be SourceGraphic, SourceAlpha, or result from other filter effects.
**result**: output after filter processing, which can be used as input for the next filter.
type ( matrix \| saturate \| hueRotate ), values.| +| \ | Defines the fill color and opacity.| **in**: filter input, which can be SourceGraphic, SourceAlpha, or result from other filter effects.
**result**: output after filter processing, which can be used as input for the next filter; flood-color and flood-opacity.| ### Masks The mask tags include the following: \ | Element| Description| Unique Attribute| | :-------- | :-------- | :-------- | -| \ | Defines the mask area.| **x**: x-axis offset of the mask area.
**y**: y-axis offset of the mask area.
**width**: width of the mask area
**height**: height of the mask area| +| \ | Defines the mask area.| **x**: x-axis offset of the mask area.
**y**: y-axis offset of the mask area.
**width**: width of the mask area
**height**: height of the mask area.| ### Clipping @@ -60,7 +60,7 @@ The pattern tags include the following: \ ### Gradients -The gradient tags include the following: \, \, \ +The gradient tags include the following: \, \, \. | Element| Description| Unique Attribute| | :-------- | :-------- | :-------- | @@ -80,8 +80,8 @@ The image tags include the following: \ The animation tags include the following: \, \ | Element| Description| Unique Attribute| | :-------- | :-------- | :-------- | -| \ | Definies an element attribute animation.| **attributeName**: animatable attribute; values: (cx\| cy \| r \| fill \| stroke \| fill-opacity \| stroke-opacity \| stroke-miterlimit)
**begin**: animation start time.
**dur**: animation duration.
**from**: start value.
**to**: end value.
**fill**: end state of the animation.
**calcMode**: interpolation.
keyTimes, values, keySplines | -| \ | Defines an element transformation animation.| **attributeName**: animatable attribute; value: transform
**type**: transformation type; values: (translate \| scale \| rotate \| skewX \| skewY);
**begin**: animation start time.
**dur**: animation duration.
**from**: start value.
**to**: end value.
**fill**: end state of the animation.
**calcMode**: interpolation.
keyTimes, values, keySplines| +| \ | Defines a property animation.| **attributeName**: animatable attribute; values: (cx\| cy \| r \| fill \| stroke \| fill-opacity \| stroke-opacity \| stroke-miterlimit)
**begin**: animation start time.
**dur**: animation duration.
**from**: start value.
**to**: end value.
**fill**: end state of the animation.
**calcMode**: interpolation.
keyTimes, values, keySplines | +| \ | Defines a transformation animation.| **attributeName**: animatable attribute; value: transform
**type**: transformation type; values: (translate \| scale \| rotate \| skewX \| skewY);
**begin**: animation start time.
**dur**: animation duration.
**from**: start value.
**to**: end value.
**fill**: end state of the animation.
**calcMode**: interpolation.
keyTimes, values, keySplines| > **NOTE** > diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-canvasrenderingcontext2d.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-canvasrenderingcontext2d.md index e942a7155880673066afa9117bfb6512dd5ed040..74dff5572737b49aa9cd44cead417f0321902ec1 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-canvasrenderingcontext2d.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-canvasrenderingcontext2d.md @@ -5,6 +5,10 @@ Use **RenderingContext** to draw rectangles, text, images, and other objects on > **NOTE** > > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. +> +> When you call drawing APIs in this module, the commands are stored in the associated **Canvas** component's command queue. These commands are only executed when the current frame enters the rendering phase and the associated **Canvas** component is visible. As such, avoid frequent drawing calls when the **Canvas** component is not visible to prevent command accumulation in the queue, which can lead to excessive memory usage. +> +> If the width or height of the **Canvas** component exceeds 8000 px, the CPU is used for rendering, which can significantly degrade performance. @@ -22,8 +26,8 @@ CanvasRenderingContext2D(settings?: RenderingContextSettings, unit?: LengthMetri | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| settings | [RenderingContextSettings](#renderingcontextsettings) | No | Settings of the **CanvasRenderingContext2D** object. For details, see [RenderingContextSettings](#renderingcontextsettings). | -| unit12+ | [LengthMetricsUnit](../js-apis-arkui-graphics.md#lengthmetricsunit12) | No | Unit mode of the **CanvasRenderingContext2D** object. The value cannot be dynamically changed once set. For details, see [LengthMetricsUnit](#lengthmetricsunit12).
Default value: **DEFAULT** | +| settings | [RenderingContextSettings](#renderingcontextsettings) | No | Settings of the **CanvasRenderingContext2D** object. For details, see [RenderingContextSettings](#renderingcontextsettings).| +| unit12+ | [LengthMetricsUnit](../js-apis-arkui-graphics.md#lengthmetricsunit12) | No | Unit mode of the **CanvasRenderingContext2D** object. The value cannot be dynamically changed once set. For details, see [LengthMetricsUnit](#lengthmetricsunit12).
Default value: **DEFAULT**| ### RenderingContextSettings @@ -46,7 +50,7 @@ Configures the settings of a **CanvasRenderingContext2D** object, including whet ### LengthMetricsUnit12+ -Unit mode of the **CanvasRenderingContext2D** object. The value cannot be dynamically changed once set. For details, see [LengthMetricsUnit](../js-apis-arkui-graphics.md#lengthmetricsunit12). +Defines the unit of the **CanvasRenderingContext2D** object. The default unit is **LengthMetricsUnit.DEFAULT**, corresponding to the vp unit. The value cannot be dynamically changed once set. For details, see [LengthMetricsUnit](../js-apis-arkui-graphics.md#lengthmetricsunit12). **Example** @@ -97,30 +101,32 @@ struct LengthMetricsUnitDemo { **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Read Only | Optional | Description | +| Name| Type| Read Only| Optional| Description| | --------- | ------------------------------- | ------------------ | ---------------------- | ---------------------------------------- | -| [fillStyle](#fillstyle) | string \|number10+ \|[CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](ts-components-canvas-canvaspattern.md#canvaspattern) | No | No | Style to fill an area.
- When the type is string, this attribute indicates the color of the fill area.
Default value: **'black'**
- When the type is number, this attribute indicates the color of the fill area.
Default value: **'#000000'**
- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.
- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API. | -| [lineWidth](#linewidth) | number | No | No | Line width.
Default value: **1(px)**
Default unit: vp
The value cannot be **0** or a negative number. If it is set to **0** or a negative number, the default value is used instead. | -| [strokeStyle](#strokestyle) | string \|number10+ \|[CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](ts-components-canvas-canvaspattern.md#canvaspattern) | No | No | Stroke color.

Default value: **'black'**

Default value: **'#000000'**
- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.
- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API. | -| [lineCap](#linecap) | [CanvasLineCap](#canvaslinecap) | No | No | Style of the line endpoints. The options are as follows:
- **'butt'**: The endpoints of the line are squared off.
- **'round'**: The endpoints of the line are rounded.
- **'square'**: The endpoints of the line are squared off by adding a box with an equal width and half the height of the line's thickness.
Default value: **'butt'** | -| [lineJoin](#linejoin) | [CanvasLineJoin](#canvaslinejoin) | No | No | Style of the shape used to join line segments. The options are as follows:
- **'round'**: The shape used to join line segments is a sector, whose radius at the rounded corner is equal to the line width.
- **'bevel'**: The shape used to join line segments is a triangle. The rectangular corner of each line is independent.
- **'miter'**: The shape used to join line segments has a mitered corner by extending the outside edges of the lines until they meet. You can view the effect of this attribute in **miterLimit**.
Default value: **'miter'** | -| [miterLimit](#miterlimit) | number | No | No | Maximum miter length. The miter length is the distance between the inner corner and the outer corner where two lines meet.
Default value: **10**
Unit: px
The value cannot be **0** or a negative number. If it is set to **0** or a negative number, the default value is used instead. | -| [font](#font) | string | No | No | Font style.
Syntax: ctx.font='font-size font-family'
- (Optional) **font-size**: font size and line height. The unit can be px or vp.
- (Optional) **font-family**: font family.
Syntax: ctx.font='font-style font-weight font-size font-family'
- (Optional) **font-style**: font style. Available values are **'normal'** and **'italic'**.
- (Optional) **font-weight**: font weight. Available values are as follows: **'normal'**, **'bold'**, **'bolder'**, **'lighter'**, **'100'**, **'200'**, **'300'**, **'400'**, **'500'**, **'600'**, **'700'**, **'800'**, **'900'**.
- (Optional) **font-size**: font size and line height. The unit must be specified and can be px or vp.
- (Optional) **font-family**: font family. Available values are **'sans-serif'**, **'serif'**, and **'monospace'**.
Default value: **'normal normal 14px sans-serif'** | -| [textAlign](#textalign) | [CanvasTextAlign](#canvastextalign) | No | No | Text alignment mode. Available values are as follows:
- **'left'**: The text is left-aligned.
- **'right'**: The text is right-aligned.
- **'center'**: The text is center-aligned.
- **'start'**: The text is aligned with the start bound.
- **'end'**: The text is aligned with the end bound.
In the **ltr** layout mode, the value **'start'** equals **'left'**. In the **rtl** layout mode, the value **'start'** equals **'right'**.
Default value: **'left'** | -| [textBaseline](#textbaseline) | [CanvasTextBaseline](#canvastextbaseline) | No | No | Horizontal alignment mode of text. Available values are as follows:
- **'alphabetic'**: The text baseline is the normal alphabetic baseline.
- **'top'**: The text baseline is on the top of the text bounding box.
- **'hanging'**: The text baseline is a hanging baseline over the text.
- **'middle'**: The text baseline is in the middle of the text bounding box.
**'ideographic'**: The text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excess character.
- **'bottom'**: The text baseline is at the bottom of the text bounding box. Its difference from the ideographic baseline is that the ideographic baseline does not consider letters in the next line.
Default value: **'alphabetic'** | -| [globalAlpha](#globalalpha) | number | No | No | Opacity.
**0.0**: completely transparent.
**1.0**: completely opaque.
Default value: **1.0** | -| [lineDashOffset](#linedashoffset) | number | No | No | Offset of the dashed line. The precision is float.
Default value: **0.0**
Unit: px | -| [globalCompositeOperation](#globalcompositeoperation) | string | No | No | Composition operation type. Available values are as follows: **'source-over'**, **'source-atop'**, **'source-in'**, **'source-out'**, **'destination-over'**, **'destination-atop'**, **'destination-in'**, **'destination-out'**, **'lighter'**, **'copy'**, and **'xor'**.
Default value: **'source-over'** | -| [shadowBlur](#shadowblur) | number | No | No | Blur level during shadow drawing. A larger value indicates a more blurred effect. The precision is float.
Default value: **0.0**
The value cannot be a negative number. If it is set to a negative number, the default value is used instead. | -| [shadowColor](#shadowcolor) | string | No | No | Shadow color.
Default value: transparent black | -| [shadowOffsetX](#shadowoffsetx) | number | No | No | X-axis shadow offset relative to the original object.
Default value: **0**
Default unit: vp | -| [shadowOffsetY](#shadowoffsety) | number | No | No | Y-axis shadow offset relative to the original object.
Default value: **0**
Default unit: vp | -| [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | No | No | Whether to adjust the image smoothness during image drawing. The value **true** means to enable this feature, and **false** means the opposite.
Default value: **true** | -| [height](#height) | number | Yes | No | Component height.
Default unit: vp | -| [width](#width) | number | Yes | No | Component width.
Default unit: vp | -| [imageSmoothingQuality](#imagesmoothingquality) | [ImageSmoothingQuality](#imagesmoothingquality-1) | No | No | Quality of image smoothing. This attribute works only when **imageSmoothingEnabled** is set to **true**.
Default value: **ImageSmoothingQuality.low** | -| [direction](#direction) | [CanvasDirection](#canvasdirection) | No | No | Text direction used for drawing text.
Default value: **CanvasDirection.inherit** | -| [filter](#filter) | string | No | No | Filter effect. Available values are as follows:
- **'none'**: no filter effect.
- **'blur'**: applies the Gaussian blur for the image.
- **'brightness'**: applies a linear multiplication to the image to make it look brighter or darker.
- **'contrast'**: adjusts the image contrast.
- **'grayscale'**: converts the image to a grayscale image.
- **'hue-rotate'**: applies hue rotation to the image.
- **'invert'**: inverts the input image.
- **'opacity'**: sets the opacity of the image.
- **'saturate'**: sets the saturation of the image.
- **'sepia'**: converts the image to dark brown.
Default value: **'none'** | +| [fillStyle](#fillstyle) | string \|number10+ \|[CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](ts-components-canvas-canvaspattern.md#canvaspattern) | No| No| Style used to fill an area.
- When the type is string, this attribute indicates the color of the fill area. For details about the color format, see the description for the string type in [ResourceColor](ts-types.md#resourcecolor).
Default value: **'#000000'**
- When the type is number, this attribute indicates the color of the fill area. Fully transparent colors are not supported. For details about the color format, see the description for the number type in [ResourceColor](ts-types.md#resourcecolor).
Default value: **0x000000**
- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.
- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API.| +| [lineWidth](#linewidth) | number | No| No| Line width.
Default value: **1(px)**
Default unit: vp
The value cannot be **0** or a negative number. If it is set to **0** or a negative number, the default value is used instead. | +| [strokeStyle](#strokestyle) | string \|number10+ \|[CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](ts-components-canvas-canvaspattern.md#canvaspattern) | No| No| Stroke color.
- When the type is string, this attribute indicates the stroke color. For details about the color format, see the description for the string type in [ResourceColor](ts-types.md#resourcecolor).
Default value: **'#000000'**
- When the type is number, this attribute indicates the stroke color. Fully transparent colors are not supported. For details about the color format, see the description for the number type in [ResourceColor](ts-types.md#resourcecolor).
Default value: **0x000000**
- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.
- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API.| +| [lineCap](#linecap) | [CanvasLineCap](#canvaslinecap) | No| No| Style of the line endpoints. The options are as follows:
- **'butt'**: The endpoints of the line are squared off.
- **'round'**: The endpoints of the line are rounded.
- **'square'**: The endpoints of the line are squared off by adding a box with an equal width and half the height of the line's thickness.
Default value: **'butt'**| +| [lineJoin](#linejoin) | [CanvasLineJoin](#canvaslinejoin) | No| No| Style of the shape used to join line segments. The options are as follows:
- **'round'**: The shape used to join line segments is a sector, whose radius at the rounded corner is equal to the line width.
- **'bevel'**: The shape used to join line segments is a triangle. The rectangular corner of each line is independent.
- **'miter'**: The shape used to join line segments has a mitered corner by extending the outside edges of the lines until they meet. You can view the effect of this attribute in **miterLimit**.
Default value: **'miter'**| +| [miterLimit](#miterlimit) | number | No| No| Maximum miter length. The miter length is the distance between the inner corner and the outer corner where two lines meet.
Default value: **10** (px)
Unit: px
The value cannot be **0** or a negative number. If it is set to **0** or a negative number, the default value is used instead.| +| [font](#font) | string | No| No| Font style.
Syntax: ctx.font='font-style font-weight font-size font-family'
- (Optional) **font-style**: font style. Available values are **'normal'** and **'italic'**.
- (Optional) **font-weight**: font weight. Available values are as follows: **'normal'**, **'bold'**, **'bolder'**, **'lighter'**, **'100'**, **'200'**, **'300'**, **'400'**, **'500'**, **'600'**, **'700'**, **'800'**, **'900'**.
- (Optional) **font-size**: font size and line height. The unit must be specified and can be px or vp.
- (Optional) **font-family**: font family. Available values are **'sans-serif'**, **'serif'**, and **'monospace'**. Custom fonts are also supported, though they cannot be observed in DevEco Studio Previewer. For details, see the [custom font example](#font).
Default value: **'normal normal 14px sans-serif'**| +| [textAlign](#textalign) | [CanvasTextAlign](#canvastextalign) | No| No| Text alignment mode. Available values are as follows:
- **'left'**: The text is left-aligned.
- **'right'**: The text is right-aligned.
- **'center'**: The text is center-aligned.
- **'start'**: The text is aligned with the start bound.
- **'end'**: The text is aligned with the end bound.
In the **ltr** layout mode, the value **'start'** equals **'left'**. In the **rtl** layout mode, the value **'start'** equals **'right'**.
Default value: **'start'**| +| [textBaseline](#textbaseline) | [CanvasTextBaseline](#canvastextbaseline) | No| No| Horizontal alignment mode of text. Available values are as follows:
- **'alphabetic'**: The text baseline is the normal alphabetic baseline.
- **'top'**: The text baseline is on the top of the text bounding box.
- **'hanging'**: The text baseline is a hanging baseline over the text.
- **'middle'**: The text baseline is in the middle of the text bounding box.
**'ideographic'**: The text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excess character.
- **'bottom'**: The text baseline is at the bottom of the text bounding box. Its difference from the ideographic baseline is that the ideographic baseline does not consider letters in the next line.
Default value: **'alphabetic'**| +| [globalAlpha](#globalalpha) | number | No| No| Opacity. The value ranges from 0.0 (completely transparent) to 1.0 (completely opaque). If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.
Default value: **1.0**| +| [lineDashOffset](#linedashoffset) | number | No| No| Offset of the dashed line. The precision is float.
Default value: **0.0**
Default unit: vp| +| [globalCompositeOperation](#globalcompositeoperation) | string | No| No| Composition operation type. Available values are as follows: **'source-over'**, **'source-atop'**, **'source-in'**, **'source-out'**, **'destination-over'**, **'destination-atop'**, **'destination-in'**, **'destination-out'**, **'lighter'**, **'copy'**, and **'xor'**.
Default value: **'source-over'**| +| [shadowBlur](#shadowblur) | number | No| No| Blur level during shadow drawing. A larger value indicates a more blurred effect. The precision is float, and the value must be greater than or equal to 0.
Default value: **0.0**
Unit: px
The value cannot be a negative number. If it is set to a negative number, the default value is used instead.| +| [shadowColor](#shadowcolor) | string | No| No| Shadow color. For details about the color format, see the description for the string type in [ResourceColor](ts-types.md#resourcecolor).
Default value: transparent black| +| [shadowOffsetX](#shadowoffsetx) | number | No| No| X-axis shadow offset relative to the original object.
Default value: **0.0**
Default unit: vp| +| [shadowOffsetY](#shadowoffsety) | number | No| No| Y-axis shadow offset relative to the original object.
Default value: **0.0**
Default unit: vp| +| [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | No| No| Whether to adjust the image smoothness during image drawing. The value **true** means to enable this feature, and **false** means the opposite.
Default value: **true**| +| [height](#height) | number | Yes| No| Component height.
Default unit: vp| +| [width](#width) | number | Yes| No| Component width.
Default unit: vp| +| [imageSmoothingQuality](#imagesmoothingquality) | [ImageSmoothingQuality](#imagesmoothingquality) | No| No| Quality of image smoothing. This attribute works only when **imageSmoothingEnabled** is set to **true**.
Default value: **'low'**| +| [direction](#direction) | [CanvasDirection](#canvasdirection) | No| No| Text direction used for drawing text.
Default value: **'inherit'**| +| [filter](#filter) | string | No| No| Filter effect for an image. You can combine any number of filter effects.
Available values are as follows:
- **'none'**: no filter effect.
- 'blur(\)': applies the Gaussian blur for the image. The value must be greater than or equal to 0. The unit can be px, vp, or rem. The default unit is vp, and the default value is **blur(0px)**.
- 'brightness([\\|\])': applies a linear multiplication to the image to make it look brighter or darker. The value can be a number or percentage. It must be greater than or equal to 0. The default value is **brightness(1)**.
- 'contrast([\\|\])': adjusts the image contrast. The value can be a number or percentage. It must be greater than or equal to 0. The default value is **contrast(1)**.
- 'grayscale([\\|\])': converts the image to a grayscale image. The value can be a number or percentage. The value range is [0, 1]. The default value is **grayscale(0)**.
- 'hue-rotate(\)': applies hue rotation to the image. The value ranges from 0deg to 360deg. The default value is **hue-rotate (0deg)**.
- 'invert([\\|\])': inverts the input image. The value can be a number or percentage. The value range is [0, 1]. The default value is **invert (0)**.
- 'opacity([\\|\])': sets the opacity of the image. The value can be a number or percentage. The value range is [0, 1]. The default value is **opacity(1)**.
- 'saturate([\\|\])': sets the saturation of the image. The value can be a number or percentage. It must be greater than or equal to 0. The default value is **saturate(1)**.
- 'sepia([\\|\])': converts the image to dark brown. The value can be a number or percentage. The value range is [0, 1]. The default value is **sepia(0)**.| +| [canvas13+](#canvas13) | [FrameNode](../../apis-arkui/js-apis-arkui-frameNode.md) | Yes| No| FrameNode instance of the **Canvas** component associated with **CanvasRenderingContext2D**.
It can be used to listen for the visibility status of the associated **Canvas** component.
Default value: **null**| +| [letterSpacing18+](#letterspacing18) | string \| [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | No| No| Spacing between characters.
When the LengthMetrics type is used:
The spacing is set according to the specified unit.
The FP, PERCENT, and LPX units are not supported and will be treated as invalid values.
Negative and fractional values are supported. When set to a fraction, the spacing is not rounded.
When the string type is used:
Percentage values are not supported and will be treated as invalid.
Negative and fractional values are supported. When set to a fraction, the spacing is not rounded.
If no unit is specified (for example, **letterSpacing = '10'**) and **LengthMetricsUnit** is not set, the default unit is vp.
If **LengthMetricsUnit** is set to px, the default unit is px.
If a unit is specified (for example, **letterSpacing='10vp'**), the spacing is set according to the specified unit.
Default value: **0** (Invalid values are treated as the default value.)
**NOTE**
The LengthMetrics type is recommended for better performance.| > **NOTE** > @@ -325,6 +331,26 @@ struct MiterLimit { ### font +Before using the **font** property to load custom fonts, you must first register the custom font in the **EntryAbility.ets** file located in the **src/main/ets/entryability/** directory. The following is an example of how to do this. + +> The value of **familyName** must be a continuous string without spaces, for example, **"customFont"**. Otherwise, the **font** property will fail to load the custom font. +> +> The **familySrc** path should point to the font file located in the **font** folder, which is at the same level as the **pages** folder. + +```ts +onWindowStageCreate(windowStage: window.WindowStage): void { + windowStage.loadContent('pages/Index', (err) => { + windowStage.getMainWindow().then(res => { + const uiCtc = res.getUIContext() + uiCtc.getFont().registerFont({ + familyName: 'customFont', + familySrc: '/font/myFont.ttf' + }) + }) + }); +} +``` + ```ts // xxx.ets @Entry @@ -338,12 +364,15 @@ struct Fonts { Canvas(this.context) .width('100%') .height('100%') - .backgroundColor('#ffff00') + .backgroundColor('rgb(213,213,213)') .onReady(() =>{ this.context.font = '30px sans-serif' this.context.fillText("Hello px", 20, 60) this.context.font = '30vp sans-serif' this.context.fillText("Hello vp", 20, 100) + // Use a custom font by specifying its familyName. + this.context.font = '30vp customFont' + this.context.fillText("Hello", 20, 140) }) } .width('100%') @@ -352,8 +381,7 @@ struct Fonts { } ``` -![en-us_image_0000001257058409](figures/en-us_image_0000001257058409.png) - +![new_font](figures/new_font.jpeg) ### textAlign @@ -364,30 +392,30 @@ struct Fonts { struct CanvasExample { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) .width('100%') .height('100%') .backgroundColor('#ffff00') - .onReady(() =>{ - this.context.strokeStyle = '#0000ff' - this.context.moveTo(140, 10) - this.context.lineTo(140, 160) - this.context.stroke() - this.context.font = '18px sans-serif' - this.context.textAlign = 'start' - this.context.fillText('textAlign=start', 140, 60) - this.context.textAlign = 'end' - this.context.fillText('textAlign=end', 140, 80) - this.context.textAlign = 'left' - this.context.fillText('textAlign=left', 140, 100) - this.context.textAlign = 'center' - this.context.fillText('textAlign=center',140, 120) - this.context.textAlign = 'right' - this.context.fillText('textAlign=right',140, 140) - }) + .onReady(() => { + this.context.strokeStyle = '#0000ff' + this.context.moveTo(140, 10) + this.context.lineTo(140, 160) + this.context.stroke() + this.context.font = '18px sans-serif' + this.context.textAlign = 'start' + this.context.fillText('textAlign=start', 140, 60) + this.context.textAlign = 'end' + this.context.fillText('textAlign=end', 140, 80) + this.context.textAlign = 'left' + this.context.fillText('textAlign=left', 140, 100) + this.context.textAlign = 'center' + this.context.fillText('textAlign=center', 140, 120) + this.context.textAlign = 'right' + this.context.fillText('textAlign=right', 140, 140) + }) } .width('100%') .height('100%') @@ -413,9 +441,9 @@ struct TextBaseline { Canvas(this.context) .width('100%') .height('100%') - .backgroundColor('#ffff00') - .onReady(() =>{ - this.context.strokeStyle = '#0000ff' + .backgroundColor('rgb(213,213,213)') + .onReady(() => { + this.context.strokeStyle = 'rgb(213,213,213)' this.context.moveTo(0, 120) this.context.lineTo(400, 120) this.context.stroke() @@ -438,7 +466,7 @@ struct TextBaseline { } ``` -![en-us_image_0000001212058462](figures/en-us_image_0000001212058462.png) +![textBaseline](figures/textBaseline.jpg) ### globalAlpha @@ -510,7 +538,7 @@ struct LineDashOffset { | Name | Description | | ---------------- | ------------------------ | -| source-over | Displays the new drawing above the existing drawing. This attribute is used by default. | +| source-over | Displays the new drawing above the existing drawing. Default value. | | source-atop | Displays the new drawing on the top of the existing drawing. | | source-in | Displays the new drawing inside the existing drawing. | | source-out | Displays part of the new drawing that is outside of the existing drawing. | @@ -520,7 +548,7 @@ struct LineDashOffset { | destination-out | Displays the existing drawing outside the new drawing. | | lighter | Displays both the new and existing drawing. | | copy | Displays the new drawing and neglects the existing drawing. | -| xor | Combines the new drawing and existing drawing using the XOR operation. | +| xor | Combines the new drawing and existing drawing using the XOR operation.| ```ts // xxx.ets @@ -778,6 +806,51 @@ struct WidthExample { ![en-us_image_canvas_width](figures/en-us_image_canvas_width.png) +### canvas13+ + +```ts +import { FrameNode } from '@kit.ArkUI' +// xxx.ets +@Entry +@Component +struct CanvasExample { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + private text: string = '' + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() => { + let node: FrameNode = this.context.canvas + node?.commonEvent.setOnVisibleAreaApproximateChange( + { ratios: [0, 1], expectedUpdateInterval: 10}, + (isVisible: boolean, currentRatio: number) => { + if (!isVisible && currentRatio <= 0.0) { + this.text = 'Canvas is completely invisible.' + } + if (isVisible && currentRatio >= 1.0) { + this.text = 'Canvas is fully visible.' + } + this.context.reset() + this.context.font = '30vp sans-serif' + this.context.fillText(this.text, 50, 50) + } + ) + }) + } + .width('100%') + .height('100%') + } +} +``` + +![en-us_image_canvas](figures/en-us_image_canvas.png) + + ### imageSmoothingQuality ```ts @@ -855,15 +928,14 @@ struct WidthExample { struct FilterDemo { private settings: RenderingContextSettings = new RenderingContextSettings(true); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); - private img:ImageBitmap = new ImageBitmap("common/images/example.jpg"); + private img: ImageBitmap = new ImageBitmap("common/images/example.jpg"); build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) .width('100%') .height('100%') - .backgroundColor('#ffff00') - .onReady(() =>{ + .onReady(() => { let ctx = this.context let img = this.img @@ -896,8 +968,9 @@ struct WidthExample { ctx.filter = 'blur(5px)'; ctx.drawImage(img, 0, 300, 100, 100); - let result = ctx.toDataURL() - console.info(result) + // Applying multiple filters + ctx.filter = 'opacity(50%) contrast(200%) grayscale(50%)'; + ctx.drawImage(img, 100, 300, 100, 100); }) } .width('100%') @@ -908,6 +981,40 @@ struct WidthExample { ![filterDemo](figures/filterDemo.jpeg) +### letterSpacing18+ + +```ts + // xxx.ets + import { LengthMetrics, LengthUnit } from '@kit.ArkUI' + + @Entry + @Component + struct letterSpacingDemo { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('rgb(213,213,213)') + .onReady(() => { + this.context.font = '30vp' + this.context.letterSpacing = '10vp' + this.context.fillText('hello world', 30, 50) + this.context.letterSpacing = new LengthMetrics(10, LengthUnit.VP) + this.context.fillText('hello world', 30, 100) + }) + } + .width('100%') + .height('100%') + } + } +``` + +![letterSpacingDemo](figures/letterSpacingDemo.jpeg) + ## Methods Calls to the following methods on hidden pages will result in cache data. Therefore, avoid frequently refreshing the canvas on hidden pages. @@ -926,12 +1033,12 @@ Fills a rectangle on the canvas. **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ------ | ------ | ---- | ------------- | -| x | number | Yes | X coordinate of the upper left corner of the rectangle.
Default unit: vp
Default value: **0** | -| y | number | Yes | Y coordinate of the upper left corner of the rectangle.
Default unit: vp
Default value: **0** | -| w | number | Yes | Width of the rectangle.
Default unit: vp
Default value: **0** | -| h | number | Yes | Height of the rectangle.
Default unit: vp
Default value: **0** | +| x | number | Yes | X coordinate of the upper left corner of the rectangle.
Default unit: vp| +| y | number | Yes | Y coordinate of the upper left corner of the rectangle.
Default unit: vp| +| w | number | Yes | Width of the rectangle.
Default unit: vp| +| h | number | Yes | Height of the rectangle.
Default unit: vp| **Example** @@ -948,9 +1055,9 @@ Fills a rectangle on the canvas. Canvas(this.context) .width('100%') .height('100%') - .backgroundColor('#ffff00') - .onReady(() =>{ - this.context.fillRect(30,30,100,100) + .backgroundColor('rgb(213,213,213)') + .onReady(() => { + this.context.fillRect(30, 30, 100, 100) }) } .width('100%') @@ -959,7 +1066,7 @@ Fills a rectangle on the canvas. } ``` - ![en-us_image_0000001212218440](figures/en-us_image_0000001212218440.png) + ![fillRect](figures/fillRect.jpg) ### strokeRect @@ -978,10 +1085,10 @@ Draws an outlined rectangle on the canvas. | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ------------ | -| x | number | Yes | X coordinate of the upper left corner of the rectangle.
Default unit: vp
Default value: **0** | -| y | number | Yes | Y coordinate of the upper left corner of the rectangle.
Default unit: vp
Default value: **0** | -| w | number | Yes | Width of the rectangle.
Default unit: vp
Default value: **0** | -| h | number | Yes | Height of the rectangle.
Default unit: vp
Default value: **0** | +| x | number | Yes | X coordinate of the upper left corner of the rectangle.
Default unit: vp| +| y | number | Yes | Y coordinate of the upper left corner of the rectangle.
Default unit: vp| +| w | number | Yes | Width of the rectangle.
Default unit: vp| +| h | number | Yes | Height of the rectangle.
Default unit: vp| **Example** @@ -1009,7 +1116,7 @@ Draws an outlined rectangle on the canvas. } ``` - ![en-us_image_0000001257138359](figures/en-us_image_0000001257138359.png) + ![en-us_image_0000001194352436](figures/en-us_image_0000001194352436.png) ### clearRect @@ -1028,10 +1135,10 @@ Clears the content in a rectangle on the canvas. | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ------------- | -| x | number | Yes | X coordinate of the upper left corner of the rectangle.
Default unit: vp
Default value: **0** | -| y | number | Yes | Y coordinate of the upper left corner of the rectangle.
Default unit: vp
Default value: **0** | -| w | number | Yes | Width of the rectangle.
Default unit: vp
Default value: **0** | -| h | number | Yes | Height of the rectangle.
Default unit: vp
Default value: **0** | +| x | number | Yes| X coordinate of the upper left corner of the rectangle.
Default unit: vp| +| y | number | Yes| Y coordinate of the upper left corner of the rectangle.
Default unit: vp| +| w | number | Yes| Width of the rectangle.
Default unit: vp| +| h | number | Yes| Height of the rectangle.
Default unit: vp| **Example** @@ -1061,7 +1168,7 @@ Clears the content in a rectangle on the canvas. } ``` - ![en-us_image_0000001211898482](figures/en-us_image_0000001211898482.png) + ![en-us_image_0000001238952377](figures/en-us_image_0000001238952377.png) ### fillText @@ -1078,12 +1185,12 @@ Draws filled text on the canvas. **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory | Description| | -------- | ------ | ---- | --------------- | -| text | string | Yes | Text to draw.
Default value: **''** | -| x | number | Yes | X coordinate of the lower left corner of the text.
Default unit: vp
Default value: **0** | -| y | number | Yes | Y coordinate of the lower left corner of the text.
Default unit: vp
Default value: **0** | -| maxWidth | number | No | Maximum width allowed for the text.
Default unit: vp | +| text | string | Yes | Text to draw.| +| x | number | Yes | X coordinate of the lower left corner of the text.
Default unit: vp| +| y | number | Yes | Y coordinate of the lower left corner of the text.
Default unit: vp| +| maxWidth | number | No | Maximum width allowed for the text.
Default unit: vp
Default value: no width restriction| **Example** @@ -1112,7 +1219,7 @@ Draws filled text on the canvas. } ``` - ![en-us_image_0000001257058399](figures/en-us_image_0000001257058399.png) + ![en-us_image_0000001194032458](figures/en-us_image_0000001194032458.png) ### strokeText @@ -1129,12 +1236,12 @@ Draws a text stroke on the canvas. **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | -------- | ------ | ---- | --------------- | -| text | string | Yes | Text to draw.
Default value: **''** | -| x | number | Yes | X coordinate of the lower left corner of the text.
Default unit: vp
Default value: **0** | -| y | number | Yes | Y coordinate of the lower left corner of the text.
Default unit: vp
Default value: **0** | -| maxWidth | number | No | Maximum width of the text.
Default unit: vp | +| text | string | Yes | Text to draw.| +| x | number | Yes | X coordinate of the lower left corner of the text.
Default unit: vp| +| y | number | Yes | Y coordinate of the lower left corner of the text.
Default unit: vp| +| maxWidth | number | No | Maximum width of the text.
Default unit: vp
Default value: no width restriction| **Example** @@ -1151,9 +1258,9 @@ Draws a text stroke on the canvas. Canvas(this.context) .width('100%') .height('100%') - .backgroundColor('#ffff00') - .onReady(() =>{ - this.context.font = '55px sans-serif' + .backgroundColor('rgb(213,213,213)') + .onReady(() => { + this.context.font = '50vp sans-serif' this.context.strokeText("Hello World!", 20, 60) }) } @@ -1163,14 +1270,14 @@ Draws a text stroke on the canvas. } ``` - ![en-us_image_0000001256978349](figures/en-us_image_0000001256978349.png) + ![strokeText](figures/strokeText.jpg) ### measureText measureText(text: string): TextMetrics -Measures the specified text to obtain its width. This API returns a **TextMetrics** object. +Measures the specified text to obtain its width. This API returns a **TextMetrics** object. Note that the width obtained may vary by device. **Widget capability**: This API can be used in ArkTS widgets since API version 9. @@ -1182,13 +1289,13 @@ Measures the specified text to obtain its width. This API returns a **TextMetric | Name | Type | Mandatory | Description | | ---- | ------ | ---- |---------- | -| text | string | Yes | Text to be measured.
Default value: **''** | +| text | string | Yes | Text to be measured.| **Return value** | Type | Description | | ----------- | ---------------------------------------- | -| [TextMetrics](#textmetrics) | **TextMetrics** object. | +| [TextMetrics](#textmetrics) | **TextMetrics** object.| **Example** @@ -1205,8 +1312,8 @@ Measures the specified text to obtain its width. This API returns a **TextMetric Canvas(this.context) .width('100%') .height('100%') - .backgroundColor('#ffff00') - .onReady(() =>{ + .backgroundColor('rgb(213,213,213)') + .onReady(() => { this.context.font = '50px sans-serif' this.context.fillText("Hello World!", 20, 100) this.context.fillText("width:" + this.context.measureText("Hello World!").width, 20, 200) @@ -1218,14 +1325,59 @@ Measures the specified text to obtain its width. This API returns a **TextMetric } ``` - ![en-us_image_0000001257138343](figures/en-us_image_0000001257138343.png) + ![measureText](figures/measureText.jpg) + + +### stroke + +stroke(): void + +Strokes (outlines) this path. + +**Widget capability**: This API can be used in ArkTS widgets since API version 9. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Example** + + ```ts + // xxx.ets + @Entry + @Component + struct Stroke { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() => { + this.context.moveTo(125, 25) + this.context.lineTo(125, 105) + this.context.lineTo(175, 105) + this.context.lineTo(175, 25) + this.context.strokeStyle = 'rgb(255,0,0)' + this.context.stroke() + }) + } + .width('100%') + .height('100%') + } + } + ``` + ![en-us_image_0000001238832389](figures/en-us_image_0000001238832389.png) ### stroke -stroke(path?: Path2D): void +stroke(path: Path2D): void -Strokes a path. +Strokes (outlines) a specified path. **Widget capability**: This API can be used in ArkTS widgets since API version 9. @@ -1237,9 +1389,9 @@ Strokes a path. | Name | Type | Mandatory | Description | | ---- | ---------------------------------------- | ---- | ------------ | -| path | [Path2D](ts-components-canvas-path2d.md) | No | A **Path2D** path to draw.
Default value: **null** | +| path | [Path2D](ts-components-canvas-path2d.md) | Yes| A **Path2D** path to draw.| -**Example** + **Example** ```ts // xxx.ets @@ -1248,6 +1400,7 @@ Strokes a path. struct Stroke { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + private path2Da: Path2D = new Path2D() build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1255,13 +1408,13 @@ Strokes a path. .width('100%') .height('100%') .backgroundColor('#ffff00') - .onReady(() =>{ - this.context.moveTo(25, 25) - this.context.lineTo(25, 105) - this.context.lineTo(75, 105) - this.context.lineTo(75, 25) + .onReady(() => { + this.path2Da.moveTo(25, 25) + this.path2Da.lineTo(25, 105) + this.path2Da.lineTo(75, 105) + this.path2Da.lineTo(75, 25) this.context.strokeStyle = 'rgb(0,0,255)' - this.context.stroke() + this.context.stroke(this.path2Da) }) } .width('100%') @@ -1270,8 +1423,7 @@ Strokes a path. } ``` - ![en-us_image_0000001238832389](figures/en-us_image_0000001238832389.png) - + ![en-us_image_0000001238832389](figures/en-us_image_0000001238832390.png) ### beginPath @@ -1316,7 +1468,7 @@ Creates a drawing path. } ``` - ![en-us_image_0000001238712417](figures/en-us_image_0000001212058478.png) + ![en-us_image_0000001238712417](figures/en-us_image_0000001238712417.png) ### moveTo @@ -1335,8 +1487,8 @@ Moves a drawing path to a target position on the canvas. | Name | Type | Mandatory | Description | | ---- | ------ | ---- | --------- | -| x | number | Yes | X coordinate of the target position.
Default unit: vp
Default value: **0** | -| y | number | Yes | Y coordinate of the target position.
Default unit: vp
Default value: **0** | +| x | number | Yes | X coordinate of the target position.
Default unit: vp| +| y | number | Yes | Y coordinate of the target position.
Default unit: vp| **Example** @@ -1367,7 +1519,7 @@ Moves a drawing path to a target position on the canvas. } ``` - ![en-us_image_0000001194192438](figures/en-us_image_0000001256858391.png) + ![en-us_image_0000001194192438](figures/en-us_image_0000001194192438.png) ### lineTo @@ -1386,8 +1538,8 @@ Connects the current point to a target position using a straight line. | Name | Type | Mandatory | Description | | ---- | ------ | ---- | --------- | -| x | number | Yes | X coordinate of the target position.
Default unit: vp
Default value: **0** | -| y | number | Yes | Y coordinate of the target position.
Default unit: vp
Default value: **0** | +| x | number | Yes | X coordinate of the target position.
Default unit: vp| +| y | number | Yes | Y coordinate of the target position.
Default unit: vp| **Example** @@ -1418,7 +1570,7 @@ Connects the current point to a target position using a straight line. } ``` - ![en-us_image_0000001194352438](figures/en-us_image_0000001212378414.png) + ![en-us_image_0000001194352438](figures/en-us_image_0000001194352438.png) ### closePath @@ -1464,7 +1616,7 @@ Draws a closed path. } ``` - ![en-us_image_0000001238952379](figures/en-us_image_0000001256978347.png) + ![en-us_image_0000001238952379](figures/en-us_image_0000001238952379.png) ### createPattern @@ -1483,14 +1635,14 @@ Creates a pattern for image filling based on a specified source image and repeti | Name | Type | Mandatory | Description | | ---------- | ---------- | ---- | ---------------------------------------- | -| image | [ImageBitmap](ts-components-canvas-imagebitmap.md) | Yes | Source image. For details, see **ImageBitmap**. | -| repetition | string \| null | Yes | Repetition mode.
**'repeat'**: The image is repeated along both the x-axis and y-axis.
**'repeat-x'**: The image is repeated along the x-axis.
**'repeat-y'**: The image is repeated along the y-axis.
**'no-repeat'**: The image is not repeated.
**'clamp'**: Coordinates outside the original bounds are clamped to the edge of the image.
**'mirror'**: The image is mirrored with each repetition along the x-axis and y-axis.
Default value: **null**| +| image | [ImageBitmap](ts-components-canvas-imagebitmap.md) | Yes | Source image. For details, see **ImageBitmap**.| +| repetition | string \| null | Yes | Repetition mode.
**'repeat'**: The image is repeated along both the x-axis and y-axis.
**'repeat-x'**: The image is repeated along the x-axis.
**'repeat-y'**: The image is repeated along the y-axis.
**'no-repeat'**: The image is not repeated.
**'clamp'**: Coordinates outside the original bounds are clamped to the edge of the image.
**'mirror'**: The image is mirrored with each repetition along the x-axis and y-axis.| **Return value** | Type | Description | | ---------------------------------------- | ----------------------- | -| [CanvasPattern](ts-components-canvas-canvaspattern.md#canvaspattern) \| null | Created pattern for image filling based on a specified source image and repetition mode. | +| [CanvasPattern](ts-components-canvas-canvaspattern.md#canvaspattern) \| null | Created pattern for image filling based on a specified source image and repetition mode.| **Example** @@ -1523,7 +1675,7 @@ Creates a pattern for image filling based on a specified source image and repeti } ``` - ![en-us_image_0000001211898490](figures/en-us_image_0000001211898490.png) + ![en-us_image_0000001194032460](figures/en-us_image_0000001194032460.png) ### bezierCurveTo @@ -1542,12 +1694,12 @@ Draws a cubic Bezier curve on the canvas. | Name | Type | Mandatory | Description | | ---- | ------ | ---- | -------------- | -| cp1x | number | Yes | X coordinate of the first parameter of the bezier curve.
Default unit: vp
Default value: **0** | -| cp1y | number | Yes | Y coordinate of the first parameter of the bezier curve.
Default unit: vp
Default value: **0** | -| cp2x | number | Yes | X coordinate of the second parameter of the bezier curve.
Default unit: vp
Default value: **0** | -| cp2y | number | Yes | Y coordinate of the second parameter of the bezier curve.
Default unit: vp
Default value: **0** | -| x | number | Yes | X coordinate of the end point on the bezier curve.
Default unit: vp
Default value: **0** | -| y | number | Yes | Y coordinate of the end point on the bezier curve.
Default unit: vp
Default value: **0** | +| cp1x | number | Yes | X coordinate of the first parameter of the bezier curve.
Default unit: vp| +| cp1y | number | Yes | Y coordinate of the first parameter of the bezier curve.
Default unit: vp| +| cp2x | number | Yes | X coordinate of the second parameter of the bezier curve.
Default unit: vp| +| cp2y | number | Yes | Y coordinate of the second parameter of the bezier curve.
Default unit: vp| +| x | number | Yes | X coordinate of the end point on the bezier curve.
Default unit: vp| +| y | number | Yes | Y coordinate of the end point on the bezier curve.
Default unit: vp| **Example** @@ -1578,7 +1730,7 @@ Draws a cubic Bezier curve on the canvas. } ``` - ![en-us_image_0000001257138349](figures/en-us_image_0000001257138349.png) + ![en-us_image_0000001239032415](figures/en-us_image_0000001239032415.png) ### quadraticCurveTo @@ -1597,10 +1749,10 @@ Draws a quadratic curve on the canvas. | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ----------- | -| cpx | number | Yes | X coordinate of the bezier curve parameter.
Default unit: vp
Default value: **0** | -| cpy | number | Yes | Y coordinate of the bezier curve parameter.
Default unit: vp
Default value: **0** | -| x | number | Yes | X coordinate of the end point on the bezier curve.
Default unit: vp
Default value: **0** | -| y | number | Yes | Y coordinate of the end point on the bezier curve.
Default unit: vp
Default value: **0** | +| cpx | number | Yes | X coordinate of the bezier curve parameter.
Default unit: vp| +| cpy | number | Yes | Y coordinate of the bezier curve parameter.
Default unit: vp| +| x | number | Yes | X coordinate of the end point on the bezier curve.
Default unit: vp| +| y | number | Yes | Y coordinate of the end point on the bezier curve.
Default unit: vp| **Example** @@ -1631,7 +1783,7 @@ Draws a quadratic curve on the canvas. } ``` - ![en-us_image_0000001257058397](figures/en-us_image_0000001257058397.png) + ![en-us_image_0000001193872494](figures/en-us_image_0000001193872494.png) ### arc @@ -1650,12 +1802,12 @@ Draws an arc on the canvas. | Name | Type | Mandatory | Description | | ---------------- | ------- | ---- | ---------- | -| x | number | Yes | X coordinate of the center point of the arc.
Default unit: vp
Default value: **0** | -| y | number | Yes | Y coordinate of the center point of the arc.
Default unit: vp
Default value: **0** | -| radius | number | Yes | Radius of the arc.
Default unit: vp
Default value: **0** | -| startAngle | number | Yes | Start radian of the arc.
Default value: **0** | -| endAngle | number | Yes | End radian of the arc.
Default value: **0** | -| counterclockwise | boolean | No | Whether to draw the arc counterclockwise.
Default value: **false** | +| x | number | Yes | X coordinate of the center point of the arc.
Default unit: vp| +| y | number | Yes | Y coordinate of the center point of the arc.
Default unit: vp| +| radius | number | Yes | Radius of the arc.
Default unit: vp| +| startAngle | number | Yes | Start radian of the arc.
Unit: radian| +| endAngle | number | Yes | End radian of the arc.
Unit: radian| +| counterclockwise | boolean | No | Whether to draw the arc counterclockwise.
**true**: Draw the arc counterclockwise.
**false**: Draw the arc clockwise.
Default value: **false**| **Example** @@ -1685,14 +1837,14 @@ Draws an arc on the canvas. } ``` - ![en-us_image_0000001212378404](figures/en-us_image_0000001212378404.png) + ![en-us_image_0000001238832391](figures/en-us_image_0000001238832391.jpeg) ### arcTo arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void -Draws an arc based on the radius and points on the arc. +Creates a circular arc using the given control points and radius. **Widget capability**: This API can be used in ArkTS widgets since API version 9. @@ -1704,11 +1856,11 @@ Draws an arc based on the radius and points on the arc. | Name | Type | Mandatory | Description | | ------ | ------ | ---- | --------------- | -| x1 | number | Yes | X coordinate of the first point on the arc.
Default unit: vp
Default value: **0** | -| y1 | number | Yes | Y coordinate of the first point on the arc.
Default unit: vp
Default value: **0** | -| x2 | number | Yes | X coordinate of the second point on the arc.
Default unit: vp
Default value: **0** | -| y2 | number | Yes | Y coordinate of the second point on the arc.
Default unit: vp
Default value: **0** | -| radius | number | Yes | Radius of the arc.
Default unit: vp
Default value: **0** | +| x1 | number | Yes | X coordinate of the first control point.
Default unit: vp| +| y1 | number | Yes | Y coordinate of the first control point.
Default unit: vp| +| x2 | number | Yes | X coordinate of the second control point.
Default unit: vp| +| y2 | number | Yes | Y coordinate of the second control point.
Default unit: vp| +| radius | number | Yes | Radius of the arc.
Default unit: vp| **Example** @@ -1727,9 +1879,35 @@ Draws an arc based on the radius and points on the arc. .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.context.moveTo(100, 20) - this.context.arcTo(150, 20, 150, 70, 50) + // Tangent + this.context.beginPath() + this.context.strokeStyle = '#808080' + this.context.lineWidth = 1.5; + this.context.moveTo(360, 20); + this.context.lineTo(360, 170); + this.context.lineTo(110, 170); + this.context.stroke(); + + // Arc + this.context.beginPath() + this.context.strokeStyle = '#000000' + this.context.lineWidth = 3; + this.context.moveTo(360, 20) + this.context.arcTo(360, 170, 110, 170, 150) this.context.stroke() + + // Start point + this.context.beginPath(); + this.context.fillStyle = '#00ff00'; + this.context.arc(360, 20, 4, 0, 2 * Math.PI); + this.context.fill(); + + // Control points + this.context.beginPath(); + this.context.fillStyle = '#ff0000'; + this.context.arc(360, 170, 4, 0, 2 * Math.PI); + this.context.arc(110, 170, 4, 0, 2 * Math.PI); + this.context.fill(); }) } .width('100%') @@ -1738,7 +1916,11 @@ Draws an arc based on the radius and points on the arc. } ``` - ![en-us_image_0000001257058413](figures/en-us_image_0000001257058413.png) + ![en-us_image_0000001238712419](figures/en-us_image_0000001238712419.png) + + > In this example, the arc created by **arcTo()** is black, and the two tangents of the arc are gray. The control points are marked in red, and the start point is indicated in green. + > + > You can visualize two tangents: One tangent extends from the start point to the first control point, and the other tangent extends from the first control point to the second control point. The **arcTo()** API creates an arc between these two tangents, ensuring that the arc is tangent to both lines at the points of contact. ### ellipse @@ -1757,14 +1939,14 @@ Draws an ellipse in the specified rectangular region on the canvas. | Name | Type | Mandatory | Description | | ---------------- | ------- | ---- | ---------------------------------------- | -| x | number | Yes | X coordinate of the ellipse center.
Default unit: vp
Default value: **0** | -| y | number | Yes | Y coordinate of the ellipse center.
Default unit: vp
Default value: **0** | -| radiusX | number | Yes | Radius of the ellipse on the x-axis.
Default unit: vp
Default value: **0** | -| radiusY | number | Yes | Radius of the ellipse on the y-axis.
Default unit: vp
Default value: **0** | -| rotation | number | Yes | Rotation angle of the ellipse. The unit is radian.
Default value: **0** | -| startAngle | number | Yes | Angle of the start point for drawing the ellipse. The unit is radian.
Default value: **0** | -| endAngle | number | Yes | Angle of the end point for drawing the ellipse. The unit is radian.
Default value: **0** | -| counterclockwise | boolean | No | Whether to draw the ellipse in the counterclockwise direction.
**true**: Draw the arc counterclockwise.
**false**: Draw the arc clockwise.
Default value: **false** | +| x | number | Yes| X coordinate of the ellipse center.
Default unit: vp| +| y | number | Yes| Y coordinate of the ellipse center.
Default unit: vp| +| radiusX | number | Yes| Radius of the ellipse on the x-axis.
Default unit: vp| +| radiusY | number | Yes| Radius of the ellipse on the y-axis.
Default unit: vp| +| rotation | number | Yes| Rotation angle of the ellipse.
Unit: radian| +| startAngle | number | Yes| Angle of the start point for drawing the ellipse.
Unit: radian| +| endAngle | number | Yes| Angle of the end point for drawing the ellipse.
Unit: radian| +| counterclockwise | boolean | No| Whether to draw the ellipse in the counterclockwise direction.
**true**: Draw the arc counterclockwise.
**false**: Draw the arc clockwise.
Default value: **false**| **Example** @@ -1816,10 +1998,10 @@ Creates a rectangle on the canvas. | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ------------- | -| x | number | Yes | X coordinate of the upper left corner of the rectangle.
Default unit: vp
Default value: **0** | -| y | number | Yes | Y coordinate of the upper left corner of the rectangle.
Default unit: vp
Default value: **0** | -| w | number | Yes | Width of the rectangle.
Default unit: vp
Default value: **0** | -| h | number | Yes | Height of the rectangle.
Default unit: vp
Default value: **0** | +| x | number | Yes | X coordinate of the upper left corner of the rectangle.
Default unit: vp| +| y | number | Yes | Y coordinate of the upper left corner of the rectangle.
Default unit: vp| +| w | number | Yes | Width of the rectangle.
Default unit: vp| +| h | number | Yes | Height of the rectangle.
Default unit: vp| **Example** @@ -1848,7 +2030,7 @@ Creates a rectangle on the canvas. } ``` - ![en-us_image_0000001256978341](figures/en-us_image_0000001256978341.png) + ![en-us_image_0000001194352440](figures/en-us_image_0000001194352440.jpeg) ### fill @@ -1863,11 +2045,11 @@ Fills the area inside a closed path on the canvas. **System capability**: SystemCapability.ArkUI.ArkUI.Full -**Parameters** +**Parameters** -| Name | Type | Mandatory | Description | +| Name| Type | Mandatory | Description | | -------- | -------------- | ---- | ---------------------------------------- | -| fillRule | [CanvasFillRule](ts-canvasrenderingcontext2d.md#canvasfillrule) | No | Rule by which to determine whether a point is inside or outside the area to fill.
The options are **"nonzero"** and **"evenodd"**.
Default value: **"nonzero"** | +| fillRule | [CanvasFillRule](#canvasfillrule) | No | Rule by which to determine whether a point is inside or outside the area to fill.
The options are **"nonzero"** and **"evenodd"**.
Default value: **"nonzero"**| **Example** @@ -1897,7 +2079,7 @@ Fills the area inside a closed path on the canvas. } ``` - ![en-us_image_0000001256858389](figures/en-us_image_0000001256858389.png) + ![en-us_image_0000001238952381](figures/en-us_image_0000001238952381.png) fill(path: Path2D, fillRule?: CanvasFillRule): void @@ -1910,12 +2092,12 @@ Fills the area inside a closed path on the canvas. **System capability**: SystemCapability.ArkUI.ArkUI.Full -**Parameters** +**Parameters** | Name | Type | Mandatory | Description | | -------- | -------------- | ---- | ---------------------------------------- | | path | [Path2D](ts-components-canvas-path2d.md) | Yes | A **Path2D** path to fill. | -| fillRule | [CanvasFillRule](ts-canvasrenderingcontext2d.md#canvasfillrule) | No | Rule by which to determine whether a point is inside or outside the area to fill.
The options are **"nonzero"** and **"evenodd"**.
Default value: **"nonzero"** | +| fillRule | [CanvasFillRule](#canvasfillrule) | No | Rule by which to determine whether a point is inside or outside the area to fill.
The options are **"nonzero"** and **"evenodd"**.
Default value: **"nonzero"**| **Example** @@ -1954,7 +2136,7 @@ struct Fill { } ``` - ![en-us_image_000000127777774](figures/en-us_image_000000127777774.png) + ![en-us_image_000000127777774](figures/en-us_image_000000127777774.jpg) ### clip @@ -1969,13 +2151,13 @@ Sets the current path to a clipping area. **System capability**: SystemCapability.ArkUI.ArkUI.Full -**Parameters** +**Parameters** | Name | Type | Mandatory | Description | | -------- | -------------- | ---- | ---------------------------------------- | -| fillRule | [CanvasFillRule](#canvasfillrule) | No | Rule by which to determine whether a point is inside or outside the area to clip.
The options are **"nonzero"** and **"evenodd"**.
Default value: **"nonzero"** | +| fillRule | [CanvasFillRule](#canvasfillrule) | No| Rule by which to determine whether a point is inside or outside the area to clip.
The options are **"nonzero"** and **"evenodd"**.
Default value: **"nonzero"**| -**Example** +**Example** ```ts // xxx.ets @@ -2005,12 +2187,12 @@ Sets the current path to a clipping area. } ``` - ![en-us_image_0000001211898488](figures/en-us_image_0000001211898488.png) + ![en-us_image_0000001194032462](figures/en-us_image_0000001194032462.png) clip(path: Path2D, fillRule?: CanvasFillRule): void -Sets the current path to a clipping path. +Sets the current path to a clipping area. **Widget capability**: This API can be used in ArkTS widgets since API version 9. @@ -2018,15 +2200,15 @@ Sets the current path to a clipping path. **System capability**: SystemCapability.ArkUI.ArkUI.Full -**Parameters** +**Parameters** | Name | Type | Mandatory | Description | | -------- | -------------- | ---- | ---------------------------------------- | | path | [Path2D](ts-components-canvas-path2d.md) | Yes | A **Path2D** path to use as a clipping area. | -| fillRule | [CanvasFillRule](#canvasfillrule) | No | Rule by which to determine whether a point is inside or outside the area to clip.
The options are **"nonzero"** and **"evenodd"**.
Default value: **"nonzero"** | +| fillRule | [CanvasFillRule](#canvasfillrule) | No | Rule by which to determine whether a point is inside or outside the area to clip.
The options are **"nonzero"** and **"evenodd"**.
Default value: **"nonzero"**| -**Example** +**Example** ```ts // xxx.ets @@ -2061,7 +2243,7 @@ Sets the current path to a clipping path. } ``` - ![en-us_image_000000127777779](figures/en-us_image_000000127777779.png) + ![en-us_image_000000127777779](figures/en-us_image_000000127777779.jpg) ### reset12+ @@ -2070,8 +2252,6 @@ reset(): void Resets this **CanvasRenderingContext2D** object to its default state and clears the background buffer, drawing state stack, defined paths, and styles. -**Widget capability**: This API can be used in ArkTS widgets since API version 12. - **System capability**: SystemCapability.ArkUI.ArkUI.Full **Example** @@ -2112,8 +2292,6 @@ saveLayer(): void Saves this layer. -**Widget capability**: This API can be used in ArkTS widgets since API version 12. - **System capability**: SystemCapability.ArkUI.ArkUI.Full **Example** @@ -2161,8 +2339,6 @@ restoreLayer(): void Restores the image transformation and cropping state to the state before **saveLayer**, and then draws the layer onto the canvas. For the sample code, see the code for **saveLayer**. -**Widget capability**: This API can be used in ArkTS widgets since API version 12. - **System capability**: SystemCapability.ArkUI.ArkUI.Full ### resetTransform @@ -2226,7 +2402,7 @@ Rotates a canvas clockwise around its coordinate axes. | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ---------------------------------------- | -| angle | number | Yes | Clockwise rotation angle. You can use **Math.PI / 180** to convert the angle to a radian.
Default value: **0** | +| angle | number | Yes | Clockwise rotation angle. You can convert degrees to radians using the following formula: degree * Math.PI/180.
Unit: radian| **Example** @@ -2255,7 +2431,7 @@ Rotates a canvas clockwise around its coordinate axes. } ``` - ![en-us_image_0000001212218442](figures/en-us_image_0000001212218442.png) + ![en-us_image_0000001239032417](figures/en-us_image_0000001239032417.png) ### scale @@ -2274,8 +2450,8 @@ Scales the canvas based on the given scale factors. | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ----------- | -| x | number | Yes | Horizontal scale factor.
Default value: **0** | -| y | number | Yes | Vertical scale factor.
Default value: **0** | +| x | number | Yes | Horizontal scale factor.| +| y | number | Yes | Vertical scale factor.| **Example** @@ -2306,7 +2482,7 @@ Scales the canvas based on the given scale factors. } ``` - ![en-us_image_0000001257138347](figures/en-us_image_0000001257138347.png) + ![en-us_image_0000001193872498](figures/en-us_image_0000001193872498.png) ### transform @@ -2332,12 +2508,12 @@ Defines a transformation matrix. To transform a graph, you only need to set para | Name | Type | Mandatory | Description | | ---- | ------ | ---- | -------------------- | -| a | number | Yes | X-axis scale.
Default value: **0** | -| b | number | Yes | Y-axis skew.
Default value: **0** | -| c | number | Yes | X-axis skew.
Default value: **0** | -| d | number | Yes | Y-axis scale.
Default value: **0** | -| e | number | Yes | **translateX**: distance to translate on the x-axis.
Default unit: vp
Default value: **0** | -| f | number | Yes | **translateY**: distance to translate on the y-axis.
Default unit: vp
Default value: **0** | +| a | number | Yes | X-axis scale. | +| b | number | Yes | Y-axis skew. | +| c | number | Yes | X-axis skew. | +| d | number | Yes | Y-axis scale. | +| e | number | Yes | **translateX**: distance to translate on the x-axis.
Default unit: vp| +| f | number | Yes | **translateY**: distance to translate on the y-axis.
Default unit: vp| **Example** @@ -2355,7 +2531,7 @@ Defines a transformation matrix. To transform a graph, you only need to set para .width('100%') .height('100%') .backgroundColor('#ffff00') - .onReady(() =>{ + .onReady(() => { this.context.fillStyle = 'rgb(0,0,0)' this.context.fillRect(0, 0, 100, 100) this.context.transform(1, 0.5, -0.5, 1, 10, 10) @@ -2372,7 +2548,7 @@ Defines a transformation matrix. To transform a graph, you only need to set para } ``` - ![en-us_image_0000001256858393](figures/en-us_image_0000001256858393.png) + ![transform](figures/transform.jpg) ### setTransform @@ -2391,12 +2567,12 @@ Resets the existing transformation matrix and creates a new transformation matri | Name | Type | Mandatory | Description | | ---- | ------ | ---- | -------------------- | -| a | number | Yes | X-axis scale.
Default value: **0** | -| b | number | Yes | Y-axis skew.
Default value: **0** | -| c | number | Yes | X-axis skew.
Default value: **0** | -| d | number | Yes | Y-axis scale.
Default value: **0** | -| e | number | Yes | **translateX**: distance to translate on the x-axis.
Default unit: vp
Default value: **0** | -| f | number | Yes | **translateY**: distance to translate on the y-axis.
Default unit: vp
Default value: **0** | +| a | number | Yes| X-axis scale.| +| b | number | Yes| Y-axis skew. | +| c | number | Yes| X-axis skew. | +| d | number | Yes| Y-axis scale.| +| e | number | Yes| **translateX**: distance to translate on the x-axis.
Default unit: vp| +| f | number | Yes| **translateY**: distance to translate on the y-axis.
Default unit: vp| **Example** @@ -2428,9 +2604,7 @@ Resets the existing transformation matrix and creates a new transformation matri } ``` - ![en-us_image_0000001256858395](figures/en-us_image_0000001256858395.png) - -### setTransform + ![en-us_image_0000001238712421](figures/en-us_image_0000001238712421.png) setTransform(transform?: Matrix2D): void @@ -2444,9 +2618,9 @@ Resets the current transformation to the identity matrix, and then creates a new **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type| Mandatory| Description | | --------- | ---------------------------------------- | ---- | ----- | -| transform | [Matrix2D](ts-components-canvas-matrix2d.md#Matrix2D) | No | Transformation matrix.
Default value: **null** | +| transform | [Matrix2D](ts-components-canvas-matrix2d.md#Matrix2D) | No| Transformation matrix.
Default value: **null**| **Example** @@ -2507,7 +2681,7 @@ Obtains the current transformation matrix being applied to the context. | Type | Description | | ---------------------------------------- | ----- | -| [Matrix2D](ts-components-canvas-matrix2d.md#Matrix2D) | **Matrix2D** object. | +| [Matrix2D](ts-components-canvas-matrix2d.md#Matrix2D) | **Matrix2D** object.| **Example** @@ -2569,10 +2743,10 @@ Moves the origin of the coordinate system. **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory | Description| | ---- | ------ | ---- | -------- | -| x | number | Yes | Distance to translate on the x-axis.
Default unit: vp
Default value: **0** | -| y | number | Yes | Distance to translate on the y-axis.
Default unit: vp
Default value: **0** | +| x | number | Yes | Distance to translate on the x-axis.
Default unit: vp| +| y | number | Yes | Distance to translate on the y-axis.
Default unit: vp| **Example** @@ -2602,15 +2776,49 @@ Moves the origin of the coordinate system. } ``` - ![en-us_image_0000001257138357](figures/en-us_image_0000001257138357.png) + ![en-us_image_0000001194192446](figures/en-us_image_0000001194192446.png) ### drawImage drawImage(image: ImageBitmap | PixelMap, dx: number, dy: number): void +Draws an image on the canvas. + +**Widget capability**: This API can be used in ArkTS widgets since API version 9, except that **PixelMap** objects are not supported. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description| +| ----- | ---------------------------------------- | ---- | ---------------------------------------- | +| image | [ImageBitmap](ts-components-canvas-imagebitmap.md) or [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7)| Yes | Image resource. For details, see **ImageBitmap** or PixelMap. | +| dx | number | Yes | X coordinate of the upper left corner of the drawing area on the canvas.
Default unit: vp| +| dy | number | Yes | Y coordinate of the upper left corner of the drawing area on the canvas.
Default unit: vp| + drawImage(image: ImageBitmap | PixelMap, dx: number, dy: number, dw: number, dh: number): void +Draws an image on the canvas. + +**Widget capability**: This API can be used in ArkTS widgets since API version 9, except that **PixelMap** objects are not supported. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description| +| ----- | ---------------------------------------- | ---- | ---------------------------------------- | +| image | [ImageBitmap](ts-components-canvas-imagebitmap.md) or [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7)| Yes | Image resource. For details, see **ImageBitmap** or PixelMap. | +| dx | number | Yes | X coordinate of the upper left corner of the drawing area on the canvas.
Default unit: vp| +| dy | number | Yes | Y coordinate of the upper left corner of the drawing area on the canvas.
Default unit: vp| +| dw | number | Yes | Width of the drawing area. If the width of the drawing area is different from that of the cropped image, the latter will be stretched or compressed to the former.
Default unit: vp| +| dh | number | Yes | Height of the drawing area. If the height of the drawing area is different from that of the cropped image, the latter will be stretched or compressed to the former.
Default unit: vp| + drawImage(image: ImageBitmap | PixelMap, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void Draws an image on the canvas. @@ -2623,18 +2831,17 @@ Draws an image on the canvas. **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory | Description| | ----- | ---------------------------------------- | ---- | ---------------------------------------- | -| image | [ImageBitmap](ts-components-canvas-imagebitmap.md) or [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) | Yes | Image resource. For details, see **ImageBitmap** or PixelMap. | -| sx | number | No | X coordinate of the upper left corner of the rectangle used to crop the source image.
Default unit: vp
Default value: **0** | -| sy | number | No | Y coordinate of the upper left corner of the rectangle used to crop the source image.
Default unit: vp
Default value: **0** | -| sw | number | No | Target width to crop the source image.
Default unit: vp
Default value: **0** | -| sh | number | No | Target height to crop the source image.
Default unit: vp
Default value: **0** | -| dx | number | Yes | X coordinate of the upper left corner of the drawing area on the canvas.
Default unit: vp
Default value: **0** | -| dy | number | Yes | Y coordinate of the upper left corner of the drawing area on the canvas.
Default unit: vp
Default value: **0** | -| dw | number | No | Width of the drawing area. If the width of the drawing area is different from that of the cropped image, the latter will be stretched or compressed to the former.
Default unit: vp
Default value: **0** | -| dh | number | No | Height of the drawing area. If the height of the drawing area is different from that of the cropped image, the latter will be stretched or compressed to the former.
Default unit: vp
Default value: **0** | - +| image | [ImageBitmap](ts-components-canvas-imagebitmap.md) or [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7)| Yes | Image resource. For details, see **ImageBitmap** or PixelMap. | +| sx | number | Yes | X coordinate of the upper left corner of the rectangle used to crop the source image.
If the type of **image** is ImageBitmap, the default unit is vp.
If the type of **image** is PixelMap, the default unit is px in versions earlier than API version 18 and vp in API version 18 and later.| +| sy | number | Yes | Y coordinate of the upper left corner of the rectangle used to crop the source image.
If the type of **image** is ImageBitmap, the default unit is vp.
If the type of **image** is PixelMap, the default unit is px in versions earlier than API version 18 and vp in API version 18 and later. | +| sw | number | Yes | Target width to crop the source image.
If the type of **image** is ImageBitmap, the default unit is vp.
If the type of **image** is PixelMap, the default unit is px in versions earlier than API version 18 and vp in API version 18 and later. | +| sh | number | Yes | Target height to crop the source image.
If the type of **image** is ImageBitmap, the default unit is vp.
If the type of **image** is PixelMap, the default unit is px in versions earlier than API version 18 and vp in API version 18 and later. | +| dx | number | Yes | X coordinate of the upper left corner of the drawing area on the canvas.
Default unit: vp| +| dy | number | Yes | Y coordinate of the upper left corner of the drawing area on the canvas.
Default unit: vp| +| dw | number | Yes | Width of the drawing area. If the width of the drawing area is different from that of the cropped image, the latter will be stretched or compressed to the former.
Default unit: vp| +| dh | number | Yes | Height of the drawing area. If the height of the drawing area is different from that of the cropped image, the latter will be stretched or compressed to the former.
Default unit: vp| **Example** @@ -2645,7 +2852,7 @@ Draws an image on the canvas. struct ImageExample { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private img:ImageBitmap = new ImageBitmap("common/images/example.jpg") + private img: ImageBitmap = new ImageBitmap("common/images/example.jpg") build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -2653,9 +2860,11 @@ Draws an image on the canvas. .width('100%') .height('100%') .backgroundColor('#ffff00') - .onReady(() =>{ - this.context.drawImage( this.img,0,0,500,500,0,0,400,200) - }) + .onReady(() => { + this.context.drawImage(this.img, 0, 0) + this.context.drawImage(this.img, 0, 150, 300, 100) + this.context.drawImage(this.img, 0, 0, 500, 500, 0, 300, 400, 200) + }) } .width('100%') .height('100%') @@ -2663,14 +2872,14 @@ Draws an image on the canvas. } ``` - ![en-us_image_0000001194352442](figures/en-us_image_0000001194352442.png) + ![en-us_image_0000001194352442](figures/en-us_image_0000001194352441.png) ### createImageData createImageData(sw: number, sh: number): ImageData -Creates a blank **ImageData** object of a specified size. For details, see [ImageData](ts-components-canvas-imagedata.md). The example is the same as that of **putImageData**. +Creates a blank [ImageData](ts-components-canvas-imagedata.md) object of a specified size. This API involves time-consuming memory copy. Therefore, avoid frequent calls to it. The example is the same as that of **putImageData**. **Widget capability**: This API can be used in ArkTS widgets since API version 9. @@ -2680,15 +2889,15 @@ Creates a blank **ImageData** object of a specified size. For details, see [Imag **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory | Description| | ---- | ------ | ---- | ------------- | -| sw | number | Yes | Width of the **ImageData** object.
Default unit: vp
Default value: **0** | -| sh | number | Yes | Height of the **ImageData** object.
Default unit: vp
Default value: **0** | +| sw | number | Yes| Width of the **ImageData** object.
Default unit: vp| +| sh | number | Yes| Height of the **ImageData** object.
Default unit: vp| createImageData(imageData: ImageData): ImageData -Creates an [ImageData](ts-components-canvas-imagedata.md) object with the same width and height of an existing **ImageData** object. The example is the same as that of **putImageData**. +Creates an [ImageData](ts-components-canvas-imagedata.md) object with the same width and height of an existing **ImageData** object. This API involves time-consuming memory copy. Therefore, avoid frequent calls to it. The example is the same as that of **putImageData**. **Widget capability**: This API can be used in ArkTS widgets since API version 9. @@ -2698,15 +2907,15 @@ Creates an [ImageData](ts-components-canvas-imagedata.md) object with the same w **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type | Mandatory| Description | | --------- | ---------------------------------------- | ---- | ----------------- | -| imagedata | [ImageData](ts-components-canvas-imagedata.md) | Yes | Existing **ImageData** object. | +| imagedata | [ImageData](ts-components-canvas-imagedata.md) | Yes| Existing **ImageData** object.| **Return value** | Type | Description | | ---------------------------------------- | -------------- | -| [ImageData](ts-components-canvas-imagedata.md) | New **ImageData** object. | +| [ImageData](ts-components-canvas-imagedata.md) | New **ImageData** object.| ### getPixelMap @@ -2721,21 +2930,25 @@ Obtains the [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) object c **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description| | ---- | ------ | ---- | --------------- | -| sx | number | Yes | X coordinate of the upper left corner of the output area.
Default unit: vp
Default value: **0** | -| sy | number | Yes | Y coordinate of the upper left corner of the output area.
Default unit: vp
Default value: **0** | -| sw | number | Yes | Width of the output area.
Default unit: vp
Default value: **0** | -| sh | number | Yes | Height of the output area.
Default unit: vp
Default value: **0** | +| sx | number | Yes | X coordinate of the upper left corner of the output area.
Default unit: vp| +| sy | number | Yes | Y coordinate of the upper left corner of the output area.
Default unit: vp| +| sw | number | Yes | Width of the output area.
Default unit: vp| +| sh | number | Yes | Height of the output area.
Default unit: vp| **Return value** | Type | Description | | ---------------------------------------- | ------------- | -| [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) | **PixelMap** object. | +| [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) | **PixelMap** object.| **Example** +> **NOTE** +> +> DevEco Studio Previewer does not support displaying content drawn using **setPixelMap**. + ```ts // xxx.ets @Entry @@ -2743,7 +2956,7 @@ Obtains the [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) object c struct GetPixelMap { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private img:ImageBitmap = new ImageBitmap("/images/star.png") + private img: ImageBitmap = new ImageBitmap("common/images/example.jpg") build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -2751,19 +2964,35 @@ Obtains the [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) object c .width('100%') .height('100%') .backgroundColor('#ffff00') - .onReady(() =>{ - this.context.drawImage(this.img,0,0,130,130) - let pixelmap = this.context.getPixelMap(50,50,130,130) - this.context.drawImage(pixelmap,150,150) + .onReady(() => { + this.context.drawImage(this.img, 100, 100, 130, 130) + let pixelmap = this.context.getPixelMap(150, 150, 130, 130) + this.context.setPixelMap(pixelmap) }) } .width('100%') .height('100%') } - } + } ``` - ![en-us_image_000000127777782](figures/en-us_image_000000127777782.jpeg) + ![en-us_image_000000127777782](figures/en-us_image_000000127777782.png) + +### setPixelMap + +setPixelMap(value?: PixelMap): void + +Draws the input [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) object on the canvas. The example is the same as that of **getPixelMap**. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + + **Parameters** + +| Name | Type | Mandatory | Description| +| ---- | ------ | ---- | --------------- | +| value | [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) | No| **PixelMap** object that contains pixel values.
Default value: **null**| ### getImageData @@ -2779,18 +3008,18 @@ Obtains the [ImageData](ts-components-canvas-imagedata.md) object created with t **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory | Description | | ---- | ------ | ---- | --------------- | -| sx | number | Yes | X coordinate of the upper left corner of the output area.
Default unit: vp
Default value: **0** | -| sy | number | Yes | Y coordinate of the upper left corner of the output area.
Default unit: vp
Default value: **0** | -| sw | number | Yes | Width of the output area.
Default unit: vp
Default value: **0** | -| sh | number | Yes | Height of the output area.
Default unit: vp
Default value: **0** | +| sx | number | Yes| X coordinate of the upper left corner of the output area.
Default unit: vp| +| sy | number | Yes| Y coordinate of the upper left corner of the output area.
Default unit: vp| +| sw | number | Yes| Width of the output area.
Default unit: vp| +| sh | number | Yes| Height of the output area.
Default unit: vp| **Return value** | Type | Description | | ---------------------------------------- | -------------- | -| [ImageData](ts-components-canvas-imagedata.md) | New **ImageData** object. | +| [ImageData](ts-components-canvas-imagedata.md) | New **ImageData** object.| **Example** @@ -2829,6 +3058,22 @@ Obtains the [ImageData](ts-components-canvas-imagedata.md) object created with t putImageData(imageData: ImageData, dx: number | string, dy: number | string): void +Puts an [ImageData](ts-components-canvas-imagedata.md) object onto a rectangular area on the canvas. + +**Widget capability**: This API can be used in ArkTS widgets since API version 9. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type| Mandatory | Description| +| ----------- | ---------------------------------------- | ---- | ----------------------------- | +| imagedata | [ImageData](ts-components-canvas-imagedata.md) | Yes | **ImageData** object with pixels to put onto the canvas.| +| dx | number \| string10+ | Yes | X-axis offset of the rectangular area on the canvas.
Default unit: vp| +| dy | number \| string10+ | Yes | Y-axis offset of the rectangular area on the canvas.
Default unit: vp| + putImageData(imageData: ImageData, dx: number | string, dy: number | string, dirtyX: number | string, dirtyY: number | string, dirtyWidth: number | string, dirtyHeight: number | string): void Puts an **[ImageData](ts-components-canvas-imagedata.md)** object onto a rectangular area on the canvas. @@ -2841,15 +3086,15 @@ Puts an **[ImageData](ts-components-canvas-imagedata.md)** object onto a rectang **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory | Description| | ----------- | ---------------------------------------- | ---- | ----------------------------- | -| imagedata | [ImageData](ts-components-canvas-imagedata.md) | Yes | **ImageData** object with pixels to put onto the canvas. | -| dx | number \| string10+ | Yes | X-axis offset of the rectangular area on the canvas.
Default unit: vp
Default value: **0** | -| dy | number \| string10+ | Yes | Y-axis offset of the rectangular area on the canvas.
Default unit: vp
Default value: **0** | -| dirtyX | number \| string10+ | No | X-axis offset of the upper left corner of the rectangular area relative to that of the source image.
Default unit: vp
Default value: **0** | -| dirtyY | number \| string10+ | No | Y-axis offset of the upper left corner of the rectangular area relative to that of the source image.
Default unit: vp
Default value: **0** | -| dirtyWidth | number \| string10+ | No | Width of the rectangular area to crop the source image.
Default unit: vp
Default value: width of the **ImageData** object | -| dirtyHeight | number \| string10+ | No | Height of the rectangular area to crop the source image.
Default unit: vp
Default value: height of the **ImageData** object | +| imagedata | [ImageData](ts-components-canvas-imagedata.md) | Yes | **ImageData** object with pixels to put onto the canvas.| +| dx | number \| string10+ | Yes | X-axis offset of the rectangular area on the canvas.
Default unit: vp| +| dy | number \| string10+ | Yes | Y-axis offset of the rectangular area on the canvas.
Default unit: vp| +| dirtyX | number \| string10+ | Yes | X-axis offset of the upper left corner of the rectangular area relative to that of the source image.
Default unit: vp| +| dirtyY | number \| string10+ | Yes | Y-axis offset of the upper left corner of the rectangular area relative to that of the source image.
Default unit: vp| +| dirtyWidth | number \| string10+ | Yes | Width of the rectangular area to crop the source image.
Default unit: vp| +| dirtyHeight | number \| string10+ | Yes | Height of the rectangular area to crop the source image.
Default unit: vp| **Example** @@ -2867,16 +3112,17 @@ Puts an **[ImageData](ts-components-canvas-imagedata.md)** object onto a rectang .width('100%') .height('100%') .backgroundColor('#ffff00') - .onReady(() =>{ + .onReady(() => { let imageDataNum = this.context.createImageData(100, 100) - for (let i = 0; i < imageDataNum.data.length; i += 4) { - imageDataNum.data[i + 0] = 255 - imageDataNum.data[i + 1] = 0 - imageDataNum.data[i + 2] = 255 - imageDataNum.data[i + 3] = 255 - } let imageData = this.context.createImageData(imageDataNum) + for (let i = 0; i < imageData.data.length; i += 4) { + imageData.data[i + 0] = 255 + imageData.data[i + 1] = 0 + imageData.data[i + 2] = 255 + imageData.data[i + 3] = 255 + } this.context.putImageData(imageData, 10, 10) + this.context.putImageData(imageData, 150, 10, 0, 0, 50, 50) }) } .width('100%') @@ -2900,13 +3146,13 @@ Sets the dash line style. **System capability**: SystemCapability.ArkUI.ArkUI.Full -**Parameters** +**Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory | Description| | -------- | -------- | ------- | ------------ | -| segments | number[] | Yes | An array of numbers that specify distances to alternately draw a line and a gap.
Default unit: vp | +| segments | number[] | Yes| An array of numbers that specify distances to alternately draw a line and a gap.
Default unit: vp| -**Example** +**Example** ```ts // xxx.ets @@ -2949,14 +3195,14 @@ Obtains the dash line style. **System capability**: SystemCapability.ArkUI.ArkUI.Full -**Return value** +**Return value** | Type | Description | | -------- | ------------------------ | -| number[] | Interval of alternate line segments and the length of spacing.
Default unit: vp | +| number[] | Interval of alternate line segments and the length of spacing.
Default unit: vp| -**Example** +**Example** ```ts // xxx.ets @@ -3009,13 +3255,13 @@ Displays the specified **ImageBitmap** object. **System capability**: SystemCapability.ArkUI.ArkUI.Full -**Parameters** +**Parameters** -| Name | Type | Mandatory | Description | +| Name| Type | Mandatory| Description | | ------ | ----------------------- | ----------------- | ------------------ | -| bitmap | [ImageBitmap](ts-components-canvas-imagebitmap.md) | Yes | **ImageBitmap** object to display. | +| bitmap | [ImageBitmap](ts-components-canvas-imagebitmap.md) | Yes| **ImageBitmap** object to display.| -**Example** +**Example** ```ts // xxx.ets @@ -3031,14 +3277,14 @@ Displays the specified **ImageBitmap** object. Canvas(this.context) .width('100%') .height('100%') - .backgroundColor('#ffff00') + .backgroundColor('rgb(213,213,213)') .onReady(() =>{ let imageData = this.offContext.createImageData(100, 100) for (let i = 0; i < imageData.data.length; i += 4) { imageData.data[i + 0] = 255 imageData.data[i + 1] = 0 - imageData.data[i + 2] = 255 - imageData.data[i + 3] = 255 + imageData.data[i + 2] = 60 + imageData.data[i + 3] = 80 } this.offContext.putImageData(imageData, 10, 10) let image = this.offContext.transferToImageBitmap() @@ -3050,14 +3296,14 @@ Displays the specified **ImageBitmap** object. } } ``` - ![en-us_image_0000001238952387](figures/en-us_image_0000001238952387.png) + ![transferFromImageBitmap](figures/transferFromImageBitmap.jpg) ### toDataURL toDataURL(type?: string, quality?: any): string -Generates a URL containing image display information. +Creates a data URL that contains a representation of an image. This API involves time-consuming memory copy. Therefore, avoid frequent calls to it. **Widget capability**: This API can be used in ArkTS widgets since API version 9. @@ -3065,18 +3311,18 @@ Generates a URL containing image display information. **System capability**: SystemCapability.ArkUI.ArkUI.Full -**Parameters** +**Parameters** | Name | Type | Mandatory | Description | | ------- | ------ | ---- | ---------------------------------------- | -| type | string | No | Image format. The default value is **image/png**. | -| quality | any | No | Image quality, which ranges from 0 to 1, when the image format is **image/jpeg** or **image/webp**. If the set value is beyond the value range, the default value **0.92** is used. | +| type | string | No | Image format.
The options are as follows: **"image/png"**, **"image/jpeg"**, **"image/webp"**.
Default value: **"image/png"** | +| quality | any | No | Image quality, which ranges from 0 to 1, when the image format is **image/jpeg** or **image/webp**. If the set value is beyond the value range, the default value **0.92** is used.
Default value: **0.92**| -**Return value** +**Return value** | Type | Description | | ------ | --------- | -| string | Image URL. | +| string | Image URL.| **Example** @@ -3116,6 +3362,12 @@ restore(): void Restores the saved drawing context. +> **NOTE** +> +> When the number of calls to **restore()** does not exceed the number of calls to **save()**, this API pops the saved drawing state from the stack and restores the properties, clipping path, and transformation matrix of the **CanvasRenderingContext2D** object.
+> If the number of calls to **restore()** exceeds the number of calls to **save()**, this API does nothing.
+> If there is no saved state, this API does nothing. + **Widget capability**: This API can be used in ArkTS widgets since API version 9. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -3212,18 +3464,18 @@ Creates a linear gradient. **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ---- | ------ | ---- | -------- | -| x0 | number | Yes | X coordinate of the start point.
Default unit: vp
Default value: **0** | -| y0 | number | Yes | Y coordinate of the start point.
Default unit: vp
Default value: **0** | -| x1 | number | Yes | X coordinate of the end point.
Default unit: vp
Default value: **0** | -| y1 | number | Yes | Y coordinate of the end point.
Default unit: vp
Default value: **0** | +| x0 | number | Yes | X coordinate of the start point.
Default unit: vp| +| y0 | number | Yes | Y coordinate of the start point.
Default unit: vp| +| x1 | number | Yes | X coordinate of the end point.
Default unit: vp| +| y1 | number | Yes | Y coordinate of the end point.
Default unit: vp| -**Return value** +**Return value** | Type | Description | | ------ | --------- | -| [CanvasGradient](ts-components-canvas-canvasgradient.md) | New **CanvasGradient** object used to create a gradient on the canvas. | +| [CanvasGradient](ts-components-canvas-canvasgradient.md) | New **CanvasGradient** object used to create a gradient on the canvas.| **Example** @@ -3275,18 +3527,18 @@ Creates a linear gradient. | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ----------------- | -| x0 | number | Yes | X coordinate of the center of the start circle.
Default unit: vp
Default value: **0** | -| y0 | number | Yes | Y coordinate of the center of the start circle.
Default unit: vp
Default value: **0** | -| r0 | number | Yes | Radius of the start circle, which must be a non-negative finite number.
Default unit: vp
Default value: **0** | -| x1 | number | Yes | X coordinate of the center of the end circle.
Default unit: vp
Default value: **0** | -| y1 | number | Yes | Y coordinate of the center of the end circle.
Default unit: vp
Default value: **0** | -| r1 | number | Yes | Radius of the end circle, which must be a non-negative finite number.
Default unit: vp
Default value: **0** | +| x0 | number | Yes | X coordinate of the center of the start circle.
Default unit: vp| +| y0 | number | Yes | Y coordinate of the center of the start circle.
Default unit: vp| +| r0 | number | Yes | Radius of the start circle, which must be a non-negative finite number.
Default unit: vp| +| x1 | number | Yes | X coordinate of the center of the end circle.
Default unit: vp| +| y1 | number | Yes | Y coordinate of the center of the end circle.
Default unit: vp| +| r1 | number | Yes | Radius of the end circle, which must be a non-negative finite number.
Default unit: vp| -**Return value** +**Return value** | Type | Description | | ------ | --------- | -| [CanvasGradient](ts-components-canvas-canvasgradient.md) | New **CanvasGradient** object used to create a gradient on the canvas. | +| [CanvasGradient](ts-components-canvas-canvasgradient.md) | New **CanvasGradient** object used to create a gradient on the canvas.| **Example** @@ -3333,17 +3585,17 @@ Creates a conic gradient. **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ---------- | ------ | ---- | ----------------------------------- | -| startAngle | number | Yes | Angle at which the gradient starts, in radians. The angle measurement starts horizontally from the right side of the center and moves clockwise.
Default value: **0** | -| x | number | Yes | X coordinate of the center of the conic gradient,
Default unit: vp
Default value: **0** | -| y | number | Yes | Y coordinate of the center of the conic gradient,
Default unit: vp
Default value: **0** | +| startAngle | number | Yes | Angle at which the gradient starts. The angle measurement starts horizontally from the right side of the center and moves clockwise.
Unit: radian| +| x | number | Yes | X coordinate of the center of the conic gradient,
Default unit: vp| +| y | number | Yes | Y coordinate of the center of the conic gradient,
Default unit: vp| -**Return value** +**Return value** | Type | Description | | ------ | --------- | -| [CanvasGradient](ts-components-canvas-canvasgradient.md) | New **CanvasGradient** object used to create a gradient on the canvas. | +| [CanvasGradient](ts-components-canvas-canvasgradient.md) | New **CanvasGradient** object used to create a gradient on the canvas.| **Example** @@ -3378,11 +3630,180 @@ struct CanvasExample { ![en-us_image_0000001239032419](figures/en-us_image_0000001239032420.png) +### on('onAttach')13+ + +on(type: 'onAttach', callback: () => void): void + +Subscribes to the event when a **CanvasRenderingContext2D** object is bound to a **Canvas** component. + +**Atomic service API**: This API can be used in atomic services since API version 13. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | --------- | ---- | ---------------------------------------------------------------------- | +| type | string | Yes | Event type, which is **'onAttach'** in this case.| +| callback | () => void | Yes | Callback triggered when the **CanvasRenderingContext2D** object is bound to the **Canvas** component.| + +> **NOTE** +> +> A **CanvasRenderingContext2D** object can only be bound to one **Canvas** component at a time.
+> When a **CanvasRenderingContext2D** object is bound to a **Canvas** component, the **onAttach** callback is triggered, indicating that the [canvas](#canvas13) object is accessible.
+> Avoid performing drawing operations in the **onAttach** callback. Make sure the **Canvas** component has completed its **[onReady](ts-components-canvas-canvas.md#events)** event before performing any drawing.
+> The **onAttach** callback is triggered when:
+> 1. A **Canvas** component is created and bound to a **CanvasRenderingContext2D** object.
+> 2. A **CanvasRenderingContext2D** object is bound to a new **Canvas** component.
+ + +### on('onDetach')13+ + +on(type: 'onDetach', callback: () => void): void + +Subscribes to the event when a **CanvasRenderingContext2D** object is unbound from a **Canvas** component. + +**Atomic service API**: This API can be used in atomic services since API version 13. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | --------- | ---- | ---------------------------------------------------------------------- | +| type | string | Yes | Event type, which is **'onDetach'** in this case.| +| callback | () => void | Yes | Callback triggered when the **CanvasRenderingContext2D** object is unbound from the **Canvas** component.| + +> **NOTE** +> +> When a **CanvasRenderingContext2D** object is unbound from a **Canvas** component, the **onDetach** callback is triggered. In this case, cease any drawing operations.
+> The **onDetach** callback is triggered when:
+> 1. A **Canvas** component is destroyed and unbound from a **CanvasRenderingContext2D** object.
+> 2. A **CanvasRenderingContext2D** object is bound to a different** Canvas** component, causing the existing binding to be released.
+ +### off('onAttach')13+ + +off(type: 'onAttach', callback?: () => void): void + +Unsubscribes from the event when a **CanvasRenderingContext2D** object is bound to a **Canvas** component. + +**Atomic service API**: This API can be used in atomic services since API version 13. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | --------- | ---- | ---------------------------------------------------------------------- | +| type | string | Yes | Event type, which is **'onAttach'** in this case.| +| callback | () => void | No | Callback to unregister.
If this parameter is not specified, this API unregisters all callbacks for the **'onAttach'** event.| + +### off('onDetach')13+ + +off(type: 'onDetach', callback?: () => void): void + +Unsubscribes from the event when a **CanvasRenderingContext2D** object is unbound from a **Canvas** component. + +**Atomic service API**: This API can be used in atomic services since API version 13. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | --------- | ---- | ---------------------------------------------------------------------- | +| type | string | Yes | Event type, which is **'onDetach'** in this case.| +| callback | () => void | No | Callback to unregister.
If this parameter is not specified, this API unregisters all callbacks for the **'onDetach'** event.| + +**Example** + +```ts +import { FrameNode } from '@kit.ArkUI' +// xxx.ets +@Entry +@Component +struct AttachDetachExample { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + private scroller: Scroller = new Scroller() + private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] + private node: FrameNode | null = null + private attachCallback: Callback = this.attachFunc.bind(this) + private detachCallback: Callback = this.detachFunc.bind(this) + + attachFunc(): void { + console.info('CanvasRenderingContext2D attached to the canvas frame node.') + this.node = this.context.canvas + } + detachFunc(): void { + console.info('CanvasRenderingContext2D detach from the canvas frame node.') + this.node = null + } + aboutToAppear(): void { + this.context.on('onAttach', this.attachCallback) + this.context.on('onDetach', this.detachCallback) + } + aboutToDisappear(): void { + this.context.off('onAttach') + this.context.off('onDetach') + } + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Scroll(this.scroller) { + Flex({ direction: FlexDirection.Column}) { + ForEach(this.arr, (item: number) => { + Row() { + if (item == 3) { + Canvas(this.context) + .width('100%') + .height(150) + .backgroundColor('rgb(213,213,213)') + .onReady(() => { + this.context.font = '30vp sans-serif' + this.node?.commonEvent.setOnVisibleAreaApproximateChange( + { ratios: [0, 1], expectedUpdateInterval: 10}, + (isVisible: boolean, currentRatio: number) => { + if (!isVisible && currentRatio <= 0.0) { + console.info('Canvas is completely invisible.') + } + if (isVisible && currentRatio >= 1.0) { + console.info('Canvas is fully visible.') + } + } + ) + }) + } else { + Text(item.toString()) + .width('100%') + .height(150) + .backgroundColor('rgb(39,135,217)') + .borderRadius(15) + .fontSize(16) + .textAlign(TextAlign.Center) + .margin({ top: 5 }) + } + } + }, (item: number) => item.toString()) + } + } + .width('90%') + .scrollBar(BarState.Off) + .scrollable(ScrollDirection.Vertical) + } + .width('100%') + .height('100%') + } +} +``` + +![on_off_1](figures/on_off_cut.gif) + ### startImageAnalyzer12+ startImageAnalyzer(config: ImageAnalyzerConfig): Promise\ -Starts AI image analysis in the given settings. Before calling this API, make sure the AI analyzer is [enabled](ts-components-canvas-canvas.md#enableanalyzer12).
Because the image frame used for analysis is the one captured when this API is called, pay attention to the invoking time of this API.
If this method is repeatedly called before the execution is complete, an error callback is triggered. For the sample code, see the code for **stopImageAnalyzer**. +Starts AI image analysis in the given settings. Before calling this API, make sure the AI image analyzer is [enabled](ts-components-canvas-canvas.md#enableanalyzer12).
Because the image frame used for analysis is the one captured when this API is called, pay attention to the invoking time of this API.
If this method is repeatedly called before the execution is complete, an error callback is triggered. For the sample code, see the code for **stopImageAnalyzer**. > **NOTE** > @@ -3396,21 +3817,21 @@ Starts AI image analysis in the given settings. Before calling this API, make su **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type | Mandatory| Description | | ------ | --------- | ---- | ---------------------------------------------------------------------- | -| config | [ImageAnalyzerConfig](ts-image-common.md#imageanalyzerconfig) | Yes | Settings of the AI analyzer. | +| config | [ImageAnalyzerConfig](ts-image-common.md#imageanalyzerconfig) | Yes | Settings of the AI analyzer.| **Return value** | Type | Description | | ----------------- | ------------------------------------ | -| Promise\ | Promise used to return the result. | +| Promise\ | Promise used to return the result.| **Error codes** For details about the error codes, see [AI Analysis Error Codes](../errorcode-image-analyzer.md). -| ID | Error Message | +| ID| Error Message | | -------- | -------------------------------------------- | | 110001 | AI analysis is unsupported. | | 110002 | AI analysis is ongoing. | @@ -3501,7 +3922,7 @@ struct ImageAnalyzerExample { | Type | Description | | ------- | ------------------- | -| inherit | The text direction is inherited from the **Canvas** component. | +| inherit | The text direction is inherited from the **Canvas** component.| | ltr | The text direction is from left to right. | | rtl | The text direction is from right to left. | @@ -3515,8 +3936,8 @@ struct ImageAnalyzerExample { | Type | Description | | ------- | ----- | -| evenodd | The inside part of a shape is determined based on whether the counting result is an odd number or not. | -| nonzero | The inside part of a shape is determined based on whether the counting result is zero or not. | +| evenodd | The inside part of a shape is determined based on whether the counting result is an odd number or not.| +| nonzero | The inside part of a shape is determined based on whether the counting result is zero or not.| ## CanvasLineCap @@ -3530,7 +3951,7 @@ struct ImageAnalyzerExample { | ------ | ----------------------------- | | butt | The ends of the line are squared off, and the line does not extend beyond its two endpoints. | | round | The line is extended at the endpoints by a half circle whose diameter is equal to the line width. | -| square | The line is extended at the endpoints by a rectangle whose width is equal to half the line width and height equal to the line width. | +| square | The line is extended at the endpoints by a rectangle whose width is equal to half the line width and height equal to the line width.| ## CanvasLineJoin @@ -3543,7 +3964,7 @@ struct ImageAnalyzerExample { | Type | Description | | ----- | ---------------------------------------- | | bevel | The intersection is a triangle. The rectangular corner of each line is independent. | -| miter | The intersection has a miter corner by extending the outside edges of the lines until they meet. You can view the effect of this attribute in **miterLimit**. | +| miter | The intersection has a miter corner by extending the outside edges of the lines until they meet. You can view the effect of this attribute in **miterLimit**.| | round | The intersection is a sector, whose radius at the rounded corner is equal to the line width. | ## CanvasTextAlign @@ -3557,8 +3978,8 @@ struct ImageAnalyzerExample { | Type | Description | | ------ | ------------ | | center | The text is center-aligned. | -| start | The text is aligned with the start bound. | -| end | The text is aligned with the end bound. | +| start | The text is aligned with the start bound.| +| end | The text is aligned with the end bound.| | left | The text is left-aligned. | | right | The text is right-aligned. | @@ -3573,9 +3994,9 @@ struct ImageAnalyzerExample { | Type | Description | | ----------- | ---------------------------------------- | | alphabetic | The text baseline is the normal alphabetic baseline. | -| bottom | The text baseline is at the bottom of the text bounding box. Its difference from the ideographic baseline is that the ideographic baseline does not consider letters in the next line. | +| bottom | The text baseline is at the bottom of the text bounding box. Its difference from the ideographic baseline is that the ideographic baseline does not consider letters in the next line.| | hanging | The text baseline is a hanging baseline over the text. | -| ideographic | The text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excessive character. | +| ideographic | The text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excessive character.| | middle | The text baseline is in the middle of the text bounding box. | | top | The text baseline is on the top of the text bounding box. | @@ -3601,18 +4022,18 @@ struct ImageAnalyzerExample { **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Read Only | Optional | Description | +| Name| Type| Read Only| Optional| Description| | ---------- | -------------- | ------ | ---------------- | ------------------------ | -| width | number | Yes | No | Width of the text. Read-only. | -| height | number | Yes | No | Height of the text. Read-only. | -| actualBoundingBoxAscent | number | Yes | No | Distance from the horizontal line specified by the [CanvasRenderingContext2D.textBaseline](#canvastextbaseline) attribute to the top of the bounding rectangle used to render the text. Read-only. | -| actualBoundingBoxDescent | number | Yes | No | Distance from the horizontal line specified by the [CanvasRenderingContext2D.textBaseline](#canvastextbaseline) attribute to the bottom of the bounding rectangle used to render the text. Read-only. | -| actualBoundingBoxLeft | number | Yes | No | Distance parallel to the baseline from the alignment point determined by the [CanvasRenderingContext2D.textAlign](#canvastextalign) attribute to the left side of the bounding rectangle of the text. Read-only. | -| actualBoundingBoxRight | number | Yes | No | Distance parallel to the baseline from the alignment point determined by the [CanvasRenderingContext2D.textAlign](#canvastextalign) attribute to the right side of the bounding rectangle of the text. Read-only. | -| alphabeticBaseline | number | Yes | No | Distance from the horizontal line specified by the [CanvasRenderingContext2D.textBaseline](#canvastextbaseline) attribute to the alphabetic baseline of the line box. Read-only. | -| emHeightAscent | number | Yes | No | Distance from the horizontal line specified by the [CanvasRenderingContext2D.textBaseline](#canvastextbaseline) attribute to the top of the em square in the line box. Read-only. | -| emHeightDescent | number | Yes | No | Distance from the horizontal line specified by the [CanvasRenderingContext2D.textBaseline](#canvastextbaseline) attribute to the bottom of the em square in the line box. Read-only. | -| fontBoundingBoxAscent | number | Yes | No | Distance from the horizontal line specified by the [CanvasRenderingContext2D.textBaseline](#canvastextbaseline) attribute to the top of the bounding rectangle of all the fonts used to render the text. Read-only. | -| fontBoundingBoxDescent | number | Yes | No | Distance from the horizontal line specified by the [CanvasRenderingContext2D.textBaseline](#canvastextbaseline) attribute to the bottom of the bounding rectangle of all the fonts used to render the text. Read-only. | -| hangingBaseline | number | Yes | No | Distance from the horizontal line specified by the [CanvasRenderingContext2D.textBaseline](#canvastextbaseline) attribute to the hanging baseline of the line box. Read-only. | -| ideographicBaseline | number | Yes | No | Distance from the horizontal line specified by the [CanvasRenderingContext2D.textBaseline](#canvastextbaseline) attribute to the ideographic baseline of the line box. Read-only. | +| width | number | Yes| No| Width of the text. Read-only.| +| height | number | Yes| No| Height of the text. Read-only.| +| actualBoundingBoxAscent | number | Yes| No| Distance from the horizontal line specified by the [CanvasRenderingContext2D.textBaseline](#canvastextbaseline) attribute to the top of the bounding rectangle used to render the text. Read-only.| +| actualBoundingBoxDescent | number | Yes| No| Distance from the horizontal line specified by the [CanvasRenderingContext2D.textBaseline](#canvastextbaseline) attribute to the bottom of the bounding rectangle used to render the text. Read-only.| +| actualBoundingBoxLeft | number | Yes| No| Distance parallel to the baseline from the alignment point determined by the [CanvasRenderingContext2D.textAlign](#canvastextalign) attribute to the left side of the bounding rectangle of the text. Read-only.| +| actualBoundingBoxRight | number | Yes| No| Distance parallel to the baseline from the alignment point determined by the [CanvasRenderingContext2D.textAlign](#canvastextalign) attribute to the right side of the bounding rectangle of the text. Read-only.| +| alphabeticBaseline | number | Yes| No| Distance from the horizontal line specified by the [CanvasRenderingContext2D.textBaseline](#canvastextbaseline) attribute to the alphabetic baseline of the line box. Read-only.| +| emHeightAscent | number | Yes| No| Distance from the horizontal line specified by the [CanvasRenderingContext2D.textBaseline](#canvastextbaseline) attribute to the top of the em square in the line box. Read-only.| +| emHeightDescent | number | Yes| No| Distance from the horizontal line specified by the [CanvasRenderingContext2D.textBaseline](#canvastextbaseline) attribute to the bottom of the em square in the line box. Read-only.| +| fontBoundingBoxAscent | number | Yes| No| Distance from the horizontal line specified by the [CanvasRenderingContext2D.textBaseline](#canvastextbaseline) attribute to the top of the bounding rectangle of all the fonts used to render the text. Read-only.| +| fontBoundingBoxDescent | number | Yes| No| Distance from the horizontal line specified by the [CanvasRenderingContext2D.textBaseline](#canvastextbaseline) attribute to the bottom of the bounding rectangle of all the fonts used to render the text. Read-only.| +| hangingBaseline | number | Yes| No| Distance from the horizontal line specified by the [CanvasRenderingContext2D.textBaseline](#canvastextbaseline) attribute to the alphabetic baseline of the line box. Read-only.| +| ideographicBaseline | number | Yes| No| Distance from the horizontal line specified by the [CanvasRenderingContext2D.textBaseline](#canvastextbaseline) attribute to the ideographic baseline of the line box. Read-only.| diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-component-general-attributes.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-component-general-attributes.md new file mode 100644 index 0000000000000000000000000000000000000000..bfce463dec1991479522f9efdfa4518a68e6e927 --- /dev/null +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-component-general-attributes.md @@ -0,0 +1,58 @@ +# Universal Attributes + +- [Size](ts-universal-attributes-size.md) +- [Location](ts-universal-attributes-location.md) +- [Layout Constraints](ts-universal-attributes-layout-constraints.md) +- [Component-Level Pixel Rounding](ts-universal-attributes-pixelRound.md) +- [Flex Layout](ts-universal-attributes-flex-layout.md) +- [Border](ts-universal-attributes-border.md) +- [Border Image](ts-universal-attributes-border-image.md) +- [Background](ts-universal-attributes-background.md) +- [Opacity](ts-universal-attributes-opacity.md) +- [Visibility](ts-universal-attributes-visibility.md) +- [Enable/Disable](ts-universal-attributes-enable.md) +- [Overlay](ts-universal-attributes-overlay.md) +- [Z-order Control](ts-universal-attributes-z-order.md) +- [Transformation](ts-universal-attributes-transformation.md) +- [Image Effect](ts-universal-attributes-image-effect.md) +- [Shape Clipping](ts-universal-attributes-sharp-clipping.md) +- [Gradient Color](ts-universal-attributes-gradient-color.md) +- [Popup Control](ts-universal-attributes-popup.md) +- [Menu Control](ts-universal-attributes-menu.md) +- [Focus Control](ts-universal-attributes-focus.md) +- [Hover Effect](ts-universal-attributes-hover-effect.md) +- [Component ID](ts-universal-attributes-component-id.md) +- [Reuse ID](ts-universal-attributes-reuse-id.md) +- [Polymorphic Style](ts-universal-attributes-polymorphic-style.md) +- [restoreId](ts-universal-attributes-restoreId.md) +- [Foreground Color](ts-universal-attributes-foreground-color.md) +- [Foreground Effect](ts-universal-attributes-foreground-effect.md) +- [Foreground Blur](ts-universal-attributes-foreground-blur-style.md) +- [Motion Blur](ts-universal-attributes-motionBlur.md) +- [Click Effect](ts-universal-attributes-click-effect.md) +- [Accessibility](ts-universal-attributes-accessibility.md) +- [Attribute Modifier](ts-universal-attributes-attribute-modifier.md) +- [Gesture Modifier](ts-universal-attributes-gesture-modifier.md) +- [Outline](ts-universal-attributes-outline.md) +- [Visual Effect](ts-universal-attributes-filter-effect.md) +- [Drawing Modifier](ts-universal-attributes-draw-modifier.md) +- [Content Modifier](ts-universal-attributes-content-modifier.md) +- [Custom Property](ts-universal-attributes-custom-property.md) +- Touch Interactions + - [Touch Target](ts-universal-attributes-touch-target.md) + - [Hit Test Control](ts-universal-attributes-hit-test-behavior.md) +- Transition + - [Modal Transition](ts-universal-attributes-modal-transition.md) + - [Sheet Transition](ts-universal-attributes-sheet-transition.md) + - [Sheet Transition (System API)](ts-universal-attributes-sheet-transition-sys.md) +- [Obscuring](ts-universal-attributes-obscured.md) +- [Universal Text Attributes](ts-universal-attributes-text-style.md) +- [Drag and Drop Control](ts-universal-attributes-drag-drop.md) +- [Safe Area](ts-universal-attributes-expand-safe-area.md) +- [Render Fit](ts-universal-attributes-renderfit.md) +- [Event Monopolization](ts-universal-attributes-monopolize-events.md) +- [Cursor Control](ts-universal-attributes-cursor.md) +- [Special Effect Drawing Combination](ts-universal-attributes-use-effect.md) +- [Point Light Style (System API)](ts-universal-attributes-point-light-style-sys.md) +- [Image Effect (System API)](ts-universal-attributes-image-effect-sys.md) + diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-component-general-events.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-component-general-events.md new file mode 100644 index 0000000000000000000000000000000000000000..dd8283bbe7664e4ba196a5b3fcd9fdb0f0fc7e48 --- /dev/null +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-component-general-events.md @@ -0,0 +1,21 @@ +# Universal Events + +- [Click Event](ts-universal-events-click.md) +- [Touch Event](ts-universal-events-touch.md) +- [Show/Hide Event](ts-universal-events-show-hide.md) +- [Drag/Drop Event](ts-universal-events-drag-drop.md) +- [Key Event](ts-universal-events-key.md) +- [Focus Event](ts-universal-focus-event.md) +- [Mouse Event](ts-universal-mouse-key.md) +- [Crown Event](ts-universal-events-crown.md) +- [Hover Event](ts-universal-events-hover.md) +- [Accessibility Hover Event](ts-universal-accessibility-hover-event.md) +- [Component Area Change Event](ts-universal-component-area-change-event.md) +- [Component Size Change Event](ts-universal-component-size-change-event.md) +- [Visible Area Change Event](ts-universal-component-visible-area-change-event.md) +- [Component Keyboard Shortcut Event](ts-universal-events-keyboardshortcut.md) +- [Custom Event Dispatch](ts-universal-attributes-on-child-touch-test.md) +- [Custom Event Interception](ts-universal-attributes-on-touch-intercept.md) +- [Focus Axis Event](ts-universal-events-focus_axis.md) +- [Axis Event](ts-universal-events-axis.md) + diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-components-canvas-canvas.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-components-canvas-canvas.md index 5a0f865fc86b2630646c669cf50a6990383e6191..e4b96f4bf0be22ac293107350791fa7b42a87b56 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-components-canvas-canvas.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-components-canvas-canvas.md @@ -45,12 +45,12 @@ Canvas(context: CanvasRenderingContext2D | DrawingRenderingContext, imageAIOptio ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### enableAnalyzer12+ Sets whether to enable the AI analyzer, which supports subject recognition, text recognition, and object lookup. -For the settings to take effect, this attribute must be used together with [StartImageAnalyzer](ts-canvasrenderingcontext2d.md#startimageanalyzer12) and [StopImageAnalyzer](ts-canvasrenderingcontext2d.md#stopimageanalyzer12) of [context](ts-canvasrenderingcontext2d.md). +For the settings to take effect, this attribute must be used together with [StartImageAnalyzer](ts-canvasrenderingcontext2d.md#startimageanalyzer12) and [StopImageAnalyzer](ts-canvasrenderingcontext2d.md#stopimageanalyzer12) of [CanvasRenderingContext2D](ts-canvasrenderingcontext2d.md#canvasrenderingcontext2d). This attribute cannot be used together with the [overlay](ts-universal-attributes-overlay.md#overlay) attribute. If they are set at the same time, the **CustomBuilder** attribute in **overlay** has no effect. This feature depends on device capabilities. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -65,21 +65,33 @@ This attribute cannot be used together with the [overlay](ts-universal-attribute ## Events +In addition to the [universal events](ts-component-general-events.md), the following events are supported. + +### onReady + +onReady(event: VoidCallback) + +Triggered when the **Canvas** component is initialized or when its size changes. + +When this event is triggered, the canvas is cleared. The width and height of the **Canvas** component are then determined and can be obtained, allowing you to use APIs related to the **Canvas** component for drawing. If only the position of the canvas changes, only the [onAreaChange](ts-universal-component-area-change-event.md#onAreaChange) event is triggered, not the **onReady** event. The [onAreaChange](ts-universal-component-area-change-event.md#onAreaChange) event is triggered after the **onReady** event. + **Widget capability**: This API can be used in ArkTS widgets since API version 9. **Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full -In addition to the [universal events](ts-universal-events-click.md), the following events are supported. +**Parameters** + +| Name| Type | Mandatory| Description| +| ------ | ------- | ---- | ------------------------------------------------------------ | +| event | [VoidCallback](ts-types.md#voidcallback12) | Yes | Callback event triggered when the **Canvas** component is initialized or when its size changes.| -| Name | Description | -| -------------------------- | ---------------------------------------- | -| onReady(event: () => void) | Triggered when a canvas is ready or its size changes. When this event is triggered, the canvas is cleared. The width and height of the canvas can then be obtained, and you can use the canvas APIs to draw images. If only the position of the canvas changes, only the [onAreaChange](ts-universal-component-area-change-event.md#onAreaChange) event is triggered, not the **onReady** event.
The [onAreaChange](ts-universal-component-area-change-event.md#onAreaChange) event is triggered after the **onReady** event.| +## Example -**Example** +### Example 1: Using APIs in CanvasRenderingContext2D -This example describes how to use the methods in **CanvasRenderingContext2D** for drawing on a canvas. +This example describes how to use the APIs in **CanvasRenderingContext2D** for drawing on a canvas. ```ts // xxx.ets @@ -106,8 +118,9 @@ struct CanvasExample { ``` ![en-us_image_0000001194032666](figures/en-us_image_0000001194032666.png) +### Example 2: Using APIs in DrawingRenderingContext -This example describes how to use the methods in **DrawingRenderingContext** for drawing on a canvas. +This example describes how to use the APIs in **DrawingRenderingContext** for drawing on a canvas. ```ts // xxx.ets diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-components-canvas-canvasgradient.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-components-canvas-canvasgradient.md index 33732e79cfb894fe33dd3b3fd3dbbadffd77895a..a6b5dbe581c91f20739ef2a88b10b5658f52c559 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-components-canvas-canvasgradient.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-components-canvas-canvasgradient.md @@ -22,13 +22,15 @@ Adds a color stop for the **CanvasGradient** object based on the specified offse **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | ------ | ------ | ---- | ---------------------------------------- | -| offset | number | Yes | Relative position of the gradient stop along the gradient vector. The value ranges from 0 to 1. | -| color | string | Yes | Gradient color to set. For details about the color notation, see the description of the string type in [ResourceColor](ts-types.md#resourcecolor). | +| offset | number | Yes | Relative position of the gradient stop along the gradient vector, represented by the ratio of the distance between the gradient stop and the start point to the total length. The value ranges from 0 to 1.
If the value of **offset** is less than 0 or greater than 1, there is no gradient effect. | +| color | string | Yes | Gradient color to set. For details about the color notation, see the description of the string type in [ResourceColor](ts-types.md#resourcecolor).
Invalid values result in no gradient effect being displayed.| -**Example** +## Example + +This example shows how to add a color stop using **addColorStop**. ```ts // xxx.ets diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-components-canvas-canvaspattern.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-components-canvas-canvaspattern.md index e97d3913e6eb1daa668a8811caa7938533ccd528..8a3364e3e374c99d42ef5072f4cf94f70728971d 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-components-canvas-canvaspattern.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-components-canvas-canvaspattern.md @@ -26,7 +26,9 @@ Uses a **Matrix2D** object as a parameter to perform matrix transformation on th | --------- | -------------- | ------ | ---------- | | transform | [Matrix2D](ts-components-canvas-matrix2d.md#Matrix2D) | No | Transformation matrix.
Default value: **null**| -**Example** +## Example + +This example demonstrates how to apply matrix transformations to a **CanvasPattern** object using the **setTransform** API. ```ts // xxx.ets @@ -37,7 +39,7 @@ struct CanvasPatternPage { private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private matrix: Matrix2D = new Matrix2D() private img: ImageBitmap = new ImageBitmap("common/pattern.jpg") - private pattern : CanvasPattern | null = null + private pattern: CanvasPattern | null = null build() { Column() { diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-components-canvas-imagebitmap.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-components-canvas-imagebitmap.md index 889bc78f96e312810356923da5a72887326636e9..0366fdeef4322bc2972d0df2381d9076f6a3ddc7 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-components-canvas-imagebitmap.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-components-canvas-imagebitmap.md @@ -76,7 +76,9 @@ Since API version 11, when an application creates a [worker thread](../../../ark ## Example -### Example 1 +### Example 1: Loading an Image + +This example demonstrates how to load a local image using the **ImageBitmap** object. ```ts // xxx.ets @@ -85,7 +87,7 @@ Since API version 11, when an application creates a [worker thread](../../../ark struct ImageExample { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private img:ImageBitmap = new ImageBitmap("common/images/example.jpg") + private img: ImageBitmap = new ImageBitmap("common/images/example.jpg") build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -106,9 +108,11 @@ Since API version 11, when an application creates a [worker thread](../../../ark ![en-us_image_0000001194352442](figures/en-us_image_0000001194352442.png) -### Example 2 +### Example 2: Creating an ImageBitmap Object - ```ts +This example shows how to create an **ImageBitmap** object using a **PixelMap** object. + +```ts // xxx.ets @Entry @Component @@ -135,14 +139,21 @@ struct Demo { .height('100%') } } - ``` +``` ![en-us_image_0000001194352442](figures/en-us_image_0000001194352444.png) -### Example 3 +### Example 3: Supporting Concurrent Thread Drawing + +This example demonstrates how to implement concurrent thread drawing by creating a Worker thread. + +> **NOTE** +> +> The content drawn in the Worker thread cannot be previewed in DevEco Studio Previewer. + ```ts -import worker from '@ohos.worker'; +import { worker } from '@kit.ArkTS'; @Entry @Component @@ -150,7 +161,7 @@ struct imageBitmapExamplePage { private settings: RenderingContextSettings = new RenderingContextSettings(true); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private myWorker = new worker.ThreadWorker('entry/ets/workers/Worker.ts'); - private img:ImageBitmap = new ImageBitmap("common/images/example.jpg") + private img: ImageBitmap = new ImageBitmap("common/images/example.jpg") build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -173,12 +184,12 @@ struct imageBitmapExamplePage { } } ``` -In the worker thread, the application uses **onmessage** to receive the **ImageBitmap** instance sent by the main thread through **postMessage **and proceeds with rendering. +In the worker thread, the application uses **onmessage** to receive the **ImageBitmap** object sent by the main thread through **postMessage** and proceeds with rendering. ```ts -workerPort.onmessage = function (e: MessageEvents) { +workerPort.onmessage = (e: MessageEvents) => { if (e.data.myImage) { - let img = e.data.myImage + let img: ImageBitmap = e.data.myImage let offCanvas = new OffscreenCanvas(600, 600) let offContext = offCanvas.getContext("2d") offContext.drawImage(img, 0, 0, 500, 500, 0, 0, 400, 200) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-components-canvas-matrix2d.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-components-canvas-matrix2d.md index fb15b8ba73b3771a327fb1565e0db0a27dc82bc3..027b8d5a46dc12a7958c7e0dfec9c81391faf881 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-components-canvas-matrix2d.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-components-canvas-matrix2d.md @@ -18,7 +18,7 @@ Matrix2D(unit?: LengthMetricsUnit) **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description | | ------ | -------- | ---- | ------------------------------------- | | unit12+ | [LengthMetricsUnit](../js-apis-arkui-graphics.md#lengthmetricsunit12) | No | Unit mode of the **Matrix2D** object. The value cannot be dynamically changed once set. The configuration method is the same as that of [CanvasRenderingContext2D](ts-canvasrenderingcontext2d.md#lengthmetricsunit12).
Default value: **DEFAULT**| @@ -30,228 +30,56 @@ Matrix2D(unit?: LengthMetricsUnit) **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Read Only | Optional | Description | +| Name| Type| Read Only| Optional | Description| | ----- | ----- | --------------- | ------ | ------------------------ | -| [scaleX](#scalex) | number | No | Yes | Horizontal scale factor. | -| [scaleY](#scaley) | number | No | Yes | Vertical scale factor. | -| [rotateX](#rotatex) | number | No | Yes | Horizontal tilt coefficient. | -| [rotateY](#rotatey) | number | No | Yes | Vertical tilt coefficient. | -| [translateX](#translatex) | number | No | Yes | Distance to translate on the x-axis.
Default unit: vp | -| [translateY](#translatey) | number | No | Yes | Distance to translate on the y-axis.
Default unit: vp | +| scaleX | number | No| Yes| Horizontal scale factor. | +| scaleY | number | No| Yes| Vertical scale factor. | +| rotateX | number | No| Yes| Horizontal tilt coefficient. | +| rotateY | number | No| Yes| Vertical tilt coefficient. | +| translateX | number | No| Yes| Distance to translate on the x-axis.
Default unit: vp.| +| translateY | number | No| Yes| Distance to translate on the y-axis.
Default unit: vp.| > **NOTE** > > You can use the [px2vp](ts-pixel-units.md#pixel-unit-conversion) API to convert the unit. -### scaleX - -```ts -// xxx.ets -@Entry -@Component -struct Matrix2DScaleX { - @State message: string = 'Matrix2D ScaleX' - - printMatrix(title: string, matrix: Matrix2D) { - console.log(title) - console.log("Matrix [scaleX = " + matrix.scaleX + ", scaleY = " + matrix.scaleY + - ", rotateX = " + matrix.rotateX + ", rotateY = " + matrix.rotateY + - ", translateX = " + matrix.translateX + ", translateY = " + matrix.translateY + "]") - } - build() { - Row() { - Column() { - Text(this.message) - .fontSize(20) - .fontWeight(FontWeight.Bold) - Button("Set scaleX") - .onClick(() => { - let matrix : Matrix2D = new Matrix2D() - matrix.scaleX = 1 - this.printMatrix(this.message, matrix) - }) - } - .width('100%') - } - .height('100%') - } -} -``` - -### scaleY - -```ts -// xxx.ets -@Entry -@Component -struct Matrix2DScaleY { - @State message: string = 'Matrix2D ScaleY' - - printMatrix(title: string, matrix: Matrix2D) { - console.log(title) - console.log("Matrix [scaleX = " + matrix.scaleX + ", scaleY = " + matrix.scaleY + - ", rotateX = " + matrix.rotateX + ", rotateY = " + matrix.rotateY + - ", translateX = " + matrix.translateX + ", translateY = " + matrix.translateY + "]") - } - build() { - Row() { - Column() { - Text(this.message) - .fontSize(20) - .fontWeight(FontWeight.Bold) - Button("Set scaleY") - .onClick(() => { - let matrix : Matrix2D = new Matrix2D() - matrix.scaleY = 1 - this.printMatrix(this.message, matrix) - }) - } - .width('100%') - } - .height('100%') - } -} -``` - -### rotateX +**Example** ```ts // xxx.ets @Entry @Component -struct Matrix2DRotateX { - @State message: string = 'Matrix2D RotateX' - - printMatrix(title: string, matrix: Matrix2D) { - console.log(title) - console.log("Matrix [scaleX = " + matrix.scaleX + ", scaleY = " + matrix.scaleY + - ", rotateX = " + matrix.rotateX + ", rotateY = " + matrix.rotateY + - ", translateX = " + matrix.translateX + ", translateY = " + matrix.translateY + "]") - } - build() { - Row() { - Column() { - Text(this.message) - .fontSize(20) - .fontWeight(FontWeight.Bold) - Button("Set rotateX") - .onClick(() => { - let matrix : Matrix2D = new Matrix2D() - matrix.rotateX = Math.sin(45 / Math.PI) - this.printMatrix(this.message, matrix) - }) - } - .width('100%') - } - .height('100%') - } -} -``` - -### rotateY +struct Parameter { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + private matrix: Matrix2D = new Matrix2D() -```ts -// xxx.ets -@Entry -@Component -struct Matrix2DRotateY { - @State message: string = 'Matrix2D RotateY' - - printMatrix(title: string, matrix: Matrix2D) { - console.log(title) - console.log("Matrix [scaleX = " + matrix.scaleX + ", scaleY = " + matrix.scaleY + - ", rotateX = " + matrix.rotateX + ", rotateY = " + matrix.rotateY + - ", translateX = " + matrix.translateX + ", translateY = " + matrix.translateY + "]") - } build() { - Row() { - Column() { - Text(this.message) - .fontSize(20) - .fontWeight(FontWeight.Bold) - Button("Set rotateY") - .onClick(() => { - let matrix : Matrix2D = new Matrix2D() - matrix.rotateY = Math.cos(45 / Math.PI) - this.printMatrix(this.message, matrix) - }) - } - .width('100%') + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('240vp') + .height('180vp') + .backgroundColor('#ffff00') + .onReady(() => { + this.context.fillRect(100, 20, 50, 50) + this.matrix.scaleX = 1 + this.matrix.scaleY = 1 + this.matrix.rotateX = -0.5 + this.matrix.rotateY = 0.5 + this.matrix.translateX = 10 + this.matrix.translateY = 10 + this.context.setTransform(this.matrix) + this.context.fillRect(100, 20, 50, 50) + }) } + .width('100%') .height('100%') } } ``` -### translateX +![matrix-parameters.png](figures/matrix-parameters.png) -```ts -// xxx.ets -@Entry -@Component -struct Matrix2DTranslateX { - @State message: string = 'Matrix2D TranslateX' - - printMatrix(title: string, matrix: Matrix2D) { - console.log(title) - console.log("Matrix [scaleX = " + matrix.scaleX + ", scaleY = " + matrix.scaleY + - ", rotateX = " + matrix.rotateX + ", rotateY = " + matrix.rotateY + - ", translateX = " + matrix.translateX + ", translateY = " + matrix.translateY + "]") - } - build() { - Row() { - Column() { - Text(this.message) - .fontSize(20) - .fontWeight(FontWeight.Bold) - Button("Set translateX") - .onClick(() => { - let matrix : Matrix2D = new Matrix2D() - matrix.translateX = 10 - this.printMatrix(this.message, matrix) - }) - } - .width('100%') - } - .height('100%') - } -} -``` - -### translateY - -```ts -// xxx.ets -@Entry -@Component -struct Matrix2DTranslateY { - @State message: string = 'Matrix2D TranslateY' - - printMatrix(title: string, matrix: Matrix2D) { - console.log(title) - console.log("Matrix [scaleX = " + matrix.scaleX + ", scaleY = " + matrix.scaleY + - ", rotateX = " + matrix.rotateX + ", rotateY = " + matrix.rotateY + - ", translateX = " + matrix.translateX + ", translateY = " + matrix.translateY + "]") - } - build() { - Row() { - Column() { - Text(this.message) - .fontSize(20) - .fontWeight(FontWeight.Bold) - Button("Set translateY") - .onClick(() => { - let matrix : Matrix2D = new Matrix2D() - matrix.translateY = 10 - this.printMatrix(this.message, matrix) - }) - } - .width('100%') - } - .height('100%') - } -} -``` ## Methods @@ -271,7 +99,7 @@ Creates an identity matrix. | Type | Description | | --------------------- | ---------- | -| [Matrix2D](#matrix2d) | Identity matrix. | +| [Matrix2D](#matrix2d) | Identity matrix.| **Example** @@ -279,35 +107,33 @@ Creates an identity matrix. // xxx.ets @Entry @Component -struct Matrix2DIdentity { - @State message: string = 'Matrix2D Identity' - - printMatrix(title: string, matrix: Matrix2D) { - console.log(title) - console.log("Matrix [scaleX = " + matrix.scaleX + ", scaleY = " + matrix.scaleY + - ", rotateX = " + matrix.rotateX + ", rotateY = " + matrix.rotateY + - ", translateX = " + matrix.translateX + ", translateY = " + matrix.translateY + "]") - } +struct Identity { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + private matrix: Matrix2D = new Matrix2D() + build() { - Row() { - Column() { - Text(this.message) - .fontSize(20) - .fontWeight(FontWeight.Bold) - Button("matrix identity") - .onClick(() => { - let matrix : Matrix2D = new Matrix2D() - matrix = matrix.identity() - this.printMatrix(this.message, matrix) - }) - } - .width('100%') + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('240vp') + .height('180vp') + .backgroundColor('#ffff00') + .onReady(() => { + this.context.fillRect(100, 20, 50, 50) + this.matrix = this.matrix.identity() + this.context.setTransform(this.matrix) + this.context.fillRect(100, 100, 50, 50) + }) } + .width('100%') .height('100%') } } ``` +![matrix-identity.png](figures/matrix-identity.png) + + ### invert invert(): Matrix2D @@ -324,7 +150,7 @@ Obtains an inverse of this matrix. | Type | Description | | --------------------- | ------------ | -| [Matrix2D](#matrix2d) | Inverse of the current matrix. | +| [Matrix2D](#matrix2d) | Inverse of the current matrix.| **Example** @@ -332,41 +158,39 @@ Obtains an inverse of this matrix. // xxx.ets @Entry @Component -struct Matrix2DInvert { - @State message: string = 'Matrix2D Invert' - - printMatrix(title: string, matrix: Matrix2D) { - console.log(title) - console.log("Matrix [scaleX = " + matrix.scaleX + ", scaleY = " + matrix.scaleY + - ", rotateX = " + matrix.rotateX + ", rotateY = " + matrix.rotateY + - ", translateX = " + matrix.translateX + ", translateY = " + matrix.translateY + "]") - } +struct Invert { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + private matrix: Matrix2D = new Matrix2D() + build() { - Row() { - Column() { - Text(this.message) - .fontSize(20) - .fontWeight(FontWeight.Bold) - Button("matrix invert") - .onClick(() => { - let matrix : Matrix2D = new Matrix2D() - matrix.scaleX = 2 - matrix.scaleY = 1 - matrix.rotateX = 0 - matrix.rotateY = 0 - matrix.translateX = 10 - matrix.translateY = 20 - matrix.invert() - this.printMatrix(this.message, matrix) - }) - } - .width('100%') + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('240vp') + .height('180vp') + .backgroundColor('#ffff00') + .onReady(() => { + this.context.fillRect(100, 110, 50, 50) + this.matrix.scaleX = 1 + this.matrix.scaleY = 1 + this.matrix.rotateX = -0.5 + this.matrix.rotateY = 0.5 + this.matrix.translateX = 10 + this.matrix.translateY = 10 + this.matrix.invert() + this.context.setTransform(this.matrix) + this.context.fillRect(100, 110, 50, 50) + }) } + .width('100%') .height('100%') } } ``` +![matrix-invert.png](figures/matrix-invert.png) + + ### multiply(deprecated) multiply(other?: Matrix2D): Matrix2D @@ -375,67 +199,19 @@ Multiplies this matrix by the target matrix. **Widget capability**: This API can be used in ArkTS widgets since API version 9. This API is an empty API. -This API is deprecated since API version 10. +This API is deprecated since API version 10, and does not provide any actual rendering effects. Therefore, no examples are provided. **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ----- | -------- | ---- | ---------- | -| other | Matrix2D | No | Target matrix.
Default value: **null** | +| other | Matrix2D | No| Target matrix.
Default value: **null**| **Return value** | Type | Description | | --------------------- | -------------- | -| [Matrix2D](#matrix2d) | Matrix of the multiplication result. | - -**Example** - -```ts -// xxx.ets -@Entry -@Component -struct Matrix2DMultiply { - @State message: string = 'Matrix2D Multiply' - - printMatrix(title: string, matrix: Matrix2D) { - console.log(title) - console.log("Matrix [scaleX = " + matrix.scaleX + ", scaleY = " + matrix.scaleY + - ", rotateX = " + matrix.rotateX + ", rotateY = " + matrix.rotateY + - ", translateX = " + matrix.translateX + ", translateY = " + matrix.translateY + "]") - } - build() { - Row() { - Column() { - Text(this.message) - .fontSize(20) - .fontWeight(FontWeight.Bold) - Button("matrix multiply") - .onClick(() => { - let matrix : Matrix2D = new Matrix2D() - matrix.scaleX = 1 - matrix.scaleY = 1 - matrix.rotateX = 0 - matrix.rotateY = 0 - matrix.translateX = 0 - matrix.translateY = 0 - let other: Matrix2D = new Matrix2D() - other.scaleX = 2 - other.scaleY = 2 - other.rotateX = 0 - other.rotateY = 0 - other.translateX = 10 - other.translateY = 10 - other.multiply(other) - this.printMatrix(this.message, matrix) - }) - } - .width('100%') - } - .height('100%') - } -} -``` +| [Matrix2D](#matrix2d) | Matrix of the multiplication result.| ### rotate(deprecated) @@ -449,16 +225,16 @@ This API is deprecated since API version 10. You are advised to use [rotate](#ro **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type | Mandatory| Description | | ---- | ------ | ---- | -------------------------------- | -| rx | number | No | Horizontal coordinate of the rotation point.
Default unit: vp
Default value: **0** | -| ry | number | No | Vertical coordinate of the rotation point.
Default unit: vp
Default value: **0** | +| rx | number | No | Horizontal coordinate of the rotation point.
Default unit: vp.| +| ry | number | No | Vertical coordinate of the rotation point.
Default unit: vp.| **Return value** | Type | Description | | --------------------- | -------------------- | -| [Matrix2D](#matrix2d) | Matrix of the rotation result. | +| [Matrix2D](#matrix2d) | Matrix of the rotation result.| **Example** @@ -466,41 +242,39 @@ This API is deprecated since API version 10. You are advised to use [rotate](#ro // xxx.ets @Entry @Component -struct Matrix2DRotate { - @State message: string = 'Matrix2D Rotate' - - printMatrix(title: string, matrix: Matrix2D) { - console.log(title) - console.log("Matrix [scaleX = " + matrix.scaleX + ", scaleY = " + matrix.scaleY + - ", rotateX = " + matrix.rotateX + ", rotateY = " + matrix.rotateY + - ", translateX = " + matrix.translateX + ", translateY = " + matrix.translateY + "]") - } +struct Rotate { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + private matrix: Matrix2D = new Matrix2D() + build() { - Row() { - Column() { - Text(this.message) - .fontSize(20) - .fontWeight(FontWeight.Bold) - Button("matrix rotate") - .onClick(() => { - let matrix : Matrix2D = new Matrix2D() - matrix.scaleX = 1 - matrix.scaleY = 1 - matrix.rotateX = 0 - matrix.rotateY = 0 - matrix.translateX = 0 - matrix.translateY = 0 - matrix.rotate(10, 10) - this.printMatrix(this.message, matrix) - }) - } - .width('100%') + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('240vp') + .height('180vp') + .backgroundColor('#ffff00') + .onReady(() => { + this.context.fillRect(50, 110, 50, 50) + this.matrix.scaleX = 1 + this.matrix.scaleY = 1 + this.matrix.rotateX = -0.5 + this.matrix.rotateY = 0.5 + this.matrix.translateX = 10 + this.matrix.translateY = 10 + this.matrix.rotate(5, 5) + this.context.setTransform(this.matrix) + this.context.fillRect(50, 110, 50, 50) + }) } + .width('100%') .height('100%') } } ``` +![matrix-rotate.png](figures/matrix-rotate.png) + + ### rotate10+ rotate(degree: number, rx?: number, ry?: number): Matrix2D @@ -515,17 +289,17 @@ Performs a right multiplication rotation operation on this matrix, with the spec **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| degree | number | Yes | Rotation angle, in radians. A positive angle denotes a clockwise rotation. You can use **Math.PI& / 180** to convert the angle to a radian value.
Default value: **0**| -| rx | number | No | Horizontal coordinate of the rotation point.
Default unit: vp
Default value: **0** | -| ry | number | No | Vertical coordinate of the rotation point.
Default unit: vp
Default value: **0** | +| degree | number | Yes | Rotation angle. Positive angles represent clockwise rotation. You can convert the angle to radians using the following formula: degree * Math.PI/180.
Default unit: radian.| +| rx | number | No | Horizontal coordinate of the rotation point.
Default unit: vp.
Default value: **0** | +| ry | number | No | Vertical coordinate of the rotation point.
Default unit: vp.
Default value: **0** | **Return value** | Type | Description | | --------------------- | -------------------- | -| [Matrix2D](#matrix2d) | Matrix of the rotation result. | +| [Matrix2D](#matrix2d) | Matrix of the rotation result.| **Example** @@ -533,41 +307,39 @@ Performs a right multiplication rotation operation on this matrix, with the spec // xxx.ets @Entry @Component -struct Matrix2DRotate { - @State message: string = 'Matrix2D Rotate' - - printMatrix(title: string, matrix: Matrix2D) { - console.log(title) - console.log("Matrix [scaleX = " + matrix.scaleX + ", scaleY = " + matrix.scaleY + - ", rotateX = " + matrix.rotateX + ", rotateY = " + matrix.rotateY + - ", translateX = " + matrix.translateX + ", translateY = " + matrix.translateY + "]") - } +struct Rotate { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + private matrix: Matrix2D = new Matrix2D() + build() { - Row() { - Column() { - Text(this.message) - .fontSize(20) - .fontWeight(FontWeight.Bold) - Button("matrix rotate") - .onClick(() => { - let matrix : Matrix2D = new Matrix2D() - matrix.scaleX = 1 - matrix.scaleY = 1 - matrix.rotateX = 0 - matrix.rotateY = 0 - matrix.translateX = 0 - matrix.translateY = 0 - matrix.rotate(90 / Math.PI, 10, 10) - this.printMatrix(this.message, matrix) - }) - } - .width('100%') + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('240vp') + .height('180vp') + .backgroundColor('#ffff00') + .onReady(() => { + this.context.fillRect(60, 80, 50, 50) + this.matrix.scaleX = 1 + this.matrix.scaleY = 1 + this.matrix.rotateX = -0.5 + this.matrix.rotateY = 0.5 + this.matrix.translateX = 10 + this.matrix.translateY = 10 + this.matrix.rotate(-60 * Math.PI / 180, 5, 5) + this.context.setTransform(this.matrix) + this.context.fillRect(60, 80, 50, 50) + }) } + .width('100%') .height('100%') } } ``` +![matrix-rotate10+.png](figures/matrix-rotate10+.png) + + ### translate translate(tx?: number, ty?: number): Matrix2D @@ -582,16 +354,16 @@ Performs a left multiplication translation operation on this matrix. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type | Mandatory| Description | | ---- | ------ | ---- | ---------------------------- | -| tx | number | No | Distance to translate on the x-axis.
Default unit: vp
Default value: **0** | -| ty | number | No | Distance to translate on the y-axis.
Default unit: vp
Default value: **0** | +| tx | number | No | Distance to translate on the X axis.
Default unit: vp.
Default value: **0**| +| ty | number | No | Distance to translate on the Y axis.
Default unit: vp.
Default value: **0**| **Return value** | Type | Description | | --------------------- | -------------------- | -| [Matrix2D](#matrix2d) | Matrix of the translation result. | +| [Matrix2D](#matrix2d) | Matrix of the translation result.| **Example** @@ -599,41 +371,39 @@ Performs a left multiplication translation operation on this matrix. // xxx.ets @Entry @Component -struct Matrix2DTranslate { - @State message: string = 'Matrix2D Translate' - - printMatrix(title: string, matrix: Matrix2D) { - console.log(title) - console.log("Matrix [scaleX = " + matrix.scaleX + ", scaleY = " + matrix.scaleY + - ", rotateX = " + matrix.rotateX + ", rotateY = " + matrix.rotateY + - ", translateX = " + matrix.translateX + ", translateY = " + matrix.translateY + "]") - } +struct Translate { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + private matrix: Matrix2D = new Matrix2D() + build() { - Row() { - Column() { - Text(this.message) - .fontSize(20) - .fontWeight(FontWeight.Bold) - Button("matrix translate") - .onClick(() => { - let matrix : Matrix2D = new Matrix2D() - matrix.scaleX = 1 - matrix.scaleY = 1 - matrix.rotateX = 0 - matrix.rotateY = 0 - matrix.translateX = 0 - matrix.translateY = 0 - matrix.translate(100, 100) - this.printMatrix(this.message, matrix) - }) - } - .width('100%') + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('240vp') + .height('180vp') + .backgroundColor('#ffff00') + .onReady(() => { + this.context.fillRect(40, 20, 50, 50) + this.matrix.scaleX = 1 + this.matrix.scaleY = 1 + this.matrix.rotateX = 0 + this.matrix.rotateY = 0 + this.matrix.translateX = 0 + this.matrix.translateY = 0 + this.matrix.translate(100, 100) + this.context.setTransform(this.matrix) + this.context.fillRect(40, 20, 50, 50) + }) } + .width('100%') .height('100%') } } ``` +![matrix-translate.png](figures/matrix-translate.png) + + ### scale scale(sx?: number, sy?: number): Matrix2D @@ -648,16 +418,16 @@ Performs a right multiplication scaling operation on this matrix. **Parameters** -| Name | Type | Mandatory | Description | +| Parameter| Type | Mandatory| Description | | ---- | ------ | ---- | ------------------ | -| sx | number | No | Horizontal scale factor.
Default value: **1** | -| sy | number | No | Vertical scale factor.
Default value: **1** | +| sx | number | No | Horizontal scale factor.
Default value: **1.0**.| +| sy | number | No | Vertical scale factor.
Default value: **1.0**.| **Return value** | Type | Description | | --------------------- | ------------------ | -| [Matrix2D](#matrix2d) | Matrix of the scale result. | +| [Matrix2D](#matrix2d) | Matrix of the scale result.| **Example** @@ -665,37 +435,34 @@ Performs a right multiplication scaling operation on this matrix. // xxx.ets @Entry @Component -struct Matrix2DScale { - @State message: string = 'Matrix2D Scale' - - printMatrix(title: string, matrix: Matrix2D) { - console.log(title) - console.log("Matrix [scaleX = " + matrix.scaleX + ", scaleY = " + matrix.scaleY + - ", rotateX = " + matrix.rotateX + ", rotateY = " + matrix.rotateY + - ", translateX = " + matrix.translateX + ", translateY = " + matrix.translateY + "]") - } +struct Scale { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + private matrix: Matrix2D = new Matrix2D() + build() { - Row() { - Column() { - Text(this.message) - .fontSize(20) - .fontWeight(FontWeight.Bold) - Button("matrix scale") - .onClick(() => { - let matrix : Matrix2D = new Matrix2D() - matrix.scaleX = 1 - matrix.scaleY = 1 - matrix.rotateX = 0 - matrix.rotateY = 0 - matrix.translateX = 0 - matrix.translateY = 0 - matrix.scale(0.5, 0.5) - this.printMatrix(this.message, matrix) - }) - } - .width('100%') + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('240vp') + .height('180vp') + .backgroundColor('#ffff00') + .onReady(() => { + this.context.fillRect(120, 70, 50, 50) + this.matrix.scaleX = 1 + this.matrix.scaleY = 1 + this.matrix.rotateX = -0.5 + this.matrix.rotateY = 0.5 + this.matrix.translateX = 10 + this.matrix.translateY = 10 + this.matrix.scale(0.5, 0.5) + this.context.setTransform(this.matrix) + this.context.fillRect(120, 70, 50, 50) + }) } + .width('100%') .height('100%') } } ``` + +![matrix-scale.png](figures/matrix-scale.png) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-components-canvas-path2d.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-components-canvas-path2d.md index 8d189ae00cd64887fda485e3b5e469ae45172ddf..74dee769210350d1c5c71acf2e612c4b12bdfa0f 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-components-canvas-path2d.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-components-canvas-path2d.md @@ -20,9 +20,9 @@ Constructs an empty **Path2D** object. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ------ | -------- | ---- | ------ | ----- | -| unit12+ | [LengthMetricsUnit](../js-apis-arkui-graphics.md#lengthmetricsunit12) | No | DEFAULT | Unit mode of the **Path2D** object. The value cannot be dynamically changed once set. The configuration method is the same as that of [CanvasRenderingContext2D](ts-canvasrenderingcontext2d.md#lengthmetricsunit12).| +| Name | Type | Mandatory| Description | +| ----- | -------- | ---- | ---------- | +| unit12+ | [LengthMetricsUnit](../js-apis-arkui-graphics.md#lengthmetricsunit12) | No| Unit mode of the **Path2D** object. The value cannot be dynamically changed once set. The configuration method is the same as that of [CanvasRenderingContext2D](ts-canvasrenderingcontext2d.md#lengthmetricsunit12).
Default value: **DEFAULT**| Path2D(description: string, unit?: LengthMetricsUnit) @@ -36,10 +36,10 @@ Constructs a **Path2D** object using a path that complies with the SVG path spec **Parameters** -| Name | Type | Mandatory | Description | -| ------ | -------- | ---- | ----- | -| description | string | Yes | Path that complies with the SVG path specifications. | -| unit12+ | [LengthMetricsUnit](../js-apis-arkui-graphics.md#lengthmetricsunit12) | No | Unit mode of the **Path2D** object. The value cannot be dynamically changed once set. The configuration method is the same as that of [CanvasRenderingContext2D](ts-canvasrenderingcontext2d.md#lengthmetricsunit12).
Default value: **DEFAULT**| +| Name | Type | Mandatory| Description | +| ----- | -------- | ---- | ---------- | +| description | string | Yes| Path that complies with the [SVG path syntax](ts-drawing-components-path.md#svg-path-syntax).| +| unit12+ | [LengthMetricsUnit](../js-apis-arkui-graphics.md#lengthmetricsunit12) | No| Unit mode of the **Path2D** object. The value cannot be dynamically changed once set. The configuration method is the same as that of [CanvasRenderingContext2D](ts-canvasrenderingcontext2d.md#lengthmetricsunit12).
Default value: **DEFAULT**| ## addPath @@ -55,10 +55,10 @@ Adds a path to this path. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| --------- | -------- | ---- | ---- | --------------- | -| path | [Path2D](ts-components-canvas-path2d.md) | Yes | - | Path to be added to this path. Unit: px. | -| transform | [Matrix2D](ts-components-canvas-matrix2d.md) | No | null | Transformation matrix of the new path. | +| Name | Type | Mandatory| Description | +| ----- | -------- | ---- | ---------- | +| path | [Path2D](ts-components-canvas-path2d.md) | Yes| Path to be added to this path. Unit: px.| +| transform | [Matrix2D](ts-components-canvas-matrix2d.md) | No| Transformation matrix of the new path.
Default value: **null**.| **Example** @@ -70,17 +70,16 @@ Adds a path to this path. struct AddPath { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private path2Da: Path2D = new Path2D("M250 150 L150 350 L350 350 Z") private path2Db: Path2D = new Path2D() - + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) .width('100%') .height('100%') .backgroundColor('#ffff00') - .onReady(() =>{ + .onReady(() => { this.path2Db.addPath(this.path2Da) this.context.stroke(this.path2Db) }) @@ -123,7 +122,7 @@ Moves the current point of the path back to the start point of the path, and dra .width('100%') .height('100%') .backgroundColor('#ffff00') - .onReady(() =>{ + .onReady(() => { this.path2Db.moveTo(200, 100) this.path2Db.lineTo(300, 100) this.path2Db.lineTo(200, 200) @@ -154,10 +153,10 @@ Moves the current coordinate point of the path to the target point, without draw **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ---- | ------ | ---- | ---- | -------- | -| x | number | Yes | 0 | X coordinate of the target point.
Default unit: vp | -| y | number | Yes | 0 | Y coordinate of the target point.
Default unit: vp | +| Name | Type | Mandatory| Description | +| ---- | ------ | ---- | -------- | +| x | number | Yes| X coordinate of the target point.
Default unit: vp.| +| y | number | Yes| Y coordinate of the target point.
Default unit: vp.| **Example** @@ -176,7 +175,7 @@ Moves the current coordinate point of the path to the target point, without draw .width('100%') .height('100%') .backgroundColor('#ffff00') - .onReady(() =>{ + .onReady(() => { this.path2Db.moveTo(50, 100) this.path2Db.lineTo(250, 100) this.path2Db.lineTo(150, 200) @@ -207,10 +206,10 @@ Draws a straight line from the current point to the target point. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ---- | ------ | ---- | ---- | -------- | -| x | number | Yes | 0 | X coordinate of the target point.
Default unit: vp | -| y | number | Yes | 0 | Y coordinate of the target point.
Default unit: vp | +| Name | Type | Mandatory| Description | +| ----- | -------- | ---- | ---------- | +| x | number | Yes| X coordinate of the target point.
Default unit: vp.| +| y | number | Yes| Y coordinate of the target point.
Default unit: vp.| **Example** @@ -229,7 +228,7 @@ Draws a straight line from the current point to the target point. .width('100%') .height('100%') .backgroundColor('#ffff00') - .onReady(() =>{ + .onReady(() => { this.path2Db.moveTo(100, 100) this.path2Db.lineTo(100, 200) this.path2Db.lineTo(200, 200) @@ -261,14 +260,14 @@ Draws a cubic Bezier curve on the canvas. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ---- | ------ | ---- | ---- | -------------- | -| cp1x | number | Yes | 0 | X coordinate of the first parameter of the bezier curve.
Default unit: vp | -| cp1y | number | Yes | 0 | Y coordinate of the first parameter of the bezier curve.
Default unit: vp | -| cp2x | number | Yes | 0 | X coordinate of the second parameter of the bezier curve.
Default unit: vp | -| cp2y | number | Yes | 0 | Y coordinate of the second parameter of the bezier curve.
Default unit: vp | -| x | number | Yes | 0 | X coordinate of the end point on the bezier curve.
Default unit: vp | -| y | number | Yes | 0 | Y coordinate of the end point on the bezier curve.
Default unit: vp | +| Name | Type | Mandatory| Description | +| ----- | -------- | ---- | ---------- | +| cp1x | number | Yes| X coordinate of the first parameter of the bezier curve.
Default unit: vp.| +| cp1y | number | Yes| Y coordinate of the first parameter of the bezier curve.
Default unit: vp.| +| cp2x | number | Yes| X coordinate of the second parameter of the bezier curve.
Default unit: vp.| +| cp2y | number | Yes| Y coordinate of the second parameter of the bezier curve.
Default unit: vp.| +| x | number | Yes| X coordinate of the end point on the bezier curve.
Default unit: vp. | +| y | number | Yes| Y coordinate of the end point on the bezier curve.
Default unit: vp. | **Example** @@ -287,7 +286,7 @@ Draws a cubic Bezier curve on the canvas. .width('100%') .height('100%') .backgroundColor('#ffff00') - .onReady(() =>{ + .onReady(() => { this.path2Db.moveTo(10, 10) this.path2Db.bezierCurveTo(20, 100, 200, 100, 200, 20) this.context.stroke(this.path2Db) @@ -316,12 +315,12 @@ Draws a quadratic curve on the canvas. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ---- | ------ | ---- | ---- | ----------- | -| cpx | number | Yes | 0 | X coordinate of the bezier curve parameter.
Default unit: vp | -| cpy | number | Yes | 0 | Y coordinate of the bezier curve parameter.
Default unit: vp | -| x | number | Yes | 0 | X coordinate of the end point on the bezier curve.
Default unit: vp | -| y | number | Yes | 0 | Y coordinate of the end point on the bezier curve.
Default unit: vp | +| Name | Type | Mandatory| Description | +| ----- | -------- | ---- | ---------- | +| cpx | number | Yes| X coordinate of the bezier curve parameter.
Default unit: vp.| +| cpy | number | Yes| Y coordinate of the bezier curve parameter.
Default unit: vp.| +| x | number | Yes| X coordinate of the end point on the bezier curve.
Default unit: vp.| +| y | number | Yes| Y coordinate of the end point on the bezier curve.
Default unit: vp.| **Example** @@ -340,7 +339,7 @@ Draws a quadratic curve on the canvas. .width('100%') .height('100%') .backgroundColor('#ffff00') - .onReady(() =>{ + .onReady(() => { this.path2Db.moveTo(10, 10) this.path2Db.quadraticCurveTo(100, 100, 200, 20) this.context.stroke(this.path2Db) @@ -369,14 +368,14 @@ Draws an arc on the canvas. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ---------------- | ------- | ---- | ----- | ---------- | -| x | number | Yes | 0 | X coordinate of the center point of the arc.
Default unit: vp | -| y | number | Yes | 0 | Y coordinate of the center point of the arc.
Default unit: vp | -| radius | number | Yes | 0 | Radius of the arc.
Default unit: vp | -| startAngle | number | Yes | 0 | Start radian of the arc. | -| endAngle | number | Yes | 0 | End radian of the arc. | -| counterclockwise | boolean | No | false | Whether to draw the arc counterclockwise. | +| Name | Type | Mandatory| Description | +| ----- | -------- | ---- | ---------- | +| x | number | Yes| X coordinate of the center point of the arc.
Default unit: vp.| +| y | number | Yes| Y coordinate of the center point of the arc.
Default unit: vp.| +| radius | number | Yes| Radius of the arc.
Default unit: vp. | +| startAngle | number | Yes| Start radian of the arc.
Unit: radian. | +| endAngle | number | Yes| End radian of the arc.
Unit: radian. | +| counterclockwise | boolean | No| Whether to draw the arc counterclockwise.
**true**: Draw the ellipse counterclockwise.
**false**: Draw the ellipse clockwise.
Default value: **false**.| **Example** @@ -395,7 +394,7 @@ Draws an arc on the canvas. .width('100%') .height('100%') .backgroundColor('#ffff00') - .onReady(() =>{ + .onReady(() => { this.path2Db.arc(100, 75, 50, 0, 6.28) this.context.stroke(this.path2Db) }) @@ -423,13 +422,13 @@ Draws an arc based on the radius and points on the arc. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ------ | ------ | ---- | ---- | --------------- | -| x1 | number | Yes | 0 | X coordinate of the first point on the arc.
Default unit: vp | -| y1 | number | Yes | 0 | Y coordinate of the first point on the arc.
Default unit: vp | -| x2 | number | Yes | 0 | X coordinate of the second point on the arc.
Default unit: vp | -| y2 | number | Yes | 0 | Y coordinate of the second point on the arc.
Default unit: vp | -| radius | number | Yes | 0 | Radius of the arc.
Default unit: vp | +| Name | Type | Mandatory| Description | +| ----- | -------- | ---- | ---------- | +| x1 | number | Yes| X coordinate of the first point on the arc.
Default unit: vp.| +| y1 | number | Yes| Y coordinate of the first point on the arc.
Default unit: vp.| +| x2 | number | Yes| X coordinate of the second point on the arc.
Default unit: vp.| +| y2 | number | Yes| Y coordinate of the second point on the arc.
Default unit: vp.| +| radius | number | Yes| Radius of the arc.
Default unit: vp.| **Example** @@ -448,7 +447,7 @@ Draws an arc based on the radius and points on the arc. .width('100%') .height('100%') .backgroundColor('#ffff00') - .onReady(() =>{ + .onReady(() => { this.path2Db.arcTo(150, 20, 150, 70, 50) this.context.stroke(this.path2Db) }) @@ -476,16 +475,16 @@ Draws an ellipse in the specified rectangular region on the canvas. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ---------------- | ------- | ---- | ----- | ---------------------------------------- | -| x | number | Yes | 0 | X coordinate of the ellipse center.
Default unit: vp| -| y | number | Yes | 0 | Y coordinate of the ellipse center.
Default unit: vp| -| radiusX | number | Yes | 0 | Radius of the ellipse on the x-axis.
Default unit: vp| -| radiusY | number | Yes | 0 | Radius of the ellipse on the y-axis.
Default unit: vp| -| rotation | number | Yes | 0 | Rotation angle of the ellipse.
Unit: radian | -| startAngle | number | Yes | 0 | Angle of the start point for drawing the ellipse, in radians. | -| endAngle | number | Yes | 0 | Angle of the end point for drawing the ellipse, in radians. | -| counterclockwise | boolean | No | false | Whether to draw the ellipse counterclockwise.
**true**: Draw the ellipse counterclockwise.
**false**: Draw the ellipse clockwise. | +| Name | Type | Mandatory| Description | +| ----- | -------- | ---- | ---------- | +| x | number | Yes | X coordinate of the ellipse center.
Default unit: vp.| +| y | number | Yes | Y coordinate of the ellipse center.
Default unit: vp.| +| radiusX | number | Yes | Radius of the ellipse on the x-axis.
Default unit: vp.| +| radiusY | number | Yes | Radius of the ellipse on the y-axis.
Default unit: vp.| +| rotation | number | Yes | Rotation angle of the ellipse.
Unit: radian. | +| startAngle | number | Yes | Angle of the start point for drawing the ellipse.
Unit: radian. | +| endAngle | number | Yes | Angle of the end point for drawing the ellipse.
Unit: radian. | +| counterclockwise | boolean | No | Whether to draw the ellipse counterclockwise.
**true**: Draw the ellipse counterclockwise.
**false**: Draw the ellipse clockwise.
Default value: **false**.| **Example** @@ -504,8 +503,8 @@ Draws an ellipse in the specified rectangular region on the canvas. .width('100%') .height('100%') .backgroundColor('#ffff00') - .onReady(() =>{ - this.path2Db.ellipse(200, 200, 50, 100, 0, Math.PI * 1, Math.PI*2) + .onReady(() => { + this.path2Db.ellipse(200, 200, 50, 100, 0, Math.PI * 1, Math.PI * 2) this.context.stroke(this.path2Db) }) } @@ -532,12 +531,12 @@ Creates a rectangle on the canvas. **Parameters** -| Name | Type | Mandatory | Default Value | Description | -| ---- | ------ | ---- | ---- | ------------- | -| x | number | Yes | 0 | X coordinate of the upper left corner of the rectangle.
Default unit: vp | -| y | number | Yes | 0 | Y coordinate of the upper left corner of the rectangle.
Default unit: vp | -| w | number | Yes | 0 | Width of the rectangle.
Default unit: vp | -| h | number | Yes | 0 | Height of the rectangle.
Default unit: vp | +| Name | Type | Mandatory| Description | +| ----- | -------- | ---- | ---------- | +| x | number | Yes| X coordinate of the upper left corner of the rectangle.
Default unit: vp.| +| y | number | Yes| Y coordinate of the upper left corner of the rectangle.
Default unit: vp.| +| w | number | Yes| Width of the rectangle.
Default unit: vp.| +| h | number | Yes| Height of the rectangle.
Default unit: vp.| **Example** @@ -556,7 +555,7 @@ Creates a rectangle on the canvas. .width('100%') .height('100%') .backgroundColor('#ffff00') - .onReady(() =>{ + .onReady(() => { this.path2Db.rect(20, 20, 100, 100); this.context.stroke(this.path2Db) }) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-components-contentSlot.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-components-contentSlot.md index 4ff250b5961ba45c299309ee96c6a48724680502..d8e7e8a587eb1cfbcbeea0aee626d426af4a9d6c 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-components-contentSlot.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-components-contentSlot.md @@ -22,9 +22,23 @@ Called when content is added to a placeholder component | Name | Type| Mandatory| Description | | ------- | -------- | ---- | ------------------------------------------------------------ | -| content | [Content](../js-apis-arkui-Content.md) | Yes | Manager of the **ContentSlot** component. Through the APIs provided by the native side, it can register and trigger the attach and detach event callbacks for **ContentSlot**, as well as manage the child components of **ContentSlot**.| +| content | [Content](#content) | Yes | Manager of the **ContentSlot** component. Through the APIs provided by the native side, it can register and trigger the attach and detach event callbacks for **ContentSlot**, as well as manage the child components of **ContentSlot**.| -**Example** +## Content + +type Content = Content + +Defines a base class for **ComponentContent** and **NodeContent**. + +**Atomic service API**: This API can be used in atomic services since API version 12. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Type| Description | +| ---- | ------------------------------------------------------------ | +| [Content](../js-apis-arkui-Content.md) | Base class for **ComponentContent** and **NodeContent**.| + +## Example The following example shows the basic usage of **ContentSlot**. @@ -35,18 +49,20 @@ import { NodeContent } from '@kit.ArkUI' @Entry @Component struct Parent { - private nodeContent: Content = new NodeContent(); + private nodeContent: Content = new NodeContent(); - aboutToAppear() { - // Create a node through the C API and add it to the nodeContent manager. - nativeNode.createNativeNode(this.nodeContent); - } + aboutToAppear() { + // Create a node through the C API and add it to the nodeContent manager. + nativeNode.createNativeNode(this.nodeContent); + } - build() { - Column() { - // Display the native components stored in the nodeContent manager. - ContentSlot(this.nodeContent) - } + build() { + Column() { + // Display the native components stored in the nodeContent manager. + ContentSlot(this.nodeContent) } + } } ``` + + diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-components-offscreencanvas.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-components-offscreencanvas.md index 275e156ae94e851699e75898cbdb8a80e666f531..6aee3f754fc1527b21585b8b9745e96a3ca6d382 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-components-offscreencanvas.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-components-offscreencanvas.md @@ -4,7 +4,7 @@ When using [Canvas](ts-components-canvas-canvas.md) or [Canvas API](ts-canvasrenderingcontext2d.md), rendering, animations, and user interactions generally occur on the main thread of an application. The computation relating to canvas animations and rendering may affect application performance. **OffscreenCanvas** allows for rendering off the screen. This means that some tasks can be run in a separate thread to reduce the load on the main thread. -> **NOTE** +> **NOTE** > > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. @@ -24,11 +24,11 @@ OffscreenCanvas(width: number, height: number, unit?: LengthMetricsUnit) **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description | | ------ | -------- | ---- | ------------------------------------- | -| width | number | Yes | Width of the offscreen canvas.
Default unit: vp | -| height | number | Yes | Height of the offscreen canvas.
Default unit: vp | -| unit12+ | [LengthMetricsUnit](../js-apis-arkui-graphics.md#lengthmetricsunit12) | No | Unit mode of the **OffscreenCanvas** object. The value cannot be dynamically changed once set. The configuration method is the same as that of [CanvasRenderingContext2D](ts-canvasrenderingcontext2d.md#lengthmetricsunit12).
Default value: **DEFAULT** | +| width | number | Yes | Width of the offscreen canvas.
Default unit: vp| +| height | number | Yes | Height of the offscreen canvas.
Default unit: vp| +| unit12+ | [LengthMetricsUnit](../js-apis-arkui-graphics.md#lengthmetricsunit12) | No | Unit mode of the **OffscreenCanvas** object. The value cannot be dynamically changed once set. The configuration method is the same as that of [CanvasRenderingContext2D](ts-canvasrenderingcontext2d.md#lengthmetricsunit12).
Default value: **DEFAULT**| ## Attributes @@ -40,10 +40,10 @@ OffscreenCanvas(width: number, height: number, unit?: LengthMetricsUnit) The following attributes are supported. -| Name | Type | Read Only | Optional | Description | +| Name | Type | Read Only| Optional| Description| | ------ | ------ | ------ | ------- | ---- | -| width | number | No | No | Width of the offscreen canvas.
Default unit: vp | -| height | number | No | No | Height of the offscreen canvas.
Default unit: vp | +| width | number | No | No | Width of the offscreen canvas.
Default unit: vp| +| height | number | No | No | Height of the offscreen canvas.
Default unit: vp| ### width @@ -135,7 +135,7 @@ Creates an **ImageBitmap** object from the most recently rendered image of the o | Type | Description | | -------------------------------------------------- | ----------------------- | -| [ImageBitmap](ts-components-canvas-imagebitmap.md) | **ImageBitmap** object created. | +| [ImageBitmap](ts-components-canvas-imagebitmap.md) | **ImageBitmap** object created.| **Example** @@ -173,7 +173,7 @@ struct OffscreenCanvasPage { } ``` -![zh-cn_image_0000001194032666](figures/offscreen_canvas_transferToImageBitmap.png) +![en-us_image_0000001194032666](figures/offscreen_canvas_transferToImageBitmap.png) ### getContext10+ @@ -187,16 +187,16 @@ Obtains the drawing context of the offscreen canvas. **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type| Mandatory| Description | | ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| contextType | string | Yes | Type of the drawing context of the offscreen canvas. The value can only be **"2d"**.
Default value: **"2d"**| -| options | [RenderingContextSettings](ts-canvasrenderingcontext2d.md#renderingcontextsettings) | No | Parameters of the **OffscreenCanvasRenderingContext2D** object. For details, see [RenderingContextSettings](ts-canvasrenderingcontext2d.md#renderingcontextsettings).
Default value: **null** | +| contextType | string | Yes | Type of the drawing context of the offscreen canvas. The value can only be **"2d"**.| +| options | [RenderingContextSettings](ts-canvasrenderingcontext2d.md#renderingcontextsettings) | No| Parameters of the **OffscreenCanvasRenderingContext2D** object. For details, see [RenderingContextSettings](ts-canvasrenderingcontext2d.md#renderingcontextsettings).
Default value: **null**| **Return value** | Type | Description | | ------------------------------------------------------------ | --------------------------------- | -| [OffscreenCanvasRenderingContext2D](ts-offscreencanvasrenderingcontext2d.md) | Drawing context of the offscreen canvas. If **contextType** in **getContext** is set to a value other than **"2d"** (including **null** and **undefined**), **null** is returned. | +| [OffscreenCanvasRenderingContext2D](ts-offscreencanvasrenderingcontext2d.md) | Drawing context of the offscreen canvas. If **contextType** in **getContext** is set to a value other than **"2d"** (including **null** and **undefined**), **null** is returned.| **Example** @@ -252,7 +252,7 @@ struct OffscreenCanvasExamplePage { ## Concurrent Thread Drawing -Since API version 11, an application can call **postMessage** to pass an **OffscreenCanvas** instance to a worker thread for drawing, and call **onmessage** to receive the drawing result for display. +Since API version 11, an application can call **postMessage** to pass an **OffscreenCanvas** instance to a [worker thread](../../../arkts-utils/worker-introduction.md) for drawing, and call **onmessage** to receive the drawing result for display. > **NOTE** > @@ -261,6 +261,8 @@ Since API version 11, an application can call **postMessage** to pass an **Offsc > After an **OffscreenCanvas** object is passed to a thread through **postMessage**, it cannot use the **getContext** or **transferToImageBitmap** APIs. Otherwise, an exception is thrown. > > After an **OffscreenCanvas** object is passed to a thread through **postMessage**, it cannot be passed to any other thread through **postMessage**. Otherwise, an exception is thrown. +> +> The content drawn in the Worker thread cannot be previewed in DevEco Studio Previewer. **Example** diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-alphabet-indexer.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-alphabet-indexer.md index d6c2c468fa28596d582b13a2529d5f0f801b4d39..69fcb0ee809a2f6c9d3414f42fa9ea13600e25e2 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-alphabet-indexer.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-alphabet-indexer.md @@ -24,16 +24,20 @@ AlphabetIndexer(options: AlphabetIndexerOptions) | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| options | [AlphabetIndexerOptions](#alphabetindexeroptions16) | Yes| Options of the **AlphabetIndexer** component.| +| options | [AlphabetIndexerOptions](#alphabetindexeroptions18) | Yes| Options of the **AlphabetIndexer** component.| -## AlphabetIndexerOptions16+ +## AlphabetIndexerOptions18+ Defines the options of the **AlphabetIndexer** component. +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| arrayValue | Array<string> | Yes| Array of index items.| -| selected | number | Yes | Index of the initially selected item. If the value exceeds the value range, the default value 0 is used.
This parameter supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md).| +| arrayValue7+ | Array<string> | Yes| Array of index items.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| selected7+ | number | Yes | Index of the initially selected item. If the value exceeds the value range, the default value 0 is used.
This parameter supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md).
**Atomic service API**: This API can be used in atomic services since API version 11.| ## Attributes @@ -43,7 +47,7 @@ The default value of the [padding](ts-universal-attributes-size.md#padding) attr The [maxFontScale](ts-basic-components-text.md#maxfontscale12) and [minFontScale](ts-basic-components-text.md#minfontscale12) attributes are both set to a constant value of 1, which means that they do not change with the system font size. -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### color @@ -139,7 +143,7 @@ Sets whether to display the pop-up window. | Name| Type | Mandatory| Description | | ------ | ------- | ---- | -------------------------------------- | -| value | boolean | Yes | Whether to display the pop-up window.
Default value: **false**| +| value | boolean | Yes | Whether to display the pop-up window.
Default value: **false** (no the pop-up window is displayed).| ### selectedFont @@ -155,7 +159,7 @@ Sets the text style for the selected item. | Name| Type | Mandatory| Description | | ------ | ------------------------ | ---- | ------------------------------------------------------------ | -| value | [Font](ts-types.md#font) | Yes | Text style of the selected item.
Default value:
API version 11 and earlier:
{
size:'12.0fp',
style:FontStyle.Normal,
weight:FontWeight.Normal,
family:'HarmonyOS Sans'
}
API version 12 and later:
{
size:'10.0vp',
style:FontStyle.Normal,
weight:FontWeight.Medium,
family:'HarmonyOS Sans'
} | +| value | [Font](ts-types.md#font) | Yes | Text style of the selected item.
Default value:
API version 11 and earlier:
{
size:'12.0fp',
style:FontStyle.Normal,
weight:FontWeight.Regular,
family:'HarmonyOS Sans'
}
API version 12 and later:
{
size:'10.0vp',
style:FontStyle.Normal,
weight:FontWeight.Medium,
family:'HarmonyOS Sans'
} | ### popupFont @@ -171,7 +175,7 @@ Sets the text style for the primary index item in the pop-up window. | Name| Type | Mandatory| Description | | ------ | ------------------------ | ---- | ------------------------------------------------------------ | -| value | [Font](ts-types.md#font) | Yes | Text style of the primary index item in the pop-up window.
Default value:
{
size:'24.0vp',
style:FontStyle.Normal,
weight:FontWeight.Normal,
family:'HarmonyOS Sans'
} | +| value | [Font](ts-types.md#font) | Yes | Text style of the primary index item in the pop-up window.
Default value:
{
size:'24.0vp',
style:FontStyle.Normal,
weight:FontWeight.Medium,
family:'HarmonyOS Sans'
} | ### font @@ -187,7 +191,7 @@ Sets the text style for unselected items. | Name| Type | Mandatory| Description | | ------ | ------------------------ | ---- | ------------------------------------------------------------ | -| value | [Font](ts-types.md#font) | Yes | Text style of unselected items.
Default value:
API version 11 and earlier:
{
size:'12.0fp',
style:FontStyle.Normal,
weight:FontWeight.Normal,
family:'HarmonyOS Sans'
}
API version 12 and later:
{
size:'10.0vp',
style:FontStyle.Normal,
weight:FontWeight.Medium,
family:'HarmonyOS Sans'
} | +| value | [Font](ts-types.md#font) | Yes | Text style of unselected items.
Default value:
API version 11 and earlier:
{
size:'12.0fp',
style:FontStyle.Normal,
weight:FontWeight.Regular,
family:'HarmonyOS Sans'
}
API version 12 and later:
{
size:'10.0vp',
style:FontStyle.Normal,
weight:FontWeight.Medium,
family:'HarmonyOS Sans'
} | ### itemSize @@ -286,7 +290,7 @@ Sets the text color for the unselected secondary index items in the pop-up windo | Name| Type | Mandatory| Description | | ------ | ------------------------------------------ | ---- | ------------------------------------------------------- | -| value | [ResourceColor](ts-types.md#resourcecolor) | Yes | Text color of the unselected secondary index items in the pop-up window.
Default value: **#FF182431**| +| value | [ResourceColor](ts-types.md#resourcecolor) | Yes | Text color of the selected secondary index item in the pop-up window.
Default value: **#FF182431**| ### popupItemFont10+ @@ -422,7 +426,7 @@ enableHapticFeedback(value: boolean) | Name | Type | Mandatory| Description | |-------------|-----------------------------------------------------|----|----------------------------| -| value | boolean | Yes | Whether haptic feedback is enabled.
Default value: **true**
| +| value | boolean | Yes | Whether to enable haptic feedback.
Default value: **true** (haptic feedback is enabled).| ## IndexerAlign @@ -437,7 +441,7 @@ enableHapticFeedback(value: boolean) ## Events -In addition to the [universal events](ts-universal-events-click.md), the following events are supported. +In addition to the [universal events](ts-component-general-events.md), the following events are supported. ### onSelected(deprecated) @@ -469,7 +473,7 @@ Triggered when an index item is selected, with the callback parameter being the | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------- | -| callback | [OnAlphabetIndexerSelectCallback](#onalphabetindexerselectcallback16) | Yes | Event triggered when an index item is selected.| +| callback | [OnAlphabetIndexerSelectCallback](#onalphabetindexerselectcallback18) | Yes | Event triggered when an index item is selected.| ### onRequestPopupData8+ @@ -485,7 +489,7 @@ Triggered to set the content of the secondary index items in the pop-up window. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| callback | [OnAlphabetIndexerRequestPopupDataCallback](#onalphabetindexerrequestpopupdatacallback16) | Yes | Event triggered to set the content of the secondary index items in the pop-up window.| +| callback | [OnAlphabetIndexerRequestPopupDataCallback](#onalphabetindexerrequestpopupdatacallback18) | Yes | Event triggered to set the content of the secondary index items in the pop-up window.| ### onPopupSelect8+ @@ -501,14 +505,14 @@ Triggered when a secondary index item in the pop-up window is selected. The call | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------- | -| callback | [OnAlphabetIndexerPopupSelectCallback](#onalphabetindexerpopupselectcallback16) | Yes | Event triggered when a secondary index item in the pop-up window is selected.| +| callback | [OnAlphabetIndexerPopupSelectCallback](#onalphabetindexerpopupselectcallback18) | Yes | Event triggered when a secondary index item in the pop-up window is selected.| -## OnAlphabetIndexerSelectCallback16+ +## OnAlphabetIndexerSelectCallback18+ type OnAlphabetIndexerSelectCallback = (index: number) => void Represents the callback invoked when an index item is selected. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -517,12 +521,12 @@ Represents the callback invoked when an index item is selected. | ------- | ----- | ---- | ------ | | index | number | Yes | Index of the currently selected index item.| -## OnAlphabetIndexerPopupSelectCallback16+ +## OnAlphabetIndexerPopupSelectCallback18+ type OnAlphabetIndexerPopupSelectCallback = (index: number) => void Represents the callback invoked when a secondary index item in the pop-up window is selected. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -531,12 +535,12 @@ Represents the callback invoked when a secondary index item in the pop-up window | ------- | ----- | ---- | ------ | | index | number | Yes | Index of the currently selected secondary index item in the pop-up window.| -## OnAlphabetIndexerRequestPopupDataCallback16+ +## OnAlphabetIndexerRequestPopupDataCallback18+ type OnAlphabetIndexerRequestPopupDataCallback = (index: number) => Array\ Represents the callback invoked when an index item is selected and [usingPopup](#usingpopup) is set to **true**. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -620,7 +624,7 @@ struct AlphabetIndexerSample { AlphabetIndexer({ arrayValue: this.value, selected: 0 }) .autoCollapse (false) // Disable the auto-collapse mode. .enableHapticFeedback(false) // Disable haptic feedback. - .selectedColor(0xFFFFFF) // Font color of the selected text. + .selectedColor(0xFFFFFF) // Text color of the selected item. .popupColor(0xFFFAF0) // Text color of the primary index item in the pop-up window. .selectedBackgroundColor(0xCCCCCC) // Background color of the selected item. .popupBackground (0xD2B48C) // Background color of the pop-up window. @@ -677,7 +681,7 @@ This example demonstrates how to enable adaptive collapse mode using the [autoCo @Entry @Component struct AlphabetIndexerSample { - private arrayA:string[] = ['Ann'] + private arrayA: string[] = ['Ann'] private arrayB: string[] = ['Ben', 'Bob'] private arrayC: string[] = ['Calvin', 'Cameron', 'Charlie', 'Charlotte'] private arrayJ: string[] = ['Jack', 'James'] @@ -741,7 +745,7 @@ struct AlphabetIndexerSample { .autoCollapse (this.isNeedAutoCollapse) // Enable or disable adaptive collapse mode. .height (this.indexerHeight) // Indexer height. .enableHapticFeedback(false) // Disable haptic feedback. - .selectedColor(0xFFFFFF) // Font color of the selected text. + .selectedColor(0xFFFFFF) // Text color of the selected item. .popupColor(0xFFFAF0) // Text color of the primary index item in the pop-up window. .selectedBackgroundColor(0xCCCCCC) // Background color of the selected item. .popupBackground (0xD2B48C) // Background color of the pop-up window. @@ -819,7 +823,7 @@ This example demonstrates how to apply a background blur effect to the pop-up wi @Entry @Component struct AlphabetIndexerSample { - private arrayA:string[] = ['Ann'] + private arrayA: string[] = ['Ann'] private arrayB: string[] = ['Ben', 'Bob'] private arrayC: string[] = ['Calvin', 'Cameron', 'Charlie', 'Charlotte'] private arrayL: string[] = ['Daisy', 'Daniel', 'Darla', 'David', 'Derek', 'Dorothy', 'Duke'] diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-arclist.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-arclist.md index 85cf52fdaa9f51373c995f780c3ee822c21afdef..b384498aeb152b70c2973d1be30a6d7e0517d989 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-arclist.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-arclist.md @@ -4,7 +4,7 @@ The **ArcList** component is a circular layout container that displays a series > **NOTE** > -> This component is supported since API version 16. Updates will be marked with a superscript to indicate their earliest API version. +> This component is supported since API version 18. Updates will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -30,8 +30,6 @@ Only the [ArcListItem](ts-container-arclistitem.md) component is supported. > - If the values of [if/else](../../../quick-start/arkts-rendering-control-ifelse.md), [ForEach](../../../quick-start/arkts-rendering-control-foreach.md), and [LazyForEach](../../../quick-start/arkts-rendering-control-lazyforeach.md) change, the indexes of subnodes are updated. > > - Child components of **ArcList** whose [visibility](ts-universal-attributes-visibility.md#visibility) attribute is set to **Hidden** or **None** are still included in the index calculation. -> -> - Child components of **ArcList** whose [visibility](ts-universal-attributes-visibility.md#visibility) attribute is set to **None** are not displayed, but the spacing above and below them still takes effect. ## APIs @@ -40,7 +38,7 @@ ArcList(options?: ArkListOptions) Creates an instance of the **ArcList** component with optional configuration parameters. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Circle @@ -52,7 +50,7 @@ Creates an instance of the **ArcList** component with optional configuration par ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### digitalCrownSensitivity @@ -60,7 +58,7 @@ digitalCrownSensitivity(sensitivity: Optional\) Sets the sensitivity of the digital crown's response to events. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Circle @@ -68,7 +66,7 @@ Sets the sensitivity of the digital crown's response to events. | Name | Type | Mandatory| Description | | ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| sensitivity | [Optional<CrownSensitivity>](ts-appendix-enums.md#crownsensitivity16) | Yes | Sensitivity of the digital crown's response.
Default value: **CrownSensitivity.MEDIUM**, indicating moderate response speed| +| sensitivity | [Optional<CrownSensitivity>](ts-appendix-enums.md#crownsensitivity18) | Yes | Sensitivity of the digital crown's response.
Default value: **CrownSensitivity.MEDIUM**, indicating moderate response speed| ### space @@ -76,7 +74,7 @@ space(space: Optional\) Sets the spacing between list items. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Circle @@ -84,7 +82,7 @@ Sets the spacing between list items. | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ---------------------------------- | -| space | [Optional<LengthMetrics>](../js-apis-arkui-graphics.md#lengthmetrics12) | No | Spacing between list items.
Default value: **0**| +| space | [Optional<LengthMetrics>](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes | Spacing between list items.
Default value: **0**
Child components of **ArcList** whose [visibility](ts-universal-attributes-visibility.md#visibility) attribute is set to **None** are not displayed, but the spacing above and below them still takes effect.| ### scrollBar @@ -92,7 +90,7 @@ scrollBar(status: Optional\) Sets the state of the scrollbar. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Circle @@ -100,17 +98,17 @@ Sets the state of the scrollbar. | Name| Type | Mandatory| Description | | ------ | ---------------------------------------------------- | ---- | ---------------------------------------- | -| status | [Optional\](ts-appendix-enums.md#barstate) | No | State of the scrollbar.
Default value: **BarState.Auto**| +| status | [Optional\](ts-appendix-enums.md#barstate) | Yes | State of the scrollbar.
Default value: **BarState.Auto**| ### cachedCount cachedCount(count: Optional\) -Sets the number of list items to preload (cache) in the [LazyForEach](../../../quick-start/arkts-rendering-control-lazyforeach.md) component. +Sets the number of arc list items to be preloaded (cached). In a lazy loading scenario, only the content equivalent to **cachedCount** outside the visible area of the arc list is preloaded. In a non-lazy loading scenario, all items are loaded at once. For both lazy and non-lazy loading, only the content within the visible area of the arc list plus the content equivalent to **cachedCount** outside the visible area is laid out. -This attribute specifies the number of items to cache before and after the visible items in the **ArcList** component. +When **cachedCount** is set for the arc list, the system preloads and lays out the **cachedCount**-specified number of rows of arc list items both above and below the currently visible area of the arc list. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Circle @@ -118,7 +116,7 @@ This attribute specifies the number of items to cache before and after the visib | Name| Type | Mandatory| Description | | ------ | ----------------- | ---- | ------------------------------------------ | -| value | Optional\ | Yes | Number of list items to preload.
Default value: **1**| +| count | Optional\ | Yes | Number of list items to preload.
Default value: number of nodes visible on the screen, with the maximum value of 16.
Value range: [0, +∞).| ### chainAnimation @@ -130,7 +128,7 @@ The list items are separated with even space, and one item animation starts afte For chained animations to work properly, the edge scrolling effect of the **ArcList** component must be set to [EdgeEffect.Spring](ts-appendix-enums.md#edgeeffect). -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Circle @@ -146,7 +144,7 @@ enableScrollInteraction(enable: Optional\) Sets whether to support scroll gestures. When this attribute is set to **false**, scrolling by finger or mouse is not supported, but the [Scroller](ts-container-scroll.md#scroller) controller API is not affected. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Circle @@ -156,13 +154,29 @@ Sets whether to support scroll gestures. When this attribute is set to **false** | ------ | ------------------ | ---- | ----------------------------------- | | enable | Optional\ | Yes | Whether to support scroll gestures.
Default value: **true**| +### fadingEdge + +fadingEdge(enable: Optional<boolean>) + +Sets whether to enable the edge fading effect. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | +| enable | Optional<boolean> | Yes | Whether to enable the edge fading effect.
When **fadingEdge** is set to **true**, it overrides the **.overlay()** attribute of the component.
With **fadingEdge** set to **true**, avoid setting background-related attributes on the component, as this may affect the display of the fading effect.
With **fadingEdge** set to **true**, the component is clipped to the boundary, and setting the component's **clip** attribute to **false** will not take effect.
Default value: **false**, which means not to enable the edge fading effect.| + ### friction friction(friction: Optional\) Sets the friction coefficient. It applies only to gestures in the scrolling area, and it affects only indirectly the scroll chaining during the inertial scrolling process. If this attribute is set to a value less than or equal to 0, the default value is used. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Circle @@ -170,7 +184,7 @@ Sets the friction coefficient. It applies only to gestures in the scrolling area | Name | Type | Mandatory| Description | | -------- | ----------------- | ---- | ---------------------------- | -| friction | Optional\ | No | Friction coefficient.
Default value: **0.8**| +| friction | Optional\ | Yes | Friction coefficient.
Default value: **0.8**
Value range: (0, +∞).| ### scrollBarWidth @@ -178,7 +192,7 @@ scrollBarWidth(width: Optional\) Sets the width of the scrollbar. Once the width is set, the scrollbar will use this width in its pressed state. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Circle @@ -194,7 +208,7 @@ scrollBarColor(color: Optional\) Sets the color of the scrollbar. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Circle @@ -208,9 +222,9 @@ Sets the color of the scrollbar. flingSpeedLimit(speed: Optional\) -Sets the maximum initial speed for inertial scrolling after a fling gesture. The unit is vp/s. +Sets the maximum initial speed for inertial scrolling after a fling gesture. If this attribute is set to a value less than or equal to 0, the default value is used. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Circle @@ -218,7 +232,7 @@ Sets the maximum initial speed for inertial scrolling after a fling gesture. The | Name| Type | Mandatory| Description | | ------ | ----------------- | ---- | ------------------------------- | -| speed | Optional\ | Yes | Maximum initial speed for inertial scrolling.| +| speed | Optional\ | Yes | Maximum initial speed for inertial scrolling.
Default value: **9000**.
Unit: vp/s.
Value range: (0, +∞).| ### childrenMainSize @@ -226,7 +240,7 @@ childrenMainSize(size: Optional\) Sets the size information of the child components of the **ArcList** component along the main axis. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Circle @@ -246,7 +260,7 @@ Triggered when a child component enters or leaves the visible area of the **ArcL If the edge scrolling effect of the **ArcList** component is set to spring, this event is not triggered during continued scrolling at the edge or during the bounce-back process -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Circle @@ -264,13 +278,13 @@ Triggered when the list reaches the start position. This event is triggered during initialization of the **ArcList** component if [initialIndex](#arklistoptions) is set to **0**, and whenever the list scrolls to the start position. If the edge scrolling effect is set to spring, this event is triggered when scrolling past the start position and again when bouncing back to it. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Circle | Name | Type | Mandatory| Description | | ------- | ------------------------------------------------ | ---- | ------------------------ | -| handler | [Optional\](#voidcallback) | Yes | Callback triggered when the list reaches the start position.| +| handler | [Optional\](ts-types.md#voidcallback12) | Yes | Callback triggered when the list reaches the start position.| ### onReachEnd @@ -280,13 +294,13 @@ Triggered when the list reaches the end position. If the edge scrolling effect is set to spring, this event is triggered when scrolling past the end position and again when bouncing back to it. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Circle | Name | Type | Mandatory| Description | | ------- | ------------------------------------------------ | ---- | ------------------------ | -| handler | [Optional\](#voidcallback) | Yes | Callback triggered when the list reaches the end position.| +| handler | [Optional\](ts-types.md#voidcallback12) | Yes | Callback triggered when the list reaches the end position.| ### onScrollStart @@ -294,13 +308,13 @@ onScrollStart(handler: Optional\) Triggered when the list starts scrolling initiated by the user's finger dragging the list or its scrollbar. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](ts-container-scroll.md#scroller) starts. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Circle | Name | Type | Mandatory| Description | | ------- | ------------------------------------------------ | ---- | -------------------- | -| handler | [Optional\](#voidcallback) | Yes | Callback triggered when the list starts scrolling.| +| handler | [Optional\](ts-types.md#voidcallback12) | Yes | Callback triggered when the list starts scrolling.| ### onScrollStop @@ -308,21 +322,21 @@ onScrollStop(handler: Optional\) Triggered when the list stops scrolling after the user's finger leaves the screen. This event is also triggered when the animation contained in the scrolling triggered by [Scroller](ts-container-scroll.md#scroller) stops. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Circle | Name | Type | Mandatory| Description | | ------- | ------------------------------------------------ | ---- | -------------------- | -| handler | [Optional\](#voidcallback) | Yes | Callback triggered when the list stops scrolling.| +| handler | [Optional\](ts-types.md#voidcallback12) | Yes | Callback triggered when the list stops scrolling.| ### onWillScroll onWillScroll(handler: Optional\) -Triggered when the list is about to scroll. The return value is the offset amount by which the list will scroll and the current scroll state. The returned offset is obtained by calculation, not the actual offset. +Triggered before each frame when the list is being scrolled. The return value is the offset amount by which the list will scroll and the current scroll state. The returned offset is obtained by calculation, not the actual offset. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Circle @@ -330,7 +344,7 @@ Triggered when the list is about to scroll. The return value is the offset amoun | Name| Type| Mandatory| Description| | ------ | ------ | ------ | ------| -| handler | [Optional\](#onwillscrollcallback) | Yes| Callback triggered when the list is about to scroll.| +| handler | [Optional\](ts-container-scrollable-common.md#onwillscrollcallback12) | Yes| Callback triggered before each frame when the list is being scrolled.| > **NOTE** > @@ -341,7 +355,7 @@ onDidScroll(handler: Optional\) Triggered when the list scrolls. The return value is the offset amount by which the list has scrolled and the current scroll state. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Circle @@ -355,7 +369,7 @@ Triggered when the list scrolls. The return value is the offset amount by which Provides basic parameters for creating an **ArcList** component. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Circle @@ -365,15 +379,13 @@ Provides basic parameters for creating an **ArcList** component. | scroller | [Scroller](ts-container-scroll.md#scroller) | No | Scroller, which can be bound to scrollable components for scrolling control.
**NOTE**
The same scroller cannot be bound to multiple scrollable components.| | header | [ComponentContent](../js-apis-arkui-ComponentContent.md) | No | Header component. | -## VoidCallback - -The **VoidCallback** object has no parameters and returns no value. - ## ArcScrollIndexHandler +type ArcScrollIndexHandler = (start: number, end: number, center: number) => void + Represents the callback triggered when a child component enters or leaves the visible area of the **ArcList** component. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Circle @@ -383,20 +395,6 @@ Represents the callback triggered when a child component enters or leaves the vi | end | number | Yes | Index of the last child component in the visible area of the **ArcList** component.| | center | number | Yes | Index of the center child component in the visible area of the **ArcList** component.| -## OnWillScrollCallback - -Represents the callback invoked when the list is about to scroll. - -**Atomic service API**: This API can be used in atomic services since API version 16. - -**System capability**: SystemCapability.ArkUI.ArkUI.Circle - -| Name | Type | Mandatory| Description | -| ------------ | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| scrollOffset | number | Yes | Scroll offset of each frame. Positive values indicate upward scrolling, while negative values indicate downward scrolling.
Unit: vp| -| scrollState | [ScrollState](ts-container-list.md#scrollstate) | Yes | Current scroll state. | -| scrollSource | ScrollSource | Yes | Source of the current scrolling operation. | - ## Example This example demonstrates an **ArcList** component with a header component and auto-scaling child items. diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-arclistitem.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-arclistitem.md index 00e027e2de299a2c9352f44af4a2cb22b29dd375..2301654992c34ef5ecdf29bbec16014c1da226dc 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-arclistitem.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-arclistitem.md @@ -4,7 +4,7 @@ The **ArcListItem** component is used to display individual child components in > **NOTE** > -> - This component is supported since API version 16. Updates will be marked with a superscript to indicate their earliest API version. +> - This component is supported since API version 18. Updates will be marked with a superscript to indicate their earliest API version. > - This component can be used only as a child of [ArcList](ts-container-arclist.md). > - When this component is used with [LazyForEach](../../../quick-start/arkts-rendering-control-lazyforeach.md), its child components are created when it is created. When this component is used with [if/else](../../../quick-start/arkts-rendering-control-ifelse.md) or [ForEach](../../../quick-start/arkts-rendering-control-foreach.md), or when the parent component is [ArcList](ts-container-arclist.md), its child components are created when it is laid out. @@ -26,13 +26,13 @@ ArcListItem() Creates an item for the **ArcList** component. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Circle ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### autoScale @@ -40,7 +40,7 @@ autoScale(enable: Optional\) Sets whether to enable auto-scaling for the **ArcListItem** component. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Circle @@ -48,7 +48,7 @@ Sets whether to enable auto-scaling for the **ArcListItem** component. | Name| Type | Mandatory| Description | | ------ | ------------------ | ---- | ------------------------------------------- | -| enable | Optional\ | Yes | Whether to enable auto-scaling.
Default value: **true**| +| enable | Optional\ | Yes | Whether to enable auto-scaling.
**true**: Enable auto-scaling.
**false**: Disable auto-scaling.
Default value: **true**.| ### swipeAction @@ -56,7 +56,7 @@ swipeAction(options: Optional\) Sets the swipe action item displayed when the **ArcListItem** component is swiped out from the screen edge. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Circle diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-arcswiper.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-arcswiper.md new file mode 100644 index 0000000000000000000000000000000000000000..b7ef82f48af1fbee351402f3161a68f7190aa3ac --- /dev/null +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-arcswiper.md @@ -0,0 +1,695 @@ +# ArcSwiper + +The **ArcSwiper** component is designed for circular screens to display child components in a carousel-like manner. + +> **NOTE** +> +> This component is supported since API version 18. Updates will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```ts +import { + ArcSwiper, + ArcSwiperAttribute, + ArcDotIndicator, + ArcDirection, + ArcSwiperController +} from '@kit.ArkUI'; +``` + +## Child Components + +This component can contain child components. + +> **NOTE** +> +> - Built-in components and custom components are allowed, with support for ([if/else](../../../quick-start/arkts-rendering-control-ifelse.md), [ForEach](../../../quick-start/arkts-rendering-control-foreach.md), and [LazyForEach](../../../quick-start/arkts-rendering-control-lazyforeach.md)) rendering control. +>- Do not add or delete child components during a page turning animation. Doing so may result in child components not yet animated entering the viewport in advance and causing display exceptions. + +## APIs + +ArcSwiper(controller?: ArcSwiperController) + +Creates an **ArcSwiper** component. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------- | ---- | ---------------------------------------- | +| controller | [ArcSwiperController](#arcswipercontroller) | No | Controller bound to the component to control the page turning.| + + +## Attributes + +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. [Menu control](ts-universal-attributes-menu.md) is not supported. + +### index + +index(index: Optional\) + +Sets the index of the child component currently displayed in the container. If the value is less than 0 or greater than or equal to the number of child components, the default value **0** is used. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------ | +| index | Optional\ | Yes | Index of the child component currently displayed in the container.
Default value: **0**| + +### indicator + +indicator(style: Optional\) + +Sets the style of the arc-shaped dot-style navigation indicator. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| style | Optional\<[ArcDotIndicator](#arcdotindicator) \| boolean> | Yes | Style of the arc-shaped dot-style navigation indicator.
\- **ArcDotIndicator**: properties and functionality of the arc-shaped dot-style navigation indicator.
\- **boolean**: whether to enable the arc-shaped dot-style navigation indicator. The value **true** means to enable the arc-shaped dot-style navigation indicator, and **false** means the opposite.
Default value: **true**
Default type: **ArcDotIndicator**| + +### duration + +duration(duration: Optional\) + +Sets the duration of the animation for child component switching. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ----------------------------------------------------- | +| duration | Optional\ | Yes | Duration of the autoplay for child component switching.
Default value: **400**
Unit: ms| + +### vertical + +vertical(isVertical: Optional\) + +Sets whether vertical swiping is used. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ---------------------------------- | +| isVertical | Optional\ | Yes | Whether vertical swiping is used. The value **true** means vertical swiping, and **false** means horizontal swiping.
Default value: **false**| + +### disableSwipe + +disableSwipe(disabled: Optional\) + +Sets whether to disable the swipe feature. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ---------------------------------------- | +| disabled | Optional\ | Yes | Whether to disable the swipe feature. The value **true** means to disable the feature, and **false** means the opposite.
Default value: **false**| + +### digitalCrownSensitivity + +digitalCrownSensitivity(sensitivity: Optional\) + +Sets the sensitivity to the digital crown rotation. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------------------------------------- | ---- | --------------------------------------------------- | +| sensitivity | Optional\<[CrownSensitivity](ts-appendix-enums.md#crownsensitivity18)> | Yes | Sensitivity to the digital crown rotation.
Default value: **CrownSensitivity.LOW**| + +### effectMode + +effectMode(edgeEffect: Optional\) + +Sets the effect used when the scroll boundary is reached. For details about the supported effects, see [EdgeEffect](ts-appendix-enums.md#edgeeffect). The edge effect does not take effect when set using the controller API. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | --------------------------------------------- | ---- | -------------------------------------------- | +| edgeEffect | Optional\<[EdgeEffect](ts-appendix-enums.md#edgeeffect)> | Yes | Effect used when the component is at one of the edges.
Default value: **EdgeEffect.Spring**| + +### disableTransitionAnimation + +disableTransitionAnimation(disabled: Optional\) + +Sets whether to disable the transition animation. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------ | ---- | --------------------------------------- | +| disabled | Optional\ | Yes | Whether to disable the transition animation.
Default value: **false**, which means not to disable the transition animation.| + +## ArcSwiperController + +Implements the controller of the **ArcSwiper** component. You can bind this object to the **ArcSwiper** component and use it to control page switching. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +### constructor + +constructor() + +A constructor used to create an **ArcSwiperController** instance. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +### showNext + +showNext() + +Turns to the next page. Page turning occurs with the animation, whose duration is specified by [duration](#duration). + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +### showPrevious + +showPrevious() + +Turns to the previous page. Page turning occurs with the animation, whose duration is specified by [duration](#duration). + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +### finishAnimation + +finishAnimation(handler?: FinishAnimationHandler) + +Stops an animation. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------- | ---- | ------------------------------------------------ | +| handler | [FinishAnimationHandler](#finishanimationhandler) | No | Callback invoked when the animation stops.
If no value is provided, no callback is performed.| + +## ArcDotIndicator + +Provides the properties and functionality of the arc-shaped dot-style navigation indicator. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +### constructor + +constructor() + +A constructor used to create an **ArcDotIndicator** instance. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +### arcDirection + +arcDirection(direction: Optional\): ArcDotIndicator + +Sets the direction of the arc navigation indicator. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | +| direction | [Optional\](#arcdirection) | Yes | Direction of the arc navigation indicator.
Default value: **ArcDirection.SIX_CLOCK_DIRECTION** (6 o'clock direction)| + +**Return value** + +| Type | Description | +| ----------------------------------- | ------------------------------ | +| [ArcDotIndicator](#arcdotindicator) | Properties and functionality of the arc navigation indicator.| + +### itemColor + +itemColor(color: Optional\): ArcDotIndicator + +Sets the color of the unselected navigation points in the arc navigation indicator. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | +| color | [Optional\](ts-types.md#resourcecolor) | Yes | Color of the unselected navigation points in the arc navigation indicator.
Default value: **'#A9FFFFFF'**| + +**Return value** + +| Type | Description | +| ----------------------------------- | ------------------------------ | +| [ArcDotIndicator](#arcdotindicator) | Properties and functionality of the arc navigation indicator.| + +### selectedItemColor + +selectedItemColor(color: Optional\): ArcDotIndicator + +Sets the color of the selected navigation point in the arc navigation indicator. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | +| color | [Optional\](ts-types.md#resourcecolor) | Yes | Color of the selected navigation point in the arc navigation indicator.
Default value: **#FF5EA1FF**| + +**Return value** + +| Type | Description | +| ----------------------------------- | ------------------------------ | +| [ArcDotIndicator](#arcdotindicator) | Properties and functionality of the arc navigation indicator.| + +### backgroundColor + +backgroundColor(color: Optional\): ArcDotIndicator + +Sets the color of the arc navigation indicator when it is long-pressed. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | +| color | [Optional\](ts-types.md#resourcecolor) | Yes | Color of the arc navigation indicator when it is long-pressed.
Default value: **'#FF404040'**| + +**Return value** + +| Type | Description | +| ----------------------------------- | ------------------------------ | +| [ArcDotIndicator](#arcdotindicator) | Properties and functionality of the arc navigation indicator.| + +### maskColor + +maskColor(color: Optional\): ArcDotIndicator + +Sets the mask gradient color of the arc navigation indicator. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| color | [Optional\](ts-basic-components-datapanel.md#lineargradient10) | Yes | Mask gradient color of the arc indicator.
Default start color: **'#00000000'**
Default end color: **'#FF000000'**| + +**Return value** + +| Type | Description | +| ----------------------------------- | ------------------------------ | +| [ArcDotIndicator](#arcdotindicator) | Properties and functionality of the arc navigation indicator.| + +### ArcDirection + +Enumerates the direction of the arc navigation indicator. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +| Name | Value | Description | +| --------------------- | ---- | ----------- | +| THREE_CLOCK_DIRECTION | 0 | 3 o'clock direction.| +| SIX_CLOCK_DIRECTION | 1 | 6 o'clock direction.| +| NINE_CLOCK_DIRECTION | 2 | 9 o'clock direction.| + +## FinishAnimationHandler + +type FinishAnimationHandler = () => void + +Defines the callback to notify the application when the animation stops playing. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +## IndexChangedHandler + +type IndexChangedHandler = (index: number) => void + +Defines the callback to notify the application when the index of the currently displayed element changes. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| index | number | Yes | Index of the currently displayed element. The index is zero-based.| + +## AnimationStartHandler + +type AnimationStartHandler = (index: number, targetIndex: number, event: SwiperAnimationEvent) => void + +Defines the callback triggered when the switching animation starts. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| index | number | Yes | Index of the currently displayed element before the animation starts (not the final index after the animation ends).| +| targetIndex | number | Yes | Index of the target element to switch to. | +| event | [SwiperAnimationEvent](ts-container-swiper.md#swiperanimationevent10) | Yes | Extra information of the animation, including the offset of the currently displayed element and target element relative to the start position of the **ArcSwiper** along the main axis, and the hands-off velocity.| + +## AnimationEndHandler + +type AnimationEndHandler = (index: number, event: SwiperAnimationEvent) => void + +Defines the callback triggered when the switching animation ends. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| index | number | Yes | Index of the currently displayed element. | +| event | [SwiperAnimationEvent](ts-container-swiper.md#swiperanimationevent10) | Yes | Extra information of the animation, which is the offset of the currently displayed element relative to the start position of the **ArcSwiper** along the main axis.| + +## GestureSwipeHandler + +type GestureSwipeHandler = (index: number, event: SwiperAnimationEvent) => void + +Callback triggered on a frame-by-frame basis when the page is turned by a swipe. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| index | number | Yes | Index of the currently displayed element. | +| event | [SwiperAnimationEvent](ts-container-swiper.md#swiperanimationevent10) | Yes | Extra information of the animation, which is the offset of the currently displayed element relative to the start position of the **ArcSwiper** along the main axis.| + +## Events + +In addition to the [universal events](ts-component-general-events.md), the following events are supported. + +### onChange + +onChange(handler: Optional\) + +Triggered when the index of the currently displayed child component changes. The return value is the index of the currently displayed child component. + +When the **ArcSwiper** component is used together with **LazyForEach**, the subpage UI update cannot be triggered in the **onChange** event. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------ | ---- | ------------------------ | +| handler | [Optional\](#indexchangedhandler) | Yes | Callback for the index of the currently displayed element.| + +### onAnimationStart + +onAnimationStart(handler: Optional\) + +Triggered when the switching animation starts. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------------------------------- | ---- | ---------------------- | +| handler | [Optional\](#animationstarthandler) | Yes | Triggered when the switching animation starts.| + +### onAnimationEnd + +onAnimationEnd(handler: Optional\) + +Triggered when the switching animation ends. + +This event is triggered when the switching animation of the **ArcSwiper** component ends, whether it is caused by gesture interruption or by calling **finishAnimation** through SwiperController. The **index** parameter indicates the index after the animation ends. When the **ArcSwiper** component contains multiple columns, the index is of the leftmost element. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------ | ---- | -------------------------- | +| handler | [Optional\](#animationendhandler) | Yes | Triggered when the switching animation ends.| + +### onGestureSwipe + +onGestureSwipe(handler: Optional\) + +Triggered on a frame-by-frame basis when the page is turned by a swipe. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------ | ---- | -------------------------------------- | +| handler | [Optional\](#gestureswipehandler) | Yes | Triggered on a frame-by-frame basis when the page is turned by a swipe.| + +### customContentTransition + +customContentTransition(transition: Optional\) + +Defines a custom switching animation. You can define custom animation attributes, such as **opacity**, **scale**, and **translate**, in the callback invoked on a frame-by-frame basis during the swiping-initiated page switching animation. + +During the swiping-initiated page switching animation, the [SwiperContentTransitionProxy](#swipercontenttransitionproxy) callback is invoked for all pages in the viewport on a frame-by-frame basis. For example, when there are two pages whose subscripts are 0 and 1 in the viewport, two callbacks whose indexes are 0 and 1 are invoked in each frame. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | --------------------------------- | +| transition | Optional\<[SwiperContentAnimatedTransition](#swipercontentanimatedtransition)> | Yes | Information about the custom switching animation.| + +## SwiperContentAnimatedTransition + +Provides the information about the custom switching animation. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +| Name| Type| Read Only| Optional| Description| +| ------ | ---- | ---- | ---- | ---- | +| timeout | number | No| Yes| Timeout for the custom switching animation. The timeout timer starts when the default animation (page scrolling) reaches the point where the first frame is moved out of the viewport. If you do not call the **finishTransition** API of [SwiperContentTransitionProxy](#swipercontenttransitionproxy) before the timer expires, the component considers that the custom animation of the page ends and immediately removes the page node from the render tree. The unit is ms. The default value is **0**.| +| transition | Callback\<[SwiperContentTransitionProxy](#swipercontenttransitionproxy)> | No| No| Content of the custom switching animation.| + +## SwiperContentTransitionProxy + +Implements the proxy object returned during the execution of the custom switching animation of the **ArcSwiper** component. You can use this object to obtain the page information in the custom animation viewport. You can also call the **finishTransition** API of this object to notify the **ArcSwiper** component that the custom animation has finished playing. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +### **Properties** + +| Name| Type| Read Only| Optional| Description| +| ------ | ---- | ---- | ---- | ---- | +| selectedIndex | number | No| No| Index of the currently selected page.| +| index | number | No| No| Index of a page in the viewport.| +| position | number | No| No| Position of the page specified by **index** relative to the start position of the **ArcSwiper** main axis (start position of the page corresponding to **selectedIndex**).| +| mainAxisLength | number | No| No| Length of the page specified by **index** along the main axis.| + +>**NOTE** +> +>For example, when the currently selected child component's index is **0**, in the animation process of switching from page 0 to page 1, a callback will be triggered for all pages within the viewport on each frame. +>When there are two pages, page 0 and page 1, in the viewport, two callbacks will be triggered per frame. The first callback will have **selectedIndex** as **0**, **index** as **0**, **position** representing the movement ratio of page 0 relative to its position before the animation started at the current frame, +>and **mainAxisLength** representing the length of page 0 along the main axis. The second callback will still have **selectedIndex** as **0**, **index** as **1**, **position** representing the movement ratio of page 1 relative to page 0 before the animation started at the current frame, +>and **mainAxisLength** representing the length of page 1 along the main axis. +> +>If the animation curve is a spring interpolation curve, during the transition animation from page 0 to page 1, due to the position and velocity when the user lifts their finger off the screen, animation may overshoot and slide past to page 2, then bounce back to page 1. Throughout this process, a callback is triggered for pages 1 and 2 within the viewport on every frame. +> + + +### finishTransition + +finishTransition(): void + +Notifies the **ArcSwiper** component that the custom animation has finished playing. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Circle + +## Example + +This example demonstrates the basic functionality of the **ArcSwiper** component. + +```ts +// xxx.ets +import { + ArcSwiper, + ArcSwiperAttribute, + ArcDotIndicator, + ArcDirection, + ArcSwiperController +} from '@kit.ArkUI' + +class MyDataSource implements IDataSource { + private list: Color[] = [] + + constructor(list: Color[]) { + this.list = list + } + + totalCount(): number { + return this.list.length + } + + getData(index: number): Color { + return this.list[index] + } + + registerDataChangeListener(listener: DataChangeListener): void { + } + + unregisterDataChangeListener() { + } +} + +@Entry +@Component +struct TestNewInterface { + @State itemSimpleColor: Color | number | string = '' + @State selectedItemSimpleColor: Color | number | string = '' + private wearableSwiperController: ArcSwiperController = new ArcSwiperController() + private arcDotIndicator: ArcDotIndicator = new ArcDotIndicator() + private data: MyDataSource = new MyDataSource([]) + @State backgroundColors: Color[] = [Color.Green, Color.Blue, Color.Yellow, Color.Pink, Color.White, Color.Gray, Color.Orange, Color.Transparent] + + aboutToAppear(): void { + let list: Color[] = [] + for (let i = 1; i <= 6; i++) { + list.push(i); + } + this.data = new MyDataSource(this.backgroundColors) + } + + build() { + Column() { + Row() { + ArcSwiper(this.wearableSwiperController) { + LazyForEach(this.data, (backgroundColor: Color, index: number) => { + Text(index.toString()) + .width(233) + .height(233) + .backgroundColor(backgroundColor) + .textAlign(TextAlign.Center) + .fontSize(30) + }) + } + .clip(new Circle({ width: 233, height: 233 })) + .effectMode(EdgeEffect.None) + .backgroundColor(Color.Transparent) + .index(0) + .duration(400) + .vertical(false) + .indicator(this.arcDotIndicator + .arcDirection(ArcDirection.SIX_CLOCK_DIRECTION) + .itemColor(this.itemSimpleColor) + .selectedItemColor(this.selectedItemSimpleColor) + ) + .disableSwipe(false) + .digitalCrownSensitivity(CrownSensitivity.MEDIUM) + .onChange((index: number) => { + console.info("onChange:" + index.toString()) + }) + .onAnimationStart((index: number, targetIndex: number, extraInfo: SwiperAnimationEvent) => { + console.info("index: " + index) + console.info("targetIndex: " + targetIndex) + console.info("current offset: " + extraInfo.currentOffset) + console.info("target offset: " + extraInfo.targetOffset) + console.info("velocity: " + extraInfo.velocity) + }) + .onAnimationEnd((index: number, extraInfo: SwiperAnimationEvent) => { + console.info("index: " + index) + console.info("current offset: " + extraInfo.currentOffset) + }) + .disableTransitionAnimation(false) + }.height('100%') + }.width('100%') + } +} +``` + +![arcSwiper](figures/arcSwiper.gif) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-badge.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-badge.md index 8dffec72dbebc3b876c3adbb02aa1892d7b1e497..22d9a338747e378af4a865807c8de04df9dd5a85 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-badge.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-badge.md @@ -68,7 +68,7 @@ Provides basic parameters for creating a badge. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| position | [BadgePosition](#badgeposition)\|[Position10+](ts-types.md#position) | No| Position to display the badge relative to the parent component.
Default value: **BadgePosition.RightTop**
**NOTE**
With the **Position** type, percentage values are not supported. If an invalid value is set, the default value **(0,0)** which indicates the upper left corner of the component, will be used.
With the **BadgePosition** type, the position is mirrored based on the [Direction](ts-appendix-enums.md#direction) property.| +| position | [BadgePosition](#badgeposition)\|[Position10+](ts-types.md#position) | No| Position to display the badge relative to the parent component.
Default value: **BadgePosition.RightTop**
**NOTE**
With the **Position** type, percentage values are not supported. If an invalid value is set, the default value **(0,0)**, which indicates the upper left corner of the component, will be used.
With the **BadgePosition** type, the position is mirrored based on the [Direction](ts-appendix-enums.md#direction) property.| | style | [BadgeStyle](#badgestyle) | Yes| Style of the badge, including the font color, font size, badge color, and badge size.| @@ -124,20 +124,20 @@ Inherits from [BadgeParam](#badgeparam) and has all attributes of **BadgeParam** | Name | Type | Mandatory| Description | | ------------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | color | [ResourceColor](ts-types.md#resourcecolor) | No | Font color.
Default value: **Color.White**
**Widget capability**: This API can be used in ArkTS widgets since API version 9.| -| fontSize | number \| string | No | Font size.
Default value: **10**
Unit: fp
**NOTE**
This parameter cannot be set in percentage.
**Widget capability**: This API can be used in ArkTS widgets since API version 9.| -| badgeSize | number \| string | No | Badge size.
Default value: **16**
Unit: vp
**NOTE**
This parameter cannot be set in percentage. If it is set to an invalid value, the default value is used.
**Widget capability**: This API can be used in ArkTS widgets since API version 9.| +| fontSize | number \| string | No | Font size. For the string type, only numeric string values with optional units, for example, **"10"** or **"10fp"**, are supported.
Default value: **10**
Unit: fp
The value must be greater than or equal to 0. If the value is less than 0, the default value is used.
**NOTE**
This parameter cannot be set in percentage.
**Widget capability**: This API can be used in ArkTS widgets since API version 9.| +| badgeSize | number \| string | No | Badge size. For the string type, numeric string values with optional units, for example, **"16"** or **"16fp"**, are supported.
Default value: **16**
Unit: vp
The value must be greater than or equal to 0. If the value is less than 0, the default value is used.
**NOTE**
This parameter cannot be set in percentage. If it is set to an invalid value, the default value is used.
**Widget capability**: This API can be used in ArkTS widgets since API version 9.| | badgeColor | [ResourceColor](ts-types.md#resourcecolor) | No | Badge color.
Default value: **Color.Red**
**Widget capability**: This API can be used in ArkTS widgets since API version 9.| -| fontWeight10+ | number \|[FontWeight](ts-appendix-enums.md#fontweight) \| string | No | Font weight of the text.
Default value: **FontWeight.Normal**
**NOTE**
This parameter cannot be set in percentage.| +| fontWeight10+ | number \|[FontWeight](ts-appendix-enums.md#fontweight) \| string | No | Font weight of the text. For the number type, the value ranges from 100 to 900, at an interval of 100. The default value is **400**. A larger value indicates a heavier font weight. For the string type, only strings that represent a number, for example, **400**, and the following enumerated values of **FontWeight** are supported: **bold**, **bolder**, **lighter**, **regular**, and **medium**.
Default value: **FontWeight.Normal**
**NOTE**
This parameter cannot be set in percentage.| | borderColor10+ | [ResourceColor](ts-types.md#resourcecolor) | No | Border color of the background.
Default value: **Color.Red** | | borderWidth10+ | [Length](ts-types.md#length) | No | Border width of the background.
Default value: **1**
Unit: vp
**NOTE**
This parameter cannot be set in percentage.| ## Attributes -The [universal attributes](ts-universal-attributes-size.md) are supported. +The [universal attributes](ts-component-general-attributes.md) are supported. ## Events -The [universal events](ts-universal-events-click.md) are supported. +The [universal events](ts-component-general-events.md) are supported. ## Example diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-column-sys.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-column-sys.md index 36ae8a10df846a31c5d232e5d0658ec7141cf51b..1895e41419961f575b11c7afd64481d9addaf9ff 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-column-sys.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-column-sys.md @@ -10,7 +10,7 @@ The **Column** component lays out child components vertically. ## Attributes -## pointLight +### pointLight pointLight(value: PointLightStyle) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-column.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-column.md index c5805e71fabd34e7ce8541b172ae8f75638d015b..1b0299f2541596e06fed80fe793210e52ba3dd6e 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-column.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-column.md @@ -14,7 +14,10 @@ Supported ## APIs -Column(value?: {space?: string | number}) +### Column +Column(options?: ColumnOptions) + +Creates a vertical linear layout container. You can set the spacing between child components, which can be of type number or string. **Widget capability**: This API can be used in ArkTS widgets since API version 9. @@ -26,11 +29,70 @@ Column(value?: {space?: string | number}) | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| space | string \| number | No| Vertical spacing between two adjacent child components.
Since API version 9, this parameter does not take effect when it is set to a negative number or when [justifyContent](ts-container-column.md#justifycontent8) is set to **FlexAlign.SpaceBetween**, **FlexAlign.SpaceAround**, or **FlexAlign.SpaceEvenly**.
Default value: **0**
Unit: vp
**NOTE**
The value can be a number greater than or equal to 0 or a string that can be converted to a number.| +| options | [ColumnOptions](#columnoptions14) | No| Vertical spacing between two adjacent child components.| + +### Column16+ +Column(options?: ColumnOptions | ColumnOptionsV2) + +Creates a vertical linear layout container. You can set the spacing between child components, which can be of type number, string, or Resource. + +**Widget capability**: This API can be used in ArkTS widgets since API version 16. + +**Atomic service API**: This API can be used in atomic services since API version 16. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| options | [ColumnOptions](#columnoptions14) \| [ColumnOptionsV2](#columnoptionsv216) | No| Vertical spacing between two adjacent child components.| + +## ColumnOptions14+ + +Defines the spacing properties for child components used for constructing a **Column** component. + +**Widget capability**: This API can be used in ArkTS widgets since API version 14. + +**Atomic service API**: This API can be used in atomic services since API version 14. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| space | string \| number | No| Vertical spacing between two adjacent child components.
This parameter does not take effect if the value specified is a negative number, or if [justifyContent](ts-container-column.md#justifycontent8) is set to **FlexAlign.SpaceBetween**, **FlexAlign.SpaceAround**, or **FlexAlign.SpaceEvenly**
Default value: **0**
Unit: vp
**NOTE**
The value of **space** can be a number greater than or equal to 0 or a string that can be converted to a number.| + +## ColumnOptionsV216+ + +Defines the spacing properties for child components used for constructing a **Column** component. + +**Widget capability**: This API can be used in ArkTS widgets since API version 16. + +**Atomic service API**: This API can be used in atomic services since API version 16. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| space | [SpaceType](#spacetype16) | No| Vertical spacing between two adjacent child components.
This parameter does not take effect if the value specified is a negative number, or if **justifyContent** is set to **FlexAlign.SpaceBetween**, **FlexAlign.SpaceAround**, or **FlexAlign.SpaceEvenly**.
Default value: **0**, in vp
**NOTE**
The value of **space** can be a number greater than or equal to 0, a string that can be converted to a number, or a Resource type that can be converted to a number.| + +## SpaceType16+ + +type SpaceType = number | string | Resource + +Describes the supported data types for the **space** parameter in the constructors of **Row** and **Column** components. The type is a union of the following types. + +|Type|Description| +|---|---| +|number|Represents a numeric value. It can take any numerical value.| +|string|Represents a string value. It can take any string value.| +|[Resource](ts-types.md#resource)|Represents a resource reference type. It can take values from system resources or application resources.| + +**Atomic service API**: This API can be used in atomic services since API version 16. ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### alignItems @@ -96,10 +158,24 @@ Sets whether to reverse the arrangement of child components on the main axis (ve ## Events -The [universal events](ts-universal-events-click.md) are supported. +The [universal events](ts-component-general-events.md) are supported. ## Example +This example demonstrates how to set horizontal layout properties, such as spacing and alignment, using the **Column** component. + +```json +// resources/base/element/string.json +{ + "string": [ + { + "name": "stringSpace", + "value": "5" + } + ] +} +``` + ```ts // xxx.ets @Entry @@ -114,6 +190,13 @@ struct ColumnExample { Column().width('100%').height(30).backgroundColor(0x00FFFF) }.width('90%').height(100).border({ width: 1 }) + // Set the spacing between child elements using the Resource type. + Text('Resource space').width('90%') + Column({ space: $r("app.string.stringSpace") }) { + Column().width('100%').height(30).backgroundColor(0xAFEEEE) + Column().width('100%').height(30).backgroundColor(0x00FFFF) + }.width('90%').height(100).border({ width: 1 }) + // Set the alignment mode of the child components in the horizontal direction. Text('alignItems(Start)').width('90%') Column() { diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-columnsplit.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-columnsplit.md index 93e9b98c057fbae5ee26286a7d88ee988656c344..023488eec96cf7727e545dac97acab7136a36db1 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-columnsplit.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-columnsplit.md @@ -16,6 +16,10 @@ After initialization, if, due to dynamic changes to the [margin](ts-universal-at ColumnSplit() +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + ## Attributes ### resizeable @@ -54,6 +58,8 @@ Margin of the divider. **Atomic service API**: This API can be used in atomic services since API version 11. +**System capability**: SystemCapability.ArkUI.ArkUI.Full + | Name | Type | Mandatory| Description | | ----------- | ------------- | ---- |--------------------------| | startMargin | [Dimension](ts-types.md#dimension10) | No | Distance between the divider and the child component above it.
Default value: **0**| @@ -63,11 +69,13 @@ Margin of the divider. > > Similar to [RowSplit](ts-container-rowsplit.md#rowsplit), the divider of **ColumnSplit** can change the height of the upper and lower child components, but only to the extent that the resultant height falls within the maximum and minimum heights of the child components. > -> Universal attributes such as [clip](ts-universal-attributes-sharp-clipping.md#clip) and [margin](ts-universal-attributes-size.md#margin) are supported. If **clip** is not set, the default value **true** is used. +> Universal attributes such as [clip](ts-universal-attributes-sharp-clipping.md#clip12) and [margin](ts-universal-attributes-size.md#margin) are supported. If **clip** is not set, the default value **true** is used. ## Example +This example demonstrates the basic usage of **ColumnSplit**, which allows you to create draggable, vertically laid-out child components. + ```ts // xxx.ets @Entry diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-counter.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-counter.md index 6fccddc1ebadf56682115992f0bb611e5b7bd3f5..4dabdd7514eb81bba048c9df8b9ceadfedc5f95f 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-counter.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-counter.md @@ -24,7 +24,7 @@ Counter() ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### enableInc10+ @@ -40,7 +40,7 @@ Sets whether to enable the increment button. | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------------- | -| value | boolean | Yes | Whether to enable the increment button.
Default value: **true**| +| value | boolean | Yes | Whether to enable the increment button.
**true** (default): Enable the increment button.
**false**: Disable the increment button.| ### enableDec10+ @@ -56,11 +56,11 @@ Sets whether to enable the decrement button. | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------------- | -| value | boolean | Yes | Whether to enable the decrement button.
Default value: **true**| +| value | boolean | Yes | Whether to enable the decrement button.
**true** (default): Enable the decrement button.
**false**: Disable the decrement button.| ## Events -In addition to the [universal events](ts-universal-events-click.md), the following events are supported. +In addition to the [universal events](ts-component-general-events.md), the following events are supported. ### onInc diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-effectcomponent-sys.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-effectcomponent-sys.md index 0bfe1cf664a5371b04ad25870ea9b369d711f81a..5fdbd977d29ab241f61af56769848001b29e2d55 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-effectcomponent-sys.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-effectcomponent-sys.md @@ -34,6 +34,8 @@ The universal attributes are supported. Currently, this component only works wit ## Example +This example demonstrates how to use the **EffectComponent** component. + ```ts //Index.ets @Entry diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-embedded-component.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-embedded-component.md index 48fc5ae337ad4e967ecd91148b3fa5f50ac9f893..689184390fca6831eeb16636a710d26bbc9d2260 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-embedded-component.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-embedded-component.md @@ -24,16 +24,18 @@ EmbeddedComponent(loader: Want, type: EmbeddedType) **Atomic service API**: This API can be used in atomic services since API version 12. +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory|Description | | --------------------- | ---------------------------------------------------------- | ---- | ------------------------------------ | | loader | [Want](../../apis-ability-kit/js-apis-app-ability-want.md) | Yes | EmbeddedUIExtensionAbility to load.| | type | [EmbeddedType](ts-appendix-enums.md#embeddedtype12) | Yes | Type of the provider. | ## Attributes -The [universal attributes](ts-universal-attributes-size.md) are supported. +The [universal attributes](ts-component-general-attributes.md) are supported. > **NOTE** > @@ -43,7 +45,7 @@ The [universal attributes](ts-universal-attributes-size.md) are supported. Event information related to screen coordinates is converted based on the position, width, and height of the **EmbeddedComponent**, before being transferred to the EmbeddedUIExtensionAbility for processing. -The [universal events](ts-universal-events-click.md) are not supported. Only the following events are supported. +Universal events, such as the [click event](ts-universal-events-click.md), are not supported. Only the following events are supported. ### onTerminated @@ -53,11 +55,13 @@ Called when the started EmbeddedUIExtensionAbility is terminated by calling **te **Atomic service API**: This API can be used in atomic services since API version 12. +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Parameters** -| Name | Type | Description | -| ------- | ------ | ---------------------------------------------------------------------------------------- | -| callback | [Callback](../../apis-basic-services-kit/js-apis-base.md#callback)\<[TerminationInfo](#terminationinfo)> | Callback used to return the result from the EmbeddedUIExtensionAbility.| +| Name | Type | Mandatory| Description | +| ------- | ------ | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| callback | [Callback](../../apis-basic-services-kit/js-apis-base.md#callback)\<[TerminationInfo](#terminationinfo)> | Yes| Callback used to return the result from the EmbeddedUIExtensionAbility.| > **NOTE** > @@ -72,11 +76,13 @@ Called when an error occurs during the running of the started EmbeddedUIExtensio **Atomic service API**: This API can be used in atomic services since API version 12. +**System capability**: SystemCapability.ArkUI.ArkUI.Full + **Parameters** -| Name| Type | Description | -| ------ | ---------------------------------------------------------------------------- | --------- | -| callback | [ErrorCallback](../../apis-basic-services-kit/js-apis-base.md#errorcallback) | Callback used to return the error information of the [BusinessError](../../apis-basic-services-kit/js-apis-base.md#businesserror) type. The error information can be obtained and processed based on the **code**, **name**, and **message** parameters.| +| Name| Type | Mandatory | Description | +| ------ | ---------------------------------------------------------------------------- | --------- | --------- | +| callback | [ErrorCallback](../../apis-basic-services-kit/js-apis-base.md#errorcallback) | Yes| Callback used to return the error information of the [BusinessError](../../apis-basic-services-kit/js-apis-base.md#businesserror) type. The error information can be obtained and processed based on the **code**, **name**, and **message** parameters.| > **NOTE** > @@ -93,19 +99,22 @@ Provides the result returned by the started **EmbeddedUIExtensionAbility**. **Atomic service API**: This API can be used in atomic services since API version 12. -| Name | Type | Description | -| ------- | ------ | --------------------------------------------------- | -| code | number | Result code returned when the EmbeddedUIExtensionAbility exits.| -| want | [Want](../../apis-ability-kit/js-apis-app-ability-want.md) | Data returned when the EmbeddedUIExtensionAbility exits. | +**System capability**: SystemCapability.ArkUI.ArkUI.Full -## Example +### Properties -This example shows the basic usage of the **EmbeddedComponent** and EmbeddedUIExtensionAbility. The bundle name of the sample application is **com.example.embeddeddemo**, and the started EmbeddedUIExtensionAbility is ExampleEmbeddedAbility. +| Name| Type | Mandatory| Description | +| ---- | ---------------------------------------------------------- | ---- | ---------------------------------------------------- | +| code | number | Yes | Result code returned when the EmbeddedUIExtensionAbility exits.| +| want | [Want](../../apis-ability-kit/js-apis-app-ability-want.md) | No| Data returned when the EmbeddedUIExtensionAbility exits. | -- The EntryAbility (UIAbility) of the sample application loads the **pages/Index.ets** file, whose content is as follows: +## Example: Loading an EmbeddedComponent Component + +This example shows the basic usage of the **EmbeddedComponent** and EmbeddedUIExtensionAbility. The bundle name of the sample application is **com.example.embeddeddemo**, and the started EmbeddedUIExtensionAbility in the same application is ExampleEmbeddedAbility. This example only supports devices with multi-process permissions, such as 2-in-1 devices. + +- The EntryAbility (UIAbility) of the sample application loads the **ets/pages/Index.ets** file, whose content is as follows: ```ts - // The UIAbility loads pages/Index.ets when started. import { Want } from '@kit.AbilityKit'; @Entry @@ -124,10 +133,12 @@ This example shows the basic usage of the **EmbeddedComponent** and EmbeddedUIEx EmbeddedComponent(this.want, EmbeddedType.EMBEDDED_UI_EXTENSION) .width('100%') .height('90%') - .onTerminated((info)=>{ + .onTerminated((info) => { + // Triggered when the terminateSelfWithResult button is clicked in the extension page. this.message = 'Termination: code = ' + info.code + ', want = ' + JSON.stringify(info.want); }) - .onError((error)=>{ + .onError((error) => { + // Triggered on failure or exception. this.message = 'Error: code = ' + error.code; }) } @@ -138,14 +149,14 @@ This example shows the basic usage of the **EmbeddedComponent** and EmbeddedUIEx } ``` -- The EmbeddedUIExtensionAbility started by the **EmbeddedComponent** is implemented in the **ets/extensionAbility/ExampleEmbeddedAbility** file. The file content is as follows: +- The EmbeddedUIExtensionAbility (**ExampleEmbeddedAbility**) to start by the **EmbeddedComponent** is implemented in the **ets/extensionAbility/ExampleEmbeddedAbility.ets** file. The file content is as follows: ```ts import { EmbeddedUIExtensionAbility, UIExtensionContentSession, Want } from '@kit.AbilityKit'; const TAG: string = '[ExampleEmbeddedAbility]' + export default class ExampleEmbeddedAbility extends EmbeddedUIExtensionAbility { - onCreate() { console.log(TAG, `onCreate`); } @@ -168,6 +179,7 @@ This example shows the basic usage of the **EmbeddedComponent** and EmbeddedUIEx 'session': session }; let storage: LocalStorage = new LocalStorage(param); + // Load the pages/extension.ets content. session.loadContent('pages/extension', storage); } @@ -177,7 +189,7 @@ This example shows the basic usage of the **EmbeddedComponent** and EmbeddedUIEx } ``` -- The entry page file of the EmbeddedUIExtensionAbility is **pages/extension.ets**, whose content is as follows: +- The entry page file **ets/pages/extension.ets** for **ExampleEmbeddedAbility** (EmbeddedUIExtensionAbility) is as follows. The path to this page must also be configured in the **resources/base/profile/main_pages.json** file. ```ts import { UIExtensionContentSession } from '@kit.AbilityKit'; @@ -196,19 +208,21 @@ This example shows the basic usage of the **EmbeddedComponent** and EmbeddedUIEx .fontSize(20) .fontWeight(FontWeight.Bold) Button("terminateSelfWithResult").fontSize(20).onClick(() => { + // Call terminateSelfWithResult to exit when the button is clicked. this.session?.terminateSelfWithResult({ resultCode: 1, want: { bundleName: "com.example.embeddeddemo", abilityName: "ExampleEmbeddedAbility", - }}); + } + }); }) }.width('100%').height('100%') } } ``` -- Add an item to **extensionAbilities** in the **module.json5** file of the sample application. The details are as follows: +- Add the configuration for **ExampleEmbeddedAbility** under the **extensionAbilities** tag in the **module.json5** file. The type is set to **embeddedUI**, as shown below: ```json { "name": "ExampleEmbeddedAbility", diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-flex-sys.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-flex-sys.md index f273f003f7ddae4eb5c26884ff8bdbc68c4adf63..7a86e0dd68b6456b0c2524949bfec5d33d401bb7 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-flex-sys.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-flex-sys.md @@ -10,7 +10,7 @@ The **Flex** component allows for flexible layout of child components. ## Attributes -## pointLight +### pointLight pointLight(value: PointLightStyle) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-flex.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-flex.md index 52fe9891aadcb8d7021ffbead1bf481e1a5f76b5..fc719e0294b4a32d9d4c1910cd7950517f4535b1 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-flex.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-flex.md @@ -39,21 +39,21 @@ Creates a **Flex** component. Describes the layout and alignment of child components within the **Flex** component. -**Atomic service API**: This API can be used in atomic services since API version 11. - **System capability**: SystemCapability.ArkUI.ArkUI.Full | Name | Type | Mandatory | Description | | -------------- | ---------------------------------------- | ---- | ---------------------------------------- | -| direction | [FlexDirection](ts-appendix-enums.md#flexdirection) | No | Direction in which child components are arranged in the **Flex** component, that is, the direction of the main axis.
Default value: **FlexDirection.Row**
**Widget capability**: This API can be used in ArkTS widgets since API version 9. | -| wrap | [FlexWrap](ts-appendix-enums.md#flexwrap) | No | Whether the **Flex** component has a single line or multiple lines.
Default value: **FlexWrap.NoWrap**
**NOTE**
When wrapped onto multiple lines, the child elements on the new line are stacked in the direction based on the cross axis direction.
**Widget capability**: This API can be used in ArkTS widgets since API version 9.| -| justifyContent | [FlexAlign](ts-appendix-enums.md#flexalign) | No | Alignment mode of the child components in the **Flex** component along the main axis.
Default value: **FlexAlign.Start**
**Widget capability**: This API can be used in ArkTS widgets since API version 9. | -| alignItems | [ItemAlign](ts-appendix-enums.md#itemalign) | No | Alignment mode of the child components in the **Flex** component along the cross axis.
Default value: **ItemAlign.Start**
**Widget capability**: This API can be used in ArkTS widgets since API version 9. | -| alignContent | [FlexAlign](ts-appendix-enums.md#flexalign) | No | Alignment mode of the child components in a multi-row **Flex** component along the cross axis. This parameter is valid only when **wrap** is set to **Wrap** or **WrapReverse**.
Default value: **FlexAlign.Start**
**Widget capability**: This API can be used in ArkTS widgets since API version 9. | +| direction | [FlexDirection](ts-appendix-enums.md#flexdirection) | No | Direction in which child components are arranged in the **Flex** component, that is, the direction of the main axis.
Default value: **FlexDirection.Row**
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| wrap | [FlexWrap](ts-appendix-enums.md#flexwrap) | No | Whether the **Flex** component has a single line or multiple lines.
Default value: **FlexWrap.NoWrap**
**NOTE**
When wrapped onto multiple lines, the child elements on the new line are stacked in the direction based on the cross axis direction.
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| justifyContent | [FlexAlign](ts-appendix-enums.md#flexalign) | No | Alignment mode of the child components in the **Flex** component along the main axis.
Default value: **FlexAlign.Start**
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| alignItems | [ItemAlign](ts-appendix-enums.md#itemalign) | No | Alignment mode of the child components in the **Flex** component along the cross axis.
Default value: **ItemAlign.Start**
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| alignContent | [FlexAlign](ts-appendix-enums.md#flexalign) | No | Alignment mode of the child components in a multi-row **Flex** component along the cross axis. This parameter is valid only when **wrap** is set to **Wrap** or **WrapReverse**.
Default value: **FlexAlign.Start**
**Widget capability**: This API can be used in ArkTS widgets since API version 9.
**Atomic service API**: This API can be used in atomic services since API version 11. | | space12+ | [FlexSpaceOptions12+](ts-container-flex.md#flexspaceoptions12) | No | Spacing between child components along the main axis or cross axis of the **Flex** component.
Default value: **{main:LengthMetrics.px(0), cross:LengthMetrics.px(0)}**
This parameter does not take effect if the value specified is a negative number or percentage, or if **justifyContent** is set to **FlexAlign.SpaceBetween**, **FlexAlign.SpaceAround**, or **FlexAlign.SpaceEvenly**.
**Atomic service API**: This API can be used in atomic services since API version 12.| ## FlexSpaceOptions12+ +Defines the spacing between child components along the main axis or cross axis of the **Flex** component. + **Atomic service API**: This API can be used in atomic services since API version 12. **System capability**: SystemCapability.ArkUI.ArkUI.Full diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-folderstack.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-folderstack.md index f503cda85dc60d85c142f92ee7d45f0a118efe60..42d6cccaf8f257c632bb47b1ce8a4314638596ba 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-folderstack.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-folderstack.md @@ -34,17 +34,17 @@ FolderStack(options?: FolderStackOptions) | Name | Type | Mandatory| Description | | ------------ | -------------------------- | ---- |----------------------------| -| upperItems | Array | No | Configuration of the **FolderStack** component.
**upperItems**: array of IDs of child components that will be moved to the upper half screen in the hover state. On hover, child components with IDs in this array automatically shift away from the folding screen's crease area and move to the upper half screen, while other components are stacked in the lower half screen.| +| upperItems11+ | Array | No | Configuration of the **FolderStack** component.
**upperItems**: array of IDs of child components that will be moved to the upper half screen in the hover state. On hover, child components with IDs in this array automatically shift away from the folding screen's crease area and move to the upper half screen, while other components are stacked in the lower half screen.
**Atomic service API**: This API can be used in atomic services since API version 12.| ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### alignContent alignContent(value: Alignment) -Alignment of child components in the container. When both this attribute and the universal attribute [align](ts-universal-attributes-location.md) are set, whichever is set last takes effect. +Sets the alignment of child components in the container. When both this attribute and the universal attribute [align](ts-universal-attributes-location.md) are set, whichever is set last takes effect. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -60,7 +60,7 @@ Alignment of child components in the container. When both this attribute and the enableAnimation(value: boolean) -Whether to enable the default animation. +Sets whether to enable the default animation. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -94,7 +94,7 @@ Sets whether to enable auto rotation. This attribute is effective only when auto ## Events -In addition to the [universal events](ts-universal-events-click.md), the following events are supported. +In addition to the [universal events](ts-component-general-events.md), the following events are supported. ### onFolderStateChange @@ -117,7 +117,7 @@ Called when the folding state changes. This API takes effect only in landscape m onHoverStatusChange(handler: OnHoverStatusChangeCallback) -Invoked when the hover status changes. +Called when the hover status changes. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -168,7 +168,7 @@ Called when the folding state changes. This API takes effect only in landscape m | Name | Type | Mandatory| Description | | ---------- | ----------------------------------------------- | ---- | -------------------- | -| foldStatus | [FoldStatus](ts-appendix-enums.md#foldstatus11) | Yes | Current fold state of the device.| +| foldStatus11+ | [FoldStatus](ts-appendix-enums.md#foldstatus11) | Yes | Current fold state of the device.
**Atomic service API**: This API can be used in atomic services since API version 12.| ## HoverEventParam12+ @@ -181,7 +181,7 @@ Called when the folding state changes. This API takes effect only in landscape m | foldStatus | [FoldStatus](ts-appendix-enums.md#foldstatus11) | Yes | Current fold state of the device.| | isHoverMode | boolean | Yes | Whether the device is in hover state. | | appRotation | [AppRotation](ts-appendix-enums.md#approtation12) | Yes | Current orientation. | -| windowStatusType | [WindowStatusType12+](#windowstatustype12) | Yes | Window mode. | +| windowStatusType | [WindowStatusType](#windowstatustype12) | Yes | Window mode. | ## WindowStatusType12+ diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-formlink.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-formlink.md index 64ebc6baac82a749c906a04bd33afadb4ce233bd..583a8c5cbe75519b4543a48c55cc01024eacbd19 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-formlink.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-formlink.md @@ -50,11 +50,11 @@ FormLink(options: FormLinkOptions) ## Attributes -The [universal attributes](ts-universal-attributes-size.md) are supported. +The [universal attributes](ts-component-general-attributes.md) are supported. ## Events -The [universal events](ts-universal-events-click.md) are not supported. +The [universal events](ts-component-general-events.md) are not supported. ## Example diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-grid.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-grid.md index eb3f0a5eca1c9bf27cbf42430bf38cff96ba3fad..cbcb1f941d50eb68eca4ea9fa80c2ef6ef76e844 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-grid.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-grid.md @@ -35,6 +35,8 @@ Only the [GridItem](ts-container-griditem.md) child component is allowed, with s Grid(scroller?: Scroller, layoutOptions?: GridLayoutOptions) +Creates a **Grid** component. + **Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -43,17 +45,15 @@ Grid(scroller?: Scroller, layoutOptions?: GridLayoutOptions) | Name | Type | Mandatory| Description | | -------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | -| scroller | [Scroller](ts-container-scroll.md#scroller) | No | Controller, which can be bound to scrollable components.
**NOTE**
The scroller cannot be bound to other scrollable components, such as [List](ts-container-list.md), [Grid](ts-container-grid.md), or [Scroll](ts-container-scroll.md).| +| scroller | [Scroller](ts-container-scroll.md#scroller) | No | Controller, which can be bound to scrollable components.
**NOTE**
The scroller cannot be bound to other scrollable components, such as [ArcList](ts-container-arclist.md), [List](ts-container-list.md), [Grid](ts-container-grid.md), or [Scroll](ts-container-scroll.md).| | layoutOptions10+ | [GridLayoutOptions](#gridlayoutoptions10) | No| Grid layout options.| ## GridLayoutOptions10+ -**Atomic service API**: This API can be used in atomic services since API version 11. +Defines the grid layout options. In this API, **irregularIndexes** and **onGetIrregularSizeByIndex** can be used for grids where either **rowsTemplate** or **columnsTemplate** is set. These properties allow you to specify an index array and set the number of rows and columns to be occupied by a grid item at the specified index. For details about the usage, see [Example 3](#example-3-implementing-a-scrollable-grid-with-grid-items-spanning-rows-and-columns). On the other hand, **onGetRectByIndex** can be used for grids where both **rowsTemplate** and **columnsTemplate** are set. It allows you to specify the position and size for the grid item at the specified index. For details about the usage, see [Example 1](#example-1-creating-a-fixed-row-and-column-grid-layout). **System capability**: SystemCapability.ArkUI.ArkUI.Full -Defines the layout options. In this API, **irregularIndexes** and **onGetIrregularSizeByIndex** can be used for grids where either **rowsTemplate** or **columnsTemplate** is set. You can specify an index array and set the number of rows and columns to be occupied by a grid item with the specified index. For details, see Example 3. **onGetRectByIndex** can be used for grids where both **rowsTemplate** and **columnsTemplate** are set. It specifies the position and size for the grid item with the specified index. For details, see Example 1. - | Name | Type | Mandatory | Description | | ----- | ------- | ---- | --------------------- | | regularSize | [number, number] | Yes | Number of rows and columns occupied by a grid item with regular size. The only supported value is **[1, 1]**, meaning that the grid item occupies one row and one column.
**Atomic service API**: This API can be used in atomic services since API version 11. | @@ -63,7 +63,7 @@ Defines the layout options. In this API, **irregularIndexes** and **onGetIrregul ## Attributes -In addition to [universal attributes](ts-universal-attributes-size.md) and [scrollable component common attributes](ts-container-scrollable-common.md#attributes), the following attributes are also supported. +In addition to [universal attributes](ts-component-general-attributes.md) and [scrollable component common attributes](ts-container-scrollable-common.md#attributes), the following attributes are also supported. ### columnsTemplate @@ -82,7 +82,7 @@ For example, **'1fr 1fr 2fr'** indicates three columns, with the first column ta **repeat**, **auto-fit**, **auto-fill**, and **auto-stretch** are keywords. **track-size** indicates the column width, in the unit of px, vp (default), %, or any valid digit. The value must be greater than or equal to one valid column width.
In **auto-stretch** mode, **track-size** must be a valid column width value, in the unit of px, vp, or any valid digit; percentage values (%) are not supported. -For visual reference, see [Example 8](#example-8). +For details about the effect, see [Example 8](#example-8-using-adaptive-column-count-settings). If this attribute is set to **'0fr'**, the column width is 0, and grid item in the column is not displayed. If this attribute is set to any other invalid value, the grid item is displayed as one column. @@ -170,7 +170,7 @@ Sets the gap between columns. A value less than 0 evaluates to the default value | Name| Type | Mandatory| Description | | ------ | ---------------------------- | ---- | ---------------------------- | -| value | [Length](ts-types.md#length) | Yes | Gap between columns.
Default value: **0**| +| value | [Length](ts-types.md#length) | Yes | Gap between columns.
Default value: **0**
Value range: [0, +∞).| ### rowsGap @@ -186,7 +186,7 @@ Sets the gap between rows. A value less than 0 evaluates to the default value. | Name| Type | Mandatory| Description | | ------ | ---------------------------- | ---- | ---------------------------- | -| value | [Length](ts-types.md#length) | Yes | Gap between rows.
Default value: **0**| +| value | [Length](ts-types.md#length) | Yes | Gap between rows.
Default value: **0**
Value range: [0, +∞).| ### scrollBar @@ -218,7 +218,7 @@ Sets the scrollbar color. | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | -------------- | -| value | [Color](ts-appendix-enums.md#color) \| number \| string | Yes | Scrollbar color.
Default value: **'\#182431'** (40% opacity)| +| value | [Color](ts-appendix-enums.md#color) \| number \| string | Yes | Scrollbar color.
Default value: **'\#182431'** (40% opacity)
A number value indicates a HEX color in RGB or ARGB format, for example, **0xffffff**. A string value indicates a color in RGB or ARGB format, for example, **'#ffffff'**.| ### scrollBarWidth @@ -234,13 +234,13 @@ Sets the scrollbar width. This attribute cannot be set in percentage. After the | Name| Type | Mandatory| Description | | ------ | -------------------------- | ---- | ----------------------------------------- | -| value | number \| string | Yes | Scrollbar width.
Default value: **4**
Unit: vp| +| value | number \| string | Yes | Scrollbar width.
Default value: **4**
Unit: vp
If this parameter is set to a value less than or equal to 0, the default value is used. The value **0** means not to show the scrollbar.| ### cachedCount cachedCount(value: number) -Sets the number of grid items to be cached (preloaded). It works only in [LazyForEach](../../../quick-start/arkts-rendering-control-lazyforeach.md) and [Repeat](../../../quick-start/arkts-new-rendering-control-repeat.md) with the **virtualScroll** option enabled. A value less than 0 evaluates to the default value. For details, see [Minimizing White Blocks During Swiping](../../../performance/arkts-performance-improvement-recommendation.md#minimizing-white-blocks-during-swiping). +Sets the number of grid items to be cached (preloaded). It works only in [LazyForEach](../../../quick-start/arkts-rendering-control-lazyforeach.md) and [Repeat](../../../quick-start/arkts-new-rendering-control-repeat.md) with the **virtualScroll** option enabled. For details, see [Minimizing White Blocks During Swiping](../../../performance/arkts-performance-improvement-recommendation.md#minimizing-white-blocks-during-swiping). The number of the grid items to be cached before and after the currently displayed one equals the value of **cachedCount** multiplied by the number of columns. @@ -252,9 +252,9 @@ In [LazyForEach](../../../quick-start/arkts-rendering-control-lazyforeach.md) an **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | -------------------------------------- | -| value | number | Yes | Number of grid items to be cached (preloaded).
Default value: **1**| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| value | number | Yes | Number of grid items to be cached (preloaded).
Default value: the number of rows visible on the screen for vertical scrolling, or the number of columns visible on the screen for horizontal scrolling. The maximum value is 16.
Value range: [0, +∞).
Values less than 0 are treated as **1**.| ### cachedCount14+ @@ -262,7 +262,7 @@ cachedCount(count: number, show: boolean) Sets the number of grid items to be cached (preloaded) and specifies whether to display the preloaded nodes. -The number of the grid items to be preloaded before and after the currently displayed one equals the value of **cachedCount** multiplied by the number of columns. This attribute can be combined with the [clip](ts-universal-attributes-sharp-clipping.md#clip12) or [content clipping](ts-container-scrollable-common.md#clipcontent14) attributes to display the preloaded nodes. +The number of the grid items to be cached before and after the currently displayed one equals the value of **cachedCount** multiplied by the number of columns. This attribute can be combined with the [clip](ts-universal-attributes-sharp-clipping.md#clip12) or [content clipping](ts-container-scrollable-common.md#clipcontent14) attributes to display the preloaded nodes. **Atomic service API**: This API can be used in atomic services since API version 14. @@ -272,8 +272,8 @@ The number of the grid items to be preloaded before and after the currently disp | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------------- | -| count | number | Yes | Number of grid items to be preloaded.
Default value: **1**| -| show | boolean | Yes | Whether to display the preloaded nodes.
Default value: **false**| +| count | number | Yes | Number of grid items to be cached (preloaded).
Default value: the number of rows visible on the screen for vertical scrolling, or the number of columns visible on the screen for horizontal scrolling. The maximum value is 16.
Value range: [0, +∞).
Values less than 0 are treated as **1**.| +| show | boolean | Yes | Whether to display the preloaded nodes.
Default value: **false** (the preloaded nodes are not displayed).| ### editMode8+ @@ -289,13 +289,13 @@ Sets whether to enable edit mode. In edit mode, the user can drag the [grid item | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------------------------------- | -| value | boolean | Yes | Whether to enable edit mode.
Default value: **false**| +| value | boolean | Yes | Whether to enable edit mode.
Default value: **false** (the edit mode is disabled).| ### layoutDirection8+ layoutDirection(value: GridDirection) -Sets the main axis direction of the grid. +Sets the main axis layout direction of the grid. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -305,7 +305,7 @@ Sets the main axis direction of the grid. | Name| Type | Mandatory| Description | | ------ | ---------------------------------------- | ---- | ---------------------------------------------- | -| value | [GridDirection](#griddirection8) | Yes | Main axis direction of the grid.
Default value: **GridDirection.Row**| +| value | [GridDirection](#griddirection8) | Yes | Main axis layout direction of the grid.
Default value: **GridDirection.Row**| ### maxCount8+ @@ -339,6 +339,8 @@ When **layoutDirection** is **Row** or **RowReverse**, the value indicates the m When **layoutDirection** is **Column** or **ColumnReverse**, the value indicates the minimum number of rows that can be displayed. +If the value of **minCount** is greater than that of **maxCount**, both **minCount** and **maxCount** are treated as using their default values. + **Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -367,13 +369,13 @@ When **layoutDirection** is **Column** or **ColumnReverse**, the value indicates | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------- | -| value | number | Yes | Height per row or width per column.
Default value: size of the first element
Unit: vp| +| value | number | Yes | Height per row or width per column.
Default value: size of the first element
Unit: vp
Value range: [0, +∞).
If a value less than 0 is set, the default value is used.| ### multiSelectable8+ multiSelectable(value: boolean) -Sets whether to enable multiselect. When multiselect is enabled, you can use the **selected** attribute and **onSelect** event to obtain the selected status of grid items; you can also set the [style](./ts-universal-attributes-polymorphic-style.md) for the selected state (by default, no style is set for the selected state). +Whether to enable multiselect. When multiselect is enabled, you can use the **selected** attribute and **onSelect** event to obtain the selected status of grid items; you can also set the [style](./ts-universal-attributes-polymorphic-style.md) for the selected state (by default, no style is set for the selected state). **Atomic service API**: This API can be used in atomic services since API version 11. @@ -399,7 +401,7 @@ Sets whether to enable animation. Currently, the grid item drag animation is sup | Name| Type | Mandatory| Description | | ------ | ------- | ---- | -------------------------------- | -| value | boolean | Yes | Whether to enable animation.
Default value: **false**| +| value | boolean | Yes | Whether to enable animation.
Default value: **false** (animation is disabled).| ### edgeEffect10+ @@ -454,7 +456,7 @@ Sets the nested scrolling options. You can set the nested scrolling mode in the friction(value: number | Resource) -Sets the friction coefficient. It applies only to gestures in the scrolling area, and it affects only indirectly the scroll chaining during the inertial scrolling process. A value less than or equal to 0 evaluates to the default value. +Sets the friction coefficient. It applies only to gestures in the scrolling area, and it affects only indirectly the scroll chaining during the inertial scrolling process. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -464,13 +466,13 @@ Sets the friction coefficient. It applies only to gestures in the scrolling area | Name| Type | Mandatory| Description | | ------ | ---------------------------------------------------- | ---- | ----------------------------------------------------------- | -| value | number \| [Resource](ts-types.md#resource) | Yes | Friction coefficient.
Default value: **0.9** for wearable devices and **0.6** for non-wearable devices
Since API version 11, the default value for non-wearable devices is **0.7**.
Since API version 12, the default value for non-wearable devices is **0.75**.| +| value | number \| [Resource](ts-types.md#resource) | Yes | Friction coefficient.
Default value: **0.9** for wearable devices and **0.6** for non-wearable devices
Since API version 11, the default value for non-wearable devices is **0.7**.
Since API version 12, the default value for non-wearable devices is **0.75**.
Value range: (0, +∞). If this parameter is set to a value less than or equal to 0, the default value is used.| ### alignItems12+ alignItems(alignment: Optional\) -Sets the alignment mode of grid items in the grid. For details, see [Example 9](#example-9). +Sets the alignment mode of grid items in the grid. For details about the usage, see [Example 9](#example-9-setting-grid-item-heights-based-on-the-tallest-item-in-the-current-row). **Atomic service API**: This API can be used in atomic services since API version 12. @@ -484,6 +486,8 @@ Sets the alignment mode of grid items in the grid. For details, see [Example 9]( ## GridItemAlignment12+ +Enumerates the alignment modes of grid items. + **Atomic service API**: This API can be used in atomic services since API version 12. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -503,6 +507,8 @@ Sets the alignment mode of grid items in the grid. For details, see [Example 9]( ## GridDirection8+ +Enumerates the main axis layout directions. + **Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -520,7 +526,7 @@ Sets the alignment mode of grid items in the grid. For details, see [Example 9]( ## Events -In addition to [universal events](ts-universal-events-click.md) and [scrollable component common events](ts-container-scrollable-common.md#events), the following events are also supported. +In addition to [universal events](ts-component-general-events.md) and [scrollable component common events](ts-container-scrollable-common.md#events), the following events are also supported. ### onScrollIndex @@ -615,7 +621,9 @@ Triggered when the dragged item leaves the drop target of the grid. onItemDrop(event: (event: ItemDragInfo, itemIndex: number, insertIndex: number, isSuccess: boolean) => void) -Triggered when the dragged item is dropped on the drop target of the grid. +Triggered when the dragged grid item is dropped on the drop target of the grid. + +**isSuccess** returns **true** if the grid item is dropped within the grid, and returns **false** otherwise. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -634,7 +642,7 @@ Triggered when the dragged item is dropped on the drop target of the grid. onScrollBarUpdate(event: (index: number, offset: number) => ComputedBarAttribute) -Triggered when the first item displayed in the grid changes. You can use the callback to set the position and length of the scrollbar. +Triggered at the end of each frame layout in the grid. You can use the callback to set the position and length of the scrollbar. This API is intended solely for setting the scroll position of the grid. Avoid implementing service logic within this API. @@ -727,7 +735,9 @@ onScroll(event: (scrollOffset: number, scrollState: [ScrollState](ts-container-l Triggered when the grid scrolls. -This API is supported since API version 10 and deprecated since API version 12. You are advised to use [onDidScroll](ts-container-scrollable-common.md#ondidscroll12) instead. +This API is available since API version 10. + +This API is deprecated since API version 12. You are advised to use [onDidScroll](ts-container-scrollable-common.md#ondidscroll12) instead. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -742,6 +752,8 @@ This API is supported since API version 10 and deprecated since API version 12. ## ComputedBarAttribute10+ +Provides information about the position and length of the scrollbar. + **Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -753,9 +765,9 @@ This API is supported since API version 10 and deprecated since API version 12. ## Example -### Example 1 +### Example 1: Creating a Fixed Row and Column Grid Layout -This example shows a grid with fixed number of rows and columns, for which you can use **onGetRectByIndex** in **GridLayoutOptions** to specify the position and size of grid items. +This example demonstrates how to use **onGetRectByIndex** in **GridLayoutOptions** to define the position and size of each grid item. ```ts // xxx.ets @@ -837,7 +849,7 @@ struct GridExample { ![en-us_image_0000001219744183](figures/en-us_image_0000001219744183.gif) -### Example 2 +### Example 2: Implementing a Scrollable Grid with Scroll Events This example shows a scrollable grid with all its scrolling attributes and events specified. @@ -919,9 +931,9 @@ struct GridExample { ![scrollerExample2](figures/scrollerExample2.gif) -### Example 3 +### Example 3: Implementing a Scrollable Grid with Grid Items Spanning Rows and Columns -This example uses **irregularIndexes** and **onGetIrregularSizeByIndex** in **GridLayoutOptions**. +This example shows how to use **irregularIndexes** and **onGetIrregularSizeByIndex** in **GridLayoutOptions** to define custom sizes and spans for grid items. ```ts // xxx.ets @@ -932,12 +944,12 @@ struct GridExample { scroller: Scroller = new Scroller() layoutOptions1: GridLayoutOptions = { regularSize: [1, 1], // Only [1, 1] is supported. - irregularIndexes: [0, 6], // The grid item whose indexes are 0 and 6 occupies one row. + irregularIndexes: [0, 6], // The grid item whose indexes are 0 and 6 occupies one row. } layoutOptions2: GridLayoutOptions = { regularSize: [1, 1], - irregularIndexes: [0, 7], // The number of columns occupied by the grid item whose indexes are 0 and 7 is specified by onGetIrregularSizeByIndex. + irregularIndexes: [0, 7], // The number of columns occupied by the grid item whose indexes are 0 and 7 is specified by onGetIrregularSizeByIndex. onGetIrregularSizeByIndex: (index: number) => { if (index === 0) { return [1, 5] @@ -1001,9 +1013,9 @@ struct GridExample { ![gridLayoutOptions](figures/gridLayoutOptions.gif) -### Example 4 +### Example 4: Implementing Nested Scrolling in a Grid -Example of using **nestedScroll** and **onScrollFrameBegin**: +This example illustrates how to implement nested scrolling in a grid, using **nestedScroll** and **onScrollFrameBegin**: ```ts @Entry @@ -1177,7 +1189,7 @@ struct GridExample { ![nestedScrollExample4](figures/nestedScrollExample4.gif) -### Example 5 +### Example 5: Implementing Dragging in a Grid 1. Set **editMode\(true\)** to enable edit mode, where the user can drag the grid items. 2. In the [onItemDragStart](#onitemdragstart8) callback, set the image to be displayed during dragging. @@ -1271,9 +1283,9 @@ Below shows how the grid looks after grid item 1 and grid item 6 swap their posi ![gridDrag](figures/gridDrag2.png) -### Example 6 +### Example 6: Implementing Adaptive Grid Layout -Example of using **layoutDirection**, **maxcount**, **minCount**, and **cellLength**: +This example demonstrates the use of **layoutDirection**, **maxcount**, **minCount**, and **cellLength**: ```ts @Entry @@ -1318,7 +1330,7 @@ struct GridExample { ![cellLength](figures/cellLength.gif) -### Example 7 +### Example 7: Dynamically Adjusting the Number of Grid Columns with a Pinch Gesture This example demonstrates how to adjust the number of columns in the grid with a pinch gesture using two fingers. @@ -1394,8 +1406,8 @@ struct GridExample { ![pinch](figures/grid-pinch.gif) -### Example 8 -This example shows the usage of **auto-fill**, **auto-fit**, and **auto-stretch** in the [columnsTemplate](#columnstemplate) attribute. +### Example 8: Using Adaptive Column Count Settings +This example shows the usage of **auto-fill**, **auto-fit**, and **auto-stretch** in [columnsTemplate](#columnstemplate). ```ts @Entry @@ -1463,10 +1475,10 @@ struct GridColumnsTemplate { ![gridColumnsTemplate](figures/gridColumnsTemplate.png) -### Example 9 +### Example 9: Setting Grid Item Heights Based on the Tallest Item in the Current Row This example implements a grid that contains two columns. The grid item in each column consists of two **Column** components with determined heights and one **Text** component with an undetermined height. -By default, the heights of the left and right grid items may differ; however, after the grid's **alignItems** attribute is set to **GridItemAlignment.STRETCH**, the grid item with a shorter height in a row will adopt the height of the taller grid item, aligning their heights within the same row. +By default, the heights of the left and right grid items may differ; however, after the grid's [alignItems](#alignitems12) attribute is set to **GridItemAlignment.STRETCH**, the grid item with a shorter height in a row will adopt the height of the taller grid item, aligning their heights within the same row. ```ts @Entry @@ -1525,7 +1537,8 @@ struct Index { ``` ![gridAlignItems](figures/gridAlignItems.png) -### Example 10 +### Example 10: Setting Edge Fading +This example demonstrates how to enable the edge fading effect using [fadingEdge](ts-container-scrollable-common.md#fadingedge14). ```ts // xxx.ets @@ -1566,4 +1579,48 @@ struct GridExample { } ``` -![fadingEdge_grid](figures/fadingEdge_grid.gif) \ No newline at end of file +![fadingEdge_grid](figures/fadingEdge_grid.gif) + +### Example 11: Setting the Single-Side Edge Effect + +This example demonstrates how to set a single-side edge effect for the **Grid** component using the **edgeEffect** API. + +```ts +// xxx.ets +@Entry +@Component +struct GridExample { + @State numbers: String[] = ['0', '1', '2', '3', '4'] + @State rowNumbers: String[] = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] + scroller: Scroller = new Scroller() + + build() { + Column({ space: 5 }) { + Grid(this.scroller) { + ForEach(this.rowNumbers, (day: string) => { + ForEach(this.numbers, (day: string) => { + GridItem() { + Text(day) + .fontSize(16) + .backgroundColor(0xF9CF93) + .width('100%') + .height(80) + .textAlign(TextAlign.Center) + } + }, (day: string) => day) + }, (day: string) => day) + } + .columnsTemplate('1fr 1fr 1fr 1fr 1fr') + .columnsGap(10) + .rowsGap(20) + .edgeEffect(EdgeEffect.Spring,{alwaysEnabled:true,effectEdge:EffectEdge.START}) + .width('90%') + .backgroundColor(0xDCDCDC) + .height('80%') + + }.width('100%').margin({ top: 5 }) + } +} +``` + +![edgeEffect_grid](figures/edgeEffect_grid.gif) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-gridcol.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-gridcol.md index 0482637dcd2944b482d54415fdff0207c9c348d0..4cfacf0764e99a688c23e14ec17fcb9f0b489aa4 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-gridcol.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-gridcol.md @@ -13,6 +13,8 @@ This component can contain only one child component. GridCol(option?: GridColOptions) +Creates a **GridCol** component. + **Widget capability**: This API can be used in ArkTS widgets since API version 9. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -22,10 +24,12 @@ GridCol(option?: GridColOptions) **Parameters** | Name| Type | Mandatory| Description | | ------ | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | -| option | [GridColOptions](#gridcoloptions) | No | Child component options of the grid layout.| +| option | [GridColOptions](#gridcoloptions) | No | Options of the **GridCol** component.| ## GridColOptions +Defines the options of the **GridCol** component. + **Widget capability**: This API can be used in ArkTS widgets since API version 9. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -34,14 +38,14 @@ GridCol(option?: GridColOptions) | Name| Type | Mandatory| Description | | ------ | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | -| span | number \| [GridColColumnOption](#gridcolcolumnoption) | No | Number of columns occupied by the component. If it is set to **0**, the component is not involved in layout calculation, that is, the component is not rendered.
Default value: **1**| -| offset | number \| [GridColColumnOption](#gridcolcolumnoption) | No | Number of offset columns relative to the original position of the component.
Default value: **0** | -| order | number \| [GridColColumnOption](#gridcolcolumnoption) | No | Sequence number of the component. Child components of the grid are sorted in ascending order based on their sequence numbers.
Default value: **0**
**NOTE**
If a child component shares an **order** value with another child component or does not have **order** set, it is displayed based on its code sequence number.
If **order** is not set for all child components, those that have **order** set are displayed after those that do not and are sorted in ascending order based on the value.| +| span | number \| [GridColColumnOption](#gridcolcolumnoption) | No | Number of columns occupied by the component. If it is set to **0**, the component is not involved in layout calculation, that is, the component is not rendered.
The value is an integer greater than 0.
Default value: **1**.| +| offset | number \| [GridColColumnOption](#gridcolcolumnoption) | No | Number of offset columns relative to the original position of the component.
The value is an integer greater than 0.
Default value: **0**. | +| order | number \| [GridColColumnOption](#gridcolcolumnoption) | No | Sequence number of the component. Child components of the grid are sorted in ascending order based on their sequence numbers.
The value is an integer greater than 0.
Default value: **0**.
**NOTE**
If a child component shares an **order** value with another child component or does not have **order** set, it is displayed based on its code sequence number.
If **order** is not set for all child components, those that have **order** set are displayed after those that do not and are sorted in ascending order based on the value.| The values of `span`, `offset`, and `order` attributes are inherited in the sequence of **xs**, **sm**, **md**, **lg**, **xl**, and **xxl**. If no value is set for a breakpoint, the value is obtained from the previous breakpoint. ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### span @@ -59,7 +63,7 @@ Sets the number of columns occupied by the component. If it is set to **0**, the | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------ | -| value | number \| [GridColColumnOption](#gridcolcolumnoption) | Yes | Number of occupied columns.
Default value: **1**| +| value | number \| [GridColColumnOption](#gridcolcolumnoption) | Yes | Number of occupied columns.
The value is an integer greater than 0.
Default value: **1**.| ### gridColOffset @@ -77,7 +81,7 @@ Sets the number of offset columns relative to the original position of the compo | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------ | -| value | number \| [GridColColumnOption](#gridcolcolumnoption) | Yes | Number of offset columns relative to the previous child component of the grid
Default value: **0**| +| value | number \| [GridColColumnOption](#gridcolcolumnoption) | Yes | Number of offset columns relative to the previous child component of the grid
The value is an integer greater than 0.
Default value: **0**.| ### order @@ -95,7 +99,7 @@ Sets the sequence number of the component. Child components of the grid are sort | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| value | number \| [GridColColumnOption](#gridcolcolumnoption) | Yes | Sequence number of the component. Child components of the grid are sorted in ascending order based on their sequence numbers.
Default value: **0**| +| value | number \| [GridColColumnOption](#gridcolcolumnoption) | Yes | Sequence number of the component. Child components of the grid are sorted in ascending order based on their sequence numbers.
The value is an integer greater than 0.
Default value: **0**.| ## GridColColumnOption @@ -117,4 +121,4 @@ Describes the numbers of grid columns occupied by the **GridCol** component on d | xxl | number | No | Number of grid columns on the device where the grid size is xxl. | ## Example -See [GridRow](ts-container-gridrow.md#example). +See the example for [GridRow](ts-container-gridrow.md#example). diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-gridcontainer.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-gridcontainer.md index e7eff1af7430e290f32f8f18717da7393f0a8954..e93f3018947909b09071d0c868911b40b9f13d56 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-gridcontainer.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-gridcontainer.md @@ -52,12 +52,12 @@ GridContainer(value?: GridContainerOptions) ## Attributes -The universal attributes and attributes of the [Column](ts-container-column.md#attributes) component are supported. +The [universal attributes](ts-component-general-attributes.md) and attributes of the [Column](ts-container-column.md#attributes) component are supported. ## Events -The universal events are supported. +The [universal events](ts-component-general-events.md) are supported. ## Example diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-griditem.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-griditem.md index 27eb3ce563c0609d740778adcb145f87e0aad0dc..6fc5847bcbc7d9d66ab402d2cf8603162e92334f 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-griditem.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-griditem.md @@ -17,6 +17,8 @@ This component can contain a single child component. GridItem(value?: GridItemOptions) +Creates a **GridItem** component. + **Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -43,7 +45,7 @@ Sets the start row number of the component. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------ | -| value | number | Yes | Start row number of the component.
In situations where you need to designate the start row and column numbers as well as the number of rows and columns a grid item spans, you are advised to use the [layoutOptions parameter](ts-container-grid.md#gridlayoutoptions10) of the **Grid** component. For reference, see [Grid Example 1](ts-container-grid.md#example-1) and [Grid Example 3](ts-container-grid.md#example-3).| +| value | number | Yes | Start row number of the component.
In situations where you need to designate the start row and column numbers as well as the number of rows and columns a grid item spans, you are advised to use the [layoutOptions parameter](ts-container-grid.md#gridlayoutoptions10) of the **Grid** component. For reference, see [Grid Example 1](ts-container-grid.md#example-1-creating-a-fixed-row-and-column-grid-layout) and [Grid Example 3](ts-container-grid.md#example-3-implementing-a-scrollable-grid-with-grid-items-spanning-rows-and-columns).| ### rowEnd @@ -59,7 +61,7 @@ Sets the end row number of the component. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------ | -| value | number | Yes | End row number of the component.
In situations where you need to designate the start row and column numbers as well as the number of rows and columns a grid item spans, you are advised to use the [layoutOptions parameter](ts-container-grid.md#gridlayoutoptions10) of the **Grid** component. For reference, see [Grid Example 1](ts-container-grid.md#example-1) and [Grid Example 3](ts-container-grid.md#example-3).| +| value | number | Yes | End row number of the component.
In situations where you need to designate the start row and column numbers as well as the number of rows and columns a grid item spans, you are advised to use the [layoutOptions parameter](ts-container-grid.md#gridlayoutoptions10) of the **Grid** component. For reference, see [Grid Example 1](ts-container-grid.md#example-1-creating-a-fixed-row-and-column-grid-layout) and [Grid Example 3](ts-container-grid.md#example-3-implementing-a-scrollable-grid-with-grid-items-spanning-rows-and-columns).| ### columnStart @@ -75,7 +77,7 @@ Sets the start column number of the component. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------ | -| value | number | Yes | Start column number of the component.
In situations where you need to designate the start row and column numbers as well as the number of rows and columns a grid item spans, you are advised to use the [layoutOptions parameter](ts-container-grid.md#gridlayoutoptions10) of the **Grid** component. For reference, see [Grid Example 1](ts-container-grid.md#example-1) and [Grid Example 3](ts-container-grid.md#example-3).| +| value | number | Yes | Start column number of the component.
In situations where you need to designate the start row and column numbers as well as the number of rows and columns a grid item spans, you are advised to use the [layoutOptions parameter](ts-container-grid.md#gridlayoutoptions10) of the **Grid** component. For reference, see [Grid Example 1](ts-container-grid.md#example-1-creating-a-fixed-row-and-column-grid-layout) and [Grid Example 3](ts-container-grid.md#example-3-implementing-a-scrollable-grid-with-grid-items-spanning-rows-and-columns).| ### columnEnd @@ -91,11 +93,11 @@ Sets the end column number of the component. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------ | -| value | number | Yes | End column number of the component.
In situations where you need to designate the start row and column numbers as well as the number of rows and columns a grid item spans, you are advised to use the [layoutOptions parameter](ts-container-grid.md#gridlayoutoptions10) of the **Grid** component. For reference, see [Grid Example 1](ts-container-grid.md#example-1) and [Grid Example 3](ts-container-grid.md#example-3).| +| value | number | Yes | End column number of the component.
In situations where you need to designate the start row and column numbers as well as the number of rows and columns a grid item spans, you are advised to use the [layoutOptions parameter](ts-container-grid.md#gridlayoutoptions10) of the **Grid** component. For reference, see [Grid Example 1](ts-container-grid.md#example-1-creating-a-fixed-row-and-column-grid-layout) and [Grid Example 3](ts-container-grid.md#example-3-implementing-a-scrollable-grid-with-grid-items-spanning-rows-and-columns).| > **NOTE** > -> In situations where you need to designate the start row and column numbers as well as the number of rows and columns a grid item spans, you are advised to use the [layoutOptions parameter](ts-container-grid.md#gridlayoutoptions10) of the **Grid** component. For reference, see [Grid Example 1](ts-container-grid.md#example-1) and [Grid Example 3](ts-container-grid.md#example-3). +> In situations where you need to designate the start row and column numbers as well as the number of rows and columns a grid item spans, you are advised to use the [layoutOptions parameter](ts-container-grid.md#gridlayoutoptions10) of the **Grid** component. For reference, see [Grid Example 1](ts-container-grid.md#example-1-creating-a-fixed-row-and-column-grid-layout) and [Grid Example 3](ts-container-grid.md#example-3-implementing-a-scrollable-grid-with-grid-items-spanning-rows-and-columns). > > Rules for setting **rowStart**, **rowEnd**, **columnStart**, and **columnEnd**: > @@ -169,6 +171,8 @@ This attribute must be used before the [style for the selected state](./ts-unive ## GridItemOptions11+ +Defines the style of a grid item. + **Atomic service API**: This API can be used in atomic services since API version 12. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -179,6 +183,8 @@ This attribute must be used before the [style for the selected state](./ts-unive ## GridItemStyle11+ +Enumerates styles of grid items. + **Atomic service API**: This API can be used in atomic services since API version 12. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -212,7 +218,8 @@ Triggered when the selected state of the grid item changes. ## Example -### Example 1 +### Example 1: Setting the Grid Item Position +This example shows how to set the grid item position using **ColumnStart**, **ColumnEnd**, **RowStart**, and **RowEnd**. In situations where you need to designate the start row and column numbers as well as the number of rows and columns a grid item spans, you are advised to use the [layoutOptions parameter](ts-container-grid.md#gridlayoutoptions10) of the **Grid** component. For reference, see [Grid Example 1](ts-container-grid.md#example-1-creating-a-fixed-row-and-column-grid-layout) and [Grid Example 3](ts-container-grid.md#example-3-implementing-a-scrollable-grid-with-grid-items-spanning-rows-and-columns). ```ts // xxx.ets @@ -263,9 +270,9 @@ struct GridItemExample { ![en-us_image_0000001174582870](figures/en-us_image_0000001174582870.gif) -### Example 2 +### Example 2: Setting the Grid Item Style -This example shows how to use **GridItemOptions**. +This example shows how to set the grid item style using **GridItemOptions**. ```ts // xxx.ets diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-gridrow.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-gridrow.md index 17a0a8a18450aee162e31a527fee5f8b8ae091ac..c7faec43f4744cd32b711cde9d569bed8365700f 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-gridrow.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-gridrow.md @@ -172,7 +172,7 @@ Sets breakpoints for the responsive grid container. ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### alignItems10+ @@ -215,6 +215,8 @@ Triggered when the breakpoint changes. ## Example +This example shows the basic usage of the responsive grid layout. + ```ts // xxx.ets @Entry diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-hyperlink.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-hyperlink.md index c546beb7b6ff91a9ba6c864d7c87f94315550f87..ee0950d965f926bfbdc018b5e9af34681f95b759 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-hyperlink.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-hyperlink.md @@ -32,7 +32,7 @@ Hyperlink(address: string | Resource, content?: string | Resource) ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### color @@ -48,10 +48,12 @@ Sets the color of the hyperlink text. | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------ | -| value | [Color](ts-appendix-enums.md#color) \| number \| string \| [Resource](ts-types.md#resource) | Yes | Color of the hyperlink text
Default value: **'#ff0a59f7'**| +| value | [Color](ts-appendix-enums.md#color) \| number \| string \| [Resource](ts-types.md#resource) | Yes | Color of the hyperlink text
Default value: **'#ff007dff'**.
Default value on wearable devices: **'ff1f71ff'**. ## Example +This example shows how to create hyperlinks with both images and text that can be clicked to navigate to a specified URL. + ```ts @Entry @Component diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-isolated-component-sys.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-isolated-component-sys.md index 626a07bbd00ecfd2b79692d3413fde53a1c8b65c..76d3c06524947ffad57b5ef61ee270804e1ce08a 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-isolated-component-sys.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-isolated-component-sys.md @@ -16,7 +16,7 @@ The **FolderStack** component is usually used in modular development scenarios w 1. This component does not support preview. -2. .abc files must pass the [VerifyAbc](../../apis-ability-kit/js-apis-bundleManager.md#bundlemanagerverifyabc11) verification to be used in this component. +2. .abc files must pass the [VerifyAbc](../../apis-ability-kit/js-apis-bundleManager-sys.md#bundlemanagerverifyabc11) verification to be used in this component. 3. Construction parameter updates are not supported; only the initial input is effective. @@ -60,14 +60,14 @@ Describes the optional construction parameters during **IsolatedComponent** cons | Name | Type | Mandatory| Description | | ---- | ---------------------------------------- | ---- | --------------- | | want | [Want](../../apis-ability-kit/js-apis-app-ability-want.md) | Yes | .abc file information to load.| -| worker | [RestrictedWorker](../../apis-arkts/js-apis-worker.md#restrictedworker11) | Yes | Restricted worker thread where the .abc file is running.| +| worker | [RestrictedWorker](../../apis-arkts/js-apis-worker-sys.md#restrictedworker11) | Yes | Restricted worker thread where the .abc file is running.| ## Attributes Only the [width](ts-universal-attributes-size.md#width), [height](ts-universal-attributes-size.md#height), and [backgroundColor](ts-universal-attributes-background.md#backgroundcolor) universal attributes are supported. ## Events -The [universal events](ts-universal-events-click.md) are not supported. +The [universal events](ts-component-general-events.md) are not supported. Events are asynchronously passed to the restricted worker thread after coordinate conversion. @@ -85,76 +85,144 @@ Invoked when an error occurs during the running of the **IsolatedComponent**. Yo | ---------------------------- | ------ | ------------------------------------------------------------ | | callback | [ErrorCallback](../../apis-basic-services-kit/js-apis-base.md#errorcallback) | Error information. | -## Example - -This example shows only the usage of the component. - -```ts -// OhCardWorker.ets -import { worker, ThreadWorkerGlobalScope, MessageEvents, ErrorEvent } from '@kit.ArkTS'; -const workerPort: ThreadWorkerGlobalScope = worker.workerPort; - -workerPort.onmessage = (e: MessageEvents) => {} -workerPort.onmessageerror = (e: MessageEvents) => {} -workerPort.onerror = (e: ErrorEvent) => {} -``` - -```ts -// Index.ets -import { worker } from '@kit.ArkTS'; -import { bundleManager } from '@kit.AbilityKit'; - -@Entry -@Component -struct Index2 { - @State isShow: boolean = false; - worker ?: worker.RestrictedWorker; - resourcePath : string = ""; - abcPath : string = ""; - entryPoint : string = ""; - fileName: string = "Index" - - build() { - Row() { - Column() { - // 1. Call verifyAbc to verify /data/storage/el2/haps/entry/files/Index.abc in the application sandbox. - Button("verifyAbc").onClick(()=>{ - let abcFilePath = getContext(this).filesDir + "/" + this.fileName + ".abc"; - bundle.verifyAbc([abcFilePath], false); - }).height(100).width(100) - - // 2. Display the IsolatedComponent. - Button("showIsolatedComponent").onClick(()=>{ - if (!this.isShow) { - this.worker = new worker.RestrictedWorker("./OhCardWorker"); - // /data/storage/el2/haps/entry/files/{fileName}.hap - this.resourcePath = getContext(this).filesDir + "/" + this.fileName + '.hap'; - // /abcs/data/storage/el2/haps/entry/files/{fileName}.hap - this.abcPath = "/abcs" + getContext(this).filesDir + "/" + this.fileName; - this.entryPoint = "com.ohos.test/entry/ets/pages/Index" - this.isShow = true; +## Example: Loading an IsolatedComponent + +This example demonstrates the basic usage of the **IsolatedComponent** component. The sample application's **bundleName** is **"com.example.isolateddemo"**, and the component uses the .abc file and an extension page from the same application as the embedded content. The specific testing steps after building the application project are as follows: +1. Build the HAP in DevEco Studio and install it on the device. +2. Upload the generated **modules.abc** file to the application sandbox path** /data/app/el2/100/base/com.example.isolateddemo/haps/entry/files** using DevEco Studio or the [hdc](../../../dfx/hdc.md) tool. +3. Open the application page and click the **verifyAbc** button to verify the .abc file, which logs "VerifyAbc successfully." +4. Click the **showIsolatedComponent** button to display the **IsolatedComponent** with the content "Hello World." + +- Restricted Worker thread script **ets/workers/OhCardWorker.ets**: + ```ts + // OhCardWorker.ets + import { worker, ThreadWorkerGlobalScope, MessageEvents, ErrorEvent } from '@kit.ArkTS'; + const workerPort: ThreadWorkerGlobalScope = worker.workerPort; + + workerPort.onmessage = (e: MessageEvents) => {} + workerPort.onmessageerror = (e: MessageEvents) => {} + workerPort.onerror = (e: ErrorEvent) => {} + ``` + +- Home page (**ets/pages/Index.ets**) loaded by the entry ability (**EntryAbility**): + ```ts + import { worker } from '@kit.ArkTS'; + import { bundleManager } from '@kit.AbilityKit'; + import { BusinessError } from '@kit.BasicServicesKit'; + + // Verify the .abc file and copy it to the specified sandbox path. + function VerifyAbc(abcPaths: Array, deleteOriginalFiles: boolean) { + try { + bundleManager.verifyAbc(abcPaths, deleteOriginalFiles, (err) => { + if (err) { + console.error("VerifyAbc failed, error message: " + err.message); + } else { + console.info("VerifyAbc successfully."); + } + }); + } catch (err) { + let message = (err as BusinessError).message; + console.error("VerifyAbc failed, error message: " + message); + } + } + + @Entry + @Component + struct Index { + @State isShow: boolean = false; + @State resourcePath: string = ""; + @State abcPath: string = ""; + @State entryPoint: string = ""; + // .abc file name + private fileName: string = "modules"; + // Bundle name of the application to which the .abc file belongs + private bundleName: string = "com.example.isolateddemo"; + // Restricted Worker thread + private worker ?: worker.RestrictedWorker = new worker.RestrictedWorker("entry/ets/workers/OhCardWorker.ets"); + + build() { + Row() { + Column() { + // 1. Verify the .abc file. + Button("verifyAbc").onClick(() => { + let abcFilePath = `${getContext(this).filesDir}/${this.fileName}.abc`; + console.log("abcFilePath: " + abcFilePath); + VerifyAbc([abcFilePath], false); + }).height(100).width(100) + + // 2. Display the IsolatedComponent. + Button("showIsolatedComponent").onClick(() => { + if (!this.isShow) { + // Resource path + this.resourcePath = `${getContext(this).filesDir}/${this.fileName}.hap`; + // Sandbox path after the .abc file is verified + this.abcPath = `/abcs${getContext(this).filesDir}/${this.fileName}`; + // Entry to the page to be displayed + this.entryPoint = `${this.bundleName}/entry/ets/pages/extension`; + this.isShow = true; + } + }).height(100).width(100) + + if (this.isShow) { + IsolatedComponent({ + want: { + "parameters": { + "resourcePath": this.resourcePath, + "abcPath": this.abcPath, + "entryPoint": this.entryPoint + } + }, + worker: this.worker + }) + .width(300) + .height(300) + .onError((err) => { + console.info("onError : " + JSON.stringify(err)); + }) } - }).height(100).width(100) - - if (this.isShow) { - IsolatedComponent({ - want: { - "parameters" : { - "resourcePath" : this.resourcePath, - "abcPath" : this.abcPath, - "entryPoint" : this.entryPoint - } - }, - "worker" : this.worker - }).width(300).height(300).onError((err)=>{ - console.info("onError : " + JSON.stringify(err)); - }) } + .width('100%') + } + .height('100%') + } + } + ``` + +- The entry page file **ets/pages/extension.ets**, which runs in a restricted Worker thread, needs to be configured in the **resources/base/profile/main_pages.json** file with the following content: + ```ts + @Entry + @Component + struct Extension { + @State message: string = 'Hello World'; + + build() { + RelativeContainer() { + Text(this.message) + .id('HelloWorld') + .fontSize(50) + .fontWeight(FontWeight.Bold) + .alignRules({ + center: { anchor: '__container__', align: VerticalAlign.Center }, + middle: { anchor: '__container__', align: HorizontalAlign.Center } + }) } + .height('100%') .width('100%') } - .height('100%') } -} - -``` + ``` + +- Add the **requestPermissions** tag in the **module.json5** configuration file to allow the execution of dynamically distributed Ark bytecode in restricted mode: + ```json + "requestPermissions": [ + { + "name": "ohos.permission.RUN_DYN_CODE", + "usedScene": { + "abilities": [ + "EntryAbility" + ], + "when": "inuse" + } + } + ] + ``` diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-list-sys.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-list-sys.md index 4d07131db4d8b5d14ae88bbe43fdb12a7de92905..a49fd7fbb6c372d008e2b820cc114ef200681cf3 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-list-sys.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-list-sys.md @@ -54,3 +54,5 @@ Provides the chained animation settings, which cover the maximum spacing, minimu | conductivity | number | No | Conductivity of the chained animations. The value range is [0,1]. A larger value indicates higher conductivity.
Default value: **0.7**| | intensity | number | No | Intensity of the chained animations. The value range is [0,1]. A larger value indicates more obvious animations.
Default value: **0.3**| | edgeEffect | [ChainEdgeEffect](#chainedgeeffect10)| No | Chained animation edge scrolling effect.
Default value: **ChainEdgeEffect.DEFAULT**| +| stiffness | number | No | Stiffness of the chained animations.
Default value: **228**| +| damping | number | No | Damping of the chained animations.
Default value: **30**| diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-list.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-list.md index 4cf84bbb182232ca597977a19f42ea86c893d329..0102f610b1386951c4c2a327b4225037ce44183d 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-list.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-list.md @@ -4,25 +4,7 @@ The **List** component provides a list container that presents a series of list > **NOTE** > -> - This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. -> -> - By default, this component can produce a bounce effect only when there is more than one screen of content. To produce a bounce effect when there is less than one screen of content, use the **options** parameter of the **edgeEffect** attribute. -> -> - The default value of the universal attribute [clip](ts-universal-attributes-sharp-clipping.md) is **true** for the **List** component. -> -> - To enable the editable mode for a list, the following conditions must be met: (This feature is deprecated since API version 9.) -> -> - **editMode** is set to **true**. -> -> - The list is bound to the **onItemDelete** event and the event returns **true** in the event callback. -> -> - The **editable** attribute of **ListItem** is set to **true**. -> -> - To enable list item dragging, the following conditions must be met: -> -> - **editMode** is set to **true**. (This is not required since API version 9.) -> -> - The list item is bound to the **onDragStart** event and the event returns a floating UI during event callback. +> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. ## Child Components @@ -33,24 +15,22 @@ Only the [ListItem](ts-container-listitem.md) and [ListItemGroup](ts-container-l > > Below are the rules for calculating the indexes of the child components of **List**: > -> The index increases in ascending order of child components. +> - The index increases in ascending order of child components. > -> In the **if/else** statement, only the child components for which the condition evaluates to true participate in the index calculation. +> - In the **if/else** statement, only the child components for which the condition evaluates to true participate in the index calculation. > -> In the **ForEach**, **LazyForEach**, or **Repeat** statement, the indexes of all expanded subnodes are calculated. +> - In the **ForEach**, **LazyForEach**, or **Repeat** statement, the indexes of all expanded subnodes are calculated. > -> After changes occur in [if/else](../../../quick-start/arkts-rendering-control-ifelse.md), [ForEach](../../../quick-start/arkts-rendering-control-foreach.md), [LazyForEach](../../../quick-start/arkts-rendering-control-lazyforeach.md), or [Repeat](../../../quick-start/arkts-new-rendering-control-repeat.md), the indexes of the child nodes are updated. +> - After changes occur in [if/else](../../../quick-start/arkts-rendering-control-ifelse.md), [ForEach](../../../quick-start/arkts-rendering-control-foreach.md), [LazyForEach](../../../quick-start/arkts-rendering-control-lazyforeach.md), or [Repeat](../../../quick-start/arkts-new-rendering-control-repeat.md), the indexes of the child nodes are updated. > -> Each **ListItemGroup** component is taken as a whole and assigned an index, and the indexes of the list items within are not included in the index calculation. +> - Each **ListItemGroup** component is taken as a whole and assigned an index, and the indexes of the list items within are not included in the index calculation. > -> Child components of **List** whose **visibility** attribute is set to **Hidden** or **None** are included in the index calculation. -> -> Child components of **List** whose **visibility** attribute is set to **None** are not displayed, but the spacing above and below them still takes effect. +> - Child components of **List** whose **visibility** attribute is set to **Hidden** or **None** are included in the index calculation. ## APIs -List(value?: [ListOptions](#listoptions14)) +List(value?: [ListOptions](#listoptions18)) **Widget capability**: This API can be used in ArkTS widgets since API version 9. @@ -62,27 +42,31 @@ List(value?: [ListOptions](#listoptions14)) | Name | Type| Mandatory| Description| | ------ | ---- | ---- | ---- | -| value | [ListOptions](#listoptions14) | No | Options of the **List** component.| +| value | [ListOptions](#listoptions18) | No | Options of the **List** component.| -## ListOptions14+ +## ListOptions18+ Defines the options of the **List** component. -**Widget capability**: This API can be used in ArkTS widgets since API version 14. +**Widget capability**: This API can be used in ArkTS widgets since API version 18. -**Atomic service API**: This API can be used in atomic services since API version 14. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full | Name | Type | Mandatory| Description | | ------------ | ------------------------------------------- | ---- | ------------------------------------------------------------ | -| space | number \| string | No | Spacing between list items along the main axis.
Default value: **0**
If the parameter type is number, the unit is vp.
**NOTE**
If this parameter is set to a negative number or a value greater than or equal to the length of the list content area, the default value is used.
If this parameter is set to a value less than the width of the list divider, the width of the list divider is used as the spacing.| -| initialIndex | number | No | Index of the item to be displayed at the start when the list is initially loaded.
Default value: **0**
**NOTE**
If the set value is a negative number or is greater than the index of the last item in the list, the value is invalid. In this case, the default value will be used.| +| initialIndex | number | No| Index of the item to be displayed at the start when the list is initially loaded.
Default value: **0**
**NOTE**
If the set value is a negative number or is greater than the index of the last item in the list, the value is invalid. In this case, the default value will be used.| +| space | number \| string | No | Spacing between list items along the main axis.
Default value: **0**
If the parameter type is number, the unit is vp.
**NOTE**
If this parameter is set to a negative number or a value greater than or equal to the length of the list content area, the default value is used.
If this parameter is set to a value less than the width of the list divider, the width of the list divider is used as the spacing.
Child components of **List** whose **visibility** attribute is set to **None** are not displayed, but the spacing above and below them still takes effect.| | scroller | [Scroller](ts-container-scroll.md#scroller) | No | Scroller, which can be bound to scrollable components.
**NOTE**
The scroller cannot be bound to other scrollable components.| ## Attributes -In addition to [universal attributes](ts-universal-attributes-size.md) and [scrollable component common attributes](ts-container-scrollable-common.md#attributes), the following attributes are also supported. +In addition to [universal attributes](ts-component-general-attributes.md) and [scrollable component common attributes](ts-container-scrollable-common.md#attributes), the following attributes are also supported. + +> **NOTE** +> +> The default value of the universal attribute [clip](ts-universal-attributes-sharp-clipping.md) is **true** for the **List** component. ### listDirection @@ -104,7 +88,7 @@ Sets the direction in which the list items are arranged. ### divider -divider(value: [ListDividerOptions](#listdivideroptions14) | null) +divider(value: [ListDividerOptions](#listdivideroptions18) | null) Sets the style of the divider for the list items. By default, there is no divider. @@ -128,7 +112,7 @@ When a list item has [polymorphic styles](ts-universal-attributes-polymorphic-st | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| value | [ListDividerOptions](#listdivideroptions14) \| null | Yes | Style of the divider for the list items.
Default value: **null**| +| value | [ListDividerOptions](#listdivideroptions18) \| null | Yes | Style of the divider for the list items.
Default value: **null**| ### scrollBar @@ -166,9 +150,9 @@ When a list is nested with **LazyForEach**, and within **LazyForEach** there is **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | -------------------------------------------------- | -| value | number | Yes | Number of list items or list item groups to be preloaded (cached).
Default value: **1**
Value range: [0, +∞)| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| value | number | Yes | Number of list items or list item groups to be preloaded (cached).
Default value: number of nodes visible on the screen, with the maximum value of 16
Value range: [0, +∞)| ### cachedCount14+ @@ -188,7 +172,7 @@ When **cachedCount** is set for the list, the system preloads and lays out the * | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------------- | -| count | number | Yes | Number of list items to be preloaded.
Default value: **1**
Value range: [0, +∞)| +| count | number | Yes | Number of list items to be preloaded.
Default value: number of nodes visible on the screen, with the maximum value of 16
Value range: [0, +∞)| | show | boolean | Yes | Whether to display the preloaded list items.
Default value: **false**| ### editMode(deprecated) @@ -213,6 +197,10 @@ edgeEffect(value: EdgeEffect, options?: EdgeEffectOptions) Sets the effect used when the scroll boundary is reached. +> **NOTE** +> +> By default, this component can produce a bounce effect only when there is more than one screen of content. To produce a bounce effect when there is less than one screen of content, use the **options** parameter of the **edgeEffect** attribute. + **Widget capability**: This API can be used in ArkTS widgets since API version 9. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -343,11 +331,13 @@ Sets whether to pin the header to the top or the footer to the bottom in the [li scrollSnapAlign(value: ScrollSnapAlign) -Sets the alignment mode for the scroll snap position. +Sets the scroll snap alignment effect for list items. This effect aligns list items to the nearest snap point when scrolling ends. -This attribute is effective only when the heights of list items are the same. +This attribute is effective only when all list items have the same height. -It does not take effect after scrolling by a touchpad or mouse device ends. +It does not take effect when scrolling ends using a touchpad or mouse device. + +During the alignment animation, the scroll operation source type reported by the **onWillScroll** event is **ScrollSource.FLING**. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -476,6 +466,27 @@ Sets whether the visible content position should remain unchanged when data is i > - When **maintainVisibleContentPosition** is set to **true**, inserting or deleting data above the visible area will trigger **onDidScroll** and **onScrollIndex** events. > - In a multi-column scenario, setting **maintainVisibleContentPosition** to **true** allows you to insert or delete entire rows of data while keeping the visible content position unchanged. If the insertion or deletion does not involve entire rows, however, the visible content position will still change. +### stackFromEnd18+ + +stackFromEnd(enabled: boolean) + +Sets whether the list's layout starts from the bottom (end) rather than the top (beginning). + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------------------------------------ | +| enabled | boolean | Yes | Whether the list's layout starts from the bottom (end) rather than the top (beginning).
**false** (default): The layout starts from the top. **true**: The layout starts from the bottom.| + +> **NOTE** +> - When **stackFromEnd** is set to **true**, the following rules apply:
If the content of the **List** component is shorter than the component height, the content will be aligned to the bottom of the component. +> - If the height of a list item in the visible area changes, or if a new list item is inserted, the list items above the changed or inserted item will move upwards to accommodate the new layout. +> - The default value of **initialIndex** becomes the total number of list items minus one. + ## ListItemAlign9+ **Widget capability**: This API can be used in ArkTS widgets since API version 9. @@ -534,13 +545,13 @@ Implements the callbacks and events for the [ListItem](ts-container-listitem.md) | ------- | -------- | ---- | ---------------------- | | onFinish | ()=>void | No | Triggered after the collapse animation is complete.| -## ListDividerOptions14+ +## ListDividerOptions18+ Defines the divider style of the list or list item group. -**Widget capability**: This API can be used in ArkTS widgets since API version 14. +**Widget capability**: This API can be used in ArkTS widgets since API version 18. -**Atomic service API**: This API can be used in atomic services since API version 14. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -553,7 +564,7 @@ Defines the divider style of the list or list item group. ## Events -In addition to [universal events](ts-universal-events-click.md) and [scrollable component common events](ts-container-scrollable-common.md#events), the following events are also supported. +In addition to [universal events](ts-component-general-events.md) and [scrollable component common events](ts-container-scrollable-common.md#events), the following events are also supported. ### onItemDelete(deprecated) @@ -906,13 +917,13 @@ For details about the error codes, see [Universal Error Codes](../../errorcode-u | ------- | -------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | | 100004 | Controller not bound to component. | -### getVisibleListContentInfo13+ +### getVisibleListContentInfo14+ getVisibleListContentInfo(x:number, y: number): VisibleListContentInfo Obtains the index information of the child component at the specified coordinates. -**Atomic service API**: This API can be used in atomic services since API version 13. +**Atomic service API**: This API can be used in atomic services since API version 14. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -940,7 +951,7 @@ For details about the error codes, see [Universal Error Codes](../../errorcode-u | ID| Error Message| | ------- | -------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | -| 100004 | Controller not bound to component. | +| 100004 |The controller not bound to component.| ### scrollToItemInGroup11+ scrollToItemInGroup(index: number, indexInGroup: number, smooth?: boolean, align?: ScrollAlign): void @@ -1466,3 +1477,38 @@ struct ListExample { ``` ![fadingEdge_list](figures/fadingEdge_list.gif) + +### Example 8: Setting the Single-Side Edge Effect + +This example demonstrates how to set a single-side edge effect for the **List** component using the **edgeEffect** API. + +```ts +// xxx.ets +@Entry +@Component +struct ListExample { + private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] + scrollerForList: Scroller = new Scroller() + build() { + Column() { + List({ space: 20, initialIndex: 0, scroller: this.scrollerForList }) { + ForEach(this.arr, (item: number) => { + ListItem() { + Text('' + item) + .width('100%').height(100).fontSize(16) + .textAlign(TextAlign.Center).borderRadius(10).backgroundColor(0xFFFFFF) + } + }, (item: string) => item) + } + .edgeEffect(EdgeEffect.Spring,{alwaysEnabled:true,effectEdge:EffectEdge.START}) + .width('90%').height('90%') + } + .width('100%') + .height('100%') + .backgroundColor(0xDCDCDC) + .padding({ top: 5 }) + } +} +``` + +![edgeEffect_list](figures/edgeEffect_list.gif) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-listitem.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-listitem.md index 89ac6565e1e296c31ef2adf0c3fd9c5a44f309f2..7c501d89afe250efe34fd26f7ca1ba5e5d562ae4 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-listitem.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-listitem.md @@ -6,7 +6,7 @@ The **ListItem** component displays specific items in the list. It must be used > > - This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > - The parent of this component can only be [List](ts-container-list.md) or [ListItemGroup](ts-container-listitemgroup.md). -> - When this component is used with **LazyForEach**, its child components are created when it is created. When this component is used with **if/else** or **ForEach**, or when the parent component is **List**or **ListItemGroup**, its child components are created when it is laid out. +> - When this component is used with **LazyForEach**, its child components are created when it is created. When this component is used with **if/else** or **ForEach**, or when the parent component is **List** or **ListItemGroup**, its child components are created when it is laid out. ## Child Components @@ -18,7 +18,7 @@ This component can contain a single child component. ListItem(value?: ListItemOptions) -**Widget capability**: Since API version 10, this API is supported in ArkTS widgets. +**Widget capability**: This API can be used in ArkTS widgets since API version 10. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -48,7 +48,7 @@ This API is deprecated since API version 10. You are advised to use [ListItem(deprecated)
@@ -56,7 +56,7 @@ sticky(value: Sticky) Sets the sticky effect of the list item. -This attribute is deprecated since API version 9. You are advised to use [the sticky attribute of the List component](ts-container-list.md#attributes) instead. +This attribute is deprecated since API version 9. You are advised to use [the sticky attribute of the List component](ts-container-list.md#sticky9) instead. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -98,7 +98,7 @@ Sets whether the list item is selectable for multiselect. This attribute takes e | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------------------------- | -| value | boolean | Yes | whether the list item is selectable for multiselect.
Default value: **true**| +| value | boolean | Yes | Whether the list item is selectable for multiselect.
Default value: **true**| ### selected10+ @@ -106,7 +106,7 @@ selected(value: boolean) Sets whether the list item is selected. This attribute supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md). This attribute must be used before the [style for the selected state](./ts-universal-attributes-polymorphic-style.md) is set. Otherwise, the style settings will not take effect. -**Widget capability**: Since API version 10, this API is supported in ArkTS widgets. +**Widget capability**: This API can be used in ArkTS widgets since API version 10. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -150,7 +150,7 @@ This API is deprecated since API version 9. There is no substitute API. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Value| Description | +| Name | Value| Description | | ------ | ------ | --------- | | None | 0 | The editing operation is not restricted. | | Deletable | 1 | The list item can be deleted.| @@ -162,7 +162,7 @@ This API is deprecated since API version 9. There is no substitute API. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Value| Description | +| Name | Value| Description | | ------ | ------ | --------- | | Spring | 0 | When the list item scrolls to the edge of the list, it can continue to scroll for a distance.
If the delete area is set, the list item can continue to scroll after the scroll distance exceeds the delete threshold and,
after being released, rebound following the spring curve.| | None | 1 | The list item cannot scroll beyond the edge of the list.
If the delete area is set, the list item cannot continue to scroll after the scroll distance exceeds the delete threshold.
If the delete callback is set, it is triggered when the delete threshold is reached and the list item is released.| @@ -180,7 +180,7 @@ The swipe gesture works only in the list item area. If a swipe causes a child co | start | [CustomBuilder](ts-types.md#custombuilder8) \| [SwipeActionItem](#swipeactionitem10) | No | Swipe action item displayed on the left of the list item when the item is swiped right (in vertical list layout) or above the list item when the item is swiped down (in horizontal list layout).
**Atomic service API**: This API can be used in atomic services since API version 11.| | end | [CustomBuilder](ts-types.md#custombuilder8) \| [SwipeActionItem](#swipeactionitem10) | No | Swipe action item displayed on the right of the list item when the item is swiped left (in vertical list layout) or below the list item when the item is swiped up (in horizontal list layout).
**Atomic service API**: This API can be used in atomic services since API version 11.| | edgeEffect | [SwipeEdgeEffect](#swipeedgeeffect9) | No | Scroll effect.
**Atomic service API**: This API can be used in atomic services since API version 11. | -| onOffsetChange11+ | (offset: number) => void | No | Callback invoked when the scroll offset changes.
**NOTE**
Specifically, this callback is invoked when the location of the list item changes, in vp, when it is swiped left or right (in vertical list layout) or up or down (in horizontal list layout).
**Atomic service API**: This API can be used in atomic services since API version 12. | +| onOffsetChange11+ | (offset: number) => void | No | Callback invoked when the scroll offset changes.
**NOTE**
Specifically, this callback is invoked when the location of the list item changes, in vp, when it is swiped left or right (in vertical list layout) or up or down (in horizontal list layout).
**Atomic service API**: This API can be used in atomic services since API version 12.| ## SwipeActionItem10+ @@ -192,11 +192,12 @@ Describes the swipe action item.
For a list in vertical layout, it refers to | Name | Type | Mandatory| Description | | -------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | actionAreaDistance | [Length](ts-types.md#length) | No| Swipe distance threshold for deleting the list item.
Default value: **56vp**
**NOTE**
This parameter cannot be set in percentage.
If the value is greater than the list item width minus the width of **swipeAction**, or is less than or equal to 0, the delete area will not be set.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| onAction | () => void | No| Callback invoked when the list item is released while in the delete area.
**NOTE**
This callback is invoked only when the list item is released in a position that meets or goes beyond the specified swipe distance threshold (which must be valid) for deleting the list item.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| onAction | () => void | No| Callback invoked when the list item is released while in the delete area.
**NOTE**
This callback is invoked only when the list item is released in a position that meets or goes beyond the specified swipe distance threshold (which must be valid) for deleting the list item.
**Atomic service API**: This API can be used in atomic services since API version 11.| | onEnterActionArea | () => void | No| Callback invoked each time the list item enters the delete area.
**Atomic service API**: This API can be used in atomic services since API version 11.| | onExitActionArea | () => void | No|Callback invoked each time the list item exits the delete area.
**Atomic service API**: This API can be used in atomic services since API version 11.| | builder | [CustomBuilder](ts-types.md#custombuilder8) | No|Swipe action item displayed when the list item is swiped left or right (in vertical list layout) or up or down (in horizontal list layout).
**Atomic service API**: This API can be used in atomic services since API version 11.| -| onStateChange11+ | (swipeActionState) => void | No|Callback invoked when the swipe state of the list item changes.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| builderComponent18+ | [ComponentContent](../js-apis-arkui-ComponentContent.md) | No|Swipe action item displayed when the list item is swiped left or right (in vertical list layout) or up or down (in horizontal list layout).
**NOTE**
This parameter takes precedence over the **builder** parameter. This means that, if both **builder** and **builderComponent** are set, the value of **builderComponent** is used.
To avoid display issues, do not assign the same **builderComponent** to different swipe action items specified by **start** and **end**.
**Atomic service API**: This API can be used in atomic services since API version 18.| +| onStateChange11+ | (state:[SwipeActionState](#swipeactionstate11)) => void | No|Callback invoked when the swipe state of the list item changes.
**Atomic service API**: This API can be used in atomic services since API version 12.| ## ListItemOptions10+ **Atomic service API**: This API can be used in atomic services since API version 11. @@ -213,7 +214,7 @@ Describes the swipe action item.
For a list in vertical layout, it refers to **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name| Value | Description | +| Name| Value | Description | | ---- | ---- | ------------------ | | NONE | 0 | No style. | | CARD | 1 | Default card style.| @@ -224,7 +225,7 @@ Describes the swipe action item.
For a list in vertical layout, it refers to **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Value | Description | +| Name | Value | Description | | --------- | --------- | ------------------------------------------------------------ | | COLLAPSED | 0 | Collapsed state.
When the list item is swiped left or right (in vertical list layout) or up or down (in horizontal list layout), the swipe action item is hidden.| | EXPANDED | 1 | Expanded state.
When the list item is swiped left or right (in vertical list layout) or up or down (in horizontal list layout), the swipe action item is shown.
**NOTE**
When the list item is swiped left or right (in vertical list layout)
or up or down (in horizontal list layout), the swipe action item is shown.| @@ -238,7 +239,7 @@ onSelect(event: (isSelected: boolean) => void) Triggered when the selected state of the list item for multiselect changes. -**Widget capability**: Since API version 10, this API is supported in ArkTS widgets. +**Widget capability**: This API can be used in ArkTS widgets since API version 9. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -252,7 +253,8 @@ Triggered when the selected state of the list item for multiselect changes. ## Example -### Example 1 +### Example 1: Creating a List Item +This example demonstrates the basic usage of creating a list item. ```ts // xxx.ets @@ -284,8 +286,8 @@ struct ListItemExample { ![en-us_image_0000001219864159](figures/en-us_image_0000001219864159.gif) -### Example 2 - +### Example 2: Setting the Swipe Action Item +This example shows how to set the swipe action item for a list item using **swipeAction**. ```ts // xxx.ets @@ -295,17 +297,20 @@ struct ListItemExample2 { @State arr: number[] = [0, 1, 2, 3, 4] @State enterEndDeleteAreaString: string = "not enterEndDeleteArea" @State exitEndDeleteAreaString: string = "not exitEndDeleteArea" + private scroller: ListScroller = new ListScroller() @Builder itemEnd() { Row() { Button("Delete").margin("4vp") - Button("Set").margin("4vp") + Button("Set").margin("4vp").onClick(() => { + this.scroller.closeAllSwipeActions() + }) }.padding("4vp").justifyContent(FlexAlign.SpaceEvenly) } build() { Column() { - List({ space: 10 }) { + List({ space: 10, scroller: this.scroller }) { ForEach(this.arr, (item: number) => { ListItem() { Text("item" + item) @@ -351,7 +356,8 @@ struct ListItemExample2 { ``` ![deleteListItem](figures/deleteListItem.gif) -### Example 3 +### Example 3: Applying a Card-style Effect +This example illustrates the card-style effect of the **ListItem** component. ```ts // xxx.ets @@ -388,3 +394,113 @@ struct ListItemExample3 { } ``` ![ListItemStyle](figures/listItem3.jpeg) + +### Example 4: Setting the Swipe Action Item Using ComponentContent + +This example demonstrates how to set swipe action items for list items using **ComponentContent**. + +```ts +// xxx.ets +import { ComponentContent } from '@kit.ArkUI'; + +class BuilderParams { + text: string | Resource; + scroller: ListScroller + constructor(text: string | Resource, scroller: ListScroller) { + this.text = text; + this.scroller = scroller; + } +} + +@Builder +function itemBuilder(params: BuilderParams) { + Row() { + Button(params.text).margin("4vp") + Button("Set").margin("4vp").onClick(() => { + params.scroller.closeAllSwipeActions() + }) + }.padding("4vp").justifyContent(FlexAlign.SpaceEvenly) +} +@Component +struct MyListItem { + scroller: ListScroller = new ListScroller() + @State arr: number[] = [0, 1, 2, 3, 4] + @State project ?: number = 0 + startBuilder ?: ComponentContent = undefined + endBuilder ?: ComponentContent = undefined + + builderParam = new BuilderParams("delete", this.scroller) + + aboutToAppear(): void { + this.startBuilder = new ComponentContent(this.getUIContext(), wrapBuilder(itemBuilder), this.builderParam) + this.endBuilder = new ComponentContent(this.getUIContext(), wrapBuilder(itemBuilder), this.builderParam) + } + GetStartBuilder() { + this.startBuilder?.update(new BuilderParams("StartDelete", this.scroller)); + return this.startBuilder; + } + GetEndBuilder() { + this.endBuilder?.update(new BuilderParams("EndDelete", this.scroller)); + return this.endBuilder; + } + build() { + ListItem() { + Text("item" + this.project) + .width('100%') + .height(100) + .fontSize(16) + .textAlign(TextAlign.Center) + .borderRadius(10) + .backgroundColor(0xFFFFFF) + } + .transition({ type: TransitionType.Delete, opacity: 0 }) + .swipeAction({ + end: { + builderComponent: this.GetEndBuilder(), + onAction: () => { + animateTo({ duration: 1000 }, () => { + let index = this.arr.indexOf(this.project) + this.arr.splice(index, 1) + }) + }, + actionAreaDistance: 56 + }, + start: { + builderComponent: this.GetStartBuilder(), + onAction: () => { + animateTo({ duration: 1000 }, () => { + let index = this.arr.indexOf(this.project) + this.arr.splice(index, 1) + }) + }, + actionAreaDistance: 56 + } + }) + .padding(5) + } +} + +@Entry +@Component +struct ListItemExample { + @State arr: number[] = [0, 1, 2, 3, 4] + private scroller: ListScroller = new ListScroller() + + build() { + Column() { + List({ space: 10, scroller: this.scroller }) { + ListItemGroup() { + ForEach(this.arr, (project: number) => { + MyListItem({ scroller: this.scroller, project: project, arr:this.arr }) + }, (item: string) => item) + } + } + } + .padding(10) + .backgroundColor(0xDCDCDC) + .width('100%') + .height('100%') + } +} +``` +![ListItemStyle](figures/deleteListItem_example04.gif) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-listitemgroup.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-listitemgroup.md index de34fb36c24f69bee73f141ff08935125539ffd4..2b58818e5c245d26c4508926a0598c99c66cb40b 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-listitemgroup.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-listitemgroup.md @@ -48,7 +48,7 @@ ListItemGroup(options?: ListItemGroupOptions) ### divider -divider(value: [ListDividerOptions](ts-container-list.md#listdivideroptions14) | null) +divider(value: [ListDividerOptions](ts-container-list.md#listdivideroptions18) | null) Sets the style of the divider for the list items. By default, there is no divider. @@ -64,7 +64,7 @@ When a list item has [polymorphic styles](ts-universal-attributes-polymorphic-st | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| value | [ListDividerOptions](ts-container-list.md#listdivideroptions14) \| null | Yes | Style of the divider for the list items.
Default value: **null**| +| value | [ListDividerOptions](ts-container-list.md#listdivideroptions18) \| null | Yes | Style of the divider for the list items.
Default value: **null**| ### childrenMainSize12+ @@ -277,7 +277,7 @@ function itemHead(params: HeadBuilderParams) { @Builder function itemFoot(params: FootBuilderParams) { - Text('Total lessons:' + params.num) + Text('Total lessons: ' + params.num) .fontSize(20) .height('48vp') .width("100%") diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-navigator.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-navigator.md index 3198147e2c1d09a2612fc6af98f31e608de7460c..dcb59e983270681796f1b93608fc1710ceaadf2e 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-navigator.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-navigator.md @@ -35,7 +35,7 @@ Navigator(value?: {target: string, type?: NavigationType}) **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Value | Description | +| Name | Value | Description | | ------- | ------- | -------------------------- | | Push | 1 | Navigates to the specified page in the application. | | Replace | 2 | Replaces the current page with another one in the application and destroys the current page.| @@ -57,7 +57,7 @@ Sets whether the **Navigator** component is activated. If the component is activ | Name| Type | Mandatory| Description | | ------ | ------- | ---- | -------------------------- | -| value | boolean | Yes | Whether the **Navigator** component is activated.| +| value | boolean | Yes | Whether the **Navigator** component is activated. The value **true** means that the component is activated, and **false** means the opposite.| ### params @@ -106,7 +106,6 @@ Sets the navigation type. | ------ | ------ | ---- | ---------------------------------------------- | | value | [NavigationType](#navigationtype) | Yes | Navigation type.
Default value: **NavigationType.Push**| - ## Example ```ts diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-panel.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-panel.md index 352f631b0020e5a99a6744b856d3cc482b52db94..48ab220204903dec00ad1390c7d693f8182cb368 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-panel.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-panel.md @@ -34,7 +34,7 @@ Panel(show: boolean) ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### type @@ -232,7 +232,7 @@ Sets whether to display the close icon. | WRAP_CONTENT | When the type is **CUSTOM**, the panel automatically adapts its height to the content.| ## Events -In addition to the [universal events](ts-universal-events-click.md), the following events are supported. +In addition to the [universal events](ts-component-general-events.md), the following events are supported. ### onChange diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-refresh.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-refresh.md index 7e10da8c94a90e85c38dc6bf7c7071994536bdaf..08cc872d597e2255447614aed6063fffc1b72e3f 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-refresh.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-refresh.md @@ -47,7 +47,7 @@ Refresh(value: RefreshOptions) ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### refreshOffset12+ @@ -99,7 +99,7 @@ Sets the pull-down ratio. ## Events -In addition to the [universal events](ts-universal-events-click.md), the following events are supported. +In addition to the [universal events](ts-component-general-events.md), the following events are supported. ### onStateChange @@ -352,7 +352,7 @@ struct RefreshExample { ![en-us_image_refresh_builder](figures/en-us_image_refresh_builder.gif) -### Example 4: Customizing the Refreshing Area Content with -refreshingContent +### Example 4: Customizing the Refreshing Area Content with refreshingContent This example shows how to customize the content displayed in the refreshing area using the [refreshingContent](#refreshoptions) parameter. @@ -544,7 +544,6 @@ struct ListRefreshLoad { @State refreshing: boolean = false; @State refreshOffset: number = 0; @State refreshState: RefreshStatus = RefreshStatus.Inactive; - @State canLoad: boolean = false; @State isLoading: boolean = false; @Builder @@ -596,8 +595,7 @@ struct ListRefreshLoad { } .onScrollIndex((start: number, end: number) => { // Trigger new data loading when the end of the list is reached. - if (this.canLoad && end >= this.arr.length - 1) { - this.canLoad = false; + if (end >= this.arr.length - 1) { this.isLoading = true; // Simulate new data loading. setTimeout(() => { @@ -608,13 +606,6 @@ struct ListRefreshLoad { }, 700) } }) - .onScrollFrameBegin((offset: number, state: ScrollState) => { - // Trigger new data loading only when the list scrolls up. - if (offset > 5 && !this.isLoading) { - this.canLoad = true; - } - return { offsetRemain: offset }; - }) .scrollBar(BarState.Off) // Enable the effect used when the scroll boundary is reached. .edgeEffect(EdgeEffect.Spring, { alwaysEnabled: true }) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-relativecontainer.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-relativecontainer.md index e9eca9660a54dbaefa0923c9584c79285a3cba16..8ca4c69f43c38d58cb2477f8bfd6be920879c97c 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-relativecontainer.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-relativecontainer.md @@ -47,7 +47,7 @@ RelativeContainer() ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### guideLine12+ @@ -839,3 +839,69 @@ struct Index { } ``` ![relative container](figures/relativecontainer8.png) + +### Example 10: Setting Component Weights in a Chain + +This example demonstrates how to use [chainWeight](ts-universal-attributes-location.md#chainweight14) to set the size weights of components in a chain. + +```ts +@Entry +@Component +struct Index { + build() { + Row() { + RelativeContainer() { + Row() { + Text('row1') + } + .justifyContent(FlexAlign.Center) + .width(80) + .height(80) + .backgroundColor('#a3cf62') + .alignRules({ + left: { anchor: "__container__", align: HorizontalAlign.Start }, + right: { anchor: "row2", align: HorizontalAlign.Start }, + center: { anchor: "__container__", align: VerticalAlign.Center }, + }) + .id("row1") + .chainMode(Axis.Horizontal, ChainStyle.PACKED) + + Row() { + Text('row2') + } + .justifyContent(FlexAlign.Center) + .width(80) + .height(80) + .backgroundColor('#00ae9d') + .alignRules({ + left: { anchor: "row1", align: HorizontalAlign.End }, + right: { anchor: "row3", align: HorizontalAlign.Start }, + top: { anchor: "row1", align: VerticalAlign.Top } + }) + .id("row2") + .chainWeight({horizontal:1}) + + Row() { + Text('row3') + } + .justifyContent(FlexAlign.Center) + .width(80) + .height(80) + .backgroundColor('#0a59f7') + .alignRules({ + left: { anchor: "row2", align: HorizontalAlign.End }, + right: { anchor: "__container__", align: HorizontalAlign.End }, + top: { anchor: "row1", align: VerticalAlign.Top } + }) + .id("row3") + .chainWeight({horizontal:2}) + } + .width(300).height(300) + .margin({ left: 50 }) + .border({ width: 2, color: "#6699FF" }) + } + .height('100%') + } +} +``` +![relative container](figures/relativecontainer9.png) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-row-sys.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-row-sys.md index 6748281ee8536e3a8f221f0001cb9093537e8a88..545f63d9bbdc4e2d47c97f0c85cad7704e686af1 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-row-sys.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-row-sys.md @@ -10,7 +10,7 @@ The **Row** component lays out child components horizontally. ## Attributes -## pointLight +### pointLight pointLight(value: PointLightStyle) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-row.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-row.md index 5865525ab6d48a51b91321b19dc43a1287d582e2..1807bec66a1ad11aded55d8e25346e6584ab5efd 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-row.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-row.md @@ -13,8 +13,11 @@ Supported ## APIs +### Row -Row(value?:{space?: number | string }) +Row(options?: RowOptions) + +Creates a horizontal linear layout container. You can set the spacing between child components, which can be of type number or string. **Widget capability**: This API can be used in ArkTS widgets since API version 9. @@ -26,12 +29,56 @@ Row(value?:{space?: number | string }) | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| space | number \| string | No| Horizontal spacing between two adjacent child components.
Since API version 9, this parameter does not take effect when it is set to a negative number or when **justifyContent** is set to **FlexAlign.SpaceBetween**, **FlexAlign.SpaceAround** or **FlexAlign.SpaceEvenly**.
Default value: **0**, in vp
**NOTE**
The value can be a number greater than or equal to 0 or a string that can be converted to a number.| +| options | [RowOptions](#rowoptions14) | No| Spacing between child components.| + +### Row16+ +Row(options?: RowOptions | RowOptionsV2) + +Creates a horizontal linear layout container. You can set the spacing between child components, which can be of type number, string, or Resource. + +**Widget capability**: This API can be used in ArkTS widgets since API version 16. + +**Atomic service API**: This API can be used in atomic services since API version 16. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| options | [RowOptions](#rowoptions14) \| [RowOptionsV2](#rowoptionsv216) | No| Spacing between child components.| + +## RowOptions14+ + +Defines the spacing properties for child components used for constructing a **Row** component. + +**Widget capability**: This API can be used in ArkTS widgets since API version 14. + +**Atomic service API**: This API can be used in atomic services since API version 14. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| space | number \| string | No| Spacing between child components.
Since API version 9, this parameter does not take effect when it is set to a negative number or when **justifyContent** is set to **FlexAlign.SpaceBetween**, **FlexAlign.SpaceAround** or **FlexAlign.SpaceEvenly**.
Default value: **0**, in vp
**NOTE**
The value of **space** can be a number greater than or equal to 0 or a string that can be converted to a number.| + +## RowOptionsV216+ + +Defines the spacing properties for child components used for constructing a **Row** component. + +**Widget capability**: This API can be used in ArkTS widgets since API version 16. + +**Atomic service API**: This API can be used in atomic services since API version 16. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| space | [SpaceType](ts-container-column.md#spacetype16) | No| Horizontal spacing between two adjacent child components.
This parameter does not take effect if the value specified is a negative number, or if **justifyContent** is set to **FlexAlign.SpaceBetween**, **FlexAlign.SpaceAround**, or **FlexAlign.SpaceEvenly**.
Default value: **0**, in vp
**NOTE**
The value of **space** can be a number greater than or equal to 0, a string that can be converted to a number, or a Resource type that can be converted to a number.| ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### alignItems @@ -97,10 +144,24 @@ Sets whether to reverse the arrangement of child components on the main axis (ho ## Events -The [universal events](ts-universal-events-click.md) are supported. +The [universal events](ts-component-general-events.md) are supported. ## Example +This example demonstrates how to set horizontal layout properties, such as spacing and alignment, using the **Row** component. + +```json +// resources/base/element/string.json +{ + "string": [ + { + "name": "stringSpace", + "value": "5" + } + ] +} +``` + ```ts // xxx.ets @Entry @@ -115,6 +176,13 @@ struct RowExample { Row().width('30%').height(50).backgroundColor(0x00FFFF) }.width('90%').height(107).border({ width: 1 }) + // Set the spacing between child components using the Resource type. + Text('Resource space').width('90%') + Row({ space: $r("app.string.stringSpace") }) { + Row().width('30%').height(50).backgroundColor(0xAFEEEE) + Row().width('30%').height(50).backgroundColor(0x00FFFF) + }.width('90%').height(107).border({ width: 1 }) + // Set the alignment mode of the child components in the vertical direction. Text('alignItems(Bottom)').width('90%') Row() { diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-rowsplit.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-rowsplit.md index 7d6f30d169c9099a76cc437be93c93ab588d434e..a34824c3b8235951a017506c6461c3547a3e4efb 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-rowsplit.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-rowsplit.md @@ -17,6 +17,10 @@ After initialization, if, due to dynamic changes to the [margin](ts-universal-at RowSplit() +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + ## Attributes ### resizeable @@ -39,11 +43,13 @@ Sets whether the divider can be dragged. > > The divider of **RowSplit** can change the width of the left and right child components, but only to the extent that the resultant width falls within the maximum and minimum widths of the child components. > -> Universal attributes such as [clip](ts-universal-attributes-sharp-clipping.md#clip) and [margin](ts-universal-attributes-size.md#margin) are supported. If **clip** is not set, the default value **true** is used. +> Universal attributes such as [clip](ts-universal-attributes-sharp-clipping.md#clip12) and [margin](ts-universal-attributes-size.md#margin) are supported. If **clip** is not set, the default value **true** is used. ## Example +This example demonstrates the basic usage of **RowSplit**, which allows you to create draggable, horizontally laid-out child components. + ```ts // xxx.ets @Entry diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-scroll.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-scroll.md index 435789568a3fbdcabeaeb1b32df4ca15e001556d..a7a8a06899fb2c9ffb07bdec68b4aa8386be1624 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-scroll.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-scroll.md @@ -18,6 +18,8 @@ This component supports only one child component. Scroll(scroller?: Scroller) +Creates a **Scroll** component. + **Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -30,7 +32,7 @@ Scroll(scroller?: Scroller) ## Attributes -In addition to [universal attributes](ts-universal-attributes-size.md) and [scrollable component common attributes](ts-container-scrollable-common.md#attributes), the following attributes are also supported. +In addition to [universal attributes](ts-component-general-attributes.md) and [scrollable component common attributes](ts-container-scrollable-common.md#attributes), the following attributes are also supported. ### scrollable @@ -169,7 +171,7 @@ Sets the nested scrolling options. You can set the nested scrolling mode in the friction(value: number | Resource) -Sets the friction coefficient. It applies only to gestures in the scrolling area, and it affects only indirectly the scroll chaining during the inertial scrolling process. A value less than or equal to 0 evaluates to the default value. +Sets the friction coefficient. It applies only to gestures in the scrolling area, and it affects only indirectly the scroll chaining during the inertial scrolling process. If this attribute is set to a value less than or equal to 0, the default value is used. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -215,6 +217,8 @@ Sets the initial scrolling offset. This attribute takes effect only during the i ## ScrollDirection +Enumerates the scrolling directions. + **System capability**: SystemCapability.ArkUI.ArkUI.Full | Name | Description | @@ -226,6 +230,8 @@ Sets the initial scrolling offset. This attribute takes effect only during the i ## ScrollSnapOptions10+ +Defines a scroll snapping mode object. + **Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -233,13 +239,16 @@ Sets the initial scrolling offset. This attribute takes effect only during the i | Name | Type | Mandatory | Description | | ---------- | --------------------|-------------------- | -------- | | snapAlign | [ScrollSnapAlign](ts-container-list.md#scrollsnapalign10) | Yes| Alignment mode for the scroll snap position.
**NOTE**
1. Default value: **ScrollSnapAlign.NONE**| -| snapPagination | [Dimension](ts-types.md#dimension10) \| Array\ | No| Snap points for the **Scroll** component. Each snap point defines the offset from an edge to which the **Scroll** component can scroll.
**NOTE**
1. A value of the **Dimension** type indicates the size per page. The system automatically works out the position of each snap point based on the value. For example, if the value is **500**, the position of the snap point is [0,500,1000,1500, ...].
2. A value of the **Array\** type indicates an array of snap point positions defined by **Dimension**. The range of each dimension is [0, scrollable distance]. Point 0 and the bottom of the scrollable distance automatically become the snap points.
3. If this attribute is not set or **Dimension** is set to a value less than or equal to 0, the value is regarded as an abnormal value. In this case, there is no scroll snapping. When the value is of the **Array\** type, the items in the array must be monotonically increasing.
4. When the value is a percentage, the actual size is the product of the viewport of the **Scroll** component and the percentage value.| -| enableSnapToStart | boolean | No| Whether to enable the snap to start feature. When scroll snapping is defined for the **Scroll** component, setting this attribute to **false** enables the component to scroll between the start edge and the first snap point.
**NOTE**
1. Default value: **true**
2. This attribute takes effect only when **snapPagination** is set to a value of the **Array\** type; it does not work with values of the **Dimension** type.| -| enableSnapToEnd | boolean | No| Whether to enable the snap to end feature. When scroll snapping is defined for the **Scroll** component, setting this attribute to **false** enables the component to scroll between the end edge and the last snap point.
**NOTE**
1. Default value: **true**
2. This attribute takes effect only when **snapPagination** is set to a value of the **Array\** type; it does not work with values of the **Dimension** type.| +| snapPagination | [Dimension](ts-types.md#dimension10) \| Array\ | No| Pagination points for scroll snapping.
**NOTE**
1. If the value is of the Dimension type, it indicates the size of each page, and the system will paginate based on this size.
2. If the value is of the Array\ type, each **Dimension** represents a pagination point, and the system will paginate accordingly. Each **Dimension** value must be within the [0, scrollable distance] range.
3. If this parameter is not set or **Dimension** is set to a value less than or equal to 0, the value is regarded as an invalid value. In this case, there is no scroll snapping. When the value is of the Array\ type, the items in the array must be monotonically increasing.
4. When the value is a percentage, the actual size is the product of the viewport of the **Scroll** component and the percentage value.| +| enableSnapToStart | boolean | No| Whether to enable the snap to start feature. When scroll snapping is defined for the **Scroll** component, setting this parameter to **false** enables the component to scroll between the start and the first page.
**NOTE**
1. Default value: **true**
2. This attribute takes effect only when **snapPagination** is set to a value of the **Array\** type; it does not work with values of the **Dimension** type.| +| enableSnapToEnd | boolean | No| Whether to enable the snap to end feature. When scroll snapping is defined for the **Scroll** component, setting this parameter to **false** enables the component to scroll between the end and the last page.
**NOTE**
1. Default value: **true**
2. This attribute takes effect only when **snapPagination** is set to a value of the **Array\** type; it does not work with values of the **Dimension** type.| ## Events -In addition to [universal events](ts-universal-events-click.md) and [scrollable component common events](ts-container-scrollable-common.md#events), the following events are also supported. +In addition to [universal events](ts-component-general-events.md) and [scrollable component common events](ts-container-scrollable-common.md#events), the following events are also supported. +> **NOTE** +> +> The [onWillScroll](ts-container-scrollable-common.md#onwillscroll12) and [onDidScroll](ts-container-scrollable-common.md#ondidscroll12) events are not supported. ### onScrollFrameBegin9+ @@ -510,7 +519,7 @@ Represents the callback triggered before each frame scrolling starts. ## Scroller -Implements a controller for a scrollable container component. You can bind this component to a container component and use it to control the scrolling of that component. One controller can control only one container component. The supported container components are **List**, **Scroll**, **ScrollBar**, **Grid**, and **WaterFlow**. +Defines a controller for scrollable container components. It can be bound to a container component to control its scrolling behavior. A single **Scroller** instance cannot control multiple container components simultaneously. Currently, it can be bound to the following components: **ArcList**, **ArcScrollBar**, **List**, **Scroll**, **ScrollBar**, **Grid**, and **WaterFlow**. >**NOTE** > @@ -537,7 +546,7 @@ A constructor used to create a **Scroller** object. ### scrollTo -scrollTo(value: [ScrollOptions](#scrolloptions16)) +scrollTo(options: [ScrollOptions](#scrolloptions16)) Scrolls to the specified position. @@ -550,13 +559,12 @@ Scrolls to the specified position. | Name | Type| Mandatory | Description | | ----- | ---- | ---- | --------- | -| value | [ScrollOptions](#scrolloptions16) | Yes | Parameters for scrolling to the specified position. +| options | [ScrollOptions](#scrolloptions16) | Yes | Parameters for scrolling to the specified position. ### scrollEdge scrollEdge(value: Edge, options?: ScrollEdgeOptions) - Scrolls to the edge of the container, regardless of the scroll axis direction. **Edge.Top** and **Edge.Start** produce the same effect, and **Edge.Bottom** and **Edge.End** produce the same effect. By default, the **Scroll** component comes with an animation, while the **Grid**, **List**, and **WaterFlow** components do not. @@ -584,11 +592,11 @@ Performs inertial scrolling based on the initial velocity passed in. | Name | Type| Mandatory| Description | | -------- | -------- | ---- | ------------------------------------------------------------ | -| velocity | number | Yes | Initial velocity of inertial scrolling. Unit: vp/s
**NOTE**
If the value specified is 0, it is considered as invalid, and the scrolling for this instance will not take effect. If the value is positive, the scroll will move downward; if the value is negative, the scroll will move upward.| +| velocity | number | Yes | Initial velocity of inertial scrolling. Unit: vp/s
**NOTE**
If the value specified is 0, it is considered as invalid, and the scrolling for this instance will not take effect. A positive value indicates scrolling towards the top, while a negative value indicates scrolling towards the bottom.| **Error codes** -For details about the error codes, see [Universal Error Codes](../../errorcode-universal.md). +For details about the error codes, see [Universal Error Codes](../../errorcode-universal.md) and [Scrollable Component Error Codes](../errorcode-scroll.md). | ID| Error Message| | ------- | -------- | @@ -609,7 +617,7 @@ Scrolls to the next or previous page. | Name| Type | Mandatory| Description | | ------ | -------------------------------------------------- | ---- | -------------- | -| value | [ScrollPageOptions](#scrollpageoptions14) | Yes | Set the Home screen mode| +| value | [ScrollPageOptions](#scrollpageoptions14) | Yes | Page turning mode.| ### scrollPage(deprecated) @@ -630,13 +638,15 @@ Scrolls to the next or previous page. This API is deprecated since API version 9 currentOffset(): OffsetResult +Obtains the current scrolling offset. + **Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full | Type | Description| | -------- | -------- | -| [OffsetResult11+](#offsetresult11) | Scrolling offset.
**NOTE**
If **Scroller** is not bound to a container component or the container component is released abnormally, the return value for **currentOffset** is null.| +| [OffsetResult11+](#offsetresult11) | Obtains the scrolling offset.
**NOTE**
If **Scroller** is not bound to a container component or the container component is released abnormally, the return value for **currentOffset** is null.| ### scrollToIndex @@ -649,7 +659,7 @@ When **smooth** is set to **true**, all passed items are loaded and counted in l > **NOTE** > -> This API only works for the **Grid**, **List**, and **WaterFlow** components. +> This API only works for the **ArcList**, **Grid**, **List**, and **WaterFlow** components. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -674,7 +684,7 @@ Scrolls by the specified amount. > **NOTE** > -> This API is available for the **Scroll**, **List**, **Grid**, and **WaterFlow** components. +> This API is available for the **ArcList**, **Scroll**, **List**, **Grid**, and **WaterFlow** components. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -695,7 +705,7 @@ Checks whether the component has scrolled to the bottom. > **NOTE** > -> This API is available for the **Scroll**, **List**, **Grid**, and **WaterFlow** components. +> This API is available for the **ArcList**, **Scroll**, **List**, **Grid**, and **WaterFlow** components. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -715,7 +725,7 @@ Obtains the size and position of a child component relative to its container. > **NOTE** > -> This API is available for the **Scroll**, **List**, **Grid**, and **WaterFlow** components. +> This API is available for the **ArcList**, **Scroll**, **List**, **Grid**, and **WaterFlow** components. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -740,7 +750,7 @@ Obtains the size and position of a child component relative to its container. **Error codes** -For details about the error codes, see [Universal Error Codes](../../errorcode-universal.md). +For details about the error codes, see [Universal Error Codes](../../errorcode-universal.md) and [Scrollable Component Error Codes](../errorcode-scroll.md). | ID| Error Message| | ------- | -------- | @@ -779,15 +789,17 @@ Obtains the index of a child component based on coordinates. **Error codes** -For details about the error codes, see [Universal Error Codes](../../errorcode-universal.md). +For details about the error codes, see [Universal Error Codes](../../errorcode-universal.md) and [Scrollable Component Error Codes](../errorcode-scroll.md). | ID| Error Message| | ------- | -------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | -| 100004 | Controller not bound to component. | +| 100004 |The controller not bound to component. | ## OffsetResult11+ +Represents the offset values resulting from a scroll operation. + **Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -799,6 +811,8 @@ For details about the error codes, see [Universal Error Codes](../../errorcode-u ## ScrollAnimationOptions12+ +Provides parameters for customizing scroll animations. + **Atomic service API**: This API can be used in atomic services since API version 12. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -811,6 +825,8 @@ For details about the error codes, see [Universal Error Codes](../../errorcode-u ## ScrollAlign10+ +Enumerates alignment modes. + **Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -824,6 +840,8 @@ For details about the error codes, see [Universal Error Codes](../../errorcode-u ## ScrollToIndexOptions12+ +Provides parameters for scrolling to a specific index. + **Atomic service API**: This API can be used in atomic services since API version 12. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -834,6 +852,8 @@ For details about the error codes, see [Universal Error Codes](../../errorcode-u ## ScrollPageOptions14+ +Provides parameters for page scrolling behavior. + **Atomic service API**: This API can be used in atomic services since API version 14. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -845,6 +865,8 @@ For details about the error codes, see [Universal Error Codes](../../errorcode-u ## OffsetOptions12+ +Provides parameters for setting the initial scrolling offset. + **Atomic service API**: This API can be used in atomic services since API version 12. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -856,6 +878,8 @@ For details about the error codes, see [Universal Error Codes](../../errorcode-u ## ScrollEdgeOptions12+ +Provides parameters for scrolling to the edge of a scrollable container. + **Atomic service API**: This API can be used in atomic services since API version 12. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -866,6 +890,8 @@ For details about the error codes, see [Universal Error Codes](../../errorcode-u ## ScrollOptions16+ +Provides parameters for scrolling to a specific position in a scrollable container. + **Atomic service API**: This API can be used in atomic services since API version 16. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -1346,7 +1372,7 @@ struct ScrollExample { ![fadingEdge_scroll](figures/fadingEdge_scroll.gif) -### Example 9: Setting the Single-Side Edge Effect +### Example 8: Setting the Single-Side Edge Effect This example demonstrates how to set a single-side edge effect for the **Scroll** component using the **edgeEffect** API. diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-scrollable-common.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-scrollable-common.md index 8e57f7e4e8714cb3fc01525afcd5cc150c6b253d..dc8cafa58541bcee4b92064cc97cad191584544c 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-scrollable-common.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-scrollable-common.md @@ -38,7 +38,7 @@ Sets the scrollbar color. | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | -------------- | -| color | string \| number \| [Color](ts-appendix-enums.md#color) | Yes | Scrollbar color.
Default value: **'\#182431'** (40% opacity)| +| color | string \| number \| [Color](ts-appendix-enums.md#color) | Yes | Scrollbar color.
Default value: **'\#182431'** (40% opacity)
A number value indicates a HEX color in RGB or ARGB format, for example, **0xffffff**. A string value indicates a color in RGB or ARGB format, for example, **'#ffffff'**.| ### scrollBarWidth11+ @@ -54,7 +54,7 @@ Sets the scrollbar width. This attribute cannot be set in percentage. After the | Name| Type | Mandatory| Description | | ------ | -------------------------- | ---- | ----------------------------------------- | -| value | string \| number | Yes | Scrollbar width.
Default value: **4**
Unit: vp| +| value | string \| number | Yes | Scrollbar width.
Default value: **4**
Unit: vp
If this parameter is set to a value less than or equal to 0, the default value is used. The value **0** means not to show the scrollbar.| ### edgeEffect11+ @@ -119,13 +119,13 @@ Sets the friction coefficient. It applies only to gestures in the scrolling area | Name| Type | Mandatory| Description | | ------ | ---------------------------------------------------- | ---- | --------------------------------------------------------- | -| value | number \| [Resource](ts-types.md#resource) | Yes | Friction coefficient.
Default value: **0.9** for wearable devices and **0.6** for non-wearable devices
Since API version 11, the default value for non-wearable devices is **0.7**.
Since API version 12, the default value for non-wearable devices is **0.75**.| +| value | number \| [Resource](ts-types.md#resource) | Yes | Friction coefficient.
Default value: **0.9** for wearable devices and **0.6** for non-wearable devices
Since API version 11, the default value for non-wearable devices is **0.7**.
Since API version 12, the default value for non-wearable devices is **0.75**.
Value range: (0, +∞). If this parameter is set to a value less than or equal to 0, the default value is used.| ### flingSpeedLimit11+ flingSpeedLimit(speedLimit: number): T -Sets the maximum initial velocity at the start of the fling animation that occurs after gesture-driven scrolling ends. If this attribute is set to a value less than or equal to 0, the default value is used. +Sets the maximum initial velocity at the start of the fling animation that occurs after gesture-driven scrolling ends. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -135,7 +135,7 @@ Sets the maximum initial velocity at the start of the fling animation that occur | Name | Type | Mandatory| Description | | ---------- | ------ | ---- | ------------------------------- | -| speedLimit | number | Yes | Maximum initial velocity at the start of the fling animation.
Default value: **12000**
Unit: vp/s| +| speedLimit | number | Yes | Maximum initial velocity at the start of the fling animation.
Default value: **9000**
Unit: vp/s
Value range: (0, +∞). If this parameter is set to a value less than or equal to 0, the default value is used.| ### fadingEdge14+ @@ -151,7 +151,7 @@ Sets whether to enable the edge fading effect and the length of the fading edge. | Name | Type | Mandatory| Description | | ------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | -| enabled | Optional<boolean> | Yes | Whether to enable the edge fading effect.
When **fadingEdge** is set to **true**, it overrides the **.overlay()** attribute of the component.
With **fadingEdge** set to **true**, avoid setting background-related attributes on the component, as this may affect the display of the fading effect.
With **fadingEdge** set to **true**, the component is clipped to the boundary, and setting the component's **clip** attribute to **false** will not take effect.
Default value: **false**| +| enabled | Optional<boolean> | Yes | Whether to enable the edge fading effect.
When **fadingEdge** is set to **true**, it overrides the **.overlay()** attribute of the component.
With **fadingEdge** set to **true**, avoid setting background-related attributes on the component, as this may affect the display of the fading effect.
With **fadingEdge** set to **true**, the component is clipped to the boundary, and setting the component's **clip** attribute to **false** will not take effect.
Default value: **false**, which means not to enable the edge fading effect| | options | [FadingEdgeOptions](#fadingedgeoptions14) | No | Object defining edge fading effect properties, such as the fading edge length.| ### clipContent14+ @@ -170,6 +170,25 @@ Sets the content clipping area for this scrollable component. | ------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | | clip | [ContentClipMode](#contentclipmode14) \| [RectShape](../js-apis-arkui-shape.md#rectshape) | Yes | Clipping to apply, which is effective only for the content (that is, child components) of the scrollable component, not the background. When a custom rectangular area is passed through **RectShape**, only width, height, and [offset](../js-apis-arkui-shape.md#offset) relative to the component's upper left corner are supported, and rounded corners are not supported.
Default value: The default value for **Grid** and **Scroll** is **ContentClipMode.BOUNDARY**, and the default value for **List** and **WaterFlow** is **ContentClipMode.CONTENT_ONLY**.| +### backToTop15+ + +backToTop(backToTop: boolean) + +Sets whether to enable the back-to-top feature for a scrollable component when the status bar is touched. + +If this feature is enabled, the scrollable component on the current page scrolls to the top when the user touches the status bar. This behavior does not affect scrollable components in background applications, which will not scroll to the top. This attribute is independent of the [enableScrollInteraction](#enablescrollinteraction11) setting. + +**Atomic service API**: This API can be used in atomic services since API version 15. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ---------------------------------------------- | +| backToTop | boolean | Yes | Whether to enable the back-to-top feature for a scrollable component when the status bar is touched.
Default value: **false**| + + ## Events @@ -293,6 +312,8 @@ This API is deprecated since API version 12. For the **Scroll** component, the * ## ItemDragInfo +Provides information about the drag point. + **Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -304,6 +325,8 @@ This API is deprecated since API version 12. For the **Scroll** component, the * ## NestedScrollOptions10+ +Implements an object used to configure the [nestedScroll](#nestedscroll11) attribute. + **Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -315,6 +338,8 @@ This API is deprecated since API version 12. For the **Scroll** component, the * ## EdgeEffectOptions11+ +Implements an object used to configure the [edgeEffect](#edgeeffect11) attribute. + **Atomic service API**: This API can be used in atomic services since API version 12. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -322,10 +347,12 @@ This API is deprecated since API version 12. For the **Scroll** component, the * | Name | Type | Mandatory| Description | | ----- | ------| ------- | ----------------- | | alwaysEnabled | boolean | Yes| Whether to enable the scroll effect when the component content is smaller than the component itself.| -| effectEdge16+ | number | No| Edge where the edge effect is applied. With **[EffectEdge](#effectedge16).START**, the edge effect is applied to the start edge only. With **[EffectEdge](#effectedge16).END**, the edge effect is applied to the end edge only. The default value is [EffectEdge](#effectedge16).START \| [EffectEdge](#effectedge16).END, which means that the edge effect is applied to both the start and end edges. If an invalid value is set, the edge effect is applied to both the start and end edges by default.
**Atomic service API**: This API can be used in atomic services since API version 16.| +| effectEdge18+ | number | No| Edge where the edge effect is applied.
With **[EffectEdge](#effectedge18).START**, the edge effect is applied to the start edge only. With **[EffectEdge](#effectedge18).END**, the edge effect is applied to the end edge only.
The default value is [EffectEdge](#effectedge18).START \| [EffectEdge](#effectedge18).END, which means that the edge effect is applied to both the start and end edges. If an invalid value is set, the edge effect is applied to both the start and end edges.
To disable the effect on both edges, set **edgeEffect** to **EdgeEffect.None**.| ## FadingEdgeOptions14+ +Implements an object used to configure the [fadingEdge](#fadingedge14) attribute. + **Atomic service API**: This API can be used in atomic services since API version 14. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -334,11 +361,11 @@ This API is deprecated since API version 12. For the **Scroll** component, the * | ---------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | fadingEdgeLength | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | No | Length of the fading edge. If the value is smaller than 0, the default length, 32 vp, is used.
If the value exceeds half the height of the container, it is adjusted to exactly half the height of the container.| -## EffectEdge16+ +## EffectEdge18+ Enumerates the edges where the edge effect is applied. -**Atomic service API**: This API can be used in atomic services since API version 16. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -387,7 +414,7 @@ Callback triggered when the scrollable component is about to scroll. | Type | Description | | ----------------------------- | ------------------------------------ | -| void \| [ScrollResult](#scrollresult12) | Returns a **ScrollResult** object if the scrollable component scrolls by the offset specified by you; returns no **ScrollResult** object if the component scrolls by the offset specified by **scrollOffset** in the callback.| +| void \| [ScrollResult](#scrollresult12) | Returns a **ScrollResult** object if the scrollable component scrolls by the offset specified by you; returns no **ScrollResult** object if the component scrolls by the offset specified by **scrollOffset** in the callback.
Value range: (-∞, +∞)| ## OnScrollCallback12+ @@ -408,6 +435,8 @@ Callback triggered when the scrollable component scrolls. ## ScrollResult12+ +Implements a return value object of the [OnWillScrollCallback](#onwillscrollcallback12) callback. + **Atomic service API**: This API can be used in atomic services since API version 12. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -422,6 +451,8 @@ Provides the size information of the child components of the **List** or **ListI **Atomic service API**: This API can be used in atomic services since API version 12. +**System capability**: SystemCapability.ArkUI.ArkUI.Full + ### constructor12+ constructor(childDefaultSize: number): void @@ -475,7 +506,7 @@ Obtains the default size of the child component along the main axis. | Type | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| number | Default size of the child component along the main axis.
Unit: vp| +| number | Default size of the child component along the main axis.
Unit: vp
Value range: [0, +∞)| ### splice12+ @@ -491,9 +522,9 @@ Performs batch operations to add, delete, or modify the size information of chil | Name | Type | Mandatory | Description | | ---- | ----------------------------- | ---- | -------------------- | -| start | number | Yes | Index starting from 0, which indicates the position at which to begin modifying the size information of child components along the main axis.
**NOTE**
1. The value must be a finite non-negative number; otherwise, an exception will be thrown.
2. Non-integer values are truncated to the nearest integer.
3. Values exceeding the maximum index do not take effect.| -| deleteCount | number | No | Number of size information entries to be deleted starting from the **start** position.
**NOTE**
1. The value must be a finite non-negative number; otherwise, it will be treated as **0**.
2. Non-integer values are truncated to the nearest integer.
3. The result of (start + deleteCount - 1) can exceed the maximum index, which will delete all size information of child components starting from the **start** position.| -| childrenSize | Array\ | No | Size information of all child components to be inserted, starting from the **start** position.
Unit for each value in the array: vp
**NOTE**
1. If the values in the array are finite non-negative number, they are considered specified sizes and will not change with the default size.
2. 2. If the values in the array are not finite non-negative number, they will be treated as the default size and will change with the default size. | +| start | number | Yes | Index starting from 0, which indicates the position at which to begin modifying the size information of child components along the main axis.
**NOTE**
1. The value must be a finite non-negative number; otherwise, an exception will be thrown.
2. Non-integer values are truncated to the nearest integer.
3. Values exceeding the maximum index do not take effect.
Value range: [0, +∞)| +| deleteCount | number | No | Number of size information entries to be deleted starting from the **start** position.
**NOTE**
1. The value must be a finite non-negative number; otherwise, it will be treated as **0**.
2. Non-integer values are truncated to the nearest integer.
3. The result of (start + deleteCount - 1) can exceed the maximum index, which will delete all size information of child components starting from the **start** position.
Default value: **+∞**
Value range: [0, +∞)| +| childrenSize | Array\ | No | Size information of all child components to be inserted, starting from the **start** position.
Unit for each value in the array: vp
**NOTE**
1. If the values in the array are finite non-negative number, they are considered specified sizes and will not change with the default size.
2. 2. If the values in the array are not finite non-negative number, they will be treated as the default size and will change with the default size.
The default value is an empty array.
Value range: [0, +∞)| **Error codes** @@ -526,8 +557,8 @@ Updates the main axis size information of the child component corresponding to t | Name | Type | Mandatory | Description | | ---- | ----------------------------- | ---- | -------------------- | -| index | number | Yes | Index starting from 0, which indicates the position at which to begin modifying the size information of child components along the main axis.
**NOTE**
1. The value must be a finite non-negative number; otherwise, an exception will be thrown.
2. Non-integer values are truncated to the nearest integer.
3. Values exceeding the maximum index do not take effect.| -| childSize | number | Yes | Size to be updated to.
Unit: vp
**NOTE**
1. If the value is a finite non-negative number, it is considered a specified size and will not change with the default size.
2. 2. If the value is not a finite non-negative number, it will be processed as the default size and will change with the default size. | +| index | number | Yes | Index starting from 0, which indicates the position at which to begin modifying the size information of child components along the main axis.
**NOTE**
1. The value must be a finite non-negative number; otherwise, an exception will be thrown.
2. Non-integer values are truncated to the nearest integer.
3. Values exceeding the maximum index do not take effect.
Value range: [0, +∞)| +| childSize | number | Yes | Size to be updated to.
Unit: vp
**NOTE**
1. If the value is a finite non-negative number, it is considered a specified size and will not change with the default size.
2. 2. If the value is not a finite non-negative number, it will be processed as the default size and will change with the default size.
Value range: [0, +∞)| **Error codes** diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-sidebarcontainer.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-sidebarcontainer.md index bb96190bad560d297d1df4c59df7707e30b43ecc..f3bea7581bb5843986891dd838c92042806bfede 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-sidebarcontainer.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-sidebarcontainer.md @@ -22,6 +22,8 @@ Supported SideBarContainer( type?: SideBarContainerType ) +Creates a sidebar container. + **Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -34,6 +36,8 @@ SideBarContainer( type?: SideBarContainerType ) ## SideBarContainerType +Enumerates the types of sidebars in a container. + **Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -42,11 +46,11 @@ SideBarContainer( type?: SideBarContainerType ) | -------- | -------- | | Embed | The sidebar is embedded in the component and displayed side by side with the content area.
When the component size is less than the sum of **minContentWidth** and **minSideBarWidth** and **showSideBar** is not set, the sidebar is automatically hidden.
If **minSideBarWidth** or **minContentWidth** is not set, the default value will be used for calculation.
The user can bring out the sidebar in Overlay mode by clicking the control button.| | Overlay | The sidebar is displayed overlaid on the content area.| -| AUTO10+ | The sidebar is displayed in Embed mode when the component size is greater than or equal to the sum of **minSideBarWidth** and **minContentWidth** and in Overlay mode otherwise.
If **minSideBarWidth** or **minContentWidth** is not set, the default value will be used for calculation. If the calculation result is less than 600 vp, 600 vp will be used as the breakpoint value for mode switching.| +| AUTO10+ | The sidebar is displayed in Embed mode when the component size is greater than or equal to the sum of **minSideBarWidth** and **minContentWidth**
and in Overlay mode otherwise.
If **minSideBarWidth** or **minContentWidth** is not set, the default value will be used for calculation. If the calculation result is less than 600 vp, 600 vp will be used as the breakpoint value for mode switching.| ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### showSideBar @@ -102,7 +106,7 @@ Specifies whether to display the sidebar control button. sideBarWidth(value: number) -Sets the width of the sidebar. A value less than 0 evaluates to the default value. The value must comply with the width constraints. If it is not within the valid range, the valid value closest to the set one is used. +Sets the width of the sidebar. If a value less than 0 is set, the default value is used. The value must comply with the width constraints. If it is not within the valid range, the valid value closest to the set one is used. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -112,13 +116,13 @@ Sets the width of the sidebar. A value less than 0 evaluates to the default valu | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| value | number | Yes | Width of the sidebar.
Default value: **240vp**
Unit: vp
**NOTE**
In API version 9 and earlier versions, the default value is **200vp**. In API version 10, the default value is **240vp**.| +| value | number | Yes | Width of the sidebar.
Default value: **240vp**
Unit: vp
Value range: [0, +∞).
**NOTE**
In API version 9 and earlier versions, the default value is **200vp**. In API version 10, the default value is **240vp**.| ### sideBarWidth9+ sideBarWidth(value: Length) -Sets the width of the sidebar. A value less than 0 evaluates to the default value. The value must comply with the width constraints. If it is not within the valid range, the valid value closest to the set one is used. +Sets the width of the sidebar. If a value less than 0 is set, the default value is used. The value must comply with the width constraints. If it is not within the valid range, the valid value closest to the set one is used. Compared to [sideBarWidth](#sidebarwidth), this API supports percentage strings and other [pixel units](ts-pixel-units.md) for the **value** parameter. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -128,13 +132,13 @@ Sets the width of the sidebar. A value less than 0 evaluates to the default valu | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| value | [Length](ts-types.md#length) | Yes | Width of the sidebar.
Default value: **240vp**
Unit: vp
**NOTE**
The default value is **200vp** in API version 9 and **240vp** in API version 10.| +| value | [Length](ts-types.md#length) | Yes | Width of the sidebar.
Default value: **240vp**.
Unit: vp.
Value range: [0, +∞).
**NOTE**
The default value is **200vp** in API version 9 and **240vp** in API version 10.| ### minSideBarWidth minSideBarWidth(value: number) -Sets the minimum width of the sidebar. A value less than 0 evaluates to the default value. The value cannot exceed the width of the sidebar container itself. Otherwise, the width of the sidebar container itself is used. +Sets the minimum width of the sidebar. If a value less than 0 is set, the default value is used. The value cannot exceed the width of the sidebar container itself. Otherwise, the width of the sidebar container itself is used. **minSideBarWidth**, whether it is specified or kept at the default value, takes precedence over **minWidth** of the sidebar child components. @@ -146,13 +150,13 @@ Sets the minimum width of the sidebar. A value less than 0 evaluates to the defa | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| value | number | Yes | Minimum width of the sidebar.
Default value: In API version 9 and earlier versions, the default value is **200vp**. In API version 10, the default value is **240vp**.| +| value | number | Yes | Minimum width of the sidebar.
Default value: In API version 9 and earlier versions, the default value is **200vp**. In API version 10, the default value is **240vp**.
Value range: [0, +∞).| ### minSideBarWidth9+ minSideBarWidth(value: Length) -Sets the minimum width of the sidebar. A value less than 0 evaluates to the default value. The value cannot exceed the width of the sidebar container itself. Otherwise, the width of the sidebar container itself is used. +Sets the minimum width of the sidebar. If a value less than 0 is set, the default value is used. The value cannot exceed the width of the sidebar container itself. Otherwise, the width of the sidebar container itself is used. Compared to [minSideBarWidth](#minsidebarwidth), this API supports percentage strings and other [pixel units](ts-pixel-units.md) for the **value** parameter. **minSideBarWidth**, whether it is specified or kept at the default value, takes precedence over **minWidth** of the sidebar child components. @@ -164,13 +168,13 @@ Sets the minimum width of the sidebar. A value less than 0 evaluates to the defa | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| value | [Length](ts-types.md#length) | Yes | Minimum width of the sidebar.
Default value: In API version 9 and earlier versions, the default value is **200vp**. In API version 10, the default value is **240vp**.| +| value | [Length](ts-types.md#length) | Yes | Minimum width of the sidebar.
Default value: In API version 9 and earlier versions, the default value is **200vp**. In API version 10, the default value is **240vp**.
Value range: [0, +∞).| ### maxSideBarWidth maxSideBarWidth(value: number) -Sets the maximum width of the sidebar. A value less than 0 evaluates to the default value. The value cannot exceed the width of the sidebar container itself. Otherwise, the width of the sidebar container itself is used. +Sets the maximum width of the sidebar. If a value less than 0 is set, the default value is used. The value cannot exceed the width of the sidebar container itself. Otherwise, the width of the sidebar container itself is used. **maxSideBarWidth**, whether it is specified or kept at the default value, takes precedence over **maxWidth** of the sidebar child components. @@ -182,13 +186,13 @@ Sets the maximum width of the sidebar. A value less than 0 evaluates to the defa | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | --------------------------------------------------- | -| value | number | Yes | Maximum width of the sidebar.
Default value: **280vp**
Unit: vp| +| value | number | Yes | Maximum width of the sidebar.
Default value: **280vp**
Unit: vp.
Value range: [0, +∞).| ### maxSideBarWidth9+ maxSideBarWidth(value: Length) -Sets the maximum width of the sidebar. A value less than 0 evaluates to the default value. The value cannot exceed the width of the sidebar container itself. Otherwise, the width of the sidebar container itself is used. +Sets the maximum width of the sidebar. If a value less than 0 is set, the default value is used. The value cannot exceed the width of the sidebar container itself. Otherwise, the width of the sidebar container itself is used. **maxSideBarWidth**, whether it is specified or kept at the default value, takes precedence over **maxWidth** of the sidebar child components. @@ -200,7 +204,7 @@ Sets the maximum width of the sidebar. A value less than 0 evaluates to the defa | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | --------------------------------------------------- | -| value | [Length](ts-types.md#length) | Yes | Maximum width of the sidebar.
Default value: **280vp**
Unit: vp| +| value | [Length](ts-types.md#length) | Yes | Maximum width of the sidebar.
Default value: **280vp**
Unit: vp.
Value range: [0, +∞).| ### autoHide9+ @@ -283,17 +287,19 @@ until its width reaches the value defined by **minSideBarWidth**; if the compone ## ButtonStyle +Describes the style of the sidebar control button. + **Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| left | number | No| Spacing between the sidebar control button and the left of the container.
Default value: **16vp**
Unit: vp| -| top | number | No| Spacing between the sidebar control button and the top of the container.
Default value: **48vp**
Unit: vp| -| width | number | No| Width of the sidebar control button.
Default value:
API version 9 and earlier versions: **32vp**
API version 10 and later versions: **24vp**
Unit: vp| -| height | number | No| Height of the sidebar control button.
Default value:
API version 9 and earlier versions: **32vp**
API version 10 and later versions: **24vp**
Unit: vp| -| icons | [ButtonIconOptions](#buttoniconoptions14) | No| Icons of the sidebar control button.| +| left | number | No| Spacing between the sidebar control button and the left of the container.
Default value: **16vp**
Unit: vp.
Value range: [0, +∞).| +| top | number | No| Spacing between the sidebar control button and the top of the container.
Default value: **48vp**
Unit: vp.
Value range: [0, +∞).| +| width | number | No| Width of the sidebar control button.
Default value:
API version 9 and earlier versions: **32vp**
API version 10 and later versions: **24vp**
Unit: vp.
Value range: [0, +∞).| +| height | number | No| Height of the sidebar control button.
Default value:
API version 9 and earlier versions: **32vp**
API version 10 and later versions: **24vp**
Unit: vp.
Value range: [0, +∞).| +| icons | [ButtonIconOptions14+](#buttoniconoptions14) | No| Icons of the sidebar control button.| ## ButtonIconOptions14+ @@ -305,9 +311,9 @@ Describes the icons of the sidebar control button. | Name | Type | Mandatory| Description | | --------- | -------------------------------| ---- | ------------------------------------------ | -| shown | string \| [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Yes | Icon of the control button when the sidebar is displayed. | -| hidden | string \| [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Yes | Icon of the control button when the sidebar is hidden. | -| switching | string \| [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | No | Icon of the control button when the sidebar is switching between the shown and hidden states.| +| shown8+ | string \| [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Yes | Icon of the control button when the sidebar is displayed.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| hidden8+ | string \| [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Yes | Icon of the control button when the sidebar is hidden.
**Atomic service API**: This API can be used in atomic services since API version 11. | +| switching8+ | string \| [PixelMap](../../apis-image-kit/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | No | Icon of the control button when the sidebar is switching between the shown and hidden states.
**Atomic service API**: This API can be used in atomic services since API version 11.| > **NOTE** > @@ -328,6 +334,8 @@ Enumerates the positions of the sidebar. ## DividerStyle10+ +Sets the divider style. + **Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -350,7 +358,7 @@ Enumerates the positions of the sidebar. ## Events -In addition to the [universal events](ts-universal-events-click.md), the following events are supported. +In addition to the [universal events](ts-component-general-events.md), the following events are supported. ### onChange diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-stack-sys.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-stack-sys.md index fd15da892314a7777ca6c59f37d688d04f206a94..f0d378ecc4d7532ec03c68f0ca404761de233b68 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-stack-sys.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-stack-sys.md @@ -10,7 +10,7 @@ The **Stack** component provides a stack container where child components are su ## Attributes -## pointLight +### pointLight pointLight(value: PointLightStyle) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-stack.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-stack.md index a1d67016aff9d514957a7eab2e1e42e3f412a9a9..66a5bef06bafae1981154684208f3c84bcaf56af 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-stack.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-stack.md @@ -42,7 +42,7 @@ Stack(options?: StackOptions) ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### alignContent diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-swiper.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-swiper.md index 3096cf6f662d2789f96b5f4b570c7f34adc0a882..d37d798a4f6982a20fe7c2344948fe38725d9526 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-swiper.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-swiper.md @@ -1,13 +1,11 @@ # Swiper - The **Swiper** component is able to display child components in looping mode. + The **Swiper** component is able to display child components in a carousel-like manner. > **NOTE** > > - This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > -> - The default value of the universal attribute [clip](ts-universal-attributes-sharp-clipping.md) is **true** for the **Swiper** component. -> > - The **Swiper** component incorporates a [PanGesture](ts-basic-gestures-pangesture.md) event that facilitates the swiping action to cycle through its child components. Setting [disableSwipe](#disableswipe8) to **true** will cancel the internal listening for the **PanGesture** event, disabling the swiping interaction. ## Child Components @@ -16,26 +14,20 @@ This component can contain child components. > **NOTE** > -> - Child components can consist of both built-in components and custom components, and their rendering can be controlled with [if/else](../../../quick-start/arkts-rendering-control-ifelse.md), [ForEach](../../../quick-start/arkts-rendering-control-foreach.md), [LazyForEach](../../../quick-start/arkts-rendering-control-lazyforeach.md), and [Repeat](../../../quick-start/arkts-new-rendering-control-repeat.md). To maximize the benefits of lazy loading, avoid mixing lazy loading components (including **LazyForEach** and **Repeat**) and non-lazy loading components, and exercise caution when using multiple lazy loading components. -> -> - If a child component has its **visibility** attribute set to **None** and the **Swiper** component has its **displayCount** attribute set to **'auto'**, the child component takes up space in the viewport, but is not displayed. -> -> - If a child component has its **visibility** attribute set to **None** or **Hidden**, it takes up space in the viewport, but is not displayed. -> -> - When the number of child components is less than or equal to the total number of allowed nodes in the content area (totalDisplayCount = displayCount + prevMargin? (1 : 0 ) + nextMargin? (1 : 0 )), the **Swiper** component generally uses the non-looping mode for layout. In this case, the child components specified by **nextMargin** and **prevMargin** take up space in the viewport, but are not displayed. The specifications of the **Swiper** component are calculated based on the value of **totalDisplayCount**. The exceptions are as follows: -> -> - When the number of child components is equal to the total number of allowed nodes in the content area and both **prevMargin** and **nextMargin** take effect, set **loop** to **true** to enable loop playback. +> - Child components can consist of both built-in components and custom components, and their rendering can be controlled with [if/else](../../../quick-start/arkts-rendering-control-ifelse.md), [ForEach](../../../quick-start/arkts-rendering-control-foreach.md), [LazyForEach](../../../quick-start/arkts-rendering-control-lazyforeach.md), and [Repeat](../../../quick-start/arkts-new-rendering-control-repeat.md). To maximize the benefits of lazy loading, avoid mixing lazy loading components (including **LazyForEach** and **Repeat**) and non-lazy loading components, and exercise caution when using multiple lazy loading components. Avoid modifying the data source while an animation is in progress, as doing so can lead to layout issues. > -> - When the number of child components is equal to the value of **displayCount** plus 1 and at least one of **prevMargin** and **nextMargin** takes effect, set **loop** to **true** to enable loop playback. When loop playback is enabled, a snapshot is generated as the placeholder image. (The snapshot may not be correctly generated for those components that take a long time to display, such as those that use asynchronous image loading. Avoid enabling loop playback under this scenario.) +> - If a child component has its [visibility](ts-universal-attributes-visibility.md#visibility) attribute set to **Visibility.None** and the **Swiper** component has its **displayCount** attribute set to **'auto'**, the child component does not take up space in the viewport, but does not affect the number of navigation points. If a child component has its **visibility** attribute set to **Visibility.None** or **Visibility.Hidden**, it takes up space in the viewport, but is not displayed. > -> - Child components of the **Swiper** component are drawn based on their level if they have the **offset** attribute set. A child component with a higher level overwrites one with a lower level. For example, if the **Swiper** contains three child components and **offset({ x: 100 })** is set for the third child component, the third child component overwrites the first child component during horizontal loop playback. To prevent the first child component from being overwritten, set its **zIndex** attribute to a value greater than that of the third child component. +> - Child components of the **Swiper** component are drawn based on their level if they have the [offset](ts-universal-attributes-location.md#offset) attribute set. A child component with a higher level overwrites one with a lower level. For example, if the **Swiper** contains three child components and **offset({ x: 100 })** is set for the third child component, the third child component overwrites the first child component during horizontal loop playback. To prevent the first child component from being overwritten, set its [zIndex](ts-universal-attributes-z-order.md) attribute to a value greater than that of the third child component. > -> - If rendering control ([if/else](../../../quick-start/arkts-rendering-control-ifelse.md), [ForEach](../../../quick-start/arkts-rendering-control-foreach.md), [LazyForEach](../../../quick-start/arkts-rendering-control-lazyforeach.md), or [Repeat](../../../quick-start/arkts-new-rendering-control-repeat.md)) is employed, do not perform operations on the data source while a component animation is in progress. Such operations can cause layout issues. +> - When focus is moved to a custom child node, navigation points and arrows may be obscured by changes to the z-index due to [focus styles](../../../ui/arkts-common-events-focus-event.md#focus-style). ## APIs Swiper(controller?: SwiperController) +Creates a **Swiper** component. + **Widget capability**: This API can be used in ArkTS widgets since API version 10. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -46,12 +38,16 @@ Swiper(controller?: SwiperController) | Name | Type | Mandatory | Description | | ---------- | ------------------------------------- | ---- | -------------------- | -| controller | [SwiperController](#swipercontroller) | No | Controller bound to the component to control the page turning.| +| controller | [SwiperController](#swipercontroller) | No | Controller bound to the component to control the swiping.| ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. + +> **NOTE** +> +> The default value of the universal attribute [clip](ts-universal-attributes-sharp-clipping.md) is **true** for the **Swiper** component. ### index @@ -91,7 +87,28 @@ If **loop** is set to **false**, the playback stops when the last page is reache | Name| Type | Mandatory| Description | | ------ | ------- | ---- | -------------------------------------- | -| value | boolean | Yes | Whether to enable automatic playback for child component switching.
Default value: **false**| +| value | boolean | Yes | Whether to enable automatic playback for child component switching.
Default value: **false** (automatic playback is disabled for child component switching.)| + +### autoPlay18+ + +autoPlay(autoPlay: boolean, options: AutoPlayOptions) + +Sets whether child components automatically play when the screen is pressed by fingers, a mouse device, or other input devices. + +If [loop](#loop) is set to **false**, autoplay stops when the last page is reached. If a gesture is used to switch pages and the last page is not reached, playback will continue. Autoplay also stops when the **Swiper** component is not visible. + +**Widget capability**: This API can be used in ArkTS widgets since API version 18. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | -------------------------------------- | +| autoPlay | boolean | Yes | Whether to enable automatic playback for child component switching.
Default value: **false** (automatic playback is disabled for child component switching)| +| options | [AutoPlayOptions](#autoplayoptions18) | Yes | Whether child components stop autoplay when the screen is pressed by fingers, a mouse device, or other input devices. If **stopWhenTouched** is set to **true**, autoplay stops when the screen is pressed.
Default value: **{ stopWhenTouched: true }** (stop autoplay)| ### interval @@ -109,13 +126,13 @@ Sets the interval for automatic playback. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------------------------------------------------- | -| value | number | Yes | Interval for automatic playback.
Default value: **3000**
Unit: ms| +| value | number | Yes | Interval for automatic playback.
Default value: **3000**
Unit: ms
Value range: [0, +∞). If a value less than 0 is set, the default value is used.| ### indicator indicator(value: DotIndicator | DigitIndicator | boolean) -Sets the style of the navigation point indicator. +Sets the style of the navigation indicator. **Widget capability**: This API can be used in ArkTS widgets since API version 10. @@ -127,7 +144,26 @@ Sets the style of the navigation point indicator. | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| value | [DotIndicator](#dotindicator10)10+ \| [DigitIndicator](#digitindicator10)10+ \| boolean | Yes | Style of the navigation point indicator.
\- **DotIndicator**: dot style.
\- **DigitIndicator**: digit style.
\- **boolean**: whether to enable the navigation point indicator. The value **true** means to enable the feature, and **false** means the opposite.
Default value: **true**
Default style: **DotIndicator**| +| value | [DotIndicator](#dotindicator10)10+ \| [DigitIndicator](#digitindicator10)10+ \| boolean | Yes | Style of the navigation indicator.
\- **DotIndicator**: dot style.
\- **DigitIndicator**: digit style.
\- **boolean**: whether to enable the navigation indicator. The value **true** means to enable the feature, and **false** means the opposite.
Default value: **true**
Default style: **DotIndicator**| + +### indicator15+ + +indicator(indicator: IndicatorComponentController | DotIndicator | DigitIndicator | boolean) + +Sets the navigation indicator for the component. + +**Widget capability**: This API can be used in ArkTS widgets since API version 15. + +**Atomic service API**: This API can be used in atomic services since API version 15. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| indicator | [IndicatorComponentController](ts-swiper-components-indicator.md#indicatorcomponentcontroller)15+ \| [DotIndicator](#dotindicator10) \| [DigitIndicator](#digitindicator10) \| boolean| Yes | Style of the navigation indicator.
\- **IndicatorComponentController**: separate navigation indicator controller. This controller can be bound to an external navigation indicator, but the external and internal indicators cannot coexist.
\- **DotIndicator**: dot-style indicator.
\- **DigitIndicator**: digit-style indicator.
\- **boolean**: whether to enable the navigation indicator. The value **true** means to enable the feature, and **false** means the opposite.
Default value: **true**
Default style: **DotIndicator**| + ### loop @@ -155,8 +191,7 @@ Sets the duration of the animation for child component switching. **duration** must be used in conjunction with [curve](#curve8). -The default curve for the animation is [interpolatingSpring](../js-apis-curve.md#curvesinterpolatingspring10).When this curve is applied, the duration of the animation is determined solely by the parameters of the curve itself and is no longer governed by the **duration** setting. For curves that are not governed by the **duration** setting, see [Interpolation Calculation](../js-apis-curve.md). -Such curves include [springMotion](../js-apis-curve.md#curvesspringmotion9), [responsiveSpringMotion](../js-apis-curve.md#curvesresponsivespringmotion9), and **interpolatingSpring**. To have the animation duration managed by **duration**, you should select a different curve for the **curve** attribute. +The default curve for the animation is [interpolatingSpring](../js-apis-curve.md#curvesinterpolatingspring10).When this curve is applied, the duration of the animation is determined solely by the parameters of the curve itself and is no longer governed by the **duration** setting. For curves that are not governed by the **duration** setting, see [Interpolation Calculation](../js-apis-curve.md). Among others, [springMotion](../js-apis-curve.md#curvesspringmotion9) and [responsiveSpringMotion](../js-apis-curve.md#curvesresponsivespringmotion9) do not respect the **duration** setting. To have the animation duration managed by **duration**, you should select a different curve for the **curve** attribute. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -166,7 +201,7 @@ Such curves include [springMotion](../js-apis-curve.md#curvesspringmotion9), [re | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ----------------------------------------------------- | -| value | number | Yes | Duration of the autoplay for child component switching.
Default value: **400**
Unit: ms| +| value | number | Yes | Duration of the autoplay for child component switching.
Default value: **400**
Unit: ms
Value range: [0, +∞). If a value less than 0 is set, the default value is used.| ### vertical @@ -204,7 +239,7 @@ If the type is number, the default unit is vp. If the type is string, the pixel | Name| Type | Mandatory| Description | | ------ | -------------------------- | ---- | -------------------------------------- | -| value | number \| string | Yes | Space between child components.
Default value: **0**| +| value | number \| string | Yes | Space between child components.
Default value: **0**
Value range: [0, +∞). If a value less than 0 is set, the default value is used.| ### displayMode @@ -240,7 +275,26 @@ Sets the number of child components to be preloaded (cached), which are needed f | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------- | -| value | number | Yes | Number of child components to be preloaded (cached).
Default value: **1**| +| value | number | Yes | Number of child components to be preloaded (cached).
Default value: **1**
Value range: [0, +∞). If a value less than 0 is set, the default value is used.| + +### cachedCount15+ + +cachedCount(count: number, isShown: boolean) + +Sets the number of child components to be cached. + +**Widget capability**: This API can be used in ArkTS widgets since API version 15. + +**Atomic service API**: This API can be used in atomic services since API version 15. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------- | +| count | number | Yes | Number of child components to be preloaded (cached).
Default value: **1**
Value range: [0, +∞). If a value less than 0 is set, the default value is used.| +| isShown | boolean | Yes | Whether the cached nodes within the range rendered without being added to the render tree.
Default value: **false**, indicating that cached nodes within the range are rendered| ### disableSwipe8+ @@ -282,7 +336,7 @@ Sets the animation curve. The interpolating spring curve is used by default. For indicatorStyle(value?: IndicatorStyle) -Sets the style of the navigation point indicator. +Sets the style of the navigation indicator. This API is supported since API version 8 and is deprecated since API version 10. You are advised to use [indicator](#indicator10) instead. @@ -292,7 +346,7 @@ This API is supported since API version 8 and is deprecated since API version 10 | Name| Type | Mandatory| Description | | ------ | --------------------------------------------------- | ---- | ------------ | -| value | [IndicatorStyle](#indicatorstyledeprecated) | No | Style of the navigation point indicator.| +| value | [IndicatorStyle](#indicatorstyledeprecated) | No | Style of the navigation indicator.| ### displayCount8+ @@ -300,17 +354,9 @@ displayCount(value: number | string | SwiperAutoFill, swipeByGroup?: boolean) Sets the number of elements to display per page. -For the string type, this attribute can only be set to **'auto'**. - -If the value is set to a number less than or equal to 0, the default value **1** is used. - -If the value is of the number type, child components stretch (shrink) on the main axis after the swiper width [deducting the result of itemSpace x (displayCount - 1)] is evenly distributed among them on the main axis. - -If the value is of the SwiperAutoFill type, the system automatically works out the value based on the width and **minSize** settings of the **Swiper** component. If **minSize** is left empty or set to a value less than or equal to 0, the **Swiper** component displays one column. - -With page turning by group, placeholders are used if the number of child elements in the last group is less than the value of **displayCount**. Such placeholders are used to reserve space in the layout and does not display any content. The background style of the **Swiper** is applied to where the placeholders are displayed. +If the value is of the string type, it can only be **'auto'**. In this case, setting [customContentTransition](#customcontenttransition12) or [onContentDidScroll](#oncontentdidscroll12) has no effect. If the value is of the number type, child components stretch (shrink) on the main axis after the swiper width [deducting the result of itemSpace x (**displayCount** - 1)] is evenly distributed among them on the main axis; a value less than or equal to 0 is handled as the default value **1**. If the value is of the SwiperAutoFill type, the system automatically works out the value based on the width and **minSize** settings of the **Swiper** component. If **minSize** is left empty or set to a value less than or equal to 0, the **Swiper** component displays one column. -With page turning by group, the drag distance threshold for page turning is half of the width of the **Swiper** component. (With page turning by child element, the threshold is half of the width of the child element.) +When turning pages by group is used, the drag distance threshold for turning pages is half of the width of the **Swiper** component (50% of the child elements width if turning pages by child element is used). If the number of child elements in the last group is less than the value of **displayCount**, placeholders are used, but they show the **Swiper** background style directly and do not display any content. Since API version 16, when turning pages by group is used and the navigation points are set to circular, the number of circular navigation points matches the number of groups. The number of groups is calculated by dividing the total number of child elements by the number of elements displayed in the viewport. If the division does not result in an integer, the number is rounded up. **Widget capability**: This API can be used in ArkTS widgets since API version 10. @@ -322,8 +368,17 @@ With page turning by group, the drag distance threshold for page turning is half | Name | Type | Mandatory| Description | | -------------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| value | number \| string \| [SwiperAutoFill](#swiperautofill10)10+ | Yes | Number of elements to display per page.
Default value: **1** | -| swipeByGroup11+ | boolean | No | Whether to turn pages by group. The value **true** means to turn pages by group, and **false** means to turn pages by child element. With page turning by group, the number of child elements per group is the value of **displayCount**.
Default value: **false**| +| value | number \| string \| [SwiperAutoFill](#swiperautofill10)10+ | Yes | Number of elements to display per page.
Default value: **1**
Value range: (0, +∞). If this parameter is set to a value less than or equal to 0, the default value is used.| +| swipeByGroup11+ | boolean | No | Whether to turn pages by group. The value **true** means to turn pages by group, and **false** means to turn pages by child element. When turning pages by group is used, the number of child elements per group is the value of **displayCount**.
Default value: **false**| + +> **NOTE** +> +> When the number of child components is less than or equal to the total number of allowed nodes in the content area (totalDisplayCount = displayCount + prevMargin? (1 : 0 ) + nextMargin? (1 : 0 )), the **Swiper** component generally uses the non-looping mode for layout. In this case, the child components specified by **nextMargin** and **prevMargin** take up space in the viewport, but are not displayed. The specifications of the **Swiper** component are calculated based on the value of **totalDisplayCount**. The exceptions are as follows: +> +> - When the number of child components is equal to the total number of allowed nodes in the content area and both **prevMargin** and **nextMargin** take effect, set **loop** to **true** to enable loop playback. +> +> - When the number of child components is equal to the value of **displayCount** plus 1 and at least one of **prevMargin** and **nextMargin** takes effect, set **loop** to **true** to enable loop playback. When loop playback is enabled, a snapshot is generated as the placeholder image. (The snapshot may not be correctly generated for those components that take a long time to display, such as those that use asynchronous image loading. Avoid enabling loop playback under this scenario.) +> ### effectMode8+ @@ -347,7 +402,7 @@ Sets the effect used when the component is at one of the edges. This attribute t displayArrow(value: ArrowStyle | boolean, isHoverShow?: boolean) -Sets the arrow style of the navigation point indicator. +Sets the arrow style of the navigation indicator. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -358,7 +413,7 @@ Sets the arrow style of the navigation point indicator. | Name | Type | Mandatory| Description | | -------------------------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ | | value | [ArrowStyle](#arrowstyle10) \| boolean | Yes | Arrow and background to set. In cases of exceptions, the default values in the **ArrowStyle** object are used. The value **true** means to show the arrow and background in the default styles, and **false** means to hide the arrow and background.
Default value: **false**| -| isHoverShow | boolean | No | Whether to show the arrow only when the mouse pointer hovers over the navigation point indicator.
Default value: **false**
**NOTE**
When **isHoverShow** is set to **false**, the arrow is always displayed and can be clicked to turn pages.
When **isHoverShow** is set to **true**, the arrow is displayed only when the mouse pointer hovers over the navigation point indicator, and it can be clicked to turn pages.| +| isHoverShow | boolean | No | Whether to show the arrow only when the mouse pointer hovers over the navigation indicator.
Default value: **false**
**NOTE**
When **isHoverShow** is set to **false**, the arrow is always displayed and can be clicked to turn pages.
When **isHoverShow** is set to **true**, the arrow is displayed only when the mouse pointer hovers over the navigation indicator, and it can be clicked to turn pages.| > **NOTE** > @@ -382,7 +437,7 @@ When the main axis runs vertically and either the next margin or previous margin | Name| Type | Mandatory| Description | | ------ | ---------------------------- | ---- | ---------------------- | -| value | [Length](ts-types.md#length) | Yes | Next margin.
Default value: **0**| +| value | [Length](ts-types.md#length) | Yes | Next margin. This attribute cannot be set in percentage.
Default value: **0**| | ignoreBlank12+ | boolean | No | Whether to hide (ignore) the next margin on the last page in non-loop scenarios.
**true**: The last page does not show the next margin, and the right edge of the last page is aligned with that of the **Swiper**'s viewable area.
**false**: The last page displays the next margin, and the distance between the right edge of the last page and that of the **Swiper**'s viewable area is equal to the next margin.
Default value: **false**
**NOTE**
On the last page, the values of **prevMargin** and **nextMargin** are added to create a left margin that allows the previous page to be displayed partially.| ### prevMargin10+ @@ -403,7 +458,7 @@ When the main axis runs vertically and either the next margin or previous margin | Name| Type | Mandatory| Description | | ------ | ---------------------------- | ---- | ---------------------- | -| value | [Length](ts-types.md#length) | Yes | Previous margin.
Default value: **0**| +| value | [Length](ts-types.md#length) | Yes | Previous margin. This attribute cannot be set in percentage.
Default value: **0**| | ignoreBlank12+ | boolean | No | Whether to hide (ignore) the previous margin on the first page in non-loop scenarios.
**true**: The first page does not show the previous margin, and the left edge of the first page is align with that of the **Swiper**'s viewable area.
**false**: The first page displays the previous margin, and the distance between the left edge of the first page and that of the **Swiper**'s viewable area is equal to the previous margin.
Default value: **false**
**NOTE**
On the first page, the values of **prevMargin** and **nextMargin** are added to create a right margin that allows the next page to be displayed partially.| ### nestedScroll11+ @@ -430,7 +485,7 @@ Sets the nested scrolling mode of the **Swiper** component and its parent contai indicatorInteractive(value: boolean) -Sets whether the navigation point indicator is interactive. The value **true** means that the navigation point indicator is interactive. +Sets whether the navigation indicator is interactive. The value **true** means that the navigation indicator is interactive. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -440,15 +495,17 @@ Sets whether the navigation point indicator is interactive. The value **true** m | Name| Type | Mandatory| Description | | ------ | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| value | boolean | Yes | Whether the navigation point indicator is interactive.
Default value: **true**| +| value | boolean | Yes | Whether the navigation indicator is interactive.
Default value: **true**| -### pageFlipMode14+ +### pageFlipMode15+ -pageFlipMode(value: PageFlipMode) +pageFlipMode(mode: Optional\) Sets the mode for flipping pages using the mouse wheel. -**Atomic service API**: This API can be used in atomic services since API version 14. +**Widget capability**: This API can be used in ArkTS widgets since API version 15. + +**Atomic service API**: This API can be used in atomic services since API version 15. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -456,7 +513,7 @@ Sets the mode for flipping pages using the mouse wheel. | Name| Type | Mandatory| Description | | ------ | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| value | [PageFlipMode](ts-appendix-enums.md#pageflipmode14) | Yes | Mode for flipping pages using the mouse wheel.
Default value: **PageFlipMode.CONTINUOUS**| +| mode | Optional\<[PageFlipMode](ts-appendix-enums.md#pageflipmode15)> | Yes | Mode for flipping pages using the mouse wheel.
Default value: **PageFlipMode.CONTINUOUS**| ## IndicatorStyle(deprecated) @@ -466,14 +523,14 @@ This API is supported since API version 8 and is deprecated since API version 10 | Name | Type | Mandatory| Description | | ------------- | ------------------------------------------ | ---- | ---------------------------------------------------- | -| left | [Length](ts-types.md#length) | No | Position of the navigation point indicator relative to the left edge of the **Swiper** component.
If neither **left** nor **right** is set, the navigation point indicator is centered along the main axis based on its own size and the size of the **Swiper** component.
If the value specified is **0**, the navigation point indicator is placed at the position 0.
Priority: higher than the **right** property
Value range: [0, Swiper width - Navigation point indicator area width]. Values outside this range are adjusted to the nearest boundary. | -| top | [Length](ts-types.md#length) | No | Position of the navigation point indicator relative to the top edge of the **Swiper** component.
If neither **top** nor **bottom** is set, the navigation point indicator is aligned at the bottom along the cross axis based on its own size and the size of the **Swiper** component, which is the same effect as setting **bottom=0**.
If the value specified is **0**, the navigation point indicator is placed at the position 0.
Priority: higher than the **bottom** property
Value range: [0, Swiper height - Navigation point indicator area height]. Values outside this range are adjusted to the nearest boundary. | -| right | [Length](ts-types.md#length) | No | Position of the navigation point indicator relative to the right edge of the **Swiper** component.
If neither **left** nor **right** is set, the navigation point indicator is centered along the main axis based on its own size and the size of the **Swiper** component.
If the value specified is **0**, the navigation point indicator is placed at the position 0.
Priority: lower than the **left** property
Value range: [0, Swiper width - Navigation point indicator area width]. Values outside this range are adjusted to the nearest boundary. | -| bottom | [Length](ts-types.md#length) | No | Position of the navigation point indicator relative to the bottom edge of the **Swiper** component.
If neither **top** nor **bottom** is set, the navigation point indicator is aligned at the bottom along the cross axis based on its own size and the size of the **Swiper** component, which is the same effect as setting **bottom=0**.
If the value specified is **0**, the navigation point indicator is placed at the position 0.
Priority: lower than the **top** property
Value range: [0, Swiper height - Navigation point indicator area height]. Values outside this range are adjusted to the nearest boundary. | -| size | [Length](ts-types.md#length) | No | Diameter of the navigation point indicator. It cannot be set in percentage.
Default value: **6vp**| -| mask | boolean | No | Whether to enable the mask for the navigation point indicator. | -| color | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the navigation point indicator. | -| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the selected navigation point indicator. | +| left | [Length](ts-types.md#length) | No | Position of the navigation indicator relative to the left edge of the **Swiper** component.
If neither **left** nor **right** is set, the navigation indicator is centered along the main axis based on its own size and the size of the **Swiper** component.
If the value specified is **0**, the navigation indicator is placed at the position 0.
Priority: higher than the **right** property
Value range: [0, Swiper width - Navigation indicator area width]. Values outside this range are adjusted to the nearest boundary. | +| top | [Length](ts-types.md#length) | No | Position of the navigation indicator relative to the top edge of the **Swiper** component.
If neither **top** nor **bottom** is set, the navigation indicator is aligned at the bottom along the cross axis based on its own size and the size of the **Swiper** component, which is the same effect as setting **bottom=0**.
If the value specified is **0**, the navigation indicator is placed at the position 0.
Priority: higher than the **bottom** property
Value range: [0, Swiper height - Navigation indicator area height]. Values outside this range are adjusted to the nearest boundary. | +| right | [Length](ts-types.md#length) | No | Position of the navigation indicator relative to the right edge of the **Swiper** component.
If neither **left** nor **right** is set, the navigation indicator is centered along the main axis based on its own size and the size of the **Swiper** component.
If the value specified is **0**, the navigation indicator is placed at the position 0.
Priority: lower than the **left** property
Value range: [0, Swiper width - Navigation indicator area width]. Values outside this range are adjusted to the nearest boundary. | +| bottom | [Length](ts-types.md#length) | No | Position of the navigation indicator relative to the bottom edge of the **Swiper** component.
If neither **top** nor **bottom** is set, the navigation indicator is aligned at the bottom along the cross axis based on its own size and the size of the **Swiper** component, which is the same effect as setting **bottom=0**.
If the value specified is **0**, the navigation indicator is placed at the position 0.
Priority: lower than the **top** property
Value range: [0, Swiper height - Navigation indicator area height]. Values outside this range are adjusted to the nearest boundary. | +| size | [Length](ts-types.md#length) | No | Diameter of the navigation indicator. It cannot be set in percentage.
Default value: **6vp**| +| mask | boolean | No | Whether to enable the mask for the navigation indicator. | +| color | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the navigation indicator. | +| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the selected navigation indicator. | ## SwiperDisplayMode @@ -572,6 +629,25 @@ Goes to a specified page. | index| number | Yes | Index of the target page in the **Swiper** component.
**NOTE**
If the value specified is less than 0 or greater than the maximum page index, the value **0** is used.| | useAnimation| boolean | No | Whether to use an animation for when the target page is reached. The value **true** means to use an animation, and **false** means the opposite.
Default value: **false**| +### changeIndex15+ + +changeIndex(index: number, animationMode?: SwiperAnimationMode | boolean) + +Moves to a specific page. + +**Widget capability**: This API can be used in ArkTS widgets since API version 15. + +**Atomic service API**: This API can be used in atomic services since API version 15. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------- | ---- | -------- | +| index| number | Yes | Index of the target page in the **Swiper** component.
**NOTE**
If the value specified is less than 0 or greater than the maximum page index, the value **0** is used.| +| animationMode| [SwiperAnimationMode](#swiperanimationmode15) \| boolean | No | Animation mode for moving to the specified page.
Default value: **SwiperAnimationMode.NO_ANIMATION**
**NOTE**
The value **true** is equivalent to **SwiperAnimationMode.DEFAULT_ANIMATION**, which means to use the default animation. The value **false** is equivalent to **SwiperAnimationMode.NO_ANIMATION**, which means to use no animation.| + ### finishAnimation finishAnimation(callback?: VoidCallback) @@ -590,9 +666,62 @@ Stops an animation. | -------- | ---------- | ---- | -------- | | callback | [VoidCallback](./ts-types.md#voidcallback12) | No | Callback invoked when the animation stops.| +### preloadItems18+ + +preloadItems(indices: Optional\>): Promise\ + +Preloads child nodes. After this API is called, all specified child nodes will be loaded at once. Therefore, for performance considerations, it is recommended that you load child nodes in batches. + +If the **SwiperController** object is not bound to any **Swiper** component, any attempt to call APIs on it will result in a JavaScript exception, together with the error code 100004. Therefore, you are advised to use **try-catch** to handle potential exceptions when calling APIs on **SwiperController**. + +When combining **SwiperController** with [LazyForEach](../../../quick-start/arkts-rendering-control-lazyforeach.md) and custom components, be aware that **LazyForEach** only retains custom components within the cache range. Components outside this range are removed. Therefore, make sure the nodes to preload are within the cache range of **LazyForEach** to avoid issues. + +**Widget capability**: This API can be used in ArkTS widgets since API version 18. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ---------------------------------------- | +| indices | Optional\> | Yes| Array of indexes of the child nodes to preload.
The default value is an empty array.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ------------------------ | +| Promise\ | Promise used to return the value.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../../errorcode-universal.md) and [Scrollable Component Error Codes](../../apis-arkui/errorcode-scroll.md). + +| ID | Error Message | +| -------- | -------------------------------------------- | +| 401 | Parameter invalid. Possible causes: 1. The parameter type is not Array\; 2. The parameter is an empty array; 3. The parameter contains an invalid index. | +| 100004 | Controller not bound to component. | + +## SwiperAnimationMode15+ + +Enumerates the animation mode for moving to a specific page in the **Swiper** component. + +**Widget capability**: This API can be used in ArkTS widgets since API version 15. + +**Atomic service API**: This API can be used in atomic services since API version 15. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Value | Description | +| ------------- | ---- | ------------------------------------------------------------ | +| NO_ANIMATION | 0 | Move to the specified page without any animation. | +| DEFAULT_ANIMATION | 1 | Move to the specified page with the default animation. | +| FAST_ANIMATION | 2 | Move to a page near the specified page without animation, and then navigate to the specified page with the default animation.| + ## Indicator10+ -Sets the distance between the navigation point indicator and the **Swiper** component. Note that due to its default interaction area height of 32 vp, the navigation point indicator cannot be placed flush against the bottom edge. +Sets the distance between the navigation indicator and the **Swiper** component. Note that due to its default interaction area height of 32 vp, the navigation indicator cannot be placed flush against the bottom edge. **Widget capability**: This API can be used in ArkTS widgets since API version 10. @@ -604,7 +733,7 @@ Sets the distance between the navigation point indicator and the **Swiper** comp left(value: Length): T -Sets the position of the navigation point indicator relative to the left edge of the **Swiper** component. +Sets the position of the navigation indicator relative to the left edge of the **Swiper** component. **Widget capability**: This API can be used in ArkTS widgets since API version 10. @@ -616,13 +745,13 @@ Sets the position of the navigation point indicator relative to the left edge of | Name| Type | Mandatory| Description | | ------ | ---------------------------- | ---- | ------------------------------------------------------------ | -| value | [Length](ts-types.md#length) | Yes | Position of the navigation point indicator relative to the left edge of the **Swiper** component.
If neither **left** nor **right** is set, the navigation point indicator is centered along the main axis based on its own size and the size of the **Swiper** component.
If the value specified is **0**, the navigation point indicator is placed at the position 0.
Priority: higher than the **right** property
Value range: [0, Swiper width - Navigation point indicator area width]. Values outside this range are adjusted to the nearest boundary.| +| value | [Length](ts-types.md#length) | Yes | Position of the navigation indicator relative to the left edge of the **Swiper** component.
If neither **left** nor **right** is set, the navigation indicator is centered along the main axis based on its own size and the size of the **Swiper** component.
If the value specified is **0**, the navigation indicator is placed at the position 0.
Priority: higher than the **right** property
Value range: [0, Swiper width - Navigation indicator area width]. Values outside this range are adjusted to the nearest boundary.| ### top top(value: Length): T -Sets the position of the navigation point indicator relative to the top edge of the **Swiper** component. +Sets the position of the navigation indicator relative to the top edge of the **Swiper** component. **Widget capability**: This API can be used in ArkTS widgets since API version 10. @@ -634,13 +763,13 @@ Sets the position of the navigation point indicator relative to the top edge of | Name| Type | Mandatory| Description | | ------ | ---------------------------- | ---- | ------------------------------------------------------------ | -| value | [Length](ts-types.md#length) | Yes | Position of the navigation point indicator relative to the top edge of the **Swiper** component.
If neither **top** nor **bottom** is set, the navigation point indicator is aligned at the bottom along the cross axis based on its own size and the size of the **Swiper** component, which is the same effect as setting **bottom=0**.
If the value specified is **0**, the navigation point indicator is placed at the position 0.
Priority: higher than the **bottom** property
Value range: [0, Swiper height - Navigation point indicator area height]. Values outside this range are adjusted to the nearest boundary.| +| value | [Length](ts-types.md#length) | Yes | Position of the navigation indicator relative to the top edge of the **Swiper** component.
If neither **top** nor **bottom** is set, the navigation indicator is aligned at the bottom along the cross axis based on its own size and the size of the **Swiper** component, which is the same effect as setting **bottom=0**.
If the value specified is **0**, the navigation indicator is placed at the position 0.
Priority: higher than the **bottom** property
Value range: [0, Swiper height - Navigation indicator area height]. Values outside this range are adjusted to the nearest boundary.| ### right right(value: Length): T -Sets the position of the navigation point indicator relative to the right edge of the **Swiper** component. +Sets the position of the navigation indicator relative to the right edge of the **Swiper** component. **Widget capability**: This API can be used in ArkTS widgets since API version 10. @@ -652,13 +781,13 @@ Sets the position of the navigation point indicator relative to the right edge o | Name| Type | Mandatory| Description | | ------ | ---------------------------- | ---- | ------------------------------------------------------------ | -| value | [Length](ts-types.md#length) | Yes | Sets the position of the navigation point indicator relative to the right edge of the **Swiper** component.
If neither **left** nor **right** is set, the navigation point indicator is centered along the main axis based on its own size and the size of the **Swiper** component.
If the value specified is **0**, the navigation point indicator is placed at the position 0.
Priority: lower than the **left** property
Value range: [0, Swiper width - Navigation point indicator area width]. Values outside this range are adjusted to the nearest boundary.| +| value | [Length](ts-types.md#length) | Yes | Sets the position of the navigation indicator relative to the right edge of the **Swiper** component.
If neither **left** nor **right** is set, the navigation indicator is centered along the main axis based on its own size and the size of the **Swiper** component.
If the value specified is **0**, the navigation indicator is placed at the position 0.
Priority: lower than the **left** property
Value range: [0, Swiper width - Navigation indicator area width]. Values outside this range are adjusted to the nearest boundary.| ### bottom bottom(value: Length): T -Sets the position of the navigation point indicator relative to the bottom edge of the **Swiper** component. +Sets the position of the navigation indicator relative to the bottom edge of the **Swiper** component. **Widget capability**: This API can be used in ArkTS widgets since API version 10. @@ -670,13 +799,34 @@ Sets the position of the navigation point indicator relative to the bottom edge | Name| Type | Mandatory| Description | | ------ | ---------------------------- | ---- | ------------------------------------------------------------ | -| value | [Length](ts-types.md#length) | Yes | Position of the navigation point indicator relative to the bottom edge of the **Swiper** component.
If neither **top** nor **bottom** is set, the navigation point indicator is aligned at the bottom along the cross axis based on its own size and the size of the **Swiper** component, which is the same effect as setting **bottom=0**.
If the value specified is **0**, the navigation point indicator is placed at the position 0.
Priority: lower than the **top** property
Value range: [0, Swiper height - Navigation point indicator area height]. Values outside this range are adjusted to the nearest boundary.| +| value | [Length](ts-types.md#length) | Yes | Position of the navigation indicator relative to the bottom edge of the **Swiper** component.
If neither **top** nor **bottom** is set, the navigation indicator is aligned at the bottom along the cross axis based on its own size and the size of the **Swiper** component, which is the same effect as setting **bottom=0**.
If the value specified is **0**, the navigation indicator is placed at the position 0.
Priority: lower than the **top** property
Value range: [0, Swiper height - Navigation indicator area height]. Values outside this range are adjusted to the nearest boundary.| + + +### bottom18+ + +bottom(bottom: LengthMetrics | Length, ignoreSize: boolean): T + +Sets the position of the navigation indicator relative to the bottom edge of the **Swiper** component. You can also choose to ignore the size of the navigation indicator using the **ignoreSize** property. + +**Widget capability**: This API can be used in ArkTS widgets since API version 18. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + + +| Name| Type | Mandatory| Description | +| ------ | ---------------------------- | ---- | ------------------------------------------------------------ | +| bottom | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) \| [Length](ts-types.md#length)| Yes | Position of the navigation indicator relative to the bottom edge of the **Swiper** component.
If neither **top** nor **bottom** is set, the navigation indicator is aligned at the bottom along the cross axis based on its own size and the size of the **Swiper** component, which is the same effect as setting **bottom=0**.
If the value specified is **0**, the navigation indicator is placed at the position 0.
Priority: lower than the **top** property
Value range: [0, Swiper height - Navigation indicator area height]. Values outside this range are adjusted to the nearest boundary.| +| ignoreSize | boolean | Yes | Whether to ignore the size of the navigation indicator.
Ddefault value: **false**
The value **true** allows the navigation indicator to be positioned closer to the bottom edge of the **Swiper** component.
**NOTE**
The **ignoreSize** property for the number-style navigation indicator is ineffective in the following scenarios:
• [vertical](#vertical) is set to **false** and the value of **bottom** is greater than 0.
• When [vertical](#vertical) is set to **true**:
1. The value of **bottom** is greater than 0.
2. The value of **bottom** is **undefined**.
3. **isSidebarMiddle** is set to **false**.| ### start12+ start(value: LengthMetrics): T -Sets the distance between the navigation point indicator and the right edge (in right-to-left scripts) or the left edge (in left-to-right scripts) of the **Swiper** component. +Sets the distance between the navigation indicator and the right edge (in right-to-left scripts) or the left edge (in left-to-right scripts) of the **Swiper** component. **Widget capability**: This API can be used in ArkTS widgets since API version 12. @@ -688,13 +838,13 @@ Sets the distance between the navigation point indicator and the right edge (in | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| value | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes | Distance between the navigation point indicator and the right edge (in right-to-left scripts) or the left edge (in left-to-right scripts) of the **Swiper** component.
Default value: **0**
Unit: vp| +| value | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes | Distance between the navigation indicator and the right edge (in right-to-left scripts) or the left edge (in left-to-right scripts) of the **Swiper** component.
Default value: **0**
Unit: vp| ### end12+ end(value: LengthMetrics): T -Sets the distance between the navigation point indicator and the left edge (in right-to-left scripts) or the right edge (in left-to-right scripts) of the **Swiper** component. +Sets the distance between the navigation indicator and the left edge (in right-to-left scripts) or the right edge (in left-to-right scripts) of the **Swiper** component. **Widget capability**: This API can be used in ArkTS widgets since API version 12. @@ -706,7 +856,7 @@ Sets the distance between the navigation point indicator and the left edge (in r | Name| Type | Mandatory | Description | | ------ | ---------------------------- | ---- | ---------------------------------------- | -| value | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes | Distance between the navigation point indicator and the left edge (in right-to-left scripts) or the right edge (in left-to-right scripts) of the **Swiper** component.
Default value: **0**
Unit: vp
**Widget capability**: This API can be used in ArkTS widgets since API version 12.
**Atomic service API**: This API can be used in atomic services since API version 12.| +| value | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes | Distance between the navigation indicator and the left edge (in right-to-left scripts) or the right edge (in left-to-right scripts) of the **Swiper** component.
Default value: **0**
Unit: vp | ### dot @@ -734,7 +884,7 @@ Returns **DigitIndicator** object. ## DotIndicator10+ -Defines a dot-style navigation point indicator. Inherits [Indicator](#indicator10). +Constructs a dot indicator style. It extends from [Indicator] (#indicator10). **Atomic service API**: This API can be used in atomic services since API version 11. @@ -744,7 +894,7 @@ Defines a dot-style navigation point indicator. Inherits [Indicator](#indicator1 itemWidth(value: Length): DotIndicator -Sets the width of the dot-style navigation point indicator. This parameter cannot be set in percentage. +Sets the width of the dot-style navigation indicator. This parameter cannot be set in percentage. **Widget capability**: This API can be used in ArkTS widgets since API version 10. @@ -756,19 +906,19 @@ Sets the width of the dot-style navigation point indicator. This parameter canno | Name| Type | Mandatory| Description | | ------ | ---------------------------- | ---- | ------------------------------------------------------------ | -| value | [Length](ts-types.md#length) | Yes | Width of the dot-style navigation point indicator. This parameter cannot be set in percentage.
Default value: **6**
Unit: vp| +| value | [Length](ts-types.md#length) | Yes | Width of the dot-style navigation indicator. This parameter cannot be set in percentage.
Default value: **6**
Unit: vp| **Return value** | Type | Description | | ------------------------------- | ------------ | -| [DotIndicator](#dotindicator10) | Dot-style navigation point indicator.| +| [DotIndicator](#dotindicator10) | Dot-style navigation indicator.| ### itemHeight itemHeight(value: Length): DotIndicator -Sets the height of the dot-style navigation point indicator. This parameter cannot be set in percentage. +Sets the height of the dot-style navigation indicator. This parameter cannot be set in percentage. **Widget capability**: This API can be used in ArkTS widgets since API version 10. @@ -780,19 +930,19 @@ Sets the height of the dot-style navigation point indicator. This parameter cann | Name| Type | Mandatory| Description | | ------ | ---------------------------- | ---- | ------------------------------------------------------------ | -| value | [Length](ts-types.md#length) | Yes | Height of the dot-style navigation point indicator. This parameter cannot be set in percentage.
Default value: **6**
Unit: vp| +| value | [Length](ts-types.md#length) | Yes | Height of the dot-style navigation indicator. This parameter cannot be set in percentage.
Default value: **6**
Unit: vp| **Return value** | Type | Description | | ------------------------------- | ------------ | -| [DotIndicator](#dotindicator10) | Dot-style navigation point indicator.| +| [DotIndicator](#dotindicator10) | Dot-style navigation indicator.| ### selectedItemWidth selectedItemWidth(value: Length): DotIndicator -Sets the width of the selected dot in the dot-style navigation point indicator. This parameter cannot be set in percentage. +Sets the width of the selected dot in the dot-style navigation indicator. This parameter cannot be set in percentage. **Widget capability**: This API can be used in ArkTS widgets since API version 10. @@ -804,19 +954,19 @@ Sets the width of the selected dot in the dot-style navigation point indicator. | Name| Type | Mandatory| Description | | ------ | ---------------------------- | ---- | ------------------------------------------------------------ | -| value | [Length](ts-types.md#length) | Yes | Width of the selected dot in the dot-style navigation point indicator. This parameter cannot be set in percentage.
Default value: **12**
Unit: vp| +| value | [Length](ts-types.md#length) | Yes | Width of the selected dot in the dot-style navigation indicator. This parameter cannot be set in percentage.
Default value: **12**
Unit: vp| **Return value** | Type | Description | | ------------------------------- | ------------ | -| [DotIndicator](#dotindicator10) | Dot-style navigation point indicator.| +| [DotIndicator](#dotindicator10) | Dot-style navigation indicator.| ### selectedItemHeight selectedItemHeight(value: Length): DotIndicator -Sets the height of the selected dot in the dot-style navigation point indicator. This parameter cannot be set in percentage. +Sets the height of the selected dot in the dot-style navigation indicator. This parameter cannot be set in percentage. **Widget capability**: This API can be used in ArkTS widgets since API version 10. @@ -828,19 +978,19 @@ Sets the height of the selected dot in the dot-style navigation point indicator. | Name| Type | Mandatory| Description | | ------ | ---------------------------- | ---- | ------------------------------------------------------------ | -| value | [Length](ts-types.md#length) | Yes | Height of the selected dot in the dot-style navigation point indicator. This parameter cannot be set in percentage.
Default value: **6**
Unit: vp| +| value | [Length](ts-types.md#length) | Yes | Height of the selected dot in the dot-style navigation indicator. This parameter cannot be set in percentage.
Default value: **6**
Unit: vp| **Return value** | Type | Description | | ------------------------------- | ------------ | -| [DotIndicator](#dotindicator10) | Dot-style navigation point indicator.| +| [DotIndicator](#dotindicator10) | Dot-style navigation indicator.| ### mask mask(value: boolean): DotIndicator -Sets whether to enable the mask for the dot-style navigation point indicator. +Sets whether to enable the mask for the dot-style navigation indicator. **Widget capability**: This API can be used in ArkTS widgets since API version 10. @@ -852,19 +1002,19 @@ Sets whether to enable the mask for the dot-style navigation point indicator. | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------------------------------------ | -| value | boolean | Yes | Whether to enable the mask for the dot-style navigation point indicator.
Default value: **false**| +| value | boolean | Yes | Whether to enable the mask for the dot-style navigation indicator.
Default value: **false**| **Return value** | Type | Description | | ------------------------------- | ------------ | -| [DotIndicator](#dotindicator10) | Dot-style navigation point indicator.| +| [DotIndicator](#dotindicator10) | Dot-style navigation indicator.| ### color color(value: ResourceColor): DotIndicator -Sets the color of the dot-style navigation point indicator. +Sets the color of the dot-style navigation indicator. **Widget capability**: This API can be used in ArkTS widgets since API version 10. @@ -876,19 +1026,19 @@ Sets the color of the dot-style navigation point indicator. | Name| Type | Mandatory| Description | | ------ | ------------------------------------------ | ---- | ------------------------------------------------------------ | -| value | [ResourceColor](ts-types.md#resourcecolor) | Yes | Color of the dot-style navigation point indicator.
Default value: **'\#182431'** (10% opacity)| +| value | [ResourceColor](ts-types.md#resourcecolor) | Yes | Color of the dot-style navigation indicator.
Default value: **'\#182431'** (10% opacity)| **Return value** | Type | Description | | ------------------------------- | ------------ | -| [DotIndicator](#dotindicator10) | Dot-style navigation point indicator.| +| [DotIndicator](#dotindicator10) | Dot-style navigation indicator.| ### selectedColor selectedColor(value: ResourceColor): DotIndicator -Sets the color of the selected dot in the dot-style navigation point indicator. +Sets the color of the selected dot in the dot-style navigation indicator. **Widget capability**: This API can be used in ArkTS widgets since API version 10. @@ -900,19 +1050,21 @@ Sets the color of the selected dot in the dot-style navigation point indicator. | Name| Type | Mandatory| Description | | ------ | ------------------------------------------ | ---- | ------------------------------------------------------------ | -| value | [ResourceColor](ts-types.md#resourcecolor) | Yes | Color of the selected dot in the dot-style navigation point indicator.
Default value: **'\#007DFF'**| +| value | [ResourceColor](ts-types.md#resourcecolor) | Yes | Color of the selected dot in the dot-style navigation indicator.
Default value: **'\#007DFF'**| **Return value** | Type | Description | | ------------------------------- | ------------ | -| [DotIndicator](#dotindicator10) | Dot-style navigation point indicator.| +| [DotIndicator](#dotindicator10) | Dot-style navigation indicator.| ### maxDisplayCount12+ maxDisplayCount(maxDisplayCount: number): DotIndicator -Sets the maximum number of navigation dots in the dot-style navigation point indicator. +Sets the maximum number of navigation dots in the dot-style navigation indicator. + +In a separate navigation indicator controller, this attribute has effect only when the controller is bound to a **Swiper** component. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -922,13 +1074,37 @@ Sets the maximum number of navigation dots in the dot-style navigation point ind | Name | Type | Mandatory| Description | | --------------- | ------ | ---- | ------------------------------------------------------------ | -| maxDisplayCount | number | Yes | Maximum number of navigation dots in the dot-style navigation point indicator. If the actual number of navigation dots exceeds this limit, the overflow effect is activated, as shown in Example 5.
This parameter has no default value. If an invalid value is set, no overflow effect is applied.
Value range: 6–9
**NOTE**
In scenarios involving overflow display:
1. Interactive features, such as gestures and mouse operations, are not supported.
2. The position of the selected navigation dot corresponding to the middle page is not strictly fixed; it depends on the sequence of previous page-turning operations.| +| maxDisplayCount | number | Yes | Maximum number of navigation dots in the dot-style navigation indicator. If the actual number of navigation dots exceeds this limit, the overflow effect is activated, as shown in Example 5.
This parameter has no default value. If an invalid value is set, no overflow effect is applied.
Value range: 6–9
**NOTE**
In scenarios involving overflow display:
1. Interactive features, such as gestures and mouse operations, are not supported.
2. The position of the selected navigation dot corresponding to the middle page is not strictly fixed; it depends on the sequence of previous page-turning operations.
3. Currently, only scenarios with **displayCount** set to **1** are supported.| **Return value** | Type | Description | | ------------------------------- | ------------ | -| [DotIndicator](#dotindicator10) | Dot-style navigation point indicator.| +| [DotIndicator](#dotindicator10) | Dot-style navigation indicator.| + +### space18+ + +space(space: LengthMetrics): DotIndicator + +Sets the spacing between the dots in a dot-style navigation indicator for the **Swiper** component. Note that percentage values are not supported. + +**Widget capability**: This API can be used in ArkTS widgets since API version 18. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ---------------------------- | ---- | ------------------------------------------------------------ | +| space | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes | Spacing between the dots in the dot-style navigation indicator. Percentage values are not supported.
Default value: **8**
Unit: vp| + +**Return value** + +| Type | Description | +| ------------------------------- | ------------ | +| [DotIndicator](#dotindicator10) | Dot-style navigation indicator.| ### constructor @@ -944,11 +1120,11 @@ A constructor used to create a **DotIndicator** object. >**NOTE** > ->When pressed, the navigation point indicator is zoomed in to 1.33 times. To account for this, there is a certain distance between the navigation point indicator's visible boundary and its actual boundary in the non-pressed state. The distance increases with the value of **itemWidth**, **itemHeight**, **selectedItemWidth**, and **selectedItemHeight**. +>When pressed, the navigation indicator is zoomed in to 1.33 times. To account for this, there is a certain distance between the navigation indicator's visible boundary and its actual boundary in the non-pressed state. The distance increases with the value of **itemWidth**, **itemHeight**, **selectedItemWidth**, and **selectedItemHeight**. ## DigitIndicator10+ -Defines a digit-style navigation point indicator. Inherits [Indicator](#indicator10). +A constructor used to create a **DigitIndicator** object. It inherits from [Indicator](#indicator10). **Widget capability**: This API can be used in ArkTS widgets since API version 10. @@ -958,14 +1134,14 @@ Defines a digit-style navigation point indicator. Inherits [Indicator](#indicato >**NOTE** > ->When pages are turned by group, the child nodes displayed in the digit-style navigation point indicator do not count placeholder nodes.
->The maximum value of [maxFontScale](ts-basic-components-text.md#maxfontscale12) for the digit-style navigation point indicator is 2. +>When pages are turned by group, the child nodes displayed in the digit-style navigation indicator do not count placeholder nodes.
+>The maximum value of [maxFontScale](ts-basic-components-text.md#maxfontscale12) for the digit-style navigation indicator is 2. ### fontColor fontColor(value: ResourceColor): DigitIndicator -Sets the font color of the digit-style navigation point indicator. +Sets the font color of the digit-style navigation indicator. **Widget capability**: This API can be used in ArkTS widgets since API version 10. @@ -977,19 +1153,19 @@ Sets the font color of the digit-style navigation point indicator. | Name| Type | Mandatory| Description | | ------ | ------------------------------------------ | ---- | ------------------------------------------------------------ | -| value | [ResourceColor](ts-types.md#resourcecolor) | Yes | Font color of the digit-style navigation point indicator.
Default value: **'\#ff182431'**| +| value | [ResourceColor](ts-types.md#resourcecolor) | Yes | Font color of the digit-style navigation indicator.
Default value: **'\#ff182431'**| **Return value** | Type | Description | | ----------------------------------- | ------------ | -| [DigitIndicator](#digitindicator10) | Digit-style navigation point indicator.| +| [DigitIndicator](#digitindicator10) | Digit-style navigation indicator.| ### selectedFontColor selectedFontColor(value: ResourceColor): DigitIndicator -Sets the font color of the selected digit in the digit-style navigation point indicator. +Sets the font color of the selected digit in the digit-style navigation indicator. **Widget capability**: This API can be used in ArkTS widgets since API version 10. @@ -1001,19 +1177,19 @@ Sets the font color of the selected digit in the digit-style navigation point in | Name| Type | Mandatory| Description | | ------ | ------------------------------------------ | ---- | ------------------------------------------------------------ | -| value | [ResourceColor](ts-types.md#resourcecolor) | Yes | Font color of the selected digit in the digit-style navigation point indicator.
Default value: **'\#ff182431'**| +| value | [ResourceColor](ts-types.md#resourcecolor) | Yes | Font color of the selected digit in the digit-style navigation indicator.
Default value: **'\#ff182431'**| **Return value** | Type | Description | | ----------------------------------- | ------------ | -| [DigitIndicator](#digitindicator10) | Digit-style navigation point indicator.| +| [DigitIndicator](#digitindicator10) | Digit-style navigation indicator.| ### digitFont digitFont(value: Font): DigitIndicator -Sets the font style of the digit-style navigation point indicator. +Sets the font style of the digit-style navigation indicator. **Widget capability**: This API can be used in ArkTS widgets since API version 10. @@ -1025,19 +1201,19 @@ Sets the font style of the digit-style navigation point indicator. | Name| Type | Mandatory| Description | | ------ | ------------------------ | ---- | ------------------------------------------------------------ | -| value | [Font](ts-types.md#font) | Yes | Font style of the digit-style navigation point indicator.
Only the **size** and **weight** parameters in **Font** are adjustable. Setting **family** and **style** has no effect.
Default value:
{ size: 14, weight: FontWeight.Normal } | +| value | [Font](ts-types.md#font) | Yes | Font style of the digit-style navigation indicator.
Only the **size** and **weight** parameters in **Font** are adjustable. Setting **family** and **style** has no effect.
Default value:
{ size: 14, weight: FontWeight.Normal } | **Return value** | Type | Description | | ----------------------------------- | ------------ | -| [DigitIndicator](#digitindicator10) | Digit-style navigation point indicator.| +| [DigitIndicator](#digitindicator10) | Digit-style navigation indicator.| ### selectedDigitFont selectedDigitFont(value: Font): DigitIndicator -Sets the font style of the selected digit in the digit-style navigation point indicator. +Sets the font style of the selected digit in the digit-style navigation indicator. **Widget capability**: This API can be used in ArkTS widgets since API version 10. @@ -1049,17 +1225,17 @@ Sets the font style of the selected digit in the digit-style navigation point in | Name| Type | Mandatory| Description | | ------ | ------------------------ | ---- | ------------------------------------------------------------ | -| value | [Font](ts-types.md#font) | Yes | Font style of the selected digit in the digit-style navigation point indicator.
Default value:
{ size: 14, weight: FontWeight.Normal } | +| value | [Font](ts-types.md#font) | Yes | Font style of the selected digit in the digit-style navigation indicator.
Default value:
{ size: 14, weight: FontWeight.Normal } | >**NOTE** > -> When pages are turned by group, the child nodes displayed in the digit-style navigation point indicator do not count placeholder nodes. +> When pages are turned by group, the child nodes displayed in the digit-style navigation indicator do not count placeholder nodes. **Return value** | Type | Description | | ----------------------------------- | ------------ | -| [DigitIndicator](#digitindicator10) | Digit-style navigation point indicator.| +| [DigitIndicator](#digitindicator10) | Digit-style navigation indicator.| ### constructor @@ -1083,10 +1259,10 @@ Describes the left and right arrow attributes. | Name | Type | Mandatory | Description | | ---------------- | ---------------------------------------- | ---- | ---------------------------------------- | | showBackground | boolean | No | Whether to show the background for the arrow.
Default value: **false** | -| isSidebarMiddle | boolean | No | Whether the arrow is shown on either side of the navigation point indicator.
Default value: **false**
(the arrow is shown on either side of the navigation point indicator)| -| backgroundSize | [Length](ts-types.md#length) | No | Size of the background.
On both sides of the navigation point indicator:
Default value: **24vp**
On both sides of the component:
Default value: **32vp**
This parameter cannot be set in percentage.| -| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the background.
On both sides of the navigation point indicator:
Default value: **'\#00000000'**
On both sides of the component:
Default value: **'\#19182431'**| -| arrowSize | [Length](ts-types.md#length) | No | Size of the arrow.
On both sides of the navigation point indicator:
Default value: **18vp**
On both sides of the component:
Default value: **24vp**
**NOTE**
If **showBackground** is set to **true**, the value of **arrowSize** is 3/4 of the value of **backgroundSize**.
This parameter cannot be set in percentage.| +| isSidebarMiddle | boolean | No | Whether the arrow is shown on either side of the navigation indicator.
Default value: **false**
(the arrow is shown on either side of the navigation indicator)| +| backgroundSize | [Length](ts-types.md#length) | No | Size of the background.
On both sides of the navigation indicator:
Default value: **24vp**
On both sides of the component:
Default value: **32vp**
This parameter cannot be set in percentage.| +| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the background.
On both sides of the navigation indicator:
Default value: **'\#00000000'**
On both sides of the component:
Default value: **'\#19182431'**| +| arrowSize | [Length](ts-types.md#length) | No | Size of the arrow.
On both sides of the navigation indicator:
Default value: **18vp**
On both sides of the component:
Default value: **24vp**
**NOTE**
If **showBackground** is set to **true**, the value of **arrowSize** is 3/4 of the value of **backgroundSize**.
This parameter cannot be set in percentage.| | arrowColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the arrow.
Default value: **'\#182431'** | ## SwiperAutoFill10+ @@ -1103,9 +1279,23 @@ Describes the auto-fill attribute. | ------- | -------------------- | ------ | ------------------------------------ | | minSize | [VP](ts-types.md#vp10) | Yes | Minimum width of the element.
Default value: **0**| +## AutoPlayOptions18+ + +Defines the properties for controlling the autoplay behavior. + +**Widget capability**: This API can be used in ArkTS widgets since API version 18. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ---------------- | ---------------------------------------- | ---- | ---------------------------------------- | +| stopWhenTouched | boolean | Yes | Whether the autoplay stops immediately when the component is touched.
Default value: **true**| + ## Events -In addition to the [universal events](ts-universal-events-click.md), the following events are supported. +In addition to the [universal events](ts-component-general-events.md), the following events are supported. ### onChange @@ -1143,7 +1333,7 @@ Triggered when the switching animation starts. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------- | -| event | [OnSwiperAnimationStartCallback](#onswiperanimationstartcallback14) | Yes | Callback triggered when the switching animation starts.| +| event | [OnSwiperAnimationStartCallback](#onswiperanimationstartcallback18) | Yes | Callback triggered when the switching animation starts.| >**NOTE** > @@ -1167,7 +1357,7 @@ This event is triggered when the switching animation of the **Swiper** component | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------- | -| event | [OnSwiperAnimationEndCallback](#onswiperanimationendcallback14) | Yes | Callback triggered when the switching animation ends.| +| event | [OnSwiperAnimationEndCallback](#onswiperanimationendcallback18) | Yes | Callback triggered when the switching animation ends.| >**NOTE** > @@ -1187,7 +1377,7 @@ Triggered on a frame-by-frame basis when the page is turned by a swipe. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------- | -| event | [OnSwiperGestureSwipeCallback](#onswipergestureswipecallback14) | Yes | Callback triggered on a frame-by-frame basis when the page is turned by a swipe.| +| event | [OnSwiperGestureSwipeCallback](#onswipergestureswipecallback18) | Yes | Callback triggered on a frame-by-frame basis when the page is turned by a swipe.| ### customContentTransition12+ @@ -1197,10 +1387,7 @@ Defines a custom switching animation. You can define custom animation attributes Instructions: -1. This API does not work when **prevMargin** and **nextMargin** are set in such a way that the **Swiper** frontend and backend display the same page during loop playback. -2. During the swiping-initiated page switching animation, the [SwiperContentTransitionProxy](#swipercontenttransitionproxy12) callback is invoked for all pages in the viewport on a frame-by-frame basis. For example, when there are two pages whose subscripts are 0 and 1 in the viewport, two callbacks whose indexes are 0 and 1 are invoked in each frame. -3. When the **swipeByGroup** parameter of the **displayCount** attribute is set to **true**, the callback is invoked for all pages in a group if any page in the group is within the viewport; and all pages in a group are removed from the render tree if none of them are within the viewport. -4. During the swiping-initiated page switching animation, the default animation (page scrolling) is still effective. If you do not want the page to scroll, you can set the **translate** attribute on the main axis to offset the page scrolling. For example, if the value of **displayCount** is **2** and there are two pages whose subscripts are 0 and 1 within the viewport, you can set the **translate** attribute on the main axis to the following on a frame-by-frame basis: **translate** for page 0 = **-position** x **mainAxisLength**; **translate** for page 1 = **-(position - 1)** x **mainAxisLength** +1. This API does not work when **prevMargin** and **nextMargin** are set in such a way that the **Swiper** frontend and backend display the same page during loop playback.
2. During the swiping-initiated page switching animation, the [SwiperContentTransitionProxy][SwiperContentTransitionProxy](#swipercontenttransitionproxy12) callback is invoked for all pages in the viewport on a frame-by-frame basis. For example, when there are two pages whose subscripts are 0 and 1 in the viewport, two callbacks whose indexes are 0 and 1 are invoked in each frame.
3. When the **swipeByGroup** parameter of the **displayCount** attribute is set to **true**, the callback is invoked for all pages in a group if any page in the group is within the viewport; and all pages in a group are removed from the render tree if none of them are within the viewport.
4. During the swiping-initiated page switching animation, the default animation (page scrolling) is still effective. If you do not want the page to scroll, you can set the **translate** attribute on the main axis to offset the page scrolling. For example, if the value of **displayCount** is **2** and there are two pages whose subscripts are 0 and 1 within the viewport, you can set the **translate** attribute on the main axis to the following on a frame-by-frame basis: **translate** for page 0 = **-position** x **mainAxisLength**; **translate** for page 1 = **-(position - 1)** x **mainAxisLength** **Atomic service API**: This API can be used in atomic services since API version 12. @@ -1220,9 +1407,7 @@ Triggered when content in the **Swiper** component scrolls. Instructions: -1. This API does not work when **prevMargin** and **nextMargin** are set in such a way that the **Swiper** frontend and backend display the same page during loop playback. -2. During page scrolling, the [ContentDidScrollCallback](#contentdidscrollcallback12) callback is invoked for all pages in the viewport on a frame-by-frame basis. For example, when there are two pages whose subscripts are 0 and 1 in the viewport, two callbacks whose indexes are 0 and 1 are invoked in each frame. -3. When the **swipeByGroup** parameter of the **displayCount** attribute is set to **true**, the callback is invoked for all pages in a group if any page in the group is within the viewport. +1. This API does not work when **prevMargin** and **nextMargin** are set in such a way that the **Swiper** frontend and backend display the same page during loop playback.
2. During page scrolling, the [ContentDidScrollCallback](#contentdidscrollcallback12) callback is invoked for all pages in the viewport on a frame-by-frame basis. For example, when there are two pages whose subscripts are 0 and 1 in the viewport, two callbacks whose indexes are 0 and 1 are invoked in each frame.
3. When the **swipeByGroup** parameter of the **displayCount** attribute is set to **true**, the callback is invoked for all pages in a group if any page in the group is within the viewport. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -1234,17 +1419,83 @@ Instructions: | ------ | ---- | ---- | ---- | | handler | [ContentDidScrollCallback](#contentdidscrollcallback12) | Yes| Callback triggered when content in the **Swiper** component scrolls.| -## Callbacks +### onSelected18+ + +onSelected(event: Callback\) + +Triggered when the selected element changes. The index of the currently selected element is returned. + +**Widget capability**: This API can be used in ArkTS widgets since API version 18. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------- | +| event | [Callback](./ts-types.md#callback12)\ | Yes | Index of the currently selected element.| + +> **NOTE** +> +> In the **onSelected** callback, do not modify the **index** attribute of the **Swiper** component, or call the **SwiperController.changeIndex()**, **SwiperController.showNext()**, or **SwiperController.showPrevious()** APIs. + +### onUnselected18+ + +onUnselected(event: Callback\) -### OnSwiperAnimationStartCallback14+ +Triggered when the selected element changes. The index of the element that is about to be hidden is returned. + +**Widget capability**: This API can be used in ArkTS widgets since API version 18. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------- | +| event | [Callback](./ts-types.md#callback12)\ | Yes | Index of the element that is about to be hidden.| + +> **NOTE** +> +> In the **onUnselected** callback, do not modify the **index** attribute of the **Swiper** component, nor call the **SwiperController.changeIndex()**, **SwiperController.showNext()**, or **SwiperController.showPrevious()** APIs. + +### onContentWillScroll15+ + +onContentWillScroll(handler: ContentWillScrollCallback) + +Triggered when the **Swiper** component is about to scroll. This event allows you to intercept and control the scrolling behavior of the component. The component determines whether to allow the scroll action based on the return value. If **true** is returned, the scroll action is allowed, and the pages in the **Swiper** component will follow the scrolling. If **false** is returned, the scroll action is disallowed, and the pages will remain stationary. + +1. This event is only triggered by gesture operations, including finger swipes, scrolling the mouse wheel, and moving focus using keyboard arrow keys. + +2. During finger swipes, the event is triggered for each frame. The system uses the return value of the event to determine whether to respond to the swipe for each frame. + +3. For scrolling the mouse wheel and moving focus using keyboard arrow keys, the event is triggered once per page turning. The system uses the return value to decide whether to allow the page turning. + +**Widget capability**: This API can be used in ArkTS widgets since API version 15. + +**Atomic service API**: This API can be used in atomic services since API version 15. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------ | ---- | ---- | ---- | +| handler | [ContentWillScrollCallback](#contentwillscrollcallback15) | Yes| Callback triggered when content in the **Swiper** component scrolls.| + +## OnSwiperAnimationStartCallback18+ type OnSwiperAnimationStartCallback = (index: number, targetIndex: number, extraInfo: SwiperAnimationEvent) => void Defines the callback triggered when the switching animation starts. -**Widget capability**: This API can be used in ArkTS widgets since API version 14. +**Widget capability**: This API can be used in ArkTS widgets since API version 18. -**Atomic service API**: This API can be used in atomic services since API version 14. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -1256,15 +1507,15 @@ Defines the callback triggered when the switching animation starts. | targetIndex10+ | number | Yes | Index of the target element to switch to. | | extraInfo10+ | [SwiperAnimationEvent](#swiperanimationevent10) | Yes | Extra information of the animation, including the offset of the currently displayed element and target element relative to the start position of the **Swiper** along the main axis, and the hands-off velocity.| -### OnSwiperAnimationEndCallback14+ +## OnSwiperAnimationEndCallback18+ type OnSwiperAnimationEndCallback = (index: number, extraInfo: SwiperAnimationEvent) => void Defines the callback triggered when the switching animation ends. -**Widget capability**: This API can be used in ArkTS widgets since API version 14. +**Widget capability**: This API can be used in ArkTS widgets since API version 18. -**Atomic service API**: This API can be used in atomic services since API version 14. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -1275,15 +1526,13 @@ Defines the callback triggered when the switching animation ends. | index | number | Yes | Index of the currently displayed element. If there are multiple columns, **index** indicates the index of the leftmost component. | | extraInfo10+ | [SwiperAnimationEvent](#swiperanimationevent10) | Yes | Extra information of the animation, which is the offset of the currently displayed element relative to the start position of the **Swiper** along the main axis.| -### OnSwiperGestureSwipeCallback14+ +## OnSwiperGestureSwipeCallback18+ type OnSwiperGestureSwipeCallback = (index: number, extraInfo: SwiperAnimationEvent) => void Defines the callback triggered on a frame-by-frame basis when the page is turned by a swipe. -**Widget capability**: This API can be used in ArkTS widgets since API version 14. - -**Atomic service API**: This API can be used in atomic services since API version 14. +**Atomic service API**: This API can be used in atomic services since API version 18. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -1294,6 +1543,63 @@ Defines the callback triggered on a frame-by-frame basis when the page is turned | index | number | Yes | Index of the currently displayed element. If there are multiple columns, **index** indicates the index of the leftmost component. | | extraInfo | [SwiperAnimationEvent](#swiperanimationevent10) | Yes | Extra information of the animation, which is the offset of the currently displayed element relative to the start position of the **Swiper** along the main axis.| +## ContentDidScrollCallback12+ + +type ContentDidScrollCallback = (selectedIndex: number, index: number, position: number, mainAxisLength: number) => void + +Triggered during the swipe action of the **Swiper** component. For details about the parameters, see [SwiperContentTransitionProxy](#swipercontenttransitionproxy12). + +**Atomic service API**: This API can be used in atomic services since API version 12. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name| Type| Mandatory| Description| +| ------ | ---- | ---- | ---- | +| selectedIndex | number | Yes| Index of the currently selected page.| +| index | number | Yes| Index of a page in the viewport.| +| position | number | Yes| Position of the page specified by **index** relative to the start position of the **Swiper** main axis (start position of the page corresponding to **selectedIndex**).| +| mainAxisLength | number | Yes| Length of the page specified by **index** along the main axis.| + +## ContentWillScrollCallback15+ + +type ContentWillScrollCallback = (result: SwiperContentWillScrollResult) => boolean + +Defines the callback triggered when the **Swiper** component is about to scroll. The return value indicates whether the scroll action is allowed. + +**Widget capability**: This API can be used in ArkTS widgets since API version 15. + +**Atomic service API**: This API can be used in atomic services since API version 15. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------ | ---- | ---- | ---- | +| result | [SwiperContentWillScrollResult](#swipercontentwillscrollresult15) | Yes| Information related to the upcoming scroll action, including the index of the current page, the index of the page that will be displayed in the scroll direction, and the displacement of the scroll action.| + +**Return value** + +| Type| Description| +| ------ | ---- | +| boolean | Whether the scroll action is allowed. The value **true** means the scroll action is allowed, and **false** means the opposite.| + +## SwiperContentWillScrollResult15+ + +Provides information related to the upcoming scroll action, including the index of the current page, the index of the page that will be displayed in the scroll direction, and the displacement of the scroll action. + +**Widget capability**: This API can be used in ArkTS widgets since API version 15. + +**Atomic service API**: This API can be used in atomic services since API version 15. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name| Type| Mandatory| Description| +| ------ | ---- | ---- | ---- | +| currentIndex | number | Yes| Index of the current page. During a finger swipe, this value remains constant as long as the finger is on the screen, even if the page has completely moved out of view.| +| comingIndex | number | Yes| Index of the page that will be displayed in the scroll direction.| +| offset | number | Yes| Displacement of the scroll action, which is signed to indicate different swipe directions. A positive value indicates a swipe from index=1 to index=0, while a negative value indicates a swipe from index=0 to index=1.
This value represents the offset for each frame during a finger swipe and the distance for page turning when the mouse wheel or keyboard navigation is used.| + ## SwiperAnimationEvent10+ Describes the animation information of the **Swiper** component. @@ -1329,7 +1635,7 @@ Implements the proxy object returned during the execution of the custom switchin **System capability**: SystemCapability.ArkUI.ArkUI.Full -### Attributes +### Properties | Name| Type| Read Only| Optional| Description| | ---- | ---- | --- | ---- | --- | @@ -1355,28 +1661,11 @@ Notifies the **Swiper** component that the custom animation has finished playing **System capability**: SystemCapability.ArkUI.ArkUI.Full -## ContentDidScrollCallback12+ - -type ContentDidScrollCallback = (selectedIndex: number, index: number, position: number, mainAxisLength: number) => void - -Triggered during the swipe action of the **Swiper** component. For details about the parameters, see [SwiperContentTransitionProxy](#swipercontenttransitionproxy12). - -**Atomic service API**: This API can be used in atomic services since API version 12. - -**System capability**: SystemCapability.ArkUI.ArkUI.Full - -| Name| Type| Mandatory| Description| -| ------ | ---- | ---- | ---- | -| selectedIndex | number | Yes| Index of the currently selected page.| -| index | number | Yes| Index of a page in the viewport.| -| position | number | Yes| Position of the page specified by **index** relative to the start position of the **Swiper** main axis (start position of the page corresponding to **selectedIndex**).| -| mainAxisLength | number | Yes| Length of the page specified by **index** along the main axis.| - ## Example -### Example 1: Configuring Navigation Point Indicator Interaction +### Example 1: Setting the Navigation Indicator Interaction and Page Turning Effect -This example demonstrates how to configure the interaction of the navigation point indicator using the **indicatorInteractive** API. +This example demonstrates how to use the **changeIndex** API with **SwiperAnimationMode** to move to a specific page in the **Swiper** component. ```ts // xxx.ets @@ -1436,7 +1725,7 @@ struct SwiperExample { .indicatorInteractive(true) .duration(1000) .itemSpace(0) - .indicator( // Set the style of the navigation point indicator. + .indicator( // Set the style of the navigation indicator. new DotIndicator() .itemWidth(15) .itemHeight(15) @@ -1444,7 +1733,7 @@ struct SwiperExample { .selectedItemHeight(15) .color(Color.Gray) .selectedColor(Color.Blue)) - .displayArrow({ // Set the arrow style of the navigation point indicator. + .displayArrow({ // Set the arrow style of the navigation indicator. showBackground: true, isSidebarMiddle: true, backgroundSize: 24, @@ -1482,6 +1771,20 @@ struct SwiperExample { this.swiperController.showPrevious() }) }.margin(5) + Row({ space: 5 }) { + Button('FAST 0') + .onClick(() => { + this.swiperController.changeIndex(0, SwiperAnimationMode.FAST_ANIMATION) + }) + Button('FAST 3') + .onClick(() => { + this.swiperController.changeIndex(3, SwiperAnimationMode.FAST_ANIMATION) + }) + Button('FAST ' + 9) + .onClick(() => { + this.swiperController.changeIndex(9, SwiperAnimationMode.FAST_ANIMATION) + }) + }.margin(5) }.width('100%') .margin({ top: 5 }) } @@ -1490,9 +1793,9 @@ struct SwiperExample { ![swiper](figures/swiper.gif) -### Example 2: Implementing a Digit-Style Navigation Point Indicator +### Example 2: Implementing a Digit Indicator -This example showcases how to implement a digit-style navigation point indicator using the **DigitIndicator** API. +This example showcases how to implement a digit indicator using the **DigitIndicator** API. ```ts // xxx.ets @@ -1548,7 +1851,7 @@ struct SwiperExample { .index(1) .autoPlay(true) .interval(4000) - .indicator(Indicator.digit() // Set the digit-style navigation point indicator. + .indicator(Indicator.digit() // Set the digit-style navigation indicator. .top(200) .fontColor(Color.Gray) .selectedFontColor(Color.Gray) @@ -1636,7 +1939,7 @@ struct SwiperExample { .loop(true) .duration(1000) .itemSpace(10) - .indicator( // Set the style of the navigation point indicator. + .indicator( // Set the style of the navigation indicator. new DotIndicator() .itemWidth(15) .itemHeight(15) @@ -1664,7 +1967,7 @@ struct SwiperExample { ### Example 4: Customizing the Page Switching Animation -This example presents how to implement a custom page switching animation for the **Swiper** component through the **customContentTransition** API. +This example presents how to implement a custom page turning animation for the **Swiper** component through the **customContentTransition** API. ```ts // xxx.ets @@ -1717,7 +2020,7 @@ struct SwiperCustomAnimationExample { this.translateList[proxy.index] = 0.0 this.zIndexList[proxy.index] = 0 } else { - // When a page in the same group is swiped right but is still within the viewport, the attribute values of the left and right pages in the same group are changed frame by frame based on the position. The changes implement the custom switching animation in which the two pages move close to the middle of the Swiper and are transparently scaled in or out. + // When a page in the same group is swiped right but is still within the viewport, the attribute values of the left and right pages in the same group are changed frame by frame based on the position. The changes implement the custom switching animation in which the two pages move close to the middle of the and are transparently scaled in or out. if (proxy.index % this.DISPLAY_COUNT === 0) { this.opacityList[proxy.index] = 1 - proxy.position / this.DISPLAY_COUNT this.scaleList[proxy.index] = this.MIN_SCALE + (1 - this.MIN_SCALE) * (1 - proxy.position / this.DISPLAY_COUNT) @@ -1732,7 +2035,7 @@ struct SwiperCustomAnimationExample { } }) .onContentDidScroll((selectedIndex: number, index: number, position: number, mainAxisLength: number) => { - // Called when content in the Swiper component scrolls. In this callback, you can customize the navigation point indicator switching animation. + // Called when content in the component scrolls. In this callback, you can customize the navigation indicator switching animation. console.info("onContentDidScroll selectedIndex: " + selectedIndex + ", index: " + index + ", position: " + position + ", mainAxisLength: " + mainAxisLength) }) }.width('100%') @@ -1741,7 +2044,7 @@ struct SwiperCustomAnimationExample { ``` ![swiper](figures/swiper-custom-animation.gif) -### Example 5: Configuring Overflow for the Dot-Style Navigation Point Indicator +### Example 5: Configuring Overflow for the Dot Indicator This example illustrates the activation of the overflow effect when the number of navigation dots exceeds the limit set through the **maxDisplayCount** property of the **DotIndicator** API. @@ -1801,7 +2104,7 @@ struct Index { .loop(true) .duration(1000) .itemSpace(0) - .indicator( // Set the style of the navigation point indicator. + .indicator( // Set the style of the navigation indicator. new DotIndicator() .itemWidth(8) .itemHeight(8) @@ -1810,7 +2113,7 @@ struct Index { .color(Color.Gray) .selectedColor(Color.Blue) .maxDisplayCount(9)) - .displayArrow({ // Set the arrow style of the navigation point indicator. + .displayArrow({ // Set the arrow style of the navigation indicator. showBackground: true, isSidebarMiddle: true, backgroundSize: 24, @@ -1836,3 +2139,366 @@ struct Index { ``` ![swiper](figures/point_animation.gif) + +### Example 6: Preloading Child Nodes + +This example shows how to use the **preloadItems** API to preload specified child nodes. + +```ts +// xxx.ets +import { BusinessError } from '@kit.BasicServicesKit' + +@Entry +@Component +struct SwiperPreloadItems { + @State currentIndex: number = 1 + private swiperController: SwiperController = new SwiperController() + @State arr: string[] = ["0", "1", "2", "3", "4", "5"] + + build() { + Column() { + Swiper(this.swiperController) { + ForEach(this.arr, (item: string) => { + MyComponent({ txt: item }) + }) + } + .cachedCount(1, true) + .width("70%") + .height("50%") + + + Button('preload items: [2, 3]') + .margin(5) + .onClick(() => { + // Preload child nodes with index=2 and index=3. + try { + this.swiperController.preloadItems([2, 3]) + .then(() => { + console.info('preloadItems [2, 3] success.') + }) + .catch((error: BusinessError) => { + console.error('preloadItems [2, 3] failed, error code: ' + error.code + ', error message: ' + error.message) + }) + } catch (error) { + console.error('preloadItems [2, 3] failed, error code: ' + error.code + ', error message: ' + error.message) + } + + }) + } + .width("100%") + .margin(5) + } +} + +@Component +struct MyComponent { + private txt: string = "" + + aboutToAppear(): void { + console.info('aboutToAppear txt:' + this.txt) + } + + aboutToDisappear(): void { + console.info('aboutToDisappear txt:' + this.txt) + } + + build() { + Text(this.txt) + .textAlign(TextAlign.Center) + .width('100%') + .height('100%') + .backgroundColor(0xAFEEEE) + } +} +``` + +### Example 7: Implementing Synchronized Switching Between the Tabs and Swiper Components + +This example shows how to implement synchronized switching between the **Tabs** and **Swiper** components using the **onSelected** callback. + +```ts +// xxx.ets +class MyDataSource implements IDataSource { + private list: number[] = [] + + constructor(list: number[]) { + this.list = list + } + + totalCount(): number { + return this.list.length + } + + getData(index: number): number { + return this.list[index] + } + + registerDataChangeListener(listener: DataChangeListener): void { + } + + unregisterDataChangeListener() { + } +} + +@Entry +@Component +struct TabsSwiperExample { + @State fontColor: string = '#182431' + @State selectedFontColor: string = '#007DFF' + @State currentIndex: number = 0 + private list: number[] = [] + private tabsController: TabsController = new TabsController() + private swiperController: SwiperController = new SwiperController() + private swiperData: MyDataSource = new MyDataSource([]) + + aboutToAppear(): void { + for (let i = 0; i <= 9; i++) { + this.list.push(i); + } + this.swiperData = new MyDataSource(this.list) + } + + @Builder tabBuilder(index: number, name: string) { + Column() { + Text(name) + .fontColor(this.currentIndex === index ? this.selectedFontColor : this.fontColor) + .fontSize(16) + .fontWeight(this.currentIndex === index ? 500 : 400) + .lineHeight(22) + .margin({ top: 17, bottom: 7 }) + Divider() + .strokeWidth(2) + .color('#007DFF') + .opacity(this.currentIndex === index ? 1 : 0) + }.width('20%') + } + + build() { + Column() { + Tabs({ barPosition: BarPosition.Start, controller: this.tabsController }) { + ForEach(this.list, (index: number) =>{ + TabContent().tabBar(this.tabBuilder(index, 'Tab ' + this.list[index])) + }) + } + .onTabBarClick((index: number) => { + this.currentIndex = index + this.swiperController.changeIndex(index, true) + }) + .barMode(BarMode.Scrollable) + .backgroundColor('#F1F3F5') + .height(56) + .width('100%') + + Swiper(this.swiperController) { + LazyForEach(this.swiperData, (item: string) => { + Text(item.toString()) + .onAppear(()=>{ + console.info('onAppear ' + item.toString()) + }) + .onDisAppear(()=>{ + console.info('onDisAppear ' + item.toString()) + }) + .width('100%') + .height('40%') + .backgroundColor(0xAFEEEE) + .textAlign(TextAlign.Center) + .fontSize(30) + }, (item: string) => item) + } + .loop(false) + .onSelected((index: number) => { + console.info("onSelected:" + index) + this.currentIndex = index; + this.tabsController.changeIndex(index) + }) + } + } +} +``` +![swiper](figures/tabs_swiper.gif) + +### Example 8: Intercepting the Scrolling Behavior + +This example demonstrates how to use the **onContentWillScroll** event to allow only forward scrolling and intercept backward scrolling. + +```ts +// xxx.ets +class MyDataSource implements IDataSource { + private list: number[] = [] + + constructor(list: number[]) { + this.list = list + } + + totalCount(): number { + return this.list.length + } + + getData(index: number): number { + return this.list[index] + } + + registerDataChangeListener(listener: DataChangeListener): void { + } + + unregisterDataChangeListener() { + } +} + +@Entry +@Component +struct SwiperExample { + private swiperController: SwiperController = new SwiperController() + private data: MyDataSource = new MyDataSource([]) + private currentIndex: number = 4 + + aboutToAppear(): void { + let list: number[] = [] + for (let i = 1; i <= 10; i++) { + list.push(i); + } + this.data = new MyDataSource(list) + } + + build() { + Column({ space: 5 }) { + Swiper(this.swiperController) { + LazyForEach(this.data, (item: string) => { + Text(item.toString()) + .width('90%') + .height(160) + .backgroundColor(0xAFEEEE) + .textAlign(TextAlign.Center) + .fontSize(30) + }, (item: string) => item) + } + .index(this.currentIndex) + .loop(false) + .onChange((index: number) => { + this.currentIndex = index + }) + .onContentWillScroll((result: SwiperContentWillScrollResult) => { + if (result.comingIndex > this.currentIndex) { + return false; + } + return true; + }) + + Row({ space: 12 }) { + Button('showNext') + .onClick(() => { + this.swiperController.showNext() + }) + Button('showPrevious') + .onClick(() => { + this.swiperController.showPrevious() + }) + }.margin(5) + }.width('100%') + .margin({ top: 5 }) + } +} +``` + +### Example 9: Using the space and bottom APIs on the Navigation Indicator + +This example demonstrates how to use the **bottom** and **space** APIs to set the spacing between the dots in a dot-style navigation indicator and the bottom margin of the **Swiper** component. + +```ts +import { LengthMetrics } from '@kit.ArkUI' + +// MyDataSource.ets +class MyDataSource implements IDataSource { + private list: number[] = [] + + constructor(list: number[]) { + this.list = list + } + + totalCount(): number { + return this.list.length + } + + getData(index: number): number { + return this.list[index] + } + + registerDataChangeListener(listener: DataChangeListener): void { + } + + unregisterDataChangeListener() { + } +} + +// SwiperExample.ets +@Entry +@Component +struct SwiperExample { + + @State space: LengthMetrics = LengthMetrics.vp(0) + @State spacePool: LengthMetrics[] = [LengthMetrics.vp(0), LengthMetrics.px(3), LengthMetrics.vp(10)] + @State spaceIndex: number = 0 + + @State ignoreSize: boolean = false + @State ignoreSizePool: boolean[] = [false, true] + @State ignoreSizeIndex: number = 0 + + private swiperController1: SwiperController = new SwiperController() + private data1: MyDataSource = new MyDataSource([]) + + aboutToAppear(): void { + let list1: number[] = [] + for (let i = 1; i <= 10; i++) { + list1.push(i); + } + this.data1 = new MyDataSource(list1) + } + + build() { + Scroll() { + Column({ space: 20 }) { + Swiper(this.swiperController1) { + LazyForEach(this.data1, (item: string) => { + Text(item.toString()) + .width('90%') + .height(120) + .backgroundColor(0xAFEEEE) + .textAlign(TextAlign.Center) + .fontSize(30) + }, (item: string) => item) + } + .indicator(new DotIndicator() + .space(this.space) + .bottom(LengthMetrics.vp(0), this.ignoreSize) + .itemWidth(15) + .itemHeight(15) + .selectedItemWidth(15) + .selectedItemHeight(15) + .color(Color.Gray) + .selectedColor(Color.Blue)) + .displayArrow({ + showBackground: true, + isSidebarMiddle: true, + backgroundSize: 24, + backgroundColor: Color.White, + arrowSize: 18, + arrowColor: Color.Blue + }, false) + + Column({ space: 4 }) { + Button('spaceIndex:' + this.spaceIndex).onClick(() => { + this.spaceIndex = (this.spaceIndex + 1) % this.spacePool.length; + this.space = this.spacePool[this.spaceIndex]; + }).margin(10) + + Button('ignoreSizeIndex:' + this.ignoreSizeIndex).onClick(() => { + this.ignoreSizeIndex = (this.ignoreSizeIndex + 1) % this.ignoreSizePool.length; + this.ignoreSize = this.ignoreSizePool[this.ignoreSizeIndex]; + }).margin(10) + }.margin(2) + }.width('100%') + } + } +} +``` +![swiper](figures/indicator_space.gif) diff --git a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-tabcontent.md b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-tabcontent.md index 9ed41c40b9885f5b0f84ed342ed5e9450c421142..3d2edc1fee64e8cbaa68aa4a6250b5ac3c3fc4a4 100644 --- a/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-tabcontent.md +++ b/en/application-dev/reference/apis-arkui/arkui-ts/ts-container-tabcontent.md @@ -20,17 +20,19 @@ This component supports only one child component. TabContent() +Creates the **TabContent** component, which represents the content associated with a specific tab. + **Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported. ### tabBar -tabBar(value: string | Resource | CustomBuilder | { icon?: string | Resource; text?: string | Resource }) +tabBar(options: string | Resource | CustomBuilder | TabBarOptions) Sets the content displayed on the tab bar. @@ -46,7 +48,7 @@ If the content set exceeds the space provided by the tab bar, it will be clipped | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | string \| [Resource](ts-types.md#resource) \|
[CustomBuilder](ts-types.md#custombuilder8)8+\| {
icon?: string \| [Resource](ts-types.md#resource),
text?: string \| [Resource](ts-types.md#resource)
} | Yes| Content displayed on the tab bar.
**CustomBuilder**: builder, to which components can be passed (applicable to API version 8 and later versions).| +| options | string \| [Resource](ts-types.md#resource) \|
[CustomBuilder](ts-types.md#custombuilder8)8+\|
[TabBarOptions](#tabbaroptions18)18+ | Yes| Content displayed on the tab bar.
**CustomBuilder**: builder, to which components can be passed (applicable to API version 8 and later versions).| ### tabBar9+ @@ -62,7 +64,27 @@ Sets the content displayed on the tab bar. The bottom tab style does not include | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| value | [SubTabBarStyle](#subtabbarstyle9) \| [BottomTabBarStyle](#bottomtabbarstyle9)| Yes | Content displayed on the tab bar.
**SubTabBarStyle**: subtab style
**BottomTabBarStyle**: bottom and side tab style| +| value | [SubTabBarStyle](#subtabbarstyle9) \| [BottomTabBarStyle](#bottomtabbarstyle9) | Yes | Content displayed on the tab bar.
**SubTabBarStyle**: subtab style
**BottomTabBarStyle**: bottom and side tab style| + +### tabBar18+ + +tabBar(content: ComponentContent | SubTabBarStyle | BottomTabBarStyle | string | Resource | CustomBuilder | TabBarOptions) + +Content displayed on the tab bar. + +If **BottomTabBarStyle** or **TabBarOptions** is used and an icon is set, a gray block will be displayed if the icon is invalid. If an icon is an SVG image, make sure the SVG image does not have its own width and height attributes. If the SVG image has embedded width and height attributes, the icon size will be determined by these attributes. + +If the content exceeds the space provided by the tab bar, it will be clipped. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| content | [ComponentContent](../js-apis-arkui-ComponentContent.md) \|
[SubTabBarStyle](#subtabbarstyle9) \|[BottomTabBarStyle](#bottomtabbarstyle9) \|
string \| [Resource](ts-types.md#resource) \|
[CustomBuilder](ts-types.md#custombuilder8)\|
[TabBarOptions](#tabbaroptions18) | Yes | Content displayed on the tab bar.
**ComponentContent**: encapsulation of the component content, which can be customized.
**SubTabBarStyle**: subtab style.
**BottomTabBarStyle**: style of the bottom and side tabs. The bottom style does not have the underline effect.
**string**: string type.
**Resource**: resource reference for importing strings from system or application resources.
**CustomBuilder**: builder that can take components as arguments.
**TabBarOptions**: options for configuring images and text content on the tabs.| > **NOTE** > @@ -70,10 +92,27 @@ Sets the content displayed on the tab bar. The bottom tab style does not include > - The **TabContent** component does not support setting of the universal height attribute. Its height is determined by the height of the parent **Tabs** component and the **TabBar** component. > - If the **vertical** attribute is **false**, the width and height descriptions are swapped in the preceding two restrictions. > - **TabContent** does not support page scrolling. If page scrolling is required, consider nesting a list. +> - Whenever possible, use a unified parameter type for the **tabBar** property of all child **TabContent** components within the **Tabs** component. +> - If there are focusable components inside any **TabContent**, focus navigation between **TabContent** and **TabBar** components within the **Tabs** component is only supported using the keyboard arrow keys. + +## TabBarOptions18+ + +Defines the options for configuring images and text content on the tabs. + +**Atomic service API**: This API can be used in atomic services since API version 18. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description| +| -------- | -------- | -------- | -------- | +| icon7+ | string \| [ResourceStr](ts-types.md#resourcestr) | No| Image for the tab.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| text7+ | string \| [ResourceStr](ts-types.md#resourcestr) | No| Text for the tab.
**Atomic service API**: This API can be used in atomic services since API version 11.| ## SubTabBarStyle9+ -Implements the subtab style. When this attribute is enabled, the transition animation is played when the user switches between tabs. +Implements the subtab style. A transition animation is played when the user switches between tabs. ### constructor @@ -133,7 +172,7 @@ Static constructor used to create a **SubTabBarStyle** instance. static of(content: ResourceStr | ComponentContent): SubTabBarStyle -Static constructor used to create a **SubTabBarStyle** instance. +Static constructor used to create a **SubTabBarStyle** instance. You can set custom content with **ComponentContent**. **Atomic service API**: This API can be used in atomic services since API version 12. @@ -151,24 +190,164 @@ Static constructor used to create a **SubTabBarStyle** instance. | ------- | ------------------------------------------------------------ | | [SubTabBarStyle](#subtabbarstyle9) | **SubTabBarStyle** object created.| -### Attributes +### indicator10+ + +indicator(value: IndicatorStyle): SubTabBarStyle + +Sets the indicator style of the selected subtab. It takes effect only in the horizontal layout. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | ------------- | +| value | [IndicatorStyle](#indicatorstyle10)| Yes | Indicator style object for the selected subtab.| + +**Return value** + +| Type | Description | +| ------- | ------------------------------------------------------------ | +| [SubTabBarStyle](#subtabbarstyle9) | **SubTabBarStyle** object.| + +### selectedMode10+ + +selectedMode(value: SelectedMode): SubTabBarStyle + +Sets the display mode of the selected subtab. It takes effect only in the horizontal layout. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | ------------- | +| value | [SelectedMode](#selectedmode10) | Yes | Display mode of the selected subtab.
Default value: **SelectedMode.INDICATOR**| + +**Return value** + +| Type | Description | +| ------- | ------------------------------------------------------------ | +| [SubTabBarStyle](#subtabbarstyle9) | **SubTabBarStyle** object.| + +### board10+ + +board(value: BoardStyle): SubTabBarStyle + +Sets the background style (board style) of the selected subtab. It takes effect only in the horizontal layout. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | ------------- | +| value | [BoardStyle](#boardstyle10) | Yes | Background style object for the selected subtab.| + +**Return value** + +| Type | Description | +| ------- | ------------------------------------------------------------ | +| [SubTabBarStyle](#subtabbarstyle9) | **SubTabBarStyle** object.| + +### labelStyle10+ + +labelStyle(value: LabelStyle): SubTabBarStyle + +Sets the style of the label text and font for the subtab. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | ------------- | +| value | [LabelStyle](#labelstyle10) | Yes | Style object for the label text and font of the subtab.| -The following attributes are supported. +**Return value** + +| Type | Description | +| ------- | ------------------------------------------------------------ | +| [SubTabBarStyle](#subtabbarstyle9) | **SubTabBarStyle** object.| + +### padding10+ + +padding(value: Padding | Dimension): SubTabBarStyle + +Sets the padding of the subtab. It cannot be set in percentage. When the parameter is of the Dimension type, the value applies to all sides. + +**Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory| Description | -| ----------- | ----------------- | ---- |---------------------------------------- | -| indicator10+ | [IndicatorStyle](#indicatorstyle10)| Yes| Indicator style of the selected subtab. It takes effect only in the horizontal layout.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| selectedMode10+ | [SelectedMode](#selectedmode10) | Yes| Display mode of the selected subtab. It takes effect only in the horizontal layout.
Default value: **SelectedMode.INDICATOR**
**Atomic service API**: This API can be used in atomic services since API version 11.| -| board10+ | [BoardStyle](#boardstyle10) | Yes| Board style of the selected subtab. It takes effect only in the horizontal layout.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| labelStyle10+ | [LabelStyle](#labelstyle10) | Yes| Label text and font of the subtab.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| padding10+ | [Padding](ts-types.md#padding) \| [Dimension](ts-types.md#dimension10) | Yes| Padding of the subtab. It cannot be set in percentage. When the parameter is of the Dimension type, the value applies to all sides.
Default value: **{left:8.0vp,right:8.0vp,top:17.0vp,bottom:18.0vp}**
**Atomic service API**: This API can be used in atomic services since API version 11.| -| padding12+ | [LocalizedPadding](ts-types.md#localizedpadding12) | Yes| Padding of the subtab. The mirroring capability is supported (percentage values are not allowed).
Default value: {start:LengthMetircs.vp(8),end:LengthMetircs.vp(8),
top:LengthMetircs.vp(17),bottom:LengthMetircs.vp(18)}
**Atomic service API**: This API can be used in atomic services since API version 12.| -| id11+ | string | Yes| [ID](ts-universal-attributes-component-id.md#attributes) of the subtab.
**Atomic service API**: This API can be used in atomic services since API version 12.| +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | ------------- | +| value | [Padding](ts-types.md#padding) \| [Dimension](ts-types.md#dimension10) | Yes | Padding of the subtab.
Default value: **{left:8.0vp,right:8.0vp,top:17.0vp,bottom:18.0vp}**| + +**Return value** + +| Type | Description | +| ------- | ------------------------------------------------------------ | +| [SubTabBarStyle](#subtabbarstyle9) | **SubTabBarStyle** object.| + +### padding12+ + +padding(padding: LocalizedPadding): SubTabBarStyle + +Sets the padding of the subtab. This API supports mirroring but does not support percentage-based settings. + +**Atomic service API**: This API can be used in atomic services since API version 12. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | ------------- | +| padding | [LocalizedPadding](ts-types.md#localizedpadding12) | Yes | Padding of the subtab.
Default value: {start:LengthMetircs.vp(8),end:LengthMetircs.vp(8),
top:LengthMetircs.vp(17),bottom:LengthMetircs.vp(18)} | + +**Return value** + +| Type | Description | +| ------- | ------------------------------------------------------------ | +| [SubTabBarStyle](#subtabbarstyle9) | **SubTabBarStyle** object.| + +### id11+ + +id(value: string): SubTabBarStyle + +Sets the [ID](ts-universal-attributes-component-id.md#id) of the subtab. + +**Atomic service API**: This API can be used in atomic services since API version 12. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | ------------- | +| value | string | Yes | [ID](ts-universal-attributes-component-id.md#id) of the subtab.| + +**Return value** + +| Type | Description | +| ------- | ------------------------------------------------------------ | +| [SubTabBarStyle](#subtabbarstyle9) | **SubTabBarStyle** object.| ## IndicatorStyle10+ +Represents an indicator style object. + **Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -176,44 +355,50 @@ The following attributes are supported. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------------------------------- | | color | [ResourceColor](ts-types.md#resourcecolor) | No| Color of the indicator and board.
Default value: **#FF007DFF**| -| height | [Length](ts-types.md#length) | No| Height of the indicator. It cannot be set in percentage.
Default value: **2.0**
Unit: vp| -| width | [Length](ts-types.md#length) | No| Width of the indicator. It cannot be set in percentage.
Default value: **0.0**
Unit: vp
**NOTE**
If this parameter is set to **0**, the tab text width will be used instead.| -| borderRadius | [Length](ts-types.md#length) | No| Rounded corner radius of the indicator. It cannot be set in percentage.
Default value: **0.0**
Unit: vp| -| marginTop | [Length](ts-types.md#length) | No| Spacing between the indicator and text. It cannot be set in percentage.
Default value: **8.0**
Unit: vp| +| height | [Length](ts-types.md#length) | No| Height of the indicator. It cannot be set in percentage.
Default value: **2.0**
Unit: vp
Value range: (0, +∞)| +| width | [Length](ts-types.md#length) | No| Width of the indicator. It cannot be set in percentage.
Default value: **0.0**
Unit: vp
Value range: (0, +∞)
**NOTE**
If this parameter is set to **0**, the tab text width will be used instead.| +| borderRadius | [Length](ts-types.md#length) | No| Rounded corner radius of the indicator. It cannot be set in percentage.
Default value: **0.0**
Unit: vp
Value range: [0, +∞)| +| marginTop | [Length](ts-types.md#length) | No| Spacing between the indicator and text. It cannot be set in percentage.
Default value: **8.0**
Unit: vp
Value range: [0, +∞)| ## SelectedMode10+ +Enumerates the display modes of selected subtabs. + **Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Description | +| Name | Description | | ---------- | ------------------------ | | INDICATOR | Indicator mode. | | BOARD | Board mode. | ## BoardStyle10+ +Represents a board style object. + **Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full | Name| Type| Mandatory| Description| | -------- | -------- | -------- | ------------------------------------ | -| borderRadius | [Length](ts-types.md#length) | No| Rounded corner radius of the board. It cannot be set in percentage.
Default value: **8.0**
Unit: vp| +| borderRadius | [Length](ts-types.md#length) | No| Rounded corner radius of the board. It cannot be set in percentage.
Default value: **8.0**
Unit: vp
Value range: [0, +∞)| ## LabelStyle10+ +Represents a style object for the label text and font. + **System capability**: SystemCapability.ArkUI.ArkUI.Full | Name | Type | Mandatory| Description | | -------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | overflow | [TextOverflow](ts-appendix-enums.md#textoverflow) | No | Display mode when the label text is too long. By default, an ellipsis (...) is used to represent text overflow.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| maxLines | number | No | Maximum number of lines in the label text. If this attribute is specified, the text will not exceed the specified number of lines. You can use **textOverflow** to specify how to represent text overflow. Default value: **1**
**Atomic service API**: This API can be used in atomic services since API version 11.| -| minFontSize | number \| [ResourceStr](ts-types.md#resourcestr) | No | Minimum font size of the label text. It cannot be set in percentage. For the setting to take effect, this attribute must be used together with **maxFontSize**, **maxLines**, or layout constraint settings. When the adaptive text size is set, **font.size** does not take effect. Default value: **0.0fp**
**Atomic service API**: This API can be used in atomic services since API version 11.| -| maxFontSize | number \| [ResourceStr](ts-types.md#resourcestr) | No | Maximum font size of the label text. It cannot be set in percentage. For the setting to take effect, this attribute must be used together with **minFontSize**, **maxLines**, or layout constraint settings. When the adaptive text size is set, **font.size** does not take effect. Default value: **0.0fp**
**Atomic service API**: This API can be used in atomic services since API version 11.| +| maxLines | number | No | Maximum number of lines in the label text. If this attribute is specified, the text will not exceed the specified number of lines. You can use **textOverflow** to specify how to represent text overflow. Default value: **1**
Value range: [1, +∞)
**Atomic service API**: This API can be used in atomic services since API version 11.| +| minFontSize | number \| [ResourceStr](ts-types.md#resourcestr) | No | Minimum font size of the label text. It cannot be set in percentage. For the setting to take effect, this attribute must be used together with **maxFontSize**, **maxLines**, or layout constraint settings. When the adaptive text size is set, **font.size** does not take effect. The default value is **0.0fp**, indicating that the adaptive text size has no effect.
Value range: (0, +∞)
**Atomic service API**: This API can be used in atomic services since API version 11.| +| maxFontSize | number \| [ResourceStr](ts-types.md#resourcestr) | No | Maximum font size of the label text. It cannot be set in percentage. For the setting to take effect, this attribute must be used together with **minFontSize**, **maxLines**, or layout constraint settings. When the adaptive text size is set, **font.size** does not take effect. The default value is **0.0fp**, indicating that the adaptive text size has no effect.
Value range: [minFontSize, +∞)
**Atomic service API**: This API can be used in atomic services since API version 11.| | heightAdaptivePolicy | [TextHeightAdaptivePolicy](ts-appendix-enums.md#textheightadaptivepolicy10) | No | How the adaptive height is determined for the label text. By default, the **maxLines** settings are prioritized.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| font | [Font](ts-types.md#font) | No | Font of the label text.
When the tab is a subtab, the default font is in 16.0 fp size, 'HarmonyOS Sans' family, and normal font style and weight.
When the tab is a bottom tab, the default font is in 10.0 fp size, 'HarmonyOS Sans' family, normal font style, and medium weight.
The default font size of the bottom tab page is 12.0 fp since API version 12.
**Atomic service API**: This API can be used in atomic services since API version 11.| +| font | [Font](ts-types.md#font) | No | Font of the label text.
When the tab is a subtab, the default font is in 16.0 fp size, 'HarmonyOS Sans' family, normal font style, medium weight when selected, and normal weight when not selected.
When the tab is a bottom tab, the default font is in 10.0 fp size, 'HarmonyOS Sans' family, normal font style, and medium weight.
The default font size of the bottom tab page is 12.0 fp since API version 12.
**Atomic service API**: This API can be used in atomic services since API version 11.| | unselectedColor12+ | [ResourceColor](ts-types.md#resourcecolor) | No| Font color of the label text when it is not selected.
Default value: **#99182431**
**Atomic service API**: This API can be used in atomic services since API version 12.| | selectedColor12+ | [ResourceColor](ts-types.md#resourcecolor) | No| Font color of the label text when it is selected.
Default value: **#FF007DFF**
**Atomic service API**: This API can be used in atomic services since API version 12.| @@ -225,7 +410,7 @@ Implements the bottom and side tab style. constructor(icon: ResourceStr | TabBarSymbol, text: ResourceStr) -A constructor used to create a **BottomTabBarStyle** instance. +Constructor used to create a **BottomTabBarStyle** instance. **Atomic service API**: This API can be used in atomic services since API version 11. @@ -259,49 +444,193 @@ Static constructor used to create a **BottomTabBarStyle** instance. | Type | Description | | ------- | ------------------------------------------------------------ | -| [BottomTabBarStyle](#bottomtabbarstyle9)| **BottomTabBarStyle** object created.| +| [BottomTabBarStyle](#bottomtabbarstyle9) | **BottomTabBarStyle** object created.| + +### padding10+ + +padding(value: Padding | Dimension | LocalizedPadding): BottomTabBarStyle + +Sets the padding of the bottom tab. It cannot be set in percentage. When the parameter is of the Dimension type, the value applies to all sides. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | ------------- | +| value | [Padding](ts-types.md#padding) \| [Dimension](ts-types.md#dimension10) \| [LocalizedPadding12+](ts-types.md#localizedpadding12) | Yes | Padding of the bottom tab.
Default value: **{left:4.0vp,right:4.0vp,top:0.0vp,bottom:0.0vp}**
If of the LocalizedPadding type, this attribute supports the mirroring capability.
Default value: {start:LengthMetircs.vp(4),end:LengthMetircs.vp(4),
top:LengthMetircs.vp(0),bottom:LengthMetircs.vp(0)} | + +**Return value** + +| Type | Description | +| ------- | ------------------------------------------------------------ | +| [BottomTabBarStyle](#bottomtabbarstyle9) | **BottomTabBarStyle** object.| + +### verticalAlign10+ + +verticalAlign(value: VerticalAlign): BottomTabBarStyle + +Sets the vertical alignment mode of the images and text on the bottom tab. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | ------------- | +| value | [VerticalAlign](ts-appendix-enums.md#verticalalign) | Yes | Vertical alignment mode of the images and text on the bottom tab.
Default value: **VerticalAlign.Center**| + +**Return value** + +| Type | Description | +| ------- | ------------------------------------------------------------ | +| [BottomTabBarStyle](#bottomtabbarstyle9) | **BottomTabBarStyle** object.| + +### layoutMode10+ + +layoutMode(value: LayoutMode): BottomTabBarStyle + +Sets the layout mode of the images and texts on the bottom tab. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | ------------- | +| value | [LayoutMode](#layoutmode10) | Yes | Layout mode of the images and text on the bottom tab.
Default value: **LayoutMode.VERTICAL**| + +**Return value** + +| Type | Description | +| ------- | ------------------------------------------------------------ | +| [BottomTabBarStyle](#bottomtabbarstyle9) | **BottomTabBarStyle** object.| + +### symmetricExtensible10+ + +symmetricExtensible(value: boolean): BottomTabBarStyle + +Sets whether the images and text on the bottom tab can be symmetrically extended by the minimum value of the available space on the left and right bottom tabs. This parameter is valid only between bottom tabs in fixed horizontal mode. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | ------------- | +| value | boolean | Yes | Whether the images and text on the bottom tab can be symmetrically extended by the minimum value of the available space on the left and right bottom tabs.
Default value: **false**, indicating that the images and text on the bottom tab cannot be symmetrically extended by the minimum value of the available space on the left and right bottom tabs| + +**Return value** + +| Type | Description | +| ------- | ------------------------------------------------------------ | +| [BottomTabBarStyle](#bottomtabbarstyle9) | **BottomTabBarStyle** object.| + +### labelStyle10+ + +labelStyle(value: LabelStyle): BottomTabBarStyle + +Sets the style of the label text and font for the bottom tab. + +**Atomic service API**: This API can be used in atomic services since API version 11. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | ------------- | +| value | [LabelStyle](#labelstyle10) | Yes | Style of the label text and font for the bottom tab.| + +**Return value** + +| Type | Description | +| ------- | ------------------------------------------------------------ | +| [BottomTabBarStyle](#bottomtabbarstyle9) | **BottomTabBarStyle** object.| + +### id11+ + +id(value: string): BottomTabBarStyle + +Sets the ID of the bottom tab. + +**Atomic service API**: This API can be used in atomic services since API version 12. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | ------------- | +| value | string | Yes | [ID](ts-universal-attributes-component-id.md#id) of the bottom tab.| + +**Return value** + +| Type | Description | +| ------- | ------------------------------------------------------------ | +| [BottomTabBarStyle](#bottomtabbarstyle9) | **BottomTabBarStyle** object.| -### Attributes +### iconStyle12+ -The following attributes are supported. +iconStyle(style: TabBarIconStyle): BottomTabBarStyle + +Sets the style of the label icon on the bottom tab. + +**Atomic service API**: This API can be used in atomic services since API version 12. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory| Description | -| ------------ | ---------------------------- | ---- |----------------------------------- | -| padding10+ | [Padding](ts-types.md#padding) \| [Dimension](ts-types.md#dimension10) \| [LocalizedPadding12+](ts-types.md#localizedpadding12) | Yes| Padding of the bottom tab. It cannot be set in percentage. When the parameter is of the Dimension type, the value applies to all sides.
Default value: **{left:4.0vp,right:4.0vp,top:0.0vp,bottom:0.0vp}**
If of the LocalizedPadding type, this attribute supports the mirroring capability.
Default value: {start:LengthMetircs.vp(4),end:LengthMetircs.vp(4),
top:LengthMetircs.vp(0),bottom:LengthMetircs.vp(0)}
**Atomic service API**: This API can be used in atomic services since API version 11.| -| verticalAlign10+ | [VerticalAlign](ts-appendix-enums.md#verticalalign) | Yes| Vertical alignment mode of the images and text on the bottom tab.
Default value: **VerticalAlign.Center**
**Atomic service API**: This API can be used in atomic services since API version 11.| -| layoutMode10+ | [LayoutMode](#layoutmode10) | Yes| Layout of the images and text on the bottom tab. For details, see **LayoutMode**.
Default value: **LayoutMode.VERTICAL**
**Atomic service API**: This API can be used in atomic services since API version 11.| -| symmetricExtensible10+ | boolean | Yes| Whether the images and text on the bottom tab can be symmetrically extended by the minimum value of the available space on the left and right bottom tabs. This parameter is valid only between bottom tabs in fixed horizontal mode.
Default value: **false**
**Atomic service API**: This API can be used in atomic services since API version 11.| -| labelStyle10+ | [LabelStyle](#labelstyle10) | Yes| Label text and font of the bottom tab.
**Atomic service API**: This API can be used in atomic services since API version 11.| -| id11+ | string | Yes| [ID](ts-universal-attributes-component-id.md#attributes) of the bottom tab.
**Atomic service API**: This API can be used in atomic services since API version 12.| -| iconStyle12+ | [TabBarIconStyle](#tabbariconstyle12) | Yes| Style of the label icon on the bottom tab.
**Atomic service API**: This API can be used in atomic services since API version 12.| +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | ------------- | +| style | [TabBarIconStyle](#tabbariconstyle12) | Yes | Style of the label icon on the bottom tab.| + +**Return value** + +| Type | Description | +| ------- | ------------------------------------------------------------ | +| [BottomTabBarStyle](#bottomtabbarstyle9) | **BottomTabBarStyle** object.| ## TabBarSymbol12+ +Represents a tab bar symbol style object. + **Atomic service API**: This API can be used in atomic services since API version 12. **System capability**: SystemCapability.ArkUI.ArkUI.Full | Name| Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| normal | [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) | Yes| Symbol icon in the normal style.
Default value:
**fontColor**: **#66182431**, **renderingStrategy**: **SymbolRenderingStrategy.MULTIPLE_OPACITY**, **fontSize**: **24vp**| -| selected | [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) | No| Symbol icon in the selected style.
Default value:
**fontColor**: **#ff007dff**, **renderingStrategy**: **SymbolRenderingStrategy.MULTIPLE_OPACITY**, **fontSize**: **24vp**| +| normal | [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) | Yes| Symbol icon in the normal style.
Default value:
**fontColor**: **#66182431**
**renderingStrategy**: **SymbolRenderingStrategy.MULTIPLE_OPACITY**
**fontSize**: **24vp**| +| selected | [SymbolGlyphModifier](ts-universal-attributes-attribute-modifier.md) | No| Symbol icon in the selected style.
Default value:
**fontColor**: **#ff007dff**
**renderingStrategy**: **SymbolRenderingStrategy.MULTIPLE_OPACITY**
**fontSize**: **24vp**| ## LayoutMode10+ +Enumerates the layout modes of the images and texts on the bottom tabs. + **Atomic service API**: This API can be used in atomic services since API version 11. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Description | -| ---------- | ---------------------------------------- | -| AUTO | When the tab width is greater than 104 vp, the tab content is arranged from left to right. Otherwise,the tab content is arranged from top to bottom. This parameter is valid only when the tab bar is in vertical mode or fixed horizontal mode.| -| VERTICAL | The tab content is arranged from top to bottom.| -| HORIZONTAL | The tab content is arranged from left to right.| +| Name | Value| Description | +| ---------- | - | ---------------------------------------- | +| AUTO | 0 | When the tab width is greater than 104 vp, the tab content is arranged from left to right. Otherwise,the tab content is arranged from top to bottom. This parameter is valid only when the tab bar is in vertical mode or fixed horizontal mode.| +| VERTICAL | 1 | The tab content is arranged from top to bottom.| +| HORIZONTAL | 2 | The tab content is arranged from left to right.| ## TabBarIconStyle12+ +Represents a label icon style object. + **Atomic service API**: This API can be used in atomic services since API version 12. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -313,7 +642,7 @@ The following attributes are supported. ## Events -In addition to the [universal events](ts-universal-events-click.md), the following events are supported. +In addition to the [universal events](ts-component-general-events.md), the following events are supported. ### onWillShow12+ @@ -349,7 +678,9 @@ Called when the tab content is about to be hidden. The scenarios include the tab ## Example -### Example 1 +### Example 1: Implementing Custom Tab Switching Synchronization + +This example demonstrates how to use **onAnimationStart** and **onChange** to implement synchronized switching between the tab bar and tab content. ```ts // xxx.ets @@ -359,17 +690,18 @@ struct TabContentExample { @State fontColor: string = '#182431' @State selectedFontColor: string = '#007DFF' @State currentIndex: number = 0 + @State selectedIndex: number = 0 private controller: TabsController = new TabsController() @Builder tabBuilder(index: number) { Column() { - Image(this.currentIndex === index ? '/common/public_icon_on.svg' : '/common/public_icon_off.svg') + Image(this.selectedIndex === index ? '/common/public_icon_on.svg' : '/common/public_icon_off.svg') .width(24) .height(24) .margin({ bottom: 4 }) .objectFit(ImageFit.Contain) Text(`Tab${index + 1}`) - .fontColor(this.currentIndex === index ? this.selectedFontColor : this.fontColor) + .fontColor(this.selectedIndex === index ? this.selectedFontColor : this.fontColor) .fontSize(10) .fontWeight(500) .lineHeight(14) @@ -442,7 +774,16 @@ struct TabContentExample { .vertical(false) .barHeight(56) .onChange((index: number) => { + // currentIndex controls the displayed tab in TabContent. this.currentIndex = index + this.selectedIndex = index + }) + .onAnimationStart((index: number, targetIndex: number, event: TabsAnimationEvent) => { + if (index === targetIndex) { + return + } + // selectedIndex controls the color switching for the image and text in the custom tab bar. + this.selectedIndex = targetIndex }) .width(360) .height(190) @@ -455,7 +796,9 @@ struct TabContentExample { ![tabContent](figures/tabContent1.gif) -### Example 2 +### Example 2: Implementing a Custom Side Tabs + +This example demonstrates how to create side tabs using **vertical** and **barPosition**. ```ts // xxx.ets @@ -465,17 +808,18 @@ struct TabContentExample { @State fontColor: string = '#182431' @State selectedFontColor: string = '#007DFF' @State currentIndex: number = 0 + @State selectedIndex: number = 0 private controller: TabsController = new TabsController() @Builder tabBuilder(index: number) { Column() { - Image(this.currentIndex === index ? '/common/public_icon_on.svg' : '/common/public_icon_off.svg') + Image(this.selectedIndex === index ? '/common/public_icon_on.svg' : '/common/public_icon_off.svg') .width(24) .height(24) .margin({ bottom: 4 }) .objectFit(ImageFit.Contain) Text('Tab') - .fontColor(this.currentIndex === index ? this.selectedFontColor : this.fontColor) + .fontColor(this.selectedIndex === index ? this.selectedFontColor : this.fontColor) .fontSize(10) .fontWeight(500) .lineHeight(14) @@ -498,7 +842,16 @@ struct TabContentExample { .barWidth(96) .barHeight(414) .onChange((index: number) => { + // currentIndex controls the displayed tab in TabContent. this.currentIndex = index + this.selectedIndex = index + }) + .onAnimationStart((index: number, targetIndex: number, event: TabsAnimationEvent) => { + if (index === targetIndex) { + return + } + // selectedIndex controls the color switching for the image and text in the custom tab bar. + this.selectedIndex = targetIndex }) .width(96) .height(414) @@ -511,7 +864,9 @@ struct TabContentExample { ![tabContent](figures/tabContent2.gif) -### Example 3 +### Example 3: Implementing Different Styles of Tabs + +This example demonstrates the implementation of subtabs, bottom tabs, and side tabs using **SubTabBarStyle** and **BottomTabBarStyle**. ```ts // xxx.ets @@ -520,7 +875,7 @@ struct TabContentExample { struct TabBarStyleExample { build() { Column({ space: 5 }) { - Text("Subtab Style") + Text("Subtab style") Column() { Tabs({ barPosition: BarPosition.Start }) { TabContent() { @@ -572,7 +927,7 @@ struct TabBarStyleExample { .width('100%') .backgroundColor(0xF1F3F5) }.width('100%').height(200) - Text("Bottom Tab Style") + Text("Bottom tab style") Column() { Tabs({ barPosition: BarPosition.End }) { TabContent() { @@ -624,7 +979,7 @@ struct TabBarStyleExample { .width('100%') .backgroundColor(0xF1F3F5) }.width('100%').height(200) - Text("Side Tab Style") + Text("Side tab style") Column() { Tabs({ barPosition: BarPosition.Start }) { TabContent() { @@ -681,7 +1036,9 @@ struct TabBarStyleExample { ![tabbarStyle](figures/TabBarStyle.jpeg) -### Example 4 +### Example 4: Setting the Indicator for Subtabs + +This example demonstrates how to set the indicator for subtabs using the **indicator** property in **SubTabBarStyle**. ```ts // xxx.ets @@ -706,7 +1063,7 @@ struct TabsAttr { Column() { Button("Change Indicator Color").width('100%').margin({ bottom: '12vp' }) .onClick((event?: ClickEvent) => { - // Animation configuration for the width and height attributes of the Button component + // Animation configuration for the width and height attributes of the